Skip to content

[ISSUE #8474] Apply the WebSocket rule timeout to the upstream handshake - #8513

Open
konlue wants to merge 4 commits into
apache:masterfrom
konlue:fix/8474-ws-rule-handshake-timeout
Open

konlue wants to merge 4 commits into
apache:masterfrom
konlue:fix/8474-ws-rule-handshake-timeout

Conversation

@konlue

@konlue konlue commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #8474.

The WebSocket rule exposes timeout, and WebSocketRuleHandle parsed and cached it, but nothing consumed it: the upstream websocket handshake had no deadline at all. PR #8377 already fixed the symptom the issue reports — idle sessions closing after about three seconds — by removing the shared HTTP client's timeout handlers from websocket connections; the remaining ask is making the rule timeout mean something, with the two controls the issue describes.

What changed

The rule timeout now bounds the upstream connection and upgrade only. ReactorNettyWebSocketClient.execute returns a Mono that completes when the proxied session ends, so a deadline on it closes healthy sessions at a fixed age. Instead, the inner upstream handler completes a handshake signal as its first statement — the only observable point at which the upgrade succeeded — and the plugin races the connection against a deadline built on that signal. Once the signal fires, the deadline turns inert and the session runs untimed; a stalled upgrade is closed with 1011 and an explicit reason, and the pending connection attempt is cancelled. A non-positive timeout disables the deadline.

A separate opt-in idleTimeout (milliseconds, default 0 = disabled) applies after establishment. Both receive directions count as activity, and a session that moved no message for the configured period is closed on both sides with 1001 and an explicit reason; traffic in either direction keeps the session alive, and no timer exists when idleTimeout is zero or below. Admin rejects negative timeout or idleTimeout handles through a new WebSocketRuleHandleValidator wired into rule create, update and import, and the rule form gains an idleTimeout field in the MySQL, PostgreSQL, Oracle and H2 init schemas plus the six 2.7.2 to 2.7.3 upgrade scripts. The rule's retry field remains unused, as in the divide plugin's websocket-facing path.

Testing

WebSocketPluginHandshakeTimeoutTest drives the real plugin with captured sessions. A permanently stalled upgrade under a 100 ms rule timeout is closed with 1011 and a reason and the plugin Mono completes. The regression case for the earlier mistake models an upgrade that succeeds after 20 ms while the rule timeout is 100 ms: the session then stays silent and nothing is closed for 400 ms, so the deadline cannot bound an established session. Idle expiry closes with 1001 and a reason, 30 ms traffic keeps a 100 ms idle limit alive, and both idleTimeout=0 and a non-positive timeout disable their controls. WebSocketPluginTest keeps the leastActive and shortestResponse coverage and now constructs the handler directly instead of by reflection, which also fixed the red CI build. WebSocketRuleHandleValidatorTest and new RuleServiceTest cases pin Admin rejection before any write.

Local results: shenyu-plugin-websocket 29/29, WebSocketRuleHandleTest 4/4, Admin validator and rule-service tests green, checkstyle clean on every touched module, RAT clean.

@Aias00 Aias00 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Stream Agent analysis

The rule timeout is applied to the entire upstream WebSocket session Mono rather than the handshake only, so an established idle session outliving the rule timeout is terminated — the exact regression the PR says it avoids. CI is also not green.

Evidence: ["WebSocketPlugin.java RIGHT line 422: upstream.timeout(Duration.ofMillis(this.timeout), Mono.error(new TimeoutException(...))) is applied directly to the Mono returned by client.execute (assigned at RIGHT line 392). The PR body itself states client.execute's Mono 'completes only when the session ends', so this bounds the whole proxied session, not the handshake.","The comment at RIGHT lines 419-420 claims 'The established session ... is never bounded by this timer' and the body says the first cut's wrapping of client.execute was the mistake supposedly moved off — both are contradicted by the implemented code.","CI not passing: pr_build completed with 'failure', build/e2e checks queued and policy checks cancelled; passed=false, pending=true, diagnosis=CI_PENDING. Full diff available in FULL_DIFF attachment; auxiliary pinned-source reads failed, so no further source context was used."]

Next steps: ["Bound only the connection/upgrade phase (e.g., the connect/handshake signal), not the Mono returned by client.execute which completes only when the upstream session closes.","Add a test with an established, idle upstream session proving it survives past the rule timeout, to distinguish handshake timeout from session timeout.","Re-run CI before merge: pr_build reported failure and several build/e2e/policy checks are queued or cancelled (passed=false, pending=true)."]

Verdict: NEEDS_CHANGES; publication: REQUEST_CHANGES (VERIFIED_BLOCKING_FINDINGS)

Findings: [{"line":422,"message":"The timeout is applied via upstream.timeout(...) to the Mono returned by client.execute, which only completes when the upstream WebSocket session closes. This bounds the entire established session rather than the handshake, so a healthy idle session outliving the rule timeout is terminated with TimeoutException — the idle-close regression (#8377) the change says it avoids, and directly contradicting the adjacent comment that the session is never bounded. The two tests use Mono.never(), which models an established idle session just as well as a stalled handshake, so they cannot detect this.","path":"shenyu-plugin/shenyu-plugin-proxy/shenyu-plugin-websocket/src/main/java/org/apache/shenyu/plugin/websocket/WebSocketPlugin.java","severity":"HIGH","side":"RIGHT"}]

Scope: captured GitHub evidence only; no local tests were executed.

Task: 0cad282a-dd97-4739-83ef-900406aca35d Commit: 9ea681f3538750b944dcc86d9c4fe6f63498fcba

@wy471x wy471x left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Standards

  • Mono.error(new TimeoutException(...)) uses a JDK exception; the project convention (AGENTS.md) prefers ShenyuException or a custom exception for failures surfaced by plugins. It is also instantiated eagerly on every request, capturing a stack trace even when the operator never fires — pass a supplier.
  • The constructor now takes a bare long timeout whose unit lives only in the javadoc. Duration would carry the unit into the type.
  • Import order in the new test interleaves org.junit.*, reactor.test.* and java.*; the existing tests in this module keep java.* after the third-party imports. Not tooling-enforced, but the repo asks for surrounding style.
  • mockChain() returns org.apache.shenyu.plugin.api.ShenyuPluginChain as an inline fully-qualified name — use an import.

Spec

The issue states: "Applying a timeout to the entire session Mono would also be incorrect, because it would terminate healthy long-lived connections at a fixed age."

  • Blocking (verified). client.execute(...) does not complete when the upgrade finishes. ReactorNettyWebSocketClient.execute ends with .handle((inbound, outbound) -> handler.handle(session)).next(), so the returned Mono<Void> completes only when the proxied handler's Mono — the session lifetime — completes. Wrapping it in .timeout(...) therefore bounds the established session: a Mono<Void> never emits, so timeout fires on the missing onComplete. Since WebSocketRuleHandle.timeout defaults to Constants.TIME_OUT = 3000, every proxied session is torn down 3 s after establishment regardless of traffic — strictly worse than the reported idle close, which at least reset on traffic. The javadoc added to ShenyuWebSocketHandler ("bound the upstream handshake … the established session keeps running on its own subscription") does not hold for this reason.
  • The new test cannot catch the defect: when(webSocketClient.execute(any(), any(), any())).thenReturn(Mono.never()) is indistinguishable between a stalled handshake and a live session. Please add a test where the proxied session stays open beyond timeout and assert it is not closed (a StepVerifier over the handler Mono, or a real socket test as the issue's validation asks for).
  • Missing behaviour: the issue asks for two separate controls — a connection/upgrade deadline that stops once the upgrade succeeds, plus an optional idleTimeout (0 disables) — with Admin validation and form metadata. This PR adds one field applied to the wrong boundary, so the second control is unimplemented.
  • Minor: a session killed by this timer after the 101 has already been sent will surface as an abrupt close without a status code or reason, which is one of the symptoms the issue reports.

Verdict

Request changes. Apply the deadline where the upstream upgrade is actually awaited (a reactor-netty connect/response timeout, or a timeout around the handshake before the session Mono is returned) and leave the session Mono untimed; then prove it with a test that outlives the configured timeout.

konlue and others added 3 commits November 18, 2026 23:45
…handshake

The WebSocket rule exposes a timeout setting (WebSocketRuleHandle
parses and caches it), but nothing consumed it end to end: the upstream
websocket handshake had no deadline at all. PR apache#8377 already fixed the
symptom the issue reports — idle sessions closing after ~3 seconds — by
removing the shared HTTP client's timeout handlers from websocket
connections; the remaining ask is making the rule's timeout mean
something.

The rule timeout now bounds the upstream handshake only: the
client.execute(...) Mono inside ShenyuWebSocketHandler is wrapped with a
rule-driven deadline, so a dead upstream fails the upgrade in a
rule-controlled time instead of hanging. The established session keeps
running on its own subscription and is never bounded by this timer —
websocket sessions are legitimately idle, and a session-wide timer
would re-introduce the idle-close bug apache#8377 fixed. A non-positive
timeout disables the deadline. The rule's retry field remains unused,
as in the divide plugin's websocket-facing path.
… the session mono

Review of the first cut wrapped client.execute(...) with the rule
timeout, but that Mono completes when the proxied session ends — a
healthy long-lived session would have been killed at a fixed age,
exactly what the issue warns about. The deadline now wraps the handshake
Mono the plugin returns (which completes when the upgrade finishes,
while the session runs on its own subscription), on all three load
balancer paths, and the handler no longer carries the timeout.
@konlue
konlue force-pushed the fix/8474-ws-rule-handshake-timeout branch from 9ea681f to 4767e50 Compare November 18, 2026 15:47
@konlue

konlue commented Nov 18, 2026

Copy link
Copy Markdown
Contributor Author

Second-round review response

Thanks @wy471x and @Aias00. Both blocking points are addressed in 4767e50b0 (rebased onto master 3a7e3ceb3), and the red build is fixed.

The timeout no longer bounds the session. You are right that ReactorNettyWebSocketClient.execute ends with .handle((inbound, outbound) -> handler.handle(session)).next(), so its Mono is the session lifetime, and wrapping it closed healthy sessions at a fixed age. The deadline is now anchored on a handshake signal: the inner handler completes a Sinks.Empty as its first statement, which is the first observable point at which the upstream upgrade succeeded, and the plugin races the connection Mono against upgraded.asMono().timeout(...).switchIfEmpty(Mono.never()). On success the gate turns inert and the established session runs untimed; on expiry the gate closes the downstream session with 1011 and an explicit reason, then completes so the pending upgrade is cancelled. The rule timeout is carried as a Duration, and no Mono.error(new TimeoutException(...)) remains on the path.

The second control is implemented. WebSocketRuleHandle.idleTimeout (milliseconds, default 0 = disabled) applies after establishment: both receive directions stamp activity, a poll at half the idle limit closes both sides with 1001 plus a reason once nothing moved for the configured period, so traffic in either direction keeps the session alive. The watch is one arm of a firstWithSignal, so ending or cancelling the session disposes the periodic task, and idleTimeout=0 never creates a timer. Admin rejects negative timeout or idleTimeout through a new WebSocketRuleHandleValidator wired into RuleService, and the dynamic form gets an idleTimeout row in the MySQL, PostgreSQL, Oracle and H2 init schemas plus all six 2.7.2→2.7.3 upgrade scripts. RELEASE-NOTES.md records both semantics.

Tests. Mono.never() still models a stalled handshake, but a new case distinguishes the two situations the old test could not: the upstream handler is invoked 20 ms in and the session then stays silent, while the rule timeout is 100 ms; the test asserts that nothing is closed within 400 ms (establishedIdleSessionOutlivesTheHandshakeTimeout). The idle control has its own cases: expiry closes with 1001 and a reason, 30 ms traffic keeps a 100 ms idle limit alive, and zero disables it. The leastActive and shortestResponse paths are untouched and still pass.

CI. The red build was WebSocketPluginTest.getSubProtocolsTest: the handler constructor gained its timeout argument while the test still reflected a four-argument constructor. The test now constructs the handler directly, which also removes its dependency on the unspecified getDeclaredClasses() order. Local results on the rebased head: shenyu-plugin-websocket 29/29, WebSocketRuleHandleTest 4/4, WebSocketRuleHandleValidatorTest 8/8 plus RuleServiceTest 69/69, checkstyle clean on all three touched modules and RAT clean.

@Aias00 Aias00 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Stream Agent analysis

Reviewed #8513 at d916652 in full. The change applies the WebSocket rule timeout to the upstream handshake via a Sinks.Empty upgrade signal (deadline becomes inert after upgrade), adds an opt-in idleTimeout with dual-direction activity tracking, adds an Admin handle validator, and adds form metadata to 4 init and 6 upgrade SQL scripts. The two blocking points from the prior CHANGES_REQUESTED review appear addressed and I found no concrete HIGH/CRITICAL defect, but CI is still pending, so PASS is not permitted.

Evidence: ["Full frozen diff read: resource_diff paged from offset 0 through 56125 with has_more=false, covering all 20 changed files; SHA256 856cc032... matches pinned comparison.","Core contract verified at head: ShenyuWebSocketHandler.handle emits upgraded.tryEmitEmpty() in the inner handler and uses upgraded.asMono().timeout(...).switchIfEmpty(Mono.never()) so the deadline goes inert after upgrade; pipe() applies idleWatch on both receive directions with GOING_AWAY/1001; the single production constructor call site (WebSocketPlugin.java:126) and the tests use the new 5-arg constructor; WebSocketRuleHandleValidator is wired into create/update/registerDefault via validateRuleHandle.","CI not passing: evidence attachment reports check_count 47, passed=false, pending=true, diagnosis CI_PENDING, with pr_build/plugin_contract/rat_check and multiple build jobs queued or in_progress and no failed checks yet."]

Next steps: ["Wait for the queued/in_progress CI checks (pr_build, plugin_contract, rat_check, native-sql, integrated websocket builds, etc.) to finish and confirm green, then re-run this review for a PASS verdict."]

Verdict: INCONCLUSIVE; publication: COMMENT (DIFF_DELIVERY_INCOMPLETE)

Findings: []

Scope: captured GitHub evidence only; no local tests were executed.

Task: ab8b6527-e9cc-4895-b63e-7b01ca93f8be Commit: d91665289d6f1945d846b0b456a54d770457a2a5

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[BUG] WebSocket rule timeout is not applied; shared HTTP read timeout closes idle sessions after ~3 seconds

3 participants