Skip to content

Commit 562017c

Browse files
authored
fix(mcp): release collected response buffers (#7203)
1 parent 01766dc commit 562017c

2 files changed

Lines changed: 97 additions & 4 deletions

File tree

‎shenyu-plugin/shenyu-plugin-mcp-server/src/main/java/org/apache/shenyu/plugin/mcp/server/response/NonCommittingMcpResponseDecorator.java‎

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@
2323
import org.slf4j.Logger;
2424
import org.slf4j.LoggerFactory;
2525
import org.springframework.core.io.buffer.DataBuffer;
26+
import org.springframework.core.io.buffer.DataBufferUtils;
2627
import org.springframework.http.server.reactive.ServerHttpResponse;
2728
import org.springframework.http.server.reactive.ServerHttpResponseDecorator;
2829
import reactor.core.publisher.Flux;
@@ -83,6 +84,7 @@ public Mono<Void> writeWith(final Publisher<? extends DataBuffer> body) {
8384

8485
return Flux.from(body)
8586
.collectList()
87+
.doOnDiscard(DataBuffer.class, DataBufferUtils::release)
8688
.doOnNext(this::processResponseData)
8789
.then()
8890
.doOnSuccess(aVoid -> LOG.debug("Successfully completed writeWith for session: {}", sessionId))
@@ -96,6 +98,7 @@ public Mono<Void> writeAndFlushWith(final Publisher<? extends Publisher<? extend
9698
return Flux.from(body)
9799
.flatMap(Flux::from)
98100
.collectList()
101+
.doOnDiscard(DataBuffer.class, DataBufferUtils::release)
99102
.doOnNext(this::processResponseData)
100103
.then()
101104
.doOnSuccess(aVoid -> LOG.debug("Successfully completed writeAndFlushWith for session: {}", sessionId))
@@ -146,10 +149,14 @@ private void processResponseData(final java.util.List<? extends DataBuffer> data
146149
private String aggregateDataBuffers(final java.util.List<? extends DataBuffer> dataBuffers) {
147150
final StringBuilder responseBuilder = new StringBuilder();
148151

149-
for (DataBuffer buffer : dataBuffers) {
150-
final byte[] bytes = new byte[buffer.readableByteCount()];
151-
buffer.read(bytes);
152-
responseBuilder.append(new String(bytes, StandardCharsets.UTF_8));
152+
try {
153+
for (DataBuffer buffer : dataBuffers) {
154+
final byte[] bytes = new byte[buffer.readableByteCount()];
155+
buffer.read(bytes);
156+
responseBuilder.append(new String(bytes, StandardCharsets.UTF_8));
157+
}
158+
} finally {
159+
dataBuffers.forEach(DataBufferUtils::release);
153160
}
154161

155162
return responseBuilder.toString();
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
/*
2+
* Licensed to the Apache Software Foundation (ASF) under one or more
3+
* contributor license agreements. See the NOTICE file distributed with
4+
* this work for additional information regarding copyright ownership.
5+
* The ASF licenses this file to You under the Apache License, Version 2.0
6+
* (the "License"); you may not use this file except in compliance with
7+
* the License. You may obtain a copy of the License at
8+
*
9+
* http://www.apache.org/licenses/LICENSE-2.0
10+
*
11+
* Unless required by applicable law or agreed to in writing, software
12+
* distributed under the License is distributed on an "AS IS" BASIS,
13+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+
* See the License for the specific language governing permissions and
15+
* limitations under the License.
16+
*/
17+
18+
package org.apache.shenyu.plugin.mcp.server.response;
19+
20+
import io.netty.buffer.PooledByteBufAllocator;
21+
import org.junit.jupiter.api.Test;
22+
import org.junit.jupiter.params.ParameterizedTest;
23+
import org.junit.jupiter.params.provider.ValueSource;
24+
import org.springframework.core.io.buffer.NettyDataBuffer;
25+
import org.springframework.core.io.buffer.NettyDataBufferFactory;
26+
import org.springframework.mock.http.server.reactive.MockServerHttpResponse;
27+
import reactor.core.publisher.Mono;
28+
import reactor.core.publisher.Flux;
29+
import reactor.test.StepVerifier;
30+
31+
import java.nio.charset.StandardCharsets;
32+
import java.util.concurrent.CompletableFuture;
33+
34+
import static org.junit.jupiter.api.Assertions.assertEquals;
35+
import static org.junit.jupiter.api.Assertions.assertTrue;
36+
37+
/**
38+
* Test cases for {@link NonCommittingMcpResponseDecorator}.
39+
*/
40+
public final class NonCommittingMcpResponseDecoratorTest {
41+
42+
@ParameterizedTest
43+
@ValueSource(booleans = {false, true})
44+
void releasesCollectedBufferOnUpstreamError(final boolean flush) {
45+
NettyDataBuffer buffer = new NettyDataBufferFactory(PooledByteBufAllocator.DEFAULT).allocateBuffer();
46+
buffer.write("partial".getBytes(StandardCharsets.UTF_8));
47+
CompletableFuture<String> future = new CompletableFuture<>();
48+
NonCommittingMcpResponseDecorator decorator = new NonCommittingMcpResponseDecorator(new MockServerHttpResponse(), "session", future, null);
49+
IllegalStateException failure = new IllegalStateException("upstream failed");
50+
Flux<NettyDataBuffer> body = Flux.concat(Mono.just(buffer), Mono.error(failure));
51+
52+
StepVerifier.create(flush ? decorator.writeAndFlushWith(Flux.just(body)) : decorator.writeWith(body))
53+
.expectErrorMatches(error -> error == failure).verify();
54+
55+
assertEquals(0, buffer.getNativeBuffer().refCnt());
56+
assertTrue(future.isCompletedExceptionally());
57+
}
58+
59+
@ParameterizedTest
60+
@ValueSource(booleans = {false, true})
61+
void releasesCollectedBufferOnCancellation(final boolean flush) {
62+
NettyDataBuffer buffer = new NettyDataBufferFactory(PooledByteBufAllocator.DEFAULT).allocateBuffer();
63+
buffer.write("partial".getBytes(StandardCharsets.UTF_8));
64+
NonCommittingMcpResponseDecorator decorator = new NonCommittingMcpResponseDecorator(new MockServerHttpResponse(), "session", new CompletableFuture<>(), null);
65+
Flux<NettyDataBuffer> body = Flux.concat(Mono.just(buffer), Mono.never());
66+
67+
StepVerifier.create(flush ? decorator.writeAndFlushWith(Flux.just(body)) : decorator.writeWith(body))
68+
.thenCancel().verify();
69+
70+
assertEquals(0, buffer.getNativeBuffer().refCnt());
71+
}
72+
73+
@Test
74+
public void testWriteWithReleasesCollectedBuffers() {
75+
NettyDataBufferFactory bufferFactory = new NettyDataBufferFactory(PooledByteBufAllocator.DEFAULT);
76+
NettyDataBuffer buffer = (NettyDataBuffer) bufferFactory.wrap("response".getBytes(StandardCharsets.UTF_8));
77+
CompletableFuture<String> responseFuture = new CompletableFuture<>();
78+
NonCommittingMcpResponseDecorator decorator = new NonCommittingMcpResponseDecorator(
79+
new MockServerHttpResponse(), "session", responseFuture, null);
80+
81+
decorator.writeWith(Mono.just(buffer)).block();
82+
83+
assertEquals("response", responseFuture.join());
84+
assertEquals(0, buffer.getNativeBuffer().refCnt());
85+
}
86+
}

0 commit comments

Comments
 (0)