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

grpc / grpc-java / #18890

09 Nov 2023 09:46PM UTC coverage: 88.206% (-0.06%) from 88.264%
#18890

push

github

web-flow
xds:Make Ring Hash LB a petiole policy (#10610)

* Update picker logic per A61 that it no longer pays attention to the first 2 elements, but rather takes the first ring element not in TF and uses that.
---------
Pulled in by rebase:
Eric Anderson  (android: Remove unneeded proguard rule 44723b6)
Terry Wilson (stub: Deprecate StreamObservers b5434e8)

30334 of 34390 relevant lines covered (88.21%)

0.88 hits per line

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

78.01
/../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
  public static final SubchannelPicker EMPTY_PICKER = new SubchannelPicker() {
1✔
120
    @Override
121
    public PickResult pickSubchannel(PickSubchannelArgs args) {
122
      return PickResult.withNoResult();
1✔
123
    }
124

125
    @Override
126
    public String toString() {
127
      return "EMPTY_PICKER";
×
128
    }
129
  };
130

131
  private int recursionCount;
132

133
  /**
134
   * Handles newly resolved server groups and metadata attributes from name resolution system.
135
   * {@code servers} contained in {@link EquivalentAddressGroup} should be considered equivalent
136
   * but may be flattened into a single list if needed.
137
   *
138
   * <p>Implementations should not modify the given {@code servers}.
139
   *
140
   * @param resolvedAddresses the resolved server addresses, attributes, and config.
141
   * @since 1.21.0
142
   */
143
  public void handleResolvedAddresses(ResolvedAddresses resolvedAddresses) {
144
    if (recursionCount++ == 0) {
1✔
145
      // Note that the information about the addresses actually being accepted will be lost
146
      // if you rely on this method for backward compatibility.
147
      acceptResolvedAddresses(resolvedAddresses);
1✔
148
    }
149
    recursionCount = 0;
1✔
150
  }
1✔
151

152
  /**
153
   * Accepts newly resolved addresses from the name resolution system. The {@link
154
   * EquivalentAddressGroup} addresses should be considered equivalent but may be flattened into a
155
   * single list if needed.
156
   *
157
   * <p>Implementations can choose to reject the given addresses by returning {@code false}.
158
   *
159
   * <p>Implementations should not modify the given {@code addresses}.
160
   *
161
   * @param resolvedAddresses the resolved server addresses, attributes, and config.
162
   * @return {@code true} if the resolved addresses were accepted. {@code false} if rejected.
163
   * @since 1.49.0
164
   */
165
  public Status acceptResolvedAddresses(ResolvedAddresses resolvedAddresses) {
166
    if (resolvedAddresses.getAddresses().isEmpty()
1✔
167
        && !canHandleEmptyAddressListFromNameResolution()) {
×
168
      Status unavailableStatus = Status.UNAVAILABLE.withDescription(
×
169
              "NameResolver returned no usable address. addrs=" + resolvedAddresses.getAddresses()
×
170
                      + ", attrs=" + resolvedAddresses.getAttributes());
×
171
      handleNameResolutionError(unavailableStatus);
×
172
      return unavailableStatus;
×
173
    } else {
174
      if (recursionCount++ == 0) {
1✔
175
        handleResolvedAddresses(resolvedAddresses);
1✔
176
      }
177
      recursionCount = 0;
1✔
178

179
      return Status.OK;
1✔
180
    }
181
  }
182

183
  /**
184
   * Represents a combination of the resolved server address, associated attributes and a load
185
   * balancing policy config.  The config is from the {@link
186
   * LoadBalancerProvider#parseLoadBalancingPolicyConfig(Map)}.
187
   *
188
   * @since 1.21.0
189
   */
190
  @ExperimentalApi("https://github.com/grpc/grpc-java/issues/1771")
191
  public static final class ResolvedAddresses {
192
    private final List<EquivalentAddressGroup> addresses;
193
    @NameResolver.ResolutionResultAttr
194
    private final Attributes attributes;
195
    @Nullable
196
    private final Object loadBalancingPolicyConfig;
197
    // Make sure to update toBuilder() below!
198

199
    private ResolvedAddresses(
200
        List<EquivalentAddressGroup> addresses,
201
        @NameResolver.ResolutionResultAttr Attributes attributes,
202
        Object loadBalancingPolicyConfig) {
1✔
203
      this.addresses =
1✔
204
          Collections.unmodifiableList(new ArrayList<>(checkNotNull(addresses, "addresses")));
1✔
205
      this.attributes = checkNotNull(attributes, "attributes");
1✔
206
      this.loadBalancingPolicyConfig = loadBalancingPolicyConfig;
1✔
207
    }
1✔
208

209
    /**
210
     * Factory for constructing a new Builder.
211
     *
212
     * @since 1.21.0
213
     */
214
    public static Builder newBuilder() {
215
      return new Builder();
1✔
216
    }
217

218
    /**
219
     * Converts this back to a builder.
220
     *
221
     * @since 1.21.0
222
     */
223
    public Builder toBuilder() {
224
      return newBuilder()
1✔
225
          .setAddresses(addresses)
1✔
226
          .setAttributes(attributes)
1✔
227
          .setLoadBalancingPolicyConfig(loadBalancingPolicyConfig);
1✔
228
    }
229

230
    /**
231
     * Gets the server addresses.
232
     *
233
     * @since 1.21.0
234
     */
235
    public List<EquivalentAddressGroup> getAddresses() {
236
      return addresses;
1✔
237
    }
238

239
    /**
240
     * Gets the attributes associated with these addresses.  If this was not previously set,
241
     * {@link Attributes#EMPTY} will be returned.
242
     *
243
     * @since 1.21.0
244
     */
245
    @NameResolver.ResolutionResultAttr
246
    public Attributes getAttributes() {
247
      return attributes;
1✔
248
    }
249

250
    /**
251
     * Gets the domain specific load balancing policy.  This is the config produced by
252
     * {@link LoadBalancerProvider#parseLoadBalancingPolicyConfig(Map)}.
253
     *
254
     * @since 1.21.0
255
     */
256
    @Nullable
257
    public Object getLoadBalancingPolicyConfig() {
258
      return loadBalancingPolicyConfig;
1✔
259
    }
260

261
    /**
262
     * Builder for {@link ResolvedAddresses}.
263
     */
264
    @ExperimentalApi("https://github.com/grpc/grpc-java/issues/1771")
265
    public static final class Builder {
266
      private List<EquivalentAddressGroup> addresses;
267
      @NameResolver.ResolutionResultAttr
1✔
268
      private Attributes attributes = Attributes.EMPTY;
269
      @Nullable
270
      private Object loadBalancingPolicyConfig;
271

272
      Builder() {}
1✔
273

274
      /**
275
       * Sets the addresses.  This field is required.
276
       *
277
       * @return this.
278
       */
279
      public Builder setAddresses(List<EquivalentAddressGroup> addresses) {
280
        this.addresses = addresses;
1✔
281
        return this;
1✔
282
      }
283

284
      /**
285
       * Sets the attributes.  This field is optional; if not called, {@link Attributes#EMPTY}
286
       * will be used.
287
       *
288
       * @return this.
289
       */
290
      public Builder setAttributes(@NameResolver.ResolutionResultAttr Attributes attributes) {
291
        this.attributes = attributes;
1✔
292
        return this;
1✔
293
      }
294

295
      /**
296
       * Sets the load balancing policy config. This field is optional.
297
       *
298
       * @return this.
299
       */
300
      public Builder setLoadBalancingPolicyConfig(@Nullable Object loadBalancingPolicyConfig) {
301
        this.loadBalancingPolicyConfig = loadBalancingPolicyConfig;
1✔
302
        return this;
1✔
303
      }
304

305
      /**
306
       * Constructs the {@link ResolvedAddresses}.
307
       */
308
      public ResolvedAddresses build() {
309
        return new ResolvedAddresses(addresses, attributes, loadBalancingPolicyConfig);
1✔
310
      }
311
    }
312

313
    @Override
314
    public String toString() {
315
      return MoreObjects.toStringHelper(this)
1✔
316
          .add("addresses", addresses)
1✔
317
          .add("attributes", attributes)
1✔
318
          .add("loadBalancingPolicyConfig", loadBalancingPolicyConfig)
1✔
319
          .toString();
1✔
320
    }
321

322
    @Override
323
    public int hashCode() {
324
      return Objects.hashCode(addresses, attributes, loadBalancingPolicyConfig);
×
325
    }
326

327
    @Override
328
    public boolean equals(Object obj) {
329
      if (!(obj instanceof ResolvedAddresses)) {
1✔
330
        return false;
×
331
      }
332
      ResolvedAddresses that = (ResolvedAddresses) obj;
1✔
333
      return Objects.equal(this.addresses, that.addresses)
1✔
334
          && Objects.equal(this.attributes, that.attributes)
1✔
335
          && Objects.equal(this.loadBalancingPolicyConfig, that.loadBalancingPolicyConfig);
1✔
336
    }
337
  }
338

339
  /**
340
   * Handles an error from the name resolution system.
341
   *
342
   * @param error a non-OK status
343
   * @since 1.2.0
344
   */
345
  public abstract void handleNameResolutionError(Status error);
346

347
  /**
348
   * Handles a state change on a Subchannel.
349
   *
350
   * <p>The initial state of a Subchannel is IDLE. You won't get a notification for the initial IDLE
351
   * state.
352
   *
353
   * <p>If the new state is not SHUTDOWN, this method should create a new picker and call {@link
354
   * Helper#updateBalancingState Helper.updateBalancingState()}.  Failing to do so may result in
355
   * unnecessary delays of RPCs. Please refer to {@link PickResult#withSubchannel
356
   * PickResult.withSubchannel()}'s javadoc for more information.
357
   *
358
   * <p>SHUTDOWN can only happen in two cases.  One is that LoadBalancer called {@link
359
   * Subchannel#shutdown} earlier, thus it should have already discarded this Subchannel.  The other
360
   * is that Channel is doing a {@link ManagedChannel#shutdownNow forced shutdown} or has already
361
   * terminated, thus there won't be further requests to LoadBalancer.  Therefore, the LoadBalancer
362
   * usually don't need to react to a SHUTDOWN state.
363
   *
364
   * @param subchannel the involved Subchannel
365
   * @param stateInfo the new state
366
   * @since 1.2.0
367
   * @deprecated This method will be removed.  Stop overriding it.  Instead, pass {@link
368
   *             SubchannelStateListener} to {@link Subchannel#start} to receive Subchannel state
369
   *             updates
370
   */
371
  @Deprecated
372
  public void handleSubchannelState(
373
      Subchannel subchannel, ConnectivityStateInfo stateInfo) {
374
    // Do nothing.  If the implementation doesn't implement this, it will get subchannel states from
375
    // the new API.  We don't throw because there may be forwarding LoadBalancers still plumb this.
376
  }
×
377

378
  /**
379
   * The channel asks the load-balancer to shutdown.  No more methods on this class will be called
380
   * after this method.  The implementation should shutdown all Subchannels and OOB channels, and do
381
   * any other cleanup as necessary.
382
   *
383
   * @since 1.2.0
384
   */
385
  public abstract void shutdown();
386

387
  /**
388
   * Whether this LoadBalancer can handle empty address group list to be passed to {@link
389
   * #handleResolvedAddresses(ResolvedAddresses)}.  The default implementation returns
390
   * {@code false}, meaning that if the NameResolver returns an empty list, the Channel will turn
391
   * that into an error and call {@link #handleNameResolutionError}.  LoadBalancers that want to
392
   * accept empty lists should override this method and return {@code true}.
393
   *
394
   * <p>This method should always return a constant value.  It's not specified when this will be
395
   * called.
396
   */
397
  public boolean canHandleEmptyAddressListFromNameResolution() {
398
    return false;
×
399
  }
400

401
  /**
402
   * The channel asks the LoadBalancer to establish connections now (if applicable) so that the
403
   * upcoming RPC may then just pick a ready connection without waiting for connections.  This
404
   * is triggered by {@link ManagedChannel#getState ManagedChannel.getState(true)}.
405
   *
406
   * <p>If LoadBalancer doesn't override it, this is no-op.  If it infeasible to create connections
407
   * given the current state, e.g. no Subchannel has been created yet, LoadBalancer can ignore this
408
   * request.
409
   *
410
   * @since 1.22.0
411
   */
412
  public void requestConnection() {}
1✔
413

414
  /**
415
   * The main balancing logic.  It <strong>must be thread-safe</strong>. Typically it should only
416
   * synchronize on its own state, and avoid synchronizing with the LoadBalancer's state.
417
   *
418
   * @since 1.2.0
419
   */
420
  @ThreadSafe
421
  @ExperimentalApi("https://github.com/grpc/grpc-java/issues/1771")
422
  public abstract static class SubchannelPicker {
1✔
423
    /**
424
     * Make a balancing decision for a new RPC.
425
     *
426
     * @param args the pick arguments
427
     * @since 1.3.0
428
     */
429
    public abstract PickResult pickSubchannel(PickSubchannelArgs args);
430

431
    /**
432
     * Tries to establish connections now so that the upcoming RPC may then just pick a ready
433
     * connection without having to connect first.
434
     *
435
     * <p>No-op if unsupported.
436
     *
437
     * @deprecated override {@link LoadBalancer#requestConnection} instead.
438
     * @since 1.11.0
439
     */
440
    @Deprecated
441
    public void requestConnection() {}
×
442
  }
443

444
  /**
445
   * Provides arguments for a {@link SubchannelPicker#pickSubchannel(
446
   * LoadBalancer.PickSubchannelArgs)}.
447
   *
448
   * @since 1.2.0
449
   */
450
  @ExperimentalApi("https://github.com/grpc/grpc-java/issues/1771")
451
  public abstract static class PickSubchannelArgs {
1✔
452

453
    /**
454
     * Call options.
455
     *
456
     * @since 1.2.0
457
     */
458
    public abstract CallOptions getCallOptions();
459

460
    /**
461
     * Headers of the call. {@link SubchannelPicker#pickSubchannel} may mutate it before before
462
     * returning.
463
     *
464
     * @since 1.2.0
465
     */
466
    public abstract Metadata getHeaders();
467

468
    /**
469
     * Call method.
470
     *
471
     * @since 1.2.0
472
     */
473
    public abstract MethodDescriptor<?, ?> getMethodDescriptor();
474
  }
475

476
  /**
477
   * A balancing decision made by {@link SubchannelPicker SubchannelPicker} for an RPC.
478
   *
479
   * <p>The outcome of the decision will be one of the following:
480
   * <ul>
481
   *   <li>Proceed: if a Subchannel is provided via {@link #withSubchannel withSubchannel()}, and is
482
   *       in READY state when the RPC tries to start on it, the RPC will proceed on that
483
   *       Subchannel.</li>
484
   *   <li>Error: if an error is provided via {@link #withError withError()}, and the RPC is not
485
   *       wait-for-ready (i.e., {@link CallOptions#withWaitForReady} was not called), the RPC will
486
   *       fail immediately with the given error.</li>
487
   *   <li>Buffer: in all other cases, the RPC will be buffered in the Channel, until the next
488
   *       picker is provided via {@link Helper#updateBalancingState Helper.updateBalancingState()},
489
   *       when the RPC will go through the same picking process again.</li>
490
   * </ul>
491
   *
492
   * @since 1.2.0
493
   */
494
  @Immutable
495
  @ExperimentalApi("https://github.com/grpc/grpc-java/issues/1771")
496
  public static final class PickResult {
497
    private static final PickResult NO_RESULT = new PickResult(null, null, Status.OK, false);
1✔
498

499
    @Nullable private final Subchannel subchannel;
500
    @Nullable private final ClientStreamTracer.Factory streamTracerFactory;
501
    // An error to be propagated to the application if subchannel == null
502
    // Or OK if there is no error.
503
    // subchannel being null and error being OK means RPC needs to wait
504
    private final Status status;
505
    // True if the result is created by withDrop()
506
    private final boolean drop;
507

508
    private PickResult(
509
        @Nullable Subchannel subchannel, @Nullable ClientStreamTracer.Factory streamTracerFactory,
510
        Status status, boolean drop) {
1✔
511
      this.subchannel = subchannel;
1✔
512
      this.streamTracerFactory = streamTracerFactory;
1✔
513
      this.status = checkNotNull(status, "status");
1✔
514
      this.drop = drop;
1✔
515
    }
1✔
516

517
    /**
518
     * A decision to proceed the RPC on a Subchannel.
519
     *
520
     * <p>The Subchannel should either be an original Subchannel returned by {@link
521
     * Helper#createSubchannel Helper.createSubchannel()}, or a wrapper of it preferably based on
522
     * {@code ForwardingSubchannel}.  At the very least its {@link Subchannel#getInternalSubchannel
523
     * getInternalSubchannel()} must return the same object as the one returned by the original.
524
     * Otherwise the Channel cannot use it for the RPC.
525
     *
526
     * <p>When the RPC tries to use the return Subchannel, which is briefly after this method
527
     * returns, the state of the Subchannel will decide where the RPC would go:
528
     *
529
     * <ul>
530
     *   <li>READY: the RPC will proceed on this Subchannel.</li>
531
     *   <li>IDLE: the RPC will be buffered.  Subchannel will attempt to create connection.</li>
532
     *   <li>All other states: the RPC will be buffered.</li>
533
     * </ul>
534
     *
535
     * <p><strong>All buffered RPCs will stay buffered</strong> until the next call of {@link
536
     * Helper#updateBalancingState Helper.updateBalancingState()}, which will trigger a new picking
537
     * process.
538
     *
539
     * <p>Note that Subchannel's state may change at the same time the picker is making the
540
     * decision, which means the decision may be made with (to-be) outdated information.  For
541
     * example, a picker may return a Subchannel known to be READY, but it has become IDLE when is
542
     * about to be used by the RPC, which makes the RPC to be buffered.  The LoadBalancer will soon
543
     * learn about the Subchannels' transition from READY to IDLE, create a new picker and allow the
544
     * RPC to use another READY transport if there is any.
545
     *
546
     * <p>You will want to avoid running into a situation where there are READY Subchannels out
547
     * there but some RPCs are still buffered for longer than a brief time.
548
     * <ul>
549
     *   <li>This can happen if you return Subchannels with states other than READY and IDLE.  For
550
     *       example, suppose you round-robin on 2 Subchannels, in READY and CONNECTING states
551
     *       respectively.  If the picker ignores the state and pick them equally, 50% of RPCs will
552
     *       be stuck in buffered state until both Subchannels are READY.</li>
553
     *   <li>This can also happen if you don't create a new picker at key state changes of
554
     *       Subchannels.  Take the above round-robin example again.  Suppose you do pick only READY
555
     *       and IDLE Subchannels, and initially both Subchannels are READY.  Now one becomes IDLE,
556
     *       then CONNECTING and stays CONNECTING for a long time.  If you don't create a new picker
557
     *       in response to the CONNECTING state to exclude that Subchannel, 50% of RPCs will hit it
558
     *       and be buffered even though the other Subchannel is READY.</li>
559
     * </ul>
560
     *
561
     * <p>In order to prevent unnecessary delay of RPCs, the rules of thumb are:
562
     * <ol>
563
     *   <li>The picker should only pick Subchannels that are known as READY or IDLE.  Whether to
564
     *       pick IDLE Subchannels depends on whether you want Subchannels to connect on-demand or
565
     *       actively:
566
     *       <ul>
567
     *         <li>If you want connect-on-demand, include IDLE Subchannels in your pick results,
568
     *             because when an RPC tries to use an IDLE Subchannel, the Subchannel will try to
569
     *             connect.</li>
570
     *         <li>If you want Subchannels to be always connected even when there is no RPC, you
571
     *             would call {@link Subchannel#requestConnection Subchannel.requestConnection()}
572
     *             whenever the Subchannel has transitioned to IDLE, then you don't need to include
573
     *             IDLE Subchannels in your pick results.</li>
574
     *       </ul></li>
575
     *   <li>Always create a new picker and call {@link Helper#updateBalancingState
576
     *       Helper.updateBalancingState()} whenever {@link #handleSubchannelState
577
     *       handleSubchannelState()} is called, unless the new state is SHUTDOWN. See
578
     *       {@code handleSubchannelState}'s javadoc for more details.</li>
579
     * </ol>
580
     *
581
     * @param subchannel the picked Subchannel.  It must have been {@link Subchannel#start started}
582
     * @param streamTracerFactory if not null, will be used to trace the activities of the stream
583
     *                            created as a result of this pick. Note it's possible that no
584
     *                            stream is created at all in some cases.
585
     * @since 1.3.0
586
     */
587
    public static PickResult withSubchannel(
588
        Subchannel subchannel, @Nullable ClientStreamTracer.Factory streamTracerFactory) {
589
      return new PickResult(
1✔
590
          checkNotNull(subchannel, "subchannel"), streamTracerFactory, Status.OK,
1✔
591
          false);
592
    }
593

594
    /**
595
     * Equivalent to {@code withSubchannel(subchannel, null)}.
596
     *
597
     * @since 1.2.0
598
     */
599
    public static PickResult withSubchannel(Subchannel subchannel) {
600
      return withSubchannel(subchannel, null);
1✔
601
    }
602

603
    /**
604
     * A decision to report a connectivity error to the RPC.  If the RPC is {@link
605
     * CallOptions#withWaitForReady wait-for-ready}, it will stay buffered.  Otherwise, it will fail
606
     * with the given error.
607
     *
608
     * @param error the error status.  Must not be OK.
609
     * @since 1.2.0
610
     */
611
    public static PickResult withError(Status error) {
612
      Preconditions.checkArgument(!error.isOk(), "error status shouldn't be OK");
1✔
613
      return new PickResult(null, null, error, false);
1✔
614
    }
615

616
    /**
617
     * A decision to fail an RPC immediately.  This is a final decision and will ignore retry
618
     * policy.
619
     *
620
     * @param status the status with which the RPC will fail.  Must not be OK.
621
     * @since 1.8.0
622
     */
623
    public static PickResult withDrop(Status status) {
624
      Preconditions.checkArgument(!status.isOk(), "drop status shouldn't be OK");
1✔
625
      return new PickResult(null, null, status, true);
1✔
626
    }
627

628
    /**
629
     * No decision could be made.  The RPC will stay buffered.
630
     *
631
     * @since 1.2.0
632
     */
633
    public static PickResult withNoResult() {
634
      return NO_RESULT;
1✔
635
    }
636

637
    /**
638
     * The Subchannel if this result was created by {@link #withSubchannel withSubchannel()}, or
639
     * null otherwise.
640
     *
641
     * @since 1.2.0
642
     */
643
    @Nullable
644
    public Subchannel getSubchannel() {
645
      return subchannel;
1✔
646
    }
647

648
    /**
649
     * The stream tracer factory this result was created with.
650
     *
651
     * @since 1.3.0
652
     */
653
    @Nullable
654
    public ClientStreamTracer.Factory getStreamTracerFactory() {
655
      return streamTracerFactory;
1✔
656
    }
657

658
    /**
659
     * The status associated with this result.  Non-{@code OK} if created with {@link #withError
660
     * withError}, or {@code OK} otherwise.
661
     *
662
     * @since 1.2.0
663
     */
664
    public Status getStatus() {
665
      return status;
1✔
666
    }
667

668
    /**
669
     * Returns {@code true} if this result was created by {@link #withDrop withDrop()}.
670
     *
671
     * @since 1.8.0
672
     */
673
    public boolean isDrop() {
674
      return drop;
1✔
675
    }
676

677
    @Override
678
    public String toString() {
679
      return MoreObjects.toStringHelper(this)
1✔
680
          .add("subchannel", subchannel)
1✔
681
          .add("streamTracerFactory", streamTracerFactory)
1✔
682
          .add("status", status)
1✔
683
          .add("drop", drop)
1✔
684
          .toString();
1✔
685
    }
686

687
    @Override
688
    public int hashCode() {
689
      return Objects.hashCode(subchannel, status, streamTracerFactory, drop);
×
690
    }
691

692
    /**
693
     * Returns true if the {@link Subchannel}, {@link Status}, and
694
     * {@link ClientStreamTracer.Factory} all match.
695
     */
696
    @Override
697
    public boolean equals(Object other) {
698
      if (!(other instanceof PickResult)) {
1✔
699
        return false;
×
700
      }
701
      PickResult that = (PickResult) other;
1✔
702
      return Objects.equal(subchannel, that.subchannel) && Objects.equal(status, that.status)
1✔
703
          && Objects.equal(streamTracerFactory, that.streamTracerFactory)
1✔
704
          && drop == that.drop;
705
    }
706
  }
707

708
  /**
709
   * Arguments for creating a {@link Subchannel}.
710
   *
711
   * @since 1.22.0
712
   */
713
  @ExperimentalApi("https://github.com/grpc/grpc-java/issues/1771")
714
  public static final class CreateSubchannelArgs {
715
    private final List<EquivalentAddressGroup> addrs;
716
    private final Attributes attrs;
717
    private final Object[][] customOptions;
718

719
    private CreateSubchannelArgs(
720
        List<EquivalentAddressGroup> addrs, Attributes attrs, Object[][] customOptions) {
1✔
721
      this.addrs = checkNotNull(addrs, "addresses are not set");
1✔
722
      this.attrs = checkNotNull(attrs, "attrs");
1✔
723
      this.customOptions = checkNotNull(customOptions, "customOptions");
1✔
724
    }
1✔
725

726
    /**
727
     * Returns the addresses, which is an unmodifiable list.
728
     */
729
    public List<EquivalentAddressGroup> getAddresses() {
730
      return addrs;
1✔
731
    }
732

733
    /**
734
     * Returns the attributes.
735
     */
736
    public Attributes getAttributes() {
737
      return attrs;
1✔
738
    }
739

740
    /**
741
     * Get the value for a custom option or its inherent default.
742
     *
743
     * @param key Key identifying option
744
     */
745
    @SuppressWarnings("unchecked")
746
    public <T> T getOption(Key<T> key) {
747
      Preconditions.checkNotNull(key, "key");
1✔
748
      for (int i = 0; i < customOptions.length; i++) {
1✔
749
        if (key.equals(customOptions[i][0])) {
1✔
750
          return (T) customOptions[i][1];
1✔
751
        }
752
      }
753
      return key.defaultValue;
1✔
754
    }
755

756
    /**
757
     * Returns a builder with the same initial values as this object.
758
     */
759
    public Builder toBuilder() {
760
      return newBuilder().setAddresses(addrs).setAttributes(attrs).copyCustomOptions(customOptions);
1✔
761
    }
762

763
    /**
764
     * Creates a new builder.
765
     */
766
    public static Builder newBuilder() {
767
      return new Builder();
1✔
768
    }
769

770
    @Override
771
    public String toString() {
772
      return MoreObjects.toStringHelper(this)
1✔
773
          .add("addrs", addrs)
1✔
774
          .add("attrs", attrs)
1✔
775
          .add("customOptions", Arrays.deepToString(customOptions))
1✔
776
          .toString();
1✔
777
    }
778

779
    @ExperimentalApi("https://github.com/grpc/grpc-java/issues/1771")
780
    public static final class Builder {
781

782
      private List<EquivalentAddressGroup> addrs;
783
      private Attributes attrs = Attributes.EMPTY;
1✔
784
      private Object[][] customOptions = new Object[0][2];
1✔
785

786
      Builder() {
1✔
787
      }
1✔
788

789
      private Builder copyCustomOptions(Object[][] options) {
790
        customOptions = new Object[options.length][2];
1✔
791
        System.arraycopy(options, 0, customOptions, 0, options.length);
1✔
792
        return this;
1✔
793
      }
794

795
      /**
796
       * Add a custom option. Any existing value for the key is overwritten.
797
       *
798
       * <p>This is an <strong>optional</strong> property.
799
       *
800
       * @param key the option key
801
       * @param value the option value
802
       */
803
      public <T> Builder addOption(Key<T> key, T value) {
804
        Preconditions.checkNotNull(key, "key");
1✔
805
        Preconditions.checkNotNull(value, "value");
1✔
806

807
        int existingIdx = -1;
1✔
808
        for (int i = 0; i < customOptions.length; i++) {
1✔
809
          if (key.equals(customOptions[i][0])) {
1✔
810
            existingIdx = i;
1✔
811
            break;
1✔
812
          }
813
        }
814

815
        if (existingIdx == -1) {
1✔
816
          Object[][] newCustomOptions = new Object[customOptions.length + 1][2];
1✔
817
          System.arraycopy(customOptions, 0, newCustomOptions, 0, customOptions.length);
1✔
818
          customOptions = newCustomOptions;
1✔
819
          existingIdx = customOptions.length - 1;
1✔
820
        }
821
        customOptions[existingIdx] = new Object[]{key, value};
1✔
822
        return this;
1✔
823
      }
824

825
      /**
826
       * The addresses to connect to.  All addresses are considered equivalent and will be tried
827
       * in the order they are provided.
828
       */
829
      public Builder setAddresses(EquivalentAddressGroup addrs) {
830
        this.addrs = Collections.singletonList(addrs);
1✔
831
        return this;
1✔
832
      }
833

834
      /**
835
       * The addresses to connect to.  All addresses are considered equivalent and will
836
       * be tried in the order they are provided.
837
       *
838
       * <p>This is a <strong>required</strong> property.
839
       *
840
       * @throws IllegalArgumentException if {@code addrs} is empty
841
       */
842
      public Builder setAddresses(List<EquivalentAddressGroup> addrs) {
843
        checkArgument(!addrs.isEmpty(), "addrs is empty");
1✔
844
        this.addrs = Collections.unmodifiableList(new ArrayList<>(addrs));
1✔
845
        return this;
1✔
846
      }
847

848
      /**
849
       * Attributes provided here will be included in {@link Subchannel#getAttributes}.
850
       *
851
       * <p>This is an <strong>optional</strong> property.  Default is empty if not set.
852
       */
853
      public Builder setAttributes(Attributes attrs) {
854
        this.attrs = checkNotNull(attrs, "attrs");
1✔
855
        return this;
1✔
856
      }
857

858
      /**
859
       * Creates a new args object.
860
       */
861
      public CreateSubchannelArgs build() {
862
        return new CreateSubchannelArgs(addrs, attrs, customOptions);
1✔
863
      }
864
    }
865

866
    /**
867
     * Key for a key-value pair. Uses reference equality.
868
     */
869
    @ExperimentalApi("https://github.com/grpc/grpc-java/issues/1771")
870
    public static final class Key<T> {
871

872
      private final String debugString;
873
      private final T defaultValue;
874

875
      private Key(String debugString, T defaultValue) {
1✔
876
        this.debugString = debugString;
1✔
877
        this.defaultValue = defaultValue;
1✔
878
      }
1✔
879

880
      /**
881
       * Factory method for creating instances of {@link Key}. The default value of the key is
882
       * {@code null}.
883
       *
884
       * @param debugString a debug string that describes this key.
885
       * @param <T> Key type
886
       * @return Key object
887
       */
888
      public static <T> Key<T> create(String debugString) {
889
        Preconditions.checkNotNull(debugString, "debugString");
1✔
890
        return new Key<>(debugString, /*defaultValue=*/ null);
1✔
891
      }
892

893
      /**
894
       * Factory method for creating instances of {@link Key}.
895
       *
896
       * @param debugString a debug string that describes this key.
897
       * @param defaultValue default value to return when value for key not set
898
       * @param <T> Key type
899
       * @return Key object
900
       */
901
      public static <T> Key<T> createWithDefault(String debugString, T defaultValue) {
902
        Preconditions.checkNotNull(debugString, "debugString");
1✔
903
        return new Key<>(debugString, defaultValue);
1✔
904
      }
905

906
      /**
907
       * Returns the user supplied default value for this key.
908
       */
909
      public T getDefault() {
910
        return defaultValue;
×
911
      }
912

913
      @Override
914
      public String toString() {
915
        return debugString;
1✔
916
      }
917
    }
918
  }
919

920
  /**
921
   * Provides essentials for LoadBalancer implementations.
922
   *
923
   * @since 1.2.0
924
   */
925
  @ThreadSafe
926
  @ExperimentalApi("https://github.com/grpc/grpc-java/issues/1771")
927
  public abstract static class Helper {
1✔
928
    /**
929
     * Creates a Subchannel, which is a logical connection to the given group of addresses which are
930
     * considered equivalent.  The {@code attrs} are custom attributes associated with this
931
     * Subchannel, and can be accessed later through {@link Subchannel#getAttributes
932
     * Subchannel.getAttributes()}.
933
     *
934
     * <p>The LoadBalancer is responsible for closing unused Subchannels, and closing all
935
     * Subchannels within {@link #shutdown}.
936
     *
937
     * <p>It must be called from {@link #getSynchronizationContext the Synchronization Context}
938
     *
939
     * @since 1.22.0
940
     */
941
    public Subchannel createSubchannel(CreateSubchannelArgs args) {
942
      throw new UnsupportedOperationException();
1✔
943
    }
944

945
    /**
946
     * Out-of-band channel for LoadBalancer’s own RPC needs, e.g., talking to an external
947
     * load-balancer service.
948
     *
949
     * <p>The LoadBalancer is responsible for closing unused OOB channels, and closing all OOB
950
     * channels within {@link #shutdown}.
951
     *
952
     * @since 1.4.0
953
     */
954
    public abstract ManagedChannel createOobChannel(EquivalentAddressGroup eag, String authority);
955

956
    /**
957
     * Accept a list of EAG for multiple authorities: https://github.com/grpc/grpc-java/issues/4618
958
     * */
959
    public ManagedChannel createOobChannel(List<EquivalentAddressGroup> eag,
960
        String authority) {
961
      throw new UnsupportedOperationException();
×
962
    }
963

964
    /**
965
     * Updates the addresses used for connections in the {@code Channel} that was created by {@link
966
     * #createOobChannel(EquivalentAddressGroup, String)}. This is superior to {@link
967
     * #createOobChannel(EquivalentAddressGroup, String)} when the old and new addresses overlap,
968
     * since the channel can continue using an existing connection.
969
     *
970
     * @throws IllegalArgumentException if {@code channel} was not returned from {@link
971
     *     #createOobChannel}
972
     * @since 1.4.0
973
     */
974
    public void updateOobChannelAddresses(ManagedChannel channel, EquivalentAddressGroup eag) {
975
      throw new UnsupportedOperationException();
×
976
    }
977

978
    /**
979
     * Updates the addresses with a new EAG list. Connection is continued when old and new addresses
980
     * overlap.
981
     * */
982
    public void updateOobChannelAddresses(ManagedChannel channel,
983
        List<EquivalentAddressGroup> eag) {
984
      throw new UnsupportedOperationException();
×
985
    }
986

987
    /**
988
     * Creates an out-of-band channel for LoadBalancer's own RPC needs, e.g., talking to an external
989
     * load-balancer service, that is specified by a target string.  See the documentation on
990
     * {@link ManagedChannelBuilder#forTarget} for the format of a target string.
991
     *
992
     * <p>The target string will be resolved by a {@link NameResolver} created according to the
993
     * target string.
994
     *
995
     * <p>The LoadBalancer is responsible for closing unused OOB channels, and closing all OOB
996
     * channels within {@link #shutdown}.
997
     *
998
     * @since 1.20.0
999
     */
1000
    public ManagedChannel createResolvingOobChannel(String target) {
1001
      return createResolvingOobChannelBuilder(target).build();
1✔
1002
    }
1003

1004
    /**
1005
     * Creates an out-of-band channel builder for LoadBalancer's own RPC needs, e.g., talking to an
1006
     * external load-balancer service, that is specified by a target string.  See the documentation
1007
     * on {@link ManagedChannelBuilder#forTarget} for the format of a target string.
1008
     *
1009
     * <p>The target string will be resolved by a {@link NameResolver} created according to the
1010
     * target string.
1011
     *
1012
     * <p>The returned oob-channel builder defaults to use the same authority and ChannelCredentials
1013
     * (without bearer tokens) as the parent channel's for authentication. This is different from
1014
     * {@link #createResolvingOobChannelBuilder(String, ChannelCredentials)}.
1015
     *
1016
     * <p>The LoadBalancer is responsible for closing unused OOB channels, and closing all OOB
1017
     * channels within {@link #shutdown}.
1018
     *
1019
     * @deprecated Use {@link #createResolvingOobChannelBuilder(String, ChannelCredentials)}
1020
     *     instead.
1021
     * @since 1.31.0
1022
     */
1023
    @Deprecated
1024
    public ManagedChannelBuilder<?> createResolvingOobChannelBuilder(String target) {
1025
      throw new UnsupportedOperationException("Not implemented");
×
1026
    }
1027

1028
    /**
1029
     * Creates an out-of-band channel builder for LoadBalancer's own RPC needs, e.g., talking to an
1030
     * external load-balancer service, that is specified by a target string and credentials.  See
1031
     * the documentation on {@link Grpc#newChannelBuilder} for the format of a target string.
1032
     *
1033
     * <p>The target string will be resolved by a {@link NameResolver} created according to the
1034
     * target string.
1035
     *
1036
     * <p>The LoadBalancer is responsible for closing unused OOB channels, and closing all OOB
1037
     * channels within {@link #shutdown}.
1038
     *
1039
     * @since 1.35.0
1040
     */
1041
    public ManagedChannelBuilder<?> createResolvingOobChannelBuilder(
1042
        String target, ChannelCredentials creds) {
1043
      throw new UnsupportedOperationException();
×
1044
    }
1045

1046
    /**
1047
     * Set a new state with a new picker to the channel.
1048
     *
1049
     * <p>When a new picker is provided via {@code updateBalancingState()}, the channel will apply
1050
     * the picker on all buffered RPCs, by calling {@link SubchannelPicker#pickSubchannel(
1051
     * LoadBalancer.PickSubchannelArgs)}.
1052
     *
1053
     * <p>The channel will hold the picker and use it for all RPCs, until {@code
1054
     * updateBalancingState()} is called again and a new picker replaces the old one.  If {@code
1055
     * updateBalancingState()} has never been called, the channel will buffer all RPCs until a
1056
     * picker is provided.
1057
     *
1058
     * <p>It should be called from the Synchronization Context.  Currently will log a warning if
1059
     * violated.  It will become an exception eventually.  See <a
1060
     * href="https://github.com/grpc/grpc-java/issues/5015">#5015</a> for the background.
1061
     *
1062
     * <p>The passed state will be the channel's new state. The SHUTDOWN state should not be passed
1063
     * and its behavior is undefined.
1064
     *
1065
     * @since 1.6.0
1066
     */
1067
    public abstract void updateBalancingState(
1068
        @Nonnull ConnectivityState newState, @Nonnull SubchannelPicker newPicker);
1069

1070
    /**
1071
     * Call {@link NameResolver#refresh} on the channel's resolver.
1072
     *
1073
     * <p>It should be called from the Synchronization Context.  Currently will log a warning if
1074
     * violated.  It will become an exception eventually.  See <a
1075
     * href="https://github.com/grpc/grpc-java/issues/5015">#5015</a> for the background.
1076
     *
1077
     * @since 1.18.0
1078
     */
1079
    public void refreshNameResolution() {
1080
      throw new UnsupportedOperationException();
×
1081
    }
1082

1083
    /**
1084
     * Historically the channel automatically refreshes name resolution if any subchannel
1085
     * connection is broken. It's transitioning to let load balancers make the decision. To
1086
     * avoid silent breakages, the channel checks if {@link #refreshNameResolution} is called
1087
     * by the load balancer. If not, it will do it and log a warning. This will be removed in
1088
     * the future and load balancers are completely responsible for triggering the refresh.
1089
     * See <a href="https://github.com/grpc/grpc-java/issues/8088">#8088</a> for the background.
1090
     *
1091
     * <p>This should rarely be used, but sometimes the address for the subchannel wasn't
1092
     * provided by the name resolver and a refresh needs to be directed somewhere else instead.
1093
     * Then you can call this method to disable the short-tem check for detecting LoadBalancers
1094
     * that need to be updated for the new expected behavior.
1095
     *
1096
     * @since 1.38.0
1097
     * @deprecated Warning has been removed
1098
     */
1099
    @ExperimentalApi("https://github.com/grpc/grpc-java/issues/8088")
1100
    @Deprecated
1101
    public void ignoreRefreshNameResolutionCheck() {
1102
      // no-op
1103
    }
×
1104

1105
    /**
1106
     * Returns a {@link SynchronizationContext} that runs tasks in the same Synchronization Context
1107
     * as that the callback methods on the {@link LoadBalancer} interface are run in.
1108
     *
1109
     * <p>Pro-tip: in order to call {@link SynchronizationContext#schedule}, you need to provide a
1110
     * {@link ScheduledExecutorService}.  {@link #getScheduledExecutorService} is provided for your
1111
     * convenience.
1112
     *
1113
     * @since 1.17.0
1114
     */
1115
    public SynchronizationContext getSynchronizationContext() {
1116
      // TODO(zhangkun): make getSynchronizationContext() abstract after runSerialized() is deleted
1117
      throw new UnsupportedOperationException();
×
1118
    }
1119

1120
    /**
1121
     * Returns a {@link ScheduledExecutorService} for scheduling delayed tasks.
1122
     *
1123
     * <p>This service is a shared resource and is only meant for quick tasks.  DO NOT block or run
1124
     * time-consuming tasks.
1125
     *
1126
     * <p>The returned service doesn't support {@link ScheduledExecutorService#shutdown shutdown()}
1127
     * and {@link ScheduledExecutorService#shutdownNow shutdownNow()}.  They will throw if called.
1128
     *
1129
     * @since 1.17.0
1130
     */
1131
    public ScheduledExecutorService getScheduledExecutorService() {
1132
      throw new UnsupportedOperationException();
×
1133
    }
1134

1135
    /**
1136
     * Returns the authority string of the channel, which is derived from the DNS-style target name.
1137
     * If overridden by a load balancer, {@link #getUnsafeChannelCredentials} must also be
1138
     * overridden to call {@link #getChannelCredentials} or provide appropriate credentials.
1139
     *
1140
     * @since 1.2.0
1141
     */
1142
    public abstract String getAuthority();
1143

1144
    /**
1145
     * Returns the ChannelCredentials used to construct the channel, without bearer tokens.
1146
     *
1147
     * @since 1.35.0
1148
     */
1149
    public ChannelCredentials getChannelCredentials() {
1150
      return getUnsafeChannelCredentials().withoutBearerTokens();
×
1151
    }
1152

1153
    /**
1154
     * Returns the UNSAFE ChannelCredentials used to construct the channel,
1155
     * including bearer tokens. Load balancers should generally have no use for
1156
     * these credentials and use of them is heavily discouraged. These must be used
1157
     * <em>very</em> carefully to avoid sending bearer tokens to untrusted servers
1158
     * as the server could then impersonate the client. Generally it is only safe
1159
     * to use these credentials when communicating with the backend.
1160
     *
1161
     * @since 1.35.0
1162
     */
1163
    public ChannelCredentials getUnsafeChannelCredentials() {
1164
      throw new UnsupportedOperationException();
×
1165
    }
1166

1167
    /**
1168
     * Returns the {@link ChannelLogger} for the Channel served by this LoadBalancer.
1169
     *
1170
     * @since 1.17.0
1171
     */
1172
    public ChannelLogger getChannelLogger() {
1173
      throw new UnsupportedOperationException();
×
1174
    }
1175

1176
    /**
1177
     * Returns the {@link NameResolver.Args} that the Channel uses to create {@link NameResolver}s.
1178
     *
1179
     * @since 1.22.0
1180
     */
1181
    public NameResolver.Args getNameResolverArgs() {
1182
      throw new UnsupportedOperationException();
×
1183
    }
1184

1185
    /**
1186
     * Returns the {@link NameResolverRegistry} that the Channel uses to look for {@link
1187
     * NameResolver}s.
1188
     *
1189
     * @since 1.22.0
1190
     */
1191
    public NameResolverRegistry getNameResolverRegistry() {
1192
      throw new UnsupportedOperationException();
×
1193
    }
1194
  }
1195

1196
  /**
1197
   * A logical connection to a server, or a group of equivalent servers represented by an {@link 
1198
   * EquivalentAddressGroup}.
1199
   *
1200
   * <p>It maintains at most one physical connection (aka transport) for sending new RPCs, while
1201
   * also keeps track of previous transports that has been shut down but not terminated yet.
1202
   *
1203
   * <p>If there isn't an active transport yet, and an RPC is assigned to the Subchannel, it will
1204
   * create a new transport.  It won't actively create transports otherwise.  {@link
1205
   * #requestConnection requestConnection()} can be used to ask Subchannel to create a transport if
1206
   * there isn't any.
1207
   *
1208
   * <p>{@link #start} must be called prior to calling any other methods, with the exception of
1209
   * {@link #shutdown}, which can be called at any time.
1210
   *
1211
   * @since 1.2.0
1212
   */
1213
  @ExperimentalApi("https://github.com/grpc/grpc-java/issues/1771")
1214
  public abstract static class Subchannel {
1✔
1215
    /**
1216
     * Starts the Subchannel.  Can only be called once.
1217
     *
1218
     * <p>Must be called prior to any other method on this class, except for {@link #shutdown} which
1219
     * may be called at any time.
1220
     *
1221
     * <p>Must be called from the {@link Helper#getSynchronizationContext Synchronization Context},
1222
     * otherwise it may throw.  See <a href="https://github.com/grpc/grpc-java/issues/5015">
1223
     * #5015</a> for more discussions.
1224
     *
1225
     * @param listener receives state updates for this Subchannel.
1226
     */
1227
    public void start(SubchannelStateListener listener) {
1228
      throw new UnsupportedOperationException("Not implemented");
×
1229
    }
1230

1231
    /**
1232
     * Shuts down the Subchannel.  After this method is called, this Subchannel should no longer
1233
     * be returned by the latest {@link SubchannelPicker picker}, and can be safely discarded.
1234
     *
1235
     * <p>Calling it on an already shut-down Subchannel has no effect.
1236
     *
1237
     * <p>It should be called from the Synchronization Context.  Currently will log a warning if
1238
     * violated.  It will become an exception eventually.  See <a
1239
     * href="https://github.com/grpc/grpc-java/issues/5015">#5015</a> for the background.
1240
     *
1241
     * @since 1.2.0
1242
     */
1243
    public abstract void shutdown();
1244

1245
    /**
1246
     * Asks the Subchannel to create a connection (aka transport), if there isn't an active one.
1247
     *
1248
     * <p>It should be called from the Synchronization Context.  Currently will log a warning if
1249
     * violated.  It will become an exception eventually.  See <a
1250
     * href="https://github.com/grpc/grpc-java/issues/5015">#5015</a> for the background.
1251
     *
1252
     * @since 1.2.0
1253
     */
1254
    public abstract void requestConnection();
1255

1256
    /**
1257
     * Returns the addresses that this Subchannel is bound to.  This can be called only if
1258
     * the Subchannel has only one {@link EquivalentAddressGroup}.  Under the hood it calls
1259
     * {@link #getAllAddresses}.
1260
     *
1261
     * <p>It should be called from the Synchronization Context.  Currently will log a warning if
1262
     * violated.  It will become an exception eventually.  See <a
1263
     * href="https://github.com/grpc/grpc-java/issues/5015">#5015</a> for the background.
1264
     *
1265
     * @throws IllegalStateException if this subchannel has more than one EquivalentAddressGroup.
1266
     *         Use {@link #getAllAddresses} instead
1267
     * @since 1.2.0
1268
     */
1269
    public final EquivalentAddressGroup getAddresses() {
1270
      List<EquivalentAddressGroup> groups = getAllAddresses();
1✔
1271
      Preconditions.checkState(groups.size() == 1, "%s does not have exactly one group", groups);
1✔
1272
      return groups.get(0);
1✔
1273
    }
1274

1275
    /**
1276
     * Returns the addresses that this Subchannel is bound to. The returned list will not be empty.
1277
     *
1278
     * <p>It should be called from the Synchronization Context.  Currently will log a warning if
1279
     * violated.  It will become an exception eventually.  See <a
1280
     * href="https://github.com/grpc/grpc-java/issues/5015">#5015</a> for the background.
1281
     *
1282
     * @since 1.14.0
1283
     */
1284
    public List<EquivalentAddressGroup> getAllAddresses() {
1285
      throw new UnsupportedOperationException();
×
1286
    }
1287

1288
    /**
1289
     * The same attributes passed to {@link Helper#createSubchannel Helper.createSubchannel()}.
1290
     * LoadBalancer can use it to attach additional information here, e.g., the shard this
1291
     * Subchannel belongs to.
1292
     *
1293
     * @since 1.2.0
1294
     */
1295
    public abstract Attributes getAttributes();
1296

1297
    /**
1298
     * (Internal use only) returns a {@link Channel} that is backed by this Subchannel.  This allows
1299
     * a LoadBalancer to issue its own RPCs for auxiliary purposes, such as health-checking, on
1300
     * already-established connections.  This channel has certain restrictions:
1301
     * <ol>
1302
     *   <li>It can issue RPCs only if the Subchannel is {@code READY}. If {@link
1303
     *   Channel#newCall} is called when the Subchannel is not {@code READY}, the RPC will fail
1304
     *   immediately.</li>
1305
     *   <li>It doesn't support {@link CallOptions#withWaitForReady wait-for-ready} RPCs. Such RPCs
1306
     *   will fail immediately.</li>
1307
     * </ol>
1308
     *
1309
     * <p>RPCs made on this Channel is not counted when determining ManagedChannel's {@link
1310
     * ManagedChannelBuilder#idleTimeout idle mode}.  In other words, they won't prevent
1311
     * ManagedChannel from entering idle mode.
1312
     *
1313
     * <p>Warning: RPCs made on this channel will prevent a shut-down transport from terminating. If
1314
     * you make long-running RPCs, you need to make sure they will finish in time after the
1315
     * Subchannel has transitioned away from {@code READY} state
1316
     * (notified through {@link #handleSubchannelState}).
1317
     *
1318
     * <p>Warning: this is INTERNAL API, is not supposed to be used by external users, and may
1319
     * change without notice. If you think you must use it, please file an issue.
1320
     */
1321
    @Internal
1322
    public Channel asChannel() {
1323
      throw new UnsupportedOperationException();
×
1324
    }
1325

1326
    /**
1327
     * Returns a {@link ChannelLogger} for this Subchannel.
1328
     *
1329
     * @since 1.17.0
1330
     */
1331
    public ChannelLogger getChannelLogger() {
1332
      throw new UnsupportedOperationException();
×
1333
    }
1334

1335
    /**
1336
     * Replaces the existing addresses used with this {@code Subchannel}. If the new and old
1337
     * addresses overlap, the Subchannel can continue using an existing connection.
1338
     *
1339
     * <p>It must be called from the Synchronization Context or will throw.
1340
     *
1341
     * @throws IllegalArgumentException if {@code addrs} is empty
1342
     * @since 1.22.0
1343
     */
1344
    public void updateAddresses(List<EquivalentAddressGroup> addrs) {
1345
      throw new UnsupportedOperationException();
×
1346
    }
1347

1348
    /**
1349
     * (Internal use only) returns an object that represents the underlying subchannel that is used
1350
     * by the Channel for sending RPCs when this {@link Subchannel} is picked.  This is an opaque
1351
     * object that is both provided and consumed by the Channel.  Its type <strong>is not</strong>
1352
     * {@code Subchannel}.
1353
     *
1354
     * <p>Warning: this is INTERNAL API, is not supposed to be used by external users, and may
1355
     * change without notice. If you think you must use it, please file an issue and we can consider
1356
     * removing its "internal" status.
1357
     */
1358
    @Internal
1359
    public Object getInternalSubchannel() {
1360
      throw new UnsupportedOperationException();
×
1361
    }
1362
  }
1363

1364
  /**
1365
   * Receives state changes for one {@link Subchannel}. All methods are run under {@link
1366
   * Helper#getSynchronizationContext}.
1367
   *
1368
   * @since 1.22.0
1369
   */
1370
  public interface SubchannelStateListener {
1371
    /**
1372
     * Handles a state change on a Subchannel.
1373
     *
1374
     * <p>The initial state of a Subchannel is IDLE. You won't get a notification for the initial
1375
     * IDLE state.
1376
     *
1377
     * <p>If the new state is not SHUTDOWN, this method should create a new picker and call {@link
1378
     * Helper#updateBalancingState Helper.updateBalancingState()}.  Failing to do so may result in
1379
     * unnecessary delays of RPCs. Please refer to {@link PickResult#withSubchannel
1380
     * PickResult.withSubchannel()}'s javadoc for more information.
1381
     *
1382
     * <p>When a subchannel's state is IDLE or TRANSIENT_FAILURE and the address for the subchannel
1383
     * was received in {@link LoadBalancer#handleResolvedAddresses}, load balancers should call
1384
     * {@link Helper#refreshNameResolution} to inform polling name resolvers that it is an
1385
     * appropriate time to refresh the addresses. Without the refresh, changes to the addresses may
1386
     * never be detected.
1387
     *
1388
     * <p>SHUTDOWN can only happen in two cases.  One is that LoadBalancer called {@link
1389
     * Subchannel#shutdown} earlier, thus it should have already discarded this Subchannel.  The
1390
     * other is that Channel is doing a {@link ManagedChannel#shutdownNow forced shutdown} or has
1391
     * already terminated, thus there won't be further requests to LoadBalancer.  Therefore, the
1392
     * LoadBalancer usually don't need to react to a SHUTDOWN state.
1393
     *
1394
     * @param newState the new state
1395
     * @since 1.22.0
1396
     */
1397
    void onSubchannelState(ConnectivityStateInfo newState);
1398
  }
1399

1400
  /**
1401
   * Factory to create {@link LoadBalancer} instance.
1402
   *
1403
   * @since 1.2.0
1404
   */
1405
  @ThreadSafe
1406
  @ExperimentalApi("https://github.com/grpc/grpc-java/issues/1771")
1407
  public abstract static class Factory {
1✔
1408
    /**
1409
     * Creates a {@link LoadBalancer} that will be used inside a channel.
1410
     *
1411
     * @since 1.2.0
1412
     */
1413
    public abstract LoadBalancer newLoadBalancer(Helper helper);
1414
  }
1415

1416
  /**
1417
   * A picker that always returns an erring pick.
1418
   *
1419
   * @deprecated Use {@code new FixedResultPicker(PickResult.withError(error))} instead.
1420
   */
1421
  @Deprecated
1422
  public static final class ErrorPicker extends SubchannelPicker {
1423

1424
    private final Status error;
1425

1426
    public ErrorPicker(Status error) {
×
1427
      this.error = checkNotNull(error, "error");
×
1428
    }
×
1429

1430
    @Override
1431
    public PickResult pickSubchannel(PickSubchannelArgs args) {
1432
      return PickResult.withError(error);
×
1433
    }
1434

1435
    @Override
1436
    public String toString() {
1437
      return MoreObjects.toStringHelper(this)
×
1438
          .add("error", error)
×
1439
          .toString();
×
1440
    }
1441
  }
1442

1443
  /** A picker that always returns the same result. */
1444
  public static final class FixedResultPicker extends SubchannelPicker {
1445
    private final PickResult result;
1446

1447
    public FixedResultPicker(PickResult result) {
1✔
1448
      this.result = Preconditions.checkNotNull(result, "result");
1✔
1449
    }
1✔
1450

1451
    @Override
1452
    public PickResult pickSubchannel(PickSubchannelArgs args) {
1453
      return result;
1✔
1454
    }
1455

1456
    @Override
1457
    public String toString() {
1458
      return "FixedResultPicker(" + result + ")";
1✔
1459
    }
1460
  }
1461
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc