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

grpc / grpc-java / #19535

30 Oct 2024 03:41PM UTC coverage: 84.572% (-0.005%) from 84.577%
#19535

push

github

web-flow
xds: Per-rpc rewriting of the authority header based on the selected route. (#11631)

Implementation of A81.

33970 of 40167 relevant lines covered (84.57%)

0.85 hits per line

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

94.83
/../xds/src/main/java/io/grpc/xds/ClusterImplLoadBalancer.java
1
/*
2
 * Copyright 2020 The gRPC Authors
3
 *
4
 * Licensed under the Apache License, Version 2.0 (the "License");
5
 * you may not use this file except in compliance with the License.
6
 * You may obtain a copy of the License at
7
 *
8
 *     http://www.apache.org/licenses/LICENSE-2.0
9
 *
10
 * Unless required by applicable law or agreed to in writing, software
11
 * distributed under the License is distributed on an "AS IS" BASIS,
12
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
 * See the License for the specific language governing permissions and
14
 * limitations under the License.
15
 */
16

17
package io.grpc.xds;
18

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

21
import com.google.common.annotations.VisibleForTesting;
22
import com.google.common.base.MoreObjects;
23
import com.google.common.base.Strings;
24
import com.google.common.collect.ImmutableMap;
25
import com.google.protobuf.Struct;
26
import io.grpc.Attributes;
27
import io.grpc.ClientStreamTracer;
28
import io.grpc.ClientStreamTracer.StreamInfo;
29
import io.grpc.ConnectivityState;
30
import io.grpc.ConnectivityStateInfo;
31
import io.grpc.EquivalentAddressGroup;
32
import io.grpc.InternalLogId;
33
import io.grpc.LoadBalancer;
34
import io.grpc.Metadata;
35
import io.grpc.Status;
36
import io.grpc.internal.ForwardingClientStreamTracer;
37
import io.grpc.internal.GrpcUtil;
38
import io.grpc.internal.ObjectPool;
39
import io.grpc.services.MetricReport;
40
import io.grpc.util.ForwardingLoadBalancerHelper;
41
import io.grpc.util.ForwardingSubchannel;
42
import io.grpc.util.GracefulSwitchLoadBalancer;
43
import io.grpc.xds.ClusterImplLoadBalancerProvider.ClusterImplConfig;
44
import io.grpc.xds.Endpoints.DropOverload;
45
import io.grpc.xds.EnvoyServerProtoData.UpstreamTlsContext;
46
import io.grpc.xds.ThreadSafeRandom.ThreadSafeRandomImpl;
47
import io.grpc.xds.XdsNameResolverProvider.CallCounterProvider;
48
import io.grpc.xds.client.Bootstrapper.ServerInfo;
49
import io.grpc.xds.client.LoadStatsManager2.ClusterDropStats;
50
import io.grpc.xds.client.LoadStatsManager2.ClusterLocalityStats;
51
import io.grpc.xds.client.Locality;
52
import io.grpc.xds.client.XdsClient;
53
import io.grpc.xds.client.XdsLogger;
54
import io.grpc.xds.client.XdsLogger.XdsLogLevel;
55
import io.grpc.xds.internal.security.SslContextProviderSupplier;
56
import io.grpc.xds.orca.OrcaPerRequestUtil;
57
import io.grpc.xds.orca.OrcaPerRequestUtil.OrcaPerRequestReportListener;
58
import java.util.ArrayList;
59
import java.util.Collections;
60
import java.util.List;
61
import java.util.Map;
62
import java.util.Objects;
63
import java.util.concurrent.atomic.AtomicLong;
64
import java.util.concurrent.atomic.AtomicReference;
65
import javax.annotation.Nullable;
66

67
/**
68
 * Load balancer for cluster_impl_experimental LB policy. This LB policy is the child LB policy of
69
 * the priority_experimental LB policy and the parent LB policy of the weighted_target_experimental
70
 * LB policy in the xDS load balancing hierarchy. This LB policy applies cluster-level
71
 * configurations to requests sent to the corresponding cluster, such as drop policies, circuit
72
 * breakers.
73
 */
74
final class ClusterImplLoadBalancer extends LoadBalancer {
75

76
  @VisibleForTesting
77
  static final long DEFAULT_PER_CLUSTER_MAX_CONCURRENT_REQUESTS = 1024L;
78
  @VisibleForTesting
79
  static boolean enableCircuitBreaking =
1✔
80
      Strings.isNullOrEmpty(System.getenv("GRPC_XDS_EXPERIMENTAL_CIRCUIT_BREAKING"))
1✔
81
          || Boolean.parseBoolean(System.getenv("GRPC_XDS_EXPERIMENTAL_CIRCUIT_BREAKING"));
1✔
82

83
  private static final Attributes.Key<AtomicReference<ClusterLocality>> ATTR_CLUSTER_LOCALITY =
1✔
84
      Attributes.Key.create("io.grpc.xds.ClusterImplLoadBalancer.clusterLocality");
1✔
85

86
  private final XdsLogger logger;
87
  private final Helper helper;
88
  private final ThreadSafeRandom random;
89
  // The following fields are effectively final.
90
  private String cluster;
91
  @Nullable
92
  private String edsServiceName;
93
  private ObjectPool<XdsClient> xdsClientPool;
94
  private XdsClient xdsClient;
95
  private CallCounterProvider callCounterProvider;
96
  private ClusterDropStats dropStats;
97
  private ClusterImplLbHelper childLbHelper;
98
  private GracefulSwitchLoadBalancer childSwitchLb;
99

100
  ClusterImplLoadBalancer(Helper helper) {
101
    this(helper, ThreadSafeRandomImpl.instance);
1✔
102
  }
1✔
103

104
  ClusterImplLoadBalancer(Helper helper, ThreadSafeRandom random) {
1✔
105
    this.helper = checkNotNull(helper, "helper");
1✔
106
    this.random = checkNotNull(random, "random");
1✔
107
    InternalLogId logId = InternalLogId.allocate("cluster-impl-lb", helper.getAuthority());
1✔
108
    logger = XdsLogger.withLogId(logId);
1✔
109
    logger.log(XdsLogLevel.INFO, "Created");
1✔
110
  }
1✔
111

112
  @Override
113
  public Status acceptResolvedAddresses(ResolvedAddresses resolvedAddresses) {
114
    logger.log(XdsLogLevel.DEBUG, "Received resolution result: {0}", resolvedAddresses);
1✔
115
    Attributes attributes = resolvedAddresses.getAttributes();
1✔
116
    if (xdsClientPool == null) {
1✔
117
      xdsClientPool = attributes.get(InternalXdsAttributes.XDS_CLIENT_POOL);
1✔
118
      assert xdsClientPool != null;
1✔
119
      xdsClient = xdsClientPool.getObject();
1✔
120
    }
121
    if (callCounterProvider == null) {
1✔
122
      callCounterProvider = attributes.get(InternalXdsAttributes.CALL_COUNTER_PROVIDER);
1✔
123
    }
124

125
    ClusterImplConfig config =
1✔
126
        (ClusterImplConfig) resolvedAddresses.getLoadBalancingPolicyConfig();
1✔
127
    if (config == null) {
1✔
128
      return Status.INTERNAL.withDescription("No cluster configuration found");
×
129
    }
130

131
    if (cluster == null) {
1✔
132
      cluster = config.cluster;
1✔
133
      edsServiceName = config.edsServiceName;
1✔
134
      childLbHelper = new ClusterImplLbHelper(
1✔
135
          callCounterProvider.getOrCreate(config.cluster, config.edsServiceName),
1✔
136
          config.lrsServerInfo);
137
      childSwitchLb = new GracefulSwitchLoadBalancer(childLbHelper);
1✔
138
      // Assume load report server does not change throughout cluster lifetime.
139
      if (config.lrsServerInfo != null) {
1✔
140
        dropStats = xdsClient.addClusterDropStats(config.lrsServerInfo, cluster, edsServiceName);
1✔
141
      }
142
    }
143

144
    childLbHelper.updateDropPolicies(config.dropCategories);
1✔
145
    childLbHelper.updateMaxConcurrentRequests(config.maxConcurrentRequests);
1✔
146
    childLbHelper.updateSslContextProviderSupplier(config.tlsContext);
1✔
147
    childLbHelper.updateFilterMetadata(config.filterMetadata);
1✔
148

149
    childSwitchLb.handleResolvedAddresses(
1✔
150
        resolvedAddresses.toBuilder()
1✔
151
            .setAttributes(attributes)
1✔
152
            .setLoadBalancingPolicyConfig(config.childConfig)
1✔
153
            .build());
1✔
154
    return Status.OK;
1✔
155
  }
156

157
  @Override
158
  public void handleNameResolutionError(Status error) {
159
    if (childSwitchLb != null) {
1✔
160
      childSwitchLb.handleNameResolutionError(error);
1✔
161
    } else {
162
      helper.updateBalancingState(
1✔
163
          ConnectivityState.TRANSIENT_FAILURE, new FixedResultPicker(PickResult.withError(error)));
1✔
164
    }
165
  }
1✔
166

167
  @Override
168
  public void requestConnection() {
169
    if (childSwitchLb != null) {
1✔
170
      childSwitchLb.requestConnection();
1✔
171
    }
172
  }
1✔
173

174
  @Override
175
  public void shutdown() {
176
    if (dropStats != null) {
1✔
177
      dropStats.release();
1✔
178
    }
179
    if (childSwitchLb != null) {
1✔
180
      childSwitchLb.shutdown();
1✔
181
      if (childLbHelper != null) {
1✔
182
        childLbHelper.updateSslContextProviderSupplier(null);
1✔
183
        childLbHelper = null;
1✔
184
      }
185
    }
186
    if (xdsClient != null) {
1✔
187
      xdsClient = xdsClientPool.returnObject(xdsClient);
1✔
188
    }
189
  }
1✔
190

191
  /**
192
   * A decorated {@link LoadBalancer.Helper} that applies configurations for connections
193
   * or requests to endpoints in the cluster.
194
   */
195
  private final class ClusterImplLbHelper extends ForwardingLoadBalancerHelper {
196
    private final AtomicLong inFlights;
197
    private ConnectivityState currentState = ConnectivityState.IDLE;
1✔
198
    private SubchannelPicker currentPicker = new FixedResultPicker(PickResult.withNoResult());
1✔
199
    private List<DropOverload> dropPolicies = Collections.emptyList();
1✔
200
    private long maxConcurrentRequests = DEFAULT_PER_CLUSTER_MAX_CONCURRENT_REQUESTS;
1✔
201
    @Nullable
202
    private SslContextProviderSupplier sslContextProviderSupplier;
203
    private Map<String, Struct> filterMetadata = ImmutableMap.of();
1✔
204
    @Nullable
205
    private final ServerInfo lrsServerInfo;
206

207
    private ClusterImplLbHelper(AtomicLong inFlights, @Nullable ServerInfo lrsServerInfo) {
1✔
208
      this.inFlights = checkNotNull(inFlights, "inFlights");
1✔
209
      this.lrsServerInfo = lrsServerInfo;
1✔
210
    }
1✔
211

212
    @Override
213
    public void updateBalancingState(ConnectivityState newState, SubchannelPicker newPicker) {
214
      currentState = newState;
1✔
215
      currentPicker =  newPicker;
1✔
216
      SubchannelPicker picker = new RequestLimitingSubchannelPicker(
1✔
217
          newPicker, dropPolicies, maxConcurrentRequests, filterMetadata);
218
      delegate().updateBalancingState(newState, picker);
1✔
219
    }
1✔
220

221
    @Override
222
    public Subchannel createSubchannel(CreateSubchannelArgs args) {
223
      List<EquivalentAddressGroup> addresses = withAdditionalAttributes(args.getAddresses());
1✔
224
      // This value for  ClusterLocality is not recommended for general use.
225
      // Currently, we extract locality data from the first address, even before the subchannel is
226
      // READY.
227
      // This is mainly to accommodate scenarios where a Load Balancing API (like "pick first")
228
      // might return the subchannel before it is READY. Typically, we wouldn't report load for such
229
      // selections because the channel will disregard the chosen (not-ready) subchannel.
230
      // However, we needed to ensure this case is handled.
231
      ClusterLocality clusterLocality = createClusterLocalityFromAttributes(
1✔
232
          args.getAddresses().get(0).getAttributes());
1✔
233
      AtomicReference<ClusterLocality> localityAtomicReference = new AtomicReference<>(
1✔
234
          clusterLocality);
235
      Attributes.Builder attrsBuilder = args.getAttributes().toBuilder()
1✔
236
          .set(ATTR_CLUSTER_LOCALITY, localityAtomicReference);
1✔
237
      if (GrpcUtil.getFlag("GRPC_EXPERIMENTAL_XDS_AUTHORITY_REWRITE", false)) {
1✔
238
        String hostname = args.getAddresses().get(0).getAttributes()
1✔
239
            .get(InternalXdsAttributes.ATTR_ADDRESS_NAME);
1✔
240
        if (hostname != null) {
1✔
241
          attrsBuilder.set(InternalXdsAttributes.ATTR_ADDRESS_NAME, hostname);
1✔
242
        }
243
      }
244
      args = args.toBuilder().setAddresses(addresses).setAttributes(attrsBuilder.build()).build();
1✔
245
      final Subchannel subchannel = delegate().createSubchannel(args);
1✔
246

247
      return new ForwardingSubchannel() {
1✔
248
        @Override
249
        public void start(SubchannelStateListener listener) {
250
          delegate().start(new SubchannelStateListener() {
1✔
251
            @Override
252
            public void onSubchannelState(ConnectivityStateInfo newState) {
253
              // Do nothing if LB has been shutdown
254
              if (xdsClient != null && newState.getState().equals(ConnectivityState.READY)) {
1✔
255
                // Get locality based on the connected address attributes
256
                ClusterLocality updatedClusterLocality = createClusterLocalityFromAttributes(
1✔
257
                    subchannel.getConnectedAddressAttributes());
1✔
258
                ClusterLocality oldClusterLocality = localityAtomicReference
1✔
259
                    .getAndSet(updatedClusterLocality);
1✔
260
                oldClusterLocality.release();
1✔
261
              }
262
              listener.onSubchannelState(newState);
1✔
263
            }
1✔
264
          });
265
        }
1✔
266

267
        @Override
268
        public void shutdown() {
269
          localityAtomicReference.get().release();
1✔
270
          delegate().shutdown();
1✔
271
        }
1✔
272

273
        @Override
274
        public void updateAddresses(List<EquivalentAddressGroup> addresses) {
275
          delegate().updateAddresses(withAdditionalAttributes(addresses));
1✔
276
        }
1✔
277

278
        @Override
279
        protected Subchannel delegate() {
280
          return subchannel;
1✔
281
        }
282
      };
283
    }
284

285
    private List<EquivalentAddressGroup> withAdditionalAttributes(
286
        List<EquivalentAddressGroup> addresses) {
287
      List<EquivalentAddressGroup> newAddresses = new ArrayList<>();
1✔
288
      for (EquivalentAddressGroup eag : addresses) {
1✔
289
        Attributes.Builder attrBuilder = eag.getAttributes().toBuilder().set(
1✔
290
            InternalXdsAttributes.ATTR_CLUSTER_NAME, cluster);
1✔
291
        if (sslContextProviderSupplier != null) {
1✔
292
          attrBuilder.set(
1✔
293
              InternalXdsAttributes.ATTR_SSL_CONTEXT_PROVIDER_SUPPLIER,
294
              sslContextProviderSupplier);
295
        }
296
        newAddresses.add(new EquivalentAddressGroup(eag.getAddresses(), attrBuilder.build()));
1✔
297
      }
1✔
298
      return newAddresses;
1✔
299
    }
300

301
    private ClusterLocality createClusterLocalityFromAttributes(Attributes addressAttributes) {
302
      Locality locality = addressAttributes.get(InternalXdsAttributes.ATTR_LOCALITY);
1✔
303
      String localityName = addressAttributes.get(InternalXdsAttributes.ATTR_LOCALITY_NAME);
1✔
304

305
      // Endpoint addresses resolved by ClusterResolverLoadBalancer should always contain
306
      // attributes with its locality, including endpoints in LOGICAL_DNS clusters.
307
      // In case of not (which really shouldn't), loads are aggregated under an empty
308
      // locality.
309
      if (locality == null) {
1✔
310
        locality = Locality.create("", "", "");
×
311
        localityName = "";
×
312
      }
313

314
      final ClusterLocalityStats localityStats =
315
          (lrsServerInfo == null)
1✔
316
              ? null
1✔
317
              : xdsClient.addClusterLocalityStats(lrsServerInfo, cluster,
1✔
318
                  edsServiceName, locality);
1✔
319

320
      return new ClusterLocality(localityStats, localityName);
1✔
321
    }
322

323
    @Override
324
    protected Helper delegate()  {
325
      return helper;
1✔
326
    }
327

328
    private void updateDropPolicies(List<DropOverload> dropOverloads) {
329
      if (!dropPolicies.equals(dropOverloads)) {
1✔
330
        dropPolicies = dropOverloads;
1✔
331
        updateBalancingState(currentState, currentPicker);
1✔
332
      }
333
    }
1✔
334

335
    private void updateMaxConcurrentRequests(@Nullable Long maxConcurrentRequests) {
336
      if (Objects.equals(this.maxConcurrentRequests, maxConcurrentRequests)) {
1✔
337
        return;
×
338
      }
339
      this.maxConcurrentRequests =
1✔
340
          maxConcurrentRequests != null
1✔
341
              ? maxConcurrentRequests
1✔
342
              : DEFAULT_PER_CLUSTER_MAX_CONCURRENT_REQUESTS;
1✔
343
      updateBalancingState(currentState, currentPicker);
1✔
344
    }
1✔
345

346
    private void updateSslContextProviderSupplier(@Nullable UpstreamTlsContext tlsContext) {
347
      UpstreamTlsContext currentTlsContext =
348
          sslContextProviderSupplier != null
1✔
349
              ? (UpstreamTlsContext)sslContextProviderSupplier.getTlsContext()
1✔
350
              : null;
1✔
351
      if (Objects.equals(currentTlsContext,  tlsContext)) {
1✔
352
        return;
1✔
353
      }
354
      if (sslContextProviderSupplier != null) {
1✔
355
        sslContextProviderSupplier.close();
1✔
356
      }
357
      sslContextProviderSupplier =
1✔
358
          tlsContext != null
1✔
359
              ? new SslContextProviderSupplier(tlsContext,
1✔
360
                                               (TlsContextManager) xdsClient.getSecurityConfig())
1✔
361
              : null;
1✔
362
    }
1✔
363

364
    private void updateFilterMetadata(Map<String, Struct> filterMetadata) {
365
      this.filterMetadata = ImmutableMap.copyOf(filterMetadata);
1✔
366
    }
1✔
367

368
    private class RequestLimitingSubchannelPicker extends SubchannelPicker {
369
      private final SubchannelPicker delegate;
370
      private final List<DropOverload> dropPolicies;
371
      private final long maxConcurrentRequests;
372
      private final Map<String, Struct> filterMetadata;
373

374
      private RequestLimitingSubchannelPicker(SubchannelPicker delegate,
375
          List<DropOverload> dropPolicies, long maxConcurrentRequests,
376
          Map<String, Struct> filterMetadata) {
1✔
377
        this.delegate = delegate;
1✔
378
        this.dropPolicies = dropPolicies;
1✔
379
        this.maxConcurrentRequests = maxConcurrentRequests;
1✔
380
        this.filterMetadata = checkNotNull(filterMetadata, "filterMetadata");
1✔
381
      }
1✔
382

383
      @Override
384
      public PickResult pickSubchannel(PickSubchannelArgs args) {
385
        args.getCallOptions().getOption(ClusterImplLoadBalancerProvider.FILTER_METADATA_CONSUMER)
1✔
386
            .accept(filterMetadata);
1✔
387
        for (DropOverload dropOverload : dropPolicies) {
1✔
388
          int rand = random.nextInt(1_000_000);
1✔
389
          if (rand < dropOverload.dropsPerMillion()) {
1✔
390
            logger.log(XdsLogLevel.INFO, "Drop request with category: {0}",
1✔
391
                dropOverload.category());
1✔
392
            if (dropStats != null) {
1✔
393
              dropStats.recordDroppedRequest(dropOverload.category());
1✔
394
            }
395
            return PickResult.withDrop(
1✔
396
                Status.UNAVAILABLE.withDescription("Dropped: " + dropOverload.category()));
1✔
397
          }
398
        }
1✔
399
        PickResult result = delegate.pickSubchannel(args);
1✔
400
        if (result.getStatus().isOk() && result.getSubchannel() != null) {
1✔
401
          if (enableCircuitBreaking) {
1✔
402
            if (inFlights.get() >= maxConcurrentRequests) {
1✔
403
              if (dropStats != null) {
1✔
404
                dropStats.recordDroppedRequest();
1✔
405
              }
406
              return PickResult.withDrop(Status.UNAVAILABLE.withDescription(
1✔
407
                  "Cluster max concurrent requests limit exceeded"));
408
            }
409
          }
410
          final AtomicReference<ClusterLocality> clusterLocality =
1✔
411
              result.getSubchannel().getAttributes().get(ATTR_CLUSTER_LOCALITY);
1✔
412

413
          if (clusterLocality != null) {
1✔
414
            ClusterLocalityStats stats = clusterLocality.get().getClusterLocalityStats();
1✔
415
            if (stats != null) {
1✔
416
              String localityName =
1✔
417
                  result.getSubchannel().getAttributes().get(ATTR_CLUSTER_LOCALITY).get()
1✔
418
                      .getClusterLocalityName();
1✔
419
              args.getPickDetailsConsumer().addOptionalLabel("grpc.lb.locality", localityName);
1✔
420

421
              ClientStreamTracer.Factory tracerFactory = new CountingStreamTracerFactory(
1✔
422
                  stats, inFlights, result.getStreamTracerFactory());
1✔
423
              ClientStreamTracer.Factory orcaTracerFactory = OrcaPerRequestUtil.getInstance()
1✔
424
                  .newOrcaClientStreamTracerFactory(tracerFactory, new OrcaPerRpcListener(stats));
1✔
425
              result = PickResult.withSubchannel(result.getSubchannel(),
1✔
426
                  orcaTracerFactory);
427
            }
428
          }
429
          if (args.getCallOptions().getOption(XdsNameResolver.AUTO_HOST_REWRITE_KEY) != null
1✔
430
              && args.getCallOptions().getOption(XdsNameResolver.AUTO_HOST_REWRITE_KEY)) {
1✔
431
            result = PickResult.withSubchannel(result.getSubchannel(),
1✔
432
                result.getStreamTracerFactory(),
1✔
433
                result.getSubchannel().getAttributes().get(
1✔
434
                    InternalXdsAttributes.ATTR_ADDRESS_NAME));
435
          }
436
        }
437
        return result;
1✔
438
      }
439

440
      @Override
441
      public String toString() {
442
        return MoreObjects.toStringHelper(this).add("delegate", delegate).toString();
×
443
      }
444
    }
445
  }
446

447
  private static final class CountingStreamTracerFactory extends
448
      ClientStreamTracer.Factory {
449
    private final ClusterLocalityStats stats;
450
    private final AtomicLong inFlights;
451
    @Nullable
452
    private final ClientStreamTracer.Factory delegate;
453

454
    private CountingStreamTracerFactory(
455
        ClusterLocalityStats stats, AtomicLong inFlights,
456
        @Nullable ClientStreamTracer.Factory delegate) {
1✔
457
      this.stats = checkNotNull(stats, "stats");
1✔
458
      this.inFlights = checkNotNull(inFlights, "inFlights");
1✔
459
      this.delegate = delegate;
1✔
460
    }
1✔
461

462
    @Override
463
    public ClientStreamTracer newClientStreamTracer(StreamInfo info, Metadata headers) {
464
      stats.recordCallStarted();
1✔
465
      inFlights.incrementAndGet();
1✔
466
      if (delegate == null) {
1✔
467
        return new ClientStreamTracer() {
1✔
468
          @Override
469
          public void streamClosed(Status status) {
470
            stats.recordCallFinished(status);
1✔
471
            inFlights.decrementAndGet();
1✔
472
          }
1✔
473
        };
474
      }
475
      final ClientStreamTracer delegatedTracer = delegate.newClientStreamTracer(info, headers);
×
476
      return new ForwardingClientStreamTracer() {
×
477
        @Override
478
        protected ClientStreamTracer delegate() {
479
          return delegatedTracer;
×
480
        }
481

482
        @Override
483
        public void streamClosed(Status status) {
484
          stats.recordCallFinished(status);
×
485
          inFlights.decrementAndGet();
×
486
          delegate().streamClosed(status);
×
487
        }
×
488
      };
489
    }
490
  }
491

492
  private static final class OrcaPerRpcListener implements OrcaPerRequestReportListener {
493

494
    private final ClusterLocalityStats stats;
495

496
    private OrcaPerRpcListener(ClusterLocalityStats stats) {
1✔
497
      this.stats = checkNotNull(stats, "stats");
1✔
498
    }
1✔
499

500
    /**
501
     * Copies {@link MetricReport#getNamedMetrics()} to {@link ClusterLocalityStats} such that it is
502
     * included in the snapshot for the LRS report sent to the LRS server.
503
     */
504
    @Override
505
    public void onLoadReport(MetricReport report) {
506
      stats.recordBackendLoadMetricStats(report.getNamedMetrics());
1✔
507
    }
1✔
508
  }
509

510
  /**
511
   * Represents the {@link ClusterLocalityStats} and network locality name of a cluster.
512
   */
513
  static final class ClusterLocality {
514
    private final ClusterLocalityStats clusterLocalityStats;
515
    private final String clusterLocalityName;
516

517
    @VisibleForTesting
518
    ClusterLocality(ClusterLocalityStats localityStats, String localityName) {
1✔
519
      this.clusterLocalityStats = localityStats;
1✔
520
      this.clusterLocalityName = localityName;
1✔
521
    }
1✔
522

523
    ClusterLocalityStats getClusterLocalityStats() {
524
      return clusterLocalityStats;
1✔
525
    }
526

527
    String getClusterLocalityName() {
528
      return clusterLocalityName;
1✔
529
    }
530

531
    @VisibleForTesting
532
    void release() {
533
      if (clusterLocalityStats != null) {
1✔
534
        clusterLocalityStats.release();
1✔
535
      }
536
    }
1✔
537
  }
538
}
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