Skip to content

Commit 3e98f90

Browse files
committed
Update Cronet to latest release. Move Away from ExperimentalAPIs in cronet.
1 parent 58de563 commit 3e98f90

File tree

8 files changed

+63
-189
lines changed

8 files changed

+63
-189
lines changed

cronet/src/main/java/io/grpc/cronet/CronetChannelBuilder.java

Lines changed: 11 additions & 81 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,6 @@
2020
import static com.google.common.base.Preconditions.checkNotNull;
2121
import static io.grpc.internal.GrpcUtil.DEFAULT_MAX_MESSAGE_SIZE;
2222

23-
import android.util.Log;
2423
import com.google.common.annotations.VisibleForTesting;
2524
import com.google.common.base.Preconditions;
2625
import com.google.common.util.concurrent.MoreExecutors;
@@ -38,8 +37,6 @@
3837
import io.grpc.internal.ManagedChannelImplBuilder.ClientTransportFactoryBuilder;
3938
import io.grpc.internal.SharedResourceHolder;
4039
import io.grpc.internal.TransportTracer;
41-
import java.lang.reflect.InvocationTargetException;
42-
import java.lang.reflect.Method;
4340
import java.net.InetSocketAddress;
4441
import java.net.SocketAddress;
4542
import java.util.Collection;
@@ -49,15 +46,11 @@
4946
import javax.annotation.Nullable;
5047
import org.chromium.net.BidirectionalStream;
5148
import org.chromium.net.CronetEngine;
52-
import org.chromium.net.ExperimentalBidirectionalStream;
53-
import org.chromium.net.ExperimentalCronetEngine;
5449

5550
/** Convenience class for building channels with the cronet transport. */
5651
@ExperimentalApi("There is no plan to make this API stable, given transport API instability")
5752
public final class CronetChannelBuilder extends ForwardingChannelBuilder2<CronetChannelBuilder> {
5853

59-
private static final String LOG_TAG = "CronetChannelBuilder";
60-
6154
/** BidirectionalStream.Builder factory used for getting the gRPC BidirectionalStream. */
6255
public static abstract class StreamBuilderFactory {
6356
public abstract BidirectionalStream.Builder newBidirectionalStreamBuilder(
@@ -91,7 +84,7 @@ public static CronetChannelBuilder forAddress(String name, int port) {
9184

9285
private final CronetEngine cronetEngine;
9386
private final ManagedChannelImplBuilder managedChannelImplBuilder;
94-
private TransportTracer.Factory transportTracerFactory = TransportTracer.getDefaultFactory();
87+
private final TransportTracer.Factory transportTracerFactory = TransportTracer.getDefaultFactory();
9588

9689
private boolean alwaysUsePut = false;
9790

@@ -139,7 +132,7 @@ protected ManagedChannelBuilder<?> delegate() {
139132
* Sets the maximum message size allowed to be received on the channel. If not called,
140133
* defaults to {@link io.grpc.internal.GrpcUtil#DEFAULT_MAX_MESSAGE_SIZE}.
141134
*/
142-
public final CronetChannelBuilder maxMessageSize(int maxMessageSize) {
135+
public CronetChannelBuilder maxMessageSize(int maxMessageSize) {
143136
checkArgument(maxMessageSize >= 0, "maxMessageSize must be >= 0");
144137
this.maxMessageSize = maxMessageSize;
145138
return this;
@@ -148,7 +141,7 @@ public final CronetChannelBuilder maxMessageSize(int maxMessageSize) {
148141
/**
149142
* Sets the Cronet channel to always use PUT instead of POST. Defaults to false.
150143
*/
151-
public final CronetChannelBuilder alwaysUsePut(boolean enable) {
144+
public CronetChannelBuilder alwaysUsePut(boolean enable) {
152145
this.alwaysUsePut = enable;
153146
return this;
154147
}
@@ -170,7 +163,7 @@ public final CronetChannelBuilder alwaysUsePut(boolean enable) {
170163
* application.
171164
* @return the builder to facilitate chaining.
172165
*/
173-
final CronetChannelBuilder setTrafficStatsTag(int tag) {
166+
CronetChannelBuilder setTrafficStatsTag(int tag) {
174167
trafficStatsTagSet = true;
175168
trafficStatsTag = tag;
176169
return this;
@@ -180,7 +173,7 @@ final CronetChannelBuilder setTrafficStatsTag(int tag) {
180173
* Sets specific UID to use when accounting socket traffic caused by this channel. See {@link
181174
* android.net.TrafficStats} for more information. Designed for use when performing an operation
182175
* on behalf of another application. Caller must hold {@link
183-
* android.Manifest.permission#MODIFY_NETWORK_ACCOUNTING} permission. By default traffic is
176+
* android.Manifest.permission#UPDATE_DEVICE_STATS} permission. By default traffic is
184177
* attributed to UID of caller.
185178
*
186179
* <p><b>NOTE:</b>Setting a UID disallows sharing of sockets with channels with other UIDs, which
@@ -191,7 +184,7 @@ final CronetChannelBuilder setTrafficStatsTag(int tag) {
191184
* @param uid the UID to attribute socket traffic caused by this channel.
192185
* @return the builder to facilitate chaining.
193186
*/
194-
final CronetChannelBuilder setTrafficStatsUid(int uid) {
187+
CronetChannelBuilder setTrafficStatsUid(int uid) {
195188
trafficStatsUidSet = true;
196189
trafficStatsUid = uid;
197190
return this;
@@ -207,7 +200,7 @@ final CronetChannelBuilder setTrafficStatsUid(int uid) {
207200
*
208201
* @since 1.12.0
209202
*/
210-
public final CronetChannelBuilder scheduledExecutorService(
203+
public CronetChannelBuilder scheduledExecutorService(
211204
ScheduledExecutorService scheduledExecutorService) {
212205
this.scheduledExecutorService =
213206
checkNotNull(scheduledExecutorService, "scheduledExecutorService");
@@ -296,11 +289,6 @@ public Collection<Class<? extends SocketAddress>> getSupportedSocketAddressTypes
296289
* StreamBuilderFactory impl that applies TrafficStats tags to stream builders that are produced.
297290
*/
298291
private static class TaggingStreamFactory extends StreamBuilderFactory {
299-
private static volatile boolean loadSetTrafficStatsTagAttempted;
300-
private static volatile boolean loadSetTrafficStatsUidAttempted;
301-
private static volatile Method setTrafficStatsTagMethod;
302-
private static volatile Method setTrafficStatsUidMethod;
303-
304292
private final CronetEngine cronetEngine;
305293
private final boolean trafficStatsTagSet;
306294
private final int trafficStatsTag;
@@ -323,74 +311,16 @@ private static class TaggingStreamFactory extends StreamBuilderFactory {
323311
@Override
324312
public BidirectionalStream.Builder newBidirectionalStreamBuilder(
325313
String url, BidirectionalStream.Callback callback, Executor executor) {
326-
ExperimentalBidirectionalStream.Builder builder =
327-
((ExperimentalCronetEngine) cronetEngine)
314+
BidirectionalStream.Builder builder =
315+
cronetEngine
328316
.newBidirectionalStreamBuilder(url, callback, executor);
329317
if (trafficStatsTagSet) {
330-
setTrafficStatsTag(builder, trafficStatsTag);
318+
builder.setTrafficStatsTag(trafficStatsTag);
331319
}
332320
if (trafficStatsUidSet) {
333-
setTrafficStatsUid(builder, trafficStatsUid);
321+
builder.setTrafficStatsUid(trafficStatsUid);
334322
}
335323
return builder;
336324
}
337-
338-
private static void setTrafficStatsTag(ExperimentalBidirectionalStream.Builder builder,
339-
int tag) {
340-
if (!loadSetTrafficStatsTagAttempted) {
341-
synchronized (TaggingStreamFactory.class) {
342-
if (!loadSetTrafficStatsTagAttempted) {
343-
try {
344-
setTrafficStatsTagMethod = ExperimentalBidirectionalStream.Builder.class
345-
.getMethod("setTrafficStatsTag", int.class);
346-
} catch (NoSuchMethodException e) {
347-
Log.w(LOG_TAG,
348-
"Failed to load method ExperimentalBidirectionalStream.Builder.setTrafficStatsTag",
349-
e);
350-
} finally {
351-
loadSetTrafficStatsTagAttempted = true;
352-
}
353-
}
354-
}
355-
}
356-
if (setTrafficStatsTagMethod != null) {
357-
try {
358-
setTrafficStatsTagMethod.invoke(builder, tag);
359-
} catch (InvocationTargetException e) {
360-
throw new RuntimeException(e.getCause() == null ? e.getTargetException() : e.getCause());
361-
} catch (IllegalAccessException e) {
362-
Log.w(LOG_TAG, "Failed to set traffic stats tag: " + tag, e);
363-
}
364-
}
365-
}
366-
367-
private static void setTrafficStatsUid(ExperimentalBidirectionalStream.Builder builder,
368-
int uid) {
369-
if (!loadSetTrafficStatsUidAttempted) {
370-
synchronized (TaggingStreamFactory.class) {
371-
if (!loadSetTrafficStatsUidAttempted) {
372-
try {
373-
setTrafficStatsUidMethod = ExperimentalBidirectionalStream.Builder.class
374-
.getMethod("setTrafficStatsUid", int.class);
375-
} catch (NoSuchMethodException e) {
376-
Log.w(LOG_TAG,
377-
"Failed to load method ExperimentalBidirectionalStream.Builder.setTrafficStatsUid",
378-
e);
379-
} finally {
380-
loadSetTrafficStatsUidAttempted = true;
381-
}
382-
}
383-
}
384-
}
385-
if (setTrafficStatsUidMethod != null) {
386-
try {
387-
setTrafficStatsUidMethod.invoke(builder, uid);
388-
} catch (InvocationTargetException e) {
389-
throw new RuntimeException(e.getCause() == null ? e.getTargetException() : e.getCause());
390-
} catch (IllegalAccessException e) {
391-
Log.w(LOG_TAG, "Failed to set traffic stats uid: " + uid, e);
392-
}
393-
}
394-
}
395325
}
396326
}

cronet/src/main/java/io/grpc/cronet/CronetClientStream.java

Lines changed: 8 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -40,11 +40,9 @@
4040
import io.grpc.internal.TransportFrameUtil;
4141
import io.grpc.internal.TransportTracer;
4242
import io.grpc.internal.WritableBuffer;
43-
import java.lang.reflect.InvocationTargetException;
44-
import java.lang.reflect.Method;
4543
import java.nio.Buffer;
4644
import java.nio.ByteBuffer;
47-
import java.nio.charset.Charset;
45+
import java.nio.charset.StandardCharsets;
4846
import java.util.ArrayList;
4947
import java.util.Collection;
5048
import java.util.Collections;
@@ -55,7 +53,6 @@
5553
import javax.annotation.concurrent.GuardedBy;
5654
import org.chromium.net.BidirectionalStream;
5755
import org.chromium.net.CronetException;
58-
import org.chromium.net.ExperimentalBidirectionalStream;
5956
import org.chromium.net.UrlResponseInfo;
6057

6158
/**
@@ -66,9 +63,6 @@ class CronetClientStream extends AbstractClientStream {
6663
private static final ByteBuffer EMPTY_BUFFER = ByteBuffer.allocateDirect(0);
6764
private static final String LOG_TAG = "grpc-java-cronet";
6865

69-
private static volatile boolean loadAddRequestAnnotationAttempted;
70-
private static volatile Method addRequestAnnotationMethod;
71-
7266
@Deprecated
7367
static final CallOptions.Key<Object> CRONET_ANNOTATION_KEY =
7468
CallOptions.Key.create("cronet-annotation");
@@ -194,14 +188,12 @@ public void writeHeaders(Metadata metadata, byte[] payload) {
194188
builder.delayRequestHeadersUntilFirstFlush(true);
195189
}
196190
if (annotation != null || annotations != null) {
197-
ExperimentalBidirectionalStream.Builder expBidiStreamBuilder =
198-
(ExperimentalBidirectionalStream.Builder) builder;
199191
if (annotation != null) {
200-
addRequestAnnotation(expBidiStreamBuilder, annotation);
192+
builder.addRequestAnnotation(annotation);
201193
}
202194
if (annotations != null) {
203195
for (Object o : annotations) {
204-
addRequestAnnotation(expBidiStreamBuilder, o);
196+
builder.addRequestAnnotation(o);
205197
}
206198
}
207199
}
@@ -255,7 +247,7 @@ public void cancel(Status reason) {
255247
class TransportState extends Http2ClientStreamTransportState {
256248
private final Object lock;
257249
@GuardedBy("lock")
258-
private Collection<PendingData> pendingData = new ArrayList<PendingData>();
250+
private final Collection<PendingData> pendingData = new ArrayList<>();
259251
@GuardedBy("lock")
260252
private boolean streamReady;
261253
@GuardedBy("lock")
@@ -367,35 +359,6 @@ private static boolean isApplicationHeader(String key) {
367359
&& !TE_HEADER.name().equalsIgnoreCase(key);
368360
}
369361

370-
private static void addRequestAnnotation(ExperimentalBidirectionalStream.Builder builder,
371-
Object annotation) {
372-
if (!loadAddRequestAnnotationAttempted) {
373-
synchronized (CronetClientStream.class) {
374-
if (!loadAddRequestAnnotationAttempted) {
375-
try {
376-
addRequestAnnotationMethod = ExperimentalBidirectionalStream.Builder.class
377-
.getMethod("addRequestAnnotation", Object.class);
378-
} catch (NoSuchMethodException e) {
379-
Log.w(LOG_TAG,
380-
"Failed to load method ExperimentalBidirectionalStream.Builder.addRequestAnnotation",
381-
e);
382-
} finally {
383-
loadAddRequestAnnotationAttempted = true;
384-
}
385-
}
386-
}
387-
}
388-
if (addRequestAnnotationMethod != null) {
389-
try {
390-
addRequestAnnotationMethod.invoke(builder, annotation);
391-
} catch (InvocationTargetException e) {
392-
throw new RuntimeException(e.getCause() == null ? e.getTargetException() : e.getCause());
393-
} catch (IllegalAccessException e) {
394-
Log.w(LOG_TAG, "Failed to add request annotation: " + annotation, e);
395-
}
396-
}
397-
}
398-
399362
private void setGrpcHeaders(BidirectionalStream.Builder builder) {
400363
// Psuedo-headers are set by cronet.
401364
// All non-pseudo headers must come after pseudo headers.
@@ -409,10 +372,10 @@ private void setGrpcHeaders(BidirectionalStream.Builder builder) {
409372
// String and byte array.
410373
byte[][] serializedHeaders = TransportFrameUtil.toHttp2Headers(headers);
411374
for (int i = 0; i < serializedHeaders.length; i += 2) {
412-
String key = new String(serializedHeaders[i], Charset.forName("UTF-8"));
375+
String key = new String(serializedHeaders[i], StandardCharsets.UTF_8);
413376
// TODO(ericgribkoff): log an error or throw an exception
414377
if (isApplicationHeader(key)) {
415-
String value = new String(serializedHeaders[i + 1], Charset.forName("UTF-8"));
378+
String value = new String(serializedHeaders[i + 1], StandardCharsets.UTF_8);
416379
builder.addHeader(key, value);
417380
}
418381
}
@@ -589,8 +552,8 @@ private void reportHeaders(List<Map.Entry<String, String>> headers, boolean endO
589552

590553
byte[][] headerValues = new byte[headerList.size()][];
591554
for (int i = 0; i < headerList.size(); i += 2) {
592-
headerValues[i] = headerList.get(i).getBytes(Charset.forName("UTF-8"));
593-
headerValues[i + 1] = headerList.get(i + 1).getBytes(Charset.forName("UTF-8"));
555+
headerValues[i] = headerList.get(i).getBytes(StandardCharsets.UTF_8);
556+
headerValues[i + 1] = headerList.get(i + 1).getBytes(StandardCharsets.UTF_8);
594557
}
595558
Metadata metadata =
596559
InternalMetadata.newMetadata(TransportFrameUtil.toRawSerializedHeaders(headerValues));

cronet/src/main/java/io/grpc/cronet/CronetClientTransport.java

Lines changed: 9 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -56,14 +56,15 @@ class CronetClientTransport implements ConnectionClientTransport {
5656
private final Object lock = new Object();
5757
@GuardedBy("lock")
5858
private final Set<CronetClientStream> streams = Collections.newSetFromMap(
59-
new IdentityHashMap<CronetClientStream, Boolean>());
59+
new IdentityHashMap<>());
6060
private final Executor executor;
6161
private final int maxMessageSize;
6262
private final boolean alwaysUsePut;
6363
private final TransportTracer transportTracer;
6464
private Attributes attrs;
6565
private final boolean useGetForSafeMethods;
6666
private final boolean usePutForIdempotentMethods;
67+
private final StreamBuilderFactory streamFactory;
6768
// Indicates the transport is in go-away state: no new streams will be processed,
6869
// but existing streams may continue.
6970
@GuardedBy("lock")
@@ -79,7 +80,6 @@ class CronetClientTransport implements ConnectionClientTransport {
7980
@GuardedBy("lock")
8081
// Whether this transport has started.
8182
private boolean started;
82-
private StreamBuilderFactory streamFactory;
8383

8484
CronetClientTransport(
8585
StreamBuilderFactory streamFactory,
@@ -166,13 +166,10 @@ public Runnable start(Listener listener) {
166166
synchronized (lock) {
167167
started = true;
168168
}
169-
return new Runnable() {
170-
@Override
171-
public void run() {
172-
attrs = CronetClientTransport.this.listener.filterTransport(attrs);
173-
// Listener callbacks should not be called simultaneously
174-
CronetClientTransport.this.listener.transportReady();
175-
}
169+
return () -> {
170+
attrs = CronetClientTransport.this.listener.filterTransport(attrs);
171+
// Listener callbacks should not be called simultaneously
172+
CronetClientTransport.this.listener.transportReady();
176173
};
177174
}
178175

@@ -205,9 +202,9 @@ public void shutdownNow(Status status) {
205202
// streams.remove()
206203
streamsCopy = new ArrayList<>(streams);
207204
}
208-
for (int i = 0; i < streamsCopy.size(); i++) {
205+
for (CronetClientStream cronetClientStream : streamsCopy) {
209206
// Avoid deadlock by calling into stream without lock held
210-
streamsCopy.get(i).cancel(status);
207+
cronetClientStream.cancel(status);
211208
}
212209
stopIfNecessary();
213210
}
@@ -255,7 +252,7 @@ public InternalLogId getLogId() {
255252
*/
256253
void stopIfNecessary() {
257254
synchronized (lock) {
258-
if (goAway && !stopped && streams.size() == 0) {
255+
if (goAway && !stopped && streams.isEmpty()) {
259256
stopped = true;
260257
} else {
261258
return;

cronet/src/main/java/io/grpc/cronet/InternalCronetChannelBuilder.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,7 @@ public static void setTrafficStatsTag(CronetChannelBuilder builder, int tag) {
4747
* Sets specific UID to use when accounting socket traffic caused by this channel. See {@link
4848
* android.net.TrafficStats} for more information. Designed for use when performing an operation
4949
* on behalf of another application. Caller must hold {@link
50-
* android.Manifest.permission#MODIFY_NETWORK_ACCOUNTING} permission. By default traffic is
50+
* android.Manifest.permission#UPDATE_DEVICE_STATS} permission. By default traffic is
5151
* attributed to UID of caller.
5252
*
5353
* <p><b>NOTE:</b>Setting a UID disallows sharing of sockets with channels with other UIDs, which

cronet/src/test/java/io/grpc/cronet/CronetChannelBuilderTest.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@
3535
import io.grpc.testing.TestMethodDescriptors;
3636
import java.net.InetSocketAddress;
3737
import java.util.concurrent.ScheduledExecutorService;
38-
import org.chromium.net.ExperimentalCronetEngine;
38+
import org.chromium.net.CronetEngine;
3939
import org.junit.Rule;
4040
import org.junit.Test;
4141
import org.junit.runner.RunWith;
@@ -50,7 +50,7 @@
5050
public final class CronetChannelBuilderTest {
5151
@Rule public final MockitoRule mocks = MockitoJUnit.rule();
5252

53-
@Mock private ExperimentalCronetEngine mockEngine;
53+
@Mock private CronetEngine mockEngine;
5454
@Mock private ChannelLogger channelLogger;
5555

5656
private final ClientStreamTracer[] tracers =

0 commit comments

Comments
 (0)