• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

grpc / grpc-java / #19213

08 May 2024 11:23PM UTC coverage: 88.329% (-0.006%) from 88.335%
#19213

push

github

ejona86
Migrate GlobalInterceptors to ConfiguratorRegistry

This should preserve all the existing behavior of GlobalInterceptors as
used by grpc-gcp-observability, including it disabling the implicit
OpenCensus integration.

Both the old and new API are internal. I hid Configurator and
ConfiguratorRegistry behind Internal-prefixed classes, like had been
done with GlobalInterceptors to further discourage use until the API is
ready.

GlobalInterceptorsTest was modified to become ConfiguratorRegistryTest.

31506 of 35669 relevant lines covered (88.33%)

0.88 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

90.43
/../core/src/main/java/io/grpc/internal/ManagedChannelImplBuilder.java
1
/*
2
 * Copyright 2020 The gRPC Authors
3
 *
4
 * Licensed under the Apache License, Version 2.0 (the "License");
5
 * you may not use this file except in compliance with the License.
6
 * You may obtain a copy of the License at
7
 *
8
 *     http://www.apache.org/licenses/LICENSE-2.0
9
 *
10
 * Unless required by applicable law or agreed to in writing, software
11
 * distributed under the License is distributed on an "AS IS" BASIS,
12
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
 * See the License for the specific language governing permissions and
14
 * limitations under the License.
15
 */
16

17
package io.grpc.internal;
18

19
import static com.google.common.base.Preconditions.checkArgument;
20
import static com.google.common.base.Preconditions.checkNotNull;
21

22
import com.google.common.annotations.VisibleForTesting;
23
import com.google.common.base.Preconditions;
24
import com.google.common.util.concurrent.MoreExecutors;
25
import com.google.errorprone.annotations.DoNotCall;
26
import io.grpc.Attributes;
27
import io.grpc.BinaryLog;
28
import io.grpc.CallCredentials;
29
import io.grpc.ChannelCredentials;
30
import io.grpc.ClientInterceptor;
31
import io.grpc.ClientTransportFilter;
32
import io.grpc.CompressorRegistry;
33
import io.grpc.DecompressorRegistry;
34
import io.grpc.EquivalentAddressGroup;
35
import io.grpc.InternalChannelz;
36
import io.grpc.InternalConfiguratorRegistry;
37
import io.grpc.ManagedChannel;
38
import io.grpc.ManagedChannelBuilder;
39
import io.grpc.MetricSink;
40
import io.grpc.NameResolver;
41
import io.grpc.NameResolverProvider;
42
import io.grpc.NameResolverRegistry;
43
import io.grpc.ProxyDetector;
44
import java.lang.reflect.InvocationTargetException;
45
import java.lang.reflect.Method;
46
import java.net.SocketAddress;
47
import java.net.URI;
48
import java.net.URISyntaxException;
49
import java.util.ArrayList;
50
import java.util.Arrays;
51
import java.util.Collection;
52
import java.util.Collections;
53
import java.util.LinkedHashMap;
54
import java.util.List;
55
import java.util.Map;
56
import java.util.concurrent.Executor;
57
import java.util.concurrent.TimeUnit;
58
import java.util.logging.Level;
59
import java.util.logging.Logger;
60
import javax.annotation.Nullable;
61

62
/**
63
 * Default managed channel builder, for usage in Transport implementations.
64
 */
65
public final class ManagedChannelImplBuilder
66
    extends ManagedChannelBuilder<ManagedChannelImplBuilder> {
67
  private static final String DIRECT_ADDRESS_SCHEME = "directaddress";
68

69
  private static final Logger log = Logger.getLogger(ManagedChannelImplBuilder.class.getName());
1✔
70

71
  @DoNotCall("ClientTransportFactoryBuilder is required, use a constructor")
72
  public static ManagedChannelBuilder<?> forAddress(String name, int port) {
73
    throw new UnsupportedOperationException(
×
74
        "ClientTransportFactoryBuilder is required, use a constructor");
75
  }
76

77
  @DoNotCall("ClientTransportFactoryBuilder is required, use a constructor")
78
  public static ManagedChannelBuilder<?> forTarget(String target) {
79
    throw new UnsupportedOperationException(
×
80
        "ClientTransportFactoryBuilder is required, use a constructor");
81
  }
82

83
  /**
84
   * An idle timeout larger than this would disable idle mode.
85
   */
86
  @VisibleForTesting
87
  static final long IDLE_MODE_MAX_TIMEOUT_DAYS = 30;
88

89
  /**
90
   * The default idle timeout.
91
   */
92
  @VisibleForTesting
93
  static final long IDLE_MODE_DEFAULT_TIMEOUT_MILLIS = TimeUnit.MINUTES.toMillis(30);
1✔
94

95
  /**
96
   * An idle timeout smaller than this would be capped to it.
97
   */
98
  static final long IDLE_MODE_MIN_TIMEOUT_MILLIS = TimeUnit.SECONDS.toMillis(1);
1✔
99

100
  private static final ObjectPool<? extends Executor> DEFAULT_EXECUTOR_POOL =
1✔
101
      SharedResourcePool.forResource(GrpcUtil.SHARED_CHANNEL_EXECUTOR);
1✔
102

103
  private static final DecompressorRegistry DEFAULT_DECOMPRESSOR_REGISTRY =
104
      DecompressorRegistry.getDefaultInstance();
1✔
105

106
  private static final CompressorRegistry DEFAULT_COMPRESSOR_REGISTRY =
107
      CompressorRegistry.getDefaultInstance();
1✔
108

109
  private static final long DEFAULT_RETRY_BUFFER_SIZE_IN_BYTES = 1L << 24;  // 16M
110
  private static final long DEFAULT_PER_RPC_BUFFER_LIMIT_IN_BYTES = 1L << 20; // 1M
111

112
  private static final Method GET_CLIENT_INTERCEPTOR_METHOD;
113

114
  static {
115
    Method getClientInterceptorMethod = null;
1✔
116
    try {
117
      Class<?> censusStatsAccessor =
1✔
118
          Class.forName("io.grpc.census.InternalCensusStatsAccessor");
1✔
119
      getClientInterceptorMethod =
1✔
120
          censusStatsAccessor.getDeclaredMethod(
1✔
121
              "getClientInterceptor",
122
              boolean.class,
123
              boolean.class,
124
              boolean.class,
125
              boolean.class);
126
    } catch (ClassNotFoundException e) {
1✔
127
      // Replace these separate catch statements with multicatch when Android min-API >= 19
128
      log.log(Level.FINE, "Unable to apply census stats", e);
1✔
129
    } catch (NoSuchMethodException e) {
×
130
      log.log(Level.FINE, "Unable to apply census stats", e);
×
131
    }
1✔
132
    GET_CLIENT_INTERCEPTOR_METHOD = getClientInterceptorMethod;
1✔
133
  }
1✔
134

135

136
  ObjectPool<? extends Executor> executorPool = DEFAULT_EXECUTOR_POOL;
1✔
137

138
  ObjectPool<? extends Executor> offloadExecutorPool = DEFAULT_EXECUTOR_POOL;
1✔
139

140
  private final List<ClientInterceptor> interceptors = new ArrayList<>();
1✔
141
  NameResolverRegistry nameResolverRegistry = NameResolverRegistry.getDefaultRegistry();
1✔
142

143
  final List<ClientTransportFilter> transportFilters = new ArrayList<>();
1✔
144

145
  final String target;
146
  @Nullable
147
  final ChannelCredentials channelCredentials;
148
  @Nullable
149
  final CallCredentials callCredentials;
150

151
  @Nullable
152
  private final SocketAddress directServerAddress;
153

154
  @Nullable
155
  String userAgent;
156

157
  @Nullable
158
  String authorityOverride;
159

160
  String defaultLbPolicy = GrpcUtil.DEFAULT_LB_POLICY;
1✔
161

162
  boolean fullStreamDecompression;
163

164
  DecompressorRegistry decompressorRegistry = DEFAULT_DECOMPRESSOR_REGISTRY;
1✔
165

166
  CompressorRegistry compressorRegistry = DEFAULT_COMPRESSOR_REGISTRY;
1✔
167

168
  long idleTimeoutMillis = IDLE_MODE_DEFAULT_TIMEOUT_MILLIS;
1✔
169

170
  int maxRetryAttempts = 5;
1✔
171
  int maxHedgedAttempts = 5;
1✔
172
  long retryBufferSize = DEFAULT_RETRY_BUFFER_SIZE_IN_BYTES;
1✔
173
  long perRpcBufferLimit = DEFAULT_PER_RPC_BUFFER_LIMIT_IN_BYTES;
1✔
174
  boolean retryEnabled = true;
1✔
175

176
  InternalChannelz channelz = InternalChannelz.instance();
1✔
177
  int maxTraceEvents;
178

179
  @Nullable
180
  Map<String, ?> defaultServiceConfig;
181
  boolean lookUpServiceConfig = true;
1✔
182

183
  @Nullable
184
  BinaryLog binlog;
185

186
  @Nullable
187
  ProxyDetector proxyDetector;
188

189
  private boolean authorityCheckerDisabled;
190
  private boolean statsEnabled = true;
1✔
191
  private boolean recordStartedRpcs = true;
1✔
192
  private boolean recordFinishedRpcs = true;
1✔
193
  private boolean recordRealTimeMetrics = false;
1✔
194
  private boolean recordRetryMetrics = true;
1✔
195
  private boolean tracingEnabled = true;
1✔
196
  List<MetricSink> metricSinks = new ArrayList<>();
1✔
197

198
  /**
199
   * An interface for Transport implementors to provide the {@link ClientTransportFactory}
200
   * appropriate for the channel.
201
   */
202
  public interface ClientTransportFactoryBuilder {
203
    ClientTransportFactory buildClientTransportFactory();
204
  }
205

206
  /**
207
   * Convenience ClientTransportFactoryBuilder, throws UnsupportedOperationException().
208
   */
209
  public static class UnsupportedClientTransportFactoryBuilder implements
1✔
210
      ClientTransportFactoryBuilder {
211
    @Override
212
    public ClientTransportFactory buildClientTransportFactory() {
213
      throw new UnsupportedOperationException();
×
214
    }
215
  }
216

217
  /**
218
   * An interface for Transport implementors to provide a default port to {@link
219
   * io.grpc.NameResolver} for use in cases where the target string doesn't include a port. The
220
   * default implementation returns {@link GrpcUtil#DEFAULT_PORT_SSL}.
221
   */
222
  public interface ChannelBuilderDefaultPortProvider {
223
    int getDefaultPort();
224
  }
225

226
  /**
227
   * Default implementation of {@link ChannelBuilderDefaultPortProvider} that returns a fixed port.
228
   */
229
  public static final class FixedPortProvider implements ChannelBuilderDefaultPortProvider {
230
    private final int port;
231

232
    public FixedPortProvider(int port) {
1✔
233
      this.port = port;
1✔
234
    }
1✔
235

236
    @Override
237
    public int getDefaultPort() {
238
      return port;
1✔
239
    }
240
  }
241

242
  private static final class ManagedChannelDefaultPortProvider implements
243
      ChannelBuilderDefaultPortProvider {
244
    @Override
245
    public int getDefaultPort() {
246
      return GrpcUtil.DEFAULT_PORT_SSL;
1✔
247
    }
248
  }
249

250
  private final ClientTransportFactoryBuilder clientTransportFactoryBuilder;
251
  private final ChannelBuilderDefaultPortProvider channelBuilderDefaultPortProvider;
252

253
  /**
254
   * Creates a new managed channel builder with a target string, which can be either a valid {@link
255
   * io.grpc.NameResolver}-compliant URI, or an authority string. Transport implementors must
256
   * provide client transport factory builder, and may set custom channel default port provider.
257
   */
258
  public ManagedChannelImplBuilder(String target,
259
      ClientTransportFactoryBuilder clientTransportFactoryBuilder,
260
      @Nullable ChannelBuilderDefaultPortProvider channelBuilderDefaultPortProvider) {
261
    this(target, null, null, clientTransportFactoryBuilder, channelBuilderDefaultPortProvider);
1✔
262
  }
1✔
263

264
  /**
265
   * Creates a new managed channel builder with a target string, which can be either a valid {@link
266
   * io.grpc.NameResolver}-compliant URI, or an authority string. Transport implementors must
267
   * provide client transport factory builder, and may set custom channel default port provider.
268
   *
269
   * @param channelCreds The ChannelCredentials provided by the user. These may be used when
270
   *     creating derivative channels.
271
   */
272
  public ManagedChannelImplBuilder(
273
      String target, @Nullable ChannelCredentials channelCreds, @Nullable CallCredentials callCreds,
274
      ClientTransportFactoryBuilder clientTransportFactoryBuilder,
275
      @Nullable ChannelBuilderDefaultPortProvider channelBuilderDefaultPortProvider) {
1✔
276
    this.target = checkNotNull(target, "target");
1✔
277
    this.channelCredentials = channelCreds;
1✔
278
    this.callCredentials = callCreds;
1✔
279
    this.clientTransportFactoryBuilder = checkNotNull(clientTransportFactoryBuilder,
1✔
280
        "clientTransportFactoryBuilder");
281
    this.directServerAddress = null;
1✔
282

283
    if (channelBuilderDefaultPortProvider != null) {
1✔
284
      this.channelBuilderDefaultPortProvider = channelBuilderDefaultPortProvider;
1✔
285
    } else {
286
      this.channelBuilderDefaultPortProvider = new ManagedChannelDefaultPortProvider();
1✔
287
    }
288
    // TODO(dnvindhya): Move configurator to all the individual builders
289
    InternalConfiguratorRegistry.configureChannelBuilder(this);
1✔
290
  }
1✔
291

292
  /**
293
   * Returns a target string for the SocketAddress. It is only used as a placeholder, because
294
   * DirectAddressNameResolverProvider will not actually try to use it. However, it must be a valid
295
   * URI.
296
   */
297
  @VisibleForTesting
298
  static String makeTargetStringForDirectAddress(SocketAddress address) {
299
    try {
300
      return new URI(DIRECT_ADDRESS_SCHEME, "", "/" + address, null).toString();
1✔
301
    } catch (URISyntaxException e) {
×
302
      // It should not happen.
303
      throw new RuntimeException(e);
×
304
    }
305
  }
306

307
  /**
308
   * Creates a new managed channel builder with the given server address, authority string of the
309
   * channel. Transport implementors must provide client transport factory builder, and may set
310
   * custom channel default port provider.
311
   */
312
  public ManagedChannelImplBuilder(SocketAddress directServerAddress, String authority,
313
      ClientTransportFactoryBuilder clientTransportFactoryBuilder,
314
      @Nullable ChannelBuilderDefaultPortProvider channelBuilderDefaultPortProvider) {
315
    this(directServerAddress, authority, null, null, clientTransportFactoryBuilder,
1✔
316
        channelBuilderDefaultPortProvider);
317
  }
1✔
318

319
  /**
320
   * Creates a new managed channel builder with the given server address, authority string of the
321
   * channel. Transport implementors must provide client transport factory builder, and may set
322
   * custom channel default port provider.
323
   * 
324
   * @param channelCreds The ChannelCredentials provided by the user. These may be used when
325
   *     creating derivative channels.
326
   */
327
  public ManagedChannelImplBuilder(SocketAddress directServerAddress, String authority,
328
      @Nullable ChannelCredentials channelCreds, @Nullable CallCredentials callCreds,
329
      ClientTransportFactoryBuilder clientTransportFactoryBuilder,
330
      @Nullable ChannelBuilderDefaultPortProvider channelBuilderDefaultPortProvider) {
1✔
331
    this.target = makeTargetStringForDirectAddress(directServerAddress);
1✔
332
    this.channelCredentials = channelCreds;
1✔
333
    this.callCredentials = callCreds;
1✔
334
    this.clientTransportFactoryBuilder = checkNotNull(clientTransportFactoryBuilder,
1✔
335
        "clientTransportFactoryBuilder");
336
    this.directServerAddress = directServerAddress;
1✔
337
    NameResolverRegistry reg = new NameResolverRegistry();
1✔
338
    reg.register(new DirectAddressNameResolverProvider(directServerAddress,
1✔
339
        authority));
340
    this.nameResolverRegistry = reg;
1✔
341

342
    if (channelBuilderDefaultPortProvider != null) {
1✔
343
      this.channelBuilderDefaultPortProvider = channelBuilderDefaultPortProvider;
1✔
344
    } else {
345
      this.channelBuilderDefaultPortProvider = new ManagedChannelDefaultPortProvider();
1✔
346
    }
347
    // TODO(dnvindhya): Move configurator to all the individual builders
348
    InternalConfiguratorRegistry.configureChannelBuilder(this);
1✔
349
  }
1✔
350

351
  @Override
352
  public ManagedChannelImplBuilder directExecutor() {
353
    return executor(MoreExecutors.directExecutor());
1✔
354
  }
355

356
  @Override
357
  public ManagedChannelImplBuilder executor(Executor executor) {
358
    if (executor != null) {
1✔
359
      this.executorPool = new FixedObjectPool<>(executor);
1✔
360
    } else {
361
      this.executorPool = DEFAULT_EXECUTOR_POOL;
1✔
362
    }
363
    return this;
1✔
364
  }
365

366
  @Override
367
  public ManagedChannelImplBuilder offloadExecutor(Executor executor) {
368
    if (executor != null) {
1✔
369
      this.offloadExecutorPool = new FixedObjectPool<>(executor);
1✔
370
    } else {
371
      this.offloadExecutorPool = DEFAULT_EXECUTOR_POOL;
1✔
372
    }
373
    return this;
1✔
374
  }
375

376
  @Override
377
  public ManagedChannelImplBuilder intercept(List<ClientInterceptor> interceptors) {
378
    this.interceptors.addAll(interceptors);
1✔
379
    return this;
1✔
380
  }
381

382
  @Override
383
  public ManagedChannelImplBuilder intercept(ClientInterceptor... interceptors) {
384
    return intercept(Arrays.asList(interceptors));
1✔
385
  }
386

387
  @Override
388
  public ManagedChannelImplBuilder addTransportFilter(ClientTransportFilter hook) {
389
    transportFilters.add(checkNotNull(hook, "transport filter"));
1✔
390
    return this;
1✔
391
  }
392

393
  @Deprecated
394
  @Override
395
  public ManagedChannelImplBuilder nameResolverFactory(NameResolver.Factory resolverFactory) {
396
    Preconditions.checkState(directServerAddress == null,
1✔
397
        "directServerAddress is set (%s), which forbids the use of NameResolverFactory",
398
        directServerAddress);
399
    if (resolverFactory != null) {
1✔
400
      NameResolverRegistry reg = new NameResolverRegistry();
1✔
401
      if (resolverFactory instanceof NameResolverProvider) {
1✔
402
        reg.register((NameResolverProvider) resolverFactory);
×
403
      } else {
404
        reg.register(new NameResolverFactoryToProviderFacade(resolverFactory));
1✔
405
      }
406
      this.nameResolverRegistry = reg;
1✔
407
    } else {
1✔
408
      this.nameResolverRegistry = NameResolverRegistry.getDefaultRegistry();
1✔
409
    }
410
    return this;
1✔
411
  }
412

413
  ManagedChannelImplBuilder nameResolverRegistry(NameResolverRegistry resolverRegistry) {
414
    this.nameResolverRegistry = resolverRegistry;
1✔
415
    return this;
1✔
416
  }
417

418
  @Override
419
  public ManagedChannelImplBuilder defaultLoadBalancingPolicy(String policy) {
420
    Preconditions.checkState(directServerAddress == null,
1✔
421
        "directServerAddress is set (%s), which forbids the use of load-balancing policy",
422
        directServerAddress);
423
    Preconditions.checkArgument(policy != null, "policy cannot be null");
1✔
424
    this.defaultLbPolicy = policy;
1✔
425
    return this;
1✔
426
  }
427

428
  @Override
429
  public ManagedChannelImplBuilder decompressorRegistry(DecompressorRegistry registry) {
430
    if (registry != null) {
1✔
431
      this.decompressorRegistry = registry;
1✔
432
    } else {
433
      this.decompressorRegistry = DEFAULT_DECOMPRESSOR_REGISTRY;
1✔
434
    }
435
    return this;
1✔
436
  }
437

438
  @Override
439
  public ManagedChannelImplBuilder compressorRegistry(CompressorRegistry registry) {
440
    if (registry != null) {
1✔
441
      this.compressorRegistry = registry;
1✔
442
    } else {
443
      this.compressorRegistry = DEFAULT_COMPRESSOR_REGISTRY;
1✔
444
    }
445
    return this;
1✔
446
  }
447

448
  @Override
449
  public ManagedChannelImplBuilder userAgent(@Nullable String userAgent) {
450
    this.userAgent = userAgent;
1✔
451
    return this;
1✔
452
  }
453

454
  @Override
455
  public ManagedChannelImplBuilder overrideAuthority(String authority) {
456
    this.authorityOverride = checkAuthority(authority);
1✔
457
    return this;
1✔
458
  }
459

460
  @Override
461
  public ManagedChannelImplBuilder idleTimeout(long value, TimeUnit unit) {
462
    checkArgument(value > 0, "idle timeout is %s, but must be positive", value);
1✔
463
    // We convert to the largest unit to avoid overflow
464
    if (unit.toDays(value) >= IDLE_MODE_MAX_TIMEOUT_DAYS) {
1✔
465
      // This disables idle mode
466
      this.idleTimeoutMillis = ManagedChannelImpl.IDLE_TIMEOUT_MILLIS_DISABLE;
1✔
467
    } else {
468
      this.idleTimeoutMillis = Math.max(unit.toMillis(value), IDLE_MODE_MIN_TIMEOUT_MILLIS);
1✔
469
    }
470
    return this;
1✔
471
  }
472

473
  @Override
474
  public ManagedChannelImplBuilder maxRetryAttempts(int maxRetryAttempts) {
475
    this.maxRetryAttempts = maxRetryAttempts;
1✔
476
    return this;
1✔
477
  }
478

479
  @Override
480
  public ManagedChannelImplBuilder maxHedgedAttempts(int maxHedgedAttempts) {
481
    this.maxHedgedAttempts = maxHedgedAttempts;
1✔
482
    return this;
1✔
483
  }
484

485
  @Override
486
  public ManagedChannelImplBuilder retryBufferSize(long bytes) {
487
    checkArgument(bytes > 0L, "retry buffer size must be positive");
1✔
488
    retryBufferSize = bytes;
1✔
489
    return this;
1✔
490
  }
491

492
  @Override
493
  public ManagedChannelImplBuilder perRpcBufferLimit(long bytes) {
494
    checkArgument(bytes > 0L, "per RPC buffer limit must be positive");
1✔
495
    perRpcBufferLimit = bytes;
1✔
496
    return this;
1✔
497
  }
498

499
  @Override
500
  public ManagedChannelImplBuilder disableRetry() {
501
    retryEnabled = false;
1✔
502
    return this;
1✔
503
  }
504

505
  @Override
506
  public ManagedChannelImplBuilder enableRetry() {
507
    retryEnabled = true;
1✔
508
    return this;
1✔
509
  }
510

511
  @Override
512
  public ManagedChannelImplBuilder setBinaryLog(BinaryLog binlog) {
513
    this.binlog = binlog;
×
514
    return this;
×
515
  }
516

517
  @Override
518
  public ManagedChannelImplBuilder maxTraceEvents(int maxTraceEvents) {
519
    checkArgument(maxTraceEvents >= 0, "maxTraceEvents must be non-negative");
1✔
520
    this.maxTraceEvents = maxTraceEvents;
1✔
521
    return this;
1✔
522
  }
523

524
  @Override
525
  public ManagedChannelImplBuilder proxyDetector(@Nullable ProxyDetector proxyDetector) {
526
    this.proxyDetector = proxyDetector;
1✔
527
    return this;
1✔
528
  }
529

530
  @Override
531
  public ManagedChannelImplBuilder defaultServiceConfig(@Nullable Map<String, ?> serviceConfig) {
532
    // TODO(notcarl): use real parsing
533
    defaultServiceConfig = checkMapEntryTypes(serviceConfig);
1✔
534
    return this;
1✔
535
  }
536

537
  @Nullable
538
  private static Map<String, ?> checkMapEntryTypes(@Nullable Map<?, ?> map) {
539
    if (map == null) {
1✔
540
      return null;
×
541
    }
542
    // Not using ImmutableMap.Builder because of extra guava dependency for Android.
543
    Map<String, Object> parsedMap = new LinkedHashMap<>();
1✔
544
    for (Map.Entry<?, ?> entry : map.entrySet()) {
1✔
545
      checkArgument(
1✔
546
          entry.getKey() instanceof String,
1✔
547
          "The key of the entry '%s' is not of String type", entry);
548

549
      String key = (String) entry.getKey();
1✔
550
      Object value = entry.getValue();
1✔
551
      if (value == null) {
1✔
552
        parsedMap.put(key, null);
1✔
553
      } else if (value instanceof Map) {
1✔
554
        parsedMap.put(key, checkMapEntryTypes((Map<?, ?>) value));
1✔
555
      } else if (value instanceof List) {
1✔
556
        parsedMap.put(key, checkListEntryTypes((List<?>) value));
1✔
557
      } else if (value instanceof String) {
1✔
558
        parsedMap.put(key, value);
1✔
559
      } else if (value instanceof Double) {
1✔
560
        parsedMap.put(key, value);
1✔
561
      } else if (value instanceof Boolean) {
1✔
562
        parsedMap.put(key, value);
1✔
563
      } else {
564
        throw new IllegalArgumentException(
1✔
565
            "The value of the map entry '" + entry + "' is of type '" + value.getClass()
1✔
566
                + "', which is not supported");
567
      }
568
    }
1✔
569
    return Collections.unmodifiableMap(parsedMap);
1✔
570
  }
571

572
  private static List<?> checkListEntryTypes(List<?> list) {
573
    List<Object> parsedList = new ArrayList<>(list.size());
1✔
574
    for (Object value : list) {
1✔
575
      if (value == null) {
1✔
576
        parsedList.add(null);
1✔
577
      } else if (value instanceof Map) {
1✔
578
        parsedList.add(checkMapEntryTypes((Map<?, ?>) value));
1✔
579
      } else if (value instanceof List) {
1✔
580
        parsedList.add(checkListEntryTypes((List<?>) value));
×
581
      } else if (value instanceof String) {
1✔
582
        parsedList.add(value);
1✔
583
      } else if (value instanceof Double) {
1✔
584
        parsedList.add(value);
1✔
585
      } else if (value instanceof Boolean) {
1✔
586
        parsedList.add(value);
1✔
587
      } else {
588
        throw new IllegalArgumentException(
×
589
            "The entry '" + value + "' is of type '" + value.getClass()
×
590
                + "', which is not supported");
591
      }
592
    }
1✔
593
    return Collections.unmodifiableList(parsedList);
1✔
594
  }
595

596
  @Override
597
  public ManagedChannelImplBuilder disableServiceConfigLookUp() {
598
    this.lookUpServiceConfig = false;
1✔
599
    return this;
1✔
600
  }
601

602
  /**
603
   * Disable or enable stats features. Enabled by default.
604
   *
605
   * <p>For the current release, calling {@code setStatsEnabled(true)} may have a side effect that
606
   * disables retry.
607
   */
608
  public void setStatsEnabled(boolean value) {
609
    statsEnabled = value;
1✔
610
  }
1✔
611

612
  /**
613
   * Disable or enable stats recording for RPC upstarts.  Effective only if {@link
614
   * #setStatsEnabled} is set to true.  Enabled by default.
615
   */
616
  public void setStatsRecordStartedRpcs(boolean value) {
617
    recordStartedRpcs = value;
1✔
618
  }
1✔
619

620
  /**
621
   * Disable or enable stats recording for RPC completions.  Effective only if {@link
622
   * #setStatsEnabled} is set to true.  Enabled by default.
623
   */
624
  public void setStatsRecordFinishedRpcs(boolean value) {
625
    recordFinishedRpcs = value;
1✔
626
  }
1✔
627

628
  /**
629
   * Disable or enable real-time metrics recording.  Effective only if {@link #setStatsEnabled} is
630
   * set to true.  Disabled by default.
631
   */
632
  public void setStatsRecordRealTimeMetrics(boolean value) {
633
    recordRealTimeMetrics = value;
×
634
  }
×
635
  
636
  public void setStatsRecordRetryMetrics(boolean value) {
637
    recordRetryMetrics = value;
1✔
638
  }
1✔
639

640
  /**
641
   * Disable or enable tracing features.  Enabled by default.
642
   */
643
  public void setTracingEnabled(boolean value) {
644
    tracingEnabled = value;
1✔
645
  }
1✔
646

647
  /**
648
   * Verifies the authority is valid.
649
   */
650
  @VisibleForTesting
651
  String checkAuthority(String authority) {
652
    if (authorityCheckerDisabled) {
1✔
653
      return authority;
1✔
654
    }
655
    return GrpcUtil.checkAuthority(authority);
1✔
656
  }
657

658
  /** Disable the check whether the authority is valid. */
659
  public ManagedChannelImplBuilder disableCheckAuthority() {
660
    authorityCheckerDisabled = true;
1✔
661
    return this;
1✔
662
  }
663

664
  /** Enable previously disabled authority check. */
665
  public ManagedChannelImplBuilder enableCheckAuthority() {
666
    authorityCheckerDisabled = false;
1✔
667
    return this;
1✔
668
  }
669

670
  @Override
671
  public ManagedChannelImplBuilder addMetricSink(MetricSink metricSink) {
672
    metricSinks.add(checkNotNull(metricSink, "metric sink"));
1✔
673
    return this;
1✔
674
  }
675

676
  @Override
677
  public ManagedChannel build() {
678
    return new ManagedChannelOrphanWrapper(new ManagedChannelImpl(
1✔
679
        this,
680
        clientTransportFactoryBuilder.buildClientTransportFactory(),
1✔
681
        new ExponentialBackoffPolicy.Provider(),
682
        SharedResourcePool.forResource(GrpcUtil.SHARED_CHANNEL_EXECUTOR),
1✔
683
        GrpcUtil.STOPWATCH_SUPPLIER,
684
        getEffectiveInterceptors(),
1✔
685
        TimeProvider.SYSTEM_TIME_PROVIDER));
686
  }
687

688
  // Temporarily disable retry when stats or tracing is enabled to avoid breakage, until we know
689
  // what should be the desired behavior for retry + stats/tracing.
690
  // TODO(zdapeng): FIX IT
691
  @VisibleForTesting
692
  List<ClientInterceptor> getEffectiveInterceptors() {
693
    boolean disableImplicitCensus = InternalConfiguratorRegistry.wasSetConfiguratorsCalled();
1✔
694
    if (disableImplicitCensus) {
1✔
695
      return this.interceptors;
×
696
    }
697
    List<ClientInterceptor> effectiveInterceptors = new ArrayList<>(this.interceptors);
1✔
698
    if (statsEnabled) {
1✔
699
      ClientInterceptor statsInterceptor = null;
1✔
700

701
      if (GET_CLIENT_INTERCEPTOR_METHOD != null) {
1✔
702
        try {
703
          statsInterceptor =
1✔
704
            (ClientInterceptor) GET_CLIENT_INTERCEPTOR_METHOD
705
              .invoke(
1✔
706
                null,
707
                recordStartedRpcs,
1✔
708
                recordFinishedRpcs,
1✔
709
                recordRealTimeMetrics,
1✔
710
                recordRetryMetrics);
1✔
711
        } catch (IllegalAccessException e) {
×
712
          log.log(Level.FINE, "Unable to apply census stats", e);
×
713
        } catch (InvocationTargetException e) {
×
714
          log.log(Level.FINE, "Unable to apply census stats", e);
×
715
        }
1✔
716
      }
717

718
      if (statsInterceptor != null) {
1✔
719
        // First interceptor runs last (see ClientInterceptors.intercept()), so that no
720
        // other interceptor can override the tracer factory we set in CallOptions.
721
        effectiveInterceptors.add(0, statsInterceptor);
1✔
722
      }
723
    }
724
    if (tracingEnabled) {
1✔
725
      ClientInterceptor tracingInterceptor = null;
1✔
726
      try {
727
        Class<?> censusTracingAccessor =
1✔
728
            Class.forName("io.grpc.census.InternalCensusTracingAccessor");
1✔
729
        Method getClientInterceptroMethod =
1✔
730
            censusTracingAccessor.getDeclaredMethod("getClientInterceptor");
1✔
731
        tracingInterceptor = (ClientInterceptor) getClientInterceptroMethod.invoke(null);
1✔
732
      } catch (ClassNotFoundException e) {
1✔
733
        // Replace these separate catch statements with multicatch when Android min-API >= 19
734
        log.log(Level.FINE, "Unable to apply census stats", e);
1✔
735
      } catch (NoSuchMethodException e) {
×
736
        log.log(Level.FINE, "Unable to apply census stats", e);
×
737
      } catch (IllegalAccessException e) {
×
738
        log.log(Level.FINE, "Unable to apply census stats", e);
×
739
      } catch (InvocationTargetException e) {
×
740
        log.log(Level.FINE, "Unable to apply census stats", e);
×
741
      }
1✔
742
      if (tracingInterceptor != null) {
1✔
743
        effectiveInterceptors.add(0, tracingInterceptor);
1✔
744
      }
745
    }
746
    return effectiveInterceptors;
1✔
747
  }
748

749
  /**
750
   * Returns a default port to {@link NameResolver} for use in cases where the target string doesn't
751
   * include a port. The default implementation returns {@link GrpcUtil#DEFAULT_PORT_SSL}.
752
   */
753
  int getDefaultPort() {
754
    return channelBuilderDefaultPortProvider.getDefaultPort();
1✔
755
  }
756

757
  private static class DirectAddressNameResolverProvider extends NameResolverProvider {
758
    final SocketAddress address;
759
    final String authority;
760
    final Collection<Class<? extends SocketAddress>> producedSocketAddressTypes;
761

762
    DirectAddressNameResolverProvider(SocketAddress address, String authority) {
1✔
763
      this.address = address;
1✔
764
      this.authority = authority;
1✔
765
      this.producedSocketAddressTypes
1✔
766
          = Collections.singleton(address.getClass());
1✔
767
    }
1✔
768

769
    @Override
770
    public NameResolver newNameResolver(URI notUsedUri, NameResolver.Args args) {
771
      return new NameResolver() {
1✔
772
        @Override
773
        public String getServiceAuthority() {
774
          return authority;
1✔
775
        }
776

777
        @Override
778
        public void start(Listener2 listener) {
779
          listener.onResult(
1✔
780
              ResolutionResult.newBuilder()
1✔
781
                  .setAddresses(Collections.singletonList(new EquivalentAddressGroup(address)))
1✔
782
                  .setAttributes(Attributes.EMPTY)
1✔
783
                  .build());
1✔
784
        }
1✔
785

786
        @Override
787
        public void shutdown() {}
1✔
788
      };
789
    }
790

791
    @Override
792
    public String getDefaultScheme() {
793
      return DIRECT_ADDRESS_SCHEME;
1✔
794
    }
795

796
    @Override
797
    protected boolean isAvailable() {
798
      return true;
1✔
799
    }
800

801
    @Override
802
    protected int priority() {
803
      return 5;
1✔
804
    }
805

806
    @Override
807
    public Collection<Class<? extends SocketAddress>> getProducedSocketAddressTypes() {
808
      return producedSocketAddressTypes;
1✔
809
    }
810
  }
811

812
  /**
813
   * Returns the internal offload executor pool for offloading tasks.
814
   */
815
  public ObjectPool<? extends Executor> getOffloadExecutorPool() {
816
    return this.offloadExecutorPool;
1✔
817
  }
818
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc