Skip to content

fix: bound gRPC aggregated streaming responses with configurable budgets - #7940

Merged
Aias00 merged 1 commit into
masterfrom
fix/grpc-bounded-aggregated-response
Oct 23, 2026
Merged

Aias00 merged 1 commit into
masterfrom
fix/grpc-bounded-aggregated-response

Conversation

@dmsolr

@dmsolr dmsolr commented Oct 21, 2026

Copy link
Copy Markdown
Member

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

  • Bug fix
  • New feature / enhancement

Details

  • GrpcRegisterConfig gains maxAggregatedResultCount and maxAggregatedResultBytes. null/non-positive means unlimited, preserving the historical behavior (opt-in bounding, backward compatible).
  • MessageWriter tracks the retained item count and accumulated UTF-8 payload bytes. When a budget is crossed it clears the retained results, ignores further onNext, and cancels the bound ClientCall with a descriptive reason. Cancellation propagates through gRPC to CompleteObserver.onError, completing the result future exceptionally, which GrpcPlugin maps to a ShenyuException.
  • ShenyuGrpcClient resolves the budgets from the plugin config singleton and binds the ClientCall to the writer; invoke now creates the call once and reuses it across all method types.
  • The byte budget measures serialized payload bytes, not an exact JVM heap bound (documented in code). Each call owns its own writer/response, so concurrent RPCs are isolated.

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

  • Unit tests added / updated (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-grpc passed (24 tests)
  • ./mvnw test -pl shenyu-common -Dtest=GrpcRegisterConfigTest passed (3 tests)
  • Checkstyle passed on both modules

Checklist

  • Apache 2.0 license header present on source files
  • No breaking changes to public API / config / DB schema (new config fields are optional and default to unlimited)

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 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.

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.handlerPlugin does Singleton.INST.single(GrpcRegisterConfig.class, grpcRegisterConfig), so resolveBudget is not dead code.
  • The new fields participate in equals/hashCode, which matters more than it looks: handlerPlugin only 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 the ClientCall once (instead of per-branch) is what makes bindCall correct — the writer is bound before asyncUnaryCall / asyncServerStreamingCall starts, so the first onNext can already cancel. Previously each branch built its own call.
  • call.cancel(...) propagates through CompositeStreamObserver to CompleteObserver, so the future completes exceptionally and GrpcPlugin maps it via onErrorMap(ShenyuException::new) — the PR body's claim about a documented error rather than a success-shaped partial aggregate checks out.
  • ShenyuGrpcResponse.results is a plain ArrayList created per call in ShenyuGrpcClient.call, so clear() 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:

  1. The config→writer wiring has no test. MessageWriterTest exercises the writer in isolation and GrpcRegisterConfigTest exercises the bean, but nothing proves that a value set in the Singleton actually reaches MessageWriter.newInstance(...). That is the single place where this whole feature can silently become a no-op (wrong singleton key, resolveBudget returning 0, bindCall never called). A test that puts a GrpcRegisterConfig into Singleton, calls ShenyuGrpcClient.call(...) against an in-process gRPC server, and asserts the call is cancelled would close the loop. Making resolveMaxAggregatedResultCount/Bytes package-private would let you assert it more cheaply.
  2. Fail-open on unparsable config. handlerPlugin runs GsonUtils.fromJson(...); a malformed value (e.g. "maxAggregatedResultCount": "abc") throws, the singleton is never refreshed, and resolveBudget falls back to 0 = unlimited. For a protection knob, degrading silently to "no protection" deserves at least a WARN.
  3. The byte budget is much smaller than the retained heap. respData.getBytes(UTF_8).length measures the trimmed JSON text, while the retained object is the parsed HashMap. 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" — the GrpcRegisterConfig Javadoc should say the same thing, since that is what operators actually read.
  4. Blank payloads consume the count budget with zero bytes. The else branch does getResults().add(respData) with retained = 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.
  5. 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.
  6. The counters rely on gRPC serializing callbacks per call (documented in the class Javadoc), while only callRef is an AtomicReference. 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.

@Aias00
Aias00 merged commit fe411d3 into master Oct 23, 2026
58 of 68 checks passed
@yuluo-yx
yuluo-yx deleted the fix/grpc-bounded-aggregated-response branch November 4, 2026 15:14
@Aias00 Aias00 added this to the 2.7.2 milestone Nov 13, 2026
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.

[Enhancement][gRPC] Bound aggregated streaming responses and define downstream flow control

2 participants