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

grpc / grpc-java / #20015

13 Oct 2025 07:57AM UTC coverage: 88.57% (+0.02%) from 88.552%
#20015

push

github

web-flow
xds: ORCA to LRS propagation changes (#12203)

Implements gRFC A85 (https://github.com/grpc/proposal/pull/454).

34925 of 39432 relevant lines covered (88.57%)

0.89 hits per line

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

95.1
/../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.NameResolver;
37
import io.grpc.Status;
38
import io.grpc.internal.ForwardingClientStreamTracer;
39
import io.grpc.internal.GrpcUtil;
40
import io.grpc.internal.ObjectPool;
41
import io.grpc.services.MetricReport;
42
import io.grpc.util.ForwardingLoadBalancerHelper;
43
import io.grpc.util.ForwardingSubchannel;
44
import io.grpc.util.GracefulSwitchLoadBalancer;
45
import io.grpc.xds.ClusterImplLoadBalancerProvider.ClusterImplConfig;
46
import io.grpc.xds.Endpoints.DropOverload;
47
import io.grpc.xds.EnvoyServerProtoData.UpstreamTlsContext;
48
import io.grpc.xds.ThreadSafeRandom.ThreadSafeRandomImpl;
49
import io.grpc.xds.XdsNameResolverProvider.CallCounterProvider;
50
import io.grpc.xds.client.BackendMetricPropagation;
51
import io.grpc.xds.client.Bootstrapper.ServerInfo;
52
import io.grpc.xds.client.LoadStatsManager2.ClusterDropStats;
53
import io.grpc.xds.client.LoadStatsManager2.ClusterLocalityStats;
54
import io.grpc.xds.client.Locality;
55
import io.grpc.xds.client.XdsClient;
56
import io.grpc.xds.client.XdsLogger;
57
import io.grpc.xds.client.XdsLogger.XdsLogLevel;
58
import io.grpc.xds.internal.XdsInternalAttributes;
59
import io.grpc.xds.internal.security.SecurityProtocolNegotiators;
60
import io.grpc.xds.internal.security.SslContextProviderSupplier;
61
import io.grpc.xds.orca.OrcaPerRequestUtil;
62
import io.grpc.xds.orca.OrcaPerRequestUtil.OrcaPerRequestReportListener;
63
import java.util.ArrayList;
64
import java.util.Collections;
65
import java.util.List;
66
import java.util.Locale;
67
import java.util.Map;
68
import java.util.Objects;
69
import java.util.concurrent.atomic.AtomicLong;
70
import java.util.concurrent.atomic.AtomicReference;
71
import javax.annotation.Nullable;
72

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

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

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

92
  private final XdsLogger logger;
93
  private final Helper helper;
94
  private final ThreadSafeRandom random;
95
  // The following fields are effectively final.
96
  private String cluster;
97
  @Nullable
98
  private String edsServiceName;
99
  private ObjectPool<XdsClient> xdsClientPool;
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 (xdsClientPool == null) {
1✔
123
      xdsClientPool = attributes.get(io.grpc.xds.XdsAttributes.XDS_CLIENT_POOL);
1✔
124
      assert xdsClientPool != null;
1✔
125
      xdsClient = xdsClientPool.getObject();
1✔
126
    }
127
    if (callCounterProvider == null) {
1✔
128
      callCounterProvider = attributes.get(io.grpc.xds.XdsAttributes.CALL_COUNTER_PROVIDER);
1✔
129
    }
130

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

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

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

156
    childSwitchLb.handleResolvedAddresses(
1✔
157
        resolvedAddresses.toBuilder()
1✔
158
            .setAttributes(attributes.toBuilder()
1✔
159
              .set(NameResolver.ATTR_BACKEND_SERVICE, cluster)
1✔
160
              .build())
1✔
161
            .setLoadBalancingPolicyConfig(config.childConfig)
1✔
162
            .build());
1✔
163
    return Status.OK;
1✔
164
  }
165

166
  @Override
167
  public void handleNameResolutionError(Status error) {
168
    if (childSwitchLb != null) {
1✔
169
      childSwitchLb.handleNameResolutionError(error);
1✔
170
    } else {
171
      helper.updateBalancingState(
1✔
172
          ConnectivityState.TRANSIENT_FAILURE, new FixedResultPicker(PickResult.withError(error)));
1✔
173
    }
174
  }
1✔
175

176
  @Override
177
  public void requestConnection() {
178
    if (childSwitchLb != null) {
1✔
179
      childSwitchLb.requestConnection();
1✔
180
    }
181
  }
1✔
182

183
  @Override
184
  public void shutdown() {
185
    if (dropStats != null) {
1✔
186
      dropStats.release();
1✔
187
    }
188
    if (childSwitchLb != null) {
1✔
189
      childSwitchLb.shutdown();
1✔
190
      if (childLbHelper != null) {
1✔
191
        childLbHelper.updateSslContextProviderSupplier(null);
1✔
192
        childLbHelper = null;
1✔
193
      }
194
    }
195
    if (xdsClient != null) {
1✔
196
      xdsClient = xdsClientPool.returnObject(xdsClient);
1✔
197
    }
198
  }
1✔
199

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

218
    private ClusterImplLbHelper(AtomicLong inFlights, @Nullable ServerInfo lrsServerInfo) {
1✔
219
      this.inFlights = checkNotNull(inFlights, "inFlights");
1✔
220
      this.lrsServerInfo = lrsServerInfo;
1✔
221
    }
1✔
222

223
    @Override
224
    public void updateBalancingState(ConnectivityState newState, SubchannelPicker newPicker) {
225
      currentState = newState;
1✔
226
      currentPicker =  newPicker;
1✔
227
      SubchannelPicker picker = new RequestLimitingSubchannelPicker(
1✔
228
          newPicker, dropPolicies, maxConcurrentRequests, filterMetadata);
229
      delegate().updateBalancingState(newState, picker);
1✔
230
    }
1✔
231

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

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

278
        @Override
279
        public void shutdown() {
280
          localityAtomicReference.get().release();
1✔
281
          delegate().shutdown();
1✔
282
        }
1✔
283

284
        @Override
285
        public void updateAddresses(List<EquivalentAddressGroup> addresses) {
286
          delegate().updateAddresses(withAdditionalAttributes(addresses));
1✔
287
        }
1✔
288

289
        @Override
290
        protected Subchannel delegate() {
291
          return subchannel;
1✔
292
        }
293
      };
294
    }
295

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

312
    private ClusterLocality createClusterLocalityFromAttributes(Attributes addressAttributes) {
313
      Locality locality = addressAttributes.get(io.grpc.xds.XdsAttributes.ATTR_LOCALITY);
1✔
314
      String localityName = addressAttributes.get(EquivalentAddressGroup.ATTR_LOCALITY_NAME);
1✔
315

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

325
      final ClusterLocalityStats localityStats =
326
          (lrsServerInfo == null)
1✔
327
              ? null
1✔
328
              : xdsClient.addClusterLocalityStats(lrsServerInfo, cluster,
1✔
329
                  edsServiceName, locality, backendMetricPropagation);
1✔
330

331
      return new ClusterLocality(localityStats, localityName);
1✔
332
    }
333

334
    @Override
335
    protected Helper delegate()  {
336
      return helper;
1✔
337
    }
338

339
    private void updateDropPolicies(List<DropOverload> dropOverloads) {
340
      if (!dropPolicies.equals(dropOverloads)) {
1✔
341
        dropPolicies = dropOverloads;
1✔
342
        updateBalancingState(currentState, currentPicker);
1✔
343
      }
344
    }
1✔
345

346
    private void updateMaxConcurrentRequests(@Nullable Long maxConcurrentRequests) {
347
      if (Objects.equals(this.maxConcurrentRequests, maxConcurrentRequests)) {
1✔
348
        return;
×
349
      }
350
      this.maxConcurrentRequests =
1✔
351
          maxConcurrentRequests != null
1✔
352
              ? maxConcurrentRequests
1✔
353
              : DEFAULT_PER_CLUSTER_MAX_CONCURRENT_REQUESTS;
1✔
354
      updateBalancingState(currentState, currentPicker);
1✔
355
    }
1✔
356

357
    private void updateSslContextProviderSupplier(@Nullable UpstreamTlsContext tlsContext) {
358
      UpstreamTlsContext currentTlsContext =
359
          sslContextProviderSupplier != null
1✔
360
              ? (UpstreamTlsContext)sslContextProviderSupplier.getTlsContext()
1✔
361
              : null;
1✔
362
      if (Objects.equals(currentTlsContext,  tlsContext)) {
1✔
363
        return;
1✔
364
      }
365
      if (sslContextProviderSupplier != null) {
1✔
366
        sslContextProviderSupplier.close();
1✔
367
      }
368
      sslContextProviderSupplier =
1✔
369
          tlsContext != null
1✔
370
              ? new SslContextProviderSupplier(tlsContext,
1✔
371
                                               (TlsContextManager) xdsClient.getSecurityConfig())
1✔
372
              : null;
1✔
373
    }
1✔
374

375
    private void updateFilterMetadata(Map<String, Struct> filterMetadata) {
376
      this.filterMetadata = ImmutableMap.copyOf(filterMetadata);
1✔
377
    }
1✔
378

379
    private void updateBackendMetricPropagation(
380
        @Nullable BackendMetricPropagation backendMetricPropagation) {
381
      this.backendMetricPropagation = backendMetricPropagation;
1✔
382
    }
1✔
383

384
    private class RequestLimitingSubchannelPicker extends SubchannelPicker {
385
      private final SubchannelPicker delegate;
386
      private final List<DropOverload> dropPolicies;
387
      private final long maxConcurrentRequests;
388
      private final Map<String, Struct> filterMetadata;
389

390
      private RequestLimitingSubchannelPicker(SubchannelPicker delegate,
391
          List<DropOverload> dropPolicies, long maxConcurrentRequests,
392
          Map<String, Struct> filterMetadata) {
1✔
393
        this.delegate = delegate;
1✔
394
        this.dropPolicies = dropPolicies;
1✔
395
        this.maxConcurrentRequests = maxConcurrentRequests;
1✔
396
        this.filterMetadata = checkNotNull(filterMetadata, "filterMetadata");
1✔
397
      }
1✔
398

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

431
          if (clusterLocality != null) {
1✔
432
            ClusterLocalityStats stats = clusterLocality.get().getClusterLocalityStats();
1✔
433
            if (stats != null) {
1✔
434
              String localityName =
1✔
435
                  result.getSubchannel().getAttributes().get(ATTR_CLUSTER_LOCALITY).get()
1✔
436
                      .getClusterLocalityName();
1✔
437
              args.getPickDetailsConsumer().addOptionalLabel("grpc.lb.locality", localityName);
1✔
438

439
              ClientStreamTracer.Factory tracerFactory = new CountingStreamTracerFactory(
1✔
440
                  stats, inFlights, result.getStreamTracerFactory());
1✔
441
              ClientStreamTracer.Factory orcaTracerFactory = OrcaPerRequestUtil.getInstance()
1✔
442
                  .newOrcaClientStreamTracerFactory(tracerFactory, new OrcaPerRpcListener(stats));
1✔
443
              result = PickResult.withSubchannel(result.getSubchannel(),
1✔
444
                  orcaTracerFactory);
445
            }
446
          }
447
          if (args.getCallOptions().getOption(XdsNameResolver.AUTO_HOST_REWRITE_KEY) != null
1✔
448
              && args.getCallOptions().getOption(XdsNameResolver.AUTO_HOST_REWRITE_KEY)) {
1✔
449
            result = PickResult.withSubchannel(result.getSubchannel(),
1✔
450
                result.getStreamTracerFactory(),
1✔
451
                result.getSubchannel().getAttributes().get(
1✔
452
                    XdsInternalAttributes.ATTR_ADDRESS_NAME));
453
          }
454
        }
455
        return result;
1✔
456
      }
457

458
      @Override
459
      public String toString() {
460
        return MoreObjects.toStringHelper(this).add("delegate", delegate).toString();
×
461
      }
462
    }
463
  }
464

465
  private static final class CountingStreamTracerFactory extends
466
      ClientStreamTracer.Factory {
467
    private final ClusterLocalityStats stats;
468
    private final AtomicLong inFlights;
469
    @Nullable
470
    private final ClientStreamTracer.Factory delegate;
471

472
    private CountingStreamTracerFactory(
473
        ClusterLocalityStats stats, AtomicLong inFlights,
474
        @Nullable ClientStreamTracer.Factory delegate) {
1✔
475
      this.stats = checkNotNull(stats, "stats");
1✔
476
      this.inFlights = checkNotNull(inFlights, "inFlights");
1✔
477
      this.delegate = delegate;
1✔
478
    }
1✔
479

480
    @Override
481
    public ClientStreamTracer newClientStreamTracer(StreamInfo info, Metadata headers) {
482
      stats.recordCallStarted();
1✔
483
      inFlights.incrementAndGet();
1✔
484
      if (delegate == null) {
1✔
485
        return new ClientStreamTracer() {
1✔
486
          @Override
487
          public void streamClosed(Status status) {
488
            stats.recordCallFinished(status);
1✔
489
            inFlights.decrementAndGet();
1✔
490
          }
1✔
491
        };
492
      }
493
      final ClientStreamTracer delegatedTracer = delegate.newClientStreamTracer(info, headers);
×
494
      return new ForwardingClientStreamTracer() {
×
495
        @Override
496
        protected ClientStreamTracer delegate() {
497
          return delegatedTracer;
×
498
        }
499

500
        @Override
501
        public void streamClosed(Status status) {
502
          stats.recordCallFinished(status);
×
503
          inFlights.decrementAndGet();
×
504
          delegate().streamClosed(status);
×
505
        }
×
506
      };
507
    }
508
  }
509

510
  private static final class OrcaPerRpcListener implements OrcaPerRequestReportListener {
511

512
    private final ClusterLocalityStats stats;
513

514
    private OrcaPerRpcListener(ClusterLocalityStats stats) {
1✔
515
      this.stats = checkNotNull(stats, "stats");
1✔
516
    }
1✔
517

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

536
  /**
537
   * Represents the {@link ClusterLocalityStats} and network locality name of a cluster.
538
   */
539
  static final class ClusterLocality {
540
    private final ClusterLocalityStats clusterLocalityStats;
541
    private final String clusterLocalityName;
542

543
    @VisibleForTesting
544
    ClusterLocality(ClusterLocalityStats localityStats, String localityName) {
1✔
545
      this.clusterLocalityStats = localityStats;
1✔
546
      this.clusterLocalityName = localityName;
1✔
547
    }
1✔
548

549
    ClusterLocalityStats getClusterLocalityStats() {
550
      return clusterLocalityStats;
1✔
551
    }
552

553
    String getClusterLocalityName() {
554
      return clusterLocalityName;
1✔
555
    }
556

557
    @VisibleForTesting
558
    void release() {
559
      if (clusterLocalityStats != null) {
1✔
560
        clusterLocalityStats.release();
1✔
561
      }
562
    }
1✔
563
  }
564
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc