Skip to content
Open
Show file tree
Hide file tree
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 @@ -375,8 +375,7 @@ private void handleResponse(Response response, BiConsumer<GrpcResponse, Boolean>
onResponse.accept(responseUnsupportedGrpcEncoding(encoding), false);
return;
}
try {
GzipSource gzipSource = new GzipSource(wireBuffer);
try (GzipSource gzipSource = new GzipSource(wireBuffer)) {
Buffer decompressedBuffer = new Buffer();
while (decompressedBuffer.size() <= maxResponseBodySize) {
long n = gzipSource.read(decompressedBuffer, readUpTo - decompressedBuffer.size());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -214,8 +214,8 @@ private void handleResponse(
long readUpTo =
maxResponseBodySize == Long.MAX_VALUE ? Long.MAX_VALUE : maxResponseBodySize + 1;
Buffer buffer = new Buffer();
try {
Source source = decompress ? new GzipSource(body.source()) : body.source();
// Closing the GzipSource wrapper ensures deterministic release of its native Inflater.
try (Source source = decompress ? new GzipSource(body.source()) : body.source()) {
while (buffer.size() <= maxResponseBodySize) {
long n = source.read(buffer, readUpTo - buffer.size());
if (n == -1L) {
Expand Down Expand Up @@ -313,10 +313,12 @@ public MediaType contentType() {
@Override
public void writeTo(BufferedSink bufferedSink) throws IOException {
if (compressor != null) {
BufferedSink compressedSink =
Okio.buffer(Okio.sink(compressor.compress(bufferedSink.outputStream())));
requestBodyWriter.writeMessage(compressedSink.outputStream());
compressedSink.close();
// writeMessage can throw, which must still close the compressed sink to release the
// underlying GZIPOutputStream's native Deflater.
try (BufferedSink compressedSink =
Okio.buffer(Okio.sink(compressor.compress(bufferedSink.outputStream())))) {
requestBodyWriter.writeMessage(compressedSink.outputStream());
}
} else {
requestBodyWriter.writeMessage(bufferedSink.outputStream());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,13 @@
import io.opentelemetry.sdk.common.export.GrpcStatusCode;
import io.opentelemetry.sdk.common.export.MessageWriter;
import io.opentelemetry.sdk.common.export.RetryPolicy;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.security.Security;
import java.time.Duration;
import java.util.Collections;
Expand All @@ -34,6 +37,7 @@
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.zip.GZIPOutputStream;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLException;
import okhttp3.Headers;
Expand Down Expand Up @@ -108,6 +112,75 @@ void handleResponse_resolvesTrailerStatusAndMessageAfterConsumingBody() {
.containsExactly((byte) 'o', (byte) 'k', (byte) '!');
}

@Test
void handleResponse_gzipResponse_success() throws IOException {
OkHttpGrpcSender sender = createSender(Long.MAX_VALUE);
AtomicReference<GrpcResponse> responseRef = new AtomicReference<>();
byte[] message = "ok!".getBytes(StandardCharsets.UTF_8);

sender.handleResponse(
gzipEncodedResponse(compressedFrame(gzip(message)), "0"), responseRef::set);

assertThat(responseRef.get().getStatusCode()).isEqualTo(GrpcStatusCode.OK);
assertThat(responseRef.get().getResponseMessage()).containsExactly(message);
}

@Test
void handleResponse_gzipResponse_oversized() throws IOException {
// The compressed payload fits within the limit, but the decompressed message does not.
long maxResponseBodySize = 128;
byte[] compressed = gzip(new byte[4096]);
assertThat((long) compressed.length).isLessThan(maxResponseBodySize);
OkHttpGrpcSender sender = createSender(maxResponseBodySize);
AtomicReference<GrpcResponse> responseRef = new AtomicReference<>();

sender.handleResponse(gzipEncodedResponse(compressedFrame(compressed), "0"), responseRef::set);

assertThat(responseRef.get().getStatusCode()).isEqualTo(GrpcStatusCode.RESOURCE_EXHAUSTED);
assertThat(responseRef.get().getResponseMessage()).isEmpty();
}

@Test
void handleResponse_gzipResponse_corrupt() {
OkHttpGrpcSender sender = createSender(Long.MAX_VALUE);
AtomicReference<GrpcResponse> responseRef = new AtomicReference<>();
byte[] notGzip = "not gzip".getBytes(StandardCharsets.UTF_8);

sender.handleResponse(gzipEncodedResponse(compressedFrame(notGzip), "14"), responseRef::set);

assertThat(responseRef.get().getStatusCode()).isEqualTo(GrpcStatusCode.UNAVAILABLE);
assertThat(responseRef.get().getResponseMessage()).isEmpty();
}

private static byte[] gzip(byte[] bytes) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
try (GZIPOutputStream gzipOut = new GZIPOutputStream(out)) {
gzipOut.write(bytes);
}
return out.toByteArray();
}

/** Builds a gRPC message frame with the compression flag set. */
private static byte[] compressedFrame(byte[] payload) {
return ByteBuffer.allocate(5 + payload.length)
.put((byte) 1)
.putInt(payload.length)
.put(payload)
.array();
}

private static Response gzipEncodedResponse(byte[] frame, String grpcStatus) {
return new Response.Builder()
.request(new Request.Builder().url("http://localhost/").build())
.protocol(Protocol.HTTP_2)
.code(200)
.header("grpc-encoding", "gzip")
.body(ResponseBody.create(frame, GRPC_MEDIA_TYPE))
.message("HTTP message")
.trailers(() -> Headers.of("grpc-status", grpcStatus))
.build();
}

private static OkHttpGrpcSender createSender(long maxResponseBodySize) {
return new OkHttpGrpcSender(
"http://localhost",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,13 @@
import com.linecorp.armeria.testing.junit5.server.SelfSignedCertificateExtension;
import io.opentelemetry.exporter.internal.TlsUtil;
import io.opentelemetry.sdk.common.CompletableResultCode;
import io.opentelemetry.sdk.common.export.Compressor;
import io.opentelemetry.sdk.common.export.HttpResponse;
import io.opentelemetry.sdk.common.export.MessageWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Constructor;
import java.net.ServerSocket;
import java.net.URI;
import java.nio.charset.StandardCharsets;
Expand All @@ -32,6 +35,7 @@
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import javax.annotation.Nullable;
import javax.net.ssl.KeyManagerFactory;
Expand All @@ -42,6 +46,9 @@
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okio.Buffer;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;

Expand Down Expand Up @@ -363,6 +370,69 @@ void constructor_usesDefaultTrustManagerWhenTrustManagerIsNull() throws Exceptio
.doesNotThrowAnyException();
}

@Test
void requestBody_compressedWriterThrows_closesCompressedSink() throws Exception {
// A throw from writeMessage must still close the compressed sink, which ensures deterministic
// release of the compressor's native Deflater.
AtomicInteger streamCloseCount = new AtomicInteger();
Compressor trackingCompressor =
new Compressor() {
@Override
public String getEncoding() {
return "fake";
}

@Override
public OutputStream compress(OutputStream outputStream) {
return new OutputStream() {
@Override
public void write(int b) throws IOException {
outputStream.write(b);
}

@Override
public void close() throws IOException {
streamCloseCount.incrementAndGet();
outputStream.close();
}
};
}
};

MessageWriter throwingWriter =
new MessageWriter() {
@Override
public void writeMessage(OutputStream output) throws IOException {
throw new IOException("boom");
}

@Override
public int getContentLength() {
return 0;
}
};

// RequestBodyImpl is a private inner class; construct it via reflection.
Class<?> cls =
Class.forName(
"io.opentelemetry.exporter.sender.okhttp.internal.OkHttpHttpSender$RequestBodyImpl");
Constructor<?> ctor =
cls.getDeclaredConstructor(MessageWriter.class, Compressor.class, MediaType.class);
ctor.setAccessible(true);
RequestBody body =
(RequestBody)
ctor.newInstance(throwingWriter, trackingCompressor, MediaType.parse("text/plain"));

Buffer buffer = new Buffer();
assertThatThrownBy(() -> body.writeTo(buffer))
.isInstanceOf(IOException.class)
.hasMessage("boom");
assertThat(streamCloseCount.get())
.withFailMessage(
"gzip wrapper was not closed, so its native state release is deferred to GC")
.isEqualTo(1);
}

@Test
void constructor_wrapsDefaultTrustManagerFailure() throws Exception {
String originalAlgorithm = Security.getProperty("ssl.TrustManagerFactory.algorithm");
Expand Down
Loading