Skip to content

Adds flushing after each buffer write in RestClientProxyExchange #3481

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -22,12 +22,14 @@

import org.springframework.cloud.gateway.server.mvc.common.MvcUtils;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.util.StreamUtils;
import org.springframework.util.Assert;
import org.springframework.web.client.RestClient;
import org.springframework.web.servlet.function.ServerResponse;

public class RestClientProxyExchange implements ProxyExchange {

private static final int BUFFER_SIZE = 16384;

private final RestClient restClient;

public RestClientProxyExchange(RestClient restClient) {
Expand All @@ -44,7 +46,33 @@ public ServerResponse exchange(Request request) {
}

private static int copyBody(Request request, OutputStream outputStream) throws IOException {
return StreamUtils.copy(request.getServerRequest().servletRequest().getInputStream(), outputStream);
return copy(request.getServerRequest().servletRequest().getInputStream(), outputStream);
}

private static int copy(InputStream inputStream, OutputStream outputStream) throws IOException {
Assert.notNull(inputStream, "No InputStream specified");
Assert.notNull(outputStream, "No OutputStream specified");

int readBytes;
var totalReadBytes = 0;
var buffer = new byte[BUFFER_SIZE];

while ((readBytes = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, readBytes);
outputStream.flush();
if (totalReadBytes < Integer.MAX_VALUE) {
try {
totalReadBytes = Math.addExact(totalReadBytes, readBytes);
}
catch (ArithmeticException e) {
totalReadBytes = Integer.MAX_VALUE;
}
}
}

outputStream.flush();

return totalReadBytes;
}

private static ServerResponse doExchange(Request request, ClientHttpResponse clientResponse) throws IOException {
Expand All @@ -59,7 +87,7 @@ private static ServerResponse doExchange(Request request, ClientHttpResponse cli
InputStream inputStream = MvcUtils.getAttribute(request.getServerRequest(),
MvcUtils.CLIENT_RESPONSE_INPUT_STREAM_ATTR);
// copy body from request to clientHttpRequest
StreamUtils.copy(inputStream, httpServletResponse.getOutputStream());
copy(inputStream, httpServletResponse.getOutputStream());
}
return null;
});
Expand Down