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
130 changes: 130 additions & 0 deletions docs/divide-configuration-contract.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
<!--
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.
-->

# Divide rule configuration, contract version 1

`DivideRuleContract` registers the existing HTTP routing rule handle with the
shared registry. It inventories every current root, Canary, predicate, sticky-key
and session-affinity DTO field. It does not invent plugin or selector scopes,
change JSON storage, construct SDK clients, or change routing/response ownership.
The machine-readable catalog is also available through Admin's existing
`/plugin-template/config-contracts` metadata API.

| Root field | Omitted-field default | Units / interpretation |
| --- | --- | --- |
| `loadBalance` | `random` | Open SPI name, including external implementations |
| `retryStrategy` | `current` | Existing retry strategy selection |
| `retryBackOffSpec` | `default` | Existing default/fixed/exponential interpretation and fallback |
| `retry` | 3 | Retry count |
| `timeout` | 3000 | Milliseconds |
| `requestTimeout` | absent | Overall HTTPRoute request budget in milliseconds. An absent value uses legacy timeout handling. Zero disables the deadline. |
| `headerMaxSize` | 0 | UTF-8 bytes plus framing allowance; non-positive disables this check |
| `requestMaxSize` | 0 | Body bytes; non-positive disables enforcement |
| `poolGroup` | absent | Optional [upstream connection-pool group](upstream-pool-groups.md). An absent or empty value uses the shared default pool. Named groups are resolved by the gateway. |
| `canary` | absent | Legacy routing; a present configuration uses existing partition validation |
| `sticky` | absent | Existing optional HTTP affinity |

Defaults are descriptive and never inserted into stored JSON. Gson's existing
root-field coercion, explicit-null and unknown-field behavior remains in force.
For primitive fields, explicit null retains the initializer; reference fields can
remain null. This version adds no universal positive-range rule for legacy root
fields and no closed built-in allowlist for extension names. A descriptor does
not prove an extension is installed.

## Nested fields

| Field group | Current meaning / default |
| --- | --- |
| `canary.enabled` | false selects Stable; present value must be a JSON boolean |
| `canary.conditions` | Optional array; empty allows participation; explicit null is invalid |
| `canary.conditions[].paramType`, `.operator` | Existing ParameterData and PredicateJudge SPI names |
| `canary.conditions[].paramName`, `.paramValue` | Existing source/operator-specific requirements, including regex/time applicability |
| `canary.matchMode` | 0 AND; 1 OR; no fractional/string/null coercion |
| `canary.percentage` | 0, range 0..100; same existing strict integral validation |
| `canary.stickyKey.paramType`, `.paramName` | Source required when enabled at 1..99%; availability is a separate binding fact |
| `canary.canaryLabels`, `.stableLabels` | Both nonempty string maps; a shared key must have different values |
| `canary.fallbackPolicy` | STABLE, or REJECT |
| `sticky.enabled` | false; existing affinity activation requirements still apply |
| `sticky.cookieName` | Shenyu-Route base name, with the existing rule suffix; a custom name remains verbatim/shared |
| `sticky.maxAgeSeconds` | 3600 seconds |
| `sticky.secrets` | First HMAC key signs, all keys verify; configured values are sensitive |
| `sticky.onUnavailable` | REBIND; existing interpretation is unchanged |
| `sticky.key.type`, `.name` | Optional HEADER/COOKIE deterministic key; HEADER is the DTO default |

For a present Canary object, the existing parser validates labels and conditional
requirements even when Canary is disabled. The contract reuses
`CanaryConfigValidator`; it does not create a second parser. Canary plus retries
to another target remains rejected until partition-aware failover exists.

Sticky parsing follows the shared validator. It rejects string booleans and unknown key types. Affinity activation also depends on runtime configuration:
the existing runtime still needs usable secrets, cookie settings and lifetime.
Array element descriptions and conditional constraints are owned by semantic
validation, rather than silently enabling generic strict structural validation.

## Validation, binding and updates

Admin create/update/import/registration paths dispatch shared semantic validation
through the registry before writes. Admin's Canary dictionary checks remain
separate. The gateway validates a complete candidate before replacing the typed
handle and checks its actual ParameterData/PredicateJudge providers. A dictionary
entry can therefore be accepted by Admin and still be unavailable on a gateway.
Both failures use bounded field paths and codes; a missing binding is explicitly
`RUNTIME_BINDING_UNAVAILABLE`, with no raw provider exception/configuration value.

| Boundary | Preserved version-one behavior |
| --- | --- |
| missing Java update value | no-op; previous typed handle remains |
| blank Admin value | accepted legacy input |
| blank gateway update | existing parse failure; previous typed handle remains |
| malformed/invalid candidate | rejected before replacing the previous handle |
| `{}` | parsed DTO defaults replace the previous handle |
| `removeRule` with null handle | current conditional removal leaves the typed handle present |
| `removeRule` with non-null handle | removes it; repeated removal is safe |
| disable | existing matching/lifecycle policy; this schema adds no universal cache clearing |

The conditional removal limitation is intentionally characterized, not silently
strengthened by adopting a schema. Rewrite's blank-clear/invalid-expression
eviction policy is not applied to Divide. None of these per-handle checks
establishes atomic publication across selector, upstream or plugin caches.

## Form projection and verification

Metadata tests inventory every writable DTO property and verify the maintained
MySQL/PostgreSQL/Oracle/H2 field/control seeds. Their existing seven root controls
remain intact; the optional full catalog additionally describes nested JSON
fields. No IDs, seed rows or upgrade scripts change. In particular, existing
forms preset header/body limits to 10240/102400, while an omitted raw JSON field
has the runtime default 0. Both facts are explicitly described rather than
normalizing stored values or changing form behavior.

The versioned `divide-rule-v1.tsv` corpus runs through common validation, real
Admin create/update/import services and the real gateway data handler. It checks
shared error paths/codes, missing/null/empty input, custom names, coercion,
Canary types/ranges/partitions/retry restrictions, sticky variants, binding
differences, valid-to-invalid retention and conditional removal. Existing routing,
Canary/failover, affinity, deterministic-key, retry, timeout and size-limit tests
are included in the focused verification; their behavior is not redesigned.

```text
./mvnw -B -ntp -pl shenyu-admin,shenyu-plugin/shenyu-plugin-proxy/shenyu-plugin-divide -am verify -Dtest=RuleServiceTest,DivideRuleContractTest,CanaryConfigValidatorTest,*Divide*,*Canary*,*Sticky*,ConfigurationContractRegistryTest,RewriteRuleContractTest,PluginControllerTest -Dsurefire.failIfNoSpecifiedTests=false -Djacoco.skip=true -DskipRemoteResources=true -Dmaven.javadoc.skip=true
```

No full distribution/Docker E2E or released-version availability is implied by
the local deterministic checks. Pure validation runs on configuration updates;
no registry parsing or metadata projection is added to request forwarding.
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,10 @@
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.config.contract.ConfigurationValidationException;
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 @@ -273,11 +276,16 @@ private void validateCanaryAndStickyConfig(final String selectorId, final String
if (Objects.isNull(plugin) || !PluginEnum.DIVIDE.getName().equals(plugin.getName())) {
return;
}
validateRegisteredHandle(plugin.getName(), handle);
try {
DivideRuleHandle divide = CanaryConfigValidator.parseHandle(handle);
if (Objects.nonNull(divide.getCanary())) {
CanaryConfigValidator.validateExtensions(divide.getCanary(),
name -> validateCanaryDictionary("paramType", name), name -> validateCanaryDictionary("operator", name));
if (Objects.nonNull(divide) && Objects.nonNull(divide.getCanary())) {
try {
CanaryConfigValidator.validateExtensions(divide.getCanary(),
name -> validateCanaryDictionary("paramType", name), name -> validateCanaryDictionary("operator", name));
} catch (IllegalArgumentException error) {
throw ConfigurationValidationException.bindingUnavailable("divide", ConfigurationScope.RULE, "canary");
}
}
StickySessionConfigValidator.validate(divide.getSticky());
} catch (IllegalArgumentException ex) {
Expand Down Expand Up @@ -509,8 +517,14 @@ 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);
}
validateRegisteredHandle(plugin.getName(), handle);
}

private void validateRegisteredHandle(final String plugin, final String handle) {
ConfigurationValidation validation = ConfigurationContractRegistry.shared().validate(plugin, ConfigurationScope.RULE, "1", handle);
if (validation.status() == ConfigurationValidation.Status.INVALID) {
throw new ShenyuAdminException(new ConfigurationValidationException(validation).getMessage());
}
}

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