Skip to content

Commit 03131be

Browse files
committed
[ISSUE #8208] Address review: registration token, full-flow decision split, real-chain test
1 parent 57f6efb commit 03131be

6 files changed

Lines changed: 244 additions & 108 deletions

File tree

‎shenyu-plugin/shenyu-plugin-base/src/main/java/org/apache/shenyu/plugin/base/AbstractShenyuPlugin.java‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -143,7 +143,7 @@ private Mono<Void> matchRuleAndExecute(final ServerWebExchange exchange, final S
143143
if (selectorData.getType() == SelectorTypeEnum.FULL_FLOW.getCode()) {
144144
RuleData rule = lastEnabledRule(rules);
145145
if (Objects.isNull(rule)) {
146-
reportDecision(Decision.NO_RULE, selectorData, null, false,
146+
reportDecision(Decision.FULL_FLOW_NO_ENABLED_RULE, selectorData, null, false,
147147
selectorCache, CacheResolution.NOT_CONSULTED);
148148
return handleRuleIfNull(pluginName, exchange, chain);
149149
}

‎shenyu-plugin/shenyu-plugin-base/src/main/java/org/apache/shenyu/plugin/base/match/SelectorRuleMatchObservation.java‎

Lines changed: 20 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,10 @@
3232
* <p>Instances carry plugin identity, the selected ids and the decision reason only. They
3333
* never contain request paths, credentials, condition payloads or bodies, so they are safe
3434
* to forward to metric labels or log pipelines.</p>
35+
*
36+
* <p>Observations are dispatched synchronously on the request's event-loop thread; the
37+
* observer contract requires returning immediately, because blocking there directly slows
38+
* the real request.</p>
3539
*/
3640
public final class SelectorRuleMatchObservation {
3741

@@ -179,8 +183,10 @@ public enum Decision {
179183
PLUGIN_DISABLED,
180184

181185
/**
182-
* No selector was selected: the selector list is empty, the negative match cache
183-
* recorded no match for this path, or live matching found no candidate.
186+
* The selector stage found no candidate and the plugin entered its
187+
* {@code handleSelectorIfNull} fallback hook (the default hook continues the
188+
* chain; plugins overriding the hook decide their own route). Covers an empty
189+
* selector list and a negative match-cache hit for this path.
184190
*/
185191
NO_SELECTOR,
186192

@@ -190,15 +196,24 @@ public enum Decision {
190196
SELECTOR_UNMATCHED,
191197

192198
/**
193-
* No rule was selected: the rule list is empty, the negative match cache recorded
194-
* no match for this path, or live matching found no enabled rule.
199+
* The rule stage found no candidate and the plugin entered its
200+
* {@code handleRuleIfNull} fallback hook (the default hook continues the chain;
201+
* plugins overriding the hook decide their own route). Covers an empty rule list
202+
* and a negative match-cache hit for this path.
195203
*/
196204
NO_RULE,
197205

198206
/**
199207
* Live rule matching evaluated the candidate set and found no candidate.
200208
*/
201-
RULE_UNMATCHED
209+
RULE_UNMATCHED,
210+
211+
/**
212+
* A full-flow selector supplied no rule because none of its rules is enabled.
213+
* Operationally distinct from {@link #NO_RULE}: the configuration exists but is
214+
* entirely disabled.
215+
*/
216+
FULL_FLOW_NO_ENABLED_RULE
202217
}
203218

204219
/**

‎shenyu-plugin/shenyu-plugin-base/src/main/java/org/apache/shenyu/plugin/base/match/SelectorRuleMatchObserver.java‎

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -21,11 +21,13 @@
2121
* Read-only consumer of selector/rule matching decisions.
2222
*
2323
* <p>Implementations are invoked synchronously on the gateway request path after a matching
24-
* decision has been taken. The contract is strict: the callback must not throw, must not
25-
* block, must not mutate the exchange, the configuration caches or the observation, and must
26-
* never consume or buffer request bodies. Sampling, bounded queues and export backpressure
27-
* are the consumer's own responsibility, so a slow or saturated consumer can never alter a
28-
* request outcome, hold an unbounded queue or retain request data.</p>
24+
* decision has been taken, on the event-loop thread that is driving the request. The
25+
* contract is strict: the callback must return immediately (blocking there directly slows
26+
* the real request), must not throw, must not mutate the exchange, the configuration caches
27+
* or the observation, and must never consume or buffer request bodies. Sampling, bounded
28+
* queues and export backpressure are the consumer's own responsibility, so a slow or
29+
* saturated consumer can never alter a request outcome, hold an unbounded queue or retain
30+
* request data.</p>
2931
*/
3032
@FunctionalInterface
3133
public interface SelectorRuleMatchObserver {

‎shenyu-plugin/shenyu-plugin-base/src/main/java/org/apache/shenyu/plugin/base/match/SelectorRuleMatchObserverHolder.java‎

Lines changed: 13 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -22,10 +22,11 @@
2222
/**
2323
* Opt-in static registration point for the {@link SelectorRuleMatchObserver}.
2424
*
25-
* <p>The holder follows the same pattern as the diagnostics and metrics registration
26-
* points: exactly one observer is registered at startup by whichever consumer (metrics,
27-
* diagnostics, agent) wants the decision stream. With no observer registered the matching
28-
* path performs a single null read and never allocates an observation, so instrumentation
25+
* <p>This is a single-slot adapter wiring point, not a telemetry backend: it follows the
26+
* same pattern as the existing static registration points (the metrics reporter and the
27+
* diagnostics configuration), where exactly one consumer is registered at startup and no
28+
* new observation machinery is introduced. With no observer registered the matching path
29+
* performs a single volatile read and never allocates an observation, so instrumentation
2930
* enabled/disabled is behaviourally and cost-invisible at the request path.</p>
3031
*/
3132
public final class SelectorRuleMatchObserverHolder {
@@ -39,9 +40,16 @@ private SelectorRuleMatchObserverHolder() {
3940
* Register the process-wide observer, replacing any previous one.
4041
*
4142
* @param newObserver the observer to register, must not be null
43+
* @return a registration token whose {@code close()} unregisters this observer
44+
* (only while it is still the registered one); it never throws
4245
*/
43-
public static void register(final SelectorRuleMatchObserver newObserver) {
46+
public static AutoCloseable register(final SelectorRuleMatchObserver newObserver) {
4447
observer = Objects.requireNonNull(newObserver, "observer");
48+
return () -> {
49+
if (observer == newObserver) {
50+
observer = null;
51+
}
52+
};
4553
}
4654

4755
/**
@@ -59,13 +67,4 @@ public static void unregister() {
5967
public static SelectorRuleMatchObserver get() {
6068
return observer;
6169
}
62-
63-
/**
64-
* Whether an observer is registered.
65-
*
66-
* @return true when decisions are being reported
67-
*/
68-
public static boolean isInstrumented() {
69-
return Objects.nonNull(observer);
70-
}
7170
}

‎shenyu-plugin/shenyu-plugin-base/src/test/java/org/apache/shenyu/plugin/base/match/SelectorRuleMatchObservationTest.java‎

Lines changed: 37 additions & 83 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,6 @@
2424
import org.apache.shenyu.common.dto.RuleData;
2525
import org.apache.shenyu.common.dto.SelectorData;
2626
import org.apache.shenyu.common.enums.SelectorTypeEnum;
27-
import org.apache.shenyu.plugin.api.ShenyuPlugin;
2827
import org.apache.shenyu.plugin.api.ShenyuPluginChain;
2928
import org.apache.shenyu.plugin.api.context.ShenyuContext;
3029
import org.apache.shenyu.plugin.api.utils.SpringBeanUtils;
@@ -41,13 +40,9 @@
4140
import reactor.core.publisher.Mono;
4241
import reactor.test.StepVerifier;
4342

44-
import java.lang.reflect.Field;
45-
import java.lang.reflect.Method;
46-
import java.lang.reflect.Modifier;
4743
import java.util.ArrayList;
4844
import java.util.Collections;
4945
import java.util.List;
50-
import java.util.Objects;
5146

5247
import static org.mockito.ArgumentMatchers.any;
5348
import static org.junit.jupiter.api.Assertions.assertEquals;
@@ -260,7 +255,29 @@ public void fullFlowWithoutEnabledRuleReportsNoRule() {
260255
.conditionDataList(Collections.singletonList(conditionData)).build());
261256
StepVerifier.create(testShenyuPlugin.execute(exchange, shenyuPluginChain)).verifyComplete();
262257
assertEquals(1, events.size());
263-
assertEquals(SelectorRuleMatchObservation.Decision.NO_RULE, events.get(0).getDecision());
258+
assertEquals(SelectorRuleMatchObservation.Decision.FULL_FLOW_NO_ENABLED_RULE, events.get(0).getDecision());
259+
}
260+
261+
@Test
262+
public void negativeRuleCacheHitReportsNoRuleFromCache() {
263+
mockShenyuConfig(true);
264+
BaseDataCache.getInstance().cachePluginData(pluginData);
265+
BaseDataCache.getInstance().cacheSelectData(selectorData);
266+
// the rule list carries only non-matching, path-only, uniquely decidable rules,
267+
// so the first request evaluates live and warms the negative rule entry
268+
BaseDataCache.getInstance().cacheRuleData(RuleData.builder().id("r2").pluginName("SHENYU").selectorId("s1")
269+
.enabled(true).logged(true).matchRestful(false).matchMode(0).sort(1)
270+
.conditionDataList(Collections.singletonList(unmatchedCondition())).build());
271+
StepVerifier.create(testShenyuPlugin.execute(exchange, shenyuPluginChain)).verifyComplete();
272+
assertEquals(1, events.size());
273+
assertEquals(SelectorRuleMatchObservation.Decision.RULE_UNMATCHED, events.get(0).getDecision());
274+
events.clear();
275+
// the second request is served by the negative rule cache entry
276+
StepVerifier.create(testShenyuPlugin.execute(exchange, shenyuPluginChain)).verifyComplete();
277+
assertEquals(1, events.size());
278+
SelectorRuleMatchObservation observation = events.get(0);
279+
assertEquals(SelectorRuleMatchObservation.Decision.NO_RULE, observation.getDecision());
280+
assertEquals(SelectorRuleMatchObservation.CacheResolution.NEGATIVE_HIT, observation.getRuleCache());
264281
}
265282

266283
@Test
@@ -300,49 +317,28 @@ public void throwingObserverDoesNotAffectRequest() {
300317
}
301318

302319
@Test
303-
public void unregisteredObserverProducesNoEventsAndNoFailure() {
320+
public void registrationTokenUnregistersOnlyItsOwnObserver() throws Exception {
304321
seedSuccessfulConfig();
305-
SelectorRuleMatchObserverHolder.unregister();
306-
assertFalse(SelectorRuleMatchObserverHolder.isInstrumented());
322+
AutoCloseable token = SelectorRuleMatchObserverHolder.register(events::add);
323+
SelectorRuleMatchObserver later = observation -> { };
324+
final AutoCloseable laterToken = SelectorRuleMatchObserverHolder.register(later);
325+
token.close();
326+
// the later registration must survive closing an earlier token
307327
StepVerifier.create(testShenyuPlugin.execute(exchange, shenyuPluginChain)).verifyComplete();
308328
verify(testShenyuPlugin).doExecute(exchange, shenyuPluginChain, selectorData, ruleData);
309-
assertTrue(events.isEmpty());
310-
}
311-
312-
@Test
313-
public void outerSkipProducesNoEventBecauseExecuteIsNeverReached() {
314-
seedSuccessfulConfig();
315-
// emulate the chain: skip is checked before execute and a skipped plugin never matches
316-
SkippingPlugin skippingPlugin = new SkippingPlugin();
317-
if (!skippingPlugin.skip(exchange)) {
318-
skippingPlugin.execute(exchange, shenyuPluginChain).subscribe();
319-
}
320-
assertTrue(events.isEmpty(), "a skipped plugin must not fabricate a matching event");
321-
}
322-
323-
@Test
324-
public void pluginsOutsideAbstractShenyuPluginProduceNoEvents() throws Exception {
325-
seedSuccessfulConfig();
326-
// a direct ShenyuPlugin implementation has no selector/rule decision to report
327-
ShenyuPlugin plainPlugin = new PlainPlugin();
328-
StepVerifier.create(plainPlugin.execute(exchange, shenyuPluginChain)).verifyComplete();
329-
assertTrue(events.isEmpty(), "unsupported plugins must not get fabricated events");
329+
assertTrue(events.isEmpty(), "the later observer discards, but stays registered");
330+
laterToken.close();
331+
StepVerifier.create(testShenyuPlugin.execute(exchange, shenyuPluginChain)).verifyComplete();
332+
verify(testShenyuPlugin, org.mockito.Mockito.times(2)).doExecute(exchange, shenyuPluginChain, selectorData, ruleData);
330333
}
331334

332335
@Test
333-
public void observationIsImmutableAndFreeOfRequestData() {
336+
public void unregisteredObserverProducesNoEventsAndNoFailure() {
334337
seedSuccessfulConfig();
338+
SelectorRuleMatchObserverHolder.unregister();
335339
StepVerifier.create(testShenyuPlugin.execute(exchange, shenyuPluginChain)).verifyComplete();
336-
for (Method method : SelectorRuleMatchObservation.class.getDeclaredMethods()) {
337-
assertFalse(method.getName().startsWith("set"), "observations must expose no setters");
338-
}
339-
for (Field field : SelectorRuleMatchObservation.class.getDeclaredFields()) {
340-
assertTrue(Modifier.isFinal(field.getModifiers()), field.getName() + " must be final");
341-
}
342-
SelectorRuleMatchObservation observation = events.get(0);
343-
// no field can carry the request path: the record only holds ids and enums
344-
assertFalse(Objects.nonNull(observation.getSelectorId()) && observation.getSelectorId().contains("SHENYU/SHENYU"));
345-
assertEquals("SHENYU", observation.getPluginName());
340+
verify(testShenyuPlugin).doExecute(exchange, shenyuPluginChain, selectorData, ruleData);
341+
assertTrue(events.isEmpty());
346342
}
347343

348344
private void seedSuccessfulConfig() {
@@ -383,48 +379,6 @@ private void mockShenyuConfig(final boolean cacheEnabled) {
383379
SpringBeanUtils.getInstance().setApplicationContext(context);
384380
}
385381

386-
static class SkippingPlugin extends AbstractShenyuPlugin {
387-
388-
@Override
389-
public boolean skip(final ServerWebExchange serverExchange) {
390-
return true;
391-
}
392-
393-
@Override
394-
protected Mono<Void> doExecute(final ServerWebExchange serverExchange, final ShenyuPluginChain pluginChain,
395-
final SelectorData selector, final RuleData rule) {
396-
return Mono.empty();
397-
}
398-
399-
@Override
400-
public int getOrder() {
401-
return 0;
402-
}
403-
404-
@Override
405-
public String named() {
406-
return "SHENYU";
407-
}
408-
}
409-
410-
static class PlainPlugin implements ShenyuPlugin {
411-
412-
@Override
413-
public Mono<Void> execute(final ServerWebExchange serverExchange, final ShenyuPluginChain pluginChain) {
414-
return Mono.empty();
415-
}
416-
417-
@Override
418-
public int getOrder() {
419-
return 0;
420-
}
421-
422-
@Override
423-
public String named() {
424-
return "PLAIN";
425-
}
426-
}
427-
428382
static class TestShenyuPlugin extends AbstractShenyuPlugin {
429383

430384
@Override

0 commit comments

Comments
 (0)