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

grpc / grpc-java / #19182

01 May 2024 04:19PM UTC coverage: 88.315% (-0.01%) from 88.329%
#19182

push

github

ejona86
Plumb target to load balancer

gRFC A78 has WRR and pick-first include a `grpc.target` label, defined
in A66:

> `grpc.target` : Canonicalized target URI used when creating gRPC
> Channel, e.g. "dns:///pubsub.googleapis.com:443",
> "xds:///helloworld-gke:8000". Canonicalized target URI is the form
> with the scheme included if the user didn't mention the scheme
> (`scheme://[authority]/path`). For channels such as inprocess channels
> where a target URI is not available, implementations can synthesize a
> target URI.

31448 of 35609 relevant lines covered (88.31%)

0.88 hits per line

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

75.37
/../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
import javax.annotation.concurrent.ThreadSafe;
36

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

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

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

124
  @Internal
125
  public static final Attributes.Key<Boolean>
126
      HAS_HEALTH_PRODUCER_LISTENER_KEY =
1✔
127
      Attributes.Key.create("internal:has-health-check-producer-listener");
1✔
128

129
  public static final Attributes.Key<Boolean> IS_PETIOLE_POLICY =
1✔
130
      Attributes.Key.create("io.grpc.IS_PETIOLE_POLICY");
1✔
131

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

144
    @Override
145
    public String toString() {
146
      return "EMPTY_PICKER";
×
147
    }
148
  };
149

150
  private int recursionCount;
151

152
  /**
153
   * Handles newly resolved server groups and metadata attributes from name resolution system.
154
   * {@code servers} contained in {@link EquivalentAddressGroup} should be considered equivalent
155
   * but may be flattened into a single list if needed.
156
   *
157
   * <p>Implementations should not modify the given {@code servers}.
158
   *
159
   * @param resolvedAddresses the resolved server addresses, attributes, and config.
160
   * @since 1.21.0
161
   */
162
  public void handleResolvedAddresses(ResolvedAddresses resolvedAddresses) {
163
    if (recursionCount++ == 0) {
1✔
164
      // Note that the information about the addresses actually being accepted will be lost
165
      // if you rely on this method for backward compatibility.
166
      acceptResolvedAddresses(resolvedAddresses);
1✔
167
    }
168
    recursionCount = 0;
1✔
169
  }
1✔
170

171
  /**
172
   * Accepts newly resolved addresses from the name resolution system. The {@link
173
   * EquivalentAddressGroup} addresses should be considered equivalent but may be flattened into a
174
   * single list if needed.
175
   *
176
   * <p>Implementations can choose to reject the given addresses by returning {@code false}.
177
   *
178
   * <p>Implementations should not modify the given {@code addresses}.
179
   *
180
   * @param resolvedAddresses the resolved server addresses, attributes, and config.
181
   * @return {@code true} if the resolved addresses were accepted. {@code false} if rejected.
182
   * @since 1.49.0
183
   */
184
  public Status acceptResolvedAddresses(ResolvedAddresses resolvedAddresses) {
185
    if (resolvedAddresses.getAddresses().isEmpty()
1✔
186
        && !canHandleEmptyAddressListFromNameResolution()) {
×
187
      Status unavailableStatus = Status.UNAVAILABLE.withDescription(
×
188
              "NameResolver returned no usable address. addrs=" + resolvedAddresses.getAddresses()
×
189
                      + ", attrs=" + resolvedAddresses.getAttributes());
×
190
      handleNameResolutionError(unavailableStatus);
×
191
      return unavailableStatus;
×
192
    } else {
193
      if (recursionCount++ == 0) {
1✔
194
        handleResolvedAddresses(resolvedAddresses);
×
195
      }
196
      recursionCount = 0;
1✔
197

198
      return Status.OK;
1✔
199
    }
200
  }
201

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

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

228
    /**
229
     * Factory for constructing a new Builder.
230
     *
231
     * @since 1.21.0
232
     */
233
    public static Builder newBuilder() {
234
      return new Builder();
1✔
235
    }
236

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

249
    /**
250
     * Gets the server addresses.
251
     *
252
     * @since 1.21.0
253
     */
254
    public List<EquivalentAddressGroup> getAddresses() {
255
      return addresses;
1✔
256
    }
257

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

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

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

291
      Builder() {}
1✔
292

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

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

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

324
      /**
325
       * Constructs the {@link ResolvedAddresses}.
326
       */
327
      public ResolvedAddresses build() {
328
        return new ResolvedAddresses(addresses, attributes, loadBalancingPolicyConfig);
1✔
329
      }
330
    }
331

332
    @Override
333
    public String toString() {
334
      return MoreObjects.toStringHelper(this)
1✔
335
          .add("addresses", addresses)
1✔
336
          .add("attributes", attributes)
1✔
337
          .add("loadBalancingPolicyConfig", loadBalancingPolicyConfig)
1✔
338
          .toString();
1✔
339
    }
340

341
    @Override
342
    public int hashCode() {
343
      return Objects.hashCode(addresses, attributes, loadBalancingPolicyConfig);
×
344
    }
345

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

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

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

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

406
  /**
407
   * Whether this LoadBalancer can handle empty address group list to be passed to {@link
408
   * #handleResolvedAddresses(ResolvedAddresses)}.  The default implementation returns
409
   * {@code false}, meaning that if the NameResolver returns an empty list, the Channel will turn
410
   * that into an error and call {@link #handleNameResolutionError}.  LoadBalancers that want to
411
   * accept empty lists should override this method and return {@code true}.
412
   *
413
   * <p>This method should always return a constant value.  It's not specified when this will be
414
   * called.
415
   */
416
  public boolean canHandleEmptyAddressListFromNameResolution() {
417
    return false;
×
418
  }
419

420
  /**
421
   * The channel asks the LoadBalancer to establish connections now (if applicable) so that the
422
   * upcoming RPC may then just pick a ready connection without waiting for connections.  This
423
   * is triggered by {@link ManagedChannel#getState ManagedChannel.getState(true)}.
424
   *
425
   * <p>If LoadBalancer doesn't override it, this is no-op.  If it infeasible to create connections
426
   * given the current state, e.g. no Subchannel has been created yet, LoadBalancer can ignore this
427
   * request.
428
   *
429
   * @since 1.22.0
430
   */
431
  public void requestConnection() {}
1✔
432

433
  /**
434
   * The main balancing logic.  It <strong>must be thread-safe</strong>. Typically it should only
435
   * synchronize on its own state, and avoid synchronizing with the LoadBalancer's state.
436
   *
437
   * @since 1.2.0
438
   */
439
  @ThreadSafe
440
  @ExperimentalApi("https://github.com/grpc/grpc-java/issues/1771")
441
  public abstract static class SubchannelPicker {
1✔
442
    /**
443
     * Make a balancing decision for a new RPC.
444
     *
445
     * @param args the pick arguments
446
     * @since 1.3.0
447
     */
448
    public abstract PickResult pickSubchannel(PickSubchannelArgs args);
449

450
    /**
451
     * Tries to establish connections now so that the upcoming RPC may then just pick a ready
452
     * connection without having to connect first.
453
     *
454
     * <p>No-op if unsupported.
455
     *
456
     * @deprecated override {@link LoadBalancer#requestConnection} instead.
457
     * @since 1.11.0
458
     */
459
    @Deprecated
460
    public void requestConnection() {}
×
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");
×
514
      checkNotNull(value, "value");
×
515
    }
×
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

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

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

636
    /**
637
     * Equivalent to {@code withSubchannel(subchannel, null)}.
638
     *
639
     * @since 1.2.0
640
     */
641
    public static PickResult withSubchannel(Subchannel subchannel) {
642
      return withSubchannel(subchannel, null);
1✔
643
    }
644

645
    /**
646
     * A decision to report a connectivity error to the RPC.  If the RPC is {@link
647
     * CallOptions#withWaitForReady wait-for-ready}, it will stay buffered.  Otherwise, it will fail
648
     * with the given error.
649
     *
650
     * @param error the error status.  Must not be OK.
651
     * @since 1.2.0
652
     */
653
    public static PickResult withError(Status error) {
654
      Preconditions.checkArgument(!error.isOk(), "error status shouldn't be OK");
1✔
655
      return new PickResult(null, null, error, false);
1✔
656
    }
657

658
    /**
659
     * A decision to fail an RPC immediately.  This is a final decision and will ignore retry
660
     * policy.
661
     *
662
     * @param status the status with which the RPC will fail.  Must not be OK.
663
     * @since 1.8.0
664
     */
665
    public static PickResult withDrop(Status status) {
666
      Preconditions.checkArgument(!status.isOk(), "drop status shouldn't be OK");
1✔
667
      return new PickResult(null, null, status, true);
1✔
668
    }
669

670
    /**
671
     * No decision could be made.  The RPC will stay buffered.
672
     *
673
     * @since 1.2.0
674
     */
675
    public static PickResult withNoResult() {
676
      return NO_RESULT;
1✔
677
    }
678

679
    /**
680
     * The Subchannel if this result was created by {@link #withSubchannel withSubchannel()}, or
681
     * null otherwise.
682
     *
683
     * @since 1.2.0
684
     */
685
    @Nullable
686
    public Subchannel getSubchannel() {
687
      return subchannel;
1✔
688
    }
689

690
    /**
691
     * The stream tracer factory this result was created with.
692
     *
693
     * @since 1.3.0
694
     */
695
    @Nullable
696
    public ClientStreamTracer.Factory getStreamTracerFactory() {
697
      return streamTracerFactory;
1✔
698
    }
699

700
    /**
701
     * The status associated with this result.  Non-{@code OK} if created with {@link #withError
702
     * withError}, or {@code OK} otherwise.
703
     *
704
     * @since 1.2.0
705
     */
706
    public Status getStatus() {
707
      return status;
1✔
708
    }
709

710
    /**
711
     * Returns {@code true} if this result was created by {@link #withDrop withDrop()}.
712
     *
713
     * @since 1.8.0
714
     */
715
    public boolean isDrop() {
716
      return drop;
1✔
717
    }
718

719
    @Override
720
    public String toString() {
721
      return MoreObjects.toStringHelper(this)
1✔
722
          .add("subchannel", subchannel)
1✔
723
          .add("streamTracerFactory", streamTracerFactory)
1✔
724
          .add("status", status)
1✔
725
          .add("drop", drop)
1✔
726
          .toString();
1✔
727
    }
728

729
    @Override
730
    public int hashCode() {
731
      return Objects.hashCode(subchannel, status, streamTracerFactory, drop);
×
732
    }
733

734
    /**
735
     * Returns true if the {@link Subchannel}, {@link Status}, and
736
     * {@link ClientStreamTracer.Factory} all match.
737
     */
738
    @Override
739
    public boolean equals(Object other) {
740
      if (!(other instanceof PickResult)) {
1✔
741
        return false;
×
742
      }
743
      PickResult that = (PickResult) other;
1✔
744
      return Objects.equal(subchannel, that.subchannel) && Objects.equal(status, that.status)
1✔
745
          && Objects.equal(streamTracerFactory, that.streamTracerFactory)
1✔
746
          && drop == that.drop;
747
    }
748
  }
749

750
  /**
751
   * Arguments for creating a {@link Subchannel}.
752
   *
753
   * @since 1.22.0
754
   */
755
  @ExperimentalApi("https://github.com/grpc/grpc-java/issues/1771")
756
  public static final class CreateSubchannelArgs {
757
    private final List<EquivalentAddressGroup> addrs;
758
    private final Attributes attrs;
759
    private final Object[][] customOptions;
760

761
    private CreateSubchannelArgs(
762
        List<EquivalentAddressGroup> addrs, Attributes attrs, Object[][] customOptions) {
1✔
763
      this.addrs = checkNotNull(addrs, "addresses are not set");
1✔
764
      this.attrs = checkNotNull(attrs, "attrs");
1✔
765
      this.customOptions = checkNotNull(customOptions, "customOptions");
1✔
766
    }
1✔
767

768
    /**
769
     * Returns the addresses, which is an unmodifiable list.
770
     */
771
    public List<EquivalentAddressGroup> getAddresses() {
772
      return addrs;
1✔
773
    }
774

775
    /**
776
     * Returns the attributes.
777
     */
778
    public Attributes getAttributes() {
779
      return attrs;
1✔
780
    }
781

782
    /**
783
     * Get the value for a custom option or its inherent default.
784
     *
785
     * @param key Key identifying option
786
     */
787
    @SuppressWarnings("unchecked")
788
    public <T> T getOption(Key<T> key) {
789
      Preconditions.checkNotNull(key, "key");
1✔
790
      for (int i = 0; i < customOptions.length; i++) {
1✔
791
        if (key.equals(customOptions[i][0])) {
1✔
792
          return (T) customOptions[i][1];
1✔
793
        }
794
      }
795
      return key.defaultValue;
1✔
796
    }
797

798
    /**
799
     * Returns a builder with the same initial values as this object.
800
     */
801
    public Builder toBuilder() {
802
      return newBuilder().setAddresses(addrs).setAttributes(attrs).copyCustomOptions(customOptions);
1✔
803
    }
804

805
    /**
806
     * Creates a new builder.
807
     */
808
    public static Builder newBuilder() {
809
      return new Builder();
1✔
810
    }
811

812
    @Override
813
    public String toString() {
814
      return MoreObjects.toStringHelper(this)
1✔
815
          .add("addrs", addrs)
1✔
816
          .add("attrs", attrs)
1✔
817
          .add("customOptions", Arrays.deepToString(customOptions))
1✔
818
          .toString();
1✔
819
    }
820

821
    @ExperimentalApi("https://github.com/grpc/grpc-java/issues/1771")
822
    public static final class Builder {
823

824
      private List<EquivalentAddressGroup> addrs;
825
      private Attributes attrs = Attributes.EMPTY;
1✔
826
      private Object[][] customOptions = new Object[0][2];
1✔
827

828
      Builder() {
1✔
829
      }
1✔
830

831
      private Builder copyCustomOptions(Object[][] options) {
832
        customOptions = new Object[options.length][2];
1✔
833
        System.arraycopy(options, 0, customOptions, 0, options.length);
1✔
834
        return this;
1✔
835
      }
836

837
      /**
838
       * Add a custom option. Any existing value for the key is overwritten.
839
       *
840
       * <p>This is an <strong>optional</strong> property.
841
       *
842
       * @param key the option key
843
       * @param value the option value
844
       */
845
      public <T> Builder addOption(Key<T> key, T value) {
846
        Preconditions.checkNotNull(key, "key");
1✔
847
        Preconditions.checkNotNull(value, "value");
1✔
848

849
        int existingIdx = -1;
1✔
850
        for (int i = 0; i < customOptions.length; i++) {
1✔
851
          if (key.equals(customOptions[i][0])) {
1✔
852
            existingIdx = i;
1✔
853
            break;
1✔
854
          }
855
        }
856

857
        if (existingIdx == -1) {
1✔
858
          Object[][] newCustomOptions = new Object[customOptions.length + 1][2];
1✔
859
          System.arraycopy(customOptions, 0, newCustomOptions, 0, customOptions.length);
1✔
860
          customOptions = newCustomOptions;
1✔
861
          existingIdx = customOptions.length - 1;
1✔
862
        }
863
        customOptions[existingIdx] = new Object[]{key, value};
1✔
864
        return this;
1✔
865
      }
866

867
      /**
868
       * The addresses to connect to.  All addresses are considered equivalent and will be tried
869
       * in the order they are provided.
870
       */
871
      public Builder setAddresses(EquivalentAddressGroup addrs) {
872
        this.addrs = Collections.singletonList(addrs);
1✔
873
        return this;
1✔
874
      }
875

876
      /**
877
       * The addresses to connect to.  All addresses are considered equivalent and will
878
       * be tried in the order they are provided.
879
       *
880
       * <p>This is a <strong>required</strong> property.
881
       *
882
       * @throws IllegalArgumentException if {@code addrs} is empty
883
       */
884
      public Builder setAddresses(List<EquivalentAddressGroup> addrs) {
885
        checkArgument(!addrs.isEmpty(), "addrs is empty");
1✔
886
        this.addrs = Collections.unmodifiableList(new ArrayList<>(addrs));
1✔
887
        return this;
1✔
888
      }
889

890
      /**
891
       * Attributes provided here will be included in {@link Subchannel#getAttributes}.
892
       *
893
       * <p>This is an <strong>optional</strong> property.  Default is empty if not set.
894
       */
895
      public Builder setAttributes(Attributes attrs) {
896
        this.attrs = checkNotNull(attrs, "attrs");
1✔
897
        return this;
1✔
898
      }
899

900
      /**
901
       * Creates a new args object.
902
       */
903
      public CreateSubchannelArgs build() {
904
        return new CreateSubchannelArgs(addrs, attrs, customOptions);
1✔
905
      }
906
    }
907

908
    /**
909
     * Key for a key-value pair. Uses reference equality.
910
     */
911
    @ExperimentalApi("https://github.com/grpc/grpc-java/issues/1771")
912
    public static final class Key<T> {
913

914
      private final String debugString;
915
      private final T defaultValue;
916

917
      private Key(String debugString, T defaultValue) {
1✔
918
        this.debugString = debugString;
1✔
919
        this.defaultValue = defaultValue;
1✔
920
      }
1✔
921

922
      /**
923
       * Factory method for creating instances of {@link Key}. The default value of the key is
924
       * {@code null}.
925
       *
926
       * @param debugString a debug string that describes this key.
927
       * @param <T> Key type
928
       * @return Key object
929
       */
930
      public static <T> Key<T> create(String debugString) {
931
        Preconditions.checkNotNull(debugString, "debugString");
1✔
932
        return new Key<>(debugString, /*defaultValue=*/ null);
1✔
933
      }
934

935
      /**
936
       * Factory method for creating instances of {@link Key}.
937
       *
938
       * @param debugString a debug string that describes this key.
939
       * @param defaultValue default value to return when value for key not set
940
       * @param <T> Key type
941
       * @return Key object
942
       */
943
      public static <T> Key<T> createWithDefault(String debugString, T defaultValue) {
944
        Preconditions.checkNotNull(debugString, "debugString");
1✔
945
        return new Key<>(debugString, defaultValue);
1✔
946
      }
947

948
      /**
949
       * Returns the user supplied default value for this key.
950
       */
951
      public T getDefault() {
952
        return defaultValue;
×
953
      }
954

955
      @Override
956
      public String toString() {
957
        return debugString;
1✔
958
      }
959
    }
960
  }
961

962
  /**
963
   * Provides essentials for LoadBalancer implementations.
964
   *
965
   * @since 1.2.0
966
   */
967
  @ThreadSafe
968
  @ExperimentalApi("https://github.com/grpc/grpc-java/issues/1771")
969
  public abstract static class Helper {
1✔
970
    /**
971
     * Creates a Subchannel, which is a logical connection to the given group of addresses which are
972
     * considered equivalent.  The {@code attrs} are custom attributes associated with this
973
     * Subchannel, and can be accessed later through {@link Subchannel#getAttributes
974
     * Subchannel.getAttributes()}.
975
     *
976
     * <p>The LoadBalancer is responsible for closing unused Subchannels, and closing all
977
     * Subchannels within {@link #shutdown}.
978
     *
979
     * <p>It must be called from {@link #getSynchronizationContext the Synchronization Context}
980
     *
981
     * @return Must return a valid Subchannel object, may not return null.
982
     *
983
     * @since 1.22.0
984
     */
985
    public Subchannel createSubchannel(CreateSubchannelArgs args) {
986
      throw new UnsupportedOperationException();
1✔
987
    }
988

989
    /**
990
     * Out-of-band channel for LoadBalancer’s own RPC needs, e.g., talking to an external
991
     * load-balancer service.
992
     *
993
     * <p>The LoadBalancer is responsible for closing unused OOB channels, and closing all OOB
994
     * channels within {@link #shutdown}.
995
     *
996
     * @since 1.4.0
997
     */
998
    public abstract ManagedChannel createOobChannel(EquivalentAddressGroup eag, String authority);
999

1000
    /**
1001
     * Accept a list of EAG for multiple authorities: https://github.com/grpc/grpc-java/issues/4618
1002
     * */
1003
    public ManagedChannel createOobChannel(List<EquivalentAddressGroup> eag,
1004
        String authority) {
1005
      throw new UnsupportedOperationException();
×
1006
    }
1007

1008
    /**
1009
     * Updates the addresses used for connections in the {@code Channel} that was created by {@link
1010
     * #createOobChannel(EquivalentAddressGroup, String)}. This is superior to {@link
1011
     * #createOobChannel(EquivalentAddressGroup, String)} when the old and new addresses overlap,
1012
     * since the channel can continue using an existing connection.
1013
     *
1014
     * @throws IllegalArgumentException if {@code channel} was not returned from {@link
1015
     *     #createOobChannel}
1016
     * @since 1.4.0
1017
     */
1018
    public void updateOobChannelAddresses(ManagedChannel channel, EquivalentAddressGroup eag) {
1019
      throw new UnsupportedOperationException();
×
1020
    }
1021

1022
    /**
1023
     * Updates the addresses with a new EAG list. Connection is continued when old and new addresses
1024
     * overlap.
1025
     * */
1026
    public void updateOobChannelAddresses(ManagedChannel channel,
1027
        List<EquivalentAddressGroup> eag) {
1028
      throw new UnsupportedOperationException();
×
1029
    }
1030

1031
    /**
1032
     * Creates an out-of-band channel for LoadBalancer's own RPC needs, e.g., talking to an external
1033
     * load-balancer service, that is specified by a target string.  See the documentation on
1034
     * {@link ManagedChannelBuilder#forTarget} for the format of a target string.
1035
     *
1036
     * <p>The target string will be resolved by a {@link NameResolver} created according to the
1037
     * target string.
1038
     *
1039
     * <p>The LoadBalancer is responsible for closing unused OOB channels, and closing all OOB
1040
     * channels within {@link #shutdown}.
1041
     *
1042
     * @since 1.20.0
1043
     */
1044
    public ManagedChannel createResolvingOobChannel(String target) {
1045
      return createResolvingOobChannelBuilder(target).build();
1✔
1046
    }
1047

1048
    /**
1049
     * Creates an out-of-band channel builder for LoadBalancer's own RPC needs, e.g., talking to an
1050
     * external load-balancer service, that is specified by a target string.  See the documentation
1051
     * on {@link ManagedChannelBuilder#forTarget} for the format of a target string.
1052
     *
1053
     * <p>The target string will be resolved by a {@link NameResolver} created according to the
1054
     * target string.
1055
     *
1056
     * <p>The returned oob-channel builder defaults to use the same authority and ChannelCredentials
1057
     * (without bearer tokens) as the parent channel's for authentication. This is different from
1058
     * {@link #createResolvingOobChannelBuilder(String, ChannelCredentials)}.
1059
     *
1060
     * <p>The LoadBalancer is responsible for closing unused OOB channels, and closing all OOB
1061
     * channels within {@link #shutdown}.
1062
     *
1063
     * @deprecated Use {@link #createResolvingOobChannelBuilder(String, ChannelCredentials)}
1064
     *     instead.
1065
     * @since 1.31.0
1066
     */
1067
    @Deprecated
1068
    public ManagedChannelBuilder<?> createResolvingOobChannelBuilder(String target) {
1069
      throw new UnsupportedOperationException("Not implemented");
×
1070
    }
1071

1072
    /**
1073
     * Creates an out-of-band channel builder for LoadBalancer's own RPC needs, e.g., talking to an
1074
     * external load-balancer service, that is specified by a target string and credentials.  See
1075
     * the documentation on {@link Grpc#newChannelBuilder} for the format of a target string.
1076
     *
1077
     * <p>The target string will be resolved by a {@link NameResolver} created according to the
1078
     * target string.
1079
     *
1080
     * <p>The LoadBalancer is responsible for closing unused OOB channels, and closing all OOB
1081
     * channels within {@link #shutdown}.
1082
     *
1083
     * @since 1.35.0
1084
     */
1085
    public ManagedChannelBuilder<?> createResolvingOobChannelBuilder(
1086
        String target, ChannelCredentials creds) {
1087
      throw new UnsupportedOperationException();
×
1088
    }
1089

1090
    /**
1091
     * Set a new state with a new picker to the channel.
1092
     *
1093
     * <p>When a new picker is provided via {@code updateBalancingState()}, the channel will apply
1094
     * the picker on all buffered RPCs, by calling {@link SubchannelPicker#pickSubchannel(
1095
     * LoadBalancer.PickSubchannelArgs)}.
1096
     *
1097
     * <p>The channel will hold the picker and use it for all RPCs, until {@code
1098
     * updateBalancingState()} is called again and a new picker replaces the old one.  If {@code
1099
     * updateBalancingState()} has never been called, the channel will buffer all RPCs until a
1100
     * picker is provided.
1101
     *
1102
     * <p>It should be called from the Synchronization Context.  Currently will log a warning if
1103
     * violated.  It will become an exception eventually.  See <a
1104
     * href="https://github.com/grpc/grpc-java/issues/5015">#5015</a> for the background.
1105
     *
1106
     * <p>The passed state will be the channel's new state. The SHUTDOWN state should not be passed
1107
     * and its behavior is undefined.
1108
     *
1109
     * @since 1.6.0
1110
     */
1111
    public abstract void updateBalancingState(
1112
        @Nonnull ConnectivityState newState, @Nonnull SubchannelPicker newPicker);
1113

1114
    /**
1115
     * Call {@link NameResolver#refresh} on the channel's resolver.
1116
     *
1117
     * <p>It should be called from the Synchronization Context.  Currently will log a warning if
1118
     * violated.  It will become an exception eventually.  See <a
1119
     * href="https://github.com/grpc/grpc-java/issues/5015">#5015</a> for the background.
1120
     *
1121
     * @since 1.18.0
1122
     */
1123
    public void refreshNameResolution() {
1124
      throw new UnsupportedOperationException();
×
1125
    }
1126

1127
    /**
1128
     * Historically the channel automatically refreshes name resolution if any subchannel
1129
     * connection is broken. It's transitioning to let load balancers make the decision. To
1130
     * avoid silent breakages, the channel checks if {@link #refreshNameResolution} is called
1131
     * by the load balancer. If not, it will do it and log a warning. This will be removed in
1132
     * the future and load balancers are completely responsible for triggering the refresh.
1133
     * See <a href="https://github.com/grpc/grpc-java/issues/8088">#8088</a> for the background.
1134
     *
1135
     * <p>This should rarely be used, but sometimes the address for the subchannel wasn't
1136
     * provided by the name resolver and a refresh needs to be directed somewhere else instead.
1137
     * Then you can call this method to disable the short-tem check for detecting LoadBalancers
1138
     * that need to be updated for the new expected behavior.
1139
     *
1140
     * @since 1.38.0
1141
     * @deprecated Warning has been removed
1142
     */
1143
    @ExperimentalApi("https://github.com/grpc/grpc-java/issues/8088")
1144
    @Deprecated
1145
    public void ignoreRefreshNameResolutionCheck() {
1146
      // no-op
1147
    }
×
1148

1149
    /**
1150
     * Returns a {@link SynchronizationContext} that runs tasks in the same Synchronization Context
1151
     * as that the callback methods on the {@link LoadBalancer} interface are run in.
1152
     *
1153
     * <p>Pro-tip: in order to call {@link SynchronizationContext#schedule}, you need to provide a
1154
     * {@link ScheduledExecutorService}.  {@link #getScheduledExecutorService} is provided for your
1155
     * convenience.
1156
     *
1157
     * @since 1.17.0
1158
     */
1159
    public SynchronizationContext getSynchronizationContext() {
1160
      // TODO(zhangkun): make getSynchronizationContext() abstract after runSerialized() is deleted
1161
      throw new UnsupportedOperationException();
×
1162
    }
1163

1164
    /**
1165
     * Returns a {@link ScheduledExecutorService} for scheduling delayed tasks.
1166
     *
1167
     * <p>This service is a shared resource and is only meant for quick tasks.  DO NOT block or run
1168
     * time-consuming tasks.
1169
     *
1170
     * <p>The returned service doesn't support {@link ScheduledExecutorService#shutdown shutdown()}
1171
     * and {@link ScheduledExecutorService#shutdownNow shutdownNow()}.  They will throw if called.
1172
     *
1173
     * @since 1.17.0
1174
     */
1175
    public ScheduledExecutorService getScheduledExecutorService() {
1176
      throw new UnsupportedOperationException();
×
1177
    }
1178

1179
    /**
1180
     * Returns the authority string of the channel, which is derived from the DNS-style target name.
1181
     * If overridden by a load balancer, {@link #getUnsafeChannelCredentials} must also be
1182
     * overridden to call {@link #getChannelCredentials} or provide appropriate credentials.
1183
     *
1184
     * @since 1.2.0
1185
     */
1186
    public abstract String getAuthority();
1187

1188
    /**
1189
     * Returns the target string of the channel, guaranteed to include its scheme.
1190
     */
1191
    public String getChannelTarget() {
1192
      throw new UnsupportedOperationException();
×
1193
    }
1194

1195
    /**
1196
     * Returns the ChannelCredentials used to construct the channel, without bearer tokens.
1197
     *
1198
     * @since 1.35.0
1199
     */
1200
    public ChannelCredentials getChannelCredentials() {
1201
      return getUnsafeChannelCredentials().withoutBearerTokens();
×
1202
    }
1203

1204
    /**
1205
     * Returns the UNSAFE ChannelCredentials used to construct the channel,
1206
     * including bearer tokens. Load balancers should generally have no use for
1207
     * these credentials and use of them is heavily discouraged. These must be used
1208
     * <em>very</em> carefully to avoid sending bearer tokens to untrusted servers
1209
     * as the server could then impersonate the client. Generally it is only safe
1210
     * to use these credentials when communicating with the backend.
1211
     *
1212
     * @since 1.35.0
1213
     */
1214
    public ChannelCredentials getUnsafeChannelCredentials() {
1215
      throw new UnsupportedOperationException();
×
1216
    }
1217

1218
    /**
1219
     * Returns the {@link ChannelLogger} for the Channel served by this LoadBalancer.
1220
     *
1221
     * @since 1.17.0
1222
     */
1223
    public ChannelLogger getChannelLogger() {
1224
      throw new UnsupportedOperationException();
×
1225
    }
1226

1227
    /**
1228
     * Returns the {@link NameResolver.Args} that the Channel uses to create {@link NameResolver}s.
1229
     *
1230
     * @since 1.22.0
1231
     */
1232
    public NameResolver.Args getNameResolverArgs() {
1233
      throw new UnsupportedOperationException();
×
1234
    }
1235

1236
    /**
1237
     * Returns the {@link NameResolverRegistry} that the Channel uses to look for {@link
1238
     * NameResolver}s.
1239
     *
1240
     * @since 1.22.0
1241
     */
1242
    public NameResolverRegistry getNameResolverRegistry() {
1243
      throw new UnsupportedOperationException();
×
1244
    }
1245

1246
    /**
1247
     * Returns the {@link MetricRecorder} that the channel uses to record metrics.
1248
     *
1249
     * @since 1.64.0
1250
     */
1251
    @ExperimentalApi("https://github.com/grpc/grpc-java/issues/11110")
1252
    public MetricRecorder getMetricRecorder() {
1253
      return new MetricRecorder() {};
×
1254
    }
1255
  }
1256

1257
  /**
1258
   * A logical connection to a server, or a group of equivalent servers represented by an {@link 
1259
   * EquivalentAddressGroup}.
1260
   *
1261
   * <p>It maintains at most one physical connection (aka transport) for sending new RPCs, while
1262
   * also keeps track of previous transports that has been shut down but not terminated yet.
1263
   *
1264
   * <p>If there isn't an active transport yet, and an RPC is assigned to the Subchannel, it will
1265
   * create a new transport.  It won't actively create transports otherwise.  {@link
1266
   * #requestConnection requestConnection()} can be used to ask Subchannel to create a transport if
1267
   * there isn't any.
1268
   *
1269
   * <p>{@link #start} must be called prior to calling any other methods, with the exception of
1270
   * {@link #shutdown}, which can be called at any time.
1271
   *
1272
   * @since 1.2.0
1273
   */
1274
  @ExperimentalApi("https://github.com/grpc/grpc-java/issues/1771")
1275
  public abstract static class Subchannel {
1✔
1276
    /**
1277
     * Starts the Subchannel.  Can only be called once.
1278
     *
1279
     * <p>Must be called prior to any other method on this class, except for {@link #shutdown} which
1280
     * may be called at any time.
1281
     *
1282
     * <p>Must be called from the {@link Helper#getSynchronizationContext Synchronization Context},
1283
     * otherwise it may throw.  See <a href="https://github.com/grpc/grpc-java/issues/5015">
1284
     * #5015</a> for more discussions.
1285
     *
1286
     * @param listener receives state updates for this Subchannel.
1287
     */
1288
    public void start(SubchannelStateListener listener) {
1289
      throw new UnsupportedOperationException("Not implemented");
×
1290
    }
1291

1292
    /**
1293
     * Shuts down the Subchannel.  After this method is called, this Subchannel should no longer
1294
     * be returned by the latest {@link SubchannelPicker picker}, and can be safely discarded.
1295
     *
1296
     * <p>Calling it on an already shut-down Subchannel has no effect.
1297
     *
1298
     * <p>It should be called from the Synchronization Context.  Currently will log a warning if
1299
     * violated.  It will become an exception eventually.  See <a
1300
     * href="https://github.com/grpc/grpc-java/issues/5015">#5015</a> for the background.
1301
     *
1302
     * @since 1.2.0
1303
     */
1304
    public abstract void shutdown();
1305

1306
    /**
1307
     * Asks the Subchannel to create a connection (aka transport), if there isn't an active one.
1308
     *
1309
     * <p>It should be called from the Synchronization Context.  Currently will log a warning if
1310
     * violated.  It will become an exception eventually.  See <a
1311
     * href="https://github.com/grpc/grpc-java/issues/5015">#5015</a> for the background.
1312
     *
1313
     * @since 1.2.0
1314
     */
1315
    public abstract void requestConnection();
1316

1317
    /**
1318
     * Returns the addresses that this Subchannel is bound to.  This can be called only if
1319
     * the Subchannel has only one {@link EquivalentAddressGroup}.  Under the hood it calls
1320
     * {@link #getAllAddresses}.
1321
     *
1322
     * <p>It should be called from the Synchronization Context.  Currently will log a warning if
1323
     * violated.  It will become an exception eventually.  See <a
1324
     * href="https://github.com/grpc/grpc-java/issues/5015">#5015</a> for the background.
1325
     *
1326
     * @throws IllegalStateException if this subchannel has more than one EquivalentAddressGroup.
1327
     *         Use {@link #getAllAddresses} instead
1328
     * @since 1.2.0
1329
     */
1330
    public final EquivalentAddressGroup getAddresses() {
1331
      List<EquivalentAddressGroup> groups = getAllAddresses();
1✔
1332
      Preconditions.checkState(groups != null && groups.size() == 1,
1✔
1333
          "%s does not have exactly one group", groups);
1334
      return groups.get(0);
1✔
1335
    }
1336

1337
    /**
1338
     * Returns the addresses that this Subchannel is bound to. The returned list will not be empty.
1339
     *
1340
     * <p>It should be called from the Synchronization Context.  Currently will log a warning if
1341
     * violated.  It will become an exception eventually.  See <a
1342
     * href="https://github.com/grpc/grpc-java/issues/5015">#5015</a> for the background.
1343
     *
1344
     * @since 1.14.0
1345
     */
1346
    public List<EquivalentAddressGroup> getAllAddresses() {
1347
      throw new UnsupportedOperationException();
×
1348
    }
1349

1350
    /**
1351
     * The same attributes passed to {@link Helper#createSubchannel Helper.createSubchannel()}.
1352
     * LoadBalancer can use it to attach additional information here, e.g., the shard this
1353
     * Subchannel belongs to.
1354
     *
1355
     * @since 1.2.0
1356
     */
1357
    public abstract Attributes getAttributes();
1358

1359
    /**
1360
     * (Internal use only) returns a {@link Channel} that is backed by this Subchannel.  This allows
1361
     * a LoadBalancer to issue its own RPCs for auxiliary purposes, such as health-checking, on
1362
     * already-established connections.  This channel has certain restrictions:
1363
     * <ol>
1364
     *   <li>It can issue RPCs only if the Subchannel is {@code READY}. If {@link
1365
     *   Channel#newCall} is called when the Subchannel is not {@code READY}, the RPC will fail
1366
     *   immediately.</li>
1367
     *   <li>It doesn't support {@link CallOptions#withWaitForReady wait-for-ready} RPCs. Such RPCs
1368
     *   will fail immediately.</li>
1369
     * </ol>
1370
     *
1371
     * <p>RPCs made on this Channel is not counted when determining ManagedChannel's {@link
1372
     * ManagedChannelBuilder#idleTimeout idle mode}.  In other words, they won't prevent
1373
     * ManagedChannel from entering idle mode.
1374
     *
1375
     * <p>Warning: RPCs made on this channel will prevent a shut-down transport from terminating. If
1376
     * you make long-running RPCs, you need to make sure they will finish in time after the
1377
     * Subchannel has transitioned away from {@code READY} state
1378
     * (notified through {@link #handleSubchannelState}).
1379
     *
1380
     * <p>Warning: this is INTERNAL API, is not supposed to be used by external users, and may
1381
     * change without notice. If you think you must use it, please file an issue.
1382
     */
1383
    @Internal
1384
    public Channel asChannel() {
1385
      throw new UnsupportedOperationException();
×
1386
    }
1387

1388
    /**
1389
     * Returns a {@link ChannelLogger} for this Subchannel.
1390
     *
1391
     * @since 1.17.0
1392
     */
1393
    public ChannelLogger getChannelLogger() {
1394
      throw new UnsupportedOperationException();
×
1395
    }
1396

1397
    /**
1398
     * Replaces the existing addresses used with this {@code Subchannel}. If the new and old
1399
     * addresses overlap, the Subchannel can continue using an existing connection.
1400
     *
1401
     * <p>It must be called from the Synchronization Context or will throw.
1402
     *
1403
     * @throws IllegalArgumentException if {@code addrs} is empty
1404
     * @since 1.22.0
1405
     */
1406
    public void updateAddresses(List<EquivalentAddressGroup> addrs) {
1407
      throw new UnsupportedOperationException();
×
1408
    }
1409

1410
    /**
1411
     * (Internal use only) returns an object that represents the underlying subchannel that is used
1412
     * by the Channel for sending RPCs when this {@link Subchannel} is picked.  This is an opaque
1413
     * object that is both provided and consumed by the Channel.  Its type <strong>is not</strong>
1414
     * {@code Subchannel}.
1415
     *
1416
     * <p>Warning: this is INTERNAL API, is not supposed to be used by external users, and may
1417
     * change without notice. If you think you must use it, please file an issue and we can consider
1418
     * removing its "internal" status.
1419
     */
1420
    @Internal
1421
    public Object getInternalSubchannel() {
1422
      throw new UnsupportedOperationException();
×
1423
    }
1424
  }
1425

1426
  /**
1427
   * Receives state changes for one {@link Subchannel}. All methods are run under {@link
1428
   * Helper#getSynchronizationContext}.
1429
   *
1430
   * @since 1.22.0
1431
   */
1432
  public interface SubchannelStateListener {
1433
    /**
1434
     * Handles a state change on a Subchannel.
1435
     *
1436
     * <p>The initial state of a Subchannel is IDLE. You won't get a notification for the initial
1437
     * IDLE state.
1438
     *
1439
     * <p>If the new state is not SHUTDOWN, this method should create a new picker and call {@link
1440
     * Helper#updateBalancingState Helper.updateBalancingState()}.  Failing to do so may result in
1441
     * unnecessary delays of RPCs. Please refer to {@link PickResult#withSubchannel
1442
     * PickResult.withSubchannel()}'s javadoc for more information.
1443
     *
1444
     * <p>When a subchannel's state is IDLE or TRANSIENT_FAILURE and the address for the subchannel
1445
     * was received in {@link LoadBalancer#handleResolvedAddresses}, load balancers should call
1446
     * {@link Helper#refreshNameResolution} to inform polling name resolvers that it is an
1447
     * appropriate time to refresh the addresses. Without the refresh, changes to the addresses may
1448
     * never be detected.
1449
     *
1450
     * <p>SHUTDOWN can only happen in two cases.  One is that LoadBalancer called {@link
1451
     * Subchannel#shutdown} earlier, thus it should have already discarded this Subchannel.  The
1452
     * other is that Channel is doing a {@link ManagedChannel#shutdownNow forced shutdown} or has
1453
     * already terminated, thus there won't be further requests to LoadBalancer.  Therefore, the
1454
     * LoadBalancer usually don't need to react to a SHUTDOWN state.
1455
     *
1456
     * @param newState the new state
1457
     * @since 1.22.0
1458
     */
1459
    void onSubchannelState(ConnectivityStateInfo newState);
1460
  }
1461

1462
  /**
1463
   * Factory to create {@link LoadBalancer} instance.
1464
   *
1465
   * @since 1.2.0
1466
   */
1467
  @ThreadSafe
1468
  @ExperimentalApi("https://github.com/grpc/grpc-java/issues/1771")
1469
  public abstract static class Factory {
1✔
1470
    /**
1471
     * Creates a {@link LoadBalancer} that will be used inside a channel.
1472
     *
1473
     * @since 1.2.0
1474
     */
1475
    public abstract LoadBalancer newLoadBalancer(Helper helper);
1476
  }
1477

1478
  /**
1479
   * A picker that always returns an erring pick.
1480
   *
1481
   * @deprecated Use {@code new FixedResultPicker(PickResult.withError(error))} instead.
1482
   */
1483
  @Deprecated
1484
  public static final class ErrorPicker extends SubchannelPicker {
1485

1486
    private final Status error;
1487

1488
    public ErrorPicker(Status error) {
×
1489
      this.error = checkNotNull(error, "error");
×
1490
    }
×
1491

1492
    @Override
1493
    public PickResult pickSubchannel(PickSubchannelArgs args) {
1494
      return PickResult.withError(error);
×
1495
    }
1496

1497
    @Override
1498
    public String toString() {
1499
      return MoreObjects.toStringHelper(this)
×
1500
          .add("error", error)
×
1501
          .toString();
×
1502
    }
1503
  }
1504

1505
  /** A picker that always returns the same result. */
1506
  public static final class FixedResultPicker extends SubchannelPicker {
1507
    private final PickResult result;
1508

1509
    public FixedResultPicker(PickResult result) {
1✔
1510
      this.result = Preconditions.checkNotNull(result, "result");
1✔
1511
    }
1✔
1512

1513
    @Override
1514
    public PickResult pickSubchannel(PickSubchannelArgs args) {
1515
      return result;
1✔
1516
    }
1517

1518
    @Override
1519
    public String toString() {
1520
      return "FixedResultPicker(" + result + ")";
1✔
1521
    }
1522
  }
1523
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc