Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
107 changes: 107 additions & 0 deletions docs/ai-proxy-rule-overrides.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-->

# AI Proxy Rule generation overrides

#8127 adds an explicit opt-in generation block to Rule.handle. Plugin defaults
and Selector settings remain the only owners of provider, protocol, target,
credentials, proxy-key authentication, fallback configuration and native body
patch policy. Valid legacy Rule root fields remain inert; a previously unused
root-level model/provider is not silently activated.

The audit found AI Proxy Plugin/Selector metadata but no Rule-scope (type=2)
AI Proxy metadata in the four H2, MySQL, PostgreSQL and Oracle initialization
scripts. Existing repository configuration/examples and the prior request path
resolve provider settings from Plugin/Selector data. This delivery keeps that
metadata intact and exposes the version-one RULE contract through the existing
configuration-contract API. Configure the new JSON block with the existing Admin
Rule API/import; no new dashboard form control or database migration is implied.

Example:

```json
{
"generationOverrides": {
"model": "operator-model",
"temperature": null,
"maxTokens": 1024,
"stream": false
}
}
```

| Field | Allowed value | Explicit null |
| --- | --- | --- |
| model | Nonblank string, at most 256 characters, no surrounding whitespace/control characters | Clear configured model; use the client model |
| temperature | Finite JSON number in [0,2] | Clear configured override; retain client/provider default |
| maxTokens | Positive JSON integer within Java int range | Clear configured override; retain client/provider default |
| stream | JSON boolean | Clear configured default; use explicit client value or non-streaming default |

Absent fields inherit Plugin/Selector configuration. An absent, null or empty
generationOverrides block means no Rule override. Plugin < Selector < Rule is
the configured precedence. The existing engine applies configured model,
temperature and maxTokens over client values; **explicit client stream remains
authoritative**. Null clearing removes the configured value rather than filling
it from the lower scope again. Removing the block restores lower-scope
inheritance. Provider dialect/model/token-field mappings and existing native
body-patch policy still run in their original order; Rule configuration does
not override those protected mechanisms.

Only these four nested keys are accepted. Credentials, provider, baseUrl,
protocol, fallbackConfig, proxyEnabled, requestBodyOverrides and any other
nested field are rejected, including null-valued attempts. Root legacy fields
remain ignored. New publication validation requires blank/null or a valid JSON
object; malformed legacy handles, arrays and duplicate keys should be replaced
with a valid object before editing/importing them. This is an explicit migration
constraint for previously unused arbitrary Rule payloads, not reinterpretation
of their fields.

The shared lightweight parser/contract validates Admin create/update/import and
gateway publication with bounded, value-free errors. It limits source length to
65,536 characters and JSON depth to 32. No network, client initialization or
credential resolution occurs in validation. The gateway parses once on a Rule
update and publishes an immutable value. Invalid updates retain the previous
published value. Rule deletion (even with only its ID), Selector removal and
Plugin removal evict owned values. Rule-ID reuse is also checked against the
actual selected Selector identity.

The existing request owner reads one cached value and merges the four fields
into its request-owned AiCommonConfig. It does not parse Rule JSON per request,
modify cached DTOs, or share a mutable effective configuration with another
request. The normal engine/provider capability and request validation runs
before transport execution. Missing required effective target/model settings
still fail there; Rule overrides do not grant model authorization or add virtual
model policy.

Fallback selection, accepted request-body fallback configuration, credential
supplementation and no-replay-after-output remain with their existing owners.
They are not new Rule fields. An existing fallback resolver may inherit
generation values from the already-resolved primary configuration where it did
so before; an explicitly configured fallback model still takes precedence.
No alternate fallback mechanism or credential inheritance rule is introduced.

AiProxyRuleContractTest covers presence, clearing, strict types, bounds,
protected fields, duplicate keys and immutable publication. RuleServiceTest
exercises real Admin create/update/import validation before writes/events.
AiProxyPluginTest exercises the real plugin and engine through outgoing requests,
including provider token-field adaptation, credential preservation, stream
precedence, clearing and invalid-update/removal behavior.
AiProxyConfigServiceTest checks all three scopes, request ownership and
concurrent independent resolution. Existing Selector-only, proxy-key and
fallback tests remain compatibility controls.
111 changes: 111 additions & 0 deletions docs/rewrite-configuration-contract.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-->

# Rewrite rule configuration, contract version 1

`RewriteRuleContract` publishes the existing rule-handle behavior through the
optional shared registry. Rewrite has no plugin- or selector-specific fields in
this contract. The shared catalog and Admin metadata endpoint describe these
four fields; `RewriteHandle` and the original JSON storage are unchanged.

| Field | Declared type | Effective execution default | Meaning |
| --- | --- | --- | --- |
| `regex` | string | absent: no rewrite | Java regex, or existing brace-based placeholder expression |
| `replace` | string | absent: no rewrite | Replacement template |
| `percentage` | integer | omitted/null: 100 | Compared with an integer drawn from 0 through 99 |
| `rewriteMetaData` | boolean | omitted/null: false | Resolve metadata using the rewritten URI and effective context-path prefix |

Version 1 preserves Gson coercion and unknown-field behavior. Field types describe
the DTO; this version does not enable generic strict structural validation. In
particular, it does not clamp or reject existing percentage values: 0 and negative
values never rewrite, 100 and values above 100 always pass the threshold. The
compatibility fixtures test these deterministic cases without statistical
sampling. A stricter range policy would require a separate version and migration.

## Examples / 配置示例

An existing two-field handle still rewrites all matching requests by default:

```json
{"regex":"/api/(.*)","replace":"/v2/$1"}
```

旧版双字段配置仍然有效;未填写 `percentage` 时默认按 100 处理,
未填写 `rewriteMetaData` 时默认不切换元数据。契约中的默认值仅用于描述执行行为,
不会自动写回已保存的 JSON。

The existing placeholder branch applies when both strings contain `{`:

```json
{"regex":"/shenyu/{id}","replace":"/target/{id}","percentage":100,"rewriteMetaData":true}
```

当两个字符串都包含 `{` 时,仍使用现有占位符分支,不引入新的占位符语法。
只填写一个表达式时允许保存,但不会执行改写。正则或替换模板确实不可用时,
仍由现有 `RewriteHandleUtils` 判断;运行时的原始 URI 回退保护保持不变。

## Update boundaries / 更新边界

| Input or operation | Admin acceptance | Gateway handle update |
| --- | --- | --- |
| missing Java value | accepted | leave previous cached handle unchanged |
| blank string | accepted | remove previous cached handle |
| `{}` | accepted | replace with a no-op handle |
| literal JSON `null` | rejected | evict previous cached handle |
| malformed JSON / incompatible object shape | rejected | existing parse exception; previous cached handle remains |
| unusable applicable regex/replacement | rejected | evict previous cached handle |
| incomplete expression | accepted | cache it; execution skips rewriting |
| rule removal | operation-specific | idempotent removal; handle is not required |

“未传更新”“清空字符串”和“空对象”不是同一操作;无效表达式更新仍会淘汰旧改写,
不能套用 Divide 的“无效更新保留旧句柄”策略。契约返回校验事实,具体清除/淘汰行为
仍由原数据处理器负责。

Admin create/update/import uses the generic registry, with no new rewrite-name
branch. Its existing direct validator remains a compatibility entry point.
Gateway publication uses the same applicability provider while preserving parse,
clear and eviction boundaries. No contract parsing runs on the request path.
Unknown configuration fields remain ignored, and existing matching, URI/context
handling, downstream continuation and metadata/RPC-type rules are unchanged.

## Evidence

The versioned `rewrite-rule-v1.tsv` corpus is packaged with the common contract.
Common validation, Admin direct validation and real create/update/import services,
and the gateway data handler plus real `RewritePlugin` execution consume it.
It covers existing two-field JSON, null defaults, legacy coercion/unknown fields,
0/100/out-of-range thresholds, blank/no-op/null/invalid updates, capture groups,
placeholder mode, repeated removal and metadata enabled/disabled/missing/context
prefix cases. Existing applicability, stale-handle and runtime fallback tests are
also retained.

Metadata tests compare the four contract fields with DTO bean properties and the
maintained MySQL, PostgreSQL, Oracle and H2 form seed representations. No SQL seed
or field ID changes are needed: regex/replace use string controls, percentage a
numeric control, and rewriteMetaData a select control. Existing seeds explicitly
default rewriteMetaData to false; percentage's effective default comes from the
runtime, rather than being newly materialized in existing seed rows.

```text
./mvnw -B -ntp -pl shenyu-admin,shenyu-plugin/shenyu-plugin-rewrite -am verify -Dtest=RewriteRuleContractTest,RewriteRuleHandleValidatorTest,RuleServiceTest,RewriteHandleUtilsTest,RewritePluginDataHandlerTest,RewritePluginTest,RewriteContractCompatibilityTest -Dsurefire.failIfNoSpecifiedTests=false -Djacoco.skip=true -DskipRemoteResources=true -Dmaven.javadoc.skip=true
```

This is source-build behavior for the current development branch, not a claim
that the contract has shipped in a released distribution. Full Docker E2E remains
separate from these local deterministic publication/runtime fixtures.
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,9 @@
import org.apache.shenyu.admin.utils.Assert;
import org.apache.shenyu.admin.utils.SessionUtil;
import org.apache.shenyu.admin.validation.validator.AgentGatewayRuleHandleValidator;
import org.apache.shenyu.admin.validation.validator.RewriteRuleHandleValidator;
import org.apache.shenyu.common.config.contract.ConfigurationContractRegistry;
import org.apache.shenyu.common.config.contract.ConfigurationScope;
import org.apache.shenyu.common.config.contract.ConfigurationValidation;
import org.apache.shenyu.common.constant.AdminConstants;
import org.apache.shenyu.common.dto.ConditionData;
import org.apache.shenyu.common.dto.RuleData;
Expand Down Expand Up @@ -509,8 +511,11 @@ private void validateRuleHandle(final String selectorId, final String handle) {
}
if (PluginEnum.AGENT_GATEWAY.getName().equals(plugin.getName())) {
AgentGatewayRuleHandleValidator.validate(handle);
} else if (PluginEnum.REWRITE.getName().equals(plugin.getName())) {
RewriteRuleHandleValidator.validate(handle);
}
ConfigurationValidation validation = ConfigurationContractRegistry.shared().validate(plugin.getName(), ConfigurationScope.RULE, "1", handle);
if (validation.status() == ConfigurationValidation.Status.INVALID) {
throw new ShenyuAdminException("Invalid rule configuration: " + plugin.getName() + " " + validation.violations().get(0).path()
+ " " + validation.violations().get(0).code());
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,14 +17,11 @@

package org.apache.shenyu.admin.validation.validator;

import com.google.gson.JsonSyntaxException;
import org.apache.commons.lang3.StringUtils;
import org.apache.shenyu.admin.exception.ShenyuAdminException;
import org.apache.shenyu.common.dto.convert.rule.RewriteHandle;
import org.apache.shenyu.common.utils.GsonUtils;
import org.apache.shenyu.common.utils.RewriteHandleUtils;

import java.util.Objects;
import org.apache.shenyu.common.config.contract.ConfigurationContractRegistry;
import org.apache.shenyu.common.config.contract.ConfigurationScope;
import org.apache.shenyu.common.config.contract.ConfigurationValidation;
import org.apache.shenyu.common.config.contract.ConfigurationViolation;

/**
* Validates rewrite rule handles before Admin stores them.
Expand All @@ -41,22 +38,14 @@ private RewriteRuleHandleValidator() {
* @param handle the rule handle supplied to Admin
*/
public static void validate(final String handle) {
if (StringUtils.isBlank(handle)) {
// an empty handle means the rule does not rewrite, which the plugin tolerates as well
return;
}
final RewriteHandle rewriteHandle;
try {
rewriteHandle = GsonUtils.getInstance().fromJson(handle, RewriteHandle.class);
} catch (JsonSyntaxException ex) {
ConfigurationValidation result = ConfigurationContractRegistry.shared().validate("rewrite", ConfigurationScope.RULE, "1", handle);
if (result.status() == ConfigurationValidation.Status.INVALID) {
ConfigurationViolation problem = result.violations().get(0);
if (problem.code() == ConfigurationViolation.Code.SEMANTIC_INVALID) {
throw new ShenyuAdminException("rewrite rule handle can not be applied, "
+ ("regex".equals(problem.path()) ? "invalid regular expression" : "invalid replacement template"));
}
throw new ShenyuAdminException("rewrite rule handle must be a valid JSON object");
}
if (Objects.isNull(rewriteHandle)) {
throw new ShenyuAdminException("rewrite rule handle must be a valid JSON object");
}
final String problem = RewriteHandleUtils.applicabilityProblem(rewriteHandle.getRegex(), rewriteHandle.getReplace());
if (Objects.nonNull(problem)) {
throw new ShenyuAdminException("rewrite rule handle can not be applied, " + problem);
}
}
}
Loading
Loading