Skip to content

Commit 7536955

Browse files
authored
fix(ai): bound gzip observation to the usage-inspection budget (#8396)
GzipStreamDecoder expanded a whole compressed chunk into a ByteArrayOutputStream before the bounded usage extractor saw any bytes, so a highly compressible response allocated and inflated far beyond the 64 KiB inspection budget, and kept inflating later chunks after observation had stopped. Push each 4 KiB decompression slice straight into the extractor and abandon the decoder as soon as the extractor budget is exhausted; forwarded response bytes and backpressure are untouched. Make inflater close idempotent so success, error and cancellation paths close it exactly once. Unknown usage stays on the existing OptionalLong reporting path. Add high-expansion, many-chunk, malformed-compression and lifecycle fixtures; keep the header-across-buffer and SSE-across-flush regressions.
1 parent d7d2f7c commit 7536955

3 files changed

Lines changed: 337 additions & 13 deletions

File tree

‎shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-token-limiter/src/main/java/org/apache/shenyu/plugin/ai/token/limiter/AiTokenLimiterPlugin.java‎

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -259,7 +259,8 @@ private boolean isEventStream() {
259259
return Objects.nonNull(contentType) && MediaType.TEXT_EVENT_STREAM.isCompatibleWith(contentType);
260260
}
261261

262-
private GzipStreamDecoder createDecoder() {
262+
// Package-visible so tests can substitute a decoder and verify its lifecycle.
263+
GzipStreamDecoder createDecoder() {
263264
HttpHeaders headers = serverHttpResponse.getHeaders();
264265
boolean isGzip = headers.containsKey(Constants.CONTENT_ENCODING)
265266
&& headers.getFirst(Constants.CONTENT_ENCODING)
@@ -278,9 +279,16 @@ private Flux<? extends DataBuffer> appendResponse(final Publisher<? extends Data
278279
byte[] inBytes = new byte[ro.remaining()];
279280
ro.get(inBytes);
280281

281-
byte[] processedBytes = Objects.nonNull(decoder) ? decoder.decode(inBytes) : inBytes;
282-
if (processedBytes.length > 0) {
283-
extractor.accept(processedBytes);
282+
if (Objects.nonNull(decoder)) {
283+
// Push bounded slices straight into the extractor; once its budget
284+
// is exhausted the decoder stops inflating, and later chunks skip
285+
// decompression entirely. Forwarded bytes are untouched either way.
286+
decoder.decode(inBytes, slice -> {
287+
extractor.accept(slice);
288+
return extractor.isActive();
289+
});
290+
} else {
291+
extractor.accept(inBytes);
284292
}
285293
});
286294
} catch (Exception e) {
@@ -354,6 +362,10 @@ static final class ResponseUsageExtractor {
354362
this.eventStream = eventStream;
355363
}
356364

365+
synchronized boolean isActive() {
366+
return !stopped && !invalid && !finished;
367+
}
368+
357369
synchronized void accept(final byte[] bytes) {
358370
if (stopped || invalid || finished) {
359371
return;

‎shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-token-limiter/src/main/java/org/apache/shenyu/plugin/ai/token/limiter/GzipStreamDecoder.java‎

Lines changed: 45 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,8 @@
2121
import org.slf4j.LoggerFactory;
2222

2323
import java.io.ByteArrayOutputStream;
24+
import java.util.Arrays;
25+
import java.util.function.Predicate;
2426
import java.util.zip.DataFormatException;
2527
import java.util.zip.Inflater;
2628

@@ -40,44 +42,78 @@ class GzipStreamDecoder {
4042

4143
private boolean abandoned;
4244

45+
private boolean closed;
46+
4347
/**
44-
* Decode a chunk of gzip data.
48+
* Decode a chunk of gzip data, collecting the whole expanded chunk.
49+
* Only for callers that can afford the full expansion, such as tests; the
50+
* response observation path must use {@link #decode(byte[], Predicate)} so
51+
* the inspection budget bounds the decompression work itself.
4552
* @param inBytes compressed input bytes
4653
* @return decompressed bytes, or empty array if header incomplete or abandoned
4754
*/
4855
byte[] decode(final byte[] inBytes) {
49-
if (abandoned) {
50-
return new byte[0];
56+
ByteArrayOutputStream collected = new ByteArrayOutputStream();
57+
decode(inBytes, slice -> {
58+
collected.writeBytes(slice);
59+
return true;
60+
});
61+
return collected.toByteArray();
62+
}
63+
64+
/**
65+
* Decode a chunk of gzip data, pushing each decompressed slice straight into
66+
* the sink without ever materializing the whole expanded chunk. When the sink
67+
* reports exhaustion (returns {@code false}) inflation stops immediately and
68+
* the decoder abandons further input, so a highly compressible chunk cannot
69+
* allocate or inflate beyond the observer's budget. The compressed input is
70+
* only observed here; the forwarded response bytes are untouched.
71+
* @param inBytes compressed input bytes
72+
* @param sink receives a copy of each decompressed slice; returns whether observation should continue
73+
*/
74+
void decode(final byte[] inBytes, final Predicate<byte[]> sink) {
75+
if (abandoned || closed) {
76+
return;
5177
}
5278

5379
int offset = 0;
5480
if (!headerState.isComplete()) {
5581
offset = headerState.process(inBytes);
5682
if (headerState.isCapacityExceeded()) {
5783
abandoned = true;
58-
return new byte[0];
84+
return;
5985
}
6086
if (!headerState.isComplete()) {
61-
return new byte[0];
87+
return;
6288
}
6389
}
6490

6591
inflater.setInput(inBytes, offset, inBytes.length - offset);
66-
ByteArrayOutputStream baos = new ByteArrayOutputStream();
6792
try {
6893
int cnt;
6994
while (!inflater.needsInput() && (cnt = inflater.inflate(decompressBuffer)) > 0) {
70-
baos.write(decompressBuffer, 0, cnt);
95+
if (!sink.test(Arrays.copyOf(decompressBuffer, cnt))) {
96+
// The observer budget is exhausted; leave the remaining input
97+
// un-inflated instead of expanding it into a discarded buffer.
98+
abandoned = true;
99+
return;
100+
}
71101
}
72102
} catch (DataFormatException ex) {
73103
LOG.error("Inflater decompression failed", ex);
74104
abandoned = true;
75-
return new byte[0];
76105
}
77-
return baos.toByteArray();
78106
}
79107

108+
/**
109+
* Release the inflater. Idempotent so success, error and cancellation paths
110+
* can all close the decoder without a double end.
111+
*/
80112
void close() {
113+
if (closed) {
114+
return;
115+
}
116+
closed = true;
81117
inflater.end();
82118
}
83119

0 commit comments

Comments
 (0)