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

grpc / grpc-java / #20337

26 Jun 2026 11:37AM UTC coverage: 89.06% (+0.2%) from 88.876%
#20337

push

github

web-flow
Ext_proc filter and client interceptor (#12792)

Implements ext_proc filter from [grfc A93](https://github.com/grpc/proposal/pull/484)  (internal [design doc](http://go/ext-proc-design-java)).

37585 of 42202 relevant lines covered (89.06%)

0.89 hits per line

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

91.64
/../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.FilterContext;
55
import io.grpc.xds.Filter.NamedFilterConfig;
56
import io.grpc.xds.RouteLookupServiceClusterSpecifierPlugin.RlsPluginConfig;
57
import io.grpc.xds.ThreadSafeRandom.ThreadSafeRandomImpl;
58
import io.grpc.xds.VirtualHost.Route;
59
import io.grpc.xds.VirtualHost.Route.RouteAction;
60
import io.grpc.xds.VirtualHost.Route.RouteAction.ClusterWeight;
61
import io.grpc.xds.VirtualHost.Route.RouteAction.HashPolicy;
62
import io.grpc.xds.VirtualHost.Route.RouteAction.RetryPolicy;
63
import io.grpc.xds.VirtualHost.Route.RouteMatch;
64
import io.grpc.xds.XdsNameResolverProvider.CallCounterProvider;
65
import io.grpc.xds.client.Bootstrapper.AuthorityInfo;
66
import io.grpc.xds.client.Bootstrapper.BootstrapInfo;
67
import io.grpc.xds.client.XdsClient;
68
import io.grpc.xds.client.XdsInitializationException;
69
import io.grpc.xds.client.XdsLogger;
70
import io.grpc.xds.client.XdsLogger.XdsLogLevel;
71
import java.io.InputStream;
72
import java.util.ArrayList;
73
import java.util.Collections;
74
import java.util.HashMap;
75
import java.util.HashSet;
76
import java.util.List;
77
import java.util.Locale;
78
import java.util.Map;
79
import java.util.Objects;
80
import java.util.Set;
81
import java.util.concurrent.ConcurrentHashMap;
82
import java.util.concurrent.ConcurrentMap;
83
import java.util.concurrent.ScheduledExecutorService;
84
import java.util.concurrent.atomic.AtomicInteger;
85
import java.util.function.Supplier;
86
import javax.annotation.Nullable;
87

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

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

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

142

143
  /**
144
   * Constructs a new instance.
145
   *
146
   * @param target the target URI to resolve
147
   * @param targetAuthority the authority component of `target`, possibly the empty string, or null
148
   *     if 'target' has no such component
149
   */
150
  XdsNameResolver(
151
      String target, @Nullable String targetAuthority, String name,
152
      @Nullable String overrideAuthority, ServiceConfigParser serviceConfigParser,
153
      SynchronizationContext syncContext, ScheduledExecutorService scheduler,
154
      @Nullable Map<String, ?> bootstrapOverride,
155
      MetricRecorder metricRecorder, Args nameResolverArgs) {
156
    this(target, targetAuthority, name, overrideAuthority, serviceConfigParser,
1✔
157
        syncContext, scheduler,
158
        bootstrapOverride == null
1✔
159
            ? SharedXdsClientPoolProvider.getDefaultProvider()
1✔
160
            : new SharedXdsClientPoolProvider(),
1✔
161
        ThreadSafeRandomImpl.instance, FilterRegistry.getDefaultRegistry(), bootstrapOverride,
1✔
162
        metricRecorder, nameResolverArgs);
163
  }
1✔
164

165
  @VisibleForTesting
166
  XdsNameResolver(
167
      String target, @Nullable String targetAuthority, String name,
168
      @Nullable String overrideAuthority, ServiceConfigParser serviceConfigParser,
169
      SynchronizationContext syncContext, ScheduledExecutorService scheduler,
170
      XdsClientPoolFactory xdsClientPoolFactory, ThreadSafeRandom random,
171
      FilterRegistry filterRegistry, @Nullable Map<String, ?> bootstrapOverride,
172
      MetricRecorder metricRecorder, Args nameResolverArgs) {
1✔
173
    this.targetAuthority = targetAuthority;
1✔
174

175
    // The name might have multiple slashes so encode it before verifying.
176
    serviceAuthority = checkNotNull(name, "name");
1✔
177
    this.encodedServiceAuthority =
1✔
178
        GrpcUtil.checkAuthority(GrpcUtil.AuthorityEscaper.encodeAuthority(serviceAuthority));
1✔
179

180
    this.overrideAuthority = overrideAuthority;
1✔
181
    this.serviceConfigParser = checkNotNull(serviceConfigParser, "serviceConfigParser");
1✔
182
    this.syncContext = checkNotNull(syncContext, "syncContext");
1✔
183
    this.scheduler = checkNotNull(scheduler, "scheduler");
1✔
184
    Supplier<XdsClient> xdsClientSupplierArg =
1✔
185
        nameResolverArgs.getArg(XdsNameResolverProvider.XDS_CLIENT_SUPPLIER);
1✔
186
    if (xdsClientSupplierArg != null) {
1✔
187
      this.xdsClientPool = new SupplierXdsClientPool(xdsClientSupplierArg);
×
188
    } else {
189
      checkNotNull(xdsClientPoolFactory, "xdsClientPoolFactory");
1✔
190
      this.xdsClientPool = new BootstrappingXdsClientPool(
1✔
191
          xdsClientPoolFactory, target, bootstrapOverride, metricRecorder);
192
    }
193
    this.random = checkNotNull(random, "random");
1✔
194
    this.filterRegistry = checkNotNull(filterRegistry, "filterRegistry");
1✔
195
    this.nameResolverArgs = checkNotNull(nameResolverArgs, "nameResolverArgs");
1✔
196

197
    randomChannelId = random.nextLong();
1✔
198
    logId = InternalLogId.allocate("xds-resolver", name);
1✔
199
    logger = XdsLogger.withLogId(logId);
1✔
200
    logger.log(XdsLogLevel.INFO, "Created resolver for {0}", name);
1✔
201
  }
1✔
202

203
  @Override
204
  public String getServiceAuthority() {
205
    return encodedServiceAuthority;
1✔
206
  }
207

208
  @Override
209
  public void start(Listener2 listener) {
210
    this.listener = checkNotNull(listener, "listener");
1✔
211
    try {
212
      xdsClient = xdsClientPool.getObject();
1✔
213
    } catch (Exception e) {
1✔
214
      listener.onError(
1✔
215
          Status.UNAVAILABLE.withDescription("Failed to initialize xDS").withCause(e));
1✔
216
      return;
1✔
217
    }
1✔
218
    BootstrapInfo bootstrapInfo = xdsClient.getBootstrapInfo();
1✔
219
    String listenerNameTemplate;
220
    if (targetAuthority == null || targetAuthority.isEmpty()) {
1✔
221
      // Both https://github.com/grpc/proposal/blob/master/A27-xds-global-load-balancing.md and
222
      // A47-xds-federation.md seem to treat an empty authority the same as an undefined one.
223
      listenerNameTemplate = bootstrapInfo.clientDefaultListenerResourceNameTemplate();
1✔
224
    } else {
225
      AuthorityInfo authorityInfo = bootstrapInfo.authorities().get(targetAuthority);
1✔
226
      if (authorityInfo == null) {
1✔
227
        listener.onError(Status.INVALID_ARGUMENT.withDescription(
1✔
228
            "invalid target URI: target authority not found in the bootstrap"));
229
        return;
1✔
230
      }
231
      listenerNameTemplate = authorityInfo.clientListenerResourceNameTemplate();
1✔
232
    }
233
    String replacement = serviceAuthority;
1✔
234
    if (listenerNameTemplate.startsWith(XDSTP_SCHEME)) {
1✔
235
      replacement = XdsClient.percentEncodePath(replacement);
1✔
236
    }
237
    String ldsResourceName = expandPercentS(listenerNameTemplate, replacement);
1✔
238
    if (!XdsClient.isResourceNameValid(ldsResourceName, XdsListenerResource.getInstance().typeUrl())
1✔
239
    ) {
240
      listener.onError(Status.INVALID_ARGUMENT.withDescription(
×
241
          "invalid listener resource URI for service authority: " + serviceAuthority));
242
      return;
×
243
    }
244
    ldsResourceName = XdsClient.canonifyResourceName(ldsResourceName);
1✔
245
    callCounterProvider = SharedCallCounterMap.getInstance();
1✔
246

247
    resolveState = new ResolveState(ldsResourceName);
1✔
248
    resolveState.start();
1✔
249
  }
1✔
250

251
  @Override
252
  public void refresh() {
253
    if (resolveState != null) {
×
254
      resolveState.refresh();
×
255
    }
256
  }
×
257

258
  private static String expandPercentS(String template, String replacement) {
259
    return template.replace("%s", replacement);
1✔
260
  }
261

262
  @Override
263
  public void shutdown() {
264
    logger.log(XdsLogLevel.INFO, "Shutdown");
1✔
265
    if (resolveState != null) {
1✔
266
      resolveState.shutdown();
1✔
267
    }
268
    if (xdsClient != null) {
1✔
269
      xdsClient = xdsClientPool.returnObject(xdsClient);
1✔
270
    }
271
  }
1✔
272

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

309
  @VisibleForTesting
310
  XdsClient getXdsClient() {
311
    return xdsClient;
1✔
312
  }
313

314
  // called in syncContext
315
  private void updateResolutionResult(XdsConfig xdsConfig) {
316
    syncContext.throwIfNotInThisSynchronizationContext();
1✔
317

318
    ImmutableMap.Builder<String, Object> childPolicy = new ImmutableMap.Builder<>();
1✔
319
    for (String name : clusterRefs.keySet()) {
1✔
320
      Map<String, ?> lbPolicy = clusterRefs.get(name).toLbPolicy();
1✔
321
      childPolicy.put(name, ImmutableMap.of("lbPolicy", ImmutableList.of(lbPolicy)));
1✔
322
    }
1✔
323
    Map<String, ?> rawServiceConfig = ImmutableMap.of(
1✔
324
        "loadBalancingConfig",
325
        ImmutableList.of(ImmutableMap.of(
1✔
326
            XdsLbPolicies.CLUSTER_MANAGER_POLICY_NAME,
327
            ImmutableMap.of("childPolicy", childPolicy.buildOrThrow()))));
1✔
328

329
    if (logger.isLoggable(XdsLogLevel.INFO)) {
1✔
330
      logger.log(
×
331
          XdsLogLevel.INFO, "Generated service config: {0}", new Gson().toJson(rawServiceConfig));
×
332
    }
333
    ConfigOrError parsedServiceConfig = serviceConfigParser.parseServiceConfig(rawServiceConfig);
1✔
334
    Attributes attrs =
335
        Attributes.newBuilder()
1✔
336
            .set(XdsAttributes.XDS_CLIENT, xdsClient)
1✔
337
            .set(XdsAttributes.XDS_CONFIG, xdsConfig)
1✔
338
            .set(XdsAttributes.XDS_CLUSTER_SUBSCRIPT_REGISTRY, resolveState.xdsDependencyManager)
1✔
339
            .set(XdsAttributes.CALL_COUNTER_PROVIDER, callCounterProvider)
1✔
340
            .set(InternalConfigSelector.KEY, configSelector)
1✔
341
            .build();
1✔
342
    ResolutionResult result =
343
        ResolutionResult.newBuilder()
1✔
344
            .setAttributes(attrs)
1✔
345
            .setServiceConfig(parsedServiceConfig)
1✔
346
            .build();
1✔
347
    if (!listener.onResult2(result).isOk()) {
1✔
348
      resolveState.xdsDependencyManager.requestReresolution();
×
349
    }
350
  }
1✔
351

352
  /**
353
   * Returns {@code true} iff {@code hostName} matches the domain name {@code pattern} with
354
   * case-insensitive.
355
   *
356
   * <p>Wildcard pattern rules:
357
   * <ol>
358
   * <li>A single asterisk (*) matches any domain.</li>
359
   * <li>Asterisk (*) is only permitted in the left-most or the right-most part of the pattern,
360
   *     but not both.</li>
361
   * </ol>
362
   */
363
  @VisibleForTesting
364
  static boolean matchHostName(String hostName, String pattern) {
365
    checkArgument(hostName.length() != 0 && !hostName.startsWith(".") && !hostName.endsWith("."),
1✔
366
        "Invalid host name");
367
    checkArgument(pattern.length() != 0 && !pattern.startsWith(".") && !pattern.endsWith("."),
1✔
368
        "Invalid pattern/domain name");
369

370
    hostName = hostName.toLowerCase(Locale.US);
1✔
371
    pattern = pattern.toLowerCase(Locale.US);
1✔
372
    // hostName and pattern are now in lower case -- domain names are case-insensitive.
373

374
    if (!pattern.contains("*")) {
1✔
375
      // Not a wildcard pattern -- hostName and pattern must match exactly.
376
      return hostName.equals(pattern);
1✔
377
    }
378
    // Wildcard pattern
379

380
    if (pattern.length() == 1) {
1✔
381
      return true;
×
382
    }
383

384
    int index = pattern.indexOf('*');
1✔
385

386
    // At most one asterisk (*) is allowed.
387
    if (pattern.indexOf('*', index + 1) != -1) {
1✔
388
      return false;
×
389
    }
390

391
    // Asterisk can only match prefix or suffix.
392
    if (index != 0 && index != pattern.length() - 1) {
1✔
393
      return false;
×
394
    }
395

396
    // HostName must be at least as long as the pattern because asterisk has to
397
    // match one or more characters.
398
    if (hostName.length() < pattern.length()) {
1✔
399
      return false;
1✔
400
    }
401

402
    if (index == 0 && hostName.endsWith(pattern.substring(1))) {
1✔
403
      // Prefix matching fails.
404
      return true;
1✔
405
    }
406

407
    // Pattern matches hostname if suffix matching succeeds.
408
    return index == pattern.length() - 1
1✔
409
        && hostName.startsWith(pattern.substring(0, pattern.length() - 1));
1✔
410
  }
411

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

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

517
                @Override
518
                public void onHeaders(Metadata headers) {
519
                  committed = true;
1✔
520
                  releaseCluster(finalCluster);
1✔
521
                  delegate().onHeaders(headers);
1✔
522
                }
1✔
523

524
                @Override
525
                public void onClose(Status status, Metadata trailers) {
526
                  if (!committed) {
1✔
527
                    releaseCluster(finalCluster);
1✔
528
                  }
529
                  delegate().onClose(status, trailers);
1✔
530
                }
1✔
531
              };
532
              delegate().start(listener, headers);
1✔
533
            }
1✔
534
          };
535
        }
536
      }
537

538
      return
1✔
539
          Result.newBuilder()
1✔
540
              .setConfig(config)
1✔
541
              .setInterceptor(combineInterceptors(
1✔
542
                  ImmutableList.of(new ClusterSelectionInterceptor(), filters)))
1✔
543
              .build();
1✔
544
    }
545

546
    private boolean retainCluster(String cluster) {
547
      ClusterRefState clusterRefState = clusterRefs.get(cluster);
1✔
548
      if (clusterRefState == null) {
1✔
549
        return false;
×
550
      }
551
      AtomicInteger refCount = clusterRefState.refCount;
1✔
552
      int count;
553
      do {
554
        count = refCount.get();
1✔
555
        if (count == 0) {
1✔
556
          return false;
×
557
        }
558
      } while (!refCount.compareAndSet(count, count + 1));
1✔
559
      return true;
1✔
560
    }
561

562
    private void releaseCluster(final String cluster) {
563
      int count = clusterRefs.get(cluster).refCount.decrementAndGet();
1✔
564
      if (count < 0) {
1✔
565
        throw new AssertionError();
×
566
      }
567
      if (count == 0) {
1✔
568
        syncContext.execute(new Runnable() {
1✔
569
          @Override
570
          public void run() {
571
            if (clusterRefs.get(cluster).refCount.get() != 0) {
1✔
572
              throw new AssertionError();
×
573
            }
574
            clusterRefs.remove(cluster).close();
1✔
575
            if (resolveState.lastConfigOrStatus.hasValue()) {
1✔
576
              updateResolutionResult(resolveState.lastConfigOrStatus.getValue());
1✔
577
            } else {
578
              resolveState.cleanUpRoutes(resolveState.lastConfigOrStatus.getStatus());
×
579
            }
580
          }
1✔
581
        });
582
      }
583
    }
1✔
584

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

616
  static final class PassthroughClientInterceptor implements ClientInterceptor {
1✔
617
    @Override
618
    public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(
619
        MethodDescriptor<ReqT, RespT> method, CallOptions callOptions, Channel next) {
620
      return next.newCall(method, callOptions);
1✔
621
    }
622
  }
623

624
  private static ClientInterceptor combineInterceptors(final List<ClientInterceptor> interceptors) {
625
    if (interceptors.size() == 0) {
1✔
626
      return new PassthroughClientInterceptor();
×
627
    }
628
    if (interceptors.size() == 1) {
1✔
629
      return interceptors.get(0);
1✔
630
    }
631
    return new ClientInterceptor() {
1✔
632
      @Override
633
      public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(
634
          MethodDescriptor<ReqT, RespT> method, CallOptions callOptions, Channel next) {
635
        next = ClientInterceptors.interceptForward(next, interceptors);
1✔
636
        return next.newCall(method, callOptions);
1✔
637
      }
638
    };
639
  }
640

641
  @Nullable
642
  private static String getHeaderValue(Metadata headers, String headerName) {
643
    if (headerName.endsWith(Metadata.BINARY_HEADER_SUFFIX)) {
1✔
644
      return null;
×
645
    }
646
    if (headerName.equals("content-type")) {
1✔
647
      return "application/grpc";
×
648
    }
649
    Metadata.Key<String> key;
650
    try {
651
      key = Metadata.Key.of(headerName, Metadata.ASCII_STRING_MARSHALLER);
1✔
652
    } catch (IllegalArgumentException e) {
×
653
      return null;
×
654
    }
1✔
655
    Iterable<String> values = headers.getAll(key);
1✔
656
    return values == null ? null : Joiner.on(",").join(values);
1✔
657
  }
658

659
  private static String prefixedClusterName(String name) {
660
    return "cluster:" + name;
1✔
661
  }
662

663
  private static String prefixedClusterSpecifierPluginName(String pluginName) {
664
    return "cluster_specifier_plugin:" + pluginName;
1✔
665
  }
666

667
  class ResolveState implements XdsDependencyManager.XdsConfigWatcher {
1✔
668
    private final ConfigOrError emptyServiceConfig =
1✔
669
        serviceConfigParser.parseServiceConfig(Collections.<String, Object>emptyMap());
1✔
670
    private final String authority;
671
    private final XdsDependencyManager xdsDependencyManager;
672
    private boolean stopped;
673
    @Nullable
674
    private Set<String> existingClusters;  // clusters to which new requests can be routed
675
    private StatusOr<XdsConfig> lastConfigOrStatus;
676

677
    private ResolveState(String ldsResourceName) {
1✔
678
      authority = overrideAuthority != null ? overrideAuthority : encodedServiceAuthority;
1✔
679
      xdsDependencyManager =
1✔
680
          new XdsDependencyManager(xdsClient, syncContext, authority, ldsResourceName,
1✔
681
              nameResolverArgs);
1✔
682
    }
1✔
683

684
    void start() {
685
      xdsDependencyManager.start(this);
1✔
686
    }
1✔
687

688
    void refresh() {
689
      xdsDependencyManager.requestReresolution();
×
690
    }
×
691

692
    private void shutdown() {
693
      if (stopped) {
1✔
694
        return;
×
695
      }
696

697
      stopped = true;
1✔
698
      xdsDependencyManager.shutdown();
1✔
699
      updateActiveFilters(null);
1✔
700
    }
1✔
701

702
    @Override
703
    public void onUpdate(StatusOr<XdsConfig> updateOrStatus) {
704
      if (stopped) {
1✔
705
        return;
×
706
      }
707
      logger.log(XdsLogLevel.INFO, "Receive XDS resource update: {0}", updateOrStatus);
1✔
708

709
      lastConfigOrStatus = updateOrStatus;
1✔
710
      if (!updateOrStatus.hasValue()) {
1✔
711
        updateActiveFilters(null);
1✔
712
        cleanUpRoutes(updateOrStatus.getStatus());
1✔
713
        return;
1✔
714
      }
715

716
      // Process Route
717
      XdsConfig update = updateOrStatus.getValue();
1✔
718
      HttpConnectionManager httpConnectionManager = update.getListener().httpConnectionManager();
1✔
719
      if (httpConnectionManager == null) {
1✔
720
        logger.log(XdsLogLevel.INFO, "API Listener: httpConnectionManager does not exist.");
×
721
        updateActiveFilters(null);
×
722
        cleanUpRoutes(updateOrStatus.getStatus());
×
723
        return;
×
724
      }
725

726
      VirtualHost virtualHost = update.getVirtualHost();
1✔
727
      ImmutableList<NamedFilterConfig> filterConfigs = httpConnectionManager.httpFilterConfigs();
1✔
728
      long streamDurationNano = httpConnectionManager.httpMaxStreamDurationNano();
1✔
729

730
      updateActiveFilters(filterConfigs);
1✔
731
      updateRoutes(update, virtualHost, streamDurationNano, filterConfigs);
1✔
732
    }
1✔
733

734
    // called in syncContext
735
    private void updateActiveFilters(@Nullable List<NamedFilterConfig> filterConfigs) {
736
      if (filterConfigs == null) {
1✔
737
        filterConfigs = ImmutableList.of();
1✔
738
      }
739
      Set<String> filtersToShutdown = new HashSet<>(activeFilters.keySet());
1✔
740
      for (NamedFilterConfig namedFilter : filterConfigs) {
1✔
741
        String typeUrl = namedFilter.filterConfig.typeUrl();
1✔
742
        String filterKey = namedFilter.filterStateKey();
1✔
743

744
        Filter.Provider provider = filterRegistry.get(typeUrl);
1✔
745
        checkNotNull(provider, "provider %s", typeUrl);
1✔
746
        Filter filter = activeFilters.computeIfAbsent(
1✔
747
            filterKey, k -> provider.newInstance(
1✔
748
                FilterContext.create(
1✔
749
                    namedFilter.name, nameResolverArgs.getMetricRecorder())));
1✔
750
        checkNotNull(filter, "filter %s", filterKey);
1✔
751
        filtersToShutdown.remove(filterKey);
1✔
752
      }
1✔
753

754
      // Shutdown filters not present in current HCM.
755
      for (String filterKey : filtersToShutdown) {
1✔
756
        Filter filterToShutdown = activeFilters.remove(filterKey);
1✔
757
        checkNotNull(filterToShutdown, "filterToShutdown %s", filterKey);
1✔
758
        filterToShutdown.close();
1✔
759
      }
1✔
760
    }
1✔
761

762
    private void updateRoutes(
763
        XdsConfig xdsConfig,
764
        @Nullable VirtualHost virtualHost,
765
        long httpMaxStreamDurationNano,
766
        @Nullable List<NamedFilterConfig> filterConfigs) {
767
      List<Route> routes = virtualHost.routes();
1✔
768
      ImmutableList.Builder<RouteData> routesData = ImmutableList.builder();
1✔
769

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

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

874
    private ClientInterceptor createFilters(
875
        @Nullable List<NamedFilterConfig> filterConfigs,
876
        VirtualHost virtualHost,
877
        Route route,
878
        @Nullable ClusterWeight weightedCluster) {
879
      if (filterConfigs == null) {
1✔
880
        return new PassthroughClientInterceptor();
1✔
881
      }
882

883
      Map<String, FilterConfig> selectedOverrideConfigs =
1✔
884
          new HashMap<>(virtualHost.filterConfigOverrides());
1✔
885
      selectedOverrideConfigs.putAll(route.filterConfigOverrides());
1✔
886
      if (weightedCluster != null) {
1✔
887
        selectedOverrideConfigs.putAll(weightedCluster.filterConfigOverrides());
1✔
888
      }
889

890
      ImmutableList.Builder<ClientInterceptor> filterInterceptors = ImmutableList.builder();
1✔
891
      for (NamedFilterConfig namedFilter : filterConfigs) {
1✔
892
        String name = namedFilter.name;
1✔
893
        FilterConfig config = namedFilter.filterConfig;
1✔
894
        FilterConfig overrideConfig = selectedOverrideConfigs.get(name);
1✔
895
        String filterKey = namedFilter.filterStateKey();
1✔
896

897
        Filter filter = activeFilters.get(filterKey);
1✔
898
        checkNotNull(filter, "activeFilters.get(%s)", filterKey);
1✔
899
        ClientInterceptor interceptor =
1✔
900
            filter.buildClientInterceptor(config, overrideConfig, scheduler);
1✔
901

902
        if (interceptor != null) {
1✔
903
          filterInterceptors.add(interceptor);
1✔
904
        }
905
      }
1✔
906

907
      ImmutableList.Builder<ClientInterceptor> withRawMessage = ImmutableList.builder();
1✔
908
      withRawMessage.add(new RawMessageClientInterceptor());
1✔
909
      withRawMessage.addAll(filterInterceptors.build());
1✔
910
      return combineInterceptors(withRawMessage.build());
1✔
911
    }
912

913
    private void cleanUpRoutes(Status error) {
914
      routingConfig = new RoutingConfig(error);
1✔
915
      if (existingClusters != null) {
1✔
916
        for (String cluster : existingClusters) {
1✔
917
          int count = clusterRefs.get(cluster).refCount.decrementAndGet();
1✔
918
          if (count == 0) {
1✔
919
            clusterRefs.remove(cluster).close();
1✔
920
          }
921
        }
1✔
922
        existingClusters = null;
1✔
923
      }
924

925
      // Without addresses the default LB (normally pick_first) should become TRANSIENT_FAILURE, and
926
      // the config selector handles the error message itself.
927
      listener.onResult2(ResolutionResult.newBuilder()
1✔
928
          .setAttributes(Attributes.newBuilder()
1✔
929
              .set(InternalConfigSelector.KEY, configSelector)
1✔
930
              .build())
1✔
931
          .setServiceConfig(emptyServiceConfig)
1✔
932
          .build());
1✔
933
    }
1✔
934
  }
935

936
  /**
937
   * VirtualHost-level configuration for request routing.
938
   */
939
  private static class RoutingConfig {
940
    final XdsConfig xdsConfig;
941
    final long fallbackTimeoutNano;
942
    final ImmutableList<RouteData> routes;
943
    final Status errorStatus;
944

945
    private RoutingConfig(
946
        XdsConfig xdsConfig, long fallbackTimeoutNano, ImmutableList<RouteData> routes) {
1✔
947
      this.xdsConfig = checkNotNull(xdsConfig, "xdsConfig");
1✔
948
      this.fallbackTimeoutNano = fallbackTimeoutNano;
1✔
949
      this.routes = checkNotNull(routes, "routes");
1✔
950
      this.errorStatus = null;
1✔
951
    }
1✔
952

953
    private RoutingConfig(Status errorStatus) {
1✔
954
      this.xdsConfig = null;
1✔
955
      this.fallbackTimeoutNano = 0;
1✔
956
      this.routes = null;
1✔
957
      this.errorStatus = checkNotNull(errorStatus, "errorStatus");
1✔
958
      checkArgument(!errorStatus.isOk(), "errorStatus should not be okay");
1✔
959
    }
1✔
960
  }
961

962
  static final class RouteData {
963
    final RouteMatch routeMatch;
964
    /** null implies non-forwarding action. */
965
    @Nullable
966
    final RouteAction routeAction;
967
    /**
968
     * Only one of these interceptors should be used per-RPC. There are only multiple values in the
969
     * list for weighted clusters, in which case the order of the list mirrors the weighted
970
     * clusters.
971
     */
972
    final ImmutableList<ClientInterceptor> filterChoices;
973

974
    RouteData(RouteMatch routeMatch, @Nullable RouteAction routeAction, ClientInterceptor filter) {
975
      this(routeMatch, routeAction, ImmutableList.of(filter));
1✔
976
    }
1✔
977

978
    RouteData(
979
        RouteMatch routeMatch,
980
        @Nullable RouteAction routeAction,
981
        ImmutableList<ClientInterceptor> filterChoices) {
1✔
982
      this.routeMatch = checkNotNull(routeMatch, "routeMatch");
1✔
983
      checkArgument(
1✔
984
          routeAction == null || !filterChoices.isEmpty(),
1✔
985
          "filter may be empty only for non-forwarding action");
986
      this.routeAction = routeAction;
1✔
987
      if (routeAction != null && routeAction.weightedClusters() != null) {
1✔
988
        checkArgument(
1✔
989
            routeAction.weightedClusters().size() == filterChoices.size(),
1✔
990
            "filter choices must match size of weighted clusters");
991
      }
992
      for (ClientInterceptor filter : filterChoices) {
1✔
993
        checkNotNull(filter, "entry in filterChoices is null");
1✔
994
      }
1✔
995
      this.filterChoices = checkNotNull(filterChoices, "filterChoices");
1✔
996
    }
1✔
997
  }
998

999
  private static class ClusterRefState {
1000
    final AtomicInteger refCount;
1001
    @Nullable
1002
    final String traditionalCluster;
1003
    @Nullable
1004
    final RlsPluginConfig rlsPluginConfig;
1005
    @Nullable
1006
    final XdsConfig.Subscription subscription;
1007

1008
    private ClusterRefState(
1009
        AtomicInteger refCount, @Nullable String traditionalCluster,
1010
        @Nullable RlsPluginConfig rlsPluginConfig, @Nullable XdsConfig.Subscription subscription) {
1✔
1011
      this.refCount = refCount;
1✔
1012
      checkArgument(traditionalCluster == null ^ rlsPluginConfig == null,
1✔
1013
          "There must be exactly one non-null value in traditionalCluster and pluginConfig");
1014
      this.traditionalCluster = traditionalCluster;
1✔
1015
      this.rlsPluginConfig = rlsPluginConfig;
1✔
1016
      this.subscription = subscription;
1✔
1017
    }
1✔
1018

1019
    private Map<String, ?> toLbPolicy() {
1020
      if (traditionalCluster != null) {
1✔
1021
        return ImmutableMap.of(
1✔
1022
            XdsLbPolicies.CDS_POLICY_NAME,
1023
            ImmutableMap.of("cluster", traditionalCluster));
1✔
1024
      } else {
1025
        ImmutableMap<String, ?> rlsConfig = new ImmutableMap.Builder<String, Object>()
1✔
1026
            .put("routeLookupConfig", rlsPluginConfig.config())
1✔
1027
            .put(
1✔
1028
                "childPolicy",
1029
                ImmutableList.of(ImmutableMap.of(XdsLbPolicies.CDS_POLICY_NAME, ImmutableMap.of(
1✔
1030
                    "is_dynamic", true))))
1✔
1031
            .put("childPolicyConfigTargetFieldName", "cluster")
1✔
1032
            .buildOrThrow();
1✔
1033
        return ImmutableMap.of("rls_experimental", rlsConfig);
1✔
1034
      }
1035
    }
1036

1037
    private void close() {
1038
      if (subscription != null) {
1✔
1039
        subscription.close();
1✔
1040
      }
1041
    }
1✔
1042

1043
    static ClusterRefState forCluster(
1044
        AtomicInteger refCount, String name, XdsConfig.Subscription subscription) {
1045
      return new ClusterRefState(refCount, name, null, checkNotNull(subscription, "subscription"));
1✔
1046
    }
1047

1048
    static ClusterRefState forRlsPlugin(
1049
        AtomicInteger refCount,
1050
        RlsPluginConfig rlsPluginConfig) {
1051
      return new ClusterRefState(refCount, null, rlsPluginConfig, null);
1✔
1052
    }
1053
  }
1054

1055
  /** An ObjectPool, except it can throw an exception. */
1056
  private interface XdsClientPool {
1057
    XdsClient getObject() throws XdsInitializationException;
1058

1059
    XdsClient returnObject(XdsClient xdsClient);
1060
  }
1061

1062
  private static final class BootstrappingXdsClientPool implements XdsClientPool {
1063
    private final XdsClientPoolFactory xdsClientPoolFactory;
1064
    private final String target;
1065
    private final @Nullable Map<String, ?> bootstrapOverride;
1066
    private final MetricRecorder metricRecorder;
1067
    private ObjectPool<XdsClient> xdsClientPool;
1068

1069
    BootstrappingXdsClientPool(
1070
        XdsClientPoolFactory xdsClientPoolFactory,
1071
        String target,
1072
        @Nullable Map<String, ?> bootstrapOverride,
1073
        MetricRecorder metricRecorder) {
1✔
1074
      this.xdsClientPoolFactory = checkNotNull(xdsClientPoolFactory, "xdsClientPoolFactory");
1✔
1075
      this.target = checkNotNull(target, "target");
1✔
1076
      this.bootstrapOverride = bootstrapOverride;
1✔
1077
      this.metricRecorder = checkNotNull(metricRecorder, "metricRecorder");
1✔
1078
    }
1✔
1079

1080
    @Override
1081
    public XdsClient getObject() throws XdsInitializationException {
1082
      if (xdsClientPool == null) {
1✔
1083
        BootstrapInfo bootstrapInfo;
1084
        if (bootstrapOverride == null) {
1✔
1085
          bootstrapInfo = GrpcBootstrapperImpl.defaultBootstrap();
×
1086
        } else {
1087
          bootstrapInfo = new GrpcBootstrapperImpl().bootstrap(bootstrapOverride);
1✔
1088
        }
1089
        this.xdsClientPool =
1✔
1090
            xdsClientPoolFactory.getOrCreate(target, bootstrapInfo, metricRecorder);
1✔
1091
      }
1092
      return xdsClientPool.getObject();
1✔
1093
    }
1094

1095
    @Override
1096
    public XdsClient returnObject(XdsClient xdsClient) {
1097
      return xdsClientPool.returnObject(xdsClient);
1✔
1098
    }
1099
  }
1100

1101
  private static final class SupplierXdsClientPool implements XdsClientPool {
1102
    private final Supplier<XdsClient> xdsClientSupplier;
1103

1104
    SupplierXdsClientPool(Supplier<XdsClient> xdsClientSupplier) {
×
1105
      this.xdsClientSupplier = checkNotNull(xdsClientSupplier, "xdsClientSupplier");
×
1106
    }
×
1107

1108
    @Override
1109
    public XdsClient getObject() throws XdsInitializationException {
1110
      XdsClient xdsClient = xdsClientSupplier.get();
×
1111
      if (xdsClient == null) {
×
1112
        throw new XdsInitializationException("Caller failed to initialize XDS_CLIENT_SUPPLIER");
×
1113
      }
1114
      return xdsClient;
×
1115
    }
1116

1117
    @Override
1118
    public XdsClient returnObject(XdsClient xdsClient) {
1119
      return null;
×
1120
    }
1121
  }
1122

1123
  static final class RawMessageClientInterceptor implements ClientInterceptor {
1✔
1124
    private static final MethodDescriptor.Marshaller<InputStream> RAW_MARSHALLER =
1✔
1125
        new MethodDescriptor.Marshaller<InputStream>() {
1✔
1126
          @Override
1127
          public InputStream stream(InputStream value) {
1128
            return value;
1✔
1129
          }
1130

1131
          @Override
1132
          public InputStream parse(InputStream stream) {
1133
            return stream;
1✔
1134
          }
1135
        };
1136

1137
    @Override
1138
    public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(
1139
        final MethodDescriptor<ReqT, RespT> method, CallOptions callOptions, Channel next) {
1140
      MethodDescriptor<InputStream, InputStream> rawMethod =
1✔
1141
          method.toBuilder(RAW_MARSHALLER, RAW_MARSHALLER).build();
1✔
1142
      final ClientCall<InputStream, InputStream> rawCall = next.newCall(rawMethod, callOptions);
1✔
1143
      return new ClientCall<ReqT, RespT>() {
1✔
1144
        @Override
1145
        public void start(final Listener<RespT> responseListener, Metadata headers) {
1146
          rawCall.start(new Listener<InputStream>() {
1✔
1147
            @Override
1148
            public void onHeaders(Metadata headers) {
1149
              responseListener.onHeaders(headers);
1✔
1150
            }
1✔
1151

1152
            @Override
1153
            public void onMessage(InputStream message) {
1154
              responseListener.onMessage(method.getResponseMarshaller().parse(message));
1✔
1155
            }
1✔
1156

1157
            @Override
1158
            public void onClose(Status status, Metadata trailers) {
1159
              responseListener.onClose(status, trailers);
1✔
1160
            }
1✔
1161

1162
            @Override
1163
            public void onReady() {
1164
              responseListener.onReady();
1✔
1165
            }
1✔
1166
          }, headers);
1167
        }
1✔
1168

1169
        @Override
1170
        public void request(int numMessages) {
1171
          rawCall.request(numMessages);
1✔
1172
        }
1✔
1173

1174
        @Override
1175
        public void cancel(@Nullable String message, @Nullable Throwable cause) {
1176
          rawCall.cancel(message, cause);
1✔
1177
        }
1✔
1178

1179
        @Override
1180
        public void halfClose() {
1181
          rawCall.halfClose();
1✔
1182
        }
1✔
1183

1184
        @Override
1185
        public void sendMessage(ReqT message) {
1186
          rawCall.sendMessage(method.getRequestMarshaller().stream(message));
1✔
1187
        }
1✔
1188

1189
        @Override
1190
        public boolean isReady() {
1191
          return rawCall.isReady();
1✔
1192
        }
1193

1194
        @Override
1195
        public void setMessageCompression(boolean enabled) {
1196
          rawCall.setMessageCompression(enabled);
×
1197
        }
×
1198

1199
        @Override
1200
        public Attributes getAttributes() {
1201
          return rawCall.getAttributes();
×
1202
        }
1203
      };
1204
    }
1205
  }
1206
}
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