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

grpc / grpc-java / #20365

27 Jul 2026 06:04AM UTC coverage: 89.199% (+0.07%) from 89.125%
#20365

push

github

web-flow
core: Implement LB Delay Observability (Proposal A121) (#12807)

This PR implements **Attempt-Level RPC Delay Observability** across the core channel transport, built-in load balancers, xDS policies, and the OpenTelemetry telemetry plugin, aligned with [gRPC Proposal A121](https://github.com/grpc/proposal/pull/556).

38276 of 42911 relevant lines covered (89.2%)

0.89 hits per line

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

80.0
/../api/src/main/java/io/grpc/LoadBalancer.java
1
/*
2
 * Copyright 2016 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;
18

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

22
import com.google.common.base.MoreObjects;
23
import com.google.common.base.Objects;
24
import com.google.common.base.Preconditions;
25
import java.util.ArrayList;
26
import java.util.Arrays;
27
import java.util.Collections;
28
import java.util.List;
29
import java.util.Map;
30
import java.util.concurrent.ScheduledExecutorService;
31
import javax.annotation.Nonnull;
32
import javax.annotation.Nullable;
33
import javax.annotation.concurrent.Immutable;
34
import javax.annotation.concurrent.NotThreadSafe;
35

36
/**
37
 * A pluggable component that receives resolved addresses from {@link NameResolver} and provides the
38
 * channel a usable subchannel when asked.
39
 *
40
 * <h3>Overview</h3>
41
 *
42
 * <p>A LoadBalancer typically implements three interfaces:
43
 * <ol>
44
 *   <li>{@link LoadBalancer} is the main interface.  All methods on it are invoked sequentially
45
 *       in the same <strong>synchronization context</strong> (see next section) as returned by
46
 *       {@link io.grpc.LoadBalancer.Helper#getSynchronizationContext}.  It receives the results
47
 *       from the {@link NameResolver}, updates of subchannels' connectivity states, and the
48
 *       channel's request for the LoadBalancer to shutdown.</li>
49
 *   <li>{@link SubchannelPicker SubchannelPicker} does the actual load-balancing work.  It selects
50
 *       a {@link Subchannel Subchannel} for each new RPC.</li>
51
 *   <li>{@link Factory Factory} creates a new {@link LoadBalancer} instance.
52
 * </ol>
53
 *
54
 * <p>{@link Helper Helper} is implemented by gRPC library and provided to {@link Factory
55
 * Factory}. It provides functionalities that a {@code LoadBalancer} implementation would typically
56
 * need.
57
 *
58
 * <h3>The Synchronization Context</h3>
59
 *
60
 * <p>All methods on the {@link LoadBalancer} interface are called from a Synchronization Context,
61
 * meaning they are serialized, thus the balancer implementation doesn't need to worry about
62
 * synchronization among them.  {@link io.grpc.LoadBalancer.Helper#getSynchronizationContext}
63
 * allows implementations to schedule tasks to be run in the same Synchronization Context, with or
64
 * without a delay, thus those tasks don't need to worry about synchronizing with the balancer
65
 * methods.
66
 *
67
 * <p>However, the actual running thread may be the network thread, thus the following rules must be
68
 * followed to prevent blocking or even dead-locking in a network:
69
 *
70
 * <ol>
71
 *
72
 *   <li><strong>Never block in the Synchronization Context</strong>.  The callback methods must
73
 *   return quickly.  Examples or work that must be avoided: CPU-intensive calculation, waiting on
74
 *   synchronization primitives, blocking I/O, blocking RPCs, etc.</li>
75
 *
76
 *   <li><strong>Avoid calling into other components with lock held</strong>.  The Synchronization
77
 *   Context may be under a lock, e.g., the transport lock of OkHttp.  If your LoadBalancer holds a
78
 *   lock in a callback method (e.g., {@link #handleResolvedAddresses handleResolvedAddresses()})
79
 *   while calling into another method that also involves locks, be cautious of deadlock.  Generally
80
 *   you wouldn't need any locking in the LoadBalancer if you follow the canonical implementation
81
 *   pattern below.</li>
82
 *
83
 * </ol>
84
 *
85
 * <h3>The canonical implementation pattern</h3>
86
 *
87
 * <p>A {@link LoadBalancer} keeps states like the latest addresses from NameResolver, the
88
 * Subchannel(s) and their latest connectivity states.  These states are mutated within the
89
 * Synchronization Context,
90
 *
91
 * <p>A typical {@link SubchannelPicker SubchannelPicker} holds a snapshot of these states.  It may
92
 * have its own states, e.g., a picker from a round-robin load-balancer may keep a pointer to the
93
 * next Subchannel, which are typically mutated by multiple threads.  The picker should only mutate
94
 * its own state, and should not mutate or re-acquire the states of the LoadBalancer.  This way the
95
 * picker only needs to synchronize its own states, which is typically trivial to implement.
96
 *
97
 * <p>When the LoadBalancer states changes, e.g., Subchannels has become or stopped being READY, and
98
 * we want subsequent RPCs to use the latest list of READY Subchannels, LoadBalancer would create a
99
 * new picker, which holds a snapshot of the latest Subchannel list.  Refer to the javadoc of {@link
100
 * io.grpc.LoadBalancer.SubchannelStateListener#onSubchannelState onSubchannelState()} how to do
101
 * this properly.
102
 *
103
 * <p>No synchronization should be necessary between LoadBalancer and its pickers if you follow
104
 * the pattern above.  It may be possible to implement in a different way, but that would usually
105
 * result in more complicated threading.
106
 *
107
 * @since 1.2.0
108
 */
109
@ExperimentalApi("https://github.com/grpc/grpc-java/issues/1771")
110
@NotThreadSafe
111
public abstract class LoadBalancer {
1✔
112

113
  @Internal
114
  @NameResolver.ResolutionResultAttr
115
  public static final Attributes.Key<Map<String, ?>> ATTR_HEALTH_CHECKING_CONFIG =
1✔
116
      Attributes.Key.create("internal:health-checking-config");
1✔
117

118
  @Internal
119
  public static final LoadBalancer.CreateSubchannelArgs.Key<LoadBalancer.SubchannelStateListener>
120
      HEALTH_CONSUMER_LISTENER_ARG_KEY =
1✔
121
      LoadBalancer.CreateSubchannelArgs.Key.create("internal:health-check-consumer-listener");
1✔
122

123
  @Internal
124
  public static final LoadBalancer.CreateSubchannelArgs.Key<Boolean>
125
      DISABLE_SUBCHANNEL_RECONNECT_KEY =
1✔
126
      LoadBalancer.CreateSubchannelArgs.Key.createWithDefault(
1✔
127
          "internal:disable-subchannel-reconnect", Boolean.FALSE);
128

129
  @Internal
130
  public static final Attributes.Key<Boolean>
131
      HAS_HEALTH_PRODUCER_LISTENER_KEY =
1✔
132
      Attributes.Key.create("internal:has-health-check-producer-listener");
1✔
133

134
  public static final Attributes.Key<Boolean> IS_PETIOLE_POLICY =
1✔
135
      Attributes.Key.create("io.grpc.IS_PETIOLE_POLICY");
1✔
136

137
  /**
138
   * A picker that always returns an erring pick.
139
   *
140
   * @deprecated Use {@code new FixedResultPicker(PickResult.withNoResult())} instead.
141
   */
142
  @Deprecated
143
  public static final SubchannelPicker EMPTY_PICKER = new SubchannelPicker() {
1✔
144
    @Override
145
    public PickResult pickSubchannel(PickSubchannelArgs args) {
146
      return PickResult.withNoResult();
×
147
    }
148

149
    @Override
150
    public String toString() {
151
      return "EMPTY_PICKER";
×
152
    }
153
  };
154

155
  private int recursionCount;
156

157
  /**
158
   * Handles newly resolved addresses and metadata attributes from name resolution system.
159
   * Addresses in {@link EquivalentAddressGroup} should be considered equivalent but may be
160
   * flattened into a single list if needed.
161
   *
162
   * @param resolvedAddresses the resolved server addresses, attributes, and config.
163
   * @since 1.21.0
164
   *
165
   * @deprecated  Use instead {@link #acceptResolvedAddresses(ResolvedAddresses)}
166
   */
167
  @Deprecated
168
  public void handleResolvedAddresses(ResolvedAddresses resolvedAddresses) {
169
    if (recursionCount++ == 0) {
1✔
170
      // Note that the information about the addresses actually being accepted will be lost
171
      // if you rely on this method for backward compatibility.
172
      acceptResolvedAddresses(resolvedAddresses);
1✔
173
    }
174
    recursionCount = 0;
1✔
175
  }
1✔
176

177
  /**
178
   * Accepts newly resolved addresses from the name resolution system. The {@link
179
   * EquivalentAddressGroup} addresses should be considered equivalent but may be flattened into a
180
   * single list if needed.
181
   *
182
   * @param resolvedAddresses the resolved server addresses, attributes, and config
183
   * @return {@code Status.OK} if the resolved addresses were accepted, otherwise an error to report
184
   *     to the name resolver
185
   *
186
   * @since 1.49.0
187
   */
188
  public Status acceptResolvedAddresses(ResolvedAddresses resolvedAddresses) {
189
    if (resolvedAddresses.getAddresses().isEmpty()
1✔
190
        && !canHandleEmptyAddressListFromNameResolution()) {
×
191
      Status unavailableStatus = Status.UNAVAILABLE.withDescription(
×
192
              "NameResolver returned no usable address. addrs=" + resolvedAddresses.getAddresses()
×
193
                      + ", attrs=" + resolvedAddresses.getAttributes());
×
194
      handleNameResolutionError(unavailableStatus);
×
195
      return unavailableStatus;
×
196
    } else {
197
      if (recursionCount++ == 0) {
1✔
198
        handleResolvedAddresses(resolvedAddresses);
×
199
      }
200
      recursionCount = 0;
1✔
201

202
      return Status.OK;
1✔
203
    }
204
  }
205

206
  /**
207
   * Represents a combination of the resolved server address, associated attributes and a load
208
   * balancing policy config.  The config is from the {@link
209
   * LoadBalancerProvider#parseLoadBalancingPolicyConfig(Map)}.
210
   *
211
   * @since 1.21.0
212
   */
213
  @ExperimentalApi("https://github.com/grpc/grpc-java/issues/11657")
214
  public static final class ResolvedAddresses {
215
    private final List<EquivalentAddressGroup> addresses;
216
    @NameResolver.ResolutionResultAttr
217
    private final Attributes attributes;
218
    @Nullable
219
    private final Object loadBalancingPolicyConfig;
220
    // Make sure to update toBuilder() below!
221

222
    private ResolvedAddresses(
223
        List<EquivalentAddressGroup> addresses,
224
        @NameResolver.ResolutionResultAttr Attributes attributes,
225
        Object loadBalancingPolicyConfig) {
1✔
226
      this.addresses =
1✔
227
          Collections.unmodifiableList(new ArrayList<>(checkNotNull(addresses, "addresses")));
1✔
228
      this.attributes = checkNotNull(attributes, "attributes");
1✔
229
      this.loadBalancingPolicyConfig = loadBalancingPolicyConfig;
1✔
230
    }
1✔
231

232
    /**
233
     * Factory for constructing a new Builder.
234
     *
235
     * @since 1.21.0
236
     */
237
    public static Builder newBuilder() {
238
      return new Builder();
1✔
239
    }
240

241
    /**
242
     * Converts this back to a builder.
243
     *
244
     * @since 1.21.0
245
     */
246
    public Builder toBuilder() {
247
      return newBuilder()
1✔
248
          .setAddresses(addresses)
1✔
249
          .setAttributes(attributes)
1✔
250
          .setLoadBalancingPolicyConfig(loadBalancingPolicyConfig);
1✔
251
    }
252

253
    /**
254
     * Gets the server addresses.
255
     *
256
     * @since 1.21.0
257
     */
258
    public List<EquivalentAddressGroup> getAddresses() {
259
      return addresses;
1✔
260
    }
261

262
    /**
263
     * Gets the attributes associated with these addresses.  If this was not previously set,
264
     * {@link Attributes#EMPTY} will be returned.
265
     *
266
     * @since 1.21.0
267
     */
268
    @NameResolver.ResolutionResultAttr
269
    public Attributes getAttributes() {
270
      return attributes;
1✔
271
    }
272

273
    /**
274
     * Gets the domain specific load balancing policy.  This is the config produced by
275
     * {@link LoadBalancerProvider#parseLoadBalancingPolicyConfig(Map)}.
276
     *
277
     * @since 1.21.0
278
     */
279
    @Nullable
280
    public Object getLoadBalancingPolicyConfig() {
281
      return loadBalancingPolicyConfig;
1✔
282
    }
283

284
    /**
285
     * Builder for {@link ResolvedAddresses}.
286
     */
287
    @ExperimentalApi("https://github.com/grpc/grpc-java/issues/1771")
288
    public static final class Builder {
289
      private List<EquivalentAddressGroup> addresses;
290
      @NameResolver.ResolutionResultAttr
1✔
291
      private Attributes attributes = Attributes.EMPTY;
292
      @Nullable
293
      private Object loadBalancingPolicyConfig;
294

295
      Builder() {}
1✔
296

297
      /**
298
       * Sets the addresses.  This field is required.
299
       *
300
       * @return this.
301
       */
302
      public Builder setAddresses(List<EquivalentAddressGroup> addresses) {
303
        this.addresses = addresses;
1✔
304
        return this;
1✔
305
      }
306

307
      /**
308
       * Sets the attributes.  This field is optional; if not called, {@link Attributes#EMPTY}
309
       * will be used.
310
       *
311
       * @return this.
312
       */
313
      public Builder setAttributes(@NameResolver.ResolutionResultAttr Attributes attributes) {
314
        this.attributes = attributes;
1✔
315
        return this;
1✔
316
      }
317

318
      /**
319
       * Sets the load balancing policy config. This field is optional.
320
       *
321
       * @return this.
322
       */
323
      public Builder setLoadBalancingPolicyConfig(@Nullable Object loadBalancingPolicyConfig) {
324
        this.loadBalancingPolicyConfig = loadBalancingPolicyConfig;
1✔
325
        return this;
1✔
326
      }
327

328
      /**
329
       * Constructs the {@link ResolvedAddresses}.
330
       */
331
      public ResolvedAddresses build() {
332
        return new ResolvedAddresses(addresses, attributes, loadBalancingPolicyConfig);
1✔
333
      }
334
    }
335

336
    @Override
337
    public String toString() {
338
      return MoreObjects.toStringHelper(this)
1✔
339
          .add("addresses", addresses)
1✔
340
          .add("loadBalancingPolicyConfig", loadBalancingPolicyConfig)
1✔
341
          .add("attributes", attributes)
1✔
342
          .toString();
1✔
343
    }
344

345
    @Override
346
    public int hashCode() {
347
      return Objects.hashCode(addresses, attributes, loadBalancingPolicyConfig);
×
348
    }
349

350
    @Override
351
    public boolean equals(Object obj) {
352
      if (!(obj instanceof ResolvedAddresses)) {
1✔
353
        return false;
×
354
      }
355
      ResolvedAddresses that = (ResolvedAddresses) obj;
1✔
356
      return Objects.equal(this.addresses, that.addresses)
1✔
357
          && Objects.equal(this.attributes, that.attributes)
1✔
358
          && Objects.equal(this.loadBalancingPolicyConfig, that.loadBalancingPolicyConfig);
1✔
359
    }
360
  }
361

362
  /**
363
   * Handles an error from the name resolution system.
364
   *
365
   * @param error a non-OK status
366
   * @since 1.2.0
367
   */
368
  public abstract void handleNameResolutionError(Status error);
369

370
  /**
371
   * Handles a state change on a Subchannel.
372
   *
373
   * <p>The initial state of a Subchannel is IDLE. You won't get a notification for the initial IDLE
374
   * state.
375
   *
376
   * <p>If the new state is not SHUTDOWN, this method should create a new picker and call {@link
377
   * Helper#updateBalancingState Helper.updateBalancingState()}.  Failing to do so may result in
378
   * unnecessary delays of RPCs. Please refer to {@link PickResult#withSubchannel
379
   * PickResult.withSubchannel()}'s javadoc for more information.
380
   *
381
   * <p>SHUTDOWN can only happen in two cases.  One is that LoadBalancer called {@link
382
   * Subchannel#shutdown} earlier, thus it should have already discarded this Subchannel.  The other
383
   * is that Channel is doing a {@link ManagedChannel#shutdownNow forced shutdown} or has already
384
   * terminated, thus there won't be further requests to LoadBalancer.  Therefore, the LoadBalancer
385
   * usually don't need to react to a SHUTDOWN state.
386
   *
387
   * @param subchannel the involved Subchannel
388
   * @param stateInfo the new state
389
   * @since 1.2.0
390
   * @deprecated This method will be removed.  Stop overriding it.  Instead, pass {@link
391
   *             SubchannelStateListener} to {@link Subchannel#start} to receive Subchannel state
392
   *             updates
393
   */
394
  @Deprecated
395
  public void handleSubchannelState(
396
      Subchannel subchannel, ConnectivityStateInfo stateInfo) {
397
    // Do nothing.  If the implementation doesn't implement this, it will get subchannel states from
398
    // the new API.  We don't throw because there may be forwarding LoadBalancers still plumb this.
399
  }
×
400

401
  /**
402
   * The channel asks the load-balancer to shutdown.  No more methods on this class will be called
403
   * after this method.  The implementation should shutdown all Subchannels and OOB channels, and do
404
   * any other cleanup as necessary.
405
   *
406
   * @since 1.2.0
407
   */
408
  public abstract void shutdown();
409

410
  /**
411
   * Whether this LoadBalancer can handle empty address group list to be passed to {@link
412
   * #handleResolvedAddresses(ResolvedAddresses)}.  The default implementation returns
413
   * {@code false}, meaning that if the NameResolver returns an empty list, the Channel will turn
414
   * that into an error and call {@link #handleNameResolutionError}.  LoadBalancers that want to
415
   * accept empty lists should override this method and return {@code true}.
416
   *
417
   * <p>This method should always return a constant value.  It's not specified when this will be
418
   * called.
419
   *
420
   * <p>Note that this method is only called when implementing {@code handleResolvedAddresses()}
421
   * instead of {@code acceptResolvedAddresses()}.
422
   *
423
   * @deprecated Instead of overwriting this and {@code handleResolvedAddresses()}, only
424
   *     overwrite {@code acceptResolvedAddresses()} which indicates if the addresses provided
425
   *     by the name resolver are acceptable with the {@code boolean} return value.
426
   */
427
  @Deprecated
428
  @SuppressWarnings("InlineMeSuggester")
429
  public boolean canHandleEmptyAddressListFromNameResolution() {
430
    return false;
×
431
  }
432

433
  /**
434
   * The channel asks the LoadBalancer to establish connections now (if applicable) so that the
435
   * upcoming RPC may then just pick a ready connection without waiting for connections.  This
436
   * is triggered by {@link ManagedChannel#getState ManagedChannel.getState(true)}.
437
   *
438
   * <p>If LoadBalancer doesn't override it, this is no-op.  If it infeasible to create connections
439
   * given the current state, e.g. no Subchannel has been created yet, LoadBalancer can ignore this
440
   * request.
441
   *
442
   * @since 1.22.0
443
   */
444
  public void requestConnection() {}
1✔
445

446
  /**
447
   * The main balancing logic.  It <strong>must be thread-safe</strong>. Typically it should only
448
   * synchronize on its own state, and avoid synchronizing with the LoadBalancer's state.
449
   *
450
   * @since 1.2.0
451
   */
452
  @ExperimentalApi("https://github.com/grpc/grpc-java/issues/1771")
453
  public abstract static class SubchannelPicker {
1✔
454
    /**
455
     * Make a balancing decision for a new RPC.
456
     *
457
     * @param args the pick arguments
458
     * @since 1.3.0
459
     */
460
    public abstract PickResult pickSubchannel(PickSubchannelArgs args);
461
  }
462

463
  /**
464
   * Provides arguments for a {@link SubchannelPicker#pickSubchannel(
465
   * LoadBalancer.PickSubchannelArgs)}.
466
   *
467
   * @since 1.2.0
468
   */
469
  @ExperimentalApi("https://github.com/grpc/grpc-java/issues/1771")
470
  public abstract static class PickSubchannelArgs {
1✔
471

472
    /**
473
     * Call options.
474
     *
475
     * @since 1.2.0
476
     */
477
    public abstract CallOptions getCallOptions();
478

479
    /**
480
     * Headers of the call. {@link SubchannelPicker#pickSubchannel} may mutate it before before
481
     * returning.
482
     *
483
     * @since 1.2.0
484
     */
485
    public abstract Metadata getHeaders();
486

487
    /**
488
     * Call method.
489
     *
490
     * @since 1.2.0
491
     */
492
    public abstract MethodDescriptor<?, ?> getMethodDescriptor();
493

494
    /**
495
     * Gets an object that can be informed about what sort of pick was made.
496
     */
497
    @Internal
498
    public PickDetailsConsumer getPickDetailsConsumer() {
499
      return new PickDetailsConsumer() {};
×
500
    }
501
  }
502

503
  /** Receives information about the pick being chosen. */
504
  @Internal
505
  public interface PickDetailsConsumer {
506
    /**
507
     * Optional labels that provide context of how the pick was routed. Particularly helpful for
508
     * per-RPC metrics.
509
     *
510
     * @throws NullPointerException if key or value is {@code null}
511
     */
512
    default void addOptionalLabel(String key, String value) {
513
      checkNotNull(key, "key");
1✔
514
      checkNotNull(value, "value");
1✔
515
    }
1✔
516
  }
517

518
  /**
519
   * A balancing decision made by {@link SubchannelPicker SubchannelPicker} for an RPC.
520
   *
521
   * <p>The outcome of the decision will be one of the following:
522
   * <ul>
523
   *   <li>Proceed: if a Subchannel is provided via {@link #withSubchannel withSubchannel()}, and is
524
   *       in READY state when the RPC tries to start on it, the RPC will proceed on that
525
   *       Subchannel.</li>
526
   *   <li>Error: if an error is provided via {@link #withError withError()}, and the RPC is not
527
   *       wait-for-ready (i.e., {@link CallOptions#withWaitForReady} was not called), the RPC will
528
   *       fail immediately with the given error.</li>
529
   *   <li>Buffer: in all other cases, the RPC will be buffered in the Channel, until the next
530
   *       picker is provided via {@link Helper#updateBalancingState Helper.updateBalancingState()},
531
   *       when the RPC will go through the same picking process again.</li>
532
   * </ul>
533
   *
534
   * @since 1.2.0
535
   */
536
  @Immutable
537
  @ExperimentalApi("https://github.com/grpc/grpc-java/issues/1771")
538
  public static final class PickResult {
539
    private static final PickResult NO_RESULT = new PickResult(null, null, Status.OK, false);
1✔
540

541
    @Nullable private final Subchannel subchannel;
542
    @Nullable private final ClientStreamTracer.Factory streamTracerFactory;
543
    // An error to be propagated to the application if subchannel == null
544
    // Or OK if there is no error.
545
    // subchannel being null and error being OK means RPC needs to wait
546
    private final Status status;
547
    // True if the result is created by withDrop()
548
    private final boolean drop;
549
    @Nullable private final String authorityOverride;
550
    @Nullable private final String delayType;
551
    @Nullable private final String delayReason;
552

553
    private PickResult(
554
        @Nullable Subchannel subchannel, @Nullable ClientStreamTracer.Factory streamTracerFactory,
555
        Status status, boolean drop) {
556
      this(subchannel, streamTracerFactory, status, drop, null, null, null);
1✔
557
    }
1✔
558

559
    private PickResult(
560
        @Nullable Subchannel subchannel, @Nullable ClientStreamTracer.Factory streamTracerFactory,
561
        Status status, boolean drop, @Nullable String authorityOverride) {
562
      this(subchannel, streamTracerFactory, status, drop, authorityOverride, null, null);
1✔
563
    }
1✔
564

565
    private PickResult(
566
        @Nullable Subchannel subchannel, @Nullable ClientStreamTracer.Factory streamTracerFactory,
567
        Status status, boolean drop, @Nullable String authorityOverride,
568
        @Nullable String delayType, @Nullable String delayReason) {
1✔
569
      this.subchannel = subchannel;
1✔
570
      this.streamTracerFactory = streamTracerFactory;
1✔
571
      this.status = checkNotNull(status, "status");
1✔
572
      this.drop = drop;
1✔
573
      this.authorityOverride = authorityOverride;
1✔
574
      this.delayType = delayType;
1✔
575
      this.delayReason = delayReason;
1✔
576
    }
1✔
577

578
    /**
579
     * A decision to proceed the RPC on a Subchannel.
580
     *
581
     * <p>The Subchannel should either be an original Subchannel returned by {@link
582
     * Helper#createSubchannel Helper.createSubchannel()}, or a wrapper of it preferably based on
583
     * {@code ForwardingSubchannel}.  At the very least its {@link Subchannel#getInternalSubchannel
584
     * getInternalSubchannel()} must return the same object as the one returned by the original.
585
     * Otherwise the Channel cannot use it for the RPC.
586
     *
587
     * <p>When the RPC tries to use the return Subchannel, which is briefly after this method
588
     * returns, the state of the Subchannel will decide where the RPC would go:
589
     *
590
     * <ul>
591
     *   <li>READY: the RPC will proceed on this Subchannel.</li>
592
     *   <li>IDLE: the RPC will be buffered.  Subchannel will attempt to create connection.</li>
593
     *   <li>All other states: the RPC will be buffered.</li>
594
     * </ul>
595
     *
596
     * <p><strong>All buffered RPCs will stay buffered</strong> until the next call of {@link
597
     * Helper#updateBalancingState Helper.updateBalancingState()}, which will trigger a new picking
598
     * process.
599
     *
600
     * <p>Note that Subchannel's state may change at the same time the picker is making the
601
     * decision, which means the decision may be made with (to-be) outdated information.  For
602
     * example, a picker may return a Subchannel known to be READY, but it has become IDLE when is
603
     * about to be used by the RPC, which makes the RPC to be buffered.  The LoadBalancer will soon
604
     * learn about the Subchannels' transition from READY to IDLE, create a new picker and allow the
605
     * RPC to use another READY transport if there is any.
606
     *
607
     * <p>You will want to avoid running into a situation where there are READY Subchannels out
608
     * there but some RPCs are still buffered for longer than a brief time.
609
     * <ul>
610
     *   <li>This can happen if you return Subchannels with states other than READY and IDLE.  For
611
     *       example, suppose you round-robin on 2 Subchannels, in READY and CONNECTING states
612
     *       respectively.  If the picker ignores the state and pick them equally, 50% of RPCs will
613
     *       be stuck in buffered state until both Subchannels are READY.</li>
614
     *   <li>This can also happen if you don't create a new picker at key state changes of
615
     *       Subchannels.  Take the above round-robin example again.  Suppose you do pick only READY
616
     *       and IDLE Subchannels, and initially both Subchannels are READY.  Now one becomes IDLE,
617
     *       then CONNECTING and stays CONNECTING for a long time.  If you don't create a new picker
618
     *       in response to the CONNECTING state to exclude that Subchannel, 50% of RPCs will hit it
619
     *       and be buffered even though the other Subchannel is READY.</li>
620
     * </ul>
621
     *
622
     * <p>In order to prevent unnecessary delay of RPCs, the rules of thumb are:
623
     * <ol>
624
     *   <li>The picker should only pick Subchannels that are known as READY or IDLE.  Whether to
625
     *       pick IDLE Subchannels depends on whether you want Subchannels to connect on-demand or
626
     *       actively:
627
     *       <ul>
628
     *         <li>If you want connect-on-demand, include IDLE Subchannels in your pick results,
629
     *             because when an RPC tries to use an IDLE Subchannel, the Subchannel will try to
630
     *             connect.</li>
631
     *         <li>If you want Subchannels to be always connected even when there is no RPC, you
632
     *             would call {@link Subchannel#requestConnection Subchannel.requestConnection()}
633
     *             whenever the Subchannel has transitioned to IDLE, then you don't need to include
634
     *             IDLE Subchannels in your pick results.</li>
635
     *       </ul></li>
636
     *   <li>Always create a new picker and call {@link Helper#updateBalancingState
637
     *       Helper.updateBalancingState()} whenever {@link #handleSubchannelState
638
     *       handleSubchannelState()} is called, unless the new state is SHUTDOWN. See
639
     *       {@code handleSubchannelState}'s javadoc for more details.</li>
640
     * </ol>
641
     *
642
     * @param subchannel the picked Subchannel.  It must have been {@link Subchannel#start started}
643
     * @param streamTracerFactory if not null, will be used to trace the activities of the stream
644
     *                            created as a result of this pick. Note it's possible that no
645
     *                            stream is created at all in some cases.
646
     * @since 1.3.0
647
     */
648
    // TODO(shivaspeaks): Need to deprecate old APIs and create new ones,
649
    // per https://github.com/grpc/grpc-java/issues/12662.
650
    public static PickResult withSubchannel(
651
        Subchannel subchannel, @Nullable ClientStreamTracer.Factory streamTracerFactory) {
652
      return new PickResult(
1✔
653
          checkNotNull(subchannel, "subchannel"), streamTracerFactory, Status.OK,
1✔
654
          false);
655
    }
656

657
    /**
658
     * Same as {@code withSubchannel(subchannel, streamTracerFactory)} but with an authority name
659
     * to override in the host header.
660
     */
661
    @ExperimentalApi("https://github.com/grpc/grpc-java/issues/11656")
662
    public static PickResult withSubchannel(
663
        Subchannel subchannel, @Nullable ClientStreamTracer.Factory streamTracerFactory,
664
        @Nullable String authorityOverride) {
665
      return new PickResult(
1✔
666
          checkNotNull(subchannel, "subchannel"), streamTracerFactory, Status.OK,
1✔
667
          false, authorityOverride);
668
    }
669

670
    /**
671
     * Equivalent to {@code withSubchannel(subchannel, null)}.
672
     *
673
     * @since 1.2.0
674
     */
675
    public static PickResult withSubchannel(Subchannel subchannel) {
676
      return withSubchannel(subchannel, null);
1✔
677
    }
678

679
    /**
680
     * Creates a new {@code PickResult} with the given {@code subchannel},
681
     * but retains all other properties from this {@code PickResult}.
682
     *
683
     * @since 1.80.0
684
     */
685
    public PickResult copyWithSubchannel(Subchannel subchannel) {
686
      return new PickResult(checkNotNull(subchannel, "subchannel"), streamTracerFactory,
1✔
687
          status, drop, authorityOverride, delayType, delayReason);
688
    }
689

690
    /**
691
     * Creates a new {@code PickResult} with the given {@code streamTracerFactory},
692
     * but retains all other properties from this {@code PickResult}.
693
     *
694
     * @since 1.80.0
695
     */
696
    public PickResult copyWithStreamTracerFactory(
697
        @Nullable ClientStreamTracer.Factory streamTracerFactory) {
698
      return new PickResult(
1✔
699
          subchannel, streamTracerFactory, status, drop, authorityOverride, delayType,
700
          delayReason);
701
    }
702

703
    /**
704
     * A decision to report a connectivity error to the RPC.  If the RPC is {@link
705
     * CallOptions#withWaitForReady wait-for-ready}, it will stay buffered.  Otherwise, it will fail
706
     * with the given error.
707
     *
708
     * @param error the error status.  Must not be OK.
709
     * @since 1.2.0
710
     */
711
    public static PickResult withError(Status error) {
712
      Preconditions.checkArgument(!error.isOk(), "error status shouldn't be OK");
1✔
713
      return new PickResult(null, null, error, false);
1✔
714
    }
715

716
    /**
717
     * A decision to fail an RPC immediately.  This is a final decision and will ignore retry
718
     * policy.
719
     *
720
     * @param status the status with which the RPC will fail.  Must not be OK.
721
     * @since 1.8.0
722
     */
723
    public static PickResult withDrop(Status status) {
724
      Preconditions.checkArgument(!status.isOk(), "drop status shouldn't be OK");
1✔
725
      return new PickResult(null, null, status, true);
1✔
726
    }
727

728
    /**
729
     * No decision could be made.  The RPC will stay buffered.
730
     *
731
     * @since 1.2.0
732
     */
733
    public static PickResult withNoResult() {
734
      return NO_RESULT;
1✔
735
    }
736

737
    /**
738
     * No decision could be made.  The RPC will stay buffered with a specific delay type and reason.
739
     *
740
     * @param delayType low-cardinality root cause label (e.g., "connecting")
741
     * @param delayReason high-cardinality diagnostic string for trace events
742
     * @since 1.82.0
743
     */
744
    public static PickResult withNoResult(String delayType, String delayReason) {
745
      Preconditions.checkNotNull(delayType, "delayType");
1✔
746
      Preconditions.checkNotNull(delayReason, "delayReason");
1✔
747
      return new PickResult(null, null, Status.OK, false, null, delayType, delayReason);
1✔
748
    }
749

750
    /** Returns the delay type label if any. */
751
    @Nullable
752
    public String getDelayType() {
753
      return delayType;
1✔
754
    }
755

756
    /** Returns the diagnostic delay reason if any. */
757
    @Nullable
758
    public String getDelayReason() {
759
      return delayReason;
1✔
760
    }
761

762
    /** Returns the authority override if any. */
763
    @ExperimentalApi("https://github.com/grpc/grpc-java/issues/11656")
764
    @Nullable
765
    public String getAuthorityOverride() {
766
      return authorityOverride;
1✔
767
    }
768

769
    /**
770
     * The Subchannel if this result was created by {@link #withSubchannel withSubchannel()}, or
771
     * null otherwise.
772
     *
773
     * @since 1.2.0
774
     */
775
    @Nullable
776
    public Subchannel getSubchannel() {
777
      return subchannel;
1✔
778
    }
779

780
    /**
781
     * The stream tracer factory this result was created with.
782
     *
783
     * @since 1.3.0
784
     */
785
    @Nullable
786
    public ClientStreamTracer.Factory getStreamTracerFactory() {
787
      return streamTracerFactory;
1✔
788
    }
789

790
    /**
791
     * The status associated with this result.  Non-{@code OK} if created with {@link #withError
792
     * withError}, or {@code OK} otherwise.
793
     *
794
     * @since 1.2.0
795
     */
796
    public Status getStatus() {
797
      return status;
1✔
798
    }
799

800
    /**
801
     * Returns {@code true} if this result was created by {@link #withDrop withDrop()}.
802
     *
803
     * @since 1.8.0
804
     */
805
    public boolean isDrop() {
806
      return drop;
1✔
807
    }
808

809
    /**
810
     * Returns {@code true} if the pick was not created with {@link #withNoResult()}.
811
     */
812
    public boolean hasResult() {
813
      return !(subchannel == null && status.isOk());
1✔
814
    }
815

816
    @Override
817
    public String toString() {
818
      return MoreObjects.toStringHelper(this)
1✔
819
          .add("subchannel", subchannel)
1✔
820
          .add("streamTracerFactory", streamTracerFactory)
1✔
821
          .add("status", status)
1✔
822
          .add("drop", drop)
1✔
823
          .add("authority-override", authorityOverride)
1✔
824
          .toString();
1✔
825
    }
826

827
    @Override
828
    public int hashCode() {
829
      return Objects.hashCode(subchannel, status, streamTracerFactory, drop);
1✔
830
    }
831

832
    /**
833
     * Returns true if the {@link Subchannel}, {@link Status}, and
834
     * {@link ClientStreamTracer.Factory} all match.
835
     */
836
    @Override
837
    public boolean equals(Object other) {
838
      if (!(other instanceof PickResult)) {
1✔
839
        return false;
×
840
      }
841
      PickResult that = (PickResult) other;
1✔
842
      return Objects.equal(subchannel, that.subchannel) && Objects.equal(status, that.status)
1✔
843
          && Objects.equal(streamTracerFactory, that.streamTracerFactory)
1✔
844
          && drop == that.drop;
845
    }
846
  }
847

848
  /**
849
   * Arguments for creating a {@link Subchannel}.
850
   *
851
   * @since 1.22.0
852
   */
853
  @ExperimentalApi("https://github.com/grpc/grpc-java/issues/1771")
854
  public static final class CreateSubchannelArgs {
855
    private final List<EquivalentAddressGroup> addrs;
856
    private final Attributes attrs;
857
    private final Object[][] customOptions;
858

859
    private CreateSubchannelArgs(
860
        List<EquivalentAddressGroup> addrs, Attributes attrs, Object[][] customOptions) {
1✔
861
      this.addrs = checkNotNull(addrs, "addresses are not set");
1✔
862
      this.attrs = checkNotNull(attrs, "attrs");
1✔
863
      this.customOptions = checkNotNull(customOptions, "customOptions");
1✔
864
    }
1✔
865

866
    /**
867
     * Returns the addresses, which is an unmodifiable list.
868
     */
869
    public List<EquivalentAddressGroup> getAddresses() {
870
      return addrs;
1✔
871
    }
872

873
    /**
874
     * Returns the attributes.
875
     */
876
    public Attributes getAttributes() {
877
      return attrs;
1✔
878
    }
879

880
    /**
881
     * Get the value for a custom option or its inherent default.
882
     *
883
     * @param key Key identifying option
884
     */
885
    @SuppressWarnings("unchecked")
886
    public <T> T getOption(Key<T> key) {
887
      Preconditions.checkNotNull(key, "key");
1✔
888
      for (int i = 0; i < customOptions.length; i++) {
1✔
889
        if (key.equals(customOptions[i][0])) {
1✔
890
          return (T) customOptions[i][1];
1✔
891
        }
892
      }
893
      return key.defaultValue;
1✔
894
    }
895

896
    /**
897
     * Returns a builder with the same initial values as this object.
898
     */
899
    public Builder toBuilder() {
900
      return newBuilder().setAddresses(addrs).setAttributes(attrs).copyCustomOptions(customOptions);
1✔
901
    }
902

903
    /**
904
     * Creates a new builder.
905
     */
906
    public static Builder newBuilder() {
907
      return new Builder();
1✔
908
    }
909

910
    @Override
911
    public String toString() {
912
      return MoreObjects.toStringHelper(this)
1✔
913
          .add("addrs", addrs)
1✔
914
          .add("attrs", attrs)
1✔
915
          .add("customOptions", Arrays.deepToString(customOptions))
1✔
916
          .toString();
1✔
917
    }
918

919
    @ExperimentalApi("https://github.com/grpc/grpc-java/issues/1771")
920
    public static final class Builder {
921

922
      private static final Object[][] EMPTY_CUSTOM_OPTIONS = new Object[0][2];
1✔
923

924
      private List<EquivalentAddressGroup> addrs;
925
      private Attributes attrs = Attributes.EMPTY;
1✔
926
      private Object[][] customOptions = EMPTY_CUSTOM_OPTIONS;
1✔
927

928
      Builder() {
1✔
929
      }
1✔
930

931
      private Builder copyCustomOptions(Object[][] options) {
932
        customOptions = new Object[options.length][2];
1✔
933
        System.arraycopy(options, 0, customOptions, 0, options.length);
1✔
934
        return this;
1✔
935
      }
936

937
      /**
938
       * Add a custom option. Any existing value for the key is overwritten.
939
       *
940
       * <p>This is an <strong>optional</strong> property.
941
       *
942
       * @param key the option key
943
       * @param value the option value
944
       */
945
      public <T> Builder addOption(Key<T> key, T value) {
946
        Preconditions.checkNotNull(key, "key");
1✔
947
        Preconditions.checkNotNull(value, "value");
1✔
948

949
        int existingIdx = -1;
1✔
950
        for (int i = 0; i < customOptions.length; i++) {
1✔
951
          if (key.equals(customOptions[i][0])) {
1✔
952
            existingIdx = i;
1✔
953
            break;
1✔
954
          }
955
        }
956

957
        if (existingIdx == -1) {
1✔
958
          Object[][] newCustomOptions = new Object[customOptions.length + 1][2];
1✔
959
          System.arraycopy(customOptions, 0, newCustomOptions, 0, customOptions.length);
1✔
960
          customOptions = newCustomOptions;
1✔
961
          existingIdx = customOptions.length - 1;
1✔
962
        }
963
        customOptions[existingIdx] = new Object[]{key, value};
1✔
964
        return this;
1✔
965
      }
966

967
      /**
968
       * The addresses to connect to.  All addresses are considered equivalent and will be tried
969
       * in the order they are provided.
970
       */
971
      public Builder setAddresses(EquivalentAddressGroup addrs) {
972
        this.addrs = Collections.singletonList(addrs);
1✔
973
        return this;
1✔
974
      }
975

976
      /**
977
       * The addresses to connect to.  All addresses are considered equivalent and will
978
       * be tried in the order they are provided.
979
       *
980
       * <p>This is a <strong>required</strong> property.
981
       *
982
       * @throws IllegalArgumentException if {@code addrs} is empty
983
       */
984
      public Builder setAddresses(List<EquivalentAddressGroup> addrs) {
985
        checkArgument(!addrs.isEmpty(), "addrs is empty");
1✔
986
        this.addrs = Collections.unmodifiableList(new ArrayList<>(addrs));
1✔
987
        return this;
1✔
988
      }
989

990
      /**
991
       * Attributes provided here will be included in {@link Subchannel#getAttributes}.
992
       *
993
       * <p>This is an <strong>optional</strong> property.  Default is empty if not set.
994
       */
995
      public Builder setAttributes(Attributes attrs) {
996
        this.attrs = checkNotNull(attrs, "attrs");
1✔
997
        return this;
1✔
998
      }
999

1000
      /**
1001
       * Creates a new args object.
1002
       */
1003
      public CreateSubchannelArgs build() {
1004
        return new CreateSubchannelArgs(addrs, attrs, customOptions);
1✔
1005
      }
1006
    }
1007

1008
    /**
1009
     * Key for a key-value pair. Uses reference equality.
1010
     */
1011
    @ExperimentalApi("https://github.com/grpc/grpc-java/issues/1771")
1012
    public static final class Key<T> {
1013

1014
      private final String debugString;
1015
      private final T defaultValue;
1016

1017
      private Key(String debugString, T defaultValue) {
1✔
1018
        this.debugString = debugString;
1✔
1019
        this.defaultValue = defaultValue;
1✔
1020
      }
1✔
1021

1022
      /**
1023
       * Factory method for creating instances of {@link Key}. The default value of the key is
1024
       * {@code null}.
1025
       *
1026
       * @param debugString a debug string that describes this key.
1027
       * @param <T> Key type
1028
       * @return Key object
1029
       */
1030
      public static <T> Key<T> create(String debugString) {
1031
        Preconditions.checkNotNull(debugString, "debugString");
1✔
1032
        return new Key<>(debugString, /*defaultValue=*/ null);
1✔
1033
      }
1034

1035
      /**
1036
       * Factory method for creating instances of {@link Key}.
1037
       *
1038
       * @param debugString a debug string that describes this key.
1039
       * @param defaultValue default value to return when value for key not set
1040
       * @param <T> Key type
1041
       * @return Key object
1042
       */
1043
      public static <T> Key<T> createWithDefault(String debugString, T defaultValue) {
1044
        Preconditions.checkNotNull(debugString, "debugString");
1✔
1045
        return new Key<>(debugString, defaultValue);
1✔
1046
      }
1047

1048
      /**
1049
       * Returns the user supplied default value for this key.
1050
       */
1051
      public T getDefault() {
1052
        return defaultValue;
×
1053
      }
1054

1055
      @Override
1056
      public String toString() {
1057
        return debugString;
1✔
1058
      }
1059
    }
1060
  }
1061

1062
  /**
1063
   * Provides essentials for LoadBalancer implementations.
1064
   *
1065
   * <p>This class is thread-safe.
1066
   *
1067
   * @since 1.2.0
1068
   */
1069
  @ExperimentalApi("https://github.com/grpc/grpc-java/issues/1771")
1070
  public abstract static class Helper {
1✔
1071
    /**
1072
     * Creates a Subchannel, which is a logical connection to the given group of addresses which are
1073
     * considered equivalent.  The {@code attrs} are custom attributes associated with this
1074
     * Subchannel, and can be accessed later through {@link Subchannel#getAttributes
1075
     * Subchannel.getAttributes()}.
1076
     *
1077
     * <p>The LoadBalancer is responsible for closing unused Subchannels, and closing all
1078
     * Subchannels within {@link #shutdown}.
1079
     *
1080
     * <p>It must be called from {@link #getSynchronizationContext the Synchronization Context}
1081
     *
1082
     * @return Must return a valid Subchannel object, may not return null.
1083
     *
1084
     * @since 1.22.0
1085
     */
1086
    public Subchannel createSubchannel(CreateSubchannelArgs args) {
1087
      throw new UnsupportedOperationException();
1✔
1088
    }
1089

1090
    /**
1091
     * Create an out-of-band channel for the LoadBalancer’s own RPC needs, e.g., talking to an
1092
     * external load-balancer service.
1093
     *
1094
     * <p>The LoadBalancer is responsible for closing unused OOB channels, and closing all OOB
1095
     * channels within {@link #shutdown}.
1096
     *
1097
     * @since 1.4.0
1098
     */
1099
    public abstract ManagedChannel createOobChannel(EquivalentAddressGroup eag, String authority);
1100

1101
    /**
1102
     * Create an out-of-band channel for the LoadBalancer's own RPC needs, e.g., talking to an
1103
     * external load-balancer service. This version of the method allows multiple EAGs, so different
1104
     * addresses can have different authorities.
1105
     *
1106
     * <p>The LoadBalancer is responsible for closing unused OOB channels, and closing all OOB
1107
     * channels within {@link #shutdown}.
1108
     * */
1109
    public ManagedChannel createOobChannel(List<EquivalentAddressGroup> eag,
1110
        String authority) {
1111
      throw new UnsupportedOperationException();
×
1112
    }
1113

1114
    /**
1115
     * Updates the addresses used for connections in the {@code Channel} that was created by {@link
1116
     * #createOobChannel(EquivalentAddressGroup, String)}. This is superior to {@link
1117
     * #createOobChannel(EquivalentAddressGroup, String)} when the old and new addresses overlap,
1118
     * since the channel can continue using an existing connection.
1119
     *
1120
     * @throws IllegalArgumentException if {@code channel} was not returned from {@link
1121
     *     #createOobChannel}
1122
     * @since 1.4.0
1123
     */
1124
    public void updateOobChannelAddresses(ManagedChannel channel, EquivalentAddressGroup eag) {
1125
      throw new UnsupportedOperationException();
×
1126
    }
1127

1128
    /**
1129
     * Updates the addresses with a new EAG list. Connection is continued when old and new addresses
1130
     * overlap.
1131
     * */
1132
    public void updateOobChannelAddresses(ManagedChannel channel,
1133
        List<EquivalentAddressGroup> eag) {
1134
      throw new UnsupportedOperationException();
×
1135
    }
1136

1137
    /**
1138
     * Creates an out-of-band channel for LoadBalancer's own RPC needs, e.g., talking to an external
1139
     * load-balancer service, that is specified by a target string.  See the documentation on
1140
     * {@link ManagedChannelBuilder#forTarget} for the format of a target string.
1141
     *
1142
     * <p>The target string will be resolved by a {@link NameResolver} created according to the
1143
     * target string.
1144
     *
1145
     * <p>The LoadBalancer is responsible for closing unused OOB channels, and closing all OOB
1146
     * channels within {@link #shutdown}.
1147
     *
1148
     * @since 1.20.0
1149
     */
1150
    public ManagedChannel createResolvingOobChannel(String target) {
1151
      return createResolvingOobChannelBuilder(target).build();
1✔
1152
    }
1153

1154
    /**
1155
     * Creates an out-of-band channel builder for LoadBalancer's own RPC needs, e.g., talking to an
1156
     * external load-balancer service, that is specified by a target string.  See the documentation
1157
     * on {@link ManagedChannelBuilder#forTarget} for the format of a target string.
1158
     *
1159
     * <p>The target string will be resolved by a {@link NameResolver} created according to the
1160
     * target string.
1161
     *
1162
     * <p>The returned oob-channel builder defaults to use the same authority and ChannelCredentials
1163
     * (without bearer tokens) as the parent channel's for authentication. This is different from
1164
     * {@link #createResolvingOobChannelBuilder(String, ChannelCredentials)}.
1165
     *
1166
     * <p>The LoadBalancer is responsible for closing unused OOB channels, and closing all OOB
1167
     * channels within {@link #shutdown}.
1168
     *
1169
     * @deprecated Use {@link #createResolvingOobChannelBuilder(String, ChannelCredentials)}
1170
     *     instead.
1171
     * @since 1.31.0
1172
     */
1173
    @Deprecated
1174
    public ManagedChannelBuilder<?> createResolvingOobChannelBuilder(String target) {
1175
      throw new UnsupportedOperationException("Not implemented");
×
1176
    }
1177

1178
    /**
1179
     * Creates an out-of-band channel builder for LoadBalancer's own RPC needs, e.g., talking to an
1180
     * external load-balancer service, that is specified by a target string and credentials.  See
1181
     * the documentation on {@link Grpc#newChannelBuilder} for the format of a target string.
1182
     *
1183
     * <p>The target string will be resolved by a {@link NameResolver} created according to the
1184
     * target string.
1185
     *
1186
     * <p>The LoadBalancer is responsible for closing unused OOB channels, and closing all OOB
1187
     * channels within {@link #shutdown}.
1188
     *
1189
     * @since 1.35.0
1190
     */
1191
    public ManagedChannelBuilder<?> createResolvingOobChannelBuilder(
1192
        String target, ChannelCredentials creds) {
1193
      throw new UnsupportedOperationException();
×
1194
    }
1195

1196
    /**
1197
     * Set a new state with a new picker to the channel.
1198
     *
1199
     * <p>When a new picker is provided via {@code updateBalancingState()}, the channel will apply
1200
     * the picker on all buffered RPCs, by calling {@link SubchannelPicker#pickSubchannel(
1201
     * LoadBalancer.PickSubchannelArgs)}.
1202
     *
1203
     * <p>The channel will hold the picker and use it for all RPCs, until {@code
1204
     * updateBalancingState()} is called again and a new picker replaces the old one.  If {@code
1205
     * updateBalancingState()} has never been called, the channel will buffer all RPCs until a
1206
     * picker is provided.
1207
     *
1208
     * <p>It should be called from the Synchronization Context.  Currently will log a warning if
1209
     * violated.  It will become an exception eventually.  See <a
1210
     * href="https://github.com/grpc/grpc-java/issues/5015">#5015</a> for the background.
1211
     *
1212
     * <p>The passed state will be the channel's new state. The SHUTDOWN state should not be passed
1213
     * and its behavior is undefined.
1214
     *
1215
     * @since 1.6.0
1216
     */
1217
    public abstract void updateBalancingState(
1218
        @Nonnull ConnectivityState newState, @Nonnull SubchannelPicker newPicker);
1219

1220
    /**
1221
     * Call {@link NameResolver#refresh} on the channel's resolver.
1222
     *
1223
     * <p>It should be called from the Synchronization Context.  Currently will log a warning if
1224
     * violated.  It will become an exception eventually.  See <a
1225
     * href="https://github.com/grpc/grpc-java/issues/5015">#5015</a> for the background.
1226
     *
1227
     * @since 1.18.0
1228
     */
1229
    public void refreshNameResolution() {
1230
      throw new UnsupportedOperationException();
×
1231
    }
1232

1233
    /**
1234
     * Historically the channel automatically refreshes name resolution if any subchannel
1235
     * connection is broken. It's transitioning to let load balancers make the decision. To
1236
     * avoid silent breakages, the channel checks if {@link #refreshNameResolution} is called
1237
     * by the load balancer. If not, it will do it and log a warning. This will be removed in
1238
     * the future and load balancers are completely responsible for triggering the refresh.
1239
     * See <a href="https://github.com/grpc/grpc-java/issues/8088">#8088</a> for the background.
1240
     *
1241
     * <p>This should rarely be used, but sometimes the address for the subchannel wasn't
1242
     * provided by the name resolver and a refresh needs to be directed somewhere else instead.
1243
     * Then you can call this method to disable the short-tem check for detecting LoadBalancers
1244
     * that need to be updated for the new expected behavior.
1245
     *
1246
     * @since 1.38.0
1247
     * @deprecated Warning has been removed
1248
     */
1249
    @ExperimentalApi("https://github.com/grpc/grpc-java/issues/8088")
1250
    @Deprecated
1251
    public void ignoreRefreshNameResolutionCheck() {
1252
      // no-op
1253
    }
×
1254

1255
    /**
1256
     * Returns a {@link SynchronizationContext} that runs tasks in the same Synchronization Context
1257
     * as that the callback methods on the {@link LoadBalancer} interface are run in.
1258
     *
1259
     * <p>Work added to the synchronization context might not run immediately, so LB implementations
1260
     * must be careful to ensure that any assumptions still hold when it is executed. In particular,
1261
     * the LB might have been shut down or subchannels might have changed state.
1262
     *
1263
     * <p>Pro-tip: in order to call {@link SynchronizationContext#schedule}, you need to provide a
1264
     * {@link ScheduledExecutorService}.  {@link #getScheduledExecutorService} is provided for your
1265
     * convenience.
1266
     *
1267
     * @since 1.17.0
1268
     */
1269
    public SynchronizationContext getSynchronizationContext() {
1270
      // TODO(zhangkun): make getSynchronizationContext() abstract after runSerialized() is deleted
1271
      throw new UnsupportedOperationException();
×
1272
    }
1273

1274
    /**
1275
     * Returns a {@link ScheduledExecutorService} for scheduling delayed tasks.
1276
     *
1277
     * <p>This service is a shared resource and is only meant for quick tasks.  DO NOT block or run
1278
     * time-consuming tasks.
1279
     *
1280
     * <p>The returned service doesn't support {@link ScheduledExecutorService#shutdown shutdown()}
1281
     * and {@link ScheduledExecutorService#shutdownNow shutdownNow()}.  They will throw if called.
1282
     *
1283
     * @since 1.17.0
1284
     */
1285
    public ScheduledExecutorService getScheduledExecutorService() {
1286
      throw new UnsupportedOperationException();
×
1287
    }
1288

1289
    /**
1290
     * Returns the authority string of the channel, which is derived from the DNS-style target name.
1291
     * If overridden by a load balancer, {@link #getUnsafeChannelCredentials} must also be
1292
     * overridden to call {@link #getChannelCredentials} or provide appropriate credentials.
1293
     *
1294
     * @since 1.2.0
1295
     */
1296
    public abstract String getAuthority();
1297

1298
    /**
1299
     * Returns the target string of the channel, guaranteed to include its scheme.
1300
     */
1301
    public String getChannelTarget() {
1302
      throw new UnsupportedOperationException();
×
1303
    }
1304

1305
    /**
1306
     * Returns the ChannelCredentials used to construct the channel, without bearer tokens.
1307
     *
1308
     * @since 1.35.0
1309
     */
1310
    public ChannelCredentials getChannelCredentials() {
1311
      return getUnsafeChannelCredentials().withoutBearerTokens();
×
1312
    }
1313

1314
    /**
1315
     * Returns the UNSAFE ChannelCredentials used to construct the channel,
1316
     * including bearer tokens. Load balancers should generally have no use for
1317
     * these credentials and use of them is heavily discouraged. These must be used
1318
     * <em>very</em> carefully to avoid sending bearer tokens to untrusted servers
1319
     * as the server could then impersonate the client. Generally it is only safe
1320
     * to use these credentials when communicating with the backend.
1321
     *
1322
     * @since 1.35.0
1323
     */
1324
    public ChannelCredentials getUnsafeChannelCredentials() {
1325
      throw new UnsupportedOperationException();
×
1326
    }
1327

1328
    /**
1329
     * Returns the {@link ChannelLogger} for the Channel served by this LoadBalancer.
1330
     *
1331
     * @since 1.17.0
1332
     */
1333
    public ChannelLogger getChannelLogger() {
1334
      throw new UnsupportedOperationException();
×
1335
    }
1336

1337
    /**
1338
     * Returns the {@link NameResolver.Args} that the Channel uses to create {@link NameResolver}s.
1339
     *
1340
     * @since 1.22.0
1341
     */
1342
    public NameResolver.Args getNameResolverArgs() {
1343
      throw new UnsupportedOperationException();
×
1344
    }
1345

1346
    /**
1347
     * Returns the {@link NameResolverRegistry} that the Channel uses to look for {@link
1348
     * NameResolver}s.
1349
     *
1350
     * @since 1.22.0
1351
     */
1352
    public NameResolverRegistry getNameResolverRegistry() {
1353
      throw new UnsupportedOperationException();
×
1354
    }
1355

1356
    /**
1357
     * Returns the {@link MetricRecorder} that the channel uses to record metrics.
1358
     *
1359
     * @since 1.64.0
1360
     */
1361
    @Internal
1362
    public MetricRecorder getMetricRecorder() {
1363
      return new MetricRecorder() {};
×
1364
    }
1365
  }
1366

1367
  /**
1368
   * A logical connection to a server, or a group of equivalent servers represented by an {@link
1369
   * EquivalentAddressGroup}.
1370
   *
1371
   * <p>It maintains at most one physical connection (aka transport) for sending new RPCs, while
1372
   * also keeps track of previous transports that has been shut down but not terminated yet.
1373
   *
1374
   * <p>If there isn't an active transport yet, and an RPC is assigned to the Subchannel, it will
1375
   * create a new transport.  It won't actively create transports otherwise.  {@link
1376
   * #requestConnection requestConnection()} can be used to ask Subchannel to create a transport if
1377
   * there isn't any.
1378
   *
1379
   * <p>{@link #start} must be called prior to calling any other methods, with the exception of
1380
   * {@link #shutdown}, which can be called at any time.
1381
   *
1382
   * @since 1.2.0
1383
   */
1384
  @ExperimentalApi("https://github.com/grpc/grpc-java/issues/1771")
1385
  public abstract static class Subchannel {
1✔
1386
    /**
1387
     * Starts the Subchannel.  Can only be called once.
1388
     *
1389
     * <p>Must be called prior to any other method on this class, except for {@link #shutdown} which
1390
     * may be called at any time.
1391
     *
1392
     * <p>Must be called from the {@link Helper#getSynchronizationContext Synchronization Context},
1393
     * otherwise it may throw.  See <a href="https://github.com/grpc/grpc-java/issues/5015">
1394
     * #5015</a> for more discussions.
1395
     *
1396
     * @param listener receives state updates for this Subchannel.
1397
     */
1398
    public void start(SubchannelStateListener listener) {
1399
      throw new UnsupportedOperationException("Not implemented");
×
1400
    }
1401

1402
    /**
1403
     * Shuts down the Subchannel.  After this method is called, this Subchannel should no longer
1404
     * be returned by the latest {@link SubchannelPicker picker}, and can be safely discarded.
1405
     *
1406
     * <p>Calling it on an already shut-down Subchannel has no effect.
1407
     *
1408
     * <p>It should be called from the Synchronization Context.  Currently will log a warning if
1409
     * violated.  It will become an exception eventually.  See <a
1410
     * href="https://github.com/grpc/grpc-java/issues/5015">#5015</a> for the background.
1411
     *
1412
     * @since 1.2.0
1413
     */
1414
    public abstract void shutdown();
1415

1416
    /**
1417
     * Asks the Subchannel to create a connection (aka transport), if there isn't an active one.
1418
     *
1419
     * <p>It should be called from the Synchronization Context.  Currently will log a warning if
1420
     * violated.  It will become an exception eventually.  See <a
1421
     * href="https://github.com/grpc/grpc-java/issues/5015">#5015</a> for the background.
1422
     *
1423
     * @since 1.2.0
1424
     */
1425
    public abstract void requestConnection();
1426

1427
    /**
1428
     * Returns the addresses that this Subchannel is bound to.  This can be called only if
1429
     * the Subchannel has only one {@link EquivalentAddressGroup}.  Under the hood it calls
1430
     * {@link #getAllAddresses}.
1431
     *
1432
     * <p>It should be called from the Synchronization Context.  Currently will log a warning if
1433
     * violated.  It will become an exception eventually.  See <a
1434
     * href="https://github.com/grpc/grpc-java/issues/5015">#5015</a> for the background.
1435
     *
1436
     * @throws IllegalStateException if this subchannel has more than one EquivalentAddressGroup.
1437
     *         Use {@link #getAllAddresses} instead
1438
     * @since 1.2.0
1439
     */
1440
    public final EquivalentAddressGroup getAddresses() {
1441
      List<EquivalentAddressGroup> groups = getAllAddresses();
1✔
1442
      Preconditions.checkState(groups != null && groups.size() == 1,
1✔
1443
          "%s does not have exactly one group", groups);
1444
      return groups.get(0);
1✔
1445
    }
1446

1447
    /**
1448
     * Returns the addresses that this Subchannel is bound to. The returned list will not be empty.
1449
     *
1450
     * <p>It should be called from the Synchronization Context.  Currently will log a warning if
1451
     * violated.  It will become an exception eventually.  See <a
1452
     * href="https://github.com/grpc/grpc-java/issues/5015">#5015</a> for the background.
1453
     *
1454
     * @since 1.14.0
1455
     */
1456
    public List<EquivalentAddressGroup> getAllAddresses() {
1457
      throw new UnsupportedOperationException();
×
1458
    }
1459

1460
    /**
1461
     * The same attributes passed to {@link Helper#createSubchannel Helper.createSubchannel()}.
1462
     * LoadBalancer can use it to attach additional information here, e.g., the shard this
1463
     * Subchannel belongs to.
1464
     *
1465
     * @since 1.2.0
1466
     */
1467
    public abstract Attributes getAttributes();
1468

1469
    /**
1470
     * (Internal use only) returns a {@link Channel} that is backed by this Subchannel.  This allows
1471
     * a LoadBalancer to issue its own RPCs for auxiliary purposes, such as health-checking, on
1472
     * already-established connections.  This channel has certain restrictions:
1473
     * <ol>
1474
     *   <li>It can issue RPCs only if the Subchannel is {@code READY}. If {@link
1475
     *   Channel#newCall} is called when the Subchannel is not {@code READY}, the RPC will fail
1476
     *   immediately.</li>
1477
     *   <li>It doesn't support {@link CallOptions#withWaitForReady wait-for-ready} RPCs. Such RPCs
1478
     *   will fail immediately.</li>
1479
     * </ol>
1480
     *
1481
     * <p>RPCs made on this Channel is not counted when determining ManagedChannel's {@link
1482
     * ManagedChannelBuilder#idleTimeout idle mode}.  In other words, they won't prevent
1483
     * ManagedChannel from entering idle mode.
1484
     *
1485
     * <p>Warning: RPCs made on this channel will prevent a shut-down transport from terminating. If
1486
     * you make long-running RPCs, you need to make sure they will finish in time after the
1487
     * Subchannel has transitioned away from {@code READY} state
1488
     * (notified through {@link #handleSubchannelState}).
1489
     *
1490
     * <p>Warning: this is INTERNAL API, is not supposed to be used by external users, and may
1491
     * change without notice. If you think you must use it, please file an issue.
1492
     */
1493
    @Internal
1494
    public Channel asChannel() {
1495
      throw new UnsupportedOperationException();
×
1496
    }
1497

1498
    /**
1499
     * Returns a {@link ChannelLogger} for this Subchannel.
1500
     *
1501
     * @since 1.17.0
1502
     */
1503
    public ChannelLogger getChannelLogger() {
1504
      throw new UnsupportedOperationException();
×
1505
    }
1506

1507
    /**
1508
     * Replaces the existing addresses used with this {@code Subchannel}. If the new and old
1509
     * addresses overlap, the Subchannel can continue using an existing connection.
1510
     *
1511
     * <p>It must be called from the Synchronization Context or will throw.
1512
     *
1513
     * @throws IllegalArgumentException if {@code addrs} is empty
1514
     * @since 1.22.0
1515
     */
1516
    public void updateAddresses(List<EquivalentAddressGroup> addrs) {
1517
      throw new UnsupportedOperationException();
×
1518
    }
1519

1520
    /**
1521
     * (Internal use only) returns an object that represents the underlying subchannel that is used
1522
     * by the Channel for sending RPCs when this {@link Subchannel} is picked.  This is an opaque
1523
     * object that is both provided and consumed by the Channel.  Its type <strong>is not</strong>
1524
     * {@code Subchannel}.
1525
     *
1526
     * <p>Warning: this is INTERNAL API, is not supposed to be used by external users, and may
1527
     * change without notice. If you think you must use it, please file an issue and we can consider
1528
     * removing its "internal" status.
1529
     */
1530
    @Internal
1531
    public Object getInternalSubchannel() {
1532
      throw new UnsupportedOperationException();
×
1533
    }
1534

1535
    /**
1536
     * (Internal use only) returns attributes of the address subchannel is connected to.
1537
     *
1538
     * <p>Warning: this is INTERNAL API, is not supposed to be used by external users, and may
1539
     * change without notice. If you think you must use it, please file an issue and we can consider
1540
     * removing its "internal" status.
1541
     */
1542
    @Internal
1543
    public Attributes getConnectedAddressAttributes() {
1544
      throw new UnsupportedOperationException();
×
1545
    }
1546
  }
1547

1548
  /**
1549
   * Receives state changes for one {@link Subchannel}. All methods are run under {@link
1550
   * Helper#getSynchronizationContext}.
1551
   *
1552
   * @since 1.22.0
1553
   */
1554
  public interface SubchannelStateListener {
1555
    /**
1556
     * Handles a state change on a Subchannel.
1557
     *
1558
     * <p>The initial state of a Subchannel is IDLE. You won't get a notification for the initial
1559
     * IDLE state.
1560
     *
1561
     * <p>If the new state is not SHUTDOWN, this method should create a new picker and call {@link
1562
     * Helper#updateBalancingState Helper.updateBalancingState()}.  Failing to do so may result in
1563
     * unnecessary delays of RPCs. Please refer to {@link PickResult#withSubchannel
1564
     * PickResult.withSubchannel()}'s javadoc for more information.
1565
     *
1566
     * <p>When a subchannel's state is IDLE or TRANSIENT_FAILURE and the address for the subchannel
1567
     * was received in {@link LoadBalancer#handleResolvedAddresses}, load balancers should call
1568
     * {@link Helper#refreshNameResolution} to inform polling name resolvers that it is an
1569
     * appropriate time to refresh the addresses. Without the refresh, changes to the addresses may
1570
     * never be detected.
1571
     *
1572
     * <p>SHUTDOWN can only happen in two cases.  One is that LoadBalancer called {@link
1573
     * Subchannel#shutdown} earlier, thus it should have already discarded this Subchannel.  The
1574
     * other is that Channel is doing a {@link ManagedChannel#shutdownNow forced shutdown} or has
1575
     * already terminated, thus there won't be further requests to LoadBalancer.  Therefore, the
1576
     * LoadBalancer usually don't need to react to a SHUTDOWN state.
1577
     *
1578
     * @param newState the new state
1579
     * @since 1.22.0
1580
     */
1581
    void onSubchannelState(ConnectivityStateInfo newState);
1582
  }
1583

1584
  /**
1585
   * Factory to create {@link LoadBalancer} instance.
1586
   *
1587
   * <p>This class is thread-safe.
1588
   *
1589
   * @since 1.2.0
1590
   */
1591
  @ExperimentalApi("https://github.com/grpc/grpc-java/issues/1771")
1592
  public abstract static class Factory {
1✔
1593
    /**
1594
     * Creates a {@link LoadBalancer} that will be used inside a channel.
1595
     *
1596
     * @since 1.2.0
1597
     */
1598
    public abstract LoadBalancer newLoadBalancer(Helper helper);
1599
  }
1600

1601
  /**
1602
   * A picker that always returns an erring pick.
1603
   *
1604
   * @deprecated Use {@code new FixedResultPicker(PickResult.withError(error))} instead.
1605
   */
1606
  @Deprecated
1607
  public static final class ErrorPicker extends SubchannelPicker {
1608

1609
    private final Status error;
1610

1611
    public ErrorPicker(Status error) {
×
1612
      this.error = checkNotNull(error, "error");
×
1613
    }
×
1614

1615
    @Override
1616
    public PickResult pickSubchannel(PickSubchannelArgs args) {
1617
      return PickResult.withError(error);
×
1618
    }
1619

1620
    @Override
1621
    public String toString() {
1622
      return MoreObjects.toStringHelper(this)
×
1623
          .add("error", error)
×
1624
          .toString();
×
1625
    }
1626
  }
1627

1628
  /** A picker that always returns the same result. */
1629
  public static final class FixedResultPicker extends SubchannelPicker {
1630
    private final PickResult result;
1631

1632
    public FixedResultPicker(PickResult result) {
1✔
1633
      this.result = Preconditions.checkNotNull(result, "result");
1✔
1634
    }
1✔
1635

1636
    @Override
1637
    public PickResult pickSubchannel(PickSubchannelArgs args) {
1638
      return result;
1✔
1639
    }
1640

1641
    @Override
1642
    public String toString() {
1643
      return "FixedResultPicker(" + result + ")";
1✔
1644
    }
1645

1646
    @Override
1647
    public int hashCode() {
1648
      return result.hashCode();
1✔
1649
    }
1650

1651
    @Override
1652
    public boolean equals(Object o) {
1653
      if (!(o instanceof FixedResultPicker)) {
1✔
1654
        return false;
1✔
1655
      }
1656
      FixedResultPicker that = (FixedResultPicker) o;
1✔
1657
      return this.result.equals(that.result);
1✔
1658
    }
1659
  }
1660
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc