From 53ed8024e357780d1ce0ce543bccefcd43695e5f Mon Sep 17 00:00:00 2001 From: hanzhe-one <200491821+hanzhe-one@users.noreply.github.com> Date: Sat, 7 Nov 2026 19:15:45 +0800 Subject: [PATCH] feat(plugin): publish opt-in read-only base configuration --- .../DivideGatewayBenchmark.java | 322 ++++++++++++- .../divide-gateway/README-config-views.md | 129 ++++++ .../divide-gateway/run-config-views.ps1 | 214 +++++++++ docs/read-only-base-configuration.md | 154 +++++++ .../apache/shenyu/common/dto/BaseData.java | 54 +++ .../shenyu/common/dto/ConditionData.java | 52 +++ .../shenyu/common/dto/DtoSnapshots.java | 136 ++++++ .../apache/shenyu/common/dto/PluginData.java | 15 + .../apache/shenyu/common/dto/RuleData.java | 25 + .../shenyu/common/dto/SelectorData.java | 29 ++ .../shenyu/common/dto/DtoSnapshotsTest.java | 429 ++++++++++++++++++ .../plugin/base/AbstractShenyuPlugin.java | 73 ++- .../plugin/base/cache/BaseDataCache.java | 198 ++++++-- .../plugin/base/cache/MatchDataCache.java | 142 +++++- .../plugin/base/cache/MatchDataCacheTest.java | 4 +- .../cache/PublishedConfigurationTest.java | 248 ++++++++++ .../shenyu/plugin/divide/DividePlugin.java | 5 + .../DividePublishedConfigurationTest.java | 246 ++++++++++ 18 files changed, 2400 insertions(+), 75 deletions(-) create mode 100644 docs/benchmarks/divide-gateway/README-config-views.md create mode 100644 docs/benchmarks/divide-gateway/run-config-views.ps1 create mode 100644 docs/read-only-base-configuration.md create mode 100644 shenyu-common/src/main/java/org/apache/shenyu/common/dto/DtoSnapshots.java create mode 100644 shenyu-common/src/test/java/org/apache/shenyu/common/dto/DtoSnapshotsTest.java create mode 100644 shenyu-plugin/shenyu-plugin-base/src/test/java/org/apache/shenyu/plugin/base/cache/PublishedConfigurationTest.java create mode 100644 shenyu-plugin/shenyu-plugin-proxy/shenyu-plugin-divide/src/test/java/org/apache/shenyu/plugin/divide/DividePublishedConfigurationTest.java diff --git a/docs/benchmarks/divide-gateway/DivideGatewayBenchmark.java b/docs/benchmarks/divide-gateway/DivideGatewayBenchmark.java index bf7386f9fa06..3fdcd424ddc7 100644 --- a/docs/benchmarks/divide-gateway/DivideGatewayBenchmark.java +++ b/docs/benchmarks/divide-gateway/DivideGatewayBenchmark.java @@ -21,18 +21,22 @@ import com.sun.management.ThreadMXBean; import org.apache.shenyu.common.config.ShenyuConfig; import org.apache.shenyu.common.constant.Constants; +import org.apache.shenyu.common.dto.ConditionData; import org.apache.shenyu.common.dto.PluginData; +import org.apache.shenyu.common.dto.RuleData; import org.apache.shenyu.common.dto.SelectorData; import org.apache.shenyu.common.dto.convert.rule.impl.DivideRuleHandle; import org.apache.shenyu.common.utils.Singleton; import org.apache.shenyu.loadbalancer.cache.UpstreamCacheManager; import org.apache.shenyu.loadbalancer.entity.Upstream; import org.apache.shenyu.plugin.api.ShenyuPlugin; +import org.apache.shenyu.plugin.api.ShenyuPluginChain; import org.apache.shenyu.plugin.api.context.ShenyuContext; import org.apache.shenyu.plugin.api.result.DefaultShenyuResult; import org.apache.shenyu.plugin.api.result.ShenyuResult; import org.apache.shenyu.plugin.api.utils.SpringBeanUtils; import org.apache.shenyu.plugin.base.cache.BaseDataCache; +import org.apache.shenyu.plugin.base.cache.MatchDataCache; import org.apache.shenyu.plugin.base.circuitbreaker.UpstreamCircuitBreaker; import org.apache.shenyu.plugin.base.utils.CacheKeyUtils; import org.apache.shenyu.plugin.divide.DividePlugin; @@ -45,9 +49,12 @@ import org.apache.shenyu.web.handler.ShenyuWebHandler; import org.springframework.context.support.GenericApplicationContext; import org.springframework.http.server.reactive.ReactorHttpHandlerAdapter; +import org.springframework.web.server.ServerWebExchange; import org.springframework.web.server.adapter.WebHttpHandlerBuilder; import reactor.core.publisher.Mono; import reactor.core.publisher.Sinks; +import reactor.core.scheduler.Scheduler; +import reactor.core.scheduler.Schedulers; import reactor.netty.DisposableServer; import reactor.netty.http.server.HttpServer; import reactor.netty.resources.ConnectionProvider; @@ -92,7 +99,12 @@ private DivideGatewayBenchmark() { } public static void main(final String[] args) throws Exception { switch (args[0]) { case "upstream" -> upstream(Path.of(args[1])); - case "gateway" -> gateway(Path.of(args[1]), Path.of(args[2])); + case "gateway" -> gateway(Path.of(args[1]), Path.of(args[2]), args.length > 3 && args[3].equals("config-views")); + case "load-config" -> { + load(Integer.parseInt(args[1]), Integer.parseInt(args[2]), Integer.parseInt(args[3]), Path.of(args[4]), + args[5], Integer.parseInt(args[6]), Integer.parseInt(args[7])); + System.exit(0); + } case "load" -> { load(Integer.parseInt(args[1]), Integer.parseInt(args[2]), Integer.parseInt(args[3]), Path.of(args[4])); System.exit(0); @@ -101,7 +113,7 @@ public static void main(final String[] args) throws Exception { verify(Integer.parseInt(args[1]), Path.of(args[2]), Path.of(args[3])); System.exit(0); } - default -> throw new IllegalArgumentException("mode: upstream, gateway, load or verify"); + default -> throw new IllegalArgumentException("mode: upstream, gateway [config-views], load, load-config or verify"); } } @@ -145,7 +157,7 @@ private static void upstream(final Path ready) throws Exception { new CountDownLatch(1).await(); } - private static void gateway(final Path upstreamFile, final Path ready) throws Exception { + private static void gateway(final Path upstreamFile, final Path ready, final boolean configViews) throws Exception { int[] ports = GSON.fromJson(Files.readString(upstreamFile), int[].class); ShenyuConfig config = new ShenyuConfig(); config.getUpstreamCheck().setEnabled(false); @@ -179,6 +191,7 @@ private static void gateway(final Path upstreamFile, final Path ready) throws Ex ConnectionProvider pool = ConnectionProvider.builder("gateway-upstreams").maxConnections(128).pendingAcquireMaxCount(2048).build(); reactor.netty.http.client.HttpClient netty = reactor.netty.http.client.HttpClient.create(pool) .runOn(LoopResources.create("gateway-client", 4, true)).disableRetry(true); + ConfigViews views = configViews ? new ConfigViews(config, ports[0]) : null; List plugins = List.of(new GlobalPlugin(exchange -> { ShenyuContext value = new ShenyuContext(); value.setRpcType("http"); @@ -186,10 +199,14 @@ private static void gateway(final Path upstreamFile, final Path ready) throws Ex value.setRealUrl(exchange.getRequest().getURI().getRawPath()); value.setHttpMethod(exchange.getRequest().getMethod().name()); return value; - }), new DividePlugin(), new URIPlugin(), new NettyHttpClientPlugin(netty, 1024 * 1024), + }), configViews ? new ConfigDividePlugin() : new DividePlugin(), new URIPlugin(), new NettyHttpClientPlugin(netty, 1024 * 1024), new ResponsePlugin(Map.of("http", new NettyClientMessageWriter()))); ShenyuWebHandler handler = new ShenyuWebHandler(plugins, null, config); ReactorHttpHandlerAdapter adapter = new ReactorHttpHandlerAdapter(WebHttpHandlerBuilder.webHandler(exchange -> { + if (views != null && exchange.getRequest().getPath().value().startsWith("/_bench/")) { + return Mono.fromCallable(() -> views.control(exchange)).subscribeOn(views.controlWorker) + .flatMap(data -> text(exchange, GSON.toJson(data))); + } if (exchange.getRequest().getPath().value().startsWith("/_bench/")) { String action = exchange.getRequest().getPath().value().substring("/_bench/".length()); Map data; @@ -251,6 +268,237 @@ private static void configure(final int[] ports, final int size, final String st DividePluginDataHandler.CACHED_HANDLE.get().cachedHandle(CacheKeyUtils.INST.getKey(SELECTOR, Constants.DEFAULT_RULE), rule); } + private static Mono text(final ServerWebExchange exchange, final String value) { + byte[] bytes = value.getBytes(java.nio.charset.StandardCharsets.UTF_8); + return exchange.getResponse().writeWith(Mono.just(exchange.getResponse().bufferFactory().wrap(bytes))); + } + + // Only observation and explicit miss responses are fixture-specific; matching and forwarding + // use the variant's actual DividePlugin/AbstractShenyuPlugin, with no new read-only API linkage. + private static final class ConfigDividePlugin extends DividePlugin { + @Override + protected Mono doExecute(final ServerWebExchange exchange, final ShenyuPluginChain chain, + final SelectorData selector, final RuleData rule) { + exchange.getResponse().getHeaders().set("X-Bench-Version", rule.getName()); + exchange.getResponse().getHeaders().set("X-Bench-Observed-Ns", Long.toString(System.nanoTime())); + return super.doExecute(exchange, chain, selector, rule); + } + + @Override + protected Mono handleSelectorIfNull(final String plugin, final ServerWebExchange exchange, final ShenyuPluginChain chain) { + return miss(exchange); + } + + @Override + protected Mono handleRuleIfNull(final String plugin, final ServerWebExchange exchange, final ShenyuPluginChain chain) { + return miss(exchange); + } + + private Mono miss(final ServerWebExchange exchange) { + exchange.getResponse().setStatusCode(org.springframework.http.HttpStatus.NOT_FOUND); + return text(exchange, "config-no-match"); + } + } + + private static String selectorId(final int index) { + return SELECTOR + "-config-" + index; + } + + private static String matchedPath(final int size) { + return "/config/" + (size - 1) + "/r" + (size - 1) + "/test"; + } + + private static List conditions(final String prefix, final int count) { + List result = new ArrayList<>(); + for (int index = 0; index < count; index++) { + ConditionData condition = new ConditionData(); + condition.setParamType("uri"); + condition.setParamName("/"); + condition.setOperator("startsWith"); + // All predicates are path-only and true for the sole matching candidate. + condition.setParamValue(index == 0 ? prefix : "/config/"); + result.add(condition); + } + return result; + } + + private static RuleData configRule(final int selector, final int index, final int count, final long version) { + RuleData rule = new RuleData(); + rule.setId(selectorId(selector) + "-r" + index); + rule.setSelectorId(selectorId(selector)); + rule.setPluginName("divide"); + rule.setName("v" + version); + rule.setEnabled(true); + rule.setLogged(false); + rule.setSort(index); + rule.setMatchMode(0); + rule.setMatchRestful(false); + rule.setConditionDataList(conditions("/config/" + selector + "/r" + index + "/", count)); + return rule; + } + + private static final class ConfigViews { + private final ShenyuConfig config; + private final int upstreamPort; + private final Scheduler controlWorker = Schedulers.newBoundedElastic(1, 16, "config-control"); + private final java.util.concurrent.ScheduledExecutorService sampler = Executors.newSingleThreadScheduledExecutor(); + private final AtomicLong peakHeap = new AtomicLong(); + private volatile boolean sampling; + private Map before; + private Map retainedBefore; + private int size; + private int conditionCount; + private long version; + + private ConfigViews(final ShenyuConfig config, final int upstreamPort) { + this.config = config; + this.upstreamPort = upstreamPort; + sampler.scheduleAtFixedRate(() -> { + if (sampling) { + peakHeap.accumulateAndGet(heap(), Math::max); + } + }, 0, 10, java.util.concurrent.TimeUnit.MILLISECONDS); + Runtime.getRuntime().addShutdownHook(new Thread(() -> { + sampler.shutdownNow(); + controlWorker.dispose(); + })); + } + + private Map control(final ServerWebExchange exchange) throws Exception { + String action = exchange.getRequest().getPath().value(); + var query = exchange.getRequest().getQueryParams(); + if (action.equals("/_bench/config-view")) { + int nextSize = Integer.parseInt(query.getFirst("size")); + int nextConditions = Integer.parseInt(query.getFirst("conditions")); + String state = query.getFirst("state"); + if ((nextSize != 1 && nextSize != 128) || nextConditions < 1 || nextConditions > 128 + || !List.of("matched", "no-match", "cache-hit").contains(state)) { + throw new IllegalArgumentException("size=1|128; conditions=1..128; state=matched|no-match|cache-hit"); + } + Map setupBefore = metrics(); + long heapBefore = heap(); + long begin = System.nanoTime(); + install(nextSize, nextConditions, state.equals("cache-hit")); + long elapsed = System.nanoTime() - begin; + Map setup = metrics(); + setup.replaceAll((key, value) -> value - setupBefore.get(key)); + setup.put("elapsed_ns", elapsed); + setup.put("heap_before_bytes", heapBefore); + setup.put("heap_after_bytes", heap()); + return Map.of("selectors", size, "rulesPerSelector", size, "conditionsPerEntry", conditionCount, + "state", state, "version", "v" + version, "setup", setup); + } + if (action.equals("/_bench/config-burst")) { + int updates = Integer.parseInt(query.getFirst("count")); + if (size == 0 || updates < 1 || updates > 128) { + throw new IllegalArgumentException("configure first; burst count=1..128"); + } + long total = 0; + long max = 0; + long published = 0; + long started = System.nanoTime(); + for (int index = 0; index < updates; index++) { + RuleData rule = configRule(size - 1, size - 1, conditionCount, ++version); + long begin = System.nanoTime(); + // Publication + derived-cache invalidation, NOT Admin/network synchronization. + BaseDataCache.getInstance().cacheRuleData(rule); + MatchDataCache.getInstance().removeRuleData("divide"); + published = System.nanoTime(); + long elapsed = published - begin; + total += elapsed; + max = Math.max(max, elapsed); + } + return Map.of("updates", updates, "updateNs", total, "maxUpdateNs", max, + "burstNs", System.nanoTime() - started, "publishedAtNs", Long.toString(published), "version", "v" + version); + } + if (action.equals("/_bench/start")) { + retainedBefore = retained(); + peakHeap.set(heap()); + sampling = true; + before = metrics(); + return Map.of("started", 1); + } + if (action.equals("/_bench/metrics")) { + Map delta = metrics(); + if (before == null) { + throw new IllegalStateException("start measurement first"); + } + delta.replaceAll((key, value) -> value - before.get(key)); + sampling = false; + peakHeap.accumulateAndGet(heap(), Math::max); + Map result = new LinkedHashMap<>(delta); + result.put("sampled_peak_heap_bytes", peakHeap.get()); + result.put("heap_sample_interval_ms", 10); + result.put("retained_before", retainedBefore); + return result; + } + if (action.equals("/_bench/retained")) { + return retained(); + } + throw new IllegalArgumentException("unknown config-view control action"); + } + + private void install(final int nextSize, final int nextConditions, final boolean cacheHit) { + BaseDataCache cache = BaseDataCache.getInstance(); + cache.cleanSelectorData(); + cache.cleanRuleData(); + MatchDataCache.getInstance().cleanSelectorData(); + MatchDataCache.getInstance().cleanRuleDataData(); + for (int index = 0; index < size; index++) { + UpstreamCacheManager.getInstance().removeByKey(selectorId(index)); + } + DividePluginDataHandler.CACHED_HANDLE.get().getAllCache().clear(); + size = nextSize; + conditionCount = nextConditions; + version = 0; + for (ShenyuConfig.MatchCacheConfig match : List.of(config.getSelectorMatchCache().getCache(), config.getRuleMatchCache().getCache())) { + match.setEnabled(cacheHit); + match.setInitialCapacity(256); + match.setMaximumSize(1024); + match.setTtl(600000); + } + for (int index = 0; index < size; index++) { + SelectorData selector = new SelectorData(); + selector.setId(selectorId(index)); + selector.setName(selectorId(index)); + selector.setPluginName("divide"); + selector.setEnabled(true); + selector.setType(1); + selector.setSort(index); + selector.setLogged(false); + selector.setContinued(true); + selector.setMatchMode(0); + selector.setMatchRestful(false); + selector.setConditionList(conditions("/config/" + index + "/", conditionCount)); + cache.cacheSelectData(selector); + UpstreamCacheManager.getInstance().submit(selector.getId(), List.of(Upstream.builder().protocol("http://") + .url("127.0.0.1:" + upstreamPort).weight(50).healthCheckEnabled(false).build())); + for (int ruleIndex = 0; ruleIndex < size; ruleIndex++) { + RuleData rule = configRule(index, ruleIndex, conditionCount, version); + DivideRuleHandle handle = new DivideRuleHandle(); + handle.setRetry(0); + handle.setTimeout(60000); + DividePluginDataHandler.CACHED_HANDLE.get().cachedHandle(CacheKeyUtils.INST.getKey(rule), handle); + cache.cacheRuleData(rule); + } + } + } + + private static long heap() { + return ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getUsed(); + } + + private static Map retained() throws InterruptedException { + long beforeGc = metrics().get("gc_count"); + System.gc(); // Control worker only; explicit GC lies outside the measurement window. + long deadline = System.nanoTime() + Duration.ofSeconds(5).toNanos(); + while (metrics().get("gc_count") <= beforeGc && System.nanoTime() < deadline) { + Thread.sleep(20); + } + return Map.of("heap_bytes", heap(), "gc_observed", metrics().get("gc_count") > beforeGc); + } + } + private static Map metrics() { Map result = new LinkedHashMap<>(); long allocated = 0; @@ -265,11 +513,32 @@ private static Map metrics() { } private static void load(final int port, final int count, final int rate, final Path output) throws Exception { + load(port, count, rate, output, null, 0, 0); + } + + private static void load(final int port, final int count, final int rate, final Path output, + final String state, final int size, final int burst) throws Exception { + boolean configViews = state != null; + if (count < 2 || rate < 1) { + throw new IllegalArgumentException("count >= 2 and rate >= 1 required"); + } + String path = configViews ? state.equals("no-match") ? "/config/no-match/test" : matchedPath(size) : "/test"; + boolean miss = configViews && state.equals("no-match"); // Warm the load-generator JVM's connection and JIT before measuring. for (int index = 0; index < 100; index++) { - get(port, "/test"); + HttpResponse warm = CLIENT.send(request(port, path), HttpResponse.BodyHandlers.ofString()); + if (configViews) { + check(expected(warm, miss), "config-view warmup response", null); + } + } + if (configViews) { + // Exercise both selector-miss and rule-miss paths; neither may fall through to URIPlugin. + check(expected(CLIENT.send(request(port, "/config/no-match/test"), HttpResponse.BodyHandlers.ofString()), true), "selector miss", null); + check(expected(CLIENT.send(request(port, "/config/" + (size - 1) + "/no-rule"), HttpResponse.BodyHandlers.ofString()), true), "rule miss", null); + checkVersion(port, matchedPath(size), "v0"); } get(port, "/_bench/start"); + CompletableFuture> update = null; Semaphore concurrent = new Semaphore(128); CountDownLatch completed = new CountDownLatch(count); AtomicInteger successes = new AtomicInteger(); @@ -284,13 +553,29 @@ private static void load(final int port, final int count, final int rate, final if (wait > 0) { LockSupport.parkNanos(wait); } + if (configViews && burst > 0 && index == count / 2) { + update = CompletableFuture.supplyAsync(() -> { + try { + Map data = GSON.fromJson(get(port, "/_bench/config-burst?count=" + burst), Map.class); + String version = (String) data.get("version"); + long published = Long.parseLong((String) data.get("publishedAtNs")); + HttpResponse visible = checkVersion(port, matchedPath(size), version); + long observed = Long.parseLong(visible.headers().firstValue("X-Bench-Observed-Ns").orElseThrow()); + data.put("firstVisibleNs", observed - published); + data.put("firstRequestVisible", true); + return data; + } catch (Exception error) { + throw new java.util.concurrent.CompletionException(error); + } + }); + } concurrent.acquire(); long sent = System.nanoTime(); - CLIENT.sendAsync(request(port, "/test"), HttpResponse.BodyHandlers.ofString()).whenComplete((response, error) -> { + CLIENT.sendAsync(request(port, path), HttpResponse.BodyHandlers.ofString()).whenComplete((response, error) -> { long finished = System.nanoTime(); latency[sample] = finished - sent; scheduledLatency[sample] = finished - due; - if (error == null && response.statusCode() == 200 && response.body().equals(BODY)) { + if (error == null && expected(response, miss)) { successes.incrementAndGet(); } else { errors.incrementAndGet(); @@ -303,19 +588,42 @@ private static void load(final int port, final int count, final int rate, final throw new IllegalStateException("load did not finish"); } long elapsed = System.nanoTime() - started; + Map updateResult = update == null ? Map.of() : update.get(30, java.util.concurrent.TimeUnit.SECONDS); Map result = GSON.fromJson(get(port, "/_bench/metrics"), Map.class); + if (configViews) { + result.put("update", updateResult); + result.put("state", state); + result.put("upstream_successes", miss ? 0 : successes.get()); + result.put("retained_after", GSON.fromJson(get(port, "/_bench/retained"), Map.class)); + if (burst > 0) { + checkVersion(port, matchedPath(size), (String) updateResult.get("version")); + } + } Arrays.sort(latency); Arrays.sort(scheduledLatency); result.put("requests", count); result.put("successes", successes.get()); result.put("errors", errors.get()); result.put("elapsed_ns", elapsed); + result.put("p95_ns", latency[count * 95 / 100]); + result.put("scheduled_p95_ns", scheduledLatency[count * 95 / 100]); result.put("p99_ns", latency[count * 99 / 100]); result.put("scheduled_p99_ns", scheduledLatency[count * 99 / 100]); result.put("rate", rate); Files.writeString(output, GSON.toJson(result)); } + private static boolean expected(final HttpResponse response, final boolean miss) { + return response.statusCode() == (miss ? 404 : 200) && response.body().equals(miss ? "config-no-match" : BODY); + } + + private static HttpResponse checkVersion(final int port, final String path, final String version) throws Exception { + HttpResponse response = CLIENT.send(request(port, path), HttpResponse.BodyHandlers.ofString()); + check(expected(response, false) && version.equals(response.headers().firstValue("X-Bench-Version").orElse(null)), + "first post-publication request must see " + version, null); + return response; + } + private static HttpRequest request(final int port, final String path) { return HttpRequest.newBuilder(URI.create("http://127.0.0.1:" + port + path)).timeout(Duration.ofSeconds(30)).GET().build(); } diff --git a/docs/benchmarks/divide-gateway/README-config-views.md b/docs/benchmarks/divide-gateway/README-config-views.md new file mode 100644 index 000000000000..4d5bfd516fe0 --- /dev/null +++ b/docs/benchmarks/divide-gateway/README-config-views.md @@ -0,0 +1,129 @@ + + +# Config-view comparison (issue #8223) + +No measurements are included. This is a separate mode of the existing HTTP +harness; `run.ps1` and its upstream/circuit-breaker scenarios are unchanged. +The proposed change is opt-in frozen BaseDataCache views, enabled by Divide; +this is not a gateway-wide immutable DTO migration. + +## Prerequisites and invocation + +Windows PowerShell, JDK 17 (`JAVA_HOME`), installed gateway dependencies and the +existing Divide `target/gateway-classpath.txt` are required. Compile the changed +common/base/api/Divide classes separately first. The script rejects missing or +older class files, puts those four local `target/classes` directories ahead of +installed jars (then any available local loadbalancer/web/HTTP support outputs), +and **never runs Maven or downloads dependencies**. + +```powershell +./docs/benchmarks/divide-gateway/run-config-views.ps1 -CompileOnly +./docs/benchmarks/divide-gateway/run-config-views.ps1 +./docs/benchmarks/divide-gateway/run-config-views.ps1 -Rates 500,1000,2000 -Requests 10000 +./docs/benchmarks/divide-gateway/run-config-views.ps1 -Profile +``` + +`-Repeats` is at least three. Baseline/change order alternates on successive +repeats. Every sample gets a fresh gateway JVM; variants never run concurrently. +Both use the same fixture, dependencies, 512 MiB fixed heap, eight active CPUs, +four server/client loops, 128 client concurrency, 2 ms upstream delay, 1024-byte +body, retries disabled, and 100 warmup requests. Profile mode applies the same +JFR profile to both variants; compare unprofiled results separately. Raw JSON, +CSV, logs and optional JFR go only to Divide's `target/config-views-*` directory. +JFR is local diagnostic material, not a sanitized artifact to publish blindly. + +Baseline `548bec1f9` exports exactly BaseData, ConditionData, PluginData, +RuleData, SelectorData, BaseDataCache, MatchDataCache, AbstractShenyuPlugin and +DividePlugin using `git show`, then compiles them as classpath overrides. +It does not export DtoSnapshots or alter any baseline source. The harness is +compiled against those baseline APIs and does not reference `readOnly()` or +DtoSnapshots. Timed requests run the actual variant's Divide execute/matching +and HTTP forwarding. A small subclass only exposes the rule version/observation +time as response headers and overrides no-selector/no-rule to return explicit +`404 config-no-match`, never a URIPlugin NPE or an accidentally accepted 502. + +## Matrix and control API + +`gateway config-views` enables the new controls. +All servers bind to loopback; there are no credentials or token fixtures. + +- `/_bench/config-view?size=1|128&conditions=2&state=matched|no-match|cache-hit` + publishes 1 or 128 custom-flow selectors, each with 1 or 128 rules. Thus the + large profile has 128 selectors and 16,384 rules, **not 128 total rules**. + Every selector/rule has `-Conditions` path-only AND predicates (default 2, + allowed 1..128); selectors continue to rule matching. One upstream per + selector is held constant. Exactly one selector/rule matches the last route. +- Matched and selector-no-match run without match caches. Cache-hit repeats the + same matching URI after warmup with bounded 1024-entry caches and a 10-minute + TTL. Untimed validation also exercises rule-no-match. No-match expected + responses are 404s; CSV `upstream_successes` counts load requests only and is + explicitly zero for no-match. Untimed correctness and burst-visibility probes + still contact the upstream, even in no-match samples. +- Each state runs both steady (`updates=0`) and burst (`-Burst`, default 32, + capped at 128) cases. At the load midpoint a separate client task calls + `/_bench/config-burst?count=N`. The single bounded control worker builds new + same-ID rule DTOs, publishes through `BaseDataCache.cacheRuleData`, and calls + `MatchDataCache.removeRuleData("divide")` after each update. No parsed handle + changes are needed: only the rule name/version changes. +- The first HTTP probe issued after the burst response must see the final + version via real Divide matching, including the warm cached route. Another + post-load probe checks it again. This tests **publication visibility**, not + Admin persistence, transport sync, or atomic multi-object refresh. In-flight + requests may use older snapshots; a late stale-cache refill fails verification. + +## Metrics and limitations + +The existing load loop supplies allocation bytes, process CPU, GC count/time, +complete-body p95/p99 and scheduling-aware p95/p99. The latter includes time +waiting for the intended send slot/concurrency permit. `successes` means exact +expected status/body, not necessarily an upstream response. `sampled_peak_heap` +is the gateway heap high-water mark sampled every 10 ms, not an exact peak or +RSS. `retained_before/after` report heap after explicit GC, outside the timed +window; the runner requires an observed GC. GC and configuration run on one +bounded control worker, never blocking a gateway event loop (GC itself can +still pause the JVM). + +Setup is reported separately in each `.setup.json` and CSV: installation elapsed +ns, allocated bytes, CPU, GC and before/after used heap. It includes DTO/handle +construction and cache publication; heap endpoints are not setup peak/retained +heap. The sampled peak covers the load/update window only. + +`updateNs` sums only publication + invalidation; `maxUpdateNs` is the maximum +single update and `burstNs` includes DTO construction. `firstVisibleNs` is +measured on the **gateway clock**, from final publication completion to the +first post-ack probe's Divide observation; it includes control round-trip and +probe scheduling. It is an upper bound from one verified probe, not the earliest +visibility among all concurrent requests. Intermediate burst versions are not +individually probed. Burst allocation/CPU include control/probe work and cannot +be attributed solely to application requests. Gateway metrics are captured +after draining load and the update task; latency elapsed time covers the load. + +Fixed-rate throughput is only observed throughput at that offered rate, **not +capacity**. Use `-Rates` to sweep toward saturation and inspect errors plus +scheduled latency/queueing; increase requests/duration and check client CPU as +well. A 128-concurrency generator and 100-request warmup are limits, not proof of +steady state. All child processes and HTTP controls have deadlines and owned +process cleanup. Increase `-TimeoutSeconds` for longer sweeps, not to hide hangs. + +Local validation is compilation/static inspection only. On this machine the +current JDK's `Selector.open()` already fails with a loopback IOException, so +HTTP correctness, cache-hit behavior, burst visibility, JFR and performance +remain unverified. The expected gateway-classpath file was also absent at +implementation time; compilation using available installed jars is not a +substitute for a matching, reproducible gateway dependency classpath. No prior +circuit-breaker CSV in this directory is evidence for config-view performance. diff --git a/docs/benchmarks/divide-gateway/run-config-views.ps1 b/docs/benchmarks/divide-gateway/run-config-views.ps1 new file mode 100644 index 000000000000..3cfe7f745f89 --- /dev/null +++ b/docs/benchmarks/divide-gateway/run-config-views.ps1 @@ -0,0 +1,214 @@ +# 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. + +param( + [ValidateRange(100, 1000000)][int]$Requests = 2000, + [ValidateRange(1, 1000000)][int[]]$Rates = @(500), + [ValidateRange(3, 100)][int]$Repeats = 3, + [ValidateRange(1, 128)][int]$Conditions = 2, + [ValidateRange(1, 128)][int]$Burst = 32, + [ValidateRange(60, 3600)][int]$TimeoutSeconds = 180, + [switch]$Profile, + [switch]$CompileOnly +) +$ErrorActionPreference = 'Stop' +$workspace = (Resolve-Path (Join-Path $PSScriptRoot '../../..')).Path +$module = Join-Path $workspace 'shenyu-plugin/shenyu-plugin-proxy/shenyu-plugin-divide' +$baseline = '548bec1f9' +$java = Join-Path $env:JAVA_HOME 'bin/java.exe' +$javac = Join-Path $env:JAVA_HOME 'bin/javac.exe' +$dependenciesFile = Join-Path $module 'target/gateway-classpath.txt' +if (!(Test-Path -LiteralPath $dependenciesFile)) { + throw 'Existing target/gateway-classpath.txt is required. This script never invokes Maven or downloads dependencies.' +} +$dependencies = (Get-Content -Raw $dependenciesFile).Trim() +foreach ($entry in $dependencies.Split(';')) { + if (!$entry -or !(Test-Path -LiteralPath $entry)) { throw "Missing installed dependency: $entry" } +} +# Local changed classes MUST precede all installed jars, including old common/base jars. +$modules = @('shenyu-common', 'shenyu-plugin/shenyu-plugin-base', 'shenyu-plugin/shenyu-plugin-api', + 'shenyu-plugin/shenyu-plugin-proxy/shenyu-plugin-divide') +$localClasses = @($modules | ForEach-Object { Join-Path $workspace "$_/target/classes" }) +foreach ($directory in $localClasses) { + if (!(Test-Path -LiteralPath $directory)) { throw "Missing compiled classes: $directory" } +} +# Reuse local supporting modules when available; older installed gateway jars can be binary-incompatible. +foreach ($support in @('shenyu-loadbalancer', 'shenyu-web', 'shenyu-plugin/shenyu-plugin-global', + 'shenyu-plugin/shenyu-plugin-httpclient', 'shenyu-plugin/shenyu-plugin-response', 'shenyu-plugin/shenyu-plugin-uri')) { + $directory = Join-Path $workspace "$support/target/classes" + if (Test-Path -LiteralPath $directory) { $localClasses += $directory } +} +$classpath = ($localClasses -join ';') + ';' + $dependencies +$sourcePaths = @( + 'shenyu-common/src/main/java/org/apache/shenyu/common/dto/BaseData.java', + 'shenyu-common/src/main/java/org/apache/shenyu/common/dto/ConditionData.java', + 'shenyu-common/src/main/java/org/apache/shenyu/common/dto/PluginData.java', + 'shenyu-common/src/main/java/org/apache/shenyu/common/dto/RuleData.java', + 'shenyu-common/src/main/java/org/apache/shenyu/common/dto/SelectorData.java', + 'shenyu-plugin/shenyu-plugin-base/src/main/java/org/apache/shenyu/plugin/base/cache/BaseDataCache.java', + 'shenyu-plugin/shenyu-plugin-base/src/main/java/org/apache/shenyu/plugin/base/cache/MatchDataCache.java', + 'shenyu-plugin/shenyu-plugin-base/src/main/java/org/apache/shenyu/plugin/base/AbstractShenyuPlugin.java', + 'shenyu-plugin/shenyu-plugin-proxy/shenyu-plugin-divide/src/main/java/org/apache/shenyu/plugin/divide/DividePlugin.java' +) +# Do not silently benchmark stale target/classes. Build prerequisites separately, never here. +foreach ($relative in ($sourcePaths + 'shenyu-common/src/main/java/org/apache/shenyu/common/dto/DtoSnapshots.java')) { + $source = Join-Path $workspace $relative + $compiled = Join-Path $workspace ($relative.Replace('/src/main/java/', '/target/classes/').Replace('.java', '.class')) + if (!(Test-Path -LiteralPath $compiled) -or (Get-Item $source).LastWriteTimeUtc -gt (Get-Item $compiled).LastWriteTimeUtc) { + throw "Missing/stale changed class: $compiled" + } +} +$run = Join-Path $module ('target/config-views-' + (Get-Date -Format 'yyyyMMdd-HHmmss') + '-' + [guid]::NewGuid().ToString('N').Substring(0, 8)) +$classes = Join-Path $run 'classes' +$baselineClasses = Join-Path $run 'baseline-classes' +$baselineSource = Join-Path $run 'baseline-source' +$argumentsDirectory = Join-Path $env:TEMP ('shenyu-config-views-' + [guid]::NewGuid().ToString('N')) +New-Item -ItemType Directory -Path $classes,$baselineClasses,$baselineSource,$argumentsDirectory | Out-Null +$utf8 = [Text.UTF8Encoding]::new($false) +$processes = [Collections.Generic.List[Diagnostics.Process]]::new() +$logback = Join-Path $run 'logback.xml' +[IO.File]::WriteAllText($logback, '', $utf8) +function Stop-OwnedProcess([Diagnostics.Process]$Process) { + if (!$Process.HasExited) { + $Process.Kill() + if (!$Process.WaitForExit(5000)) { throw "Could not stop owned process $($Process.Id)" } + } +} +function Start-Tool([string]$Executable, [string]$Name, [string[]]$ToolArgs) { + $argumentFile = Join-Path $argumentsDirectory ($Name + '.args') + $lines = @($ToolArgs | ForEach-Object { '"' + $_.Replace('\', '/').Replace('"', '\"') + '"' }) + [IO.File]::WriteAllLines($argumentFile, $lines, $utf8) + $process = Start-Process -FilePath $Executable -ArgumentList "@`"$argumentFile`"" -WindowStyle Hidden -PassThru ` + -RedirectStandardOutput (Join-Path $run ($Name + '.stdout.log')) -RedirectStandardError (Join-Path $run ($Name + '.stderr.log')) + $processes.Add($process) + return $process +} +function Wait-Tool([Diagnostics.Process]$Process, [string]$Name) { + $null = $Process.Handle + if (!$Process.WaitForExit($TimeoutSeconds * 1000)) { + Stop-OwnedProcess $Process + throw "$Name timed out; inspect $run" + } + # Refresh the process handle before reading its exit status on Windows PowerShell 5.1. + $Process.Refresh() + if ($Process.ExitCode -ne 0) { throw "$Name failed; inspect $run" } +} +function Start-Java([string]$Name, [string]$ClassPath, [string[]]$ModeArgs, [bool]$Record = $false) { + $options = @('-Xms512m', '-Xmx512m', '-XX:ActiveProcessorCount=8', "-Dlogback.configurationFile=$logback") + if ($Record) { $options += "-XX:StartFlightRecording=filename=$argumentsDirectory/$Name.jfr,settings=profile,dumponexit=true" } + return Start-Tool $java $Name ($options + @('-cp', $ClassPath, 'org.apache.shenyu.benchmark.DivideGatewayBenchmark') + $ModeArgs) +} +function Wait-Ready([string]$Path, [Diagnostics.Process]$Process) { + $deadline = [DateTime]::UtcNow.AddSeconds([Math]::Min(60, $TimeoutSeconds)) + while (!(Test-Path -LiteralPath $Path)) { + if ($Process.HasExited) { throw "Process exited before readiness; inspect $run" } + if ([DateTime]::UtcNow -gt $deadline) { throw "Readiness timed out: $Path" } + Start-Sleep -Milliseconds 100 + } +} +try { + # Export ONLY the nine baseline classes. DtoSnapshots did not exist at the baseline. + $sources = @() + foreach ($relative in $sourcePaths) { + $name = [IO.Path]::GetFileName($relative) + $export = Start-Process -FilePath 'git' -ArgumentList @('-C', "`"$workspace`"", 'show', "${baseline}:$relative") ` + -WindowStyle Hidden -PassThru -RedirectStandardOutput (Join-Path $baselineSource $name) ` + -RedirectStandardError (Join-Path $run ($name + '.git.stderr.log')) + $processes.Add($export) + Wait-Tool $export "git show $relative" + $sources += Join-Path $baselineSource $name + } + $compile = Start-Tool $javac 'compile-baseline' (@('--release', '17', '-encoding', 'UTF-8', '-cp', $classpath, '-d', $baselineClasses) + $sources) + Wait-Tool $compile 'Baseline compilation' + # Compile the common harness against baseline APIs: no accidental linkage to readOnly/DtoSnapshots. + $compile = Start-Tool $javac 'compile-benchmark' @('--release', '17', '-encoding', 'UTF-8', '-cp', "$baselineClasses;$classpath", '-d', $classes, + (Join-Path $PSScriptRoot 'DivideGatewayBenchmark.java')) + Wait-Tool $compile 'Benchmark compilation' + [IO.File]::WriteAllText((Join-Path $run 'configuration.json'), (@{ + baseline=$baseline; requests=$Requests; offeredRates=$Rates; repeats=$Repeats; conditionsPerEntry=$Conditions; + burst=$Burst; profile=$Profile.IsPresent; heapMiB=512; activeProcessors=8; + dependencyClasspathSHA256=(Get-FileHash $dependenciesFile -Algorithm SHA256).Hash + } | ConvertTo-Json), $utf8) + if ($CompileOnly) { Write-Output "COMPILED=$run (no benchmark processes started)"; return } + $fixtureClasspath = "$classes;$classpath" + $upstreamFile = Join-Path $run 'upstreams.json' + $upstream = Start-Java 'upstream' $fixtureClasspath @('upstream', $upstreamFile) + Wait-Ready $upstreamFile $upstream + $rows = [Collections.Generic.List[object]]::new() + foreach ($rate in $Rates) { + foreach ($size in @(1,128)) { + foreach ($state in @('matched','no-match','cache-hit')) { + foreach ($updates in @(0,$Burst)) { + for ($repeat = 0; $repeat -lt $Repeats; $repeat++) { + $variants = if ($repeat % 2 -eq 0) { @('baseline','change') } else { @('change','baseline') } + foreach ($variant in $variants) { + $name = "$variant-$size-$state-b$updates-r$rate-$repeat" + $ready = Join-Path $run ($name + '.port') + $variantClasspath = if ($variant -eq 'baseline') { "$baselineClasses;$fixtureClasspath" } else { $fixtureClasspath } + # Fresh, sequential gateway JVMs avoid idle sibling interference and accumulated retained state. + $gateway = Start-Java $name $variantClasspath @('gateway', $upstreamFile, $ready, 'config-views') $Profile.IsPresent + try { + Wait-Ready $ready $gateway + $port = (Get-Content -Raw $ready).Trim() + $setup = Invoke-RestMethod "http://127.0.0.1:$port/_bench/config-view?size=$size&conditions=$Conditions&state=$state" ` + -TimeoutSec $TimeoutSeconds + [IO.File]::WriteAllText((Join-Path $run ($name + '.setup.json')), ($setup | ConvertTo-Json -Depth 5), $utf8) + $resultPath = Join-Path $run ($name + '.json') + $load = Start-Java ($name + '-load') $fixtureClasspath @('load-config', $port, "$Requests", "$rate", $resultPath, $state, "$size", "$updates") + Wait-Tool $load $name + $data = Get-Content -Raw $resultPath | ConvertFrom-Json + if ($data.successes -ne $Requests -or $data.errors -ne 0) { throw "Unexpected HTTP responses: $name" } + if (!$data.retained_before.gc_observed -or !$data.retained_after.gc_observed) { throw "Explicit GC was not observed: $name" } + if ($updates -gt 0 -and !$data.update.firstRequestVisible) { throw "Publication visibility failed: $name" } + $rows.Add([PSCustomObject]@{ + variant=$variant; selectors=$size; rules_per_selector=$size; conditions=$Conditions; state=$state; updates=$updates; repeat=$repeat + offered_rate=$rate; requests=$data.requests; expected_responses=$data.successes; errors=$data.errors + observed_rate=[Math]::Round($data.requests * 1e9 / $data.elapsed_ns,2); upstream_successes=$data.upstream_successes + allocated_bytes_per_request=[Math]::Round($data.allocated_bytes / $data.requests,2); cpu_ns_per_request=[Math]::Round($data.cpu_ns / $data.requests,2) + p95_ms=$data.p95_ns / 1e6; p99_ms=$data.p99_ns / 1e6; scheduled_p95_ms=$data.scheduled_p95_ns / 1e6; scheduled_p99_ms=$data.scheduled_p99_ns / 1e6 + gc_count=$data.gc_count; gc_ms=$data.gc_ms; sampled_peak_heap_bytes=$data.sampled_peak_heap_bytes + retained_before_bytes=$data.retained_before.heap_bytes; retained_after_bytes=$data.retained_after.heap_bytes + update_ns=$data.update.updateNs; max_update_ns=$data.update.maxUpdateNs; first_visible_ns=$data.update.firstVisibleNs + setup_ns=$setup.setup.elapsed_ns; setup_allocated_bytes=$setup.setup.allocated_bytes; setup_cpu_ns=$setup.setup.cpu_ns + setup_gc_count=$setup.setup.gc_count; setup_gc_ms=$setup.setup.gc_ms + setup_heap_before_bytes=$setup.setup.heap_before_bytes; setup_heap_after_bytes=$setup.setup.heap_after_bytes + }) + $rows | Export-Csv -NoTypeInformation -Encoding utf8 (Join-Path $run 'results.csv') + Write-Output "$name completed (observed rate, NOT capacity)" + if ($Profile) { + # jcmd does not accept Java @argfiles. Bound it like every other child process. + $recording = Join-Path $argumentsDirectory ($name + '.jfr') + $dump = Start-Process -FilePath (Join-Path $env:JAVA_HOME 'bin/jcmd.exe') ` + -ArgumentList @($gateway.Id, 'JFR.dump', "`"filename=$recording`"") -WindowStyle Hidden -PassThru ` + -RedirectStandardOutput (Join-Path $run ($name + '.jfr.log')) -RedirectStandardError (Join-Path $run ($name + '.jfr.stderr.log')) + $processes.Add($dump) + Wait-Tool $dump 'JFR dump' + Copy-Item -LiteralPath $recording -Destination (Join-Path $run ($name + '.jfr')) + } + } finally { Stop-OwnedProcess $gateway } + } + } + } + } + } + } + Write-Output "RESULTS=$run" +} finally { + foreach ($process in $processes) { + try { Stop-OwnedProcess $process } catch { Write-Warning $_ } + $process.Dispose() + } + Remove-Item -LiteralPath $argumentsDirectory -Recurse -Force +} diff --git a/docs/read-only-base-configuration.md b/docs/read-only-base-configuration.md new file mode 100644 index 000000000000..59231ceebb29 --- /dev/null +++ b/docs/read-only-base-configuration.md @@ -0,0 +1,154 @@ + + +# Read-only base configuration: first adoption slice + +This implements the **BaseDataCache matching-configuration slice** of +[issue 8223](https://github.com/apache/shenyu/issues/8223). It is not full +immutability for all gateway caches, transactional configuration activation, or +a security sandbox for untrusted Java code. + +## Contract and ownership + +Synchronization owns mutable `PluginData`, `SelectorData`, `RuleData` and +`ConditionData` objects. Normal `BaseDataCache` publication methods retain the +legacy mutable references and separately publish frozen copies. Copies are made +on update, not during ordinary configuration lookup. The copy includes current +and previous condition lists and their elements. Strings and boxed scalar values +are immutable; untouched published entries are reused across bucket changes. + +`BaseDataCache.getInstance().readOnly()` is the adopted read contract. Lookup +returns the already-published object/list or null; it does not deep-copy, +serialize, recompute fingerprints or lock readers. Map getters return prebuilt +unmodifiable views: entries, values, lists and condition elements cannot be used +to write back into publication state. They are **views of one backing-map +generation**, not a pinned transaction over plugins, selectors and rules. A held +DTO or bucket remains unchanged; map membership can change on incremental writes. +Batch map replacement leaves old views pointing at their old generation. + +`DtoSnapshots.freeze(...)` creates the same standard concrete DTO class, not a +subclass with different equality. Frozen and mutable equal-valued objects retain +symmetric equals/hashCode behavior. Every supported setter, including base and +fluent RuleData overrides, rejects changes on a frozen snapshot. `frozen()` is a +non-bean accessor; the internal transient flag is not a wire configuration field. +Gson/Jackson round trips produce ordinary mutable build DTOs. Unknown subclasses +are not silently projected or treated as immutable: snapshot creation rejects +unsupported concrete classes. Extensions publishing custom DTO subclasses must +explicitly map their configuration to the standard DTO contract. + +Writers serialize the paired legacy/published updates so concurrent publication +calls cannot leave the two channels in opposite update orders. This is a local +writer-only monitor, not a request lock, distributed revision protocol or atomic +multi-object activation. One publication method returning establishes its own +updates; it does not pin a whole request to one configuration revision. + +## Adoption and legacy compatibility + +`AbstractShenyuPlugin.useReadOnlyConfiguration()` defaults to false. Existing +plugins and external subclasses retain the existing getter signatures, mutable +build DTOs and `doExecute(exchange, chain, selector, rule)` signature. A plugin +opts in by overriding that method to return true. Its enabled check, selector and +rule matching, match-cache values and `doExecute` parameters then use the frozen +base configuration. It must treat those shared parameters as read-only and keep +request-specific overrides in request-owned variables or objects. + +Divide is the first built-in adopter. Its `continued=false` default rule remains +a newly created request-owned object, as before; modifying that object does not +mutate any published rule. Negative match sentinels are frozen and reused. Derived +matches use a separate read-only channel: a mutable value submitted to that +channel is rejected, never copied on a cache-hit path. Existing subscriber +invalidation methods invalidate both channels, including dangling IDs and +negative entries. The existing matching algorithm, ordering, specificity and TTL +remain in use. + +Legacy `getPluginMap()`, `getSelectorMap()`, `getRuleMap()` and match-cache map +getters still expose the legacy storage. **Writing these maps or mutating their +DTOs does not update the frozen channel.** This isolation is intentional. Use the +normal publication and subscriber APIs for configuration changes; do not mutate +a live getter and expect every plugin to observe it. The gateway still receives +configuration through existing synchronization; it does not read the Admin DB. + +### Consumer inventory for this slice + +| Consumer / storage | Behavior | +| --- | --- | +| CommonPluginDataSubscriber cache/refresh/remove/clean operations | Publish or remove both base channels; handler callbacks retain their original mutable DTOs | +| AbstractShenyuPlugin legacy subclasses | Existing mutable base and match-cache path | +| DividePlugin base matching | Explicitly adopts frozen Plugin/Selector/Rule/Condition values | +| LocalPluginController / Admin / Kubernetes DTO builders | Mutable build DTOs; publish through existing APIs | +| MatchDataCache legacy map getters | Legacy only; cannot inject a mutable object into adopted hits | +| MetaDataCache and metadata consumers | **Not migrated; remain legacy mutable** | +| CommonHandleCache, including DivideRuleHandle and nested canary/sticky configuration | **Not migrated; remain legacy mutable** | +| UpstreamCacheManager health, counters, inflight, lag and circuit-breaker state | Intentionally live and mutable; not frozen | + +Accordingly, this PR does **not** claim that every effective Divide setting or +all gateway configuration is immutable. In particular, a trusted plugin holding +a parsed handle or metadata reference can still mutate that separate legacy +state. The migration boundary is explicit rather than hidden behind an +unmodifiable outer Map. + +## Consistency limits and related work + +[Issue 8060](https://github.com/apache/shenyu/issues/8060) owns multi-object +transactional publication. [Issue 8061](https://github.com/apache/shenyu/issues/8061) +owns resource leases. This slice adds neither a revision manifest nor per-request +leases, and retains no history indexed by requests. Old DTOs remain alive only +while a reader or an existing bounded derived cache retains them. + +Existing match-cache invalidation races and selector-scoped rule-cache keys are +separate work in [PR 7681](https://github.com/apache/shenyu/pull/7681) and +[PR 8103](https://github.com/apache/shenyu/pull/8103). Frozen data alone does not +fix stale-match publication across an in-flight update; no such claim is made. +[PR 8291](https://github.com/apache/shenyu/pull/8291) owns matching observation. +The new channel must continue to receive those shared invalidations when these +changes integrate; it is not an alternative matching engine. + +## Cost and acceptance status + +This compatibility period deliberately retains both the mutable and frozen +versions. Update cost includes copying the changed DTO and nested conditions, +maintaining the second index, and sorting the affected bucket; batch refreshes +retain the existing once-per-bucket sorting approach. Unchanged frozen elements +are reused, but full-map batch replacement still allocates a new index as the +legacy algorithm already does. A retired view may be retained by application +code; there is no automatic history or new request lease. The derived cache has +the existing configurable capacity/TTL independently for each channel. + +Ordinary reads must remain reference lookups and bounded existing matching, with +no configuration deep copy, whole-map reconstruction, serialization, remote call +or global read lock. The extra index and publication allocation are **not free**; +measurement must report update allocations/convergence and peak/retained memory +as well as steady-state forwarding. + +The companion configuration mode in `docs/benchmarks/divide-gateway` reuses the +real HTTP proxy harness and separate gateway/load/upstream JVMs. Compare the +fixed base `548bec1f9` and this change using repeated, alternating small/large +matched, no-match and match-cache-hit cases plus bounded update bursts. Record +throughput, p95/p99, CPU, allocation per operation, convergence and peak/retained +memory. An offered-rate run alone is not proof of equal saturation throughput; +repeat near saturation and report run variability rather than selecting one good +sample. + +**No before/after performance acceptance result is claimed here.** On the local +Windows/JDK 17.0.16 host, even a standalone `Selector.open()` probe fails with +`IOException: Unable to establish loopback connection`, caused by +`SocketException: Invalid argument: connect` in `UnixDomainSockets`. Both default +and WindowsSelectorProvider probes fail before any gateway code starts. +Until the required forwarding measurements are produced on a working host and +show no measurable ordinary-path regression, this change must remain a **Draft** +for design/compatibility feedback. Compilation, unit tests and an in-memory +forwarding test are not substitutes for that merge gate. diff --git a/shenyu-common/src/main/java/org/apache/shenyu/common/dto/BaseData.java b/shenyu-common/src/main/java/org/apache/shenyu/common/dto/BaseData.java index 65fc3a0e3660..039de581eaf8 100644 --- a/shenyu-common/src/main/java/org/apache/shenyu/common/dto/BaseData.java +++ b/shenyu-common/src/main/java/org/apache/shenyu/common/dto/BaseData.java @@ -17,6 +17,8 @@ package org.apache.shenyu.common.dto; +import com.fasterxml.jackson.annotation.JsonIgnore; + /** * Base class for common data transfer objects. * Contains common fields shared across SelectorData, RuleData, and PluginData. @@ -49,6 +51,53 @@ public class BaseData { */ private String namespaceId; + @JsonIgnore + private transient boolean frozen; + + /** + * No args constructor. + */ + public BaseData() { + } + + /** + * Copy the base values without copying the frozen state. + * + * @param source source data + */ + BaseData(final BaseData source) { + this.id = source.id; + this.name = source.name; + this.enabled = source.enabled; + this.sort = source.sort; + this.namespaceId = source.namespaceId; + } + + /** + * Whether this data is a read-only snapshot. + * + * @return whether mutations are rejected + */ + public final boolean frozen() { + return frozen; + } + + /** + * Seal a fully initialized snapshot for publication. + */ + final void markFrozen() { + frozen = true; + } + + /** + * Reject mutations of a published snapshot. + */ + final void checkMutable() { + if (frozen) { + throw new UnsupportedOperationException("DTO snapshot is read-only"); + } + } + /** * get id. * @@ -65,6 +114,7 @@ public String getId() { * @return this */ public BaseData setId(final String id) { + checkMutable(); this.id = id; return this; } @@ -85,6 +135,7 @@ public String getName() { * @return this */ public BaseData setName(final String name) { + checkMutable(); this.name = name; return this; } @@ -105,6 +156,7 @@ public Boolean getEnabled() { * @return this */ public BaseData setEnabled(final Boolean enabled) { + checkMutable(); this.enabled = enabled; return this; } @@ -125,6 +177,7 @@ public Integer getSort() { * @return this */ public BaseData setSort(final Integer sort) { + checkMutable(); this.sort = sort; return this; } @@ -145,6 +198,7 @@ public String getNamespaceId() { * @return this */ public BaseData setNamespaceId(final String namespaceId) { + checkMutable(); this.namespaceId = namespaceId; return this; } diff --git a/shenyu-common/src/main/java/org/apache/shenyu/common/dto/ConditionData.java b/shenyu-common/src/main/java/org/apache/shenyu/common/dto/ConditionData.java index 7c47f02fc6d0..dcbf0f900234 100644 --- a/shenyu-common/src/main/java/org/apache/shenyu/common/dto/ConditionData.java +++ b/shenyu-common/src/main/java/org/apache/shenyu/common/dto/ConditionData.java @@ -17,6 +17,8 @@ package org.apache.shenyu.common.dto; +import com.fasterxml.jackson.annotation.JsonIgnore; + import java.util.Objects; /** @@ -46,6 +48,52 @@ public class ConditionData { */ private String paramValue; + @JsonIgnore + private transient boolean frozen; + + /** + * No args constructor. + */ + public ConditionData() { + } + + /** + * Copy the values without copying the frozen state. + * + * @param source source data + */ + ConditionData(final ConditionData source) { + this.paramType = source.paramType; + this.operator = source.operator; + this.paramName = source.paramName; + this.paramValue = source.paramValue; + } + + /** + * Whether this data is a read-only snapshot. + * + * @return whether mutations are rejected + */ + public final boolean frozen() { + return frozen; + } + + /** + * Seal a fully initialized snapshot for publication. + */ + final void markFrozen() { + frozen = true; + } + + /** + * Reject mutations of a published snapshot. + */ + final void checkMutable() { + if (frozen) { + throw new UnsupportedOperationException("DTO snapshot is read-only"); + } + } + /** * get paramType. * @@ -61,6 +109,7 @@ public String getParamType() { * @param paramType paramType */ public void setParamType(final String paramType) { + checkMutable(); this.paramType = paramType; } @@ -79,6 +128,7 @@ public String getOperator() { * @param operator operator */ public void setOperator(final String operator) { + checkMutable(); this.operator = operator; } @@ -97,6 +147,7 @@ public String getParamName() { * @param paramName paramName */ public void setParamName(final String paramName) { + checkMutable(); this.paramName = paramName; } @@ -115,6 +166,7 @@ public String getParamValue() { * @param paramValue paramValue */ public void setParamValue(final String paramValue) { + checkMutable(); this.paramValue = paramValue; } diff --git a/shenyu-common/src/main/java/org/apache/shenyu/common/dto/DtoSnapshots.java b/shenyu-common/src/main/java/org/apache/shenyu/common/dto/DtoSnapshots.java new file mode 100644 index 000000000000..871dacaef3b4 --- /dev/null +++ b/shenyu-common/src/main/java/org/apache/shenyu/common/dto/DtoSnapshots.java @@ -0,0 +1,136 @@ +/* + * 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.common.dto; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Objects; + +/** + * Creates read-only snapshots without changing the mutable source DTOs. + * Only the standard DTO classes are supported, preserving their value equality. + */ +public final class DtoSnapshots { + + private DtoSnapshots() { + } + + /** + * Take a read-only plugin snapshot, reusing an existing snapshot. + * + * @param source source data, or null + * @return a snapshot of the same concrete class, or null + * @throws IllegalArgumentException if the source is a subclass + */ + public static PluginData freeze(final PluginData source) { + if (Objects.isNull(source)) { + return null; + } + requireStandardClass(source, PluginData.class); + if (source.frozen()) { + return source; + } + PluginData snapshot = new PluginData(source); + snapshot.markFrozen(); + return snapshot; + } + + /** + * Take a read-only selector snapshot, including current and previous conditions. + * + * @param source source data, or null + * @return a snapshot of the same concrete class, or null + * @throws IllegalArgumentException if the source or any condition is a subclass + */ + public static SelectorData freeze(final SelectorData source) { + if (Objects.isNull(source)) { + return null; + } + requireStandardClass(source, SelectorData.class); + if (source.frozen()) { + return source; + } + SelectorData snapshot = new SelectorData(source); + snapshot.markFrozen(); + return snapshot; + } + + /** + * Take a read-only rule snapshot, including current and previous conditions. + * + * @param source source data, or null + * @return a snapshot of the same concrete class, or null + * @throws IllegalArgumentException if the source or any condition is a subclass + */ + public static RuleData freeze(final RuleData source) { + if (Objects.isNull(source)) { + return null; + } + requireStandardClass(source, RuleData.class); + if (source.frozen()) { + return source; + } + RuleData snapshot = new RuleData(source); + snapshot.markFrozen(); + return snapshot; + } + + /** + * Take a read-only condition snapshot, reusing an existing snapshot. + * + * @param source source data, or null + * @return a snapshot of the same concrete class, or null + * @throws IllegalArgumentException if the source is a subclass + */ + public static ConditionData freeze(final ConditionData source) { + if (Objects.isNull(source)) { + return null; + } + requireStandardClass(source, ConditionData.class); + if (source.frozen()) { + return source; + } + ConditionData snapshot = new ConditionData(source); + snapshot.markFrozen(); + return snapshot; + } + + /** + * Copy a condition list, retaining null lists and null elements. + * + * @param source source conditions + * @return read-only condition snapshots, or null + */ + static List freezeConditions(final List source) { + if (Objects.isNull(source)) { + return null; + } + List snapshots = new ArrayList<>(source.size()); + for (ConditionData condition : source) { + snapshots.add(freeze(condition)); + } + return Collections.unmodifiableList(snapshots); + } + + private static void requireStandardClass(final Object source, final Class expected) { + if (source.getClass() != expected) { + throw new IllegalArgumentException("Unsupported DTO snapshot class: " + source.getClass().getName()); + } + } +} diff --git a/shenyu-common/src/main/java/org/apache/shenyu/common/dto/PluginData.java b/shenyu-common/src/main/java/org/apache/shenyu/common/dto/PluginData.java index a93e39e3f6b9..b83758b2bf16 100644 --- a/shenyu-common/src/main/java/org/apache/shenyu/common/dto/PluginData.java +++ b/shenyu-common/src/main/java/org/apache/shenyu/common/dto/PluginData.java @@ -98,6 +98,18 @@ public PluginData(final String id, final String name, final String config, final this.setNamespaceId(namespaceId); } + /** + * Copy the values without changing the source. + * + * @param source source data + */ + PluginData(final PluginData source) { + super(source); + this.config = source.config; + this.role = source.role; + this.pluginJar = source.pluginJar; + } + /** * class builder. * @@ -122,6 +134,7 @@ public String getConfig() { * @param config config */ public void setConfig(final String config) { + checkMutable(); this.config = config; } @@ -140,6 +153,7 @@ public String getRole() { * @param role role */ public void setRole(final String role) { + checkMutable(); this.role = role; } @@ -158,6 +172,7 @@ public String getPluginJar() { * @param pluginJar pluginJar */ public void setPluginJar(final String pluginJar) { + checkMutable(); this.pluginJar = pluginJar; } diff --git a/shenyu-common/src/main/java/org/apache/shenyu/common/dto/RuleData.java b/shenyu-common/src/main/java/org/apache/shenyu/common/dto/RuleData.java index a97566bc73dd..e721c19f6c74 100644 --- a/shenyu-common/src/main/java/org/apache/shenyu/common/dto/RuleData.java +++ b/shenyu-common/src/main/java/org/apache/shenyu/common/dto/RuleData.java @@ -82,6 +82,23 @@ private RuleData(final Builder builder) { this.setNamespaceId(builder.namespaceId); } + /** + * Copy the values and take snapshots of both condition lists. + * + * @param source source data + */ + RuleData(final RuleData source) { + super(source); + this.pluginName = source.pluginName; + this.selectorId = source.selectorId; + this.matchMode = source.matchMode; + this.logged = source.logged; + this.handle = source.handle; + this.conditionDataList = DtoSnapshots.freezeConditions(source.conditionDataList); + this.beforeConditionDataList = DtoSnapshots.freezeConditions(source.beforeConditionDataList); + this.matchRestful = source.matchRestful; + } + /** * class builder. * @@ -107,6 +124,7 @@ public String getPluginName() { * @return this */ public RuleData setPluginName(final String pluginName) { + checkMutable(); this.pluginName = pluginName; return this; } @@ -182,6 +200,7 @@ public String getSelectorId() { * @return this */ public RuleData setSelectorId(final String selectorId) { + checkMutable(); this.selectorId = selectorId; return this; } @@ -202,6 +221,7 @@ public Integer getMatchMode() { * @return this */ public RuleData setMatchMode(final Integer matchMode) { + checkMutable(); this.matchMode = matchMode; return this; } @@ -222,6 +242,7 @@ public Boolean getLogged() { * @return this */ public RuleData setLogged(final Boolean logged) { + checkMutable(); this.logged = logged; return this; } @@ -242,6 +263,7 @@ public String getHandle() { * @return this */ public RuleData setHandle(final String handle) { + checkMutable(); this.handle = handle; return this; } @@ -262,6 +284,7 @@ public List getConditionDataList() { * @return this */ public RuleData setConditionDataList(final List conditionDataList) { + checkMutable(); this.conditionDataList = conditionDataList; return this; } @@ -281,6 +304,7 @@ public List getBeforeConditionDataList() { * @param beforeConditionDataList beforeConditionDataList */ public void setBeforeConditionDataList(final List beforeConditionDataList) { + checkMutable(); this.beforeConditionDataList = beforeConditionDataList; } @@ -299,6 +323,7 @@ public Boolean getMatchRestful() { * @param matchRestful matchRestful */ public void setMatchRestful(final Boolean matchRestful) { + checkMutable(); this.matchRestful = matchRestful; } diff --git a/shenyu-common/src/main/java/org/apache/shenyu/common/dto/SelectorData.java b/shenyu-common/src/main/java/org/apache/shenyu/common/dto/SelectorData.java index c6aec37add82..eebbbe0e21db 100644 --- a/shenyu-common/src/main/java/org/apache/shenyu/common/dto/SelectorData.java +++ b/shenyu-common/src/main/java/org/apache/shenyu/common/dto/SelectorData.java @@ -88,6 +88,25 @@ private SelectorData(final Builder builder) { this.setNamespaceId(builder.namespaceId); } + /** + * Copy the values and take snapshots of both condition lists. + * + * @param source source data + */ + SelectorData(final SelectorData source) { + super(source); + this.pluginId = source.pluginId; + this.pluginName = source.pluginName; + this.matchMode = source.matchMode; + this.type = source.type; + this.logged = source.logged; + this.continued = source.continued; + this.handle = source.handle; + this.conditionList = DtoSnapshots.freezeConditions(source.conditionList); + this.beforeConditionList = DtoSnapshots.freezeConditions(source.beforeConditionList); + this.matchRestful = source.matchRestful; + } + /** * class builder. * @@ -112,6 +131,7 @@ public String getPluginId() { * @param pluginId pluginId */ public void setPluginId(final String pluginId) { + checkMutable(); this.pluginId = pluginId; } @@ -130,6 +150,7 @@ public String getPluginName() { * @param pluginName pluginName */ public void setPluginName(final String pluginName) { + checkMutable(); this.pluginName = pluginName; } @@ -148,6 +169,7 @@ public Integer getMatchMode() { * @param matchMode matchMode */ public void setMatchMode(final Integer matchMode) { + checkMutable(); this.matchMode = matchMode; } @@ -166,6 +188,7 @@ public Integer getType() { * @param type type */ public void setType(final Integer type) { + checkMutable(); this.type = type; } @@ -184,6 +207,7 @@ public Boolean getLogged() { * @param logged logged */ public void setLogged(final Boolean logged) { + checkMutable(); this.logged = logged; } @@ -205,6 +229,7 @@ public Boolean getContinued() { * @param continued continued */ public void setContinued(final Boolean continued) { + checkMutable(); this.continued = continued; } @@ -223,6 +248,7 @@ public String getHandle() { * @param handle handle */ public void setHandle(final String handle) { + checkMutable(); this.handle = handle; } @@ -241,6 +267,7 @@ public List getConditionList() { * @param conditionList conditionList */ public void setConditionList(final List conditionList) { + checkMutable(); this.conditionList = conditionList; } @@ -259,6 +286,7 @@ public Boolean getMatchRestful() { * @param matchRestful matchRestful */ public void setMatchRestful(final Boolean matchRestful) { + checkMutable(); this.matchRestful = matchRestful; } @@ -277,6 +305,7 @@ public List getBeforeConditionList() { * @param beforeConditionList before condition list */ public void setBeforeConditionList(final List beforeConditionList) { + checkMutable(); this.beforeConditionList = beforeConditionList; } diff --git a/shenyu-common/src/test/java/org/apache/shenyu/common/dto/DtoSnapshotsTest.java b/shenyu-common/src/test/java/org/apache/shenyu/common/dto/DtoSnapshotsTest.java new file mode 100644 index 000000000000..acd8e1f8bcb0 --- /dev/null +++ b/shenyu-common/src/test/java/org/apache/shenyu/common/dto/DtoSnapshotsTest.java @@ -0,0 +1,429 @@ +/* + * 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.common.dto; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import org.apache.shenyu.common.utils.GsonUtils; +import org.junit.jupiter.api.Test; + +import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Iterator; +import java.util.List; +import java.util.Objects; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Tests for read-only DTO snapshots and the mutable wire format. + */ +class DtoSnapshotsTest { + + @Test + void testNullSourcesAndReuse() throws ReflectiveOperationException { + assertNull(DtoSnapshots.freeze((PluginData) null)); + assertNull(DtoSnapshots.freeze((SelectorData) null)); + assertNull(DtoSnapshots.freeze((RuleData) null)); + assertNull(DtoSnapshots.freeze((ConditionData) null)); + for (Object source : sources()) { + Object snapshot = freeze(source); + assertNotSame(source, snapshot); + assertFalse(frozen(source)); + assertTrue(frozen(snapshot)); + assertSame(snapshot, freeze(snapshot)); + } + } + + @Test + void testCopiesEveryFieldAndPreservesEquality() throws ReflectiveOperationException { + for (Object source : sources()) { + Object snapshot = freeze(source); + assertNonDefaultFields(source); + assertCopiedFields(source, snapshot); + assertEquals(source, snapshot); + assertEquals(snapshot, source); + assertEquals(source.hashCode(), snapshot.hashCode()); + } + } + + @Test + void testEveryPublicSetterRejectsWrites() throws ReflectiveOperationException { + for (Object source : sources()) { + Object snapshot = freeze(source); + assertAllSettersReject(snapshot); + assertCopiedFields(source, snapshot); + assertEquals(source.hashCode(), snapshot.hashCode()); + } + } + + @Test + void testSourceMutationsDoNotChangeSnapshot() throws ReflectiveOperationException { + for (Object source : sources()) { + Object snapshot = freeze(source); + Object expected = freeze(source); + mutateConditions(source); + invokeSetters(source, "changed"); + assertCopiedFields(expected, snapshot); + assertEquals(expected, snapshot); + assertEquals(expected.hashCode(), snapshot.hashCode()); + assertNotEquals(source, snapshot); + assertFalse(frozen(source)); + } + } + + @Test + void testBothConditionListsAndElementsAreReadOnly() throws ReflectiveOperationException { + for (Object source : sources()) { + Object snapshot = freeze(source); + for (List conditions : conditionLists(snapshot)) { + assertReadOnlyList(conditions); + assertAllSettersReject(conditions.get(0)); + assertNull(conditions.get(1)); + } + } + } + + @Test + void testNullAndEmptyConditionLists() { + SelectorData selector = new SelectorData(); + RuleData rule = new RuleData(); + assertNull(DtoSnapshots.freeze(selector).getConditionList()); + assertNull(DtoSnapshots.freeze(selector).getBeforeConditionList()); + assertNull(DtoSnapshots.freeze(rule).getConditionDataList()); + assertNull(DtoSnapshots.freeze(rule).getBeforeConditionDataList()); + selector.setConditionList(new ArrayList<>()); + selector.setBeforeConditionList(new ArrayList<>()); + rule.setConditionDataList(new ArrayList<>()); + rule.setBeforeConditionDataList(new ArrayList<>()); + for (Object snapshot : Arrays.asList(DtoSnapshots.freeze(selector), DtoSnapshots.freeze(rule))) { + for (List conditions : conditionLists(snapshot)) { + assertTrue(conditions.isEmpty()); + assertThrows(UnsupportedOperationException.class, () -> conditions.add(new ConditionData())); + } + } + } + + @Test + void testNullableContinuedRetainsRawValue() throws ReflectiveOperationException { + for (Boolean continued : Arrays.asList(null, Boolean.FALSE, Boolean.TRUE)) { + SelectorData source = SelectorData.builder().continued(continued).build(); + SelectorData snapshot = DtoSnapshots.freeze(source); + assertCopiedFields(source, snapshot); + assertEquals(source, snapshot); + assertEquals(snapshot, source); + assertEquals(source.hashCode(), snapshot.hashCode()); + assertEquals(source.getContinued(), snapshot.getContinued()); + assertEquals(GsonUtils.getInstance().toJson(source), GsonUtils.getInstance().toJson(snapshot)); + } + } + + @Test + void testBuildersAndBaseDataRemainMutable() throws ReflectiveOperationException { + List values = Arrays.asList(new BaseData(), PluginData.builder().build(), + SelectorData.builder().build(), RuleData.builder().build(), new ConditionData()); + for (Object value : values) { + assertFalse(frozen(value)); + invokeSetters(value, "builder"); + assertNonDefaultFields(value); + } + } + + @Test + void testRejectsUnknownSubclasses() { + assertThrows(IllegalArgumentException.class, () -> DtoSnapshots.freeze(new PluginData() { })); + assertThrows(IllegalArgumentException.class, () -> DtoSnapshots.freeze(new SelectorData() { })); + assertThrows(IllegalArgumentException.class, () -> DtoSnapshots.freeze(new RuleData() { })); + ConditionData unknown = new ConditionData() { }; + assertThrows(IllegalArgumentException.class, () -> DtoSnapshots.freeze(unknown)); + SelectorData selector = new SelectorData(); + RuleData rule = new RuleData(); + selector.setConditionList(Collections.singletonList(unknown)); + rule.setConditionDataList(Collections.singletonList(unknown)); + assertThrows(IllegalArgumentException.class, () -> DtoSnapshots.freeze(selector)); + assertThrows(IllegalArgumentException.class, () -> DtoSnapshots.freeze(rule)); + selector.setConditionList(null); + rule.setConditionDataList(null); + selector.setBeforeConditionList(Collections.singletonList(unknown)); + rule.setBeforeConditionDataList(Collections.singletonList(unknown)); + assertThrows(IllegalArgumentException.class, () -> DtoSnapshots.freeze(selector)); + assertThrows(IllegalArgumentException.class, () -> DtoSnapshots.freeze(rule)); + assertFalse(selector.frozen()); + assertFalse(rule.frozen()); + assertFalse(unknown.frozen()); + unknown.markFrozen(); + assertThrows(IllegalArgumentException.class, () -> DtoSnapshots.freeze(unknown)); + } + + @Test + void testFrozenConditionsCanBeReused() throws ReflectiveOperationException { + ConditionData condition = DtoSnapshots.freeze(condition("shared")); + SelectorData selector = SelectorData.builder().conditionList(Collections.singletonList(condition)) + .beforeConditionList(Collections.singletonList(condition)).build(); + RuleData rule = RuleData.builder().conditionDataList(Collections.singletonList(condition)) + .beforeConditionDataList(Collections.singletonList(condition)).build(); + for (Object snapshot : Arrays.asList(DtoSnapshots.freeze(selector), DtoSnapshots.freeze(rule))) { + for (List conditions : conditionLists(snapshot)) { + assertSame(condition, conditions.get(0)); + assertThrows(UnsupportedOperationException.class, () -> conditions.add(condition)); + } + } + } + + @Test + void testGsonAndJacksonRoundTripsAreMutableAndOmitFrozenState() throws Exception { + ObjectMapper mapper = new ObjectMapper(); + for (Object source : sources()) { + Object snapshot = freeze(source); + String gsonJson = GsonUtils.getInstance().toJson(snapshot); + String jacksonJson = mapper.writeValueAsString(snapshot); + assertEquals(mapper.readTree(GsonUtils.getInstance().toJson(source)), mapper.readTree(gsonJson)); + assertEquals(mapper.readTree(mapper.writeValueAsString(source)), mapper.readTree(jacksonJson)); + assertWireFields(source, mapper.readTree(gsonJson)); + assertWireFields(source, mapper.readTree(jacksonJson)); + assertMutableRoundTrip(snapshot, GsonUtils.getInstance().fromJson(gsonJson, source.getClass())); + assertMutableRoundTrip(snapshot, mapper.readValue(jacksonJson, source.getClass())); + } + } + + @Test + void testJsonCannotSetFrozenState() throws Exception { + // Even a permissive wire reader must not accept the internal snapshot state. + ObjectMapper mapper = new ObjectMapper().disable(com.fasterxml.jackson.databind.DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); + for (Object source : sources()) { + ObjectNode json = mapper.valueToTree(source); + injectFrozenState(json); + assertMutableRoundTrip(source, GsonUtils.getInstance().fromJson(json.toString(), source.getClass())); + assertMutableRoundTrip(source, mapper.readValue(json.toString(), source.getClass())); + } + assertFalse(GsonUtils.getInstance().fromJson("{\"frozen\":true}", BaseData.class).frozen()); + assertFalse(mapper.readValue("{\"frozen\":true}", BaseData.class).frozen()); + } + + private static List sources() throws ReflectiveOperationException { + List sources = Arrays.asList(new PluginData(), new SelectorData(), new RuleData(), new ConditionData()); + for (Object source : sources) { + invokeSetters(source, "source"); + } + return sources; + } + + private static Object freeze(final Object source) throws ReflectiveOperationException { + return DtoSnapshots.class.getMethod("freeze", source.getClass()).invoke(null, source); + } + + private static boolean frozen(final Object value) { + if (value instanceof BaseData) { + return ((BaseData) value).frozen(); + } + return ((ConditionData) value).frozen(); + } + + private static void invokeSetters(final Object value, final String prefix) throws ReflectiveOperationException { + for (Method method : value.getClass().getMethods()) { + if (method.getName().startsWith("set")) { + method.invoke(value, arguments(method, prefix)); + } + } + } + + private static Object[] arguments(final Method method, final String prefix) throws ReflectiveOperationException { + Class[] types = method.getParameterTypes(); + Object[] arguments = new Object[types.length]; + for (int i = 0; i < types.length; i++) { + String name = prefix + method.getName() + i; + if (types[i] == String.class) { + arguments[i] = name; + } else if (types[i] == Boolean.class || types[i] == boolean.class) { + arguments[i] = "changed".equals(prefix); + } else if (types[i] == Integer.class || types[i] == int.class) { + arguments[i] = "changed".equals(prefix) ? 73 : 31; + } else if (types[i] == List.class) { + arguments[i] = new ArrayList<>(Arrays.asList(condition(name), null)); + } else { + throw new IllegalArgumentException("Add a test value for " + method); + } + } + return arguments; + } + + private static ConditionData condition(final String prefix) throws ReflectiveOperationException { + ConditionData condition = new ConditionData(); + invokeSetters(condition, prefix); + return condition; + } + + private static void assertAllSettersReject(final Object snapshot) throws ReflectiveOperationException { + int setters = 0; + for (Method method : snapshot.getClass().getMethods()) { + if (method.getName().startsWith("set")) { + setters++; + Object[] arguments = arguments(method, "changed"); + InvocationTargetException exception = assertThrows(InvocationTargetException.class, + () -> method.invoke(snapshot, arguments), method.toString()); + assertTrue(exception.getCause() instanceof UnsupportedOperationException, method.toString()); + if (Arrays.stream(method.getParameterTypes()).noneMatch(Class::isPrimitive)) { + InvocationTargetException nullException = assertThrows(InvocationTargetException.class, + () -> method.invoke(snapshot, new Object[method.getParameterCount()]), method.toString()); + assertTrue(nullException.getCause() instanceof UnsupportedOperationException, method.toString()); + } + } + } + assertTrue(setters > 0); + } + + private static List valueFields(final Class type) { + List fields = new ArrayList<>(); + for (Class current = type; current != Object.class; current = current.getSuperclass()) { + for (Field field : current.getDeclaredFields()) { + if (!Modifier.isStatic(field.getModifiers()) && !Modifier.isTransient(field.getModifiers())) { + field.setAccessible(true); + fields.add(field); + } + } + } + return fields; + } + + private static void assertNonDefaultFields(final Object source) throws ReflectiveOperationException { + Object defaults = source.getClass().getConstructor().newInstance(); + for (Field field : valueFields(source.getClass())) { + assertNotNull(field.get(source), field.toString()); + assertNotEquals(field.get(defaults), field.get(source), field.toString()); + } + for (List conditions : conditionLists(source)) { + for (ConditionData condition : conditions) { + if (Objects.nonNull(condition)) { + assertNonDefaultFields(condition); + } + } + } + } + + private static void assertCopiedFields(final Object source, final Object snapshot) throws IllegalAccessException { + assertEquals(source.getClass(), snapshot.getClass()); + for (Field field : valueFields(source.getClass())) { + Object original = field.get(source); + Object copied = field.get(snapshot); + assertEquals(original, copied, field.toString()); + if (original instanceof List) { + assertNotSame(original, copied, field.toString()); + List originals = (List) original; + List copies = (List) copied; + for (int i = 0; i < originals.size(); i++) { + if (Objects.nonNull(originals.get(i))) { + assertNotSame(originals.get(i), copies.get(i)); + assertCopiedFields(originals.get(i), copies.get(i)); + } + } + } + } + } + + private static List> conditionLists(final Object value) { + if (value instanceof SelectorData) { + SelectorData selector = (SelectorData) value; + return Arrays.asList(selector.getConditionList(), selector.getBeforeConditionList()); + } + if (value instanceof RuleData) { + RuleData rule = (RuleData) value; + return Arrays.asList(rule.getConditionDataList(), rule.getBeforeConditionDataList()); + } + return Collections.emptyList(); + } + + private static void mutateConditions(final Object value) throws ReflectiveOperationException { + for (List conditions : conditionLists(value)) { + for (ConditionData condition : conditions) { + if (Objects.nonNull(condition)) { + assertFalse(condition.frozen()); + invokeSetters(condition, "changed"); + } + } + conditions.clear(); + conditions.add(new ConditionData()); + } + } + + private static void assertReadOnlyList(final List conditions) { + assertThrows(UnsupportedOperationException.class, () -> conditions.add(new ConditionData())); + assertThrows(UnsupportedOperationException.class, () -> conditions.set(0, new ConditionData())); + assertThrows(UnsupportedOperationException.class, () -> conditions.remove(0)); + assertThrows(UnsupportedOperationException.class, conditions::clear); + assertThrows(UnsupportedOperationException.class, () -> conditions.replaceAll(condition -> null)); + assertThrows(UnsupportedOperationException.class, () -> conditions.sort((left, right) -> 0)); + assertThrows(UnsupportedOperationException.class, () -> conditions.subList(0, 1).clear()); + Iterator iterator = conditions.iterator(); + iterator.next(); + assertThrows(UnsupportedOperationException.class, iterator::remove); + } + + private static void assertWireFields(final Object value, final JsonNode json) throws IllegalAccessException { + List fields = valueFields(value.getClass()); + assertEquals(fields.size(), json.size()); + assertFalse(json.has("frozen")); + for (Field field : fields) { + JsonNode node = json.get(field.getName()); + assertNotNull(node, field.toString()); + if (field.get(value) instanceof List) { + List conditions = (List) field.get(value); + for (int i = 0; i < conditions.size(); i++) { + if (Objects.nonNull(conditions.get(i))) { + assertWireFields(conditions.get(i), node.get(i)); + } + } + } + } + } + + private static void assertMutableRoundTrip(final Object expected, final Object actual) throws ReflectiveOperationException { + assertCopiedFields(expected, actual); + assertEquals(expected, actual); + assertEquals(actual, expected); + assertEquals(expected.hashCode(), actual.hashCode()); + assertFalse(frozen(actual)); + mutateConditions(actual); + assertDoesNotThrow(() -> invokeSetters(actual, "changed")); + } + + private static void injectFrozenState(final JsonNode node) { + if (node.isObject()) { + ((ObjectNode) node).put("frozen", true); + } + for (JsonNode child : node) { + if (child.isContainerNode()) { + injectFrozenState(child); + } + } + } +} diff --git a/shenyu-plugin/shenyu-plugin-base/src/main/java/org/apache/shenyu/plugin/base/AbstractShenyuPlugin.java b/shenyu-plugin/shenyu-plugin-base/src/main/java/org/apache/shenyu/plugin/base/AbstractShenyuPlugin.java index db6dcdab5678..cfc9aa546eec 100644 --- a/shenyu-plugin/shenyu-plugin-base/src/main/java/org/apache/shenyu/plugin/base/AbstractShenyuPlugin.java +++ b/shenyu-plugin/shenyu-plugin-base/src/main/java/org/apache/shenyu/plugin/base/AbstractShenyuPlugin.java @@ -23,6 +23,7 @@ import org.apache.shenyu.common.config.ShenyuConfig; import org.apache.shenyu.common.constant.Constants; import org.apache.shenyu.common.dto.ConditionData; +import org.apache.shenyu.common.dto.DtoSnapshots; import org.apache.shenyu.common.dto.PluginData; import org.apache.shenyu.common.dto.RuleData; import org.apache.shenyu.common.dto.SelectorData; @@ -57,9 +58,22 @@ public abstract class AbstractShenyuPlugin implements ShenyuPlugin { private static final Set PATH_ONLY_OPERATORS = Set.of("=", "equals", "contains", "startsWith", "endsWith", "match", "regex", "exclude", "pathPattern", "isBlank"); - private ShenyuConfig.SelectorMatchCache selectorMatchConfig; - - private ShenyuConfig.RuleMatchCache ruleMatchConfig; + private volatile ShenyuConfig.SelectorMatchCache selectorMatchConfig; + + private volatile ShenyuConfig.RuleMatchCache ruleMatchConfig; + + private SelectorData frozenEmptySelector; + + private RuleData frozenEmptyRule; + + /** + * Opt into publication-only base configuration. Parsed handles and metadata are separate contracts. + * Existing extension plugins keep the legacy mutable contract unless they explicitly opt in. + * @return whether to use frozen base configuration and isolated derived matches + */ + protected boolean useReadOnlyConfiguration() { + return false; + } /** * this is Template Method child has implements your own logic. @@ -84,13 +98,15 @@ public abstract class AbstractShenyuPlugin implements ShenyuPlugin { public Mono execute(final ServerWebExchange exchange, final ShenyuPluginChain chain) { initCacheConfig(); final String pluginName = named(); - PluginData pluginData = BaseDataCache.getInstance().obtainPluginData(pluginName); + PluginData pluginData = useReadOnlyConfiguration() ? BaseDataCache.getInstance().readOnly().obtainPluginData(pluginName) + : BaseDataCache.getInstance().obtainPluginData(pluginName); // early exit if (Objects.isNull(pluginData) || !pluginData.getEnabled()) { return chain.execute(exchange); } final String path = getRawPath(exchange); - List selectors = BaseDataCache.getInstance().obtainSelectorData(pluginName); + List selectors = useReadOnlyConfiguration() ? BaseDataCache.getInstance().readOnly().obtainSelectorData(pluginName) + : BaseDataCache.getInstance().obtainSelectorData(pluginName); if (CollectionUtils.isEmpty(selectors)) { return handleSelectorIfNull(pluginName, exchange, chain); } @@ -110,7 +126,8 @@ public Mono execute(final ServerWebExchange exchange, final ShenyuPluginCh // if continued, not match rules return doExecute(exchange, chain, selectorData, defaultRuleData(selectorData)); } - List rules = BaseDataCache.getInstance().obtainRuleData(selectorData.getId()); + List rules = useReadOnlyConfiguration() ? BaseDataCache.getInstance().readOnly().obtainRuleData(selectorData.getId()) + : BaseDataCache.getInstance().obtainRuleData(selectorData.getId()); if (CollectionUtils.isEmpty(rules)) { return handleRuleIfNull(pluginName, exchange, chain); } @@ -155,17 +172,29 @@ protected String getRawPath(final ServerWebExchange exchange) { private void initCacheConfig() { if (Objects.isNull(selectorMatchConfig) || Objects.isNull(ruleMatchConfig)) { ShenyuConfig shenyuConfig = SpringBeanUtils.getInstance().getBean(ShenyuConfig.class); + if (useReadOnlyConfiguration()) { + frozenEmptySelector = DtoSnapshots.freeze(SelectorData.builder().pluginName(named()).build()); + frozenEmptyRule = DtoSnapshots.freeze(RuleData.builder().pluginName(named()).build()); + } selectorMatchConfig = shenyuConfig.getSelectorMatchCache(); ruleMatchConfig = shenyuConfig.getRuleMatchCache(); } } private SelectorData obtainSelectorDataCacheIfEnabled(final String path) { - return selectorMatchConfig.getCache().getEnabled() ? MatchDataCache.getInstance().obtainSelectorData(named(), path) : null; + if (!selectorMatchConfig.getCache().getEnabled()) { + return null; + } + return useReadOnlyConfiguration() ? MatchDataCache.getInstance().readOnly().obtainSelectorData(named(), path) + : MatchDataCache.getInstance().obtainSelectorData(named(), path); } private RuleData obtainRuleDataCacheIfEnabled(final String path) { - return ruleMatchConfig.getCache().getEnabled() ? MatchDataCache.getInstance().obtainRuleData(named(), path) : null; + if (!ruleMatchConfig.getCache().getEnabled()) { + return null; + } + return useReadOnlyConfiguration() ? MatchDataCache.getInstance().readOnly().obtainRuleData(named(), path) + : MatchDataCache.getInstance().obtainRuleData(named(), path); } private void cacheSelectorData(final String path, final SelectorData selectorData) { @@ -177,14 +206,14 @@ private void cacheSelectorData(final String path, final SelectorData selectorDat long maximumSize = selectorMatchConfig.getCache().getMaximumSize(); long ttl = selectorMatchConfig.getCache().getTtl(); if (StringUtils.isBlank(selectorData.getId())) { - MatchDataCache.getInstance().cacheSelectorData(path, selectorData, initialCapacity, maximumSize, ttl); + storeSelectorMatch(path, selectorData, initialCapacity, maximumSize, ttl); return; } List conditionList = selectorData.getConditionList(); if (CollectionUtils.isNotEmpty(conditionList)) { boolean isUriCondition = conditionList.stream().allMatch(v -> URI_CONDITION_TYPE.equals(v.getParamType())); if (isUriCondition) { - MatchDataCache.getInstance().cacheSelectorData(path, selectorData, initialCapacity, maximumSize, ttl); + storeSelectorMatch(path, selectorData, initialCapacity, maximumSize, ttl); } } } @@ -199,18 +228,34 @@ private void cacheRuleData(final String path, final RuleData ruleData) { long maximumSize = ruleMatchConfig.getCache().getMaximumSize(); long ttl = ruleMatchConfig.getCache().getTtl(); if (StringUtils.isBlank(ruleData.getId())) { - MatchDataCache.getInstance().cacheRuleData(path, ruleData, initialCapacity, maximumSize, ttl); + storeRuleMatch(path, ruleData, initialCapacity, maximumSize, ttl); return; } List conditionList = ruleData.getConditionDataList(); if (CollectionUtils.isNotEmpty(conditionList)) { boolean isUriCondition = conditionList.stream().allMatch(v -> URI_CONDITION_TYPE.equals(v.getParamType())); if (isUriCondition) { - MatchDataCache.getInstance().cacheRuleData(path, ruleData, initialCapacity, maximumSize, ttl); + storeRuleMatch(path, ruleData, initialCapacity, maximumSize, ttl); } } } + private void storeSelectorMatch(final String path, final SelectorData data, final int capacity, final long maximum, final long ttl) { + if (useReadOnlyConfiguration()) { + MatchDataCache.getInstance().readOnly().cacheSelectorData(path, data, capacity, maximum, ttl); + } else { + MatchDataCache.getInstance().cacheSelectorData(path, data, capacity, maximum, ttl); + } + } + + private void storeRuleMatch(final String path, final RuleData data, final int capacity, final long maximum, final long ttl) { + if (useReadOnlyConfiguration()) { + MatchDataCache.getInstance().readOnly().cacheRuleData(path, data, capacity, maximum, ttl); + } else { + MatchDataCache.getInstance().cacheRuleData(path, data, capacity, maximum, ttl); + } + } + private RuleData defaultRuleData(final SelectorData selectorData) { RuleData ruleData = new RuleData(); ruleData.setSelectorId(selectorData.getId()); @@ -317,7 +362,7 @@ private SelectorData defaultMatchSelector(final ServerWebExchange exchange, fina // A negative entry is keyed by (plugin, path), so it is only sound when every // enabled candidate is decided by the path. if (matchSelectorPair.getLeft() && pathOnlySelectorSet(selectors)) { - SelectorData emptySelectorData = SelectorData.builder().pluginName(named()).build(); + SelectorData emptySelectorData = useReadOnlyConfiguration() ? frozenEmptySelector : SelectorData.builder().pluginName(named()).build(); cacheSelectorData(path, emptySelectorData); } return null; @@ -339,7 +384,7 @@ private RuleData defaultMatchRule(final ServerWebExchange exchange, final List PluginData. */ - private static volatile ConcurrentMap pluginMap = Maps.newConcurrentMap(); + private volatile ConcurrentMap pluginMap = Maps.newConcurrentMap(); /** * pluginName -> SelectorData. */ - private static volatile ConcurrentMap> selectorMap = Maps.newConcurrentMap(); + private volatile ConcurrentMap> selectorMap = Maps.newConcurrentMap(); /** * selectorId -> RuleData. */ - private static volatile ConcurrentMap> ruleMap = Maps.newConcurrentMap(); + private volatile ConcurrentMap> ruleMap = Maps.newConcurrentMap(); + + private volatile Map pluginView = Collections.unmodifiableMap(pluginMap); + + private volatile Map> selectorView = Collections.unmodifiableMap(selectorMap); + + private volatile Map> ruleView = Collections.unmodifiableMap(ruleMap); - private BaseDataCache() { + private BaseDataCache(final boolean published) { + this.published = published; + } + + /** + * Explicit publication-only read contract. Legacy map writes do not reach this view. + * @return shared read-only access, without copying on reads + */ + public ReadOnly readOnly() { + return READ_ONLY; } /** @@ -75,8 +98,11 @@ public static BaseDataCache getInstance() { * * @param pluginData the plugin data */ - public void cachePluginData(final PluginData pluginData) { - Optional.ofNullable(pluginData).ifPresent(data -> pluginMap.put(data.getName(), data)); + public synchronized void cachePluginData(final PluginData pluginData) { + if (!published) { + PUBLISHED.cachePluginData(pluginData); + } + Optional.ofNullable(pluginData).ifPresent(data -> pluginMap.put(data.getName(), published ? DtoSnapshots.freeze(data) : data)); } /** @@ -84,8 +110,11 @@ public void cachePluginData(final PluginData pluginData) { * * @param pluginData the plugin data */ - public void removePluginData(final PluginData pluginData) { + public synchronized void removePluginData(final PluginData pluginData) { Optional.ofNullable(pluginData).ifPresent(data -> pluginMap.remove(data.getName())); + if (!published) { + PUBLISHED.removePluginData(pluginData); + } } /** @@ -93,15 +122,21 @@ public void removePluginData(final PluginData pluginData) { * * @param pluginName the plugin name */ - public void removePluginDataByPluginName(final String pluginName) { + public synchronized void removePluginDataByPluginName(final String pluginName) { pluginMap.remove(pluginName); + if (!published) { + PUBLISHED.removePluginDataByPluginName(pluginName); + } } /** * Clean plugin data. */ - public void cleanPluginData() { + public synchronized void cleanPluginData() { pluginMap.clear(); + if (!published) { + PUBLISHED.cleanPluginData(); + } } /** @@ -109,7 +144,7 @@ public void cleanPluginData() { * * @param pluginDataList the plugin data list */ - public void cleanPluginDataSelf(final List pluginDataList) { + public synchronized void cleanPluginDataSelf(final List pluginDataList) { pluginDataList.forEach(this::removePluginData); } @@ -128,8 +163,11 @@ public PluginData obtainPluginData(final String pluginName) { * * @param selectorData the selector data */ - public void cacheSelectData(final SelectorData selectorData) { - Optional.ofNullable(selectorData).ifPresent(this::selectorAccept); + public synchronized void cacheSelectData(final SelectorData selectorData) { + if (!published) { + PUBLISHED.cacheSelectData(selectorData); + } + Optional.ofNullable(selectorData).ifPresent(data -> selectorAccept(published ? DtoSnapshots.freeze(data) : data)); } /** @@ -137,7 +175,7 @@ public void cacheSelectData(final SelectorData selectorData) { * * @param selectorData the selector data */ - public void removeSelectData(final SelectorData selectorData) { + public synchronized void removeSelectData(final SelectorData selectorData) { Optional.ofNullable(selectorData).ifPresent(data -> { if (StringUtils.isBlank(data.getPluginName())) { // a dangling selector carries no plugin name, so its entry may live under any plugin bucket @@ -146,6 +184,9 @@ public void removeSelectData(final SelectorData selectorData) { removeSelectData(data.getPluginName(), data.getId()); } }); + if (!published) { + PUBLISHED.removeSelectData(selectorData); + } } private void removeSelectData(final String pluginName, final String selectorId) { @@ -162,15 +203,21 @@ private void removeSelectData(final String pluginName, final String selectorId) * * @param pluginName the plugin name */ - public void removeSelectDataByPluginName(final String pluginName) { + public synchronized void removeSelectDataByPluginName(final String pluginName) { selectorMap.remove(pluginName); + if (!published) { + PUBLISHED.removeSelectDataByPluginName(pluginName); + } } /** * Clean selector data. */ - public void cleanSelectorData() { + public synchronized void cleanSelectorData() { selectorMap.clear(); + if (!published) { + PUBLISHED.cleanSelectorData(); + } } /** @@ -178,7 +225,7 @@ public void cleanSelectorData() { * * @param selectorDataList the selector data list */ - public void cleanSelectorDataSelf(final List selectorDataList) { + public synchronized void cleanSelectorDataSelf(final List selectorDataList) { selectorDataList.forEach(this::removeSelectData); } @@ -189,7 +236,7 @@ public void cleanSelectorDataSelf(final List selectorDataList) { * * @param selectorDataList the selectors to remove */ - void removeSelectDataBatch(final List selectorDataList) { + synchronized void removeSelectDataBatch(final List selectorDataList) { if (selectorDataList.isEmpty()) { return; } @@ -209,6 +256,9 @@ void removeSelectDataBatch(final List selectorDataList) { selectorMap.keySet().forEach(pluginName -> removeSelectDataByIds(pluginName, danglingIds)); } idsByPlugin.forEach(this::removeSelectDataByIds); + if (!published) { + PUBLISHED.removeSelectDataBatch(selectorDataList); + } } private void removeSelectDataByIds(final String pluginName, final Set selectorIds) { @@ -235,8 +285,11 @@ public List obtainSelectorData(final String pluginName) { * * @param ruleData the rule data */ - public void cacheRuleData(final RuleData ruleData) { - Optional.ofNullable(ruleData).ifPresent(this::ruleAccept); + public synchronized void cacheRuleData(final RuleData ruleData) { + if (!published) { + PUBLISHED.cacheRuleData(ruleData); + } + Optional.ofNullable(ruleData).ifPresent(data -> ruleAccept(published ? DtoSnapshots.freeze(data) : data)); } /** @@ -244,7 +297,7 @@ public void cacheRuleData(final RuleData ruleData) { * * @param ruleData the rule data */ - public void removeRuleData(final RuleData ruleData) { + public synchronized void removeRuleData(final RuleData ruleData) { Optional.ofNullable(ruleData).ifPresent(data -> { ruleMap.computeIfPresent(data.getSelectorId(), (key, value) -> { final List result = value.stream() @@ -253,6 +306,9 @@ public void removeRuleData(final RuleData ruleData) { return result.isEmpty() ? null : List.copyOf(result); }); }); + if (!published) { + PUBLISHED.removeRuleData(ruleData); + } } /** @@ -260,15 +316,21 @@ public void removeRuleData(final RuleData ruleData) { * * @param selectorId the selector id */ - public void removeRuleDataBySelectorId(final String selectorId) { + public synchronized void removeRuleDataBySelectorId(final String selectorId) { ruleMap.remove(selectorId); + if (!published) { + PUBLISHED.removeRuleDataBySelectorId(selectorId); + } } /** * Clean rule data. */ - public void cleanRuleData() { + public synchronized void cleanRuleData() { ruleMap.clear(); + if (!published) { + PUBLISHED.cleanRuleData(); + } } /** @@ -276,7 +338,7 @@ public void cleanRuleData() { * * @param ruleDataList the rule data list */ - public void cleanRuleDataSelf(final List ruleDataList) { + public synchronized void cleanRuleDataSelf(final List ruleDataList) { ruleDataList.forEach(this::removeRuleData); } @@ -285,7 +347,7 @@ public void cleanRuleDataSelf(final List ruleDataList) { * * @param ruleDataList the rules to remove */ - void removeRuleDataBatch(final List ruleDataList) { + synchronized void removeRuleDataBatch(final List ruleDataList) { if (ruleDataList.isEmpty()) { return; } @@ -302,6 +364,9 @@ void removeRuleDataBatch(final List ruleDataList) { .collect(Collectors.toList()); return result.isEmpty() ? null : List.copyOf(result); })); + if (!published) { + PUBLISHED.removeRuleDataBatch(ruleDataList); + } } /** @@ -391,14 +456,18 @@ private List upsertSorted(final List current, final List batch, * * @param dataList the received data */ - void refreshPluginData(final List dataList) { + synchronized void refreshPluginData(final List dataList) { if (dataList.isEmpty()) { return; } ConcurrentMap next = Maps.newConcurrentMap(); next.putAll(pluginMap); - dataList.forEach(data -> next.put(data.getName(), data)); + dataList.forEach(data -> next.put(data.getName(), published ? DtoSnapshots.freeze(data) : data)); + if (!published) { + PUBLISHED.refreshPluginData(dataList); + } pluginMap = next; + pluginView = Collections.unmodifiableMap(next); } /** @@ -408,7 +477,7 @@ void refreshPluginData(final List dataList) { * * @param dataList the received data */ - void refreshSelectorData(final List dataList) { + synchronized void refreshSelectorData(final List dataList) { if (dataList.isEmpty()) { return; } @@ -416,10 +485,15 @@ void refreshSelectorData(final List dataList) { next.putAll(selectorMap); Map> grouped = dataList.stream() .filter(Objects::nonNull) + .map(data -> published ? DtoSnapshots.freeze(data) : data) .collect(Collectors.groupingBy(SelectorData::getPluginName)); grouped.forEach((pluginName, batch) -> next.compute(pluginName, (key, value) -> upsertSorted(value, batch, SelectorData::getId, SelectorData::getSort))); + if (!published) { + PUBLISHED.refreshSelectorData(dataList); + } selectorMap = next; + selectorView = Collections.unmodifiableMap(next); } /** @@ -429,7 +503,7 @@ void refreshSelectorData(final List dataList) { * * @param dataList the received data */ - void refreshRuleData(final List dataList) { + synchronized void refreshRuleData(final List dataList) { if (dataList.isEmpty()) { return; } @@ -437,9 +511,75 @@ void refreshRuleData(final List dataList) { next.putAll(ruleMap); Map> grouped = dataList.stream() .filter(Objects::nonNull) + .map(data -> published ? DtoSnapshots.freeze(data) : data) .collect(Collectors.groupingBy(RuleData::getSelectorId)); grouped.forEach((selectorId, batch) -> next.compute(selectorId, (key, value) -> upsertSorted(value, batch, RuleData::getId, RuleData::getSort))); + if (!published) { + PUBLISHED.refreshRuleData(dataList); + } ruleMap = next; + ruleView = Collections.unmodifiableMap(next); + } + + /** + * Frozen configuration access. Updates must use the owning cache's publication methods. + * Individual buckets are immutable snapshots; this is not a multi-object transaction. + */ + public static final class ReadOnly { + + private ReadOnly() { + } + + /** + * Get published plugin data. + * @param pluginName plugin name + * @return frozen data or null + */ + public PluginData obtainPluginData(final String pluginName) { + return PUBLISHED.obtainPluginData(pluginName); + } + + /** + * Get a published selector bucket. + * @param pluginName plugin name + * @return frozen list and elements, or null + */ + public List obtainSelectorData(final String pluginName) { + return PUBLISHED.obtainSelectorData(pluginName); + } + + /** + * Get a published rule bucket. + * @param selectorId selector id + * @return frozen list and elements, or null + */ + public List obtainRuleData(final String selectorId) { + return PUBLISHED.obtainRuleData(selectorId); + } + + /** + * Read published plugins without exposing a writable backing map. + * @return unmodifiable live view of the current map generation + */ + public Map getPluginMap() { + return PUBLISHED.pluginView; + } + + /** + * Read published selector buckets. + * @return unmodifiable live view of the current map generation + */ + public Map> getSelectorMap() { + return PUBLISHED.selectorView; + } + + /** + * Read published rule buckets. + * @return unmodifiable live view of the current map generation + */ + public Map> getRuleMap() { + return PUBLISHED.ruleView; + } } } diff --git a/shenyu-plugin/shenyu-plugin-base/src/main/java/org/apache/shenyu/plugin/base/cache/MatchDataCache.java b/shenyu-plugin/shenyu-plugin-base/src/main/java/org/apache/shenyu/plugin/base/cache/MatchDataCache.java index 8af440af8a1b..8b557bb1d4de 100644 --- a/shenyu-plugin/shenyu-plugin-base/src/main/java/org/apache/shenyu/plugin/base/cache/MatchDataCache.java +++ b/shenyu-plugin/shenyu-plugin-base/src/main/java/org/apache/shenyu/plugin/base/cache/MatchDataCache.java @@ -27,7 +27,6 @@ import java.util.Map; import java.util.Objects; -import java.util.Optional; import java.util.concurrent.ConcurrentMap; @@ -38,16 +37,20 @@ public final class MatchDataCache { private static final MatchDataCache INSTANCE = new MatchDataCache(); + private static final MatchDataCache PUBLISHED = new MatchDataCache(); + + private static final ReadOnly READ_ONLY = new ReadOnly(); + /** * pluginName -> LRUMap. */ - private static final ConcurrentMap> SELECTOR_DATA_MAP = Maps.newConcurrentMap(); + private final ConcurrentMap> selectorDataMap = Maps.newConcurrentMap(); /** * plugin name -> LRU Map. * LRU Map: path -> rule data. */ - private static final ConcurrentMap> RULE_DATA_MAP = Maps.newConcurrentMap(); + private final ConcurrentMap> ruleDataMap = Maps.newConcurrentMap(); private MatchDataCache() { } @@ -61,13 +64,24 @@ public static MatchDataCache getInstance() { return INSTANCE; } + /** + * Access isolated derived matches for the frozen configuration contract. + * @return shared access without exposing the backing maps + */ + public ReadOnly readOnly() { + return READ_ONLY; + } + /** * Remove selector data. * * @param pluginName the pluginName */ public void removeSelectorData(final String pluginName) { - SELECTOR_DATA_MAP.remove(pluginName); + if (this == INSTANCE) { + PUBLISHED.removeSelectorData(pluginName); + } + selectorDataMap.remove(pluginName); } /** @@ -77,13 +91,16 @@ public void removeSelectorData(final String pluginName) { * @param selectorId selector id */ public void removeSelectorData(final String pluginName, final String selectorId) { + if (this == INSTANCE) { + PUBLISHED.removeSelectorData(pluginName, selectorId); + } if (StringUtils.isBlank(pluginName)) { // a dangling selector carries no plugin name, so its entries may live under any plugin bucket - SELECTOR_DATA_MAP.values().forEach(pathSelectorCache -> + selectorDataMap.values().forEach(pathSelectorCache -> pathSelectorCache.entrySet().removeIf(entry -> selectorId.equals(entry.getValue().getId()))); return; } - Map pathSelectorCache = SELECTOR_DATA_MAP.get(pluginName); + Map pathSelectorCache = selectorDataMap.get(pluginName); if (Objects.isNull(pathSelectorCache) || pathSelectorCache.isEmpty()) { return; } @@ -96,10 +113,13 @@ public void removeSelectorData(final String pluginName, final String selectorId) * @param pluginName plugin name */ public void removeEmptySelectorData(final String pluginName) { + if (this == INSTANCE) { + PUBLISHED.removeEmptySelectorData(pluginName); + } if (StringUtils.isBlank(pluginName)) { return; } - Map pathSelectorCache = SELECTOR_DATA_MAP.get(pluginName); + Map pathSelectorCache = selectorDataMap.get(pluginName); if (Objects.isNull(pathSelectorCache) || pathSelectorCache.isEmpty()) { return; } @@ -110,7 +130,10 @@ public void removeEmptySelectorData(final String pluginName) { * Clean selector data. */ public void cleanSelectorData() { - SELECTOR_DATA_MAP.clear(); + if (this == INSTANCE) { + PUBLISHED.cleanSelectorData(); + } + selectorDataMap.clear(); } /** @@ -135,7 +158,7 @@ public void cacheSelectorData(final String path, final SelectorData selectorData * @param ttl lifetime in milliseconds */ public void cacheSelectorData(final String path, final SelectorData selectorData, final int initialCapacity, final long maximumSize, final long ttl) { - MapUtils.computeIfAbsent(SELECTOR_DATA_MAP, selectorData.getPluginName(), map -> + MapUtils.computeIfAbsent(selectorDataMap, selectorData.getPluginName(), map -> new WindowTinyLFUMap<>(initialCapacity, ttl, maximumSize, Boolean.FALSE)).put(path, selectorData); } @@ -147,8 +170,8 @@ public void cacheSelectorData(final String path, final SelectorData selectorData * @return the selector data */ public SelectorData obtainSelectorData(final String pluginName, final String path) { - final Map lruMap = SELECTOR_DATA_MAP.get(pluginName); - return Optional.ofNullable(lruMap).orElse(Maps.newHashMap()).get(path); + final Map lruMap = selectorDataMap.get(pluginName); + return Objects.isNull(lruMap) ? null : lruMap.get(path); } /** @@ -173,7 +196,7 @@ public void cacheRuleData(final String path, final RuleData ruleData, final int * @param ttl lifetime in milliseconds */ public void cacheRuleData(final String path, final RuleData ruleData, final int initialCapacity, final long maximumSize, final long ttl) { - MapUtils.computeIfAbsent(RULE_DATA_MAP, ruleData.getPluginName(), map -> + MapUtils.computeIfAbsent(ruleDataMap, ruleData.getPluginName(), map -> new WindowTinyLFUMap<>(initialCapacity, ttl, maximumSize, Boolean.FALSE)).put(path, ruleData); } @@ -183,7 +206,10 @@ public void cacheRuleData(final String path, final RuleData ruleData, final int * @param pluginName pluginName */ public void removeRuleData(final String pluginName) { - RULE_DATA_MAP.remove(pluginName); + if (this == INSTANCE) { + PUBLISHED.removeRuleData(pluginName); + } + ruleDataMap.remove(pluginName); } /** @@ -193,13 +219,16 @@ public void removeRuleData(final String pluginName) { * @param ruleId ruleId */ public void removeRuleData(final String pluginName, final String ruleId) { + if (this == INSTANCE) { + PUBLISHED.removeRuleData(pluginName, ruleId); + } if (StringUtils.isBlank(pluginName)) { // a rule of a deleted plugin carries no plugin name, so its entries may live under any plugin bucket - RULE_DATA_MAP.values().forEach(pathRuleDataCache -> + ruleDataMap.values().forEach(pathRuleDataCache -> pathRuleDataCache.entrySet().removeIf(entry -> ruleId.equals(entry.getValue().getId()))); return; } - Map pathRuleDataCache = RULE_DATA_MAP.get(pluginName); + Map pathRuleDataCache = ruleDataMap.get(pluginName); if (Objects.isNull(pathRuleDataCache) || pathRuleDataCache.isEmpty()) { return; } @@ -213,13 +242,16 @@ public void removeRuleData(final String pluginName, final String ruleId) { * @param selectorId selectorId */ public void removeRuleDataBySelector(final String pluginName, final String selectorId) { + if (this == INSTANCE) { + PUBLISHED.removeRuleDataBySelector(pluginName, selectorId); + } if (StringUtils.isBlank(pluginName)) { // a dangling selector carries no plugin name, so its rule entries may live under any plugin bucket - RULE_DATA_MAP.values().forEach(pathRuleDataCache -> + ruleDataMap.values().forEach(pathRuleDataCache -> pathRuleDataCache.entrySet().removeIf(entry -> selectorId.equals(entry.getValue().getSelectorId()))); return; } - Map pathRuleDataCache = RULE_DATA_MAP.get(pluginName); + Map pathRuleDataCache = ruleDataMap.get(pluginName); if (Objects.isNull(pathRuleDataCache) || pathRuleDataCache.isEmpty()) { return; } @@ -232,10 +264,13 @@ public void removeRuleDataBySelector(final String pluginName, final String selec * @param pluginName plugin name */ public void removeEmptyRuleData(final String pluginName) { + if (this == INSTANCE) { + PUBLISHED.removeEmptyRuleData(pluginName); + } if (StringUtils.isBlank(pluginName)) { return; } - Map pathRuleDataCache = RULE_DATA_MAP.get(pluginName); + Map pathRuleDataCache = ruleDataMap.get(pluginName); if (Objects.isNull(pathRuleDataCache) || pathRuleDataCache.isEmpty()) { return; } @@ -246,7 +281,10 @@ public void removeEmptyRuleData(final String pluginName) { * clear the cache. */ public void cleanRuleDataData() { - RULE_DATA_MAP.clear(); + if (this == INSTANCE) { + PUBLISHED.cleanRuleDataData(); + } + ruleDataMap.clear(); } /** @@ -257,8 +295,8 @@ public void cleanRuleDataData() { * @return ruleData */ public RuleData obtainRuleData(final String pluginName, final String path) { - final Map lruMap = RULE_DATA_MAP.get(pluginName); - return Optional.ofNullable(lruMap).orElse(Maps.newHashMap()).get(path); + final Map lruMap = ruleDataMap.get(pluginName); + return Objects.isNull(lruMap) ? null : lruMap.get(path); } /** @@ -267,7 +305,7 @@ public RuleData obtainRuleData(final String pluginName, final String path) { * @return selector match cache */ public ConcurrentMap> getSelectorMatchCache() { - return SELECTOR_DATA_MAP; + return selectorDataMap; } /** @@ -276,7 +314,65 @@ public ConcurrentMap> getSelectorMatchCache() * @return rule match cache */ public ConcurrentMap> getRuleMatchCache() { - return RULE_DATA_MAP; + return ruleDataMap; } + /** + * Isolated match cache for already-frozen values. This API never freezes on the request path. + */ + public static final class ReadOnly { + + private ReadOnly() { + } + + /** + * Get a frozen matched selector. + * @param pluginName plugin name + * @param path request path + * @return frozen value or null + */ + public SelectorData obtainSelectorData(final String pluginName, final String path) { + return PUBLISHED.obtainSelectorData(pluginName, path); + } + + /** + * Get a frozen matched rule. + * @param pluginName plugin name + * @param path request path + * @return frozen value or null + */ + public RuleData obtainRuleData(final String pluginName, final String path) { + return PUBLISHED.obtainRuleData(pluginName, path); + } + + /** + * Cache a previously published selector without copying it. + * @param path request path + * @param data frozen selector + * @param initialCapacity initial capacity + * @param maximumSize maximum size + * @param ttl lifetime in milliseconds + */ + public void cacheSelectorData(final String path, final SelectorData data, final int initialCapacity, final long maximumSize, final long ttl) { + if (!data.frozen()) { + throw new IllegalArgumentException("Read-only matching requires a frozen selector"); + } + PUBLISHED.cacheSelectorData(path, data, initialCapacity, maximumSize, ttl); + } + + /** + * Cache a previously published rule without copying it. + * @param path request path + * @param data frozen rule + * @param initialCapacity initial capacity + * @param maximumSize maximum size + * @param ttl lifetime in milliseconds + */ + public void cacheRuleData(final String path, final RuleData data, final int initialCapacity, final long maximumSize, final long ttl) { + if (!data.frozen()) { + throw new IllegalArgumentException("Read-only matching requires a frozen rule"); + } + PUBLISHED.cacheRuleData(path, data, initialCapacity, maximumSize, ttl); + } + } } diff --git a/shenyu-plugin/shenyu-plugin-base/src/test/java/org/apache/shenyu/plugin/base/cache/MatchDataCacheTest.java b/shenyu-plugin/shenyu-plugin-base/src/test/java/org/apache/shenyu/plugin/base/cache/MatchDataCacheTest.java index 8948fd4af112..4eca7355ba5d 100644 --- a/shenyu-plugin/shenyu-plugin-base/src/test/java/org/apache/shenyu/plugin/base/cache/MatchDataCacheTest.java +++ b/shenyu-plugin/shenyu-plugin-base/src/test/java/org/apache/shenyu/plugin/base/cache/MatchDataCacheTest.java @@ -33,9 +33,9 @@ @SuppressWarnings("unchecked") public final class MatchDataCacheTest { - private final String selectorMapStr = "SELECTOR_DATA_MAP"; + private final String selectorMapStr = "selectorDataMap"; - private final String ruleMapStr = "RULE_DATA_MAP"; + private final String ruleMapStr = "ruleDataMap"; private final String mockPluginName1 = "MOCK_PLUGIN_NAME_1"; diff --git a/shenyu-plugin/shenyu-plugin-base/src/test/java/org/apache/shenyu/plugin/base/cache/PublishedConfigurationTest.java b/shenyu-plugin/shenyu-plugin-base/src/test/java/org/apache/shenyu/plugin/base/cache/PublishedConfigurationTest.java new file mode 100644 index 000000000000..7ac479f1b6fb --- /dev/null +++ b/shenyu-plugin/shenyu-plugin-base/src/test/java/org/apache/shenyu/plugin/base/cache/PublishedConfigurationTest.java @@ -0,0 +1,248 @@ +/* + * 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.base.cache; + +import org.apache.shenyu.common.dto.ConditionData; +import org.apache.shenyu.common.dto.PluginData; +import org.apache.shenyu.common.dto.RuleData; +import org.apache.shenyu.common.dto.SelectorData; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Regression for source references changing another request's published configuration. + */ +class PublishedConfigurationTest { + + private final BaseDataCache cache = BaseDataCache.getInstance(); + + private final BaseDataCache.ReadOnly view = cache.readOnly(); + + @BeforeEach + @AfterEach + void cleanup() { + cache.cleanPluginData(); + cache.cleanSelectorData(); + cache.cleanRuleData(); + MatchDataCache.getInstance().cleanSelectorData(); + MatchDataCache.getInstance().cleanRuleDataData(); + } + + @Test + void legacyControlDemonstratesWhyContainerImmutabilityAloneIsInsufficient() { + SelectorData source = selector("one", 0); + cache.cacheSelectData(source); + List legacy = cache.obtainSelectorData("divide"); + assertThrows(UnsupportedOperationException.class, legacy::clear); + source.getConditionList().get(0).setParamValue("/polluted"); + assertEquals("/polluted", legacy.get(0).getConditionList().get(0).getParamValue()); + assertEquals("/original", view.obtainSelectorData("divide").get(0).getConditionList().get(0).getParamValue()); + } + + @Test + void publicationDetachesNestedConditionsFromTheSynchronizationDto() { + SelectorData source = selector("one", 0); + cache.cacheSelectData(source); + final SelectorData published = view.obtainSelectorData("divide").get(0); + source.setHandle("changed"); + source.getConditionList().get(0).setParamValue("/polluted"); + source.getConditionList().clear(); + assertEquals("/original", published.getConditionList().get(0).getParamValue()); + assertEquals("original", published.getHandle()); + assertSame(source, cache.obtainSelectorData("divide").get(0)); + assertNotSame(source, published); + assertThrows(UnsupportedOperationException.class, () -> published.setHandle("polluted")); + assertThrows(UnsupportedOperationException.class, () -> published.getConditionList().get(0).setParamValue("polluted")); + } + + @Test + void pluginAndRuleCopiesDetachAndReuseUnchangedPublishedEntries() { + PluginData plugin = PluginData.builder().name("divide").enabled(true).config("{}").build(); + cache.cachePluginData(plugin); + RuleData first = rule("one", 1); + cache.cacheRuleData(first); + RuleData published = view.obtainRuleData("selector").get(0); + cache.cacheRuleData(rule("two", 2)); + assertSame(published, view.obtainRuleData("selector").get(0)); + plugin.setEnabled(false); + first.setHandle("changed"); + assertTrue(view.obtainPluginData("divide").getEnabled()); + assertEquals("original", published.getHandle()); + assertSame(view.getRuleMap(), view.getRuleMap()); + assertSame(view.obtainRuleData("selector"), view.obtainRuleData("selector")); + } + + @Test + void publishedMapsAndEveryExposedContainerRejectWrites() { + cache.cacheSelectData(selector("one", 0)); + cache.cacheRuleData(rule("one", 0)); + cache.cachePluginData(PluginData.builder().name("divide").enabled(true).build()); + Map> selectors = view.getSelectorMap(); + assertThrows(UnsupportedOperationException.class, selectors::clear); + assertThrows(UnsupportedOperationException.class, () -> selectors.remove("divide")); + assertThrows(UnsupportedOperationException.class, () -> selectors.compute("divide", (key, value) -> List.of())); + assertThrows(UnsupportedOperationException.class, () -> selectors.entrySet().iterator().next().setValue(List.of())); + assertThrows(UnsupportedOperationException.class, () -> selectors.values().remove(selectors.get("divide"))); + assertThrows(UnsupportedOperationException.class, () -> selectors.get("divide").clear()); + assertThrows(UnsupportedOperationException.class, () -> selectors.get("divide").get(0).getBeforeConditionList().clear()); + assertThrows(UnsupportedOperationException.class, () -> view.getPluginMap().get("divide").setEnabled(false)); + assertThrows(UnsupportedOperationException.class, () -> view.getRuleMap().get("selector").get(0).setEnabled(false)); + assertThrows(UnsupportedOperationException.class, () -> view.getRuleMap().put("injected", List.of(rule("injected", 0)))); + cache.getPluginMap().clear(); + cache.getSelectorMap().get("divide").get(0).setEnabled(false); + cache.getRuleMap().clear(); + assertTrue(view.obtainPluginData("divide").getEnabled()); + assertTrue(view.obtainSelectorData("divide").get(0).getEnabled()); + assertEquals(1, view.obtainRuleData("selector").size()); + } + + @Test + void allPublicationAndRemovalFormsReachTheReadOnlyContract() { + cache.refreshPluginData(List.of(PluginData.builder().name("divide").enabled(true).build())); + cache.refreshSelectorData(List.of(selector("a", 2), selector("b", 1))); + cache.refreshRuleData(List.of(rule("a", 2), rule("b", 1))); + assertEquals(List.of("b", "a"), view.obtainSelectorData("divide").stream().map(SelectorData::getId).toList()); + assertEquals(List.of("b", "a"), view.obtainRuleData("selector").stream().map(RuleData::getId).toList()); + SelectorData old = view.obtainSelectorData("divide").get(0); + cache.refreshSelectorData(List.of(selector("b", 4))); + assertEquals(1, old.getSort()); + assertEquals(List.of("a", "b"), view.obtainSelectorData("divide").stream().map(SelectorData::getId).toList()); + cache.removeSelectDataBatch(List.of(SelectorData.builder().id("a").build())); + cache.removeRuleDataBatch(List.of(rule("a", 2))); + assertEquals(1, view.obtainSelectorData("divide").size()); + assertEquals(1, view.obtainRuleData("selector").size()); + cache.removeSelectDataByPluginName("divide"); + cache.removeRuleDataBySelectorId("selector"); + cache.removePluginDataByPluginName("divide"); + assertNull(view.obtainPluginData("divide")); + assertNull(view.obtainSelectorData("divide")); + assertNull(view.obtainRuleData("selector")); + cache.cacheSelectData(selector("c", 1)); + cache.cacheRuleData(rule("c", 1)); + cache.removeSelectData(SelectorData.builder().id("c").build()); + cache.removeRuleData(rule("c", 1)); + assertTrue(view.getSelectorMap().isEmpty()); + assertTrue(view.getRuleMap().isEmpty()); + } + + @Test + void unsupportedSnapshotInputLeavesBothPublishedAndLegacyStateUnchanged() { + cache.cacheSelectData(selector("one", 0)); + SelectorData oldLegacy = cache.obtainSelectorData("divide").get(0); + final SelectorData oldPublished = view.obtainSelectorData("divide").get(0); + SelectorData invalid = selector("one", 1); + invalid.setConditionList(List.of(new ConditionData() { })); + assertThrows(IllegalArgumentException.class, () -> cache.cacheSelectData(invalid)); + assertSame(oldLegacy, cache.obtainSelectorData("divide").get(0)); + assertSame(oldPublished, view.obtainSelectorData("divide").get(0)); + assertThrows(IllegalArgumentException.class, () -> cache.refreshSelectorData(List.of(selector("two", 2), invalid))); + assertEquals(List.of(oldLegacy), cache.obtainSelectorData("divide")); + assertEquals(List.of(oldPublished), view.obtainSelectorData("divide")); + } + + @Test + void isolatedMatchCacheRejectsMutableInjectionAndReceivesInvalidations() { + MatchDataCache matches = MatchDataCache.getInstance(); + SelectorData source = selector("one", 0); + RuleData sourceRule = rule("one", 0); + cache.cacheSelectData(source); + cache.cacheRuleData(sourceRule); + matches.cacheSelectorData("/original", source, 8, 32, 60000); + matches.cacheRuleData("/original", sourceRule, 8, 32, 60000); + assertNull(matches.readOnly().obtainSelectorData("divide", "/original")); + assertNull(matches.readOnly().obtainRuleData("divide", "/original")); + assertThrows(IllegalArgumentException.class, () -> matches.readOnly().cacheSelectorData("/original", source, 8, 32, 60000)); + assertThrows(IllegalArgumentException.class, () -> matches.readOnly().cacheRuleData("/original", sourceRule, 8, 32, 60000)); + SelectorData frozen = view.obtainSelectorData("divide").get(0); + RuleData frozenRule = view.obtainRuleData("selector").get(0); + matches.readOnly().cacheSelectorData("/original", frozen, 8, 32, 60000); + matches.readOnly().cacheRuleData("/original", frozenRule, 8, 32, 60000); + assertSame(frozen, matches.readOnly().obtainSelectorData("divide", "/original")); + assertSame(frozenRule, matches.readOnly().obtainRuleData("divide", "/original")); + matches.removeSelectorData("divide", "one"); + matches.removeRuleDataBySelector("divide", "selector"); + assertNull(matches.readOnly().obtainSelectorData("divide", "/original")); + assertNull(matches.readOnly().obtainRuleData("divide", "/original")); + } + + @Test + void readersRetainStableNestedValuesAcrossUpdateAndDelete() throws Exception { + cache.cacheSelectData(selector("one", 0)); + SelectorData held = view.obtainSelectorData("divide").get(0); + CountDownLatch start = new CountDownLatch(1); + ExecutorService executor = Executors.newSingleThreadExecutor(); + try { + Future writer = executor.submit(() -> { + try { + assertTrue(start.await(10, TimeUnit.SECONDS)); + for (int index = 0; index < 100; index++) { + SelectorData next = selector("one", index); + next.getConditionList().get(0).setParamValue("/updated-" + index); + cache.cacheSelectData(next); + } + cache.removeSelectDataByPluginName("divide"); + } catch (InterruptedException error) { + Thread.currentThread().interrupt(); + throw new IllegalStateException(error); + } + }); + start.countDown(); + for (int index = 0; index < 1000; index++) { + assertEquals("/original", held.getConditionList().get(0).getParamValue()); + assertEquals(0, held.getSort()); + } + writer.get(10, TimeUnit.SECONDS); + assertNull(view.obtainSelectorData("divide")); + assertFalse(held.getConditionList().isEmpty()); + } finally { + executor.shutdownNow(); + assertTrue(executor.awaitTermination(10, TimeUnit.SECONDS)); + } + } + + private SelectorData selector(final String id, final int sort) { + ConditionData condition = new ConditionData(); + condition.setParamType("uri"); + condition.setOperator("="); + condition.setParamValue("/original"); + return SelectorData.builder().id(id).pluginName("divide").sort(sort).enabled(true).handle("original") + .conditionList(new ArrayList<>(List.of(condition))).beforeConditionList(new ArrayList<>(List.of(condition))).build(); + } + + private RuleData rule(final String id, final int sort) { + return RuleData.builder().id(id).pluginName("divide").selectorId("selector").sort(sort).enabled(true).handle("original").build(); + } +} diff --git a/shenyu-plugin/shenyu-plugin-proxy/shenyu-plugin-divide/src/main/java/org/apache/shenyu/plugin/divide/DividePlugin.java b/shenyu-plugin/shenyu-plugin-proxy/shenyu-plugin-divide/src/main/java/org/apache/shenyu/plugin/divide/DividePlugin.java index 63e0412afa4f..307393ce379b 100644 --- a/shenyu-plugin/shenyu-plugin-proxy/shenyu-plugin-divide/src/main/java/org/apache/shenyu/plugin/divide/DividePlugin.java +++ b/shenyu-plugin/shenyu-plugin-proxy/shenyu-plugin-divide/src/main/java/org/apache/shenyu/plugin/divide/DividePlugin.java @@ -100,6 +100,11 @@ public DividePlugin(final CanaryDecisionService canaryDecisionService) { this.canaryDecisionService = Objects.requireNonNull(canaryDecisionService); } + @Override + protected boolean useReadOnlyConfiguration() { + return true; + } + @Override protected String getRawPath(final ServerWebExchange exchange) { return RequestUrlUtils.getRewrittenRawPath(exchange); diff --git a/shenyu-plugin/shenyu-plugin-proxy/shenyu-plugin-divide/src/test/java/org/apache/shenyu/plugin/divide/DividePublishedConfigurationTest.java b/shenyu-plugin/shenyu-plugin-proxy/shenyu-plugin-divide/src/test/java/org/apache/shenyu/plugin/divide/DividePublishedConfigurationTest.java new file mode 100644 index 000000000000..ba89ba07ac41 --- /dev/null +++ b/shenyu-plugin/shenyu-plugin-proxy/shenyu-plugin-divide/src/test/java/org/apache/shenyu/plugin/divide/DividePublishedConfigurationTest.java @@ -0,0 +1,246 @@ +/* + * 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.divide; + +import org.apache.shenyu.common.config.ShenyuConfig; +import org.apache.shenyu.common.constant.Constants; +import org.apache.shenyu.common.dto.ConditionData; +import org.apache.shenyu.common.dto.PluginData; +import org.apache.shenyu.common.dto.RuleData; +import org.apache.shenyu.common.dto.SelectorData; +import org.apache.shenyu.common.dto.convert.rule.impl.DivideRuleHandle; +import org.apache.shenyu.common.enums.SelectorTypeEnum; +import org.apache.shenyu.loadbalancer.cache.UpstreamCacheManager; +import org.apache.shenyu.loadbalancer.entity.Upstream; +import org.apache.shenyu.plugin.api.ShenyuPluginChain; +import org.apache.shenyu.plugin.api.context.ShenyuContext; +import org.apache.shenyu.plugin.api.utils.SpringBeanUtils; +import org.apache.shenyu.plugin.base.AbstractShenyuPlugin; +import org.apache.shenyu.plugin.base.cache.BaseDataCache; +import org.apache.shenyu.plugin.base.cache.MatchDataCache; +import org.apache.shenyu.plugin.base.handler.PluginDataHandler; +import org.apache.shenyu.plugin.base.cache.CommonPluginDataSubscriber; +import org.apache.shenyu.plugin.base.utils.CacheKeyUtils; +import org.apache.shenyu.plugin.divide.handler.DividePluginDataHandler; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.context.ConfigurableApplicationContext; +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 java.util.List; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +/** + * Exercises production matching and forwarding without opening network connections. + */ +class DividePublishedConfigurationTest { + + private final BaseDataCache cache = BaseDataCache.getInstance(); + + private final MatchDataCache matches = MatchDataCache.getInstance(); + + private final AtomicInteger forwarded = new AtomicInteger(); + + private final ShenyuConfig config = new ShenyuConfig(); + + private SelectorData selector; + + private RuleData rule; + + @BeforeEach + void setUp() { + cleanup(); + config.getSelectorMatchCache().getCache().setEnabled(true); + config.getRuleMatchCache().getCache().setEnabled(true); + ConfigurableApplicationContext context = mock(ConfigurableApplicationContext.class); + when(context.getBean(ShenyuConfig.class)).thenReturn(config); + when(context.getBean(org.apache.shenyu.plugin.api.result.ShenyuResult.class)).thenReturn(new org.apache.shenyu.plugin.api.result.DefaultShenyuResult()); + SpringBeanUtils.getInstance().setApplicationContext(context); + cache.cachePluginData(PluginData.builder().name("divide").enabled(true).build()); + selector = SelectorData.builder().id("published-selector").pluginName("divide").name("published") + .type(SelectorTypeEnum.CUSTOM_FLOW.getCode()).matchMode(0).enabled(true).logged(false).sort(0) + .conditionList(List.of(condition())).continued(true).build(); + rule = RuleData.builder().id("published-rule").selectorId(selector.getId()).pluginName("divide").name("published") + .enabled(true).logged(false).sort(0).matchMode(0).conditionDataList(List.of(condition())).handle("{}").build(); + cache.cacheSelectData(selector); + cache.cacheRuleData(rule); + Upstream upstream = Upstream.builder().protocol("http://").url("127.0.0.1:18001").weight(50).healthCheckEnabled(false).build(); + UpstreamCacheManager.getInstance().submit(selector.getId(), List.of(upstream)); + DivideRuleHandle handle = DivideRuleHandle.newInstance(); + handle.setRetry(0); + DividePluginDataHandler.CACHED_HANDLE.get().cachedHandle(CacheKeyUtils.INST.getKey(rule), handle); + } + + @AfterEach + void cleanup() { + cache.cleanPluginData(); + cache.cleanSelectorData(); + cache.cleanRuleData(); + matches.cleanSelectorData(); + matches.cleanRuleDataData(); + UpstreamCacheManager.getInstance().removeByKey("published-selector"); + DividePluginDataHandler.CACHED_HANDLE.get().removeHandle(CacheKeyUtils.INST.getKey("published-selector", "published-rule")); + } + + @Test + void divideMatchesFrozenValuesAndIgnoresLegacyMutationsOnCacheHit() { + ProbingDivide plugin = new ProbingDivide(); + execute(plugin, "/original"); + SelectorData seen = plugin.selector; + RuleData seenRule = plugin.rule; + assertTrue(seen.frozen()); + assertTrue(seenRule.frozen()); + assertThrows(UnsupportedOperationException.class, () -> seen.setEnabled(false)); + assertThrows(UnsupportedOperationException.class, () -> seenRule.getConditionDataList().get(0).setParamValue("/polluted")); + selector.setEnabled(false); + selector.getConditionList().get(0).setParamValue("/polluted"); + rule.setEnabled(false); + matches.getSelectorMatchCache().clear(); + matches.getRuleMatchCache().clear(); + execute(plugin, "/original"); + assertSame(seen, plugin.selector); + assertSame(seenRule, plugin.rule); + assertEquals(2, forwarded.get()); + assertSame(seen, matches.readOnly().obtainSelectorData("divide", "/original")); + assertSame(seenRule, matches.readOnly().obtainRuleData("divide", "/original")); + } + + @Test + void subscriberUpdateInvalidatesFrozenPositiveAndNegativeMatches() { + ProbingDivide plugin = new ProbingDivide(); + execute(plugin, "/original"); + execute(plugin, "/missing"); + assertNull(matches.readOnly().obtainSelectorData("divide", "/missing").getId()); + CommonPluginDataSubscriber subscriber = new CommonPluginDataSubscriber(List.of(new DividePluginDataHandler()), + config.getSelectorMatchCache(), config.getRuleMatchCache()); + selector.getConditionList().get(0).setParamValue("/missing"); + rule.getConditionDataList().get(0).setParamValue("/missing"); + subscriber.onSelectorSubscribe(selector); + subscriber.onRuleSubscribe(rule); + execute(plugin, "/missing"); + assertEquals("/missing", plugin.selector.getConditionList().get(0).getParamValue()); + assertEquals(2, forwarded.get()); + subscriber.unRuleSubscribe(rule); + plugin.rule = null; + execute(plugin, "/missing"); + assertNull(plugin.rule); + } + + @Test + void defaultRuleIsRequestOwnedAndDoesNotMutateThePublishedSelector() { + selector.setContinued(false); + cache.cacheSelectData(selector); + DividePluginDataHandler.CACHED_HANDLE.get().cachedHandle(CacheKeyUtils.INST.getKey(selector.getId(), Constants.DEFAULT_RULE), DivideRuleHandle.newInstance()); + ProbingDivide plugin = new ProbingDivide(); + execute(plugin, "/original"); + RuleData first = plugin.rule; + assertFalse(first.frozen()); + first.setHandle("request override"); + execute(plugin, "/original"); + assertNull(plugin.rule.getHandle()); + assertTrue(plugin.selector.frozen()); + DividePluginDataHandler.CACHED_HANDLE.get().removeHandle(CacheKeyUtils.INST.getKey(selector.getId(), Constants.DEFAULT_RULE)); + } + + @Test + void legacyPluginKeepsMutableConfigurationAndHealthCountersRemainLive() { + AtomicReference observed = new AtomicReference<>(); + AbstractShenyuPlugin legacy = new AbstractShenyuPlugin() { + @Override + protected Mono doExecute(final ServerWebExchange exchange, final ShenyuPluginChain chain, final SelectorData data, final RuleData matched) { + observed.set(data); + return Mono.empty(); + } + + @Override + public String named() { + return "divide"; + } + + @Override + public int getOrder() { + return 0; + } + }; + legacy.execute(exchange("/original"), ignored -> Mono.empty()).block(); + assertSame(selector, observed.get()); + observed.get().setHandle("legacy mutation"); + assertNull(cache.readOnly().obtainSelectorData("divide").get(0).getHandle()); + Upstream upstream = UpstreamCacheManager.getInstance().findUpstreamListBySelectorId(selector.getId()).get(0); + long before = upstream.getInflight().get(); + assertEquals(before + 1, upstream.getInflight().incrementAndGet()); + upstream.getInflight().decrementAndGet(); + upstream.setStatus(false); + assertFalse(upstream.isStatus()); + } + + private void execute(final DividePlugin plugin, final String path) { + ServerWebExchange exchange = exchange(path); + plugin.execute(exchange, current -> { + if (java.util.Objects.nonNull(current.getAttribute(Constants.HTTP_DOMAIN))) { + forwarded.incrementAndGet(); + } + return Mono.empty(); + }).block(); + } + + private ServerWebExchange exchange(final String path) { + MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get(path).build()); + ShenyuContext context = new ShenyuContext(); + context.setRealUrl(path); + context.setRpcType("http"); + exchange.getAttributes().put(Constants.CONTEXT, context); + return exchange; + } + + private ConditionData condition() { + ConditionData data = new ConditionData(); + data.setParamType("uri"); + data.setOperator("="); + data.setParamValue("/original"); + return data; + } + + private static final class ProbingDivide extends DividePlugin { + + private SelectorData selector; + + private RuleData rule; + + @Override + protected Mono doExecute(final ServerWebExchange exchange, final ShenyuPluginChain chain, final SelectorData selected, final RuleData matched) { + selector = selected; + rule = matched; + return super.doExecute(exchange, chain, selected, matched); + } + } +}