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

grpc / grpc-java / #18820

06 Sep 2023 06:12PM UTC coverage: 88.304% (+0.02%) from 88.283%
#18820

push

github-actions

temawi
core: only try to resolve InternalCensusStatsAccessor once

30336 of 34354 relevant lines covered (88.3%)

0.88 hits per line

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

89.51
/../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.NameResolverRegistry;
39
import io.grpc.ProxyDetector;
40
import java.lang.reflect.InvocationTargetException;
41
import java.lang.reflect.Method;
42
import java.net.SocketAddress;
43
import java.net.URI;
44
import java.net.URISyntaxException;
45
import java.util.ArrayList;
46
import java.util.Arrays;
47
import java.util.Collections;
48
import java.util.LinkedHashMap;
49
import java.util.List;
50
import java.util.Map;
51
import java.util.concurrent.Executor;
52
import java.util.concurrent.TimeUnit;
53
import java.util.logging.Level;
54
import java.util.logging.Logger;
55
import javax.annotation.Nullable;
56

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

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

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

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

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

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

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

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

98
  private static final DecompressorRegistry DEFAULT_DECOMPRESSOR_REGISTRY =
99
      DecompressorRegistry.getDefaultInstance();
1✔
100

101
  private static final CompressorRegistry DEFAULT_COMPRESSOR_REGISTRY =
102
      CompressorRegistry.getDefaultInstance();
1✔
103

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

107
  private static final Method GET_CLIENT_INTERCEPTOR_METHOD;
108

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

130

131
  ObjectPool<? extends Executor> executorPool = DEFAULT_EXECUTOR_POOL;
1✔
132

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

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

138
  // Access via getter, which may perform authority override as needed
139
  NameResolver.Factory nameResolverFactory = nameResolverRegistry.asFactory();
1✔
140

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

147
  @Nullable
148
  private final SocketAddress directServerAddress;
149

150
  @Nullable
151
  String userAgent;
152

153
  @Nullable
154
  String authorityOverride;
155

156
  String defaultLbPolicy = GrpcUtil.DEFAULT_LB_POLICY;
1✔
157

158
  boolean fullStreamDecompression;
159

160
  DecompressorRegistry decompressorRegistry = DEFAULT_DECOMPRESSOR_REGISTRY;
1✔
161

162
  CompressorRegistry compressorRegistry = DEFAULT_COMPRESSOR_REGISTRY;
1✔
163

164
  long idleTimeoutMillis = IDLE_MODE_DEFAULT_TIMEOUT_MILLIS;
1✔
165

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

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

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

179
  @Nullable
180
  BinaryLog binlog;
181

182
  @Nullable
183
  ProxyDetector proxyDetector;
184

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

389
  @Override
390
  public ManagedChannelImplBuilder defaultLoadBalancingPolicy(String policy) {
391
    Preconditions.checkState(directServerAddress == null,
1✔
392
        "directServerAddress is set (%s), which forbids the use of load-balancing policy",
393
        directServerAddress);
394
    Preconditions.checkArgument(policy != null, "policy cannot be null");
1✔
395
    this.defaultLbPolicy = policy;
1✔
396
    return this;
1✔
397
  }
398

399
  @Override
400
  public ManagedChannelImplBuilder enableFullStreamDecompression() {
401
    this.fullStreamDecompression = true;
1✔
402
    return this;
1✔
403
  }
404

405
  @Override
406
  public ManagedChannelImplBuilder decompressorRegistry(DecompressorRegistry registry) {
407
    if (registry != null) {
1✔
408
      this.decompressorRegistry = registry;
1✔
409
    } else {
410
      this.decompressorRegistry = DEFAULT_DECOMPRESSOR_REGISTRY;
1✔
411
    }
412
    return this;
1✔
413
  }
414

415
  @Override
416
  public ManagedChannelImplBuilder compressorRegistry(CompressorRegistry registry) {
417
    if (registry != null) {
1✔
418
      this.compressorRegistry = registry;
1✔
419
    } else {
420
      this.compressorRegistry = DEFAULT_COMPRESSOR_REGISTRY;
1✔
421
    }
422
    return this;
1✔
423
  }
424

425
  @Override
426
  public ManagedChannelImplBuilder userAgent(@Nullable String userAgent) {
427
    this.userAgent = userAgent;
1✔
428
    return this;
1✔
429
  }
430

431
  @Override
432
  public ManagedChannelImplBuilder overrideAuthority(String authority) {
433
    this.authorityOverride = checkAuthority(authority);
1✔
434
    return this;
1✔
435
  }
436

437
  @Override
438
  public ManagedChannelImplBuilder idleTimeout(long value, TimeUnit unit) {
439
    checkArgument(value > 0, "idle timeout is %s, but must be positive", value);
1✔
440
    // We convert to the largest unit to avoid overflow
441
    if (unit.toDays(value) >= IDLE_MODE_MAX_TIMEOUT_DAYS) {
1✔
442
      // This disables idle mode
443
      this.idleTimeoutMillis = ManagedChannelImpl.IDLE_TIMEOUT_MILLIS_DISABLE;
1✔
444
    } else {
445
      this.idleTimeoutMillis = Math.max(unit.toMillis(value), IDLE_MODE_MIN_TIMEOUT_MILLIS);
1✔
446
    }
447
    return this;
1✔
448
  }
449

450
  @Override
451
  public ManagedChannelImplBuilder maxRetryAttempts(int maxRetryAttempts) {
452
    this.maxRetryAttempts = maxRetryAttempts;
1✔
453
    return this;
1✔
454
  }
455

456
  @Override
457
  public ManagedChannelImplBuilder maxHedgedAttempts(int maxHedgedAttempts) {
458
    this.maxHedgedAttempts = maxHedgedAttempts;
1✔
459
    return this;
1✔
460
  }
461

462
  @Override
463
  public ManagedChannelImplBuilder retryBufferSize(long bytes) {
464
    checkArgument(bytes > 0L, "retry buffer size must be positive");
1✔
465
    retryBufferSize = bytes;
1✔
466
    return this;
1✔
467
  }
468

469
  @Override
470
  public ManagedChannelImplBuilder perRpcBufferLimit(long bytes) {
471
    checkArgument(bytes > 0L, "per RPC buffer limit must be positive");
1✔
472
    perRpcBufferLimit = bytes;
1✔
473
    return this;
1✔
474
  }
475

476
  @Override
477
  public ManagedChannelImplBuilder disableRetry() {
478
    retryEnabled = false;
1✔
479
    return this;
1✔
480
  }
481

482
  @Override
483
  public ManagedChannelImplBuilder enableRetry() {
484
    retryEnabled = true;
1✔
485
    return this;
1✔
486
  }
487

488
  @Override
489
  public ManagedChannelImplBuilder setBinaryLog(BinaryLog binlog) {
490
    this.binlog = binlog;
×
491
    return this;
×
492
  }
493

494
  @Override
495
  public ManagedChannelImplBuilder maxTraceEvents(int maxTraceEvents) {
496
    checkArgument(maxTraceEvents >= 0, "maxTraceEvents must be non-negative");
1✔
497
    this.maxTraceEvents = maxTraceEvents;
1✔
498
    return this;
1✔
499
  }
500

501
  @Override
502
  public ManagedChannelImplBuilder proxyDetector(@Nullable ProxyDetector proxyDetector) {
503
    this.proxyDetector = proxyDetector;
1✔
504
    return this;
1✔
505
  }
506

507
  @Override
508
  public ManagedChannelImplBuilder defaultServiceConfig(@Nullable Map<String, ?> serviceConfig) {
509
    // TODO(notcarl): use real parsing
510
    defaultServiceConfig = checkMapEntryTypes(serviceConfig);
1✔
511
    return this;
1✔
512
  }
513

514
  @Nullable
515
  private static Map<String, ?> checkMapEntryTypes(@Nullable Map<?, ?> map) {
516
    if (map == null) {
1✔
517
      return null;
×
518
    }
519
    // Not using ImmutableMap.Builder because of extra guava dependency for Android.
520
    Map<String, Object> parsedMap = new LinkedHashMap<>();
1✔
521
    for (Map.Entry<?, ?> entry : map.entrySet()) {
1✔
522
      checkArgument(
1✔
523
          entry.getKey() instanceof String,
1✔
524
          "The key of the entry '%s' is not of String type", entry);
525

526
      String key = (String) entry.getKey();
1✔
527
      Object value = entry.getValue();
1✔
528
      if (value == null) {
1✔
529
        parsedMap.put(key, null);
1✔
530
      } else if (value instanceof Map) {
1✔
531
        parsedMap.put(key, checkMapEntryTypes((Map<?, ?>) value));
1✔
532
      } else if (value instanceof List) {
1✔
533
        parsedMap.put(key, checkListEntryTypes((List<?>) value));
1✔
534
      } else if (value instanceof String) {
1✔
535
        parsedMap.put(key, value);
1✔
536
      } else if (value instanceof Double) {
1✔
537
        parsedMap.put(key, value);
1✔
538
      } else if (value instanceof Boolean) {
1✔
539
        parsedMap.put(key, value);
1✔
540
      } else {
541
        throw new IllegalArgumentException(
1✔
542
            "The value of the map entry '" + entry + "' is of type '" + value.getClass()
1✔
543
                + "', which is not supported");
544
      }
545
    }
1✔
546
    return Collections.unmodifiableMap(parsedMap);
1✔
547
  }
548

549
  private static List<?> checkListEntryTypes(List<?> list) {
550
    List<Object> parsedList = new ArrayList<>(list.size());
1✔
551
    for (Object value : list) {
1✔
552
      if (value == null) {
1✔
553
        parsedList.add(null);
1✔
554
      } else if (value instanceof Map) {
1✔
555
        parsedList.add(checkMapEntryTypes((Map<?, ?>) value));
1✔
556
      } else if (value instanceof List) {
1✔
557
        parsedList.add(checkListEntryTypes((List<?>) value));
×
558
      } else if (value instanceof String) {
1✔
559
        parsedList.add(value);
1✔
560
      } else if (value instanceof Double) {
1✔
561
        parsedList.add(value);
1✔
562
      } else if (value instanceof Boolean) {
1✔
563
        parsedList.add(value);
1✔
564
      } else {
565
        throw new IllegalArgumentException(
×
566
            "The entry '" + value + "' is of type '" + value.getClass()
×
567
                + "', which is not supported");
568
      }
569
    }
1✔
570
    return Collections.unmodifiableList(parsedList);
1✔
571
  }
572

573
  @Override
574
  public ManagedChannelImplBuilder disableServiceConfigLookUp() {
575
    this.lookUpServiceConfig = false;
1✔
576
    return this;
1✔
577
  }
578

579
  /**
580
   * Disable or enable stats features. Enabled by default.
581
   *
582
   * <p>For the current release, calling {@code setStatsEnabled(true)} may have a side effect that
583
   * disables retry.
584
   */
585
  public void setStatsEnabled(boolean value) {
586
    statsEnabled = value;
1✔
587
  }
1✔
588

589
  /**
590
   * Disable or enable stats recording for RPC upstarts.  Effective only if {@link
591
   * #setStatsEnabled} is set to true.  Enabled by default.
592
   */
593
  public void setStatsRecordStartedRpcs(boolean value) {
594
    recordStartedRpcs = value;
1✔
595
  }
1✔
596

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

605
  /**
606
   * Disable or enable real-time metrics recording.  Effective only if {@link #setStatsEnabled} is
607
   * set to true.  Disabled by default.
608
   */
609
  public void setStatsRecordRealTimeMetrics(boolean value) {
610
    recordRealTimeMetrics = value;
×
611
  }
×
612
  
613
  public void setStatsRecordRetryMetrics(boolean value) {
614
    recordRetryMetrics = value;
1✔
615
  }
1✔
616

617
  /**
618
   * Disable or enable tracing features.  Enabled by default.
619
   */
620
  public void setTracingEnabled(boolean value) {
621
    tracingEnabled = value;
1✔
622
  }
1✔
623

624
  /**
625
   * Verifies the authority is valid.
626
   */
627
  @VisibleForTesting
628
  String checkAuthority(String authority) {
629
    if (authorityCheckerDisabled) {
1✔
630
      return authority;
1✔
631
    }
632
    return GrpcUtil.checkAuthority(authority);
1✔
633
  }
634

635
  /** Disable the check whether the authority is valid. */
636
  public ManagedChannelImplBuilder disableCheckAuthority() {
637
    authorityCheckerDisabled = true;
1✔
638
    return this;
1✔
639
  }
640

641
  /** Enable previously disabled authority check. */
642
  public ManagedChannelImplBuilder enableCheckAuthority() {
643
    authorityCheckerDisabled = false;
1✔
644
    return this;
1✔
645
  }
646

647
  @Override
648
  public ManagedChannel build() {
649
    return new ManagedChannelOrphanWrapper(new ManagedChannelImpl(
1✔
650
        this,
651
        clientTransportFactoryBuilder.buildClientTransportFactory(),
1✔
652
        new ExponentialBackoffPolicy.Provider(),
653
        SharedResourcePool.forResource(GrpcUtil.SHARED_CHANNEL_EXECUTOR),
1✔
654
        GrpcUtil.STOPWATCH_SUPPLIER,
655
        getEffectiveInterceptors(),
1✔
656
        TimeProvider.SYSTEM_TIME_PROVIDER));
657
  }
658

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

675
      if (GET_CLIENT_INTERCEPTOR_METHOD != null) {
1✔
676
        try {
677
          statsInterceptor =
1✔
678
            (ClientInterceptor) GET_CLIENT_INTERCEPTOR_METHOD
679
              .invoke(
1✔
680
                null,
681
                recordStartedRpcs,
1✔
682
                recordFinishedRpcs,
1✔
683
                recordRealTimeMetrics,
1✔
684
                recordRetryMetrics);
1✔
685
        } catch (IllegalAccessException e) {
×
686
          log.log(Level.FINE, "Unable to apply census stats", e);
×
687
        } catch (InvocationTargetException e) {
×
688
          log.log(Level.FINE, "Unable to apply census stats", e);
×
689
        }
1✔
690
      }
691

692
      if (statsInterceptor != null) {
1✔
693
        // First interceptor runs last (see ClientInterceptors.intercept()), so that no
694
        // other interceptor can override the tracer factory we set in CallOptions.
695
        effectiveInterceptors.add(0, statsInterceptor);
1✔
696
      }
697
    }
698
    if (!isGlobalInterceptorsSet && tracingEnabled) {
1✔
699
      ClientInterceptor tracingInterceptor = null;
1✔
700
      try {
701
        Class<?> censusTracingAccessor =
1✔
702
            Class.forName("io.grpc.census.InternalCensusTracingAccessor");
1✔
703
        Method getClientInterceptroMethod =
1✔
704
            censusTracingAccessor.getDeclaredMethod("getClientInterceptor");
1✔
705
        tracingInterceptor = (ClientInterceptor) getClientInterceptroMethod.invoke(null);
1✔
706
      } catch (ClassNotFoundException e) {
1✔
707
        // Replace these separate catch statements with multicatch when Android min-API >= 19
708
        log.log(Level.FINE, "Unable to apply census stats", e);
1✔
709
      } catch (NoSuchMethodException e) {
×
710
        log.log(Level.FINE, "Unable to apply census stats", e);
×
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
      if (tracingInterceptor != null) {
1✔
717
        effectiveInterceptors.add(0, tracingInterceptor);
1✔
718
      }
719
    }
720
    return effectiveInterceptors;
1✔
721
  }
722

723
  /**
724
   * Returns a default port to {@link NameResolver} for use in cases where the target string doesn't
725
   * include a port. The default implementation returns {@link GrpcUtil#DEFAULT_PORT_SSL}.
726
   */
727
  int getDefaultPort() {
728
    return channelBuilderDefaultPortProvider.getDefaultPort();
1✔
729
  }
730

731
  private static class DirectAddressNameResolverFactory extends NameResolver.Factory {
732
    final SocketAddress address;
733
    final String authority;
734

735
    DirectAddressNameResolverFactory(SocketAddress address, String authority) {
1✔
736
      this.address = address;
1✔
737
      this.authority = authority;
1✔
738
    }
1✔
739

740
    @Override
741
    public NameResolver newNameResolver(URI notUsedUri, NameResolver.Args args) {
742
      return new NameResolver() {
1✔
743
        @Override
744
        public String getServiceAuthority() {
745
          return authority;
1✔
746
        }
747

748
        @Override
749
        public void start(Listener2 listener) {
750
          listener.onResult(
1✔
751
              ResolutionResult.newBuilder()
1✔
752
                  .setAddresses(Collections.singletonList(new EquivalentAddressGroup(address)))
1✔
753
                  .setAttributes(Attributes.EMPTY)
1✔
754
                  .build());
1✔
755
        }
1✔
756

757
        @Override
758
        public void shutdown() {}
1✔
759
      };
760
    }
761

762
    @Override
763
    public String getDefaultScheme() {
764
      return DIRECT_ADDRESS_SCHEME;
×
765
    }
766
  }
767

768
  /**
769
   * Returns the internal offload executor pool for offloading tasks.
770
   */
771
  public ObjectPool<? extends Executor> getOffloadExecutorPool() {
772
    return this.offloadExecutorPool;
1✔
773
  }
774
}
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