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

grpc / grpc-java / #18918

27 Nov 2023 06:30PM UTC coverage: 88.203% (-0.02%) from 88.226%
#18918

push

github

ejona86
core: Detect NameResolverProviders passed as Factories

This may help some to move closer to Providers. It especially helps
cases where `NameResolverFactory`s aren't returning `InetSocketAddress`,
as it allows them to override `getProducedSocketAddressTypes()`, which
will now fail starting in 15fc70be.

30364 of 34425 relevant lines covered (88.2%)

0.88 hits per line

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

90.0
/../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
      if (resolverFactory instanceof NameResolverProvider) {
1✔
386
        reg.register((NameResolverProvider) resolverFactory);
×
387
      } else {
388
        reg.register(new NameResolverFactoryToProviderFacade(resolverFactory));
1✔
389
      }
390
      this.nameResolverRegistry = reg;
1✔
391
    } else {
1✔
392
      this.nameResolverRegistry = NameResolverRegistry.getDefaultRegistry();
1✔
393
    }
394
    return this;
1✔
395
  }
396

397
  ManagedChannelImplBuilder nameResolverRegistry(NameResolverRegistry resolverRegistry) {
398
    this.nameResolverRegistry = resolverRegistry;
1✔
399
    return this;
1✔
400
  }
401

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

412
  @Override
413
  public ManagedChannelImplBuilder enableFullStreamDecompression() {
414
    this.fullStreamDecompression = true;
1✔
415
    return this;
1✔
416
  }
417

418
  @Override
419
  public ManagedChannelImplBuilder decompressorRegistry(DecompressorRegistry registry) {
420
    if (registry != null) {
1✔
421
      this.decompressorRegistry = registry;
1✔
422
    } else {
423
      this.decompressorRegistry = DEFAULT_DECOMPRESSOR_REGISTRY;
1✔
424
    }
425
    return this;
1✔
426
  }
427

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

438
  @Override
439
  public ManagedChannelImplBuilder userAgent(@Nullable String userAgent) {
440
    this.userAgent = userAgent;
1✔
441
    return this;
1✔
442
  }
443

444
  @Override
445
  public ManagedChannelImplBuilder overrideAuthority(String authority) {
446
    this.authorityOverride = checkAuthority(authority);
1✔
447
    return this;
1✔
448
  }
449

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

463
  @Override
464
  public ManagedChannelImplBuilder maxRetryAttempts(int maxRetryAttempts) {
465
    this.maxRetryAttempts = maxRetryAttempts;
1✔
466
    return this;
1✔
467
  }
468

469
  @Override
470
  public ManagedChannelImplBuilder maxHedgedAttempts(int maxHedgedAttempts) {
471
    this.maxHedgedAttempts = maxHedgedAttempts;
1✔
472
    return this;
1✔
473
  }
474

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

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

489
  @Override
490
  public ManagedChannelImplBuilder disableRetry() {
491
    retryEnabled = false;
1✔
492
    return this;
1✔
493
  }
494

495
  @Override
496
  public ManagedChannelImplBuilder enableRetry() {
497
    retryEnabled = true;
1✔
498
    return this;
1✔
499
  }
500

501
  @Override
502
  public ManagedChannelImplBuilder setBinaryLog(BinaryLog binlog) {
503
    this.binlog = binlog;
×
504
    return this;
×
505
  }
506

507
  @Override
508
  public ManagedChannelImplBuilder maxTraceEvents(int maxTraceEvents) {
509
    checkArgument(maxTraceEvents >= 0, "maxTraceEvents must be non-negative");
1✔
510
    this.maxTraceEvents = maxTraceEvents;
1✔
511
    return this;
1✔
512
  }
513

514
  @Override
515
  public ManagedChannelImplBuilder proxyDetector(@Nullable ProxyDetector proxyDetector) {
516
    this.proxyDetector = proxyDetector;
1✔
517
    return this;
1✔
518
  }
519

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

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

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

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

586
  @Override
587
  public ManagedChannelImplBuilder disableServiceConfigLookUp() {
588
    this.lookUpServiceConfig = false;
1✔
589
    return this;
1✔
590
  }
591

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

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

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

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

630
  /**
631
   * Disable or enable tracing features.  Enabled by default.
632
   */
633
  public void setTracingEnabled(boolean value) {
634
    tracingEnabled = value;
1✔
635
  }
1✔
636

637
  /**
638
   * Verifies the authority is valid.
639
   */
640
  @VisibleForTesting
641
  String checkAuthority(String authority) {
642
    if (authorityCheckerDisabled) {
1✔
643
      return authority;
1✔
644
    }
645
    return GrpcUtil.checkAuthority(authority);
1✔
646
  }
647

648
  /** Disable the check whether the authority is valid. */
649
  public ManagedChannelImplBuilder disableCheckAuthority() {
650
    authorityCheckerDisabled = true;
1✔
651
    return this;
1✔
652
  }
653

654
  /** Enable previously disabled authority check. */
655
  public ManagedChannelImplBuilder enableCheckAuthority() {
656
    authorityCheckerDisabled = false;
1✔
657
    return this;
1✔
658
  }
659

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

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

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

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

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

744
  private static class DirectAddressNameResolverProvider extends NameResolverProvider {
745
    final SocketAddress address;
746
    final String authority;
747
    final Collection<Class<? extends SocketAddress>> producedSocketAddressTypes;
748

749
    DirectAddressNameResolverProvider(SocketAddress address, String authority) {
1✔
750
      this.address = address;
1✔
751
      this.authority = authority;
1✔
752
      this.producedSocketAddressTypes
1✔
753
          = Collections.singleton(address.getClass());
1✔
754
    }
1✔
755

756
    @Override
757
    public NameResolver newNameResolver(URI notUsedUri, NameResolver.Args args) {
758
      return new NameResolver() {
1✔
759
        @Override
760
        public String getServiceAuthority() {
761
          return authority;
1✔
762
        }
763

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

773
        @Override
774
        public void shutdown() {}
1✔
775
      };
776
    }
777

778
    @Override
779
    public String getDefaultScheme() {
780
      return DIRECT_ADDRESS_SCHEME;
1✔
781
    }
782

783
    @Override
784
    protected boolean isAvailable() {
785
      return true;
1✔
786
    }
787

788
    @Override
789
    protected int priority() {
790
      return 5;
1✔
791
    }
792

793
    @Override
794
    public Collection<Class<? extends SocketAddress>> getProducedSocketAddressTypes() {
795
      return producedSocketAddressTypes;
1✔
796
    }
797
  }
798

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