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

grpc / grpc-java / #20365

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

push

github

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

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

38276 of 42911 relevant lines covered (89.2%)

0.89 hits per line

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

95.2
/../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
import static io.grpc.xds.client.LoadStatsManager2.isEnabledOrcaLrsPropagation;
21

22
import com.google.common.annotations.VisibleForTesting;
23
import com.google.common.base.MoreObjects;
24
import com.google.common.base.Strings;
25
import com.google.common.collect.ImmutableMap;
26
import com.google.protobuf.Struct;
27
import io.grpc.Attributes;
28
import io.grpc.ClientStreamTracer;
29
import io.grpc.ClientStreamTracer.StreamInfo;
30
import io.grpc.ConnectivityState;
31
import io.grpc.ConnectivityStateInfo;
32
import io.grpc.EquivalentAddressGroup;
33
import io.grpc.InternalLogId;
34
import io.grpc.LoadBalancer;
35
import io.grpc.Metadata;
36
import io.grpc.Status;
37
import io.grpc.internal.ForwardingClientStreamTracer;
38
import io.grpc.internal.GrpcUtil;
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.BackendMetricPropagation;
49
import io.grpc.xds.client.Bootstrapper.ServerInfo;
50
import io.grpc.xds.client.LoadStatsManager2.ClusterDropStats;
51
import io.grpc.xds.client.LoadStatsManager2.ClusterLocalityStats;
52
import io.grpc.xds.client.Locality;
53
import io.grpc.xds.client.XdsClient;
54
import io.grpc.xds.client.XdsLogger;
55
import io.grpc.xds.client.XdsLogger.XdsLogLevel;
56
import io.grpc.xds.internal.XdsInternalAttributes;
57
import io.grpc.xds.internal.security.SecurityProtocolNegotiators;
58
import io.grpc.xds.internal.security.SslContextProviderSupplier;
59
import io.grpc.xds.orca.OrcaPerRequestUtil;
60
import io.grpc.xds.orca.OrcaPerRequestUtil.OrcaPerRequestReportListener;
61
import java.util.ArrayList;
62
import java.util.Collections;
63
import java.util.List;
64
import java.util.Locale;
65
import java.util.Map;
66
import java.util.Objects;
67
import java.util.concurrent.atomic.AtomicLong;
68
import java.util.concurrent.atomic.AtomicReference;
69
import javax.annotation.Nullable;
70

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

80
  @VisibleForTesting
81
  static final long DEFAULT_PER_CLUSTER_MAX_CONCURRENT_REQUESTS = 1024L;
82
  @VisibleForTesting
83
  static boolean enableCircuitBreaking =
1✔
84
      Strings.isNullOrEmpty(System.getenv("GRPC_XDS_EXPERIMENTAL_CIRCUIT_BREAKING"))
1✔
85
          || Boolean.parseBoolean(System.getenv("GRPC_XDS_EXPERIMENTAL_CIRCUIT_BREAKING"));
1✔
86

87
  private static final Attributes.Key<AtomicReference<ClusterLocality>> ATTR_CLUSTER_LOCALITY =
1✔
88
      Attributes.Key.create("io.grpc.xds.ClusterImplLoadBalancer.clusterLocality");
1✔
89
  @VisibleForTesting
90
  static final Attributes.Key<String> ATTR_SUBCHANNEL_ADDRESS_NAME =
1✔
91
      Attributes.Key.create("io.grpc.xds.ClusterImplLoadBalancer.addressName");
1✔
92

93
  private final XdsLogger logger;
94
  private final Helper helper;
95
  private final ThreadSafeRandom random;
96
  // The following fields are effectively final.
97
  private String cluster;
98
  @Nullable
99
  private String edsServiceName;
100
  private XdsClient xdsClient;
101
  private CallCounterProvider callCounterProvider;
102
  private ClusterDropStats dropStats;
103
  private ClusterImplLbHelper childLbHelper;
104
  private GracefulSwitchLoadBalancer childSwitchLb;
105

106
  ClusterImplLoadBalancer(Helper helper) {
107
    this(helper, ThreadSafeRandomImpl.instance);
1✔
108
  }
1✔
109

110
  ClusterImplLoadBalancer(Helper helper, ThreadSafeRandom random) {
1✔
111
    this.helper = checkNotNull(helper, "helper");
1✔
112
    this.random = checkNotNull(random, "random");
1✔
113
    InternalLogId logId = InternalLogId.allocate("cluster-impl-lb", helper.getAuthority());
1✔
114
    logger = XdsLogger.withLogId(logId);
1✔
115
    logger.log(XdsLogLevel.INFO, "Created");
1✔
116
  }
1✔
117

118
  @Override
119
  public Status acceptResolvedAddresses(ResolvedAddresses resolvedAddresses) {
120
    logger.log(XdsLogLevel.DEBUG, "Received resolution result: {0}", resolvedAddresses);
1✔
121
    Attributes attributes = resolvedAddresses.getAttributes();
1✔
122
    if (xdsClient == null) {
1✔
123
      xdsClient = checkNotNull(attributes.get(io.grpc.xds.XdsAttributes.XDS_CLIENT), "xdsClient");
1✔
124
    }
125
    if (callCounterProvider == null) {
1✔
126
      callCounterProvider = attributes.get(io.grpc.xds.XdsAttributes.CALL_COUNTER_PROVIDER);
1✔
127
    }
128

129
    ClusterImplConfig config =
1✔
130
        (ClusterImplConfig) resolvedAddresses.getLoadBalancingPolicyConfig();
1✔
131
    if (config == null) {
1✔
132
      return Status.INTERNAL.withDescription("No cluster configuration found");
×
133
    }
134

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

148
    childLbHelper.updateDropPolicies(config.dropCategories);
1✔
149
    childLbHelper.updateMaxConcurrentRequests(config.maxConcurrentRequests);
1✔
150
    childLbHelper.updateSslContextProviderSupplier(config.tlsContext);
1✔
151
    childLbHelper.updateFilterMetadata(config.filterMetadata);
1✔
152
    childLbHelper.updateBackendMetricPropagation(config.backendMetricPropagation);
1✔
153

154
    return childSwitchLb.acceptResolvedAddresses(
1✔
155
        resolvedAddresses.toBuilder()
1✔
156
            .setLoadBalancingPolicyConfig(config.childConfig)
1✔
157
            .build());
1✔
158
  }
159

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

170
  @Override
171
  public void requestConnection() {
172
    if (childSwitchLb != null) {
1✔
173
      childSwitchLb.requestConnection();
1✔
174
    }
175
  }
1✔
176

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

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

211
    private ClusterImplLbHelper(AtomicLong inFlights, @Nullable ServerInfo lrsServerInfo) {
1✔
212
      this.inFlights = checkNotNull(inFlights, "inFlights");
1✔
213
      this.lrsServerInfo = lrsServerInfo;
1✔
214
    }
1✔
215

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

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

251
      return new ClusterImplSubchannel(subchannel, localityAtomicReference);
1✔
252
    }
253

254
    private final class ClusterImplSubchannel extends ForwardingSubchannel {
255
      private final Subchannel delegate;
256
      private final AtomicReference<ClusterLocality> localityAtomicReference;
257

258
      private ClusterImplSubchannel(
259
          Subchannel delegate, AtomicReference<ClusterLocality> localityAtomicReference) {
1✔
260
        this.delegate = delegate;
1✔
261
        this.localityAtomicReference = localityAtomicReference;
1✔
262
      }
1✔
263

264
      @Override
265
      public void start(SubchannelStateListener listener) {
266
        delegate().start(
1✔
267
            new SubchannelStateListener() {
1✔
268
              @Override
269
              public void onSubchannelState(ConnectivityStateInfo newState) {
270
                // Do nothing if LB has been shutdown
271
                if (xdsClient != null && newState.getState().equals(ConnectivityState.READY)) {
1✔
272
                  // Get locality based on the connected address attributes
273
                  ClusterLocality updatedClusterLocality =
1✔
274
                      createClusterLocalityFromAttributes(
1✔
275
                          delegate.getConnectedAddressAttributes());
1✔
276
                  ClusterLocality oldClusterLocality =
1✔
277
                      localityAtomicReference.getAndSet(updatedClusterLocality);
1✔
278
                  oldClusterLocality.release();
1✔
279
                }
280
                listener.onSubchannelState(newState);
1✔
281
              }
1✔
282
            });
283
      }
1✔
284

285
      @Override
286
      public void shutdown() {
287
        localityAtomicReference.get().release();
1✔
288
        delegate().shutdown();
1✔
289
      }
1✔
290

291
      @Override
292
      public void updateAddresses(List<EquivalentAddressGroup> addresses) {
293
        delegate().updateAddresses(withAdditionalAttributes(addresses));
1✔
294
      }
1✔
295

296
      @Override
297
      protected Subchannel delegate() {
298
        return delegate;
1✔
299
      }
300
    }
301

302
    private List<EquivalentAddressGroup> withAdditionalAttributes(
303
        List<EquivalentAddressGroup> addresses) {
304
      List<EquivalentAddressGroup> newAddresses = new ArrayList<>();
1✔
305
      for (EquivalentAddressGroup eag : addresses) {
1✔
306
        Attributes.Builder attrBuilder = eag.getAttributes().toBuilder().set(
1✔
307
            io.grpc.xds.XdsAttributes.ATTR_CLUSTER_NAME, cluster);
1✔
308
        if (sslContextProviderSupplier != null) {
1✔
309
          attrBuilder.set(
1✔
310
              SecurityProtocolNegotiators.ATTR_SSL_CONTEXT_PROVIDER_SUPPLIER,
311
              sslContextProviderSupplier);
312
        }
313
        newAddresses.add(new EquivalentAddressGroup(eag.getAddresses(), attrBuilder.build()));
1✔
314
      }
1✔
315
      return newAddresses;
1✔
316
    }
317

318
    private ClusterLocality createClusterLocalityFromAttributes(Attributes addressAttributes) {
319
      Locality locality = addressAttributes.get(io.grpc.xds.XdsAttributes.ATTR_LOCALITY);
1✔
320
      String localityName = addressAttributes.get(EquivalentAddressGroup.ATTR_LOCALITY_NAME);
1✔
321

322
      // Endpoint addresses resolved by ClusterResolverLoadBalancer should always contain
323
      // attributes with its locality, including endpoints in LOGICAL_DNS clusters.
324
      // In case of not (which really shouldn't), loads are aggregated under an empty
325
      // locality.
326
      if (locality == null) {
1✔
327
        locality = Locality.create("", "", "");
×
328
        localityName = "";
×
329
      }
330

331
      final ClusterLocalityStats localityStats =
332
          (lrsServerInfo == null)
1✔
333
              ? null
1✔
334
              : xdsClient.addClusterLocalityStats(lrsServerInfo, cluster,
1✔
335
                  edsServiceName, locality, backendMetricPropagation);
1✔
336

337
      return new ClusterLocality(localityStats, localityName);
1✔
338
    }
339

340
    @Override
341
    protected Helper delegate()  {
342
      return helper;
1✔
343
    }
344

345
    private void updateDropPolicies(List<DropOverload> dropOverloads) {
346
      if (!dropPolicies.equals(dropOverloads)) {
1✔
347
        dropPolicies = dropOverloads;
1✔
348
        updateBalancingState(currentState, currentPicker);
1✔
349
      }
350
    }
1✔
351

352
    private void updateMaxConcurrentRequests(@Nullable Long maxConcurrentRequests) {
353
      if (Objects.equals(this.maxConcurrentRequests, maxConcurrentRequests)) {
1✔
354
        return;
×
355
      }
356
      this.maxConcurrentRequests =
1✔
357
          maxConcurrentRequests != null
1✔
358
              ? maxConcurrentRequests
1✔
359
              : DEFAULT_PER_CLUSTER_MAX_CONCURRENT_REQUESTS;
1✔
360
      updateBalancingState(currentState, currentPicker);
1✔
361
    }
1✔
362

363
    private void updateSslContextProviderSupplier(@Nullable UpstreamTlsContext tlsContext) {
364
      UpstreamTlsContext currentTlsContext =
365
          sslContextProviderSupplier != null
1✔
366
              ? (UpstreamTlsContext)sslContextProviderSupplier.getTlsContext()
1✔
367
              : null;
1✔
368
      if (Objects.equals(currentTlsContext,  tlsContext)) {
1✔
369
        return;
1✔
370
      }
371
      if (sslContextProviderSupplier != null) {
1✔
372
        sslContextProviderSupplier.close();
1✔
373
      }
374
      sslContextProviderSupplier =
1✔
375
          tlsContext != null
1✔
376
              ? new SslContextProviderSupplier(tlsContext,
1✔
377
                                               (TlsContextManager) xdsClient.getSecurityConfig())
1✔
378
              : null;
1✔
379
    }
1✔
380

381
    private void updateFilterMetadata(Map<String, Struct> filterMetadata) {
382
      this.filterMetadata = ImmutableMap.copyOf(filterMetadata);
1✔
383
    }
1✔
384

385
    private void updateBackendMetricPropagation(
386
        @Nullable BackendMetricPropagation backendMetricPropagation) {
387
      this.backendMetricPropagation = backendMetricPropagation;
1✔
388
    }
1✔
389

390
    private class RequestLimitingSubchannelPicker extends SubchannelPicker {
391
      private final SubchannelPicker delegate;
392
      private final List<DropOverload> dropPolicies;
393
      private final long maxConcurrentRequests;
394
      private final Map<String, Struct> filterMetadata;
395

396
      private RequestLimitingSubchannelPicker(SubchannelPicker delegate,
397
          List<DropOverload> dropPolicies, long maxConcurrentRequests,
398
          Map<String, Struct> filterMetadata) {
1✔
399
        this.delegate = delegate;
1✔
400
        this.dropPolicies = dropPolicies;
1✔
401
        this.maxConcurrentRequests = maxConcurrentRequests;
1✔
402
        this.filterMetadata = checkNotNull(filterMetadata, "filterMetadata");
1✔
403
      }
1✔
404

405
      @Override
406
      public PickResult pickSubchannel(PickSubchannelArgs args) {
407
        args.getCallOptions().getOption(ClusterImplLoadBalancerProvider.FILTER_METADATA_CONSUMER)
1✔
408
            .accept(filterMetadata);
1✔
409
        for (DropOverload dropOverload : dropPolicies) {
1✔
410
          int rand = random.nextInt(1_000_000);
1✔
411
          if (rand < dropOverload.dropsPerMillion()) {
1✔
412
            logger.log(XdsLogLevel.INFO, "Drop request with category: {0}",
1✔
413
                dropOverload.category());
1✔
414
            if (dropStats != null) {
1✔
415
              dropStats.recordDroppedRequest(dropOverload.category());
1✔
416
            }
417
            return PickResult.withDrop(
1✔
418
                Status.UNAVAILABLE.withDescription("Dropped: " + dropOverload.category()));
1✔
419
          }
420
        }
1✔
421
        PickResult result = delegate.pickSubchannel(args);
1✔
422
        if (result.getStatus().isOk() && result.getSubchannel() != null) {
1✔
423
          Subchannel subchannel = result.getSubchannel();
1✔
424
          if (subchannel instanceof ClusterImplLbHelper.ClusterImplSubchannel) {
1✔
425
            subchannel = ((ClusterImplLbHelper.ClusterImplSubchannel) subchannel).delegate();
1✔
426
            result = result.copyWithSubchannel(subchannel);
1✔
427
          }
428
          if (enableCircuitBreaking) {
1✔
429
            if (inFlights.get() >= maxConcurrentRequests) {
1✔
430
              if (dropStats != null) {
1✔
431
                dropStats.recordDroppedRequest();
1✔
432
              }
433
              return PickResult.withDrop(Status.UNAVAILABLE.withDescription(
1✔
434
                  String.format(Locale.US, "Cluster max concurrent requests limit of %d exceeded",
1✔
435
                      maxConcurrentRequests)));
1✔
436
            }
437
          }
438
          final AtomicReference<ClusterLocality> clusterLocality =
1✔
439
              result.getSubchannel().getAttributes().get(ATTR_CLUSTER_LOCALITY);
1✔
440

441
          if (clusterLocality != null) {
1✔
442
            ClusterLocalityStats stats = clusterLocality.get().getClusterLocalityStats();
1✔
443
            if (stats != null) {
1✔
444
              String localityName =
1✔
445
                  result.getSubchannel().getAttributes().get(ATTR_CLUSTER_LOCALITY).get()
1✔
446
                      .getClusterLocalityName();
1✔
447
              args.getPickDetailsConsumer().addOptionalLabel("grpc.lb.locality", localityName);
1✔
448

449
              ClientStreamTracer.Factory tracerFactory = new CountingStreamTracerFactory(
1✔
450
                  stats, inFlights, result.getStreamTracerFactory());
1✔
451
              ClientStreamTracer.Factory orcaTracerFactory = OrcaPerRequestUtil.getInstance()
1✔
452
                  .newOrcaClientStreamTracerFactory(tracerFactory, new OrcaPerRpcListener(stats));
1✔
453
              result = result.copyWithStreamTracerFactory(orcaTracerFactory);
1✔
454
            }
455
          }
456
          if (args.getCallOptions().getOption(XdsNameResolver.AUTO_HOST_REWRITE_KEY) != null
1✔
457
              && args.getCallOptions().getOption(XdsNameResolver.AUTO_HOST_REWRITE_KEY)) {
1✔
458
            result = PickResult.withSubchannel(result.getSubchannel(),
1✔
459
                result.getStreamTracerFactory(),
1✔
460
                result.getSubchannel().getAttributes().get(ATTR_SUBCHANNEL_ADDRESS_NAME));
1✔
461
          }
462
        }
463
        return result;
1✔
464
      }
465

466
      @Override
467
      public String toString() {
468
        return MoreObjects.toStringHelper(this).add("delegate", delegate).toString();
×
469
      }
470
    }
471
  }
472

473
  private static final class CountingStreamTracerFactory extends
474
      ClientStreamTracer.Factory {
475
    private final ClusterLocalityStats stats;
476
    private final AtomicLong inFlights;
477
    @Nullable
478
    private final ClientStreamTracer.Factory delegate;
479

480
    private CountingStreamTracerFactory(
481
        ClusterLocalityStats stats, AtomicLong inFlights,
482
        @Nullable ClientStreamTracer.Factory delegate) {
1✔
483
      this.stats = checkNotNull(stats, "stats");
1✔
484
      this.inFlights = checkNotNull(inFlights, "inFlights");
1✔
485
      this.delegate = delegate;
1✔
486
    }
1✔
487

488
    @Override
489
    public ClientStreamTracer newClientStreamTracer(StreamInfo info, Metadata headers) {
490
      stats.recordCallStarted();
1✔
491
      inFlights.incrementAndGet();
1✔
492
      if (delegate == null) {
1✔
493
        return new ClientStreamTracer() {
1✔
494
          @Override
495
          public void streamClosed(Status status) {
496
            stats.recordCallFinished(status);
1✔
497
            inFlights.decrementAndGet();
1✔
498
          }
1✔
499
        };
500
      }
501
      final ClientStreamTracer delegatedTracer = delegate.newClientStreamTracer(info, headers);
×
502
      return new ForwardingClientStreamTracer() {
×
503
        @Override
504
        protected ClientStreamTracer delegate() {
505
          return delegatedTracer;
×
506
        }
507

508
        @Override
509
        public void streamClosed(Status status) {
510
          stats.recordCallFinished(status);
×
511
          inFlights.decrementAndGet();
×
512
          delegate().streamClosed(status);
×
513
        }
×
514
      };
515
    }
516
  }
517

518
  private static final class OrcaPerRpcListener implements OrcaPerRequestReportListener {
519

520
    private final ClusterLocalityStats stats;
521

522
    private OrcaPerRpcListener(ClusterLocalityStats stats) {
1✔
523
      this.stats = checkNotNull(stats, "stats");
1✔
524
    }
1✔
525

526
    /**
527
     * Copies ORCA metrics from {@link MetricReport} to {@link ClusterLocalityStats}
528
     * such that they are included in the snapshot for the LRS report sent to the LRS server.
529
     * This includes both top-level metrics (CPU, memory, application utilization) and named
530
     * metrics, filtered according to the backend metric propagation configuration.
531
     */
532
    @Override
533
    public void onLoadReport(MetricReport report) {
534
      if (isEnabledOrcaLrsPropagation) {
1✔
535
        stats.recordTopLevelMetrics(
1✔
536
            report.getCpuUtilization(),
1✔
537
            report.getMemoryUtilization(),
1✔
538
            report.getApplicationUtilization());
1✔
539
      }
540
      stats.recordBackendLoadMetricStats(report.getNamedMetrics());
1✔
541
    }
1✔
542
  }
543

544
  /**
545
   * Represents the {@link ClusterLocalityStats} and network locality name of a cluster.
546
   */
547
  static final class ClusterLocality {
548
    private final ClusterLocalityStats clusterLocalityStats;
549
    private final String clusterLocalityName;
550

551
    @VisibleForTesting
552
    ClusterLocality(ClusterLocalityStats localityStats, String localityName) {
1✔
553
      this.clusterLocalityStats = localityStats;
1✔
554
      this.clusterLocalityName = localityName;
1✔
555
    }
1✔
556

557
    ClusterLocalityStats getClusterLocalityStats() {
558
      return clusterLocalityStats;
1✔
559
    }
560

561
    String getClusterLocalityName() {
562
      return clusterLocalityName;
1✔
563
    }
564

565
    @VisibleForTesting
566
    void release() {
567
      if (clusterLocalityStats != null) {
1✔
568
        clusterLocalityStats.release();
1✔
569
      }
570
    }
1✔
571
  }
572
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc