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

grpc / grpc-java / #20198

16 Mar 2026 09:15PM UTC coverage: 88.696% (+0.002%) from 88.694%
#20198

push

github

web-flow
xds: Add support for RFC 3986 URIs (#12660)

35481 of 40003 relevant lines covered (88.7%)

0.89 hits per line

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

91.82
/../xds/src/main/java/io/grpc/xds/XdsNameResolver.java
1
/*
2
 * Copyright 2019 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.checkArgument;
20
import static com.google.common.base.Preconditions.checkNotNull;
21
import static io.grpc.xds.client.Bootstrapper.XDSTP_SCHEME;
22

23
import com.google.common.annotations.VisibleForTesting;
24
import com.google.common.base.Joiner;
25
import com.google.common.base.Strings;
26
import com.google.common.collect.ImmutableList;
27
import com.google.common.collect.ImmutableMap;
28
import com.google.common.collect.Sets;
29
import com.google.gson.Gson;
30
import com.google.protobuf.util.Durations;
31
import io.grpc.Attributes;
32
import io.grpc.CallOptions;
33
import io.grpc.Channel;
34
import io.grpc.ClientCall;
35
import io.grpc.ClientInterceptor;
36
import io.grpc.ClientInterceptors;
37
import io.grpc.ForwardingClientCall.SimpleForwardingClientCall;
38
import io.grpc.ForwardingClientCallListener.SimpleForwardingClientCallListener;
39
import io.grpc.InternalConfigSelector;
40
import io.grpc.InternalLogId;
41
import io.grpc.LoadBalancer.PickSubchannelArgs;
42
import io.grpc.Metadata;
43
import io.grpc.MethodDescriptor;
44
import io.grpc.MetricRecorder;
45
import io.grpc.NameResolver;
46
import io.grpc.Status;
47
import io.grpc.Status.Code;
48
import io.grpc.StatusOr;
49
import io.grpc.SynchronizationContext;
50
import io.grpc.internal.GrpcUtil;
51
import io.grpc.internal.ObjectPool;
52
import io.grpc.xds.ClusterSpecifierPlugin.PluginConfig;
53
import io.grpc.xds.Filter.FilterConfig;
54
import io.grpc.xds.Filter.NamedFilterConfig;
55
import io.grpc.xds.RouteLookupServiceClusterSpecifierPlugin.RlsPluginConfig;
56
import io.grpc.xds.ThreadSafeRandom.ThreadSafeRandomImpl;
57
import io.grpc.xds.VirtualHost.Route;
58
import io.grpc.xds.VirtualHost.Route.RouteAction;
59
import io.grpc.xds.VirtualHost.Route.RouteAction.ClusterWeight;
60
import io.grpc.xds.VirtualHost.Route.RouteAction.HashPolicy;
61
import io.grpc.xds.VirtualHost.Route.RouteAction.RetryPolicy;
62
import io.grpc.xds.VirtualHost.Route.RouteMatch;
63
import io.grpc.xds.XdsNameResolverProvider.CallCounterProvider;
64
import io.grpc.xds.client.Bootstrapper.AuthorityInfo;
65
import io.grpc.xds.client.Bootstrapper.BootstrapInfo;
66
import io.grpc.xds.client.XdsClient;
67
import io.grpc.xds.client.XdsInitializationException;
68
import io.grpc.xds.client.XdsLogger;
69
import io.grpc.xds.client.XdsLogger.XdsLogLevel;
70
import java.util.ArrayList;
71
import java.util.Collections;
72
import java.util.HashMap;
73
import java.util.HashSet;
74
import java.util.List;
75
import java.util.Locale;
76
import java.util.Map;
77
import java.util.Objects;
78
import java.util.Set;
79
import java.util.concurrent.ConcurrentHashMap;
80
import java.util.concurrent.ConcurrentMap;
81
import java.util.concurrent.ScheduledExecutorService;
82
import java.util.concurrent.atomic.AtomicInteger;
83
import java.util.function.Supplier;
84
import javax.annotation.Nullable;
85

86
/**
87
 * A {@link NameResolver} for resolving gRPC target names with "xds:" scheme.
88
 *
89
 * <p>Resolving a gRPC target involves contacting the control plane management server via xDS
90
 * protocol to retrieve service information and produce a service config to the caller.
91
 *
92
 * @see XdsNameResolverProvider
93
 */
94
final class XdsNameResolver extends NameResolver {
95
  static final CallOptions.Key<String> CLUSTER_SELECTION_KEY =
1✔
96
      CallOptions.Key.create("io.grpc.xds.CLUSTER_SELECTION_KEY");
1✔
97
  static final CallOptions.Key<XdsConfig> XDS_CONFIG_CALL_OPTION_KEY =
1✔
98
      CallOptions.Key.create("io.grpc.xds.XDS_CONFIG_CALL_OPTION_KEY");
1✔
99
  static final CallOptions.Key<Long> RPC_HASH_KEY =
1✔
100
      CallOptions.Key.create("io.grpc.xds.RPC_HASH_KEY");
1✔
101
  static final CallOptions.Key<Boolean> AUTO_HOST_REWRITE_KEY =
1✔
102
      CallOptions.Key.create("io.grpc.xds.AUTO_HOST_REWRITE_KEY");
1✔
103
  @VisibleForTesting
104
  static boolean enableTimeout =
1✔
105
      Strings.isNullOrEmpty(System.getenv("GRPC_XDS_EXPERIMENTAL_ENABLE_TIMEOUT"))
1✔
106
          || Boolean.parseBoolean(System.getenv("GRPC_XDS_EXPERIMENTAL_ENABLE_TIMEOUT"));
1✔
107

108
  private final InternalLogId logId;
109
  private final XdsLogger logger;
110
  @Nullable
111
  private final String targetAuthority;
112
  private final String serviceAuthority;
113
  // Encoded version of the service authority as per 
114
  // https://datatracker.ietf.org/doc/html/rfc3986#section-3.2.
115
  private final String encodedServiceAuthority;
116
  private final String overrideAuthority;
117
  private final ServiceConfigParser serviceConfigParser;
118
  private final SynchronizationContext syncContext;
119
  private final ScheduledExecutorService scheduler;
120
  private final XdsClientPool xdsClientPool;
121
  private final ThreadSafeRandom random;
122
  private final FilterRegistry filterRegistry;
123
  private final XxHash64 hashFunc = XxHash64.INSTANCE;
1✔
124
  // Clusters (with reference counts) to which new/existing requests can be/are routed.
125
  // put()/remove() must be called in SyncContext, and get() can be called in any thread.
126
  private final ConcurrentMap<String, ClusterRefState> clusterRefs = new ConcurrentHashMap<>();
1✔
127
  private final ConfigSelector configSelector = new ConfigSelector();
1✔
128
  private final long randomChannelId;
129
  private final Args nameResolverArgs;
130
  // Must be accessed in syncContext.
131
  // Filter instances are unique per channel, and per filter (name+typeUrl).
132
  // NamedFilterConfig.filterStateKey -> filter_instance.
133
  private final HashMap<String, Filter> activeFilters = new HashMap<>();
1✔
134

135
  private volatile RoutingConfig routingConfig;
136
  private Listener2 listener;
137
  private XdsClient xdsClient;
138
  private CallCounterProvider callCounterProvider;
139
  private ResolveState resolveState;
140

141
  XdsNameResolver(
142
      String target, @Nullable String targetAuthority, String name,
143
      @Nullable String overrideAuthority, ServiceConfigParser serviceConfigParser,
144
      SynchronizationContext syncContext, ScheduledExecutorService scheduler,
145
      @Nullable Map<String, ?> bootstrapOverride,
146
      MetricRecorder metricRecorder, Args nameResolverArgs) {
147
    this(target, targetAuthority, name, overrideAuthority, serviceConfigParser,
1✔
148
        syncContext, scheduler,
149
        bootstrapOverride == null
1✔
150
          ? SharedXdsClientPoolProvider.getDefaultProvider()
1✔
151
          : new SharedXdsClientPoolProvider(),
1✔
152
        ThreadSafeRandomImpl.instance, FilterRegistry.getDefaultRegistry(), bootstrapOverride,
1✔
153
        metricRecorder, nameResolverArgs);
154
  }
1✔
155

156
  @VisibleForTesting
157
  XdsNameResolver(
158
      String target, @Nullable String targetAuthority, String name,
159
      @Nullable String overrideAuthority, ServiceConfigParser serviceConfigParser,
160
      SynchronizationContext syncContext, ScheduledExecutorService scheduler,
161
      XdsClientPoolFactory xdsClientPoolFactory, ThreadSafeRandom random,
162
      FilterRegistry filterRegistry, @Nullable Map<String, ?> bootstrapOverride,
163
      MetricRecorder metricRecorder, Args nameResolverArgs) {
1✔
164
    this.targetAuthority = targetAuthority;
1✔
165

166
    // The name might have multiple slashes so encode it before verifying.
167
    serviceAuthority = checkNotNull(name, "name");
1✔
168
    this.encodedServiceAuthority = 
1✔
169
      GrpcUtil.checkAuthority(GrpcUtil.AuthorityEscaper.encodeAuthority(serviceAuthority));
1✔
170

171
    this.overrideAuthority = overrideAuthority;
1✔
172
    this.serviceConfigParser = checkNotNull(serviceConfigParser, "serviceConfigParser");
1✔
173
    this.syncContext = checkNotNull(syncContext, "syncContext");
1✔
174
    this.scheduler = checkNotNull(scheduler, "scheduler");
1✔
175
    Supplier<XdsClient> xdsClientSupplierArg =
1✔
176
        nameResolverArgs.getArg(XdsNameResolverProvider.XDS_CLIENT_SUPPLIER);
1✔
177
    if (xdsClientSupplierArg != null) {
1✔
178
      this.xdsClientPool = new SupplierXdsClientPool(xdsClientSupplierArg);
×
179
    } else {
180
      checkNotNull(xdsClientPoolFactory, "xdsClientPoolFactory");
1✔
181
      this.xdsClientPool = new BootstrappingXdsClientPool(
1✔
182
          xdsClientPoolFactory, target, bootstrapOverride, metricRecorder);
183
    }
184
    this.random = checkNotNull(random, "random");
1✔
185
    this.filterRegistry = checkNotNull(filterRegistry, "filterRegistry");
1✔
186
    this.nameResolverArgs = checkNotNull(nameResolverArgs, "nameResolverArgs");
1✔
187

188
    randomChannelId = random.nextLong();
1✔
189
    logId = InternalLogId.allocate("xds-resolver", name);
1✔
190
    logger = XdsLogger.withLogId(logId);
1✔
191
    logger.log(XdsLogLevel.INFO, "Created resolver for {0}", name);
1✔
192
  }
1✔
193

194
  @Override
195
  public String getServiceAuthority() {
196
    return encodedServiceAuthority;
1✔
197
  }
198

199
  @Override
200
  public void start(Listener2 listener) {
201
    this.listener = checkNotNull(listener, "listener");
1✔
202
    try {
203
      xdsClient = xdsClientPool.getObject();
1✔
204
    } catch (Exception e) {
1✔
205
      listener.onError(
1✔
206
          Status.UNAVAILABLE.withDescription("Failed to initialize xDS").withCause(e));
1✔
207
      return;
1✔
208
    }
1✔
209
    BootstrapInfo bootstrapInfo = xdsClient.getBootstrapInfo();
1✔
210
    String listenerNameTemplate;
211
    if (targetAuthority == null) {
1✔
212
      listenerNameTemplate = bootstrapInfo.clientDefaultListenerResourceNameTemplate();
1✔
213
    } else {
214
      AuthorityInfo authorityInfo = bootstrapInfo.authorities().get(targetAuthority);
1✔
215
      if (authorityInfo == null) {
1✔
216
        listener.onError(Status.INVALID_ARGUMENT.withDescription(
1✔
217
            "invalid target URI: target authority not found in the bootstrap"));
218
        return;
1✔
219
      }
220
      listenerNameTemplate = authorityInfo.clientListenerResourceNameTemplate();
1✔
221
    }
222
    String replacement = serviceAuthority;
1✔
223
    if (listenerNameTemplate.startsWith(XDSTP_SCHEME)) {
1✔
224
      replacement = XdsClient.percentEncodePath(replacement);
1✔
225
    }
226
    String ldsResourceName = expandPercentS(listenerNameTemplate, replacement);
1✔
227
    if (!XdsClient.isResourceNameValid(ldsResourceName, XdsListenerResource.getInstance().typeUrl())
1✔
228
        ) {
229
      listener.onError(Status.INVALID_ARGUMENT.withDescription(
×
230
          "invalid listener resource URI for service authority: " + serviceAuthority));
231
      return;
×
232
    }
233
    ldsResourceName = XdsClient.canonifyResourceName(ldsResourceName);
1✔
234
    callCounterProvider = SharedCallCounterMap.getInstance();
1✔
235

236
    resolveState = new ResolveState(ldsResourceName);
1✔
237
    resolveState.start();
1✔
238
  }
1✔
239

240
  @Override
241
  public void refresh() {
242
    if (resolveState != null) {
×
243
      resolveState.refresh();
×
244
    }
245
  }
×
246

247
  private static String expandPercentS(String template, String replacement) {
248
    return template.replace("%s", replacement);
1✔
249
  }
250

251
  @Override
252
  public void shutdown() {
253
    logger.log(XdsLogLevel.INFO, "Shutdown");
1✔
254
    if (resolveState != null) {
1✔
255
      resolveState.shutdown();
1✔
256
    }
257
    if (xdsClient != null) {
1✔
258
      xdsClient = xdsClientPool.returnObject(xdsClient);
1✔
259
    }
260
  }
1✔
261

262
  @VisibleForTesting
263
  static Map<String, ?> generateServiceConfigWithMethodConfig(
264
      @Nullable Long timeoutNano, @Nullable RetryPolicy retryPolicy) {
265
    if (timeoutNano == null
1✔
266
        && (retryPolicy == null || retryPolicy.retryableStatusCodes().isEmpty())) {
1✔
267
      return Collections.emptyMap();
1✔
268
    }
269
    ImmutableMap.Builder<String, Object> methodConfig = ImmutableMap.builder();
1✔
270
    methodConfig.put(
1✔
271
        "name", Collections.singletonList(Collections.emptyMap()));
1✔
272
    if (retryPolicy != null && !retryPolicy.retryableStatusCodes().isEmpty()) {
1✔
273
      ImmutableMap.Builder<String, Object> rawRetryPolicy = ImmutableMap.builder();
1✔
274
      rawRetryPolicy.put("maxAttempts", (double) retryPolicy.maxAttempts());
1✔
275
      rawRetryPolicy.put("initialBackoff", Durations.toString(retryPolicy.initialBackoff()));
1✔
276
      rawRetryPolicy.put("maxBackoff", Durations.toString(retryPolicy.maxBackoff()));
1✔
277
      rawRetryPolicy.put("backoffMultiplier", 2D);
1✔
278
      List<String> codes = new ArrayList<>(retryPolicy.retryableStatusCodes().size());
1✔
279
      for (Code code : retryPolicy.retryableStatusCodes()) {
1✔
280
        codes.add(code.name());
1✔
281
      }
1✔
282
      rawRetryPolicy.put(
1✔
283
          "retryableStatusCodes", Collections.unmodifiableList(codes));
1✔
284
      if (retryPolicy.perAttemptRecvTimeout() != null) {
1✔
285
        rawRetryPolicy.put(
×
286
            "perAttemptRecvTimeout", Durations.toString(retryPolicy.perAttemptRecvTimeout()));
×
287
      }
288
      methodConfig.put("retryPolicy", rawRetryPolicy.buildOrThrow());
1✔
289
    }
290
    if (timeoutNano != null) {
1✔
291
      String timeout = timeoutNano / 1_000_000_000.0 + "s";
1✔
292
      methodConfig.put("timeout", timeout);
1✔
293
    }
294
    return Collections.singletonMap(
1✔
295
        "methodConfig", Collections.singletonList(methodConfig.buildOrThrow()));
1✔
296
  }
297

298
  @VisibleForTesting
299
  XdsClient getXdsClient() {
300
    return xdsClient;
1✔
301
  }
302

303
  // called in syncContext
304
  private void updateResolutionResult(XdsConfig xdsConfig) {
305
    syncContext.throwIfNotInThisSynchronizationContext();
1✔
306

307
    ImmutableMap.Builder<String, Object> childPolicy = new ImmutableMap.Builder<>();
1✔
308
    for (String name : clusterRefs.keySet()) {
1✔
309
      Map<String, ?> lbPolicy = clusterRefs.get(name).toLbPolicy();
1✔
310
      childPolicy.put(name, ImmutableMap.of("lbPolicy", ImmutableList.of(lbPolicy)));
1✔
311
    }
1✔
312
    Map<String, ?> rawServiceConfig = ImmutableMap.of(
1✔
313
        "loadBalancingConfig",
314
        ImmutableList.of(ImmutableMap.of(
1✔
315
            XdsLbPolicies.CLUSTER_MANAGER_POLICY_NAME,
316
            ImmutableMap.of("childPolicy", childPolicy.buildOrThrow()))));
1✔
317

318
    if (logger.isLoggable(XdsLogLevel.INFO)) {
1✔
319
      logger.log(
×
320
          XdsLogLevel.INFO, "Generated service config: {0}", new Gson().toJson(rawServiceConfig));
×
321
    }
322
    ConfigOrError parsedServiceConfig = serviceConfigParser.parseServiceConfig(rawServiceConfig);
1✔
323
    Attributes attrs =
324
        Attributes.newBuilder()
1✔
325
            .set(XdsAttributes.XDS_CLIENT, xdsClient)
1✔
326
            .set(XdsAttributes.XDS_CONFIG, xdsConfig)
1✔
327
            .set(XdsAttributes.XDS_CLUSTER_SUBSCRIPT_REGISTRY, resolveState.xdsDependencyManager)
1✔
328
            .set(XdsAttributes.CALL_COUNTER_PROVIDER, callCounterProvider)
1✔
329
            .set(InternalConfigSelector.KEY, configSelector)
1✔
330
            .build();
1✔
331
    ResolutionResult result =
332
        ResolutionResult.newBuilder()
1✔
333
            .setAttributes(attrs)
1✔
334
            .setServiceConfig(parsedServiceConfig)
1✔
335
            .build();
1✔
336
    if (!listener.onResult2(result).isOk()) {
1✔
337
      resolveState.xdsDependencyManager.requestReresolution();
×
338
    }
339
  }
1✔
340

341
  /**
342
   * Returns {@code true} iff {@code hostName} matches the domain name {@code pattern} with
343
   * case-insensitive.
344
   *
345
   * <p>Wildcard pattern rules:
346
   * <ol>
347
   * <li>A single asterisk (*) matches any domain.</li>
348
   * <li>Asterisk (*) is only permitted in the left-most or the right-most part of the pattern,
349
   *     but not both.</li>
350
   * </ol>
351
   */
352
  @VisibleForTesting
353
  static boolean matchHostName(String hostName, String pattern) {
354
    checkArgument(hostName.length() != 0 && !hostName.startsWith(".") && !hostName.endsWith("."),
1✔
355
        "Invalid host name");
356
    checkArgument(pattern.length() != 0 && !pattern.startsWith(".") && !pattern.endsWith("."),
1✔
357
        "Invalid pattern/domain name");
358

359
    hostName = hostName.toLowerCase(Locale.US);
1✔
360
    pattern = pattern.toLowerCase(Locale.US);
1✔
361
    // hostName and pattern are now in lower case -- domain names are case-insensitive.
362

363
    if (!pattern.contains("*")) {
1✔
364
      // Not a wildcard pattern -- hostName and pattern must match exactly.
365
      return hostName.equals(pattern);
1✔
366
    }
367
    // Wildcard pattern
368

369
    if (pattern.length() == 1) {
1✔
370
      return true;
×
371
    }
372

373
    int index = pattern.indexOf('*');
1✔
374

375
    // At most one asterisk (*) is allowed.
376
    if (pattern.indexOf('*', index + 1) != -1) {
1✔
377
      return false;
×
378
    }
379

380
    // Asterisk can only match prefix or suffix.
381
    if (index != 0 && index != pattern.length() - 1) {
1✔
382
      return false;
×
383
    }
384

385
    // HostName must be at least as long as the pattern because asterisk has to
386
    // match one or more characters.
387
    if (hostName.length() < pattern.length()) {
1✔
388
      return false;
1✔
389
    }
390

391
    if (index == 0 && hostName.endsWith(pattern.substring(1))) {
1✔
392
      // Prefix matching fails.
393
      return true;
1✔
394
    }
395

396
    // Pattern matches hostname if suffix matching succeeds.
397
    return index == pattern.length() - 1
1✔
398
        && hostName.startsWith(pattern.substring(0, pattern.length() - 1));
1✔
399
  }
400

401
  private final class ConfigSelector extends InternalConfigSelector {
1✔
402
    @Override
403
    public Result selectConfig(PickSubchannelArgs args) {
404
      RoutingConfig routingCfg;
405
      RouteData selectedRoute;
406
      String cluster;
407
      ClientInterceptor filters;
408
      Metadata headers = args.getHeaders();
1✔
409
      String path = "/" + args.getMethodDescriptor().getFullMethodName();
1✔
410
      do {
411
        routingCfg = routingConfig;
1✔
412
        if (routingCfg.errorStatus != null) {
1✔
413
          return Result.forError(routingCfg.errorStatus);
1✔
414
        }
415
        selectedRoute = null;
1✔
416
        for (RouteData route : routingCfg.routes) {
1✔
417
          if (RoutingUtils.matchRoute(route.routeMatch, path, headers, random)) {
1✔
418
            selectedRoute = route;
1✔
419
            break;
1✔
420
          }
421
        }
1✔
422
        if (selectedRoute == null) {
1✔
423
          return Result.forError(
1✔
424
              Status.UNAVAILABLE.withDescription("Could not find xDS route matching RPC"));
1✔
425
        }
426
        if (selectedRoute.routeAction == null) {
1✔
427
          return Result.forError(Status.UNAVAILABLE.withDescription(
1✔
428
              "Could not route RPC to Route with non-forwarding action"));
429
        }
430
        RouteAction action = selectedRoute.routeAction;
1✔
431
        if (action.cluster() != null) {
1✔
432
          cluster = prefixedClusterName(action.cluster());
1✔
433
          filters = selectedRoute.filterChoices.get(0);
1✔
434
        } else if (action.weightedClusters() != null) {
1✔
435
          // XdsRouteConfigureResource verifies the total weight will not be 0 or exceed uint32
436
          long totalWeight = 0;
1✔
437
          for (ClusterWeight weightedCluster : action.weightedClusters()) {
1✔
438
            totalWeight += weightedCluster.weight();
1✔
439
          }
1✔
440
          long select = random.nextLong(totalWeight);
1✔
441
          long accumulator = 0;
1✔
442
          for (int i = 0; ; i++) {
1✔
443
            ClusterWeight weightedCluster = action.weightedClusters().get(i);
1✔
444
            accumulator += weightedCluster.weight();
1✔
445
            if (select < accumulator) {
1✔
446
              cluster = prefixedClusterName(weightedCluster.name());
1✔
447
              filters = selectedRoute.filterChoices.get(i);
1✔
448
              break;
1✔
449
            }
450
          }
451
        } else if (action.namedClusterSpecifierPluginConfig() != null) {
1✔
452
          cluster =
1✔
453
              prefixedClusterSpecifierPluginName(action.namedClusterSpecifierPluginConfig().name());
1✔
454
          filters = selectedRoute.filterChoices.get(0);
1✔
455
        } else {
456
          // updateRoutes() discards routes with unknown actions
457
          throw new AssertionError();
×
458
        }
459
      } while (!retainCluster(cluster));
1✔
460

461
      final RouteAction routeAction = selectedRoute.routeAction;
1✔
462
      Long timeoutNanos = null;
1✔
463
      if (enableTimeout) {
1✔
464
        timeoutNanos = routeAction.timeoutNano();
1✔
465
        if (timeoutNanos == null) {
1✔
466
          timeoutNanos = routingCfg.fallbackTimeoutNano;
1✔
467
        }
468
        if (timeoutNanos <= 0) {
1✔
469
          timeoutNanos = null;
1✔
470
        }
471
      }
472
      RetryPolicy retryPolicy = routeAction.retryPolicy();
1✔
473
      // TODO(chengyuanzhang): avoid service config generation and parsing for each call.
474
      Map<String, ?> rawServiceConfig =
1✔
475
          generateServiceConfigWithMethodConfig(timeoutNanos, retryPolicy);
1✔
476
      ConfigOrError parsedServiceConfig = serviceConfigParser.parseServiceConfig(rawServiceConfig);
1✔
477
      Object config = parsedServiceConfig.getConfig();
1✔
478
      if (config == null) {
1✔
479
        releaseCluster(cluster);
×
480
        return Result.forError(
×
481
            parsedServiceConfig.getError().augmentDescription(
×
482
                "Failed to parse service config (method config)"));
483
      }
484
      final String finalCluster = cluster;
1✔
485
      final XdsConfig xdsConfig = routingCfg.xdsConfig;
1✔
486
      final long hash = generateHash(routeAction.hashPolicies(), headers);
1✔
487
      class ClusterSelectionInterceptor implements ClientInterceptor {
1✔
488
        @Override
489
        public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(
490
            final MethodDescriptor<ReqT, RespT> method, CallOptions callOptions,
491
            final Channel next) {
492
          CallOptions callOptionsForCluster =
1✔
493
              callOptions.withOption(CLUSTER_SELECTION_KEY, finalCluster)
1✔
494
                  .withOption(XDS_CONFIG_CALL_OPTION_KEY, xdsConfig)
1✔
495
                  .withOption(RPC_HASH_KEY, hash);
1✔
496
          if (routeAction.autoHostRewrite()) {
1✔
497
            callOptionsForCluster = callOptionsForCluster.withOption(AUTO_HOST_REWRITE_KEY, true);
1✔
498
          }
499
          return new SimpleForwardingClientCall<ReqT, RespT>(
1✔
500
              next.newCall(method, callOptionsForCluster)) {
1✔
501
            @Override
502
            public void start(Listener<RespT> listener, Metadata headers) {
503
              listener = new SimpleForwardingClientCallListener<RespT>(listener) {
1✔
504
                boolean committed;
505

506
                @Override
507
                public void onHeaders(Metadata headers) {
508
                  committed = true;
1✔
509
                  releaseCluster(finalCluster);
1✔
510
                  delegate().onHeaders(headers);
1✔
511
                }
1✔
512

513
                @Override
514
                public void onClose(Status status, Metadata trailers) {
515
                  if (!committed) {
1✔
516
                    releaseCluster(finalCluster);
1✔
517
                  }
518
                  delegate().onClose(status, trailers);
1✔
519
                }
1✔
520
              };
521
              delegate().start(listener, headers);
1✔
522
            }
1✔
523
          };
524
        }
525
      }
526

527
      return
1✔
528
          Result.newBuilder()
1✔
529
              .setConfig(config)
1✔
530
              .setInterceptor(combineInterceptors(
1✔
531
                  ImmutableList.of(new ClusterSelectionInterceptor(), filters)))
1✔
532
              .build();
1✔
533
    }
534

535
    private boolean retainCluster(String cluster) {
536
      ClusterRefState clusterRefState = clusterRefs.get(cluster);
1✔
537
      if (clusterRefState == null) {
1✔
538
        return false;
×
539
      }
540
      AtomicInteger refCount = clusterRefState.refCount;
1✔
541
      int count;
542
      do {
543
        count = refCount.get();
1✔
544
        if (count == 0) {
1✔
545
          return false;
×
546
        }
547
      } while (!refCount.compareAndSet(count, count + 1));
1✔
548
      return true;
1✔
549
    }
550

551
    private void releaseCluster(final String cluster) {
552
      int count = clusterRefs.get(cluster).refCount.decrementAndGet();
1✔
553
      if (count < 0) {
1✔
554
        throw new AssertionError();
×
555
      }
556
      if (count == 0) {
1✔
557
        syncContext.execute(new Runnable() {
1✔
558
          @Override
559
          public void run() {
560
            if (clusterRefs.get(cluster).refCount.get() != 0) {
1✔
561
              throw new AssertionError();
×
562
            }
563
            clusterRefs.remove(cluster).close();
1✔
564
            if (resolveState.lastConfigOrStatus.hasValue()) {
1✔
565
              updateResolutionResult(resolveState.lastConfigOrStatus.getValue());
1✔
566
            } else {
567
              resolveState.cleanUpRoutes(resolveState.lastConfigOrStatus.getStatus());
×
568
            }
569
          }
1✔
570
        });
571
      }
572
    }
1✔
573

574
    private long generateHash(List<HashPolicy> hashPolicies, Metadata headers) {
575
      Long hash = null;
1✔
576
      for (HashPolicy policy : hashPolicies) {
1✔
577
        Long newHash = null;
1✔
578
        if (policy.type() == HashPolicy.Type.HEADER) {
1✔
579
          String value = getHeaderValue(headers, policy.headerName());
1✔
580
          if (value != null) {
1✔
581
            if (policy.regEx() != null && policy.regExSubstitution() != null) {
1✔
582
              value = policy.regEx().matcher(value).replaceAll(policy.regExSubstitution());
1✔
583
            }
584
            newHash = hashFunc.hashAsciiString(value);
1✔
585
          }
586
        } else if (policy.type() == HashPolicy.Type.CHANNEL_ID) {
1✔
587
          newHash = hashFunc.hashLong(randomChannelId);
1✔
588
        }
589
        if (newHash != null ) {
1✔
590
          // Rotating the old value prevents duplicate hash rules from cancelling each other out
591
          // and preserves all of the entropy.
592
          long oldHash = hash != null ? ((hash << 1L) | (hash >> 63L)) : 0;
1✔
593
          hash = oldHash ^ newHash;
1✔
594
        }
595
        // If the policy is a terminal policy and a hash has been generated, ignore
596
        // the rest of the hash policies.
597
        if (policy.isTerminal() && hash != null) {
1✔
598
          break;
×
599
        }
600
      }
1✔
601
      return hash == null ? random.nextLong() : hash;
1✔
602
    }
603
  }
604

605
  static final class PassthroughClientInterceptor implements ClientInterceptor {
1✔
606
    @Override
607
    public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(
608
        MethodDescriptor<ReqT, RespT> method, CallOptions callOptions, Channel next) {
609
      return next.newCall(method, callOptions);
1✔
610
    }
611
  }
612

613
  private static ClientInterceptor combineInterceptors(final List<ClientInterceptor> interceptors) {
614
    if (interceptors.size() == 0) {
1✔
615
      return new PassthroughClientInterceptor();
1✔
616
    }
617
    if (interceptors.size() == 1) {
1✔
618
      return interceptors.get(0);
1✔
619
    }
620
    return new ClientInterceptor() {
1✔
621
      @Override
622
      public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(
623
          MethodDescriptor<ReqT, RespT> method, CallOptions callOptions, Channel next) {
624
        next = ClientInterceptors.interceptForward(next, interceptors);
1✔
625
        return next.newCall(method, callOptions);
1✔
626
      }
627
    };
628
  }
629

630
  @Nullable
631
  private static String getHeaderValue(Metadata headers, String headerName) {
632
    if (headerName.endsWith(Metadata.BINARY_HEADER_SUFFIX)) {
1✔
633
      return null;
×
634
    }
635
    if (headerName.equals("content-type")) {
1✔
636
      return "application/grpc";
×
637
    }
638
    Metadata.Key<String> key;
639
    try {
640
      key = Metadata.Key.of(headerName, Metadata.ASCII_STRING_MARSHALLER);
1✔
641
    } catch (IllegalArgumentException e) {
×
642
      return null;
×
643
    }
1✔
644
    Iterable<String> values = headers.getAll(key);
1✔
645
    return values == null ? null : Joiner.on(",").join(values);
1✔
646
  }
647

648
  private static String prefixedClusterName(String name) {
649
    return "cluster:" + name;
1✔
650
  }
651

652
  private static String prefixedClusterSpecifierPluginName(String pluginName) {
653
    return "cluster_specifier_plugin:" + pluginName;
1✔
654
  }
655

656
  class ResolveState implements XdsDependencyManager.XdsConfigWatcher {
1✔
657
    private final ConfigOrError emptyServiceConfig =
1✔
658
        serviceConfigParser.parseServiceConfig(Collections.<String, Object>emptyMap());
1✔
659
    private final String authority;
660
    private final XdsDependencyManager xdsDependencyManager;
661
    private boolean stopped;
662
    @Nullable
663
    private Set<String> existingClusters;  // clusters to which new requests can be routed
664
    private StatusOr<XdsConfig> lastConfigOrStatus;
665

666
    private ResolveState(String ldsResourceName) {
1✔
667
      authority = overrideAuthority != null ? overrideAuthority : encodedServiceAuthority;
1✔
668
      xdsDependencyManager =
1✔
669
          new XdsDependencyManager(xdsClient, syncContext, authority, ldsResourceName,
1✔
670
              nameResolverArgs);
1✔
671
    }
1✔
672

673
    void start() {
674
      xdsDependencyManager.start(this);
1✔
675
    }
1✔
676

677
    void refresh() {
678
      xdsDependencyManager.requestReresolution();
×
679
    }
×
680

681
    private void shutdown() {
682
      if (stopped) {
1✔
683
        return;
×
684
      }
685

686
      stopped = true;
1✔
687
      xdsDependencyManager.shutdown();
1✔
688
      updateActiveFilters(null);
1✔
689
    }
1✔
690

691
    @Override
692
    public void onUpdate(StatusOr<XdsConfig> updateOrStatus) {
693
      if (stopped) {
1✔
694
        return;
×
695
      }
696
      logger.log(XdsLogLevel.INFO, "Receive XDS resource update: {0}", updateOrStatus);
1✔
697

698
      lastConfigOrStatus = updateOrStatus;
1✔
699
      if (!updateOrStatus.hasValue()) {
1✔
700
        updateActiveFilters(null);
1✔
701
        cleanUpRoutes(updateOrStatus.getStatus());
1✔
702
        return;
1✔
703
      }
704

705
      // Process Route
706
      XdsConfig update = updateOrStatus.getValue();
1✔
707
      HttpConnectionManager httpConnectionManager = update.getListener().httpConnectionManager();
1✔
708
      if (httpConnectionManager == null) {
1✔
709
        logger.log(XdsLogLevel.INFO, "API Listener: httpConnectionManager does not exist.");
×
710
        updateActiveFilters(null);
×
711
        cleanUpRoutes(updateOrStatus.getStatus());
×
712
        return;
×
713
      }
714

715
      VirtualHost virtualHost = update.getVirtualHost();
1✔
716
      ImmutableList<NamedFilterConfig> filterConfigs = httpConnectionManager.httpFilterConfigs();
1✔
717
      long streamDurationNano = httpConnectionManager.httpMaxStreamDurationNano();
1✔
718

719
      updateActiveFilters(filterConfigs);
1✔
720
      updateRoutes(update, virtualHost, streamDurationNano, filterConfigs);
1✔
721
    }
1✔
722

723
    // called in syncContext
724
    private void updateActiveFilters(@Nullable List<NamedFilterConfig> filterConfigs) {
725
      if (filterConfigs == null) {
1✔
726
        filterConfigs = ImmutableList.of();
1✔
727
      }
728
      Set<String> filtersToShutdown = new HashSet<>(activeFilters.keySet());
1✔
729
      for (NamedFilterConfig namedFilter : filterConfigs) {
1✔
730
        String typeUrl = namedFilter.filterConfig.typeUrl();
1✔
731
        String filterKey = namedFilter.filterStateKey();
1✔
732

733
        Filter.Provider provider = filterRegistry.get(typeUrl);
1✔
734
        checkNotNull(provider, "provider %s", typeUrl);
1✔
735
        Filter filter = activeFilters.computeIfAbsent(
1✔
736
            filterKey, k -> provider.newInstance(namedFilter.name));
1✔
737
        checkNotNull(filter, "filter %s", filterKey);
1✔
738
        filtersToShutdown.remove(filterKey);
1✔
739
      }
1✔
740

741
      // Shutdown filters not present in current HCM.
742
      for (String filterKey : filtersToShutdown) {
1✔
743
        Filter filterToShutdown = activeFilters.remove(filterKey);
1✔
744
        checkNotNull(filterToShutdown, "filterToShutdown %s", filterKey);
1✔
745
        filterToShutdown.close();
1✔
746
      }
1✔
747
    }
1✔
748

749
    private void updateRoutes(
750
        XdsConfig xdsConfig,
751
        @Nullable VirtualHost virtualHost,
752
        long httpMaxStreamDurationNano,
753
        @Nullable List<NamedFilterConfig> filterConfigs) {
754
      List<Route> routes = virtualHost.routes();
1✔
755
      ImmutableList.Builder<RouteData> routesData = ImmutableList.builder();
1✔
756

757
      // Populate all clusters to which requests can be routed to through the virtual host.
758
      Set<String> clusters = new HashSet<>();
1✔
759
      // uniqueName -> clusterName
760
      Map<String, String> clusterNameMap = new HashMap<>();
1✔
761
      // uniqueName -> pluginConfig
762
      Map<String, RlsPluginConfig> rlsPluginConfigMap = new HashMap<>();
1✔
763
      for (Route route : routes) {
1✔
764
        RouteAction action = route.routeAction();
1✔
765
        String prefixedName;
766
        if (action == null) {
1✔
767
          routesData.add(new RouteData(route.routeMatch(), null, ImmutableList.of()));
1✔
768
        } else if (action.cluster() != null) {
1✔
769
          prefixedName = prefixedClusterName(action.cluster());
1✔
770
          clusters.add(prefixedName);
1✔
771
          clusterNameMap.put(prefixedName, action.cluster());
1✔
772
          ClientInterceptor filters = createFilters(filterConfigs, virtualHost, route, null);
1✔
773
          routesData.add(new RouteData(route.routeMatch(), route.routeAction(), filters));
1✔
774
        } else if (action.weightedClusters() != null) {
1✔
775
          ImmutableList.Builder<ClientInterceptor> filterList = ImmutableList.builder();
1✔
776
          for (ClusterWeight weightedCluster : action.weightedClusters()) {
1✔
777
            prefixedName = prefixedClusterName(weightedCluster.name());
1✔
778
            clusters.add(prefixedName);
1✔
779
            clusterNameMap.put(prefixedName, weightedCluster.name());
1✔
780
            filterList.add(createFilters(filterConfigs, virtualHost, route, weightedCluster));
1✔
781
          }
1✔
782
          routesData.add(
1✔
783
              new RouteData(route.routeMatch(), route.routeAction(), filterList.build()));
1✔
784
        } else if (action.namedClusterSpecifierPluginConfig() != null) {
1✔
785
          PluginConfig pluginConfig = action.namedClusterSpecifierPluginConfig().config();
1✔
786
          if (pluginConfig instanceof RlsPluginConfig) {
1✔
787
            prefixedName = prefixedClusterSpecifierPluginName(
1✔
788
                action.namedClusterSpecifierPluginConfig().name());
1✔
789
            clusters.add(prefixedName);
1✔
790
            rlsPluginConfigMap.put(prefixedName, (RlsPluginConfig) pluginConfig);
1✔
791
          }
792
          ClientInterceptor filters = createFilters(filterConfigs, virtualHost, route, null);
1✔
793
          routesData.add(new RouteData(route.routeMatch(), route.routeAction(), filters));
1✔
794
        } else {
795
          // Discard route
796
        }
797
      }
1✔
798

799
      // Updates channel's load balancing config whenever the set of selectable clusters changes.
800
      boolean shouldUpdateResult = existingClusters == null;
1✔
801
      Set<String> addedClusters =
802
          existingClusters == null ? clusters : Sets.difference(clusters, existingClusters);
1✔
803
      Set<String> deletedClusters =
804
          existingClusters == null
1✔
805
              ? Collections.emptySet() : Sets.difference(existingClusters, clusters);
1✔
806
      existingClusters = clusters;
1✔
807
      for (String cluster : addedClusters) {
1✔
808
        if (clusterRefs.containsKey(cluster)) {
1✔
809
          clusterRefs.get(cluster).refCount.incrementAndGet();
1✔
810
        } else {
811
          if (clusterNameMap.containsKey(cluster)) {
1✔
812
            assert cluster.startsWith("cluster:");
1✔
813
            XdsConfig.Subscription subscription =
1✔
814
                xdsDependencyManager.subscribeToCluster(cluster.substring("cluster:".length()));
1✔
815
            clusterRefs.put(
1✔
816
                cluster,
817
                ClusterRefState.forCluster(
1✔
818
                    new AtomicInteger(1), clusterNameMap.get(cluster), subscription));
1✔
819
          }
820
          if (rlsPluginConfigMap.containsKey(cluster)) {
1✔
821
            clusterRefs.put(
1✔
822
                cluster,
823
                ClusterRefState.forRlsPlugin(
1✔
824
                    new AtomicInteger(1), rlsPluginConfigMap.get(cluster)));
1✔
825
          }
826
          shouldUpdateResult = true;
1✔
827
        }
828
      }
1✔
829
      for (String cluster : clusters) {
1✔
830
        RlsPluginConfig rlsPluginConfig = rlsPluginConfigMap.get(cluster);
1✔
831
        if (!Objects.equals(rlsPluginConfig, clusterRefs.get(cluster).rlsPluginConfig)) {
1✔
832
          ClusterRefState newClusterRefState =
1✔
833
              ClusterRefState.forRlsPlugin(clusterRefs.get(cluster).refCount, rlsPluginConfig);
1✔
834
          clusterRefs.put(cluster, newClusterRefState);
1✔
835
          shouldUpdateResult = true;
1✔
836
        }
837
      }
1✔
838
      // Update service config to include newly added clusters.
839
      if (shouldUpdateResult && routingConfig != null) {
1✔
840
        updateResolutionResult(xdsConfig);
1✔
841
        shouldUpdateResult = false;
1✔
842
      } else {
843
        // Need to update at least once
844
        shouldUpdateResult = true;
1✔
845
      }
846
      // Make newly added clusters selectable by config selector and deleted clusters no longer
847
      // selectable.
848
      routingConfig = new RoutingConfig(xdsConfig, httpMaxStreamDurationNano, routesData.build());
1✔
849
      for (String cluster : deletedClusters) {
1✔
850
        int count = clusterRefs.get(cluster).refCount.decrementAndGet();
1✔
851
        if (count == 0) {
1✔
852
          clusterRefs.remove(cluster).close();
1✔
853
          shouldUpdateResult = true;
1✔
854
        }
855
      }
1✔
856
      if (shouldUpdateResult) {
1✔
857
        updateResolutionResult(xdsConfig);
1✔
858
      }
859
    }
1✔
860

861
    private ClientInterceptor createFilters(
862
        @Nullable List<NamedFilterConfig> filterConfigs,
863
        VirtualHost virtualHost,
864
        Route route,
865
        @Nullable ClusterWeight weightedCluster) {
866
      if (filterConfigs == null) {
1✔
867
        return new PassthroughClientInterceptor();
1✔
868
      }
869

870
      Map<String, FilterConfig> selectedOverrideConfigs =
1✔
871
          new HashMap<>(virtualHost.filterConfigOverrides());
1✔
872
      selectedOverrideConfigs.putAll(route.filterConfigOverrides());
1✔
873
      if (weightedCluster != null) {
1✔
874
        selectedOverrideConfigs.putAll(weightedCluster.filterConfigOverrides());
1✔
875
      }
876

877
      ImmutableList.Builder<ClientInterceptor> filterInterceptors = ImmutableList.builder();
1✔
878
      for (NamedFilterConfig namedFilter : filterConfigs) {
1✔
879
        String name = namedFilter.name;
1✔
880
        FilterConfig config = namedFilter.filterConfig;
1✔
881
        FilterConfig overrideConfig = selectedOverrideConfigs.get(name);
1✔
882
        String filterKey = namedFilter.filterStateKey();
1✔
883

884
        Filter filter = activeFilters.get(filterKey);
1✔
885
        checkNotNull(filter, "activeFilters.get(%s)", filterKey);
1✔
886
        ClientInterceptor interceptor =
1✔
887
            filter.buildClientInterceptor(config, overrideConfig, scheduler);
1✔
888

889
        if (interceptor != null) {
1✔
890
          filterInterceptors.add(interceptor);
1✔
891
        }
892
      }
1✔
893

894
      // Combine interceptors produced by different filters into a single one that executes
895
      // them sequentially. The order is preserved.
896
      return combineInterceptors(filterInterceptors.build());
1✔
897
    }
898

899
    private void cleanUpRoutes(Status error) {
900
      routingConfig = new RoutingConfig(error);
1✔
901
      if (existingClusters != null) {
1✔
902
        for (String cluster : existingClusters) {
1✔
903
          int count = clusterRefs.get(cluster).refCount.decrementAndGet();
1✔
904
          if (count == 0) {
1✔
905
            clusterRefs.remove(cluster).close();
1✔
906
          }
907
        }
1✔
908
        existingClusters = null;
1✔
909
      }
910

911
      // Without addresses the default LB (normally pick_first) should become TRANSIENT_FAILURE, and
912
      // the config selector handles the error message itself.
913
      listener.onResult2(ResolutionResult.newBuilder()
1✔
914
          .setAttributes(Attributes.newBuilder()
1✔
915
            .set(InternalConfigSelector.KEY, configSelector)
1✔
916
            .build())
1✔
917
          .setServiceConfig(emptyServiceConfig)
1✔
918
          .build());
1✔
919
    }
1✔
920
  }
921

922
  /**
923
   * VirtualHost-level configuration for request routing.
924
   */
925
  private static class RoutingConfig {
926
    final XdsConfig xdsConfig;
927
    final long fallbackTimeoutNano;
928
    final ImmutableList<RouteData> routes;
929
    final Status errorStatus;
930

931
    private RoutingConfig(
932
        XdsConfig xdsConfig, long fallbackTimeoutNano, ImmutableList<RouteData> routes) {
1✔
933
      this.xdsConfig = checkNotNull(xdsConfig, "xdsConfig");
1✔
934
      this.fallbackTimeoutNano = fallbackTimeoutNano;
1✔
935
      this.routes = checkNotNull(routes, "routes");
1✔
936
      this.errorStatus = null;
1✔
937
    }
1✔
938

939
    private RoutingConfig(Status errorStatus) {
1✔
940
      this.xdsConfig = null;
1✔
941
      this.fallbackTimeoutNano = 0;
1✔
942
      this.routes = null;
1✔
943
      this.errorStatus = checkNotNull(errorStatus, "errorStatus");
1✔
944
      checkArgument(!errorStatus.isOk(), "errorStatus should not be okay");
1✔
945
    }
1✔
946
  }
947

948
  static final class RouteData {
949
    final RouteMatch routeMatch;
950
    /** null implies non-forwarding action. */
951
    @Nullable
952
    final RouteAction routeAction;
953
    /**
954
     * Only one of these interceptors should be used per-RPC. There are only multiple values in the
955
     * list for weighted clusters, in which case the order of the list mirrors the weighted
956
     * clusters.
957
     */
958
    final ImmutableList<ClientInterceptor> filterChoices;
959

960
    RouteData(RouteMatch routeMatch, @Nullable RouteAction routeAction, ClientInterceptor filter) {
961
      this(routeMatch, routeAction, ImmutableList.of(filter));
1✔
962
    }
1✔
963

964
    RouteData(
965
        RouteMatch routeMatch,
966
        @Nullable RouteAction routeAction,
967
        ImmutableList<ClientInterceptor> filterChoices) {
1✔
968
      this.routeMatch = checkNotNull(routeMatch, "routeMatch");
1✔
969
      checkArgument(
1✔
970
          routeAction == null || !filterChoices.isEmpty(),
1✔
971
          "filter may be empty only for non-forwarding action");
972
      this.routeAction = routeAction;
1✔
973
      if (routeAction != null && routeAction.weightedClusters() != null) {
1✔
974
        checkArgument(
1✔
975
            routeAction.weightedClusters().size() == filterChoices.size(),
1✔
976
            "filter choices must match size of weighted clusters");
977
      }
978
      for (ClientInterceptor filter : filterChoices) {
1✔
979
        checkNotNull(filter, "entry in filterChoices is null");
1✔
980
      }
1✔
981
      this.filterChoices = checkNotNull(filterChoices, "filterChoices");
1✔
982
    }
1✔
983
  }
984

985
  private static class ClusterRefState {
986
    final AtomicInteger refCount;
987
    @Nullable
988
    final String traditionalCluster;
989
    @Nullable
990
    final RlsPluginConfig rlsPluginConfig;
991
    @Nullable
992
    final XdsConfig.Subscription subscription;
993

994
    private ClusterRefState(
995
        AtomicInteger refCount, @Nullable String traditionalCluster,
996
        @Nullable RlsPluginConfig rlsPluginConfig, @Nullable XdsConfig.Subscription subscription) {
1✔
997
      this.refCount = refCount;
1✔
998
      checkArgument(traditionalCluster == null ^ rlsPluginConfig == null,
1✔
999
          "There must be exactly one non-null value in traditionalCluster and pluginConfig");
1000
      this.traditionalCluster = traditionalCluster;
1✔
1001
      this.rlsPluginConfig = rlsPluginConfig;
1✔
1002
      this.subscription = subscription;
1✔
1003
    }
1✔
1004

1005
    private Map<String, ?> toLbPolicy() {
1006
      if (traditionalCluster != null) {
1✔
1007
        return ImmutableMap.of(
1✔
1008
            XdsLbPolicies.CDS_POLICY_NAME,
1009
            ImmutableMap.of("cluster", traditionalCluster));
1✔
1010
      } else {
1011
        ImmutableMap<String, ?> rlsConfig = new ImmutableMap.Builder<String, Object>()
1✔
1012
            .put("routeLookupConfig", rlsPluginConfig.config())
1✔
1013
            .put(
1✔
1014
                "childPolicy",
1015
                ImmutableList.of(ImmutableMap.of(XdsLbPolicies.CDS_POLICY_NAME, ImmutableMap.of(
1✔
1016
                    "is_dynamic", true))))
1✔
1017
            .put("childPolicyConfigTargetFieldName", "cluster")
1✔
1018
            .buildOrThrow();
1✔
1019
        return ImmutableMap.of("rls_experimental", rlsConfig);
1✔
1020
      }
1021
    }
1022

1023
    private void close() {
1024
      if (subscription != null) {
1✔
1025
        subscription.close();
1✔
1026
      }
1027
    }
1✔
1028

1029
    static ClusterRefState forCluster(
1030
        AtomicInteger refCount, String name, XdsConfig.Subscription subscription) {
1031
      return new ClusterRefState(refCount, name, null, checkNotNull(subscription, "subscription"));
1✔
1032
    }
1033

1034
    static ClusterRefState forRlsPlugin(
1035
        AtomicInteger refCount,
1036
        RlsPluginConfig rlsPluginConfig) {
1037
      return new ClusterRefState(refCount, null, rlsPluginConfig, null);
1✔
1038
    }
1039
  }
1040

1041
  /** An ObjectPool, except it can throw an exception. */
1042
  private interface XdsClientPool {
1043
    XdsClient getObject() throws XdsInitializationException;
1044

1045
    XdsClient returnObject(XdsClient xdsClient);
1046
  }
1047

1048
  private static final class BootstrappingXdsClientPool implements XdsClientPool {
1049
    private final XdsClientPoolFactory xdsClientPoolFactory;
1050
    private final String target;
1051
    private final @Nullable Map<String, ?> bootstrapOverride;
1052
    private final @Nullable MetricRecorder metricRecorder;
1053
    private ObjectPool<XdsClient> xdsClientPool;
1054

1055
    BootstrappingXdsClientPool(
1056
        XdsClientPoolFactory xdsClientPoolFactory,
1057
        String target,
1058
        @Nullable Map<String, ?> bootstrapOverride,
1059
        @Nullable MetricRecorder metricRecorder) {
1✔
1060
      this.xdsClientPoolFactory = checkNotNull(xdsClientPoolFactory, "xdsClientPoolFactory");
1✔
1061
      this.target = checkNotNull(target, "target");
1✔
1062
      this.bootstrapOverride = bootstrapOverride;
1✔
1063
      this.metricRecorder = metricRecorder;
1✔
1064
    }
1✔
1065

1066
    @Override
1067
    public XdsClient getObject() throws XdsInitializationException {
1068
      if (xdsClientPool == null) {
1✔
1069
        BootstrapInfo bootstrapInfo;
1070
        if (bootstrapOverride == null) {
1✔
1071
          bootstrapInfo = GrpcBootstrapperImpl.defaultBootstrap();
×
1072
        } else {
1073
          bootstrapInfo = new GrpcBootstrapperImpl().bootstrap(bootstrapOverride);
1✔
1074
        }
1075
        this.xdsClientPool =
1✔
1076
            xdsClientPoolFactory.getOrCreate(target, bootstrapInfo, metricRecorder);
1✔
1077
      }
1078
      return xdsClientPool.getObject();
1✔
1079
    }
1080

1081
    @Override
1082
    public XdsClient returnObject(XdsClient xdsClient) {
1083
      return xdsClientPool.returnObject(xdsClient);
1✔
1084
    }
1085
  }
1086

1087
  private static final class SupplierXdsClientPool implements XdsClientPool {
1088
    private final Supplier<XdsClient> xdsClientSupplier;
1089

1090
    SupplierXdsClientPool(Supplier<XdsClient> xdsClientSupplier) {
×
1091
      this.xdsClientSupplier = checkNotNull(xdsClientSupplier, "xdsClientSupplier");
×
1092
    }
×
1093

1094
    @Override
1095
    public XdsClient getObject() throws XdsInitializationException {
1096
      XdsClient xdsClient = xdsClientSupplier.get();
×
1097
      if (xdsClient == null) {
×
1098
        throw new XdsInitializationException("Caller failed to initialize XDS_CLIENT_SUPPLIER");
×
1099
      }
1100
      return xdsClient;
×
1101
    }
1102

1103
    @Override
1104
    public XdsClient returnObject(XdsClient xdsClient) {
1105
      return null;
×
1106
    }
1107
  }
1108
}
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