From 1d49d583402fd1f72ad22d7f72d7efdc8af59f86 Mon Sep 17 00:00:00 2001 From: yangjj-iso <3202137046@qq.com> Date: Sat, 31 Oct 2026 01:41:07 +0800 Subject: [PATCH] test(plugin): add consumable LEGACY contract kit (apache/shenyu#8202) --- .../legacy-plugin-consumer/pom.xml | 81 ++++ .../shenyu/ExternalGatewaySmokeTest.java | 57 +++ .../shenyu/ExternalPluginContractTest.java | 121 ++++++ .../verify-legacy-contract-consumer.ps1 | 133 +++++++ .../CONTRACT-KIT.md | 154 ++++++++ .../shenyu-plugin-store-test-support/pom.xml | 14 +- .../store/test/support/GatewayFixtures.java | 2 +- .../test/support/LegacyPluginContractKit.java | 345 ++++++++++++++++++ .../support/LegacyPluginContractKitTest.java | 341 +++++++++++++++++ 9 files changed, 1245 insertions(+), 3 deletions(-) create mode 100644 contract-examples/legacy-plugin-consumer/pom.xml create mode 100644 contract-examples/legacy-plugin-consumer/src/test/java/org/example/shenyu/ExternalGatewaySmokeTest.java create mode 100644 contract-examples/legacy-plugin-consumer/src/test/java/org/example/shenyu/ExternalPluginContractTest.java create mode 100644 script/plugin-store/verify-legacy-contract-consumer.ps1 create mode 100644 shenyu-plugin/shenyu-plugin-store-test-support/CONTRACT-KIT.md create mode 100644 shenyu-plugin/shenyu-plugin-store-test-support/src/main/java/org/apache/shenyu/plugin/store/test/support/LegacyPluginContractKit.java create mode 100644 shenyu-plugin/shenyu-plugin-store-test-support/src/test/java/org/apache/shenyu/plugin/store/test/support/LegacyPluginContractKitTest.java diff --git a/contract-examples/legacy-plugin-consumer/pom.xml b/contract-examples/legacy-plugin-consumer/pom.xml new file mode 100644 index 0000000..48a90cc --- /dev/null +++ b/contract-examples/legacy-plugin-consumer/pom.xml @@ -0,0 +1,81 @@ + + + + 4.0.0 + org.example.shenyu + legacy-plugin-contract-consumer + 1.0-SNAPSHOT + + + 17 + 17 + UTF-8 + 2.7.1-SNAPSHOT + + + + org.apache.shenyu + shenyu-plugin-store-test-support + ${contract.kit.version} + test + + + org.junit.jupiter + junit-jupiter + 5.10.2 + test + + + + + contract-staging + ${contract.stagingRepository} + truealways + true + + + cached-releases + ${contract.dependencyCache} + false + true + + + + + cached-release-plugins + ${contract.dependencyCache} + false + true + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.7.0 + + + org.apache.maven.plugins + maven-surefire-plugin + 3.0.0-M4 + + + + diff --git a/contract-examples/legacy-plugin-consumer/src/test/java/org/example/shenyu/ExternalGatewaySmokeTest.java b/contract-examples/legacy-plugin-consumer/src/test/java/org/example/shenyu/ExternalGatewaySmokeTest.java new file mode 100644 index 0000000..c59893c --- /dev/null +++ b/contract-examples/legacy-plugin-consumer/src/test/java/org/example/shenyu/ExternalGatewaySmokeTest.java @@ -0,0 +1,57 @@ +/* + * 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. + */ + +package org.example.shenyu; + +import org.apache.shenyu.plugin.api.ShenyuPlugin; +import org.apache.shenyu.plugin.api.ShenyuPluginChain; +import org.apache.shenyu.plugin.store.test.support.ShenyuGatewayTestServer; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.EnabledIfSystemProperty; +import org.springframework.web.server.ServerWebExchange; +import reactor.core.publisher.Mono; + +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** Opt-in loopback HTTP smoke using the existing real gateway fixture. */ +@EnabledIfSystemProperty(named = "contract.smoke", matches = "true") +class ExternalGatewaySmokeTest { + + @Test + void realHttpRequestTraversesTheGateway() { + ShenyuPlugin plugin = new ShenyuPlugin() { + @Override + public Mono execute(final ServerWebExchange exchange, final ShenyuPluginChain chain) { + exchange.getResponse().getHeaders().add("X-External-Plugin", "yes"); + return chain.execute(exchange); + } + + @Override + public int getOrder() { + return 0; + } + }; + try (ShenyuGatewayTestServer gateway = ShenyuGatewayTestServer.start(List.of(plugin))) { + var response = gateway.get("/external-consumer-smoke"); + assertEquals(200, response.getStatusCode()); + assertEquals("shenyu-store-test-support", response.getBody()); + assertEquals("yes", response.getHeaders().getFirst("X-External-Plugin")); + } + } +} diff --git a/contract-examples/legacy-plugin-consumer/src/test/java/org/example/shenyu/ExternalPluginContractTest.java b/contract-examples/legacy-plugin-consumer/src/test/java/org/example/shenyu/ExternalPluginContractTest.java new file mode 100644 index 0000000..adb3bc9 --- /dev/null +++ b/contract-examples/legacy-plugin-consumer/src/test/java/org/example/shenyu/ExternalPluginContractTest.java @@ -0,0 +1,121 @@ +/* + * 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. + */ + +package org.example.shenyu; + +import org.apache.shenyu.plugin.api.ShenyuPlugin; +import org.apache.shenyu.plugin.api.ShenyuPluginChain; +import org.apache.shenyu.plugin.store.test.support.LegacyPluginContractKit; +import org.apache.shenyu.plugin.store.test.support.TerminalResponsePlugin; +import org.junit.jupiter.api.Test; +import org.springframework.web.server.ServerWebExchange; +import reactor.core.publisher.Mono; +import reactor.core.publisher.Sinks; +import reactor.test.StepVerifier; + +import java.time.Duration; +import java.util.List; +import java.util.Set; +import java.util.concurrent.atomic.AtomicInteger; + +import static org.apache.shenyu.plugin.store.test.support.LegacyPluginContractKit.Profile.SHORT_CIRCUIT; +import static org.apache.shenyu.plugin.store.test.support.LegacyPluginContractKit.Profile.TRANSFORM; +import static org.apache.shenyu.plugin.store.test.support.LegacyPluginContractKit.Profile.WRAPPER; +import static org.junit.jupiter.api.Assertions.assertEquals; + +class ExternalPluginContractTest { + + @Test + void transformationUsesPackagedKitAndActualRootHandler() { + AtomicInteger effects = new AtomicInteger(); + ShenyuPlugin transformer = new Transformer(effects); + try (var session = LegacyPluginContractKit.open("external-transformer", TRANSFORM, List.of(transformer), exchange -> { + assertEquals("yes", exchange.getRequest().getHeaders().getFirst("X-Transformed")); + return TerminalResponsePlugin.ok("transformed").execute(exchange, current -> Mono.empty()); + })) { + LegacyPluginContractKit.assertDeferred("external-transformer", session::publisher, effects::longValue); + session.verifyComplete(1); + assertEquals(1, effects.get()); + assertEquals("transformed", session.exchange().getResponse().getBodyAsString().block(Duration.ofSeconds(1))); + } + var evidence = LegacyPluginContractKit.evidence(System.getProperty("contract.coreRevision"), Set.of(TRANSFORM), + Set.of("GRAPH unsupported", "SDK leases not declared")); + assertEquals("2.7.1-SNAPSHOT", evidence.kitVersion()); + assertEquals("2.7.2-SNAPSHOT", evidence.coreVersion()); + System.out.println("Packaged contract evidence: " + evidence); + } + + @Test + void wrapperEnclosesControlledAsynchronousSuccessor() { + Sinks.Empty completion = Sinks.empty(); + AtomicInteger terminalSignals = new AtomicInteger(); + ShenyuPlugin wrapper = new Wrapper(terminalSignals); + try (var session = LegacyPluginContractKit.open("external-wrapper", WRAPPER, List.of(wrapper), exchange -> completion.asMono())) { + StepVerifier.create(session.publisher()).then(() -> completion.tryEmitEmpty()).expectComplete().verify(Duration.ofSeconds(2)); + assertEquals(1, session.downstreamSubscriptions()); + assertEquals(1, terminalSignals.get()); + } + } + + @Test + void shortCircuitProfileDoesNotDemandDownstreamExecution() { + try (var session = LegacyPluginContractKit.open("external-short-circuit", SHORT_CIRCUIT, + List.of(TerminalResponsePlugin.ok("blocked-locally")))) { + session.verifyComplete(0); + assertEquals("blocked-locally", session.exchange().getResponse().getBodyAsString().block(Duration.ofSeconds(1))); + } + } + + private static final class Transformer implements ShenyuPlugin { + + private final AtomicInteger effects; + + private Transformer(final AtomicInteger effects) { + this.effects = effects; + } + + @Override + public Mono execute(final ServerWebExchange exchange, final ShenyuPluginChain chain) { + effects.incrementAndGet(); + return chain.execute(exchange.mutate().request(builder -> builder.header("X-Transformed", "yes")).build()); + } + + @Override + public int getOrder() { + return 0; + } + } + + private static final class Wrapper implements ShenyuPlugin { + + private final AtomicInteger terminalSignals; + + private Wrapper(final AtomicInteger terminalSignals) { + this.terminalSignals = terminalSignals; + } + + @Override + public Mono execute(final ServerWebExchange exchange, final ShenyuPluginChain chain) { + return chain.execute(exchange).doFinally(signal -> terminalSignals.incrementAndGet()); + } + + @Override + public int getOrder() { + return 0; + } + } +} diff --git a/script/plugin-store/verify-legacy-contract-consumer.ps1 b/script/plugin-store/verify-legacy-contract-consumer.ps1 new file mode 100644 index 0000000..359b4b6 --- /dev/null +++ b/script/plugin-store/verify-legacy-contract-consumer.ps1 @@ -0,0 +1,133 @@ +# 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. +# +[CmdletBinding()] +param( + [Parameter(Mandatory = $true)][string]$CoreCheckout, + [string]$DependencyCache +) + +$ErrorActionPreference = 'Stop' +$coreCheckoutRoot = [System.IO.Path]::GetFullPath($CoreCheckout) +$storeRoot = [System.IO.Path]::GetFullPath((Join-Path $PSScriptRoot '../..')) +$wrapper = Join-Path $coreCheckoutRoot 'mvnw.cmd' +if (-not (Test-Path -LiteralPath $wrapper -PathType Leaf)) { + throw 'CoreCheckout must contain the repository Maven wrapper' +} +$corePom = [xml](Get-Content -LiteralPath (Join-Path $coreCheckoutRoot 'pom.xml')) +$coreVersion = [string]$corePom.project.version +if ($coreVersion -ne '2.7.2-SNAPSHOT') { + throw 'This example pins core 2.7.2-SNAPSHOT; use its recorded source revision' +} +if ([string]::IsNullOrWhiteSpace($DependencyCache)) { + $settingsFile = Join-Path $env:USERPROFILE '.m2/settings.xml' + if (Test-Path -LiteralPath $settingsFile) { + $settings = [xml](Get-Content -LiteralPath $settingsFile) + $DependencyCache = [string]$settings.settings.localRepository + } + if ([string]::IsNullOrWhiteSpace($DependencyCache)) { + $DependencyCache = Join-Path $env:USERPROFILE '.m2/repository' + } +} +$dependencyRoot = [System.IO.Path]::GetFullPath($DependencyCache) +$proofRoot = Join-Path $storeRoot 'target/legacy-contract-proof' +$stagingRoot = Join-Path $proofRoot 'staging-repository' +$consumerRepository = Join-Path $proofRoot ('consumer-repository-' + [guid]::NewGuid().ToString('N')) +New-Item -ItemType Directory -Force -Path $proofRoot, $stagingRoot, $consumerRepository | Out-Null +$originalBaseDir = $env:MAVEN_BASEDIR +$env:MAVEN_BASEDIR = $coreCheckoutRoot + +function Invoke-ContractMaven { + param([string]$Directory, [string[]]$Arguments, [string]$Log) + Push-Location -LiteralPath $Directory + try { + & $wrapper @Arguments *> $Log + $result = $LASTEXITCODE + } finally { + Pop-Location + } + if ($result -ne 0) { + Get-Content -LiteralPath $Log -Tail 35 + throw "Maven verification failed; see $Log" + } +} + +$hashes = [System.Collections.Generic.List[object]]::new() +function Copy-StagedModule { + param([string]$Checkout, [string]$Module, [string]$Version) + $moduleRoot = if ($Module) { Join-Path $Checkout $Module } else { $Checkout } + $pomFile = Join-Path $moduleRoot 'pom.xml' + $model = [xml](Get-Content -LiteralPath $pomFile) + $artifact = [string]$model.project.artifactId + $destination = Join-Path $stagingRoot "org/apache/shenyu/$artifact/$Version" + New-Item -ItemType Directory -Force -Path $destination | Out-Null + Copy-Item -LiteralPath $pomFile -Destination (Join-Path $destination "$artifact-$Version.pom") -Force + $metadata = Join-Path $dependencyRoot "org/apache/shenyu/$artifact/$Version/maven-metadata-local.xml" + if (-not (Test-Path -LiteralPath $metadata)) { + throw "Missing producer install metadata for $artifact" + } + Copy-Item -LiteralPath $metadata -Destination (Join-Path $destination 'maven-metadata.xml') -Force + if ([string]$model.project.packaging -ne 'pom') { + $jarName = "$artifact-$Version.jar" + $jar = Join-Path $moduleRoot "target/$jarName" + $stagedJar = Join-Path $destination $jarName + Copy-Item -LiteralPath $jar -Destination $stagedJar -Force + $hashes.Add([pscustomobject]@{ + artifact = $artifact; version = $Version; sha256 = (Get-FileHash -LiteralPath $stagedJar -Algorithm SHA256).Hash + }) + } +} + +try { + Invoke-ContractMaven $coreCheckoutRoot @('-B', '-ntp', '-pl', 'shenyu-web', '-am', 'install', + '-DskipTests', '-Djacoco.skip=true', '-DskipRemoteResources=true', '-Dmaven.javadoc.skip=true') (Join-Path $proofRoot 'core-producer.log') + Invoke-ContractMaven $storeRoot @('-B', '-ntp', '-f', 'pom.xml', '-pl', 'shenyu-plugin/shenyu-plugin-store-test-support', '-am', 'install', + '-Dtest=LegacyPluginContractKitTest,ShenyuGatewayTestServerTest', '-Dsurefire.failIfNoSpecifiedTests=false', + '-Djacoco.skip=true', '-DskipRemoteResources=true', '-Dmaven.javadoc.skip=true') (Join-Path $proofRoot 'kit-producer.log') + foreach ($module in @('', 'shenyu-register-center', 'shenyu-register-center/shenyu-register-protocol', 'shenyu-common', 'shenyu-spi', + 'shenyu-sync-data-center', 'shenyu-sync-data-center/shenyu-sync-data-api', 'shenyu-plugin', 'shenyu-plugin/shenyu-plugin-api', + 'shenyu-loadbalancer', 'shenyu-plugin/shenyu-plugin-base', 'shenyu-web')) { + Copy-StagedModule $coreCheckoutRoot $module $coreVersion + } + foreach ($module in @('', 'shenyu-plugin', 'shenyu-plugin/shenyu-plugin-store-test-support')) { + Copy-StagedModule $storeRoot $module '2.7.1-SNAPSHOT' + } + $stagingUri = ([uri]($stagingRoot + [System.IO.Path]::DirectorySeparatorChar)).AbsoluteUri + $dependencyUri = ([uri]($dependencyRoot + [System.IO.Path]::DirectorySeparatorChar)).AbsoluteUri + $coreRevision = (& git -C $coreCheckoutRoot rev-parse HEAD).Trim() + $consumerRoot = Join-Path $storeRoot 'contract-examples/legacy-plugin-consumer' + # A fresh local repository prevents preinstalled ShenYu snapshots from satisfying the consumer. + # The fallback file repository permits releases only, never the staged ShenYu snapshots. + Invoke-ContractMaven $consumerRoot @('-B', '-ntp', '-f', 'pom.xml', 'clean', 'test', + "-Dmaven.repo.local=$consumerRepository", "-Dcontract.stagingRepository=$stagingUri", "-Dcontract.dependencyCache=$dependencyUri", + "-Dcontract.coreRevision=$coreRevision", '-Dcontract.smoke=true') (Join-Path $proofRoot 'external-consumer.log') + foreach ($entry in $hashes) { + $resolved = Join-Path $consumerRepository "org/apache/shenyu/$($entry.artifact)/$($entry.version)/$($entry.artifact)-$($entry.version).jar" + if ((Get-FileHash -LiteralPath $resolved -Algorithm SHA256).Hash -ne $entry.sha256) { + throw "Consumer did not use the staged bytes for $($entry.artifact)" + } + } + [pscustomobject]@{ + coreRevision = $coreRevision; coreVersion = $coreVersion + kitRevision = (& git -C $storeRoot rev-parse HEAD).Trim() + kitWorkingTree = (& git -C $storeRoot status --porcelain) + stagingRepository = $stagingRoot; isolatedConsumerRepository = $consumerRepository + artifacts = $hashes + } | ConvertTo-Json -Depth 6 | Set-Content -LiteralPath (Join-Path $proofRoot 'proof.json') -Encoding utf8 + Get-Content -LiteralPath (Join-Path $proofRoot 'external-consumer.log') -Tail 18 + Write-Output ("Verified staged artifact hashes; proof: " + (Join-Path $proofRoot 'proof.json')) +} finally { + $env:MAVEN_BASEDIR = $originalBaseDir +} diff --git a/shenyu-plugin/shenyu-plugin-store-test-support/CONTRACT-KIT.md b/shenyu-plugin/shenyu-plugin-store-test-support/CONTRACT-KIT.md new file mode 100644 index 0000000..228b49a --- /dev/null +++ b/shenyu-plugin/shenyu-plugin-store-test-support/CONTRACT-KIT.md @@ -0,0 +1,154 @@ + + +# Reactive LEGACY plugin contract kit + +Use `org.apache.shenyu:shenyu-plugin-store-test-support:2.7.1-SNAPSHOT` in +**test scope**. This extends the existing store gateway fixtures; it does not +create another runtime executor or a core release/BOM compatibility program. +The initial verified core is `2.7.2-SNAPSHOT` built from +`b46bf15c3a243e926994cb32c3f0a23eadc41adf`. These are local development +artifacts and evidence, not a claim of publication to Maven Central or compatibility +with every core version. Release/build matrix ownership remains with #7294/#7306. + +```xml + + org.apache.shenyu + shenyu-plugin-store-test-support + 2.7.1-SNAPSHOT + test + +``` + +Spring test and Reactor test are dependencies of this test-support artifact. +No production plugin or starter gains a runtime dependency on them. Keep this +artifact off production classpaths: its existing E2E cache fixtures are test-only. + +## Pick a role and an observable contract + +`LegacyPluginContractKit.open(name, profile, orderedPlugins)` creates a scoped +request backed by the **actual** `ShenyuWebHandler`. It does not copy the legacy +cursor, sort plugins, add `cache()`, or change continuation behavior. A caller +can supply a terminal response owner instead of the default no-op terminal. + +| Profile/check | What it proves | Limits | +| --- | --- | --- | +| TRANSFORM | Declared downstream subscription count and real request/response transformation | Does not prove an external protocol/SDK is correct | +| SHORT_CIRCUIT | Zero downstream subscriptions can be correct; the plugin owns its response | No blanket continuation-exactly-once requirement | +| WRAPPER | Explicitly expected zero/one/multiple successor subscriptions and nested scope behavior | Duration would be inclusive; plugin order does not identify a role | +| BASE_MATCHING | Actual base-plugin lookup/matching, including missing config and rule miss | Conditions/config remain the core implementation's responsibility | +| FORK | Real optional isolated cursor behavior | A fork restarts the snapshot at the chain head and shares the exchange/body/response; it is not parallel-safe isolation | +| Owner release probe | The **declared actual owner** receives one completion/error/cancellation signal | Plugin publisher cancellation alone does not prove a network RPC was cancelled | +| Configuration removal | A valid fixture is published and an explicitly supported removal removes its observed state | No universal null/clear/disable or SDK lease policy is invented | + +Use `verifyComplete(expectedDownstreamSubscriptions)` to state the role's +expectation. Counts are cumulative within one session, which lets repeated root +subscriptions show that the real handler creates fresh chains. Use a fresh +session for independent HTTP response ownership; a committed response is not +silently replayed. `verifyError` observes the escaped chain failure, before an +outer HTTP error renderer. `verifyCancellation` cancels the actual root. + +`assertDeferred` checks **request effects at root assembly/subscription**. It +does not forbid all side effects in a direct `plugin.execute()` call: the real +handler defers invocation. Existing `before/after` hooks still bracket returned +publisher construction, including overrides; they are not asynchronous +completion callbacks. The controlled asynchronous fixture verifies this timing. + +A `ReleaseProbe` is optional and must be attached to the resource owner's +terminal signal. It waits for a controlled signal with an explicit bound and +checks exactly one release; no detached cleanup subscription is introduced. +Use protocol/SDK-specific fixtures to establish that this owner is the real call +or stream. Declare unsupported lease/provider contracts rather than inventing +them for a test. + +```java +try (var session = LegacyPluginContractKit.open( + "my-plugin", LegacyPluginContractKit.Profile.TRANSFORM, List.of(plugin))) { + LegacyPluginContractKit.assertDeferred("my-plugin", session::publisher, effects::longValue); + session.verifyComplete(1); +} +``` + +The fixture supplies a default ShenYu HTTP context and ShenyuConfig bean, with +scheduling disabled for controlled unit contracts. `registerFixtureBean` lets +a consumer explicitly supply additional test beans before subscription. +Sessions restore the previous Spring helper context when closed. Core caches and +that helper are process-global: run these fixtures serially, nest scopes in LIFO +order, and remove your own cached fixtures. `GatewayFixtures.cleanBaseDataCache` +is a whole-cache helper for a dedicated test JVM, not per-request isolation. + +## Examples, evidence and rejected fixtures + +`contract-examples/legacy-plugin-consumer` is outside the source reactor and has +no parent POM. It demonstrates a transformation plugin, a downstream wrapper with +a controlled asynchronous successor, and a short-circuit response owner. Its +opt-in smoke uses the existing `ShenyuGatewayTestServer` over real loopback HTTP, +including a real plugin and response writer; no Docker or credentials are needed. + +The kit's own tests exercise completion/error/cancellation, skip, missing config, +rule match/miss, repeated roots, response decorators, nested wrappers, optional +fork dispatch and supported removal. Deliberately bad fixtures are detected for +eager root effects, unexpected duplicate downstream effects for TRANSFORM, +lost owner cancellation/cleanup, a dropped response decorator and stale state +after declared removal. A WRAPPER declaring the same two dispatches passes. +Tests use controlled publishers/signals and bounded waits, not sleeps or random +traffic percentages. + +`LegacyPluginContractKit.evidence(...)` records observed packaged kit/core +versions, explicitly declared source provenance, selected profiles, and +unsupported/skipped capabilities. Development classes report unknown version +instead of fabricating artifact provenance. Descriptors are optional; neither +schema adoption nor GRAPH execution is required. Real provider behavior, +uploaded-plugin/starter/distribution E2E and release compatibility remain in the +owning plugin/integration workflows. Existing original-suite runners under +`script/plugin-store/` and core's uploaded-plugin smoke remain available. + +## Reproduce independent consumption on Windows + +Pass a clean pinned core checkout containing its Maven wrapper: + +```powershell +./script/plugin-store/verify-legacy-contract-consumer.ps1 -CoreCheckout C:/path/to/pinned-core +``` + +The script uses that wrapper for every Maven invocation. It builds the required +pinned core modules and the kit, copies their JARs/POMs into a fixed local staging +repository, then builds the parentless consumer with a **fresh isolated local +repository**. A read-only cache repository supplies releases only; it cannot +satisfy the staged ShenYu snapshots. After the four consumer tests, every resolved +ShenYu JAR's SHA-256 must equal the staged source bytes. + +Results are written under `target/legacy-contract-proof/`: producer logs, +external consumer log, staging repository and `proof.json` containing core +revision, candidate kit state, isolated repository and artifact hashes. The script +does not delete repository data. A default consumer run skips the optional real +HTTP smoke; the verification script explicitly enables it. + +Manual standalone builds on other platforms can use the same parentless POM and +a prepared staging repository: + +```text +/path/to/core/mvnw -f contract-examples/legacy-plugin-consumer/pom.xml clean test -Dcontract.stagingRepository=file:///path/to/staging/ -Dcontract.dependencyCache=file:///path/to/release-cache/ -Dmaven.repo.local=/path/to/fresh-consumer-cache -Dcontract.smoke=true +``` + +The kit's producer tests/checks can be run independently through the wrapper: + +```text +/path/to/core/mvnw -f pom.xml -pl shenyu-plugin/shenyu-plugin-store-test-support -am verify -Dtest=LegacyPluginContractKitTest,ShenyuGatewayTestServerTest -Dsurefire.failIfNoSpecifiedTests=false -Djacoco.skip=true -DskipRemoteResources=true -Dmaven.javadoc.skip=true +``` diff --git a/shenyu-plugin/shenyu-plugin-store-test-support/pom.xml b/shenyu-plugin/shenyu-plugin-store-test-support/pom.xml index e8a42ce..06f12a4 100644 --- a/shenyu-plugin/shenyu-plugin-store-test-support/pom.xml +++ b/shenyu-plugin/shenyu-plugin-store-test-support/pom.xml @@ -29,15 +29,25 @@ ${project.artifactId} + + org.springframework + spring-test + compile + + + io.projectreactor + reactor-test + compile + org.apache.shenyu shenyu-web - 2.7.2-SNAPSHOT + ${shenyu.version} org.apache.shenyu shenyu-plugin-base - 2.7.2-SNAPSHOT + ${shenyu.version} org.springframework.boot diff --git a/shenyu-plugin/shenyu-plugin-store-test-support/src/main/java/org/apache/shenyu/plugin/store/test/support/GatewayFixtures.java b/shenyu-plugin/shenyu-plugin-store-test-support/src/main/java/org/apache/shenyu/plugin/store/test/support/GatewayFixtures.java index a8441c2..d28c8cd 100644 --- a/shenyu-plugin/shenyu-plugin-store-test-support/src/main/java/org/apache/shenyu/plugin/store/test/support/GatewayFixtures.java +++ b/shenyu-plugin/shenyu-plugin-store-test-support/src/main/java/org/apache/shenyu/plugin/store/test/support/GatewayFixtures.java @@ -113,7 +113,7 @@ public static RuleData cacheRule(final String pluginName, final String selectorI .selectorId(selectorId) .name(pluginName + "-rule") .enabled(true) - .loged(true) + .logged(true) .sort(1) .matchMode(MatchModeEnum.AND.getCode()) .matchRestful(false) diff --git a/shenyu-plugin/shenyu-plugin-store-test-support/src/main/java/org/apache/shenyu/plugin/store/test/support/LegacyPluginContractKit.java b/shenyu-plugin/shenyu-plugin-store-test-support/src/main/java/org/apache/shenyu/plugin/store/test/support/LegacyPluginContractKit.java new file mode 100644 index 0000000..580b316 --- /dev/null +++ b/shenyu-plugin/shenyu-plugin-store-test-support/src/main/java/org/apache/shenyu/plugin/store/test/support/LegacyPluginContractKit.java @@ -0,0 +1,345 @@ +/* + * 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. + */ + +package org.apache.shenyu.plugin.store.test.support; + +import org.apache.shenyu.common.config.ShenyuConfig; +import org.apache.shenyu.common.dto.RuleData; +import org.apache.shenyu.plugin.api.ShenyuPlugin; +import org.apache.shenyu.plugin.api.ShenyuPluginChain; +import org.apache.shenyu.plugin.api.utils.SpringBeanUtils; +import org.apache.shenyu.plugin.base.handler.PluginDataHandler; +import org.apache.shenyu.web.handler.ShenyuWebHandler; +import org.springframework.context.ApplicationContext; +import org.springframework.context.support.GenericApplicationContext; +import org.springframework.mock.http.server.reactive.MockServerHttpRequest; +import org.springframework.mock.web.server.MockServerWebExchange; +import org.springframework.web.server.ServerWebExchange; +import reactor.core.publisher.Mono; +import reactor.core.publisher.SignalType; +import reactor.core.publisher.Sinks; +import reactor.test.StepVerifier; + +import java.io.IOException; +import java.io.InputStream; +import java.time.Duration; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.Properties; +import java.util.Set; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Function; +import java.util.function.LongSupplier; +import java.util.function.Supplier; + +/** + * Test-scope, role-aware checks around the real LEGACY root handler. + * No cursor implementation or runtime plugin dependency is introduced. + */ +public final class LegacyPluginContractKit { + + private LegacyPluginContractKit() { + } + + + /** + * Record versions and selected/unsupported capabilities without inferring support. + * @param revision declared build provenance + * @param profiles selected checks + * @param unsupported unsupported/skipped checks and reasons + * @return immutable evidence + */ + public static Evidence evidence(final String revision, final Set profiles, final Set unsupported) { + return new Evidence(version("shenyu-plugin-store-test-support"), version("shenyu-web"), + Objects.requireNonNullElse(revision, "unknown"), profiles, unsupported); + } + + /** + * Open a serial, scoped fixture using the actual handler and a no-op terminal. + * @param pluginName diagnostic plugin identity + * @param profile explicit behavioral role + * @param plugins already-ordered plugins + * @return fixture session + */ + public static Session open(final String pluginName, final Profile profile, final List plugins) { + return open(pluginName, profile, plugins, exchange -> Mono.empty()); + } + + /** + * Open a fixture with an explicit response/terminal owner. + * @param pluginName diagnostic identity + * @param profile selected role + * @param plugins explicit legacy order, never reordered + * @param terminal response fixture, called per downstream subscription + * @return fixture session + */ + public static Session open(final String pluginName, final Profile profile, final List plugins, + final Function> terminal) { + return new Session(pluginName, profile, plugins, terminal); + } + + /** + * Probe root assembly, without imposing purity on direct execute calls. + * @param pluginName diagnostic identity + * @param rootFactory real handler root publisher factory + * @param effects observable request-side effect count + */ + public static void assertDeferred(final String pluginName, final Supplier> rootFactory, final LongSupplier effects) { + long before = effects.getAsLong(); + Objects.requireNonNull(rootFactory.get(), "root publisher"); + require(before == effects.getAsLong(), pluginName + "/ROOT: request effects occurred before root subscription"); + } + + /** + * Check an explicitly supported data-handler removal contract using valid input. + * @param pluginName diagnostic identity + * @param handler actual handler + * @param rule valid fixture, including any handle required for removal + * @param cached request-free cache observation + */ + public static void assertConfigurationRemoval(final String pluginName, final PluginDataHandler handler, + final RuleData rule, final Supplier cached) { + handler.handlerRule(rule); + require(Objects.nonNull(cached.get()), pluginName + "/CONFIG: valid fixture was not published"); + handler.removeRule(rule); + require(Objects.isNull(cached.get()), pluginName + "/CONFIG: stale state remained after supported removal"); + } + + private static void require(final boolean condition, final String message) { + if (!condition) { + throw new AssertionError(message); + } + } + + private static String version(final String artifact) { + try (InputStream input = LegacyPluginContractKit.class.getResourceAsStream( + "/META-INF/maven/org.apache.shenyu/" + artifact + "/pom.properties")) { + if (Objects.isNull(input)) { + return "unknown-development-classes"; + } + Properties properties = new Properties(); + properties.load(input); + return properties.getProperty("version", "unknown"); + } catch (IOException error) { + return "unknown"; + } + } + + /** Explicit profiles; plugin order does not imply a continuation contract. */ + public enum Profile { + TRANSFORM, SHORT_CIRCUIT, WRAPPER, BASE_MATCHING, FORK + } + + /** + * Evidence labels, not a release compatibility matrix. + * @param kitVersion observed packaged kit version + * @param coreVersion observed core artifact version + * @param declaredCoreRevision caller-declared source provenance, or unknown + * @param profiles explicitly selected profiles + * @param unsupported explicitly untested capabilities + */ + public record Evidence(String kitVersion, String coreVersion, String declaredCoreRevision, + Set profiles, Set unsupported) { + public Evidence { + profiles = Set.copyOf(profiles); + unsupported = Set.copyOf(unsupported); + } + } + + /** Static core caches and Spring context require serial fixture use. */ + public static final class Session implements AutoCloseable { + + private final String label; + + private final ApplicationContext previousContext; + + private final GenericApplicationContext context; + + private final AtomicInteger downstream = new AtomicInteger(); + + private final MockServerWebExchange exchange; + + private final Mono root; + + private Session(final String name, final Profile profile, final List plugins, + final Function> terminal) { + label = Objects.requireNonNull(name) + "/" + Objects.requireNonNull(profile); + final List snapshot = new ArrayList<>(List.copyOf(plugins)); + Objects.requireNonNull(terminal); + previousContext = SpringBeanUtils.getInstance().getApplicationContext(); + context = new GenericApplicationContext(); + ShenyuConfig config = new ShenyuConfig(); + config.getScheduler().setEnabled(false); + context.registerBean(ShenyuConfig.class, () -> config); + context.refresh(); + SpringBeanUtils.getInstance().setApplicationContext(context); + snapshot.add(new ShenyuPlugin() { + @Override + public Mono execute(final ServerWebExchange current, final ShenyuPluginChain chain) { + return Mono.defer(() -> { + downstream.incrementAndGet(); + return terminal.apply(current); + }); + } + + @Override + public int getOrder() { + return Integer.MAX_VALUE; + } + }); + exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/contract/request").build()); + GatewayFixtures.initExchange(exchange); + root = new ShenyuWebHandler(snapshot, null, config).handle(exchange); + } + + /** + * Access the owned request for response/decorator assertions. + * @return fixture exchange + */ + public MockServerWebExchange exchange() { + return exchange; + } + + /** + * Register an explicitly owned test bean before subscribing the root. + * @param type fixture bean type + * @param factory fixture supplier; no SDK or credential is supplied by the kit + * @param bean type + */ + public void registerFixtureBean(final Class type, final Supplier factory) { + context.registerBean(type, factory); + } + + /** + * Access the original root, including repeated root subscriptions. + * @return real deferred handler publisher + */ + public Mono publisher() { + return root; + } + + /** + * Observe actual terminal subscriptions, distinct from method construction. + * @return downstream subscription count + */ + public int downstreamSubscriptions() { + return downstream.get(); + } + + /** + * Verify completion with an explicit role expectation; wrappers may declare multiple subscriptions. + * @param expectedDownstream expected terminal subscriptions + */ + public void verifyComplete(final int expectedDownstream) { + try { + StepVerifier.create(root).expectComplete().verify(Duration.ofSeconds(5)); + } catch (AssertionError error) { + throw new AssertionError(label + ": completion contract failed", error); + } + require(downstream.get() == expectedDownstream, label + ": expected downstream subscriptions " + + expectedDownstream + " but observed " + downstream.get()); + } + + /** + * Verify chain failure; outer HTTP error rendering is separate. + * @param failure expected failure type + */ + public void verifyError(final Class failure) { + try { + StepVerifier.create(root).expectError(failure).verify(Duration.ofSeconds(5)); + } catch (AssertionError error) { + throw new AssertionError(label + ": error propagation contract failed", error); + } + } + + /** + * Cancel the real root after controlled subscribed-state checks. + * @param afterSubscribed controlled signal/assertions, without sleeps + */ + public void verifyCancellation(final Runnable afterSubscribed) { + try { + StepVerifier.create(root).then(afterSubscribed).thenCancel().verify(Duration.ofSeconds(5)); + } catch (AssertionError error) { + throw new AssertionError(label + ": cancellation contract failed", error); + } + } + + /** + * Check a decorator reached the actual response owner. + * @param header response header + * @param expected expected value + */ + public void assertResponseHeader(final String header, final String expected) { + require(Objects.equals(expected, exchange.getResponse().getHeaders().getFirst(header)), + label + ": response decorator/header propagation failed for " + header); + } + + /** + * Create an independent owner-termination probe. + * @return release probe + */ + public ReleaseProbe releaseProbe() { + return new ReleaseProbe(label); + } + + @Override + public void close() { + if (SpringBeanUtils.getInstance().getApplicationContext() == context) { + SpringBeanUtils.getInstance().setApplicationContext(previousContext); + } + context.close(); + } + } + + /** Optional resource-owner probe, not a universal SDK lease contract. */ + public static final class ReleaseProbe { + + private final String label; + + private final AtomicInteger releases = new AtomicInteger(); + + private final Sinks.One signal = Sinks.one(); + + private ReleaseProbe(final String label) { + this.label = label; + } + + /** + * Record actual owner termination, for example from its doFinally hook. + * @param terminal owner terminal signal + */ + public void record(final SignalType terminal) { + releases.incrementAndGet(); + signal.tryEmitValue(terminal); + } + + /** + * Await the controlled owner signal and require one release. + * @param expected terminal classification + * @param timeout explicit bounded test wait + */ + public void assertReleasedOnce(final SignalType expected, final Duration timeout) { + try { + StepVerifier.create(signal.asMono()).expectNext(expected).expectComplete().verify(timeout); + } catch (AssertionError error) { + throw new AssertionError(label + ": owner cleanup/cancellation signal missing or incorrect", error); + } + require(releases.get() == 1, label + ": resource released " + releases.get() + " times"); + } + } +} diff --git a/shenyu-plugin/shenyu-plugin-store-test-support/src/test/java/org/apache/shenyu/plugin/store/test/support/LegacyPluginContractKitTest.java b/shenyu-plugin/shenyu-plugin-store-test-support/src/test/java/org/apache/shenyu/plugin/store/test/support/LegacyPluginContractKitTest.java new file mode 100644 index 0000000..cce1057 --- /dev/null +++ b/shenyu-plugin/shenyu-plugin-store-test-support/src/test/java/org/apache/shenyu/plugin/store/test/support/LegacyPluginContractKitTest.java @@ -0,0 +1,341 @@ +/* + * 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. + */ + +package org.apache.shenyu.plugin.store.test.support; + +import org.apache.shenyu.common.dto.RuleData; +import org.apache.shenyu.common.dto.SelectorData; +import org.apache.shenyu.plugin.api.ShenyuPlugin; +import org.apache.shenyu.plugin.api.ShenyuPluginChain; +import org.apache.shenyu.plugin.base.AbstractShenyuPlugin; +import org.apache.shenyu.plugin.base.cache.BaseDataCache; +import org.apache.shenyu.plugin.base.handler.PluginDataHandler; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.reactivestreams.Publisher; +import org.springframework.core.io.buffer.DataBuffer; +import org.springframework.http.server.reactive.ServerHttpResponseDecorator; +import org.springframework.web.server.ServerWebExchange; +import reactor.core.publisher.Mono; +import reactor.core.publisher.SignalType; +import reactor.core.publisher.Sinks; +import reactor.test.StepVerifier; + +import java.time.Duration; +import java.util.ArrayList; +import java.util.List; +import java.util.Set; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.BiFunction; + +import static org.apache.shenyu.plugin.store.test.support.LegacyPluginContractKit.Profile.BASE_MATCHING; +import static org.apache.shenyu.plugin.store.test.support.LegacyPluginContractKit.Profile.FORK; +import static org.apache.shenyu.plugin.store.test.support.LegacyPluginContractKit.Profile.SHORT_CIRCUIT; +import static org.apache.shenyu.plugin.store.test.support.LegacyPluginContractKit.Profile.TRANSFORM; +import static org.apache.shenyu.plugin.store.test.support.LegacyPluginContractKit.Profile.WRAPPER; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class LegacyPluginContractKitTest { + + @AfterEach + void cleanFixtures() { + GatewayFixtures.cleanBaseDataCache(); + } + + @Test + void rootDefersRequestEffectsAndRepeatedSubscriptionsUseFreshRuntimeChains() { + AtomicInteger effects = new AtomicInteger(); + ShenyuPlugin plugin = plugin((exchange, chain) -> { + effects.incrementAndGet(); + return chain.execute(exchange); + }); + try (var session = LegacyPluginContractKit.open("transform", TRANSFORM, List.of(plugin))) { + LegacyPluginContractKit.assertDeferred("transform", session::publisher, effects::longValue); + session.verifyComplete(1); + session.verifyComplete(2); + assertEquals(2, effects.get()); + } + } + + @Test + void badAssemblyFixtureIsDetectedAtRootBoundary() { + AtomicInteger effects = new AtomicInteger(); + try (var session = LegacyPluginContractKit.open("bad-assembly", TRANSFORM, List.of())) { + AssertionError error = assertThrows(AssertionError.class, () -> LegacyPluginContractKit.assertDeferred("bad-assembly", () -> { + effects.incrementAndGet(); + return session.publisher(); + }, effects::longValue)); + assertTrue(error.getMessage().contains("bad-assembly/ROOT")); + } + } + + @Test + void wrapperAndForkProfilesDeclareTheirOwnContinuationCounts() { + ShenyuPlugin wrapper = new FixturePlugin((exchange, chain) -> { + exchange.getAttributes().put("contract-fork-dispatch", true); + return chain.fork().execute(exchange).then(chain.execute(exchange)) + .doFinally(signal -> exchange.getAttributes().remove("contract-fork-dispatch")); + }) { + @Override + public boolean skip(final ServerWebExchange exchange) { + return Boolean.TRUE.equals(exchange.getAttribute("contract-fork-dispatch")); + } + }; + try (var session = LegacyPluginContractKit.open("wrapper", WRAPPER, List.of(wrapper))) { + session.verifyComplete(2); + } + try (var session = LegacyPluginContractKit.open("fork", FORK, List.of(wrapper))) { + session.verifyComplete(2); + } + try (var session = LegacyPluginContractKit.open("bad-transform", TRANSFORM, List.of(wrapper))) { + AssertionError error = assertThrows(AssertionError.class, () -> session.verifyComplete(1)); + assertTrue(error.getMessage().contains("bad-transform/TRANSFORM")); + } + } + + @Test + void shortCircuitOwnsTheResponseWithoutCallingSuccessors() { + ShenyuPlugin response = TerminalResponsePlugin.ok("short-circuit"); + try (var session = LegacyPluginContractKit.open("response-owner", SHORT_CIRCUIT, List.of(response))) { + session.verifyComplete(0); + assertEquals("short-circuit", session.exchange().getResponse().getBodyAsString().block(Duration.ofSeconds(1))); + } + } + + @Test + void outerSkipDoesNotEnterThePlugin() { + ShenyuPlugin skipped = new FixturePlugin((exchange, chain) -> Mono.error(new IllegalStateException("Skipped plugin was entered"))) { + @Override + public boolean skip(final ServerWebExchange exchange) { + return true; + } + }; + try (var session = LegacyPluginContractKit.open("skip", TRANSFORM, List.of(skipped))) { + session.verifyComplete(1); + } + } + + @Test + void decoratorPropagationUsesTheActualResponseOwnerAndDetectsBrokenFixtures() { + for (boolean propagate : new boolean[]{true, false}) { + ShenyuPlugin transform = plugin((exchange, chain) -> { + ServerHttpResponseDecorator response = new ServerHttpResponseDecorator(exchange.getResponse()) { + @Override + public Mono writeWith(final Publisher body) { + getHeaders().add("X-Contract", "decorated"); + return super.writeWith(body); + } + }; + return chain.execute(propagate ? exchange.mutate().response(response).build() : exchange); + }); + try (var session = LegacyPluginContractKit.open("decorator", TRANSFORM, List.of(transform), + exchange -> TerminalResponsePlugin.ok("payload").execute(exchange, current -> Mono.empty()))) { + session.verifyComplete(1); + assertEquals("payload", session.exchange().getResponse().getBodyAsString().block(Duration.ofSeconds(1))); + if (propagate) { + session.assertResponseHeader("X-Contract", "decorated"); + } else { + assertThrows(AssertionError.class, () -> session.assertResponseHeader("X-Contract", "decorated")); + } + } + } + } + + @Test + void controlledAsyncCompletionKeepsBeforeAfterAtPublisherConstruction() { + List events = new ArrayList<>(); + Sinks.Empty completion = Sinks.empty(); + ShenyuPlugin wrapper = new FixturePlugin((exchange, chain) -> { + events.add("execute"); + return chain.execute(exchange); + }) { + @Override + public void before(final ServerWebExchange exchange) { + events.add("before"); + } + + @Override + public void after(final ServerWebExchange exchange) { + events.add("after"); + } + }; + try (var session = LegacyPluginContractKit.open("hooks", WRAPPER, List.of(wrapper), exchange -> completion.asMono())) { + assertTrue(events.isEmpty()); + StepVerifier.create(session.publisher()).then(() -> { + assertEquals(List.of("before", "execute", "after"), events); + completion.tryEmitEmpty(); + }).expectComplete().verify(Duration.ofSeconds(2)); + } + } + + @Test + void completionErrorAndCancellationReachTheActualOwnerExactlyOnce() { + for (SignalType terminal : new SignalType[]{SignalType.ON_COMPLETE, SignalType.ON_ERROR, SignalType.CANCEL}) { + AtomicReference owner = new AtomicReference<>(); + ShenyuPlugin plugin = plugin((exchange, chain) -> { + Mono source = terminal == SignalType.ON_COMPLETE ? Mono.empty() : Mono.never(); + if (terminal == SignalType.ON_ERROR) { + source = Mono.error(new IllegalStateException("fixture")); + } + return source.doFinally(signal -> owner.get().record(signal)); + }); + try (var session = LegacyPluginContractKit.open("owner", WRAPPER, List.of(plugin))) { + owner.set(session.releaseProbe()); + if (terminal == SignalType.ON_ERROR) { + session.verifyError(IllegalStateException.class); + } else if (terminal == SignalType.ON_COMPLETE) { + session.verifyComplete(0); + } else { + session.verifyCancellation(() -> assertEquals(0, session.downstreamSubscriptions())); + } + owner.get().assertReleasedOnce(terminal, Duration.ofSeconds(2)); + } + } + } + + @Test + void lostCancellationFixtureFailsTheOwnerCleanupCheck() { + AtomicReference owner = new AtomicReference<>(); + ShenyuPlugin bad = plugin((exchange, chain) -> Mono.never().doFinally(signal -> owner.get().record(signal)).cache()); + try (var session = LegacyPluginContractKit.open("lost-cancel", WRAPPER, List.of(bad))) { + owner.set(session.releaseProbe()); + session.verifyCancellation(() -> assertEquals(0, session.downstreamSubscriptions())); + assertThrows(AssertionError.class, () -> owner.get().assertReleasedOnce(SignalType.CANCEL, Duration.ofMillis(50))); + } + } + + @Test + void actualBaseMatchingCoversMissingConfigurationMatchAndRuleMiss() { + AtomicInteger matches = new AtomicInteger(); + AbstractShenyuPlugin base = new AbstractShenyuPlugin() { + @Override + protected Mono doExecute(final ServerWebExchange exchange, final ShenyuPluginChain chain, + final SelectorData selector, final RuleData rule) { + matches.incrementAndGet(); + return chain.execute(exchange); + } + + @Override + public int getOrder() { + return 0; + } + + @Override + public String named() { + return "contract-base-matching"; + } + }; + try (var session = LegacyPluginContractKit.open("base", BASE_MATCHING, List.of(base))) { + session.verifyComplete(1); + assertEquals(0, matches.get()); + GatewayFixtures.CachedPluginData route = GatewayFixtures.cachePluginRoute(base, "{}"); + session.verifyComplete(2); + assertEquals(1, matches.get()); + BaseDataCache.getInstance().removeRuleData(route.getRuleData()); + session.verifyComplete(3); + assertEquals(1, matches.get()); + } + } + + @Test + void supportedConfigurationRemovalDetectsStaleState() { + AtomicReference cached = new AtomicReference<>(); + RuleData rule = new RuleData(); + rule.setHandle("{}"); + for (boolean remove : new boolean[]{true, false}) { + PluginDataHandler handler = new PluginDataHandler() { + @Override + public void handlerRule(final RuleData update) { + cached.set(update.getHandle()); + } + + @Override + public void removeRule(final RuleData removed) { + if (remove) { + cached.set(null); + } + } + + @Override + public String pluginNamed() { + return "fixture-config"; + } + }; + if (remove) { + LegacyPluginContractKit.assertConfigurationRemoval("fixture-config", handler, rule, cached::get); + } else { + assertThrows(AssertionError.class, () -> LegacyPluginContractKit.assertConfigurationRemoval("fixture-config", handler, rule, cached::get)); + } + } + } + + @Test + void evidenceKeepsUnsupportedProfilesExplicit() { + var evidence = LegacyPluginContractKit.evidence("declared-fixture-revision", Set.of(TRANSFORM), Set.of("SDK leases: unsupported")); + assertEquals(Set.of(TRANSFORM), evidence.profiles()); + assertTrue(evidence.unsupported().contains("SDK leases: unsupported")); + assertThrows(UnsupportedOperationException.class, () -> evidence.profiles().clear()); + } + + @Test + void nestedWrappersKeepTheirDeclaredSuccessorScopes() { + List events = new ArrayList<>(); + ShenyuPlugin outer = plugin((exchange, chain) -> Mono.defer(() -> { + events.add("outer-enter"); + return chain.execute(exchange).doOnSuccess(value -> events.add("outer-exit")); + })); + ShenyuPlugin inner = plugin((exchange, chain) -> Mono.defer(() -> { + events.add("inner-enter"); + return chain.execute(exchange).doOnSuccess(value -> events.add("inner-exit")); + })); + try (var session = LegacyPluginContractKit.open("nested", WRAPPER, List.of(outer, inner))) { + session.verifyComplete(1); + assertEquals(List.of("outer-enter", "inner-enter", "inner-exit", "outer-exit"), events); + } + } + + private ShenyuPlugin plugin(final BiFunction> behavior) { + return new FixturePlugin(behavior); + } + + private static class FixturePlugin implements ShenyuPlugin { + + private final BiFunction> behavior; + + protected FixturePlugin(final BiFunction> behavior) { + this.behavior = behavior; + } + + @Override + public Mono execute(final ServerWebExchange exchange, final ShenyuPluginChain chain) { + return behavior.apply(exchange, chain); + } + + @Override + public int getOrder() { + return 0; + } + + @Override + public String named() { + return "contract-fixture"; + } + } +}