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

grpc / grpc-java / #19175

25 Apr 2024 10:38PM UTC coverage: 88.068% (-0.02%) from 88.091%
#19175

push

github

ejona86
rls: Fix time handling in CachingRlsLbClient

`getMinEvictionTime()` was fixed to make sure only deltas were used for
comparisons (`a < b` is broken; `a - b < 0` is okay). It had also
returned `0` by default, which was meaningless as there is no epoch for
`System.nanoTime()`. LinkedHashLruCache now passes the current time into
a few more functions since the implementations need it and it was
sometimes already available. This made it easier to make some classes
static.

31206 of 35434 relevant lines covered (88.07%)

0.88 hits per line

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

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

17
package io.grpc.rls;
18

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

22
import com.google.common.annotations.VisibleForTesting;
23
import com.google.common.base.Converter;
24
import com.google.common.base.MoreObjects;
25
import com.google.common.base.MoreObjects.ToStringHelper;
26
import com.google.common.base.Ticker;
27
import com.google.common.util.concurrent.Futures;
28
import com.google.common.util.concurrent.ListenableFuture;
29
import com.google.common.util.concurrent.MoreExecutors;
30
import com.google.common.util.concurrent.SettableFuture;
31
import io.grpc.ChannelLogger;
32
import io.grpc.ChannelLogger.ChannelLogLevel;
33
import io.grpc.ConnectivityState;
34
import io.grpc.LoadBalancer.Helper;
35
import io.grpc.LoadBalancer.PickResult;
36
import io.grpc.LoadBalancer.PickSubchannelArgs;
37
import io.grpc.LoadBalancer.ResolvedAddresses;
38
import io.grpc.LoadBalancer.SubchannelPicker;
39
import io.grpc.ManagedChannel;
40
import io.grpc.ManagedChannelBuilder;
41
import io.grpc.Metadata;
42
import io.grpc.Status;
43
import io.grpc.internal.BackoffPolicy;
44
import io.grpc.internal.ExponentialBackoffPolicy;
45
import io.grpc.lookup.v1.RouteLookupServiceGrpc;
46
import io.grpc.lookup.v1.RouteLookupServiceGrpc.RouteLookupServiceStub;
47
import io.grpc.rls.ChildLoadBalancerHelper.ChildLoadBalancerHelperProvider;
48
import io.grpc.rls.LbPolicyConfiguration.ChildLbStatusListener;
49
import io.grpc.rls.LbPolicyConfiguration.ChildPolicyWrapper;
50
import io.grpc.rls.LbPolicyConfiguration.RefCountedChildPolicyWrapperFactory;
51
import io.grpc.rls.LruCache.EvictionListener;
52
import io.grpc.rls.LruCache.EvictionType;
53
import io.grpc.rls.RlsProtoConverters.RouteLookupResponseConverter;
54
import io.grpc.rls.RlsProtoData.RouteLookupConfig;
55
import io.grpc.rls.RlsProtoData.RouteLookupRequest;
56
import io.grpc.rls.RlsProtoData.RouteLookupResponse;
57
import io.grpc.stub.StreamObserver;
58
import io.grpc.util.ForwardingLoadBalancerHelper;
59
import java.net.URI;
60
import java.net.URISyntaxException;
61
import java.util.HashMap;
62
import java.util.List;
63
import java.util.Map;
64
import java.util.concurrent.Future;
65
import java.util.concurrent.ScheduledExecutorService;
66
import java.util.concurrent.TimeUnit;
67
import javax.annotation.CheckReturnValue;
68
import javax.annotation.Nullable;
69
import javax.annotation.concurrent.GuardedBy;
70
import javax.annotation.concurrent.ThreadSafe;
71

72
/**
73
 * A CachingRlsLbClient is a core implementation of RLS loadbalancer supports dynamic request
74
 * routing by fetching the decision from route lookup server. Every single request is routed by
75
 * the server's decision. To reduce the performance penalty, {@link LruCache} is used.
76
 */
77
@ThreadSafe
78
final class CachingRlsLbClient {
79

80
  private static final Converter<RouteLookupRequest, io.grpc.lookup.v1.RouteLookupRequest>
81
      REQUEST_CONVERTER = new RlsProtoConverters.RouteLookupRequestConverter().reverse();
1✔
82
  private static final Converter<RouteLookupResponse, io.grpc.lookup.v1.RouteLookupResponse>
83
      RESPONSE_CONVERTER = new RouteLookupResponseConverter().reverse();
1✔
84
  public static final long MIN_EVICTION_TIME_DELTA_NANOS = TimeUnit.SECONDS.toNanos(5);
1✔
85
  public static final int BYTES_PER_CHAR = 2;
86
  public static final int STRING_OVERHEAD_BYTES = 38;
87
  /** Minimum bytes for a Java Object. */
88
  public static final int OBJ_OVERHEAD_B = 16;
89

90
  // All cache status changes (pending, backoff, success) must be under this lock
91
  private final Object lock = new Object();
1✔
92
  // LRU cache based on access order (BACKOFF and actual data will be here)
93
  @GuardedBy("lock")
94
  private final RlsAsyncLruCache linkedHashLruCache;
95
  // any RPC on the fly will cached in this map
96
  @GuardedBy("lock")
1✔
97
  private final Map<RouteLookupRequest, PendingCacheEntry> pendingCallCache = new HashMap<>();
98

99
  private final ScheduledExecutorService scheduledExecutorService;
100
  private final Ticker ticker;
101
  private final Throttler throttler;
102

103
  private final LbPolicyConfiguration lbPolicyConfig;
104
  private final BackoffPolicy.Provider backoffProvider;
105
  private final long maxAgeNanos;
106
  private final long staleAgeNanos;
107
  private final long callTimeoutNanos;
108

109
  private final RlsLbHelper helper;
110
  private final ManagedChannel rlsChannel;
111
  private final RouteLookupServiceStub rlsStub;
112
  private final RlsPicker rlsPicker;
113
  private final ResolvedAddressFactory childLbResolvedAddressFactory;
114
  @GuardedBy("lock")
115
  private final RefCountedChildPolicyWrapperFactory refCountedChildPolicyWrapperFactory;
116
  private final ChannelLogger logger;
117

118
  private CachingRlsLbClient(Builder builder) {
1✔
119
    helper = new RlsLbHelper(checkNotNull(builder.helper, "helper"));
1✔
120
    scheduledExecutorService = helper.getScheduledExecutorService();
1✔
121
    lbPolicyConfig = checkNotNull(builder.lbPolicyConfig, "lbPolicyConfig");
1✔
122
    RouteLookupConfig rlsConfig = lbPolicyConfig.getRouteLookupConfig();
1✔
123
    maxAgeNanos = rlsConfig.maxAgeInNanos();
1✔
124
    staleAgeNanos = rlsConfig.staleAgeInNanos();
1✔
125
    callTimeoutNanos = rlsConfig.lookupServiceTimeoutInNanos();
1✔
126
    ticker = checkNotNull(builder.ticker, "ticker");
1✔
127
    throttler = checkNotNull(builder.throttler, "throttler");
1✔
128
    linkedHashLruCache =
1✔
129
        new RlsAsyncLruCache(
130
            rlsConfig.cacheSizeBytes(),
1✔
131
            new AutoCleaningEvictionListener(builder.evictionListener),
1✔
132
            scheduledExecutorService,
133
            ticker,
134
            lock,
135
            helper);
136
    logger = helper.getChannelLogger();
1✔
137
    String serverHost = null;
1✔
138
    try {
139
      serverHost = new URI(null, helper.getAuthority(), null, null, null).getHost();
1✔
140
    } catch (URISyntaxException ignore) {
×
141
      // handled by the following null check
142
    }
1✔
143
    if (serverHost == null) {
1✔
144
      logger.log(
×
145
          ChannelLogLevel.DEBUG, "Can not get hostname from authority: {0}", helper.getAuthority());
×
146
      serverHost = helper.getAuthority();
×
147
    }
148
    RlsRequestFactory requestFactory = new RlsRequestFactory(
1✔
149
        lbPolicyConfig.getRouteLookupConfig(), serverHost);
1✔
150
    rlsPicker = new RlsPicker(requestFactory);
1✔
151
    // It is safe to use helper.getUnsafeChannelCredentials() because the client authenticates the
152
    // RLS server using the same authority as the backends, even though the RLS server’s addresses
153
    // will be looked up differently than the backends; overrideAuthority(helper.getAuthority()) is
154
    // called to impose the authority security restrictions.
155
    ManagedChannelBuilder<?> rlsChannelBuilder = helper.createResolvingOobChannelBuilder(
1✔
156
        rlsConfig.lookupService(), helper.getUnsafeChannelCredentials());
1✔
157
    rlsChannelBuilder.overrideAuthority(helper.getAuthority());
1✔
158
    Map<String, ?> routeLookupChannelServiceConfig =
1✔
159
        lbPolicyConfig.getRouteLookupChannelServiceConfig();
1✔
160
    if (routeLookupChannelServiceConfig != null) {
1✔
161
      logger.log(
1✔
162
          ChannelLogLevel.DEBUG,
163
          "RLS channel service config: {0}",
164
          routeLookupChannelServiceConfig);
165
      rlsChannelBuilder.defaultServiceConfig(routeLookupChannelServiceConfig);
1✔
166
      rlsChannelBuilder.disableServiceConfigLookUp();
1✔
167
    }
168
    rlsChannel = rlsChannelBuilder.build();
1✔
169
    rlsStub = RouteLookupServiceGrpc.newStub(rlsChannel);
1✔
170
    childLbResolvedAddressFactory =
1✔
171
        checkNotNull(builder.resolvedAddressFactory, "resolvedAddressFactory");
1✔
172
    backoffProvider = builder.backoffProvider;
1✔
173
    ChildLoadBalancerHelperProvider childLbHelperProvider =
1✔
174
        new ChildLoadBalancerHelperProvider(helper, new SubchannelStateManagerImpl(), rlsPicker);
175
    refCountedChildPolicyWrapperFactory =
1✔
176
        new RefCountedChildPolicyWrapperFactory(
177
            lbPolicyConfig.getLoadBalancingPolicy(), childLbResolvedAddressFactory,
1✔
178
            childLbHelperProvider,
179
            new BackoffRefreshListener());
180
    logger.log(ChannelLogLevel.DEBUG, "CachingRlsLbClient created");
1✔
181
  }
1✔
182

183
  /**
184
   * Convert the status to UNAVAILBLE and enhance the error message.
185
   * @param status status as provided by server
186
   * @param serverName Used for error description
187
   * @return Transformed status
188
   */
189
  static Status convertRlsServerStatus(Status status, String serverName) {
190
    return Status.UNAVAILABLE.withCause(status.getCause()).withDescription(
1✔
191
        String.format("Unable to retrieve RLS targets from RLS server %s.  "
1✔
192
                + "RLS server returned: %s: %s",
193
            serverName, status.getCode(), status.getDescription()));
1✔
194
  }
195

196
  /** Populates async cache entry for new request. */
197
  @GuardedBy("lock")
198
  private CachedRouteLookupResponse asyncRlsCall(
199
      RouteLookupRequest request, @Nullable BackoffPolicy backoffPolicy) {
200
    logger.log(ChannelLogLevel.DEBUG, "Making an async call to RLS");
1✔
201
    if (throttler.shouldThrottle()) {
1✔
202
      logger.log(ChannelLogLevel.DEBUG, "Request is throttled");
1✔
203
      // Cache updated, but no need to call updateBalancingState because no RPCs were queued waiting
204
      // on this result
205
      return CachedRouteLookupResponse.backoffEntry(createBackOffEntry(
1✔
206
          request, Status.RESOURCE_EXHAUSTED.withDescription("RLS throttled"), backoffPolicy));
1✔
207
    }
208
    final SettableFuture<RouteLookupResponse> response = SettableFuture.create();
1✔
209
    io.grpc.lookup.v1.RouteLookupRequest routeLookupRequest = REQUEST_CONVERTER.convert(request);
1✔
210
    logger.log(ChannelLogLevel.DEBUG, "Sending RouteLookupRequest: {0}", routeLookupRequest);
1✔
211
    rlsStub.withDeadlineAfter(callTimeoutNanos, TimeUnit.NANOSECONDS)
1✔
212
        .routeLookup(
1✔
213
            routeLookupRequest,
214
            new StreamObserver<io.grpc.lookup.v1.RouteLookupResponse>() {
1✔
215
              @Override
216
              public void onNext(io.grpc.lookup.v1.RouteLookupResponse value) {
217
                logger.log(ChannelLogLevel.DEBUG, "Received RouteLookupResponse: {0}", value);
1✔
218
                response.set(RESPONSE_CONVERTER.reverse().convert(value));
1✔
219
              }
1✔
220

221
              @Override
222
              public void onError(Throwable t) {
223
                logger.log(ChannelLogLevel.DEBUG, "Error looking up route:", t);
1✔
224
                response.setException(t);
1✔
225
                throttler.registerBackendResponse(true);
1✔
226
              }
1✔
227

228
              @Override
229
              public void onCompleted() {
230
                logger.log(ChannelLogLevel.DEBUG, "routeLookup call completed");
1✔
231
                throttler.registerBackendResponse(false);
1✔
232
              }
1✔
233
            });
234
    return CachedRouteLookupResponse.pendingResponse(
1✔
235
        createPendingEntry(request, response, backoffPolicy));
1✔
236
  }
237

238
  /**
239
   * Returns async response of the {@code request}. The returned value can be in 3 different states;
240
   * cached, pending and backed-off due to error. The result remains same even if the status is
241
   * changed after the return.
242
   */
243
  @CheckReturnValue
244
  final CachedRouteLookupResponse get(final RouteLookupRequest request) {
245
    logger.log(ChannelLogLevel.DEBUG, "Acquiring lock to get cached entry");
1✔
246
    synchronized (lock) {
1✔
247
      logger.log(ChannelLogLevel.DEBUG, "Acquired lock to get cached entry");
1✔
248
      final CacheEntry cacheEntry;
249
      cacheEntry = linkedHashLruCache.read(request);
1✔
250
      if (cacheEntry == null) {
1✔
251
        logger.log(ChannelLogLevel.DEBUG, "No cache entry found, making a new lrs request");
1✔
252
        PendingCacheEntry pendingEntry = pendingCallCache.get(request);
1✔
253
        if (pendingEntry != null) {
1✔
254
          return CachedRouteLookupResponse.pendingResponse(pendingEntry);
1✔
255
        }
256
        return asyncRlsCall(request, /* backoffPolicy= */ null);
1✔
257
      }
258

259
      if (cacheEntry instanceof DataCacheEntry) {
1✔
260
        // cache hit, initiate async-refresh if entry is staled
261
        logger.log(ChannelLogLevel.DEBUG, "Cache hit for the request");
1✔
262
        DataCacheEntry dataEntry = ((DataCacheEntry) cacheEntry);
1✔
263
        if (dataEntry.isStaled(ticker.read())) {
1✔
264
          logger.log(ChannelLogLevel.DEBUG, "Cache entry is stale");
1✔
265
          dataEntry.maybeRefresh();
1✔
266
        }
267
        return CachedRouteLookupResponse.dataEntry((DataCacheEntry) cacheEntry);
1✔
268
      }
269
      logger.log(ChannelLogLevel.DEBUG, "Cache hit for a backup entry");
1✔
270
      return CachedRouteLookupResponse.backoffEntry((BackoffCacheEntry) cacheEntry);
1✔
271
    }
272
  }
273

274
  /** Performs any pending maintenance operations needed by the cache. */
275
  void close() {
276
    logger.log(ChannelLogLevel.DEBUG, "CachingRlsLbClient closed");
1✔
277
    synchronized (lock) {
1✔
278
      // all childPolicyWrapper will be returned via AutoCleaningEvictionListener
279
      linkedHashLruCache.close();
1✔
280
      // TODO(creamsoup) maybe cancel all pending requests
281
      pendingCallCache.clear();
1✔
282
      rlsChannel.shutdownNow();
1✔
283
      rlsPicker.close();
1✔
284
    }
1✔
285
  }
1✔
286

287
  void requestConnection() {
288
    rlsChannel.getState(true);
×
289
  }
×
290

291
  @GuardedBy("lock")
292
  private PendingCacheEntry createPendingEntry(
293
      RouteLookupRequest request,
294
      ListenableFuture<RouteLookupResponse> pendingCall,
295
      @Nullable BackoffPolicy backoffPolicy) {
296
    PendingCacheEntry entry = new PendingCacheEntry(request, pendingCall, backoffPolicy);
1✔
297
    // Add the entry to the map before adding the Listener, because the listener removes the
298
    // entry from the map
299
    pendingCallCache.put(request, entry);
1✔
300
    // Beware that the listener can run immediately on the current thread
301
    pendingCall.addListener(() -> pendingRpcComplete(entry), MoreExecutors.directExecutor());
1✔
302
    return entry;
1✔
303
  }
304

305
  private void pendingRpcComplete(PendingCacheEntry entry) {
306
    synchronized (lock) {
1✔
307
      boolean clientClosed = pendingCallCache.remove(entry.request) == null;
1✔
308
      if (clientClosed) {
1✔
309
        return;
1✔
310
      }
311

312
      try {
313
        createDataEntry(entry.request, Futures.getDone(entry.pendingCall));
1✔
314
        // Cache updated. DataCacheEntry constructor indirectly calls updateBalancingState() to
315
        // reattempt picks when the child LB is done connecting
316
      } catch (Exception e) {
1✔
317
        createBackOffEntry(entry.request, Status.fromThrowable(e), entry.backoffPolicy);
1✔
318
        // Cache updated. updateBalancingState() to reattempt picks
319
        helper.propagateRlsError();
1✔
320
      }
1✔
321
    }
1✔
322
  }
1✔
323

324
  @GuardedBy("lock")
325
  private DataCacheEntry createDataEntry(
326
      RouteLookupRequest request, RouteLookupResponse routeLookupResponse) {
327
    logger.log(
1✔
328
        ChannelLogLevel.DEBUG,
329
        "Transition to data cache: routeLookupResponse={0}",
330
        routeLookupResponse);
331
    DataCacheEntry entry = new DataCacheEntry(request, routeLookupResponse);
1✔
332
    // Constructor for DataCacheEntry causes updateBalancingState, but the picks can't happen until
333
    // this cache update because the lock is held
334
    linkedHashLruCache.cacheAndClean(request, entry);
1✔
335
    return entry;
1✔
336
  }
337

338
  @GuardedBy("lock")
339
  private BackoffCacheEntry createBackOffEntry(
340
      RouteLookupRequest request, Status status, @Nullable BackoffPolicy backoffPolicy) {
341
    logger.log(ChannelLogLevel.DEBUG, "Transition to back off: status={0}", status);
1✔
342
    if (backoffPolicy == null) {
1✔
343
      backoffPolicy = backoffProvider.get();
1✔
344
    }
345
    long delayNanos = backoffPolicy.nextBackoffNanos();
1✔
346
    BackoffCacheEntry entry = new BackoffCacheEntry(request, status, backoffPolicy);
1✔
347
    // Lock is held, so the task can't execute before the assignment
348
    entry.scheduledFuture = scheduledExecutorService.schedule(
1✔
349
        () -> refreshBackoffEntry(entry), delayNanos, TimeUnit.NANOSECONDS);
1✔
350
    linkedHashLruCache.cacheAndClean(request, entry);
1✔
351
    logger.log(ChannelLogLevel.DEBUG, "BackoffCacheEntry created with a delay of {0} nanos",
1✔
352
        delayNanos);
1✔
353
    return entry;
1✔
354
  }
355

356
  private void refreshBackoffEntry(BackoffCacheEntry entry) {
357
    synchronized (lock) {
1✔
358
      // This checks whether the task has been cancelled and prevents a second execution.
359
      if (!entry.scheduledFuture.cancel(false)) {
1✔
360
        // Future was previously cancelled
361
        return;
×
362
      }
363
      logger.log(ChannelLogLevel.DEBUG, "Calling RLS for transition to pending");
1✔
364
      linkedHashLruCache.invalidate(entry.request);
1✔
365
      asyncRlsCall(entry.request, entry.backoffPolicy);
1✔
366
    }
1✔
367
  }
1✔
368

369
  private static final class RlsLbHelper extends ForwardingLoadBalancerHelper {
370

371
    final Helper helper;
372
    private ConnectivityState state;
373
    private SubchannelPicker picker;
374

375
    RlsLbHelper(Helper helper) {
1✔
376
      this.helper = helper;
1✔
377
    }
1✔
378

379
    @Override
380
    protected Helper delegate() {
381
      return helper;
1✔
382
    }
383

384
    @Override
385
    public void updateBalancingState(ConnectivityState newState, SubchannelPicker newPicker) {
386
      state = newState;
1✔
387
      picker = newPicker;
1✔
388
      super.updateBalancingState(newState, newPicker);
1✔
389
    }
1✔
390

391
    void propagateRlsError() {
392
      getSynchronizationContext().execute(new Runnable() {
1✔
393
        @Override
394
        public void run() {
395
          if (picker != null) {
1✔
396
            // Refresh the channel state and let pending RPCs reprocess the picker.
397
            updateBalancingState(state, picker);
1✔
398
          }
399
        }
1✔
400
      });
401
    }
1✔
402

403
    void triggerPendingRpcProcessing() {
404
      helper.getSynchronizationContext().execute(
×
405
          () -> super.updateBalancingState(state, picker));
×
406
    }
×
407
  }
408

409
  /**
410
   * Viewer class for cached {@link RouteLookupResponse} and associated {@link ChildPolicyWrapper}.
411
   */
412
  static final class CachedRouteLookupResponse {
413
    // Should only have 1 of following 3 cache entries
414
    @Nullable
415
    private final DataCacheEntry dataCacheEntry;
416
    @Nullable
417
    private final PendingCacheEntry pendingCacheEntry;
418
    @Nullable
419
    private final BackoffCacheEntry backoffCacheEntry;
420

421
    CachedRouteLookupResponse(
422
        DataCacheEntry dataCacheEntry,
423
        PendingCacheEntry pendingCacheEntry,
424
        BackoffCacheEntry backoffCacheEntry) {
1✔
425
      this.dataCacheEntry = dataCacheEntry;
1✔
426
      this.pendingCacheEntry = pendingCacheEntry;
1✔
427
      this.backoffCacheEntry = backoffCacheEntry;
1✔
428
      checkState((dataCacheEntry != null ^ pendingCacheEntry != null ^ backoffCacheEntry != null)
1✔
429
          && !(dataCacheEntry != null && pendingCacheEntry != null && backoffCacheEntry != null),
430
          "Expected only 1 cache entry value provided");
431
    }
1✔
432

433
    static CachedRouteLookupResponse pendingResponse(PendingCacheEntry pendingEntry) {
434
      return new CachedRouteLookupResponse(null, pendingEntry, null);
1✔
435
    }
436

437
    static CachedRouteLookupResponse backoffEntry(BackoffCacheEntry backoffEntry) {
438
      return new CachedRouteLookupResponse(null, null, backoffEntry);
1✔
439
    }
440

441
    static CachedRouteLookupResponse dataEntry(DataCacheEntry dataEntry) {
442
      return new CachedRouteLookupResponse(dataEntry, null, null);
1✔
443
    }
444

445
    boolean hasData() {
446
      return dataCacheEntry != null;
1✔
447
    }
448

449
    @Nullable
450
    ChildPolicyWrapper getChildPolicyWrapper() {
451
      if (!hasData()) {
1✔
452
        return null;
×
453
      }
454
      return dataCacheEntry.getChildPolicyWrapper();
1✔
455
    }
456

457
    @VisibleForTesting
458
    @Nullable
459
    ChildPolicyWrapper getChildPolicyWrapper(String target) {
460
      if (!hasData()) {
1✔
461
        return null;
×
462
      }
463
      return dataCacheEntry.getChildPolicyWrapper(target);
1✔
464
    }
465

466
    @Nullable
467
    String getHeaderData() {
468
      if (!hasData()) {
1✔
469
        return null;
1✔
470
      }
471
      return dataCacheEntry.getHeaderData();
1✔
472
    }
473

474
    boolean hasError() {
475
      return backoffCacheEntry != null;
1✔
476
    }
477

478
    boolean isPending() {
479
      return pendingCacheEntry != null;
1✔
480
    }
481

482
    @Nullable
483
    Status getStatus() {
484
      if (!hasError()) {
×
485
        return null;
×
486
      }
487
      return backoffCacheEntry.getStatus();
×
488
    }
489

490
    @Override
491
    public String toString() {
492
      ToStringHelper toStringHelper = MoreObjects.toStringHelper(this);
×
493
      if (dataCacheEntry != null) {
×
494
        toStringHelper.add("dataCacheEntry", dataCacheEntry);
×
495
      }
496
      if (pendingCacheEntry != null) {
×
497
        toStringHelper.add("pendingCacheEntry", pendingCacheEntry);
×
498
      }
499
      if (backoffCacheEntry != null) {
×
500
        toStringHelper.add("backoffCacheEntry", backoffCacheEntry);
×
501
      }
502
      return toStringHelper.toString();
×
503
    }
504
  }
505

506
  /** A pending cache entry when the async RouteLookup RPC is still on the fly. */
507
  static final class PendingCacheEntry {
508
    private final ListenableFuture<RouteLookupResponse> pendingCall;
509
    private final RouteLookupRequest request;
510
    @Nullable
511
    private final BackoffPolicy backoffPolicy;
512

513
    PendingCacheEntry(
514
        RouteLookupRequest request,
515
        ListenableFuture<RouteLookupResponse> pendingCall,
516
        @Nullable BackoffPolicy backoffPolicy) {
1✔
517
      this.request = checkNotNull(request, "request");
1✔
518
      this.pendingCall = checkNotNull(pendingCall, "pendingCall");
1✔
519
      this.backoffPolicy = backoffPolicy;
1✔
520
    }
1✔
521

522
    @Override
523
    public String toString() {
524
      return MoreObjects.toStringHelper(this)
×
525
          .add("request", request)
×
526
          .toString();
×
527
    }
528
  }
529

530
  /** Common cache entry data for {@link RlsAsyncLruCache}. */
531
  abstract static class CacheEntry {
532

533
    protected final RouteLookupRequest request;
534

535
    CacheEntry(RouteLookupRequest request) {
1✔
536
      this.request = checkNotNull(request, "request");
1✔
537
    }
1✔
538

539
    abstract int getSizeBytes();
540

541
    abstract boolean isExpired(long now);
542

543
    abstract void cleanup();
544

545
    protected boolean isOldEnoughToBeEvicted(long now) {
546
      return true;
×
547
    }
548
  }
549

550
  /** Implementation of {@link CacheEntry} contains valid data. */
551
  final class DataCacheEntry extends CacheEntry {
552
    private final RouteLookupResponse response;
553
    private final long minEvictionTime;
554
    private final long expireTime;
555
    private final long staleTime;
556
    private final List<ChildPolicyWrapper> childPolicyWrappers;
557

558
    // GuardedBy CachingRlsLbClient.lock
559
    DataCacheEntry(RouteLookupRequest request, final RouteLookupResponse response) {
1✔
560
      super(request);
1✔
561
      this.response = checkNotNull(response, "response");
1✔
562
      checkState(!response.targets().isEmpty(), "No targets returned by RLS");
1✔
563
      childPolicyWrappers =
1✔
564
          refCountedChildPolicyWrapperFactory
1✔
565
              .createOrGet(response.targets());
1✔
566
      long now = ticker.read();
1✔
567
      minEvictionTime = now + MIN_EVICTION_TIME_DELTA_NANOS;
1✔
568
      expireTime = now + maxAgeNanos;
1✔
569
      staleTime = now + staleAgeNanos;
1✔
570
    }
1✔
571

572
    /**
573
     * Refreshes cache entry by creating {@link PendingCacheEntry}. When the {@code
574
     * PendingCacheEntry} received data from RLS server, it will replace the data entry if valid
575
     * data still exists. Flow looks like following.
576
     *
577
     * <pre>
578
     * Timeline                       | async refresh
579
     *                                V put new cache (entry2)
580
     * entry1: Pending | hasValue | staled  |
581
     * entry2:                        | OV* | pending | hasValue | staled |
582
     *
583
     * OV: old value
584
     * </pre>
585
     */
586
    void maybeRefresh() {
587
      synchronized (lock) { // Lock is already held, but ErrorProne can't tell
1✔
588
        if (pendingCallCache.containsKey(request)) {
1✔
589
          // pending already requested
590
          logger.log(ChannelLogLevel.DEBUG,
×
591
              "A pending refresh request already created, no need to proceed with refresh");
592
          return;
×
593
        }
594
        asyncRlsCall(request, /* backoffPolicy= */ null);
1✔
595
      }
1✔
596
    }
1✔
597

598
    @VisibleForTesting
599
    ChildPolicyWrapper getChildPolicyWrapper(String target) {
600
      for (ChildPolicyWrapper childPolicyWrapper : childPolicyWrappers) {
1✔
601
        if (childPolicyWrapper.getTarget().equals(target)) {
1✔
602
          return childPolicyWrapper;
1✔
603
        }
604
      }
1✔
605

606
      throw new RuntimeException("Target not found:" + target);
×
607
    }
608

609
    @Nullable
610
    ChildPolicyWrapper getChildPolicyWrapper() {
611
      for (ChildPolicyWrapper childPolicyWrapper : childPolicyWrappers) {
1✔
612
        if (childPolicyWrapper.getState() != ConnectivityState.TRANSIENT_FAILURE) {
1✔
613
          return childPolicyWrapper;
1✔
614
        }
615
      }
1✔
616
      return childPolicyWrappers.get(0);
1✔
617
    }
618

619
    String getHeaderData() {
620
      return response.getHeaderData();
1✔
621
    }
622

623
    // Assume UTF-16 (2 bytes) and overhead of a String object is 38 bytes
624
    int calcStringSize(String target) {
625
      return target.length() * BYTES_PER_CHAR + STRING_OVERHEAD_BYTES;
1✔
626
    }
627

628
    @Override
629
    int getSizeBytes() {
630
      int targetSize = 0;
1✔
631
      for (String target : response.targets()) {
1✔
632
        targetSize += calcStringSize(target);
1✔
633
      }
1✔
634
      return targetSize + calcStringSize(response.getHeaderData()) + OBJ_OVERHEAD_B // response size
1✔
635
          + Long.SIZE * 2 + OBJ_OVERHEAD_B; // Other fields
636
    }
637

638
    @Override
639
    boolean isExpired(long now) {
640
      return expireTime - now <= 0;
1✔
641
    }
642

643
    boolean isStaled(long now) {
644
      return staleTime - now <= 0;
1✔
645
    }
646

647
    @Override
648
    protected boolean isOldEnoughToBeEvicted(long now) {
649
      return minEvictionTime - now <= 0;
×
650
    }
651

652
    @Override
653
    void cleanup() {
654
      synchronized (lock) {
1✔
655
        for (ChildPolicyWrapper policyWrapper : childPolicyWrappers) {
1✔
656
          refCountedChildPolicyWrapperFactory.release(policyWrapper);
1✔
657
        }
1✔
658
      }
1✔
659
    }
1✔
660

661
    @Override
662
    public String toString() {
663
      return MoreObjects.toStringHelper(this)
×
664
          .add("request", request)
×
665
          .add("response", response)
×
666
          .add("expireTime", expireTime)
×
667
          .add("staleTime", staleTime)
×
668
          .add("childPolicyWrappers", childPolicyWrappers)
×
669
          .toString();
×
670
    }
671
  }
672

673
  /**
674
   * Implementation of {@link CacheEntry} contains error. This entry will transition to pending
675
   * status when the backoff time is expired.
676
   */
677
  private static final class BackoffCacheEntry extends CacheEntry {
678

679
    private final Status status;
680
    private final BackoffPolicy backoffPolicy;
681
    private Future<?> scheduledFuture;
682

683
    BackoffCacheEntry(RouteLookupRequest request, Status status, BackoffPolicy backoffPolicy) {
684
      super(request);
1✔
685
      this.status = checkNotNull(status, "status");
1✔
686
      this.backoffPolicy = checkNotNull(backoffPolicy, "backoffPolicy");
1✔
687
    }
1✔
688

689
    Status getStatus() {
690
      return status;
×
691
    }
692

693
    @Override
694
    int getSizeBytes() {
695
      return OBJ_OVERHEAD_B * 3 + Long.SIZE + 8; // 3 java objects, 1 long and a boolean
1✔
696
    }
697

698
    @Override
699
    boolean isExpired(long now) {
700
      return scheduledFuture.isDone();
1✔
701
    }
702

703
    @Override
704
    void cleanup() {
705
      scheduledFuture.cancel(false);
1✔
706
    }
1✔
707

708
    @Override
709
    public String toString() {
710
      return MoreObjects.toStringHelper(this)
×
711
          .add("request", request)
×
712
          .add("status", status)
×
713
          .toString();
×
714
    }
715
  }
716

717
  /** Returns a Builder for {@link CachingRlsLbClient}. */
718
  static Builder newBuilder() {
719
    return new Builder();
1✔
720
  }
721

722
  /** A Builder for {@link CachingRlsLbClient}. */
723
  static final class Builder {
1✔
724

725
    private Helper helper;
726
    private LbPolicyConfiguration lbPolicyConfig;
727
    private Throttler throttler = new HappyThrottler();
1✔
728
    private ResolvedAddressFactory resolvedAddressFactory;
729
    private Ticker ticker = Ticker.systemTicker();
1✔
730
    private EvictionListener<RouteLookupRequest, CacheEntry> evictionListener;
731
    private BackoffPolicy.Provider backoffProvider = new ExponentialBackoffPolicy.Provider();
1✔
732

733
    Builder setHelper(Helper helper) {
734
      this.helper = checkNotNull(helper, "helper");
1✔
735
      return this;
1✔
736
    }
737

738
    Builder setLbPolicyConfig(LbPolicyConfiguration lbPolicyConfig) {
739
      this.lbPolicyConfig = checkNotNull(lbPolicyConfig, "lbPolicyConfig");
1✔
740
      return this;
1✔
741
    }
742

743
    Builder setThrottler(Throttler throttler) {
744
      this.throttler = checkNotNull(throttler, "throttler");
1✔
745
      return this;
1✔
746
    }
747

748
    /**
749
     * Sets a factory to create {@link ResolvedAddresses} for child load balancer.
750
     */
751
    Builder setResolvedAddressesFactory(
752
        ResolvedAddressFactory resolvedAddressFactory) {
753
      this.resolvedAddressFactory =
1✔
754
          checkNotNull(resolvedAddressFactory, "resolvedAddressFactory");
1✔
755
      return this;
1✔
756
    }
757

758
    Builder setTicker(Ticker ticker) {
759
      this.ticker = checkNotNull(ticker, "ticker");
1✔
760
      return this;
1✔
761
    }
762

763
    Builder setEvictionListener(
764
        @Nullable EvictionListener<RouteLookupRequest, CacheEntry> evictionListener) {
765
      this.evictionListener = evictionListener;
1✔
766
      return this;
1✔
767
    }
768

769
    Builder setBackoffProvider(BackoffPolicy.Provider provider) {
770
      this.backoffProvider = checkNotNull(provider, "provider");
1✔
771
      return this;
1✔
772
    }
773

774
    CachingRlsLbClient build() {
775
      CachingRlsLbClient client = new CachingRlsLbClient(this);
1✔
776
      helper.updateBalancingState(ConnectivityState.CONNECTING, client.rlsPicker);
1✔
777
      return client;
1✔
778
    }
779
  }
780

781
  /**
782
   * When any {@link CacheEntry} is evicted from {@link LruCache}, it performs {@link
783
   * CacheEntry#cleanup()} after original {@link EvictionListener} is finished.
784
   */
785
  private static final class AutoCleaningEvictionListener
786
      implements EvictionListener<RouteLookupRequest, CacheEntry> {
787

788
    private final EvictionListener<RouteLookupRequest, CacheEntry> delegate;
789

790
    AutoCleaningEvictionListener(
791
        @Nullable EvictionListener<RouteLookupRequest, CacheEntry> delegate) {
1✔
792
      this.delegate = delegate;
1✔
793
    }
1✔
794

795
    @Override
796
    public void onEviction(RouteLookupRequest key, CacheEntry value, EvictionType cause) {
797
      if (delegate != null) {
1✔
798
        delegate.onEviction(key, value, cause);
1✔
799
      }
800
      // performs cleanup after delegation
801
      value.cleanup();
1✔
802
    }
1✔
803
  }
804

805
  /** A Throttler never throttles. */
806
  private static final class HappyThrottler implements Throttler {
807

808
    @Override
809
    public boolean shouldThrottle() {
810
      return false;
×
811
    }
812

813
    @Override
814
    public void registerBackendResponse(boolean throttled) {
815
      // no-op
816
    }
×
817
  }
818

819
  /** Implementation of {@link LinkedHashLruCache} for RLS. */
820
  private static final class RlsAsyncLruCache
821
      extends LinkedHashLruCache<RouteLookupRequest, CacheEntry> {
822
    private final RlsLbHelper helper;
823

824
    RlsAsyncLruCache(long maxEstimatedSizeBytes,
825
        @Nullable EvictionListener<RouteLookupRequest, CacheEntry> evictionListener,
826
        ScheduledExecutorService ses, Ticker ticker, Object lock, RlsLbHelper helper) {
827
      super(
1✔
828
          maxEstimatedSizeBytes,
829
          evictionListener,
830
          1,
831
          TimeUnit.MINUTES,
832
          ses,
833
          ticker,
834
          lock);
835
      this.helper = checkNotNull(helper, "helper");
1✔
836
    }
1✔
837

838
    @Override
839
    protected boolean isExpired(RouteLookupRequest key, CacheEntry value, long nowNanos) {
840
      return value.isExpired(nowNanos);
1✔
841
    }
842

843
    @Override
844
    protected int estimateSizeOf(RouteLookupRequest key, CacheEntry value) {
845
      return value.getSizeBytes();
1✔
846
    }
847

848
    @Override
849
    protected boolean shouldInvalidateEldestEntry(
850
        RouteLookupRequest eldestKey, CacheEntry eldestValue, long now) {
851
      if (!eldestValue.isOldEnoughToBeEvicted(now)) {
×
852
        return false;
×
853
      }
854

855
      // eldest entry should be evicted if size limit exceeded
856
      return this.estimatedSizeBytes() > this.estimatedMaxSizeBytes();
×
857
    }
858

859
    public CacheEntry cacheAndClean(RouteLookupRequest key, CacheEntry value) {
860
      CacheEntry newEntry = cache(key, value);
1✔
861

862
      // force cleanup if new entry pushed cache over max size (in bytes)
863
      if (fitToLimit()) {
1✔
864
        helper.triggerPendingRpcProcessing();
×
865
      }
866
      return newEntry;
1✔
867
    }
868
  }
869

870
  /**
871
   * LbStatusListener refreshes {@link BackoffCacheEntry} when lb state is changed to {@link
872
   * ConnectivityState#READY} from {@link ConnectivityState#TRANSIENT_FAILURE}.
873
   */
874
  private final class BackoffRefreshListener implements ChildLbStatusListener {
1✔
875

876
    @Nullable
1✔
877
    private ConnectivityState prevState = null;
878

879
    @Override
880
    public void onStatusChanged(ConnectivityState newState) {
881
      logger.log(ChannelLogLevel.DEBUG, "LB status changed to: {0}", newState);
1✔
882
      if (prevState == ConnectivityState.TRANSIENT_FAILURE
1✔
883
          && newState == ConnectivityState.READY) {
884
        logger.log(ChannelLogLevel.DEBUG, "Transitioning from TRANSIENT_FAILURE to READY");
1✔
885
        logger.log(ChannelLogLevel.DEBUG, "Acquiring lock force refresh backoff cache entries");
1✔
886
        synchronized (lock) {
1✔
887
          logger.log(ChannelLogLevel.DEBUG, "Lock acquired for refreshing backoff cache entries");
1✔
888
          for (CacheEntry value : linkedHashLruCache.values()) {
1✔
889
            if (value instanceof BackoffCacheEntry) {
1✔
890
              refreshBackoffEntry((BackoffCacheEntry) value);
×
891
            }
892
          }
1✔
893
        }
1✔
894
      }
895
      prevState = newState;
1✔
896
    }
1✔
897
  }
898

899
  /** A header will be added when RLS server respond with additional header data. */
900
  @VisibleForTesting
901
  static final Metadata.Key<String> RLS_DATA_KEY =
1✔
902
      Metadata.Key.of("X-Google-RLS-Data", Metadata.ASCII_STRING_MARSHALLER);
1✔
903

904
  final class RlsPicker extends SubchannelPicker {
905

906
    private final RlsRequestFactory requestFactory;
907

908
    RlsPicker(RlsRequestFactory requestFactory) {
1✔
909
      this.requestFactory = checkNotNull(requestFactory, "requestFactory");
1✔
910
    }
1✔
911

912
    @Override
913
    public PickResult pickSubchannel(PickSubchannelArgs args) {
914
      String serviceName = args.getMethodDescriptor().getServiceName();
1✔
915
      String methodName = args.getMethodDescriptor().getBareMethodName();
1✔
916
      RouteLookupRequest request =
1✔
917
          requestFactory.create(serviceName, methodName, args.getHeaders());
1✔
918
      final CachedRouteLookupResponse response = CachingRlsLbClient.this.get(request);
1✔
919
      logger.log(ChannelLogLevel.DEBUG,
1✔
920
          "Got route lookup cache entry for service={0}, method={1}, headers={2}:\n {3}",
921
          new Object[]{serviceName, methodName, args.getHeaders(), response});
1✔
922

923
      if (response.getHeaderData() != null && !response.getHeaderData().isEmpty()) {
1✔
924
        logger.log(ChannelLogLevel.DEBUG, "Updating LRS metadata from the LRS response headers");
1✔
925
        Metadata headers = args.getHeaders();
1✔
926
        headers.discardAll(RLS_DATA_KEY);
1✔
927
        headers.put(RLS_DATA_KEY, response.getHeaderData());
1✔
928
      }
929
      String defaultTarget = lbPolicyConfig.getRouteLookupConfig().defaultTarget();
1✔
930
      logger.log(ChannelLogLevel.DEBUG, "defaultTarget = {0}", defaultTarget);
1✔
931
      boolean hasFallback = defaultTarget != null && !defaultTarget.isEmpty();
1✔
932
      if (response.hasData()) {
1✔
933
        logger.log(ChannelLogLevel.DEBUG, "LRS response has data, proceed with selecting a picker");
1✔
934
        ChildPolicyWrapper childPolicyWrapper = response.getChildPolicyWrapper();
1✔
935
        SubchannelPicker picker =
936
            (childPolicyWrapper != null) ? childPolicyWrapper.getPicker() : null;
1✔
937
        if (picker == null) {
1✔
938
          logger.log(ChannelLogLevel.DEBUG,
×
939
              "Child policy wrapper didn't return a picker, returning PickResult with no results");
940
          return PickResult.withNoResult();
×
941
        }
942
        // Happy path
943
        logger.log(ChannelLogLevel.DEBUG, "Returning PickResult");
1✔
944
        return picker.pickSubchannel(args);
1✔
945
      } else if (response.hasError()) {
1✔
946
        logger.log(ChannelLogLevel.DEBUG, "RLS response has errors");
1✔
947
        if (hasFallback) {
1✔
948
          logger.log(ChannelLogLevel.DEBUG, "Using RLS fallback");
1✔
949
          return useFallback(args);
1✔
950
        }
951
        logger.log(ChannelLogLevel.DEBUG, "No RLS fallback, returning PickResult with an error");
×
952
        return PickResult.withError(
×
953
            convertRlsServerStatus(response.getStatus(),
×
954
                lbPolicyConfig.getRouteLookupConfig().lookupService()));
×
955
      } else {
956
        logger.log(ChannelLogLevel.DEBUG,
1✔
957
            "RLS response had no data, return a PickResult with no data");
958
        return PickResult.withNoResult();
1✔
959
      }
960
    }
961

962
    private ChildPolicyWrapper fallbackChildPolicyWrapper;
963

964
    /** Uses Subchannel connected to default target. */
965
    private PickResult useFallback(PickSubchannelArgs args) {
966
      // TODO(creamsoup) wait until lb is ready
967
      startFallbackChildPolicy();
1✔
968
      SubchannelPicker picker = fallbackChildPolicyWrapper.getPicker();
1✔
969
      if (picker == null) {
1✔
970
        return PickResult.withNoResult();
×
971
      }
972
      return picker.pickSubchannel(args);
1✔
973
    }
974

975
    private void startFallbackChildPolicy() {
976
      String defaultTarget = lbPolicyConfig.getRouteLookupConfig().defaultTarget();
1✔
977
      logger.log(ChannelLogLevel.DEBUG, "starting fallback to {0}", defaultTarget);
1✔
978
      logger.log(ChannelLogLevel.DEBUG, "Acquiring lock to start fallback child policy");
1✔
979
      synchronized (lock) {
1✔
980
        logger.log(ChannelLogLevel.DEBUG, "Acquired lock for starting fallback child policy");
1✔
981
        if (fallbackChildPolicyWrapper != null) {
1✔
982
          return;
1✔
983
        }
984
        fallbackChildPolicyWrapper = refCountedChildPolicyWrapperFactory.createOrGet(defaultTarget);
1✔
985
      }
1✔
986
    }
1✔
987

988
    // GuardedBy CachingRlsLbClient.lock
989
    void close() {
990
      synchronized (lock) { // Lock is already held, but ErrorProne can't tell
1✔
991
        logger.log(ChannelLogLevel.DEBUG, "Closing RLS picker");
1✔
992
        if (fallbackChildPolicyWrapper != null) {
1✔
993
          refCountedChildPolicyWrapperFactory.release(fallbackChildPolicyWrapper);
1✔
994
        }
995
      }
1✔
996
    }
1✔
997

998
    @Override
999
    public String toString() {
1000
      return MoreObjects.toStringHelper(this)
×
1001
          .add("target", lbPolicyConfig.getRouteLookupConfig().lookupService())
×
1002
          .toString();
×
1003
    }
1004
  }
1005

1006
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc