Repository navigation
fix: bound gRPC aggregated streaming responses with configurable budgets - #7940
Merged
Merged
Conversation
The gRPC plugin aggregates SERVER_STREAMING/BIDI_STREAMING responses into an unbounded ArrayList (ShenyuGrpcResponse.results) that only completes when the RPC terminates, so retained results can grow without limit and the HTTP client consumption rate cannot regulate upstream receipt. Add opt-in aggregate budgets to the gRPC plugin config: - GrpcRegisterConfig gains maxAggregatedResultCount and maxAggregatedResultBytes (null/non-positive = unlimited, preserving existing behavior). - MessageWriter tracks retained item count and UTF-8 payload bytes; on budget exhaustion it releases retained results, stops appending and cancels the underlying ClientCall, so the call future completes exceptionally and a documented error is returned instead of a success-shaped partial aggregate. - ShenyuGrpcClient resolves the budgets from config and binds the ClientCall to the writer (invoke now creates the call once). The byte budget bounds serialized payload bytes, not exact JVM heap. Each call owns its writer/response, so concurrent RPCs stay isolated. Fixes #7928
Aias00
approved these changes
Oct 21, 2026
Aias00
left a comment
Contributor
There was a problem hiding this comment.
Review: bound gRPC aggregated streaming responses
Solid, well-scoped change. I verified the wiring end to end rather than just reading the diff:
Singleton.INST.get(GrpcRegisterConfig.class)is genuinely populated —GrpcPluginDataHandler.handlerPlugindoesSingleton.INST.single(GrpcRegisterConfig.class, grpcRegisterConfig), soresolveBudgetis not dead code.- The new fields participate in
equals/hashCode, which matters more than it looks:handlerPluginonly refreshes the singleton when!grpcRegisterConfig.equals(exist), so without that change a budget-only edit would have been silently ignored until some other field changed. Good catch. invoke()creating theClientCallonce (instead of per-branch) is what makesbindCallcorrect — the writer is bound beforeasyncUnaryCall/asyncServerStreamingCallstarts, so the firstonNextcan already cancel. Previously each branch built its own call.call.cancel(...)propagates throughCompositeStreamObservertoCompleteObserver, so the future completes exceptionally andGrpcPluginmaps it viaonErrorMap(ShenyuException::new)— the PR body's claim about a documented error rather than a success-shaped partial aggregate checks out.ShenyuGrpcResponse.resultsis a plainArrayListcreated per call inShenyuGrpcClient.call, soclear()on overflow is safe and cannot leak into another request.
The > comparison means budget N retains exactly N items and the (N+1)-th triggers the discard-and-cancel — consistent with withinCountBudgetDoesNotCancel / exceedingCountBudgetCancelsAndReleasesResults, and consistent with "never return a partial aggregate". Tests cover below/at/above for both dimensions, post-overflow suppression, unbound call, and writer isolation. Good coverage.
Non-blocking notes:
- The config→writer wiring has no test.
MessageWriterTestexercises the writer in isolation andGrpcRegisterConfigTestexercises the bean, but nothing proves that a value set in theSingletonactually reachesMessageWriter.newInstance(...). That is the single place where this whole feature can silently become a no-op (wrong singleton key,resolveBudgetreturning 0,bindCallnever called). A test that puts aGrpcRegisterConfigintoSingleton, callsShenyuGrpcClient.call(...)against an in-process gRPC server, and asserts the call is cancelled would close the loop. MakingresolveMaxAggregatedResultCount/Bytespackage-private would let you assert it more cheaply. - Fail-open on unparsable config.
handlerPluginrunsGsonUtils.fromJson(...); a malformed value (e.g."maxAggregatedResultCount": "abc") throws, the singleton is never refreshed, andresolveBudgetfalls back to0= unlimited. For a protection knob, degrading silently to "no protection" deserves at least a WARN. - The byte budget is much smaller than the retained heap.
respData.getBytes(UTF_8).lengthmeasures the trimmed JSON text, while the retained object is the parsedHashMap. Real heap is typically several times the JSON length, so an operator who sets the budget near their heap size will still OOM. The code comments say "payload bytes, not heap" — theGrpcRegisterConfigJavadoc should say the same thing, since that is what operators actually read. - Blank payloads consume the count budget with zero bytes. The
elsebranch doesgetResults().add(respData)withretained = true, so a stream of empty messages trips the count budget while contributing nothing to the byte budget. That preserves historical aggregation, but it is surprising enough to be worth a comment. - Single global budget, no per-selector/rule override. Coarse for a gateway fronting several gRPC backends with very different payload profiles. Fine as a first cut — worth a follow-up note on #7928.
- The counters rely on gRPC serializing callbacks per call (documented in the class Javadoc), while only
callRefis anAtomicReference. The reasoning is sound; just be aware that if that assumption is ever violated the counters race silently rather than loudly.
LGTM. Point 1 is the one I would most like to see added before merge.
1 task done
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
What this PR does
Adds an opt-in bound to the gRPC plugin's aggregated response so that SERVER_STREAMING / BIDI_STREAMING calls can no longer retain an unbounded number of results before the RPC terminates. Two configurable budgets (item count and payload bytes) are introduced; on exhaustion the underlying RPC is cancelled, retained results are released, and the call future completes exceptionally so a documented error is returned instead of a success-shaped partial aggregate.
Related Issue
Fixes #7928
Type of change
Details
GrpcRegisterConfiggainsmaxAggregatedResultCountandmaxAggregatedResultBytes.null/non-positive means unlimited, preserving the historical behavior (opt-in bounding, backward compatible).MessageWritertracks the retained item count and accumulated UTF-8 payload bytes. When a budget is crossed it clears the retained results, ignores furtheronNext, and cancels the boundClientCallwith a descriptive reason. Cancellation propagates through gRPC toCompleteObserver.onError, completing the result future exceptionally, whichGrpcPluginmaps to aShenyuException.ShenyuGrpcClientresolves the budgets from the plugin config singleton and binds theClientCallto the writer;invokenow creates the call once and reuses it across all method types.Note: this bounds aggregation only; it does not introduce end-to-end streaming backpressure or change the aggregated JSON output shape for calls within the configured limits.
How was this tested
MessageWriterTest: below/at/above count and byte budgets, overflow releases results and cancels once, post-overflow messages ignored, unlimited default, writer isolation;GrpcRegisterConfigTest: new fields + equals/hashCode)./mvnw test -pl shenyu-plugin/.../shenyu-plugin-grpcpassed (24 tests)./mvnw test -pl shenyu-common -Dtest=GrpcRegisterConfigTestpassed (3 tests)Checklist