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
81 changes: 81 additions & 0 deletions contract-examples/legacy-plugin-consumer/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
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.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example.shenyu</groupId>
<artifactId>legacy-plugin-contract-consumer</artifactId>
<version>1.0-SNAPSHOT</version>
<!-- Deliberately no parent and no membership in the source reactor. -->
<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<contract.kit.version>2.7.1-SNAPSHOT</contract.kit.version>
</properties>
<dependencies>
<dependency>
<groupId>org.apache.shenyu</groupId>
<artifactId>shenyu-plugin-store-test-support</artifactId>
<version>${contract.kit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>5.10.2</version>
<scope>test</scope>
</dependency>
</dependencies>
<repositories>
<repository>
<id>contract-staging</id>
<url>${contract.stagingRepository}</url>
<snapshots><enabled>true</enabled><updatePolicy>always</updatePolicy></snapshots>
<releases><enabled>true</enabled></releases>
</repository>
<repository>
<id>cached-releases</id>
<url>${contract.dependencyCache}</url>
<snapshots><enabled>false</enabled></snapshots>
<releases><enabled>true</enabled></releases>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>cached-release-plugins</id>
<url>${contract.dependencyCache}</url>
<snapshots><enabled>false</enabled></snapshots>
<releases><enabled>true</enabled></releases>
</pluginRepository>
</pluginRepositories>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.7.0</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.0.0-M4</version>
</plugin>
</plugins>
</build>
</project>
Original file line number Diff line number Diff line change
@@ -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<Void> 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"));
}
}
}
Original file line number Diff line number Diff line change
@@ -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<Void> 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<Void> 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<Void> execute(final ServerWebExchange exchange, final ShenyuPluginChain chain) {
return chain.execute(exchange).doFinally(signal -> terminalSignals.incrementAndGet());
}

@Override
public int getOrder() {
return 0;
}
}
}
133 changes: 133 additions & 0 deletions script/plugin-store/verify-legacy-contract-consumer.ps1
Original file line number Diff line number Diff line change
@@ -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
}
Loading