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

grpc / grpc-java / #18883

03 Nov 2023 04:57PM UTC coverage: 88.246% (+0.03%) from 88.218%
#18883

push

github

web-flow
core, netty, okhttp: implement new logic for nameResolverFactory API in channelBuilder (#10590)

* core, netty, okhttp: implement new logic for nameResolverFactory API in channelBuilder
fix ManagedChannelImpl to use NameResolverRegistry instead of NameResolverFactory
fix the ManagedChannelImplBuilder and remove nameResolverFactory

* Integrate target parsing and NameResolverProvider searching

Actually creating the name resolver is now delayed to the end of
ManagedChannelImpl.getNameResolver; we don't want to call into the name
resolver to determine if we should use the name resolver.

Added getDefaultScheme() to NameResolverRegistry to avoid needing
NameResolver.Factory.
---------

Co-authored-by: Eric Anderson <ejona@google.com>

30370 of 34415 relevant lines covered (88.25%)

0.88 hits per line

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

90.29
/../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

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

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

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

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

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

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

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

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

97
  private static final ObjectPool<? extends Executor> DEFAULT_EXECUTOR_POOL =
1✔
98
      SharedResourcePool.forResource(GrpcUtil.SHARED_CHANNEL_EXECUTOR);
1✔
99

100
  private static final DecompressorRegistry DEFAULT_DECOMPRESSOR_REGISTRY =
101
      DecompressorRegistry.getDefaultInstance();
1✔
102

103
  private static final CompressorRegistry DEFAULT_COMPRESSOR_REGISTRY =
104
      CompressorRegistry.getDefaultInstance();
1✔
105

106
  private static final long DEFAULT_RETRY_BUFFER_SIZE_IN_BYTES = 1L << 24;  // 16M
107
  private static final long DEFAULT_PER_RPC_BUFFER_LIMIT_IN_BYTES = 1L << 20; // 1M
108

109
  private static final Method GET_CLIENT_INTERCEPTOR_METHOD;
110

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

132

133
  ObjectPool<? extends Executor> executorPool = DEFAULT_EXECUTOR_POOL;
1✔
134

135
  ObjectPool<? extends Executor> offloadExecutorPool = DEFAULT_EXECUTOR_POOL;
1✔
136

137
  private final List<ClientInterceptor> interceptors = new ArrayList<>();
1✔
138
  NameResolverRegistry nameResolverRegistry = NameResolverRegistry.getDefaultRegistry();
1✔
139

140
  final String target;
141
  @Nullable
142
  final ChannelCredentials channelCredentials;
143
  @Nullable
144
  final CallCredentials callCredentials;
145

146
  @Nullable
147
  private final SocketAddress directServerAddress;
148

149
  @Nullable
150
  String userAgent;
151

152
  @Nullable
153
  String authorityOverride;
154

155
  String defaultLbPolicy = GrpcUtil.DEFAULT_LB_POLICY;
1✔
156

157
  boolean fullStreamDecompression;
158

159
  DecompressorRegistry decompressorRegistry = DEFAULT_DECOMPRESSOR_REGISTRY;
1✔
160

161
  CompressorRegistry compressorRegistry = DEFAULT_COMPRESSOR_REGISTRY;
1✔
162

163
  long idleTimeoutMillis = IDLE_MODE_DEFAULT_TIMEOUT_MILLIS;
1✔
164

165
  int maxRetryAttempts = 5;
1✔
166
  int maxHedgedAttempts = 5;
1✔
167
  long retryBufferSize = DEFAULT_RETRY_BUFFER_SIZE_IN_BYTES;
1✔
168
  long perRpcBufferLimit = DEFAULT_PER_RPC_BUFFER_LIMIT_IN_BYTES;
1✔
169
  boolean retryEnabled = true;
1✔
170

171
  InternalChannelz channelz = InternalChannelz.instance();
1✔
172
  int maxTraceEvents;
173

174
  @Nullable
175
  Map<String, ?> defaultServiceConfig;
176
  boolean lookUpServiceConfig = true;
1✔
177

178
  @Nullable
179
  BinaryLog binlog;
180

181
  @Nullable
182
  ProxyDetector proxyDetector;
183

184
  private boolean authorityCheckerDisabled;
185
  private boolean statsEnabled = true;
1✔
186
  private boolean recordStartedRpcs = true;
1✔
187
  private boolean recordFinishedRpcs = true;
1✔
188
  private boolean recordRealTimeMetrics = false;
1✔
189
  private boolean recordRetryMetrics = true;
1✔
190
  private boolean tracingEnabled = true;
1✔
191

192
  /**
193
   * An interface for Transport implementors to provide the {@link ClientTransportFactory}
194
   * appropriate for the channel.
195
   */
196
  public interface ClientTransportFactoryBuilder {
197
    ClientTransportFactory buildClientTransportFactory();
198
  }
199

200
  /**
201
   * Convenience ClientTransportFactoryBuilder, throws UnsupportedOperationException().
202
   */
203
  public static class UnsupportedClientTransportFactoryBuilder implements
1✔
204
      ClientTransportFactoryBuilder {
205
    @Override
206
    public ClientTransportFactory buildClientTransportFactory() {
207
      throw new UnsupportedOperationException();
×
208
    }
209
  }
210

211
  /**
212
   * An interface for Transport implementors to provide a default port to {@link
213
   * io.grpc.NameResolver} for use in cases where the target string doesn't include a port. The
214
   * default implementation returns {@link GrpcUtil#DEFAULT_PORT_SSL}.
215
   */
216
  public interface ChannelBuilderDefaultPortProvider {
217
    int getDefaultPort();
218
  }
219

220
  /**
221
   * Default implementation of {@link ChannelBuilderDefaultPortProvider} that returns a fixed port.
222
   */
223
  public static final class FixedPortProvider implements ChannelBuilderDefaultPortProvider {
224
    private final int port;
225

226
    public FixedPortProvider(int port) {
1✔
227
      this.port = port;
1✔
228
    }
1✔
229

230
    @Override
231
    public int getDefaultPort() {
232
      return port;
1✔
233
    }
234
  }
235

236
  private static final class ManagedChannelDefaultPortProvider implements
237
      ChannelBuilderDefaultPortProvider {
238
    @Override
239
    public int getDefaultPort() {
240
      return GrpcUtil.DEFAULT_PORT_SSL;
1✔
241
    }
242
  }
243

244
  private final ClientTransportFactoryBuilder clientTransportFactoryBuilder;
245
  private final ChannelBuilderDefaultPortProvider channelBuilderDefaultPortProvider;
246

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

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

277
    if (channelBuilderDefaultPortProvider != null) {
1✔
278
      this.channelBuilderDefaultPortProvider = channelBuilderDefaultPortProvider;
1✔
279
    } else {
280
      this.channelBuilderDefaultPortProvider = new ManagedChannelDefaultPortProvider();
1✔
281
    }
282
  }
1✔
283

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

299
  /**
300
   * Creates a new managed channel builder with the given server address, authority string of the
301
   * channel. Transport implementors must provide client transport factory builder, and may set
302
   * custom channel default port provider.
303
   */
304
  public ManagedChannelImplBuilder(SocketAddress directServerAddress, String authority,
305
      ClientTransportFactoryBuilder clientTransportFactoryBuilder,
306
      @Nullable ChannelBuilderDefaultPortProvider channelBuilderDefaultPortProvider) {
307
    this(directServerAddress, authority, null, null, clientTransportFactoryBuilder,
1✔
308
        channelBuilderDefaultPortProvider);
309
  }
1✔
310

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

334
    if (channelBuilderDefaultPortProvider != null) {
1✔
335
      this.channelBuilderDefaultPortProvider = channelBuilderDefaultPortProvider;
1✔
336
    } else {
337
      this.channelBuilderDefaultPortProvider = new ManagedChannelDefaultPortProvider();
1✔
338
    }
339
  }
1✔
340

341
  @Override
342
  public ManagedChannelImplBuilder directExecutor() {
343
    return executor(MoreExecutors.directExecutor());
1✔
344
  }
345

346
  @Override
347
  public ManagedChannelImplBuilder executor(Executor executor) {
348
    if (executor != null) {
1✔
349
      this.executorPool = new FixedObjectPool<>(executor);
1✔
350
    } else {
351
      this.executorPool = DEFAULT_EXECUTOR_POOL;
1✔
352
    }
353
    return this;
1✔
354
  }
355

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

366
  @Override
367
  public ManagedChannelImplBuilder intercept(List<ClientInterceptor> interceptors) {
368
    this.interceptors.addAll(interceptors);
1✔
369
    return this;
1✔
370
  }
371

372
  @Override
373
  public ManagedChannelImplBuilder intercept(ClientInterceptor... interceptors) {
374
    return intercept(Arrays.asList(interceptors));
1✔
375
  }
376

377
  @Deprecated
378
  @Override
379
  public ManagedChannelImplBuilder nameResolverFactory(NameResolver.Factory resolverFactory) {
380
    Preconditions.checkState(directServerAddress == null,
1✔
381
        "directServerAddress is set (%s), which forbids the use of NameResolverFactory",
382
        directServerAddress);
383
    if (resolverFactory != null) {
1✔
384
      NameResolverRegistry reg = new NameResolverRegistry();
1✔
385
      reg.register(new NameResolverFactoryToProviderFacade(resolverFactory));
1✔
386
      this.nameResolverRegistry = reg;
1✔
387
    } else {
1✔
388
      this.nameResolverRegistry = NameResolverRegistry.getDefaultRegistry();
1✔
389
    }
390
    return this;
1✔
391
  }
392

393
  ManagedChannelImplBuilder nameResolverRegistry(NameResolverRegistry resolverRegistry) {
394
    this.nameResolverRegistry = resolverRegistry;
1✔
395
    return this;
1✔
396
  }
397

398
  @Override
399
  public ManagedChannelImplBuilder defaultLoadBalancingPolicy(String policy) {
400
    Preconditions.checkState(directServerAddress == null,
1✔
401
        "directServerAddress is set (%s), which forbids the use of load-balancing policy",
402
        directServerAddress);
403
    Preconditions.checkArgument(policy != null, "policy cannot be null");
1✔
404
    this.defaultLbPolicy = policy;
1✔
405
    return this;
1✔
406
  }
407

408
  @Override
409
  public ManagedChannelImplBuilder enableFullStreamDecompression() {
410
    this.fullStreamDecompression = true;
1✔
411
    return this;
1✔
412
  }
413

414
  @Override
415
  public ManagedChannelImplBuilder decompressorRegistry(DecompressorRegistry registry) {
416
    if (registry != null) {
1✔
417
      this.decompressorRegistry = registry;
1✔
418
    } else {
419
      this.decompressorRegistry = DEFAULT_DECOMPRESSOR_REGISTRY;
1✔
420
    }
421
    return this;
1✔
422
  }
423

424
  @Override
425
  public ManagedChannelImplBuilder compressorRegistry(CompressorRegistry registry) {
426
    if (registry != null) {
1✔
427
      this.compressorRegistry = registry;
1✔
428
    } else {
429
      this.compressorRegistry = DEFAULT_COMPRESSOR_REGISTRY;
1✔
430
    }
431
    return this;
1✔
432
  }
433

434
  @Override
435
  public ManagedChannelImplBuilder userAgent(@Nullable String userAgent) {
436
    this.userAgent = userAgent;
1✔
437
    return this;
1✔
438
  }
439

440
  @Override
441
  public ManagedChannelImplBuilder overrideAuthority(String authority) {
442
    this.authorityOverride = checkAuthority(authority);
1✔
443
    return this;
1✔
444
  }
445

446
  @Override
447
  public ManagedChannelImplBuilder idleTimeout(long value, TimeUnit unit) {
448
    checkArgument(value > 0, "idle timeout is %s, but must be positive", value);
1✔
449
    // We convert to the largest unit to avoid overflow
450
    if (unit.toDays(value) >= IDLE_MODE_MAX_TIMEOUT_DAYS) {
1✔
451
      // This disables idle mode
452
      this.idleTimeoutMillis = ManagedChannelImpl.IDLE_TIMEOUT_MILLIS_DISABLE;
1✔
453
    } else {
454
      this.idleTimeoutMillis = Math.max(unit.toMillis(value), IDLE_MODE_MIN_TIMEOUT_MILLIS);
1✔
455
    }
456
    return this;
1✔
457
  }
458

459
  @Override
460
  public ManagedChannelImplBuilder maxRetryAttempts(int maxRetryAttempts) {
461
    this.maxRetryAttempts = maxRetryAttempts;
1✔
462
    return this;
1✔
463
  }
464

465
  @Override
466
  public ManagedChannelImplBuilder maxHedgedAttempts(int maxHedgedAttempts) {
467
    this.maxHedgedAttempts = maxHedgedAttempts;
1✔
468
    return this;
1✔
469
  }
470

471
  @Override
472
  public ManagedChannelImplBuilder retryBufferSize(long bytes) {
473
    checkArgument(bytes > 0L, "retry buffer size must be positive");
1✔
474
    retryBufferSize = bytes;
1✔
475
    return this;
1✔
476
  }
477

478
  @Override
479
  public ManagedChannelImplBuilder perRpcBufferLimit(long bytes) {
480
    checkArgument(bytes > 0L, "per RPC buffer limit must be positive");
1✔
481
    perRpcBufferLimit = bytes;
1✔
482
    return this;
1✔
483
  }
484

485
  @Override
486
  public ManagedChannelImplBuilder disableRetry() {
487
    retryEnabled = false;
1✔
488
    return this;
1✔
489
  }
490

491
  @Override
492
  public ManagedChannelImplBuilder enableRetry() {
493
    retryEnabled = true;
1✔
494
    return this;
1✔
495
  }
496

497
  @Override
498
  public ManagedChannelImplBuilder setBinaryLog(BinaryLog binlog) {
499
    this.binlog = binlog;
×
500
    return this;
×
501
  }
502

503
  @Override
504
  public ManagedChannelImplBuilder maxTraceEvents(int maxTraceEvents) {
505
    checkArgument(maxTraceEvents >= 0, "maxTraceEvents must be non-negative");
1✔
506
    this.maxTraceEvents = maxTraceEvents;
1✔
507
    return this;
1✔
508
  }
509

510
  @Override
511
  public ManagedChannelImplBuilder proxyDetector(@Nullable ProxyDetector proxyDetector) {
512
    this.proxyDetector = proxyDetector;
1✔
513
    return this;
1✔
514
  }
515

516
  @Override
517
  public ManagedChannelImplBuilder defaultServiceConfig(@Nullable Map<String, ?> serviceConfig) {
518
    // TODO(notcarl): use real parsing
519
    defaultServiceConfig = checkMapEntryTypes(serviceConfig);
1✔
520
    return this;
1✔
521
  }
522

523
  @Nullable
524
  private static Map<String, ?> checkMapEntryTypes(@Nullable Map<?, ?> map) {
525
    if (map == null) {
1✔
526
      return null;
×
527
    }
528
    // Not using ImmutableMap.Builder because of extra guava dependency for Android.
529
    Map<String, Object> parsedMap = new LinkedHashMap<>();
1✔
530
    for (Map.Entry<?, ?> entry : map.entrySet()) {
1✔
531
      checkArgument(
1✔
532
          entry.getKey() instanceof String,
1✔
533
          "The key of the entry '%s' is not of String type", entry);
534

535
      String key = (String) entry.getKey();
1✔
536
      Object value = entry.getValue();
1✔
537
      if (value == null) {
1✔
538
        parsedMap.put(key, null);
1✔
539
      } else if (value instanceof Map) {
1✔
540
        parsedMap.put(key, checkMapEntryTypes((Map<?, ?>) value));
1✔
541
      } else if (value instanceof List) {
1✔
542
        parsedMap.put(key, checkListEntryTypes((List<?>) value));
1✔
543
      } else if (value instanceof String) {
1✔
544
        parsedMap.put(key, value);
1✔
545
      } else if (value instanceof Double) {
1✔
546
        parsedMap.put(key, value);
1✔
547
      } else if (value instanceof Boolean) {
1✔
548
        parsedMap.put(key, value);
1✔
549
      } else {
550
        throw new IllegalArgumentException(
1✔
551
            "The value of the map entry '" + entry + "' is of type '" + value.getClass()
1✔
552
                + "', which is not supported");
553
      }
554
    }
1✔
555
    return Collections.unmodifiableMap(parsedMap);
1✔
556
  }
557

558
  private static List<?> checkListEntryTypes(List<?> list) {
559
    List<Object> parsedList = new ArrayList<>(list.size());
1✔
560
    for (Object value : list) {
1✔
561
      if (value == null) {
1✔
562
        parsedList.add(null);
1✔
563
      } else if (value instanceof Map) {
1✔
564
        parsedList.add(checkMapEntryTypes((Map<?, ?>) value));
1✔
565
      } else if (value instanceof List) {
1✔
566
        parsedList.add(checkListEntryTypes((List<?>) value));
×
567
      } else if (value instanceof String) {
1✔
568
        parsedList.add(value);
1✔
569
      } else if (value instanceof Double) {
1✔
570
        parsedList.add(value);
1✔
571
      } else if (value instanceof Boolean) {
1✔
572
        parsedList.add(value);
1✔
573
      } else {
574
        throw new IllegalArgumentException(
×
575
            "The entry '" + value + "' is of type '" + value.getClass()
×
576
                + "', which is not supported");
577
      }
578
    }
1✔
579
    return Collections.unmodifiableList(parsedList);
1✔
580
  }
581

582
  @Override
583
  public ManagedChannelImplBuilder disableServiceConfigLookUp() {
584
    this.lookUpServiceConfig = false;
1✔
585
    return this;
1✔
586
  }
587

588
  /**
589
   * Disable or enable stats features. Enabled by default.
590
   *
591
   * <p>For the current release, calling {@code setStatsEnabled(true)} may have a side effect that
592
   * disables retry.
593
   */
594
  public void setStatsEnabled(boolean value) {
595
    statsEnabled = value;
1✔
596
  }
1✔
597

598
  /**
599
   * Disable or enable stats recording for RPC upstarts.  Effective only if {@link
600
   * #setStatsEnabled} is set to true.  Enabled by default.
601
   */
602
  public void setStatsRecordStartedRpcs(boolean value) {
603
    recordStartedRpcs = value;
1✔
604
  }
1✔
605

606
  /**
607
   * Disable or enable stats recording for RPC completions.  Effective only if {@link
608
   * #setStatsEnabled} is set to true.  Enabled by default.
609
   */
610
  public void setStatsRecordFinishedRpcs(boolean value) {
611
    recordFinishedRpcs = value;
1✔
612
  }
1✔
613

614
  /**
615
   * Disable or enable real-time metrics recording.  Effective only if {@link #setStatsEnabled} is
616
   * set to true.  Disabled by default.
617
   */
618
  public void setStatsRecordRealTimeMetrics(boolean value) {
619
    recordRealTimeMetrics = value;
×
620
  }
×
621
  
622
  public void setStatsRecordRetryMetrics(boolean value) {
623
    recordRetryMetrics = value;
1✔
624
  }
1✔
625

626
  /**
627
   * Disable or enable tracing features.  Enabled by default.
628
   */
629
  public void setTracingEnabled(boolean value) {
630
    tracingEnabled = value;
1✔
631
  }
1✔
632

633
  /**
634
   * Verifies the authority is valid.
635
   */
636
  @VisibleForTesting
637
  String checkAuthority(String authority) {
638
    if (authorityCheckerDisabled) {
1✔
639
      return authority;
1✔
640
    }
641
    return GrpcUtil.checkAuthority(authority);
1✔
642
  }
643

644
  /** Disable the check whether the authority is valid. */
645
  public ManagedChannelImplBuilder disableCheckAuthority() {
646
    authorityCheckerDisabled = true;
1✔
647
    return this;
1✔
648
  }
649

650
  /** Enable previously disabled authority check. */
651
  public ManagedChannelImplBuilder enableCheckAuthority() {
652
    authorityCheckerDisabled = false;
1✔
653
    return this;
1✔
654
  }
655

656
  @Override
657
  public ManagedChannel build() {
658
    return new ManagedChannelOrphanWrapper(new ManagedChannelImpl(
1✔
659
        this,
660
        clientTransportFactoryBuilder.buildClientTransportFactory(),
1✔
661
        new ExponentialBackoffPolicy.Provider(),
662
        SharedResourcePool.forResource(GrpcUtil.SHARED_CHANNEL_EXECUTOR),
1✔
663
        GrpcUtil.STOPWATCH_SUPPLIER,
664
        getEffectiveInterceptors(),
1✔
665
        TimeProvider.SYSTEM_TIME_PROVIDER));
666
  }
667

668
  // Temporarily disable retry when stats or tracing is enabled to avoid breakage, until we know
669
  // what should be the desired behavior for retry + stats/tracing.
670
  // TODO(zdapeng): FIX IT
671
  @VisibleForTesting
672
  List<ClientInterceptor> getEffectiveInterceptors() {
673
    List<ClientInterceptor> effectiveInterceptors = new ArrayList<>(this.interceptors);
1✔
674
    boolean isGlobalInterceptorsSet = false;
1✔
675
    List<ClientInterceptor> globalClientInterceptors =
676
        InternalGlobalInterceptors.getClientInterceptors();
1✔
677
    if (globalClientInterceptors != null) {
1✔
678
      effectiveInterceptors.addAll(globalClientInterceptors);
×
679
      isGlobalInterceptorsSet = true;
×
680
    }
681
    if (!isGlobalInterceptorsSet && statsEnabled) {
1✔
682
      ClientInterceptor statsInterceptor = null;
1✔
683

684
      if (GET_CLIENT_INTERCEPTOR_METHOD != null) {
1✔
685
        try {
686
          statsInterceptor =
1✔
687
            (ClientInterceptor) GET_CLIENT_INTERCEPTOR_METHOD
688
              .invoke(
1✔
689
                null,
690
                recordStartedRpcs,
1✔
691
                recordFinishedRpcs,
1✔
692
                recordRealTimeMetrics,
1✔
693
                recordRetryMetrics);
1✔
694
        } catch (IllegalAccessException e) {
×
695
          log.log(Level.FINE, "Unable to apply census stats", e);
×
696
        } catch (InvocationTargetException e) {
×
697
          log.log(Level.FINE, "Unable to apply census stats", e);
×
698
        }
1✔
699
      }
700

701
      if (statsInterceptor != null) {
1✔
702
        // First interceptor runs last (see ClientInterceptors.intercept()), so that no
703
        // other interceptor can override the tracer factory we set in CallOptions.
704
        effectiveInterceptors.add(0, statsInterceptor);
1✔
705
      }
706
    }
707
    if (!isGlobalInterceptorsSet && tracingEnabled) {
1✔
708
      ClientInterceptor tracingInterceptor = null;
1✔
709
      try {
710
        Class<?> censusTracingAccessor =
1✔
711
            Class.forName("io.grpc.census.InternalCensusTracingAccessor");
1✔
712
        Method getClientInterceptroMethod =
1✔
713
            censusTracingAccessor.getDeclaredMethod("getClientInterceptor");
1✔
714
        tracingInterceptor = (ClientInterceptor) getClientInterceptroMethod.invoke(null);
1✔
715
      } catch (ClassNotFoundException e) {
1✔
716
        // Replace these separate catch statements with multicatch when Android min-API >= 19
717
        log.log(Level.FINE, "Unable to apply census stats", e);
1✔
718
      } catch (NoSuchMethodException e) {
×
719
        log.log(Level.FINE, "Unable to apply census stats", e);
×
720
      } catch (IllegalAccessException e) {
×
721
        log.log(Level.FINE, "Unable to apply census stats", e);
×
722
      } catch (InvocationTargetException e) {
×
723
        log.log(Level.FINE, "Unable to apply census stats", e);
×
724
      }
1✔
725
      if (tracingInterceptor != null) {
1✔
726
        effectiveInterceptors.add(0, tracingInterceptor);
1✔
727
      }
728
    }
729
    return effectiveInterceptors;
1✔
730
  }
731

732
  /**
733
   * Returns a default port to {@link NameResolver} for use in cases where the target string doesn't
734
   * include a port. The default implementation returns {@link GrpcUtil#DEFAULT_PORT_SSL}.
735
   */
736
  int getDefaultPort() {
737
    return channelBuilderDefaultPortProvider.getDefaultPort();
1✔
738
  }
739

740
  private static class DirectAddressNameResolverProvider extends NameResolverProvider {
741
    final SocketAddress address;
742
    final String authority;
743
    final Collection<Class<? extends SocketAddress>> producedSocketAddressTypes;
744

745
    DirectAddressNameResolverProvider(SocketAddress address, String authority) {
1✔
746
      this.address = address;
1✔
747
      this.authority = authority;
1✔
748
      this.producedSocketAddressTypes
1✔
749
          = Collections.singleton(address.getClass());
1✔
750
    }
1✔
751

752
    @Override
753
    public NameResolver newNameResolver(URI notUsedUri, NameResolver.Args args) {
754
      return new NameResolver() {
1✔
755
        @Override
756
        public String getServiceAuthority() {
757
          return authority;
1✔
758
        }
759

760
        @Override
761
        public void start(Listener2 listener) {
762
          listener.onResult(
1✔
763
              ResolutionResult.newBuilder()
1✔
764
                  .setAddresses(Collections.singletonList(new EquivalentAddressGroup(address)))
1✔
765
                  .setAttributes(Attributes.EMPTY)
1✔
766
                  .build());
1✔
767
        }
1✔
768

769
        @Override
770
        public void shutdown() {}
1✔
771
      };
772
    }
773

774
    @Override
775
    public String getDefaultScheme() {
776
      return DIRECT_ADDRESS_SCHEME;
1✔
777
    }
778

779
    @Override
780
    protected boolean isAvailable() {
781
      return true;
1✔
782
    }
783

784
    @Override
785
    protected int priority() {
786
      return 5;
1✔
787
    }
788

789
    @Override
790
    public Collection<Class<? extends SocketAddress>> getProducedSocketAddressTypes() {
791
      return producedSocketAddressTypes;
1✔
792
    }
793
  }
794

795
  /**
796
   * Returns the internal offload executor pool for offloading tasks.
797
   */
798
  public ObjectPool<? extends Executor> getOffloadExecutorPool() {
799
    return this.offloadExecutorPool;
1✔
800
  }
801
}
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

© 2026 Coveralls, Inc