diff --git a/autosharding/BUILD.bazel b/autosharding/BUILD.bazel index 4877451e2dc..099dec8711a 100644 --- a/autosharding/BUILD.bazel +++ b/autosharding/BUILD.bazel @@ -9,9 +9,18 @@ java_library( srcs = glob([ "src/main/java/io/grpc/autosharding/*.java", ]), + resources = glob([ + "src/main/resources/**", + ]), visibility = ["//visibility:public"], deps = [ + ":autosharding_java_grpc", + ":autosharding_java_proto", "//api", + "//core:internal", + "//stub", + "//util", + "@com_google_protobuf//:protobuf_java", artifact("com.google.code.findbugs:jsr305"), artifact("com.google.guava:guava"), ], diff --git a/autosharding/build.gradle b/autosharding/build.gradle index 8c88f6d0e64..94565ef205c 100644 --- a/autosharding/build.gradle +++ b/autosharding/build.gradle @@ -60,6 +60,9 @@ tasks.named("javadoc").configure { exclude 'io/grpc/autosharding/*Provider.java' exclude 'io/grpc/autosharding/internal/**' exclude 'io/grpc/autosharding/Internal*' + // @Internal types, published only so that the xDS integration can inject them. + exclude 'io/grpc/autosharding/AutoShardingAttributes.java' + exclude 'io/grpc/autosharding/ChannelFactory*' } tasks.named("jacocoTestReport").configure { diff --git a/autosharding/src/main/java/io/grpc/autosharding/Assignment.java b/autosharding/src/main/java/io/grpc/autosharding/Assignment.java new file mode 100644 index 00000000000..f243a91e5c0 --- /dev/null +++ b/autosharding/src/main/java/io/grpc/autosharding/Assignment.java @@ -0,0 +1,142 @@ +/* + * Copyright 2026 The gRPC Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.grpc.autosharding; + +import static com.google.common.base.Preconditions.checkNotNull; + +import com.google.common.base.MoreObjects; +import com.google.common.collect.ImmutableList; +import com.google.common.io.BaseEncoding; +import com.google.common.primitives.UnsignedBytes; +import java.util.Comparator; +import java.util.List; +import javax.annotation.Nullable; +import javax.annotation.concurrent.Immutable; + +/** + * An immutable, validated assignment from the sharding service: slices sorted by start key that + * together cover the whole keyspace, from the empty key to infinity, without gaps or overlaps. + * Key ranges without a usable slice from the server are slices with no endpoints. Produced only + * by {@link AssignmentParser}; see gRFC A119, "Contract of the AutoshardingClient". + */ +@Immutable +final class Assignment { + + /** + * A single contiguous key range and the endpoints assigned to it. Its key arrays are shared + * rather than copied, and must not be modified. + */ + @Immutable + @SuppressWarnings("Immutable") // The key arrays are never modified. + static final class Slice { + /** Orders slices by start key, compared as unsigned bytes. */ + static final Comparator START_KEY_ORDER = + (a, b) -> UnsignedBytes.lexicographicalComparator().compare(a.startKey, b.startKey); + + private final byte[] startKey; + @Nullable private final byte[] endKey; + private final ImmutableList endpoints; + private final boolean fallbackDisabled; + + /** + * Constructs a {@link Slice} that may fall back. + * + * @param startKey the inclusive start key of the range + * @param endKey the exclusive end key of the range, or {@code null} for the infinity + * sentinel covering the largest allowed key + * @param endpoints indices into {@link Assignment#getEndpointNames()} assigned to this range + */ + Slice(byte[] startKey, @Nullable byte[] endKey, List endpoints) { + this(startKey, endKey, endpoints, false); + } + + /** + * Constructs a {@link Slice}. + * + * @param fallbackDisabled whether picks for this range must fail rather than fall back; set + * when the server assigned the range no endpoints, never for a filled gap + */ + Slice( + byte[] startKey, + @Nullable byte[] endKey, + List endpoints, + boolean fallbackDisabled) { + this.startKey = checkNotNull(startKey, "startKey"); + this.endKey = endKey; + this.endpoints = ImmutableList.copyOf(checkNotNull(endpoints, "endpoints")); + this.fallbackDisabled = fallbackDisabled; + } + + byte[] getStartKey() { + return startKey; + } + + @Nullable + byte[] getEndKey() { + return endKey; + } + + ImmutableList getEndpoints() { + return endpoints; + } + + boolean isFallbackDisabled() { + return fallbackDisabled; + } + + @Override + public String toString() { + return MoreObjects.toStringHelper(this) + .add("startKey", BaseEncoding.base16().encode(startKey)) + .add("endKey", endKey == null ? "inf" : BaseEncoding.base16().encode(endKey)) + .add("endpoints", endpoints) + .add("fallbackDisabled", fallbackDisabled) + .toString(); + } + } + + private final ImmutableList slices; + private final ImmutableList endpointNames; + + /** + * Constructs an {@link Assignment}. + * + * @param slices the validated, sorted, contiguous and gap-free list of key-range slices + * @param endpointNames the complete list of endpoint names, combined across all chunks in + * chunk order + */ + Assignment(List slices, List endpointNames) { + this.slices = ImmutableList.copyOf(checkNotNull(slices, "slices")); + this.endpointNames = ImmutableList.copyOf(checkNotNull(endpointNames, "endpointNames")); + } + + ImmutableList getSlices() { + return slices; + } + + ImmutableList getEndpointNames() { + return endpointNames; + } + + @Override + public String toString() { + return MoreObjects.toStringHelper(this) + .add("endpointNames", endpointNames) + .add("slices", slices) + .toString(); + } +} diff --git a/autosharding/src/main/java/io/grpc/autosharding/AssignmentParser.java b/autosharding/src/main/java/io/grpc/autosharding/AssignmentParser.java new file mode 100644 index 00000000000..5a51db7c776 --- /dev/null +++ b/autosharding/src/main/java/io/grpc/autosharding/AssignmentParser.java @@ -0,0 +1,321 @@ +/* + * Copyright 2026 The gRPC Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.grpc.autosharding; + +import static com.google.common.base.Preconditions.checkNotNull; + +import com.google.cloud.autosharding.v1.AssignmentChunk; +import com.google.cloud.autosharding.v1.EndpointState; +import com.google.cloud.autosharding.v1.PerSliceEndpointState; +import com.google.cloud.autosharding.v1.SliceAssignment; +import com.google.common.collect.ImmutableList; +import com.google.common.io.BaseEncoding; +import com.google.common.primitives.UnsignedBytes; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; +import javax.annotation.Nullable; + +/** + * Combines the {@link AssignmentChunk} messages of a single logical assignment into a sorted, + * contiguous and gap-free {@link Assignment}, following gRFC A119, "Handling assignments from the + * Autosharding server". + * + *

A slice is dropped if either key is longer than 512 bytes, its start key is not below its + * end key, it references an endpoint index that is out of range, or it overlaps another slice. A + * dropped slice leaves a gap instead of invalidating the assignment, and gaps are filled with + * slices that have no endpoints. + */ +final class AssignmentParser { + + /** The outcome of parsing one logical assignment. */ + static final class Result { + /** The assignment to hand to the LB policy, or null if no usable slice remained. */ + @Nullable final Assignment assignment; + + /** + * Describes the dropped slices and the gaps, or that no slice was received at all, suitable + * for the {@code error_message} of an {@code AssignmentAck}. Null when every slice was usable + * and they left no gaps. + */ + @Nullable final String errorMessage; + + private Result(@Nullable Assignment assignment, @Nullable String errorMessage) { + this.assignment = assignment; + this.errorMessage = errorMessage; + } + } + + /** + * The limit on {@code AssignmentAck.error_message}, from {@code autosharding.proto}: "The + * length of this field MUST NOT exceed 512 characters". + */ + private static final int MAX_ERROR_MESSAGE_CHARS = 512; + + /** + * The limit on slice keys, from {@code autosharding.proto}: "Will be at most 512 bytes". A slice + * with a longer key is dropped. + */ + private static final int MAX_KEY_BYTES = 512; + + /** How many leading bytes of a key to hex-encode into a description. */ + private static final int MAX_ENCODED_KEY_BYTES = 8; + + private static final String SEPARATOR = "; "; + + private static final Comparator UNSIGNED_BYTES_COMPARATOR = + UnsignedBytes.lexicographicalComparator(); + private static final byte[] EMPTY_BYTES = new byte[0]; + + private AssignmentParser() {} + + /** + * Parses and validates the buffered chunks of a single logical assignment. + * + * @param chunks the chunks received since the last {@code AssignmentMetadata}, in the order + * they were received + */ + static Result parse(List chunks) { + checkNotNull(chunks, "chunks"); + + ImmutableList endpointNames = combineEndpointNames(chunks); + List errorDetails = new ArrayList<>(); + List slices = combineSlices(chunks, endpointNames.size(), errorDetails); + + slices.sort(Assignment.Slice.START_KEY_ORDER); + slices = dropOverlaps(slices, errorDetails); + + if (slices.isEmpty()) { + return new Result( + null, errorDetails.isEmpty() ? "no slice assignments received" : describe(errorDetails)); + } + List filled = fillGaps(slices, errorDetails); + String errorMessage = errorDetails.isEmpty() ? null : describe(errorDetails); + return new Result(new Assignment(filled, endpointNames), errorMessage); + } + + /** + * Concatenates the endpoint names across all chunks, in chunk order. Slice endpoint indices + * are defined against this combined list. + */ + private static ImmutableList combineEndpointNames(List chunks) { + ImmutableList.Builder names = ImmutableList.builder(); + for (AssignmentChunk chunk : chunks) { + for (EndpointState endpointState : chunk.getEndpointsList()) { + names.add(endpointState.getEndpoint()); + } + } + return names.build(); + } + + /** + * Concatenates the slice assignments across all chunks, dropping any with a key longer than 512 + * bytes, a start key not below its end key, or an out-of-range endpoint index. Slice assignments + * may appear in any order across chunks. + * + * @param errorDetails collects a description of each slice that was dropped + */ + private static List combineSlices( + List chunks, int endpointCount, List errorDetails) { + List slices = new ArrayList<>(); + for (AssignmentChunk chunk : chunks) { + for (SliceAssignment sliceAssignment : chunk.getSliceAssignmentsList()) { + // An unset slice reads as ["", inf), the whole keyspace. + com.google.cloud.autosharding.v1.Slice slice = sliceAssignment.getSlice(); + byte[] startKey = slice.getStartKey().toByteArray(); + byte[] endKey = slice.hasEndKey() ? slice.getEndKey().toByteArray() : null; + + if (startKey.length > MAX_KEY_BYTES) { + errorDetails.add( + String.format( + "slice starting at %s has a start_key longer than %s bytes", + encode(startKey), MAX_KEY_BYTES)); + continue; + } + if (endKey != null && endKey.length > MAX_KEY_BYTES) { + errorDetails.add( + String.format( + "slice starting at %s has an end_key longer than %s bytes", + encode(startKey), MAX_KEY_BYTES)); + continue; + } + + // end_key is exclusive, so a slice covers keys only if start_key < end_key. [k, k) is + // empty rather than the single key k: a server assigning one key sends an end_key of k + // with a trailing 0x00. A slice that covers nothing cannot leave a gap when dropped. + if (endKey != null && UNSIGNED_BYTES_COMPARATOR.compare(startKey, endKey) >= 0) { + errorDetails.add( + String.format( + "slice [%s, %s) has start_key >= end_key", encode(startKey), encode(endKey))); + continue; + } + + List endpoints = new ArrayList<>(sliceAssignment.getEndpointsCount()); + String indexProblem = null; + for (PerSliceEndpointState perSlice : sliceAssignment.getEndpointsList()) { + int index = perSlice.getEndpointIndex(); + if (index < 0 || index >= endpointCount) { + indexProblem = + String.format( + "slice starting at %s references out-of-range endpoint index %s" + + " (assignment has %s endpoints)", + encode(startKey), index, endpointCount); + break; + } + endpoints.add(index); + } + if (indexProblem != null) { + errorDetails.add(indexProblem); + continue; + } + // No endpoints means the server deliberately left the range unassigned, so it must not + // fall back either. + slices.add(new Assignment.Slice(startKey, endKey, endpoints, endpoints.isEmpty())); + } + } + return slices; + } + + /** + * Returns the slices of {@code slicesByStartKey} that overlap no other slice. + * + *

When slices overlap, every one of them is dropped. The server has told us two different + * things about the same key and there is no basis for preferring either, so the keys they cover + * become a gap. + * + * @param slicesByStartKey slices in ascending {@code startKey} order + * @param errorDetails collects a description of each slice that was dropped + */ + private static List dropOverlaps( + List slicesByStartKey, List errorDetails) { + List nonOverlapping = new ArrayList<>(slicesByStartKey.size()); + int index = 0; + while (index < slicesByStartKey.size()) { + // Extend a run of slices for as long as the keys covered so far reach into the next one. + // Every slice that joins overlaps some earlier member, and the first two overlap directly, + // so a run longer than one slice consists entirely of slices that overlap something. + byte[] runEndKey = slicesByStartKey.get(index).getEndKey(); + int end = index + 1; + while (end < slicesByStartKey.size() + && reaches(runEndKey, slicesByStartKey.get(end).getStartKey())) { + byte[] endKey = slicesByStartKey.get(end).getEndKey(); + // A run that already reaches infinity cannot be extended any further. + if (runEndKey != null + && (endKey == null || UNSIGNED_BYTES_COMPARATOR.compare(endKey, runEndKey) > 0)) { + runEndKey = endKey; + } + end++; + } + + if (end - index == 1) { + nonOverlapping.add(slicesByStartKey.get(index)); + } else { + for (Assignment.Slice slice : slicesByStartKey.subList(index, end)) { + errorDetails.add( + String.format( + "slice [%s, %s) overlaps another slice", + encode(slice.getStartKey()), encode(slice.getEndKey()))); + } + } + index = end; + } + return nonOverlapping; + } + + /** + * Returns whether a range ending at {@code endKey}, or at infinity when it is null, extends + * past {@code startKey}. + */ + private static boolean reaches(@Nullable byte[] endKey, byte[] startKey) { + return endKey == null || UNSIGNED_BYTES_COMPARATOR.compare(endKey, startKey) > 0; + } + + /** + * Returns a contiguous list of slices covering {@code ["", inf)}, inserting endpoint-less + * slices wherever the sorted input leaves a gap. Those slices may fall back: only a range the + * server itself assigned no endpoints disables fallback. + * + * @param slicesByStartKey slices in ascending {@code startKey} order, none overlapping + * @param errorDetails collects a description of each gap + */ + private static List fillGaps( + List slicesByStartKey, List errorDetails) { + List filled = new ArrayList<>(slicesByStartKey.size() + 1); + // Exclusive upper bound of the key range covered so far; null once infinity is reached. + byte[] cursor = EMPTY_BYTES; + for (Assignment.Slice slice : slicesByStartKey) { + if (UNSIGNED_BYTES_COMPARATOR.compare(cursor, slice.getStartKey()) < 0) { + errorDetails.add(describeGap(cursor, slice.getStartKey())); + filled.add(new Assignment.Slice(cursor, slice.getStartKey(), ImmutableList.of())); + } + filled.add(slice); + cursor = slice.getEndKey(); + } + if (cursor != null) { + errorDetails.add(describeGap(cursor, null)); + filled.add(new Assignment.Slice(cursor, null, ImmutableList.of())); + } + return filled; + } + + private static String describeGap(byte[] startKey, @Nullable byte[] endKey) { + return String.format( + "keys [%s, %s) are not covered by any slice", encode(startKey), encode(endKey)); + } + + /** + * Summarizes the dropped slices and gaps, reporting as many as fit in the {@code error_message} + * of an {@code AssignmentAck}, followed by the count of those left out. + */ + private static String describe(List errorDetails) { + StringBuilder message = new StringBuilder(); + int reported = 0; + for (String detail : errorDetails) { + int separator = reported == 0 ? 0 : SEPARATOR.length(); + // Leave room for the suffix that will be needed if this is where we stop. + int reserved = andMore(errorDetails.size() - reported - 1).length(); + if (message.length() + separator + detail.length() + reserved + > MAX_ERROR_MESSAGE_CHARS) { + break; + } + if (reported > 0) { + message.append(SEPARATOR); + } + message.append(detail); + reported++; + } + return message + andMore(errorDetails.size() - reported); + } + + private static String andMore(int omitted) { + return omitted == 0 ? "" : String.format("; and %s more", omitted); + } + + /** + * Hex-encodes a key for a description, shortened to its first {@link #MAX_ENCODED_KEY_BYTES} + * bytes. A null key, meaning infinity, is written as "inf". + */ + private static String encode(@Nullable byte[] key) { + if (key == null) { + return "inf"; + } + if (key.length <= MAX_ENCODED_KEY_BYTES) { + return BaseEncoding.base16().encode(key); + } + return BaseEncoding.base16().encode(key, 0, MAX_ENCODED_KEY_BYTES) + "..."; + } +} diff --git a/autosharding/src/main/java/io/grpc/autosharding/AutoShardingAttributes.java b/autosharding/src/main/java/io/grpc/autosharding/AutoShardingAttributes.java new file mode 100644 index 00000000000..f242cd074e0 --- /dev/null +++ b/autosharding/src/main/java/io/grpc/autosharding/AutoShardingAttributes.java @@ -0,0 +1,34 @@ +/* + * Copyright 2026 The gRPC Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.grpc.autosharding; + +import io.grpc.Attributes; +import io.grpc.Internal; + +/** + * Attributes that the parent of the {@code autosharding_experimental} LB policy sets on the + * {@link io.grpc.LoadBalancer.ResolvedAddresses} given to the policy. + */ +@Internal +public final class AutoShardingAttributes { + + /** The {@link ChannelFactory} for the channel to the sharding service. */ + public static final Attributes.Key ATTR_CHANNEL_FACTORY = + Attributes.Key.create("io.grpc.autosharding.channelFactory"); + + private AutoShardingAttributes() {} +} diff --git a/autosharding/src/main/java/io/grpc/autosharding/AutoShardingLoadBalancer.java b/autosharding/src/main/java/io/grpc/autosharding/AutoShardingLoadBalancer.java new file mode 100644 index 00000000000..108fc4bba9f --- /dev/null +++ b/autosharding/src/main/java/io/grpc/autosharding/AutoShardingLoadBalancer.java @@ -0,0 +1,554 @@ +/* + * Copyright 2026 The gRPC Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.grpc.autosharding; + +import static com.google.common.base.Preconditions.checkNotNull; +import static io.grpc.ConnectivityState.IDLE; +import static io.grpc.ConnectivityState.READY; +import static io.grpc.ConnectivityState.TRANSIENT_FAILURE; + +import com.google.common.annotations.VisibleForTesting; +import com.google.common.base.Stopwatch; +import com.google.common.base.Supplier; +import com.google.common.collect.ImmutableList; +import io.grpc.CallOptions; +import io.grpc.Channel; +import io.grpc.ClientCall; +import io.grpc.ConnectivityState; +import io.grpc.EquivalentAddressGroup; +import io.grpc.LoadBalancer; +import io.grpc.LoadBalancerProvider; +import io.grpc.LoadBalancerRegistry; +import io.grpc.Metadata; +import io.grpc.MethodDescriptor; +import io.grpc.Status; +import io.grpc.StatusOr; +import io.grpc.SynchronizationContext; +import io.grpc.internal.BackoffPolicy; +import io.grpc.internal.ExponentialBackoffPolicy; +import io.grpc.internal.GrpcUtil; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.ScheduledExecutorService; +import java.util.logging.Level; +import java.util.logging.Logger; +import javax.annotation.Nullable; + +/** + * The {@code autosharding_experimental} load balancing policy. Shards RPCs across endpoints by an + * application-defined key carried in a request header, using key ranges streamed from an external + * sharding service. See gRFC A119. + * + *

Until its {@link AutoshardingClient} reports an assignment or an error, the policy queues + * RPCs and reports IDLE. After an error, RPCs go to any resolved endpoint or fail, depending on + * {@code enable_fallback}. + * + *

Threading model

+ * + *

Every method, and every callback from the client and from the endpoints' child policies, + * runs on the helper's {@link SynchronizationContext}, so the fields need no locking. Published + * pickers run on RPC threads; they read only immutable snapshots and hand connection requests to + * the synchronization context. + */ +final class AutoShardingLoadBalancer extends LoadBalancer { + private static final Logger logger = + Logger.getLogger(AutoShardingLoadBalancer.class.getName()); + + /** + * Published while waiting for the first assignment. The delay type is consumed by gRFC A121, + * RPC Delay Observability. + */ + private static final SubchannelPicker ASSIGNMENT_PENDING_PICKER = + new FixedResultPicker( + PickResult.withNoResult( + "autosharding_assignment_pending", "Waiting for initial sharding assignment")); + + private final Helper helper; + private final SynchronizationContext syncContext; + private final ScheduledExecutorService timeService; + private final LoadBalancerProvider childProvider; + private final BackoffPolicy.Provider backoffPolicyProvider; + private final Supplier stopwatchSupplier; + + /** Identifies this client to the sharding service; stable across stream restarts. */ + private final String clientUuid; + + /** One lazily-created {@code pick_first} child per resolved endpoint, each with a dense index. */ + private final EndpointMap endpointMap; + + @Nullable private AutoShardingLoadBalancerConfig config; + + /** + * The client streaming assignments, and the lease on the channel it streams on. Null until an + * update is accepted, and again after one is rejected. + */ + @Nullable private ShardingConnection shardingConnection; + + /** + * Set when an update is rejected, or when the name resolver reports an error while no update is + * in effect; cleared when an update is accepted. While set there is no client, and every RPC + * fails with this error. + */ + @Nullable private Status resolverError; + + /** + * The last assignment or error reported by an {@link AutoshardingClient}. Survives client + * replacement, so what the previous client reported stays in use until the new one reports. + * Null until a client reports, which queues RPCs, and cleared when an update is rejected. + */ + @Nullable private StatusOr assignmentOrError; + + /** + * The key ranges of the assignment in {@link #assignmentOrError}, with the hostnames it names + * endpoints by translated into indices into {@link #endpointMap}. Rebuilt whenever either + * changes; null only before the first update. + */ + @Nullable private SliceMap sliceMap; + + private boolean shutdown; + + AutoShardingLoadBalancer(Helper helper) { + this( + helper, + LoadBalancerRegistry.getDefaultRegistry().getProvider("pick_first"), + new ExponentialBackoffPolicy.Provider(), + GrpcUtil.STOPWATCH_SUPPLIER, + UUID.randomUUID().toString()); + } + + /** + * Constructs a load balancer with injectable collaborators. + * + * @param childProvider provides the per-endpoint child load balancer, {@code pick_first} in + * production. {@link EndpointMap} takes care of deferring its instantiation, so this must + * not be wrapped in a {@link io.grpc.util.LazyLoadBalancer.Factory} by the caller + */ + @VisibleForTesting + AutoShardingLoadBalancer( + Helper helper, + LoadBalancerProvider childProvider, + BackoffPolicy.Provider backoffPolicyProvider, + Supplier stopwatchSupplier, + String clientUuid) { + this.helper = checkNotNull(helper, "helper"); + this.syncContext = helper.getSynchronizationContext(); + this.timeService = helper.getScheduledExecutorService(); + this.childProvider = checkNotNull(childProvider, "childProvider"); + this.backoffPolicyProvider = checkNotNull(backoffPolicyProvider, "backoffPolicyProvider"); + this.stopwatchSupplier = checkNotNull(stopwatchSupplier, "stopwatchSupplier"); + this.clientUuid = checkNotNull(clientUuid, "clientUuid"); + this.endpointMap = new EndpointMap(helper, this.childProvider, this::onChildStateUpdate); + } + + @Override + public Status acceptResolvedAddresses(ResolvedAddresses resolvedAddresses) { + if (shutdown) { + return Status.OK; + } + // Null when this policy is the channel's default and there is no service config. + Object rawConfig = resolvedAddresses.getLoadBalancingPolicyConfig(); + if (rawConfig == null) { + return rejectUpdate("autosharding: no load balancing config"); + } + AutoShardingLoadBalancerConfig newConfig = (AutoShardingLoadBalancerConfig) rawConfig; + + // The endpoints are applied even when a check below rejects the update. When the set is empty + // this tears the children down, so that in-flight picks stop resolving to endpoints the + // resolver has retracted. + List endpoints = resolvedAddresses.getAddresses(); + endpointMap.updateEndpoints(endpoints, resolvedAddresses.getAttributes()); + + if (endpointMap.size() == 0) { + return rejectUpdate("autosharding: name resolver returned no endpoints"); + } + ChannelFactory factory = + resolvedAddresses.getAttributes().get(AutoShardingAttributes.ATTR_CHANNEL_FACTORY); + if (factory == null) { + return rejectUpdate("autosharding: no channel factory supplied to the LB policy"); + } + + // Decide what changes. The key identifies the channel, so a different factory under the same + // key changes nothing. The target depends on the locality of the endpoints, so it can change + // while the configuration does not. With no client, as before the first update or after a + // rejected one, both are new. + boolean channelFactoryKeyChanged = + shardingConnection == null + || !config.getChannelFactoryKey().equals(newConfig.getChannelFactoryKey()); + String target = resolveTarget(newConfig.getAutoshardingTarget(), sharedLocality(endpoints)); + boolean targetChanged = + shardingConnection == null || !target.equals(shardingConnection.client.getTarget()); + + // Then apply it. The new client starts before the previous one is shut down, and the previous + // channel is closed last, so no client is ever left streaming on a closed channel. + resolverError = null; + config = newConfig; + if (channelFactoryKeyChanged || targetChanged) { + ShardingConnection previous = shardingConnection; + ChannelFactory.ChannelLease channelLease = + channelFactoryKeyChanged + ? leaseChannel(factory, newConfig.getChannelFactoryKey()) + : previous.channelLease; + AutoshardingClient client = + startClient(channelLease.channel(), target, newConfig.getInitialAssignmentTimeoutNanos()); + shardingConnection = new ShardingConnection(channelLease, client); + if (previous != null) { + previous.client.shutdown(); + if (channelFactoryKeyChanged) { + previous.channelLease.close(); + } + } + } + // The slice map indexes into the endpoints, so it is rebuilt with them. + sliceMap = buildSliceMap(); + publishPicker(); + return Status.OK; + } + + @Override + public void handleNameResolutionError(Status error) { + if (shutdown) { + return; + } + Status failure = + error.isOk() + ? Status.UNAVAILABLE.withDescription("autosharding: name resolution failed") + : error; + if (shardingConnection == null) { + // No update is in effect, so there is nothing to serve with. As after a rejected update, + // RPCs fail with the error until an update is accepted. + resolverError = failure; + helper.updateBalancingState( + TRANSIENT_FAILURE, new FixedResultPicker(PickResult.withError(failure))); + return; + } + if (isStillServing()) { + logger.log(Level.FINE, "Ignoring name resolution error, still serving: {0}", error); + return; + } + // Not serving, so the resolver's error names the cause better than the endpoints' errors. + helper.updateBalancingState( + TRANSIENT_FAILURE, new FixedResultPicker(PickResult.withError(failure))); + } + + /** + * Whether RPCs are being served with the endpoints from an earlier resolution, so a resolver + * error can be ignored. Waiting for the sharding service counts: RPCs are queued for it, not + * failing. So does IDLE: IDLE endpoints report nothing until picked, so a failing picker + * published then would never be replaced. + */ + private boolean isStillServing() { + if (assignmentOrError == null) { + return true; + } + ConnectivityState state = endpointMap.aggregateConnectivityState(); + return state == READY || state == IDLE; + } + + @Override + public void requestConnection() { + // Nothing to do: picks connect the endpoint they choose, and child and resolver updates wake + // one when needed. + } + + @Override + public void shutdown() { + if (shutdown) { + return; + } + shutdown = true; + closeShardingConnection(); + + endpointMap.shutdown(); + } + + /** + * Leases a channel to the sharding service, or returns a {@link LameChannel} carrying the error + * if the factory throws. + */ + private static ChannelFactory.ChannelLease leaseChannel( + ChannelFactory factory, String channelFactoryKey) { + try { + return factory.createChannel(channelFactoryKey); + } catch (RuntimeException e) { + logger.log(Level.WARNING, "Failed to create a channel to the sharding service", e); + return new LameChannel( + Status.UNAVAILABLE + .withDescription( + "autosharding: channel factory rejected key '" + + channelFactoryKey + + "': " + + e.getMessage()) + .withCause(e)); + } + } + + /** + * Creates and starts an {@link AutoshardingClient}. Every target or channel change gets a new + * client, so that an accepted generation never carries over to another server or target. + */ + private AutoshardingClient startClient( + Channel channel, String target, long initialAssignmentTimeoutNanos) { + AutoshardingClient client = + new AutoshardingClient( + clientUuid, + syncContext, + timeService, + backoffPolicyProvider, + stopwatchSupplier, + channel, + target, + initialAssignmentTimeoutNanos, + new AssignmentWatcherImpl()); + client.start(); + return client; + } + + /** + * Returns the locality every endpoint is in, or null if any endpoint has none or they differ. + * Under xDS this is the {@code weighted_target_experimental} child name. + */ + @Nullable + private static String sharedLocality(List endpoints) { + String shared = null; + for (EquivalentAddressGroup endpoint : endpoints) { + String endpointLocality = + endpoint.getAttributes().get(EquivalentAddressGroup.ATTR_LOCALITY_NAME); + if (endpointLocality == null || (shared != null && !shared.equals(endpointLocality))) { + return null; + } + shared = endpointLocality; + } + return shared; + } + + /** + * Replaces the first {@code %s} in the configured target with the locality, or with the empty + * string when there is none. + */ + private static String resolveTarget(String configuredTarget, @Nullable String locality) { + int token = configuredTarget.indexOf("%s"); + if (token == -1) { + return configuredTarget; + } + return configuredTarget.substring(0, token) + + (locality == null ? "" : locality) + + configuredTarget.substring(token + 2); + } + + /** + * Receives what the current {@link AutoshardingClient} reports. Both callbacks arrive on the + * synchronization context. + * + *

A client that has been replaced cannot deliver anything, because {@link + * AutoshardingClient#shutdown()} closes its stream and cancels its timer, so there is no need to + * check which client a callback came from. + */ + private final class AssignmentWatcherImpl implements AutoshardingClient.AssignmentWatcher { + @Override + public void onAssignment(Assignment newAssignment) { + if (shutdown) { + return; + } + assignmentOrError = StatusOr.fromValue(newAssignment); + rebuildSliceMapAndPublish(); + } + + @Override + public void onError(Status error) { + if (shutdown) { + return; + } + // A client only reports errors before it has reported an assignment, so an assignment in + // hand here came from a previous client. The new client's state replaces it. + logger.log( + Level.WARNING, + "No assignment from the sharding service; proceeding {0} fallback: {1}", + new Object[] {config != null && config.isFallbackEnabled() ? "with" : "without", error}); + assignmentOrError = StatusOr.fromStatus(error); + rebuildSliceMapAndPublish(); + } + } + + /** + * Called by {@link EndpointMap} when a child reports a new state or picker. The endpoint set + * and the indices into it are unchanged, so the existing {@link SliceMap} still applies and + * only the picker needs rebuilding. + */ + private void onChildStateUpdate() { + publishPicker(); + } + + private void rebuildSliceMapAndPublish() { + sliceMap = buildSliceMap(); + publishPicker(); + } + + /** + * Translates the endpoint names in the current assignment into indices into + * {@link #endpointMap}, dropping names the resolver has not supplied. Without an assignment the + * result has no slices, so every lookup misses and RPCs use the fallback pool. + */ + private SliceMap buildSliceMap() { + int endpointCount = endpointMap.size(); + List fallbackPool = new ArrayList<>(endpointCount); + for (int i = 0; i < endpointCount; i++) { + fallbackPool.add(i); + } + if (assignmentOrError == null || !assignmentOrError.hasValue()) { + return new SliceMap(ImmutableList.of(), fallbackPool); + } + + Assignment assignment = assignmentOrError.getValue(); + ImmutableList endpointNames = assignment.getEndpointNames(); + List entries = new ArrayList<>(assignment.getSlices().size()); + for (Assignment.Slice slice : assignment.getSlices()) { + List indices = new ArrayList<>(slice.getEndpoints().size()); + for (int nameIndex : slice.getEndpoints()) { + int endpointIndex = endpointMap.indexOf(endpointNames.get(nameIndex)); + if (endpointIndex != -1) { + indices.add(endpointIndex); + } + } + entries.add( + new SliceMap.SliceEntry(slice.getStartKey(), indices, slice.isFallbackDisabled())); + } + return new SliceMap(entries, fallbackPool); + } + + private void publishPicker() { + // Before the first accepted update there is nothing to publish. After a rejected one, or a + // resolver error with no update in effect, the TRANSIENT_FAILURE already reported stands + // until an update is accepted. + if (shutdown || config == null || resolverError != null) { + return; + } + if (assignmentOrError == null) { + // RPCs are queued until a client reports, so the state is IDLE whatever the endpoints + // report. Reporting CONNECTING instead would keep a parent priority policy's failover + // timer running while the sharding service answers. + helper.updateBalancingState(IDLE, ASSIGNMENT_PENDING_PICKER); + return; + } + if (!assignmentOrError.hasValue() && !config.isFallbackEnabled()) { + // No endpoint can be picked, so there is nothing to connect for either. + helper.updateBalancingState( + TRANSIENT_FAILURE, + new FixedResultPicker(PickResult.withError(assignmentOrError.getStatus()))); + return; + } + helper.updateBalancingState( + endpointMap.aggregateConnectivityState(), + new AutoShardingPicker( + sliceMap, + endpointMap.toPickerEndpoints(), + config.isFallbackEnabled(), + config.getKeyHeader())); + endpointMap.maybeWakeUpIdleEndpoint(); + } + + @VisibleForTesting + EndpointMap getEndpointMap() { + return endpointMap; + } + + /** + * Rejects an update the policy cannot use, returning the error for {@link + * #acceptResolvedAddresses} to hand back to the channel. Every RPC fails with it until an update + * is accepted. The client is shut down, its channel lease closed and what it reported dropped, + * so the next accepted update starts afresh, queueing RPCs until its client reports. + */ + private Status rejectUpdate(String description) { + resolverError = Status.UNAVAILABLE.withDescription(description); + closeShardingConnection(); + assignmentOrError = null; + sliceMap = buildSliceMap(); + helper.updateBalancingState( + TRANSIENT_FAILURE, new FixedResultPicker(PickResult.withError(resolverError))); + return resolverError; + } + + /** Shuts down the client, then closes the lease on the channel it streamed on. */ + private void closeShardingConnection() { + if (shardingConnection != null) { + shardingConnection.client.shutdown(); + shardingConnection.channelLease.close(); + shardingConnection = null; + } + } + + /** An {@link AutoshardingClient} and the lease on the channel it streams on. */ + private static final class ShardingConnection { + final ChannelFactory.ChannelLease channelLease; + final AutoshardingClient client; + + ShardingConnection(ChannelFactory.ChannelLease channelLease, AutoshardingClient client) { + this.channelLease = channelLease; + this.client = client; + } + } + + /** + * A channel whose every call fails with a fixed status. Stands in for a channel to the sharding + * service that the {@link ChannelFactory} failed to create, so that the client reports the + * failure like any other error from the sharding service. No factory created it, so it is its + * own lease and closing it does nothing. + */ + private static final class LameChannel extends Channel implements ChannelFactory.ChannelLease { + private final Status error; + + LameChannel(Status error) { + this.error = error; + } + + @Override + public ClientCall newCall( + MethodDescriptor method, CallOptions callOptions) { + return new ClientCall() { + @Override + public void start(Listener listener, Metadata headers) { + listener.onClose(error, new Metadata()); + } + + @Override + public void request(int numMessages) {} + + @Override + public void cancel(@Nullable String message, @Nullable Throwable cause) {} + + @Override + public void halfClose() {} + + @Override + public void sendMessage(ReqT message) {} + }; + } + + @Override + public String authority() { + return "lame-channel"; + } + + @Override + public Channel channel() { + return this; + } + + @Override + public void close() {} + } +} diff --git a/autosharding/src/main/java/io/grpc/autosharding/AutoShardingLoadBalancerConfig.java b/autosharding/src/main/java/io/grpc/autosharding/AutoShardingLoadBalancerConfig.java new file mode 100644 index 00000000000..9426c2cea7c --- /dev/null +++ b/autosharding/src/main/java/io/grpc/autosharding/AutoShardingLoadBalancerConfig.java @@ -0,0 +1,130 @@ +/* + * Copyright 2026 The gRPC Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.grpc.autosharding; + +import static com.google.common.base.Preconditions.checkArgument; +import static com.google.common.base.Preconditions.checkNotNull; + +import com.google.common.base.MoreObjects; +import io.grpc.Metadata; +import java.util.Objects; +import java.util.concurrent.TimeUnit; + +/** + * Configuration for the {@code autosharding_experimental} LB policy, as specified by + * {@code AutoshardingLbConfig} in gRFC A119. + */ +final class AutoShardingLoadBalancerConfig { + + /** Default for {@link #getInitialAssignmentTimeoutNanos} when the field is unset. */ + static final long DEFAULT_INITIAL_ASSIGNMENT_TIMEOUT_NANOS = TimeUnit.SECONDS.toNanos(60); + + /** Opaque key passed to the {@link ChannelFactory} to reach the sharding service. */ + private final String channelFactoryKey; + + /** + * Identifies the assignments this client should receive. + * + *

May contain a single {@code %s} token. Before sending the target to the sharding service, + * the LB policy replaces it with the {@link io.grpc.EquivalentAddressGroup#ATTR_LOCALITY_NAME} + * that all endpoints share, or with the empty string when they don't share one. + */ + private final String autoshardingTarget; + + /** Request header holding the application-defined sharding key. */ + private final Metadata.Key keyHeader; + + /** Whether RPCs may fall back to the full set of resolved endpoints. */ + private final boolean enableFallback; + + /** How long each new client waits for its first assignment before reporting an error. */ + private final long initialAssignmentTimeoutNanos; + + AutoShardingLoadBalancerConfig( + String channelFactoryKey, + String autoshardingTarget, + Metadata.Key keyHeader, + boolean enableFallback, + long initialAssignmentTimeoutNanos) { + this.channelFactoryKey = checkNotNull(channelFactoryKey, "channelFactoryKey"); + this.autoshardingTarget = checkNotNull(autoshardingTarget, "autoshardingTarget"); + this.keyHeader = checkNotNull(keyHeader, "keyHeader"); + checkArgument( + initialAssignmentTimeoutNanos >= 0, + "initialAssignmentTimeoutNanos is negative: %s", + initialAssignmentTimeoutNanos); + this.enableFallback = enableFallback; + this.initialAssignmentTimeoutNanos = initialAssignmentTimeoutNanos; + } + + String getChannelFactoryKey() { + return channelFactoryKey; + } + + String getAutoshardingTarget() { + return autoshardingTarget; + } + + Metadata.Key getKeyHeader() { + return keyHeader; + } + + boolean isFallbackEnabled() { + return enableFallback; + } + + long getInitialAssignmentTimeoutNanos() { + return initialAssignmentTimeoutNanos; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (!(o instanceof AutoShardingLoadBalancerConfig)) { + return false; + } + AutoShardingLoadBalancerConfig that = (AutoShardingLoadBalancerConfig) o; + return enableFallback == that.enableFallback + && initialAssignmentTimeoutNanos == that.initialAssignmentTimeoutNanos + && channelFactoryKey.equals(that.channelFactoryKey) + && autoshardingTarget.equals(that.autoshardingTarget) + && keyHeader.equals(that.keyHeader); + } + + @Override + public int hashCode() { + return Objects.hash( + channelFactoryKey, + autoshardingTarget, + keyHeader, + enableFallback, + initialAssignmentTimeoutNanos); + } + + @Override + public String toString() { + return MoreObjects.toStringHelper(this) + .add("channelFactoryKey", channelFactoryKey) + .add("autoshardingTarget", autoshardingTarget) + .add("keyHeader", keyHeader.name()) + .add("enableFallback", enableFallback) + .add("initialAssignmentTimeoutNanos", initialAssignmentTimeoutNanos) + .toString(); + } +} diff --git a/autosharding/src/main/java/io/grpc/autosharding/AutoShardingLoadBalancerProvider.java b/autosharding/src/main/java/io/grpc/autosharding/AutoShardingLoadBalancerProvider.java new file mode 100644 index 00000000000..c9458a3df5f --- /dev/null +++ b/autosharding/src/main/java/io/grpc/autosharding/AutoShardingLoadBalancerProvider.java @@ -0,0 +1,116 @@ +/* + * Copyright 2026 The gRPC Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.grpc.autosharding; + +import io.grpc.Internal; +import io.grpc.LoadBalancer; +import io.grpc.LoadBalancerProvider; +import io.grpc.Metadata; +import io.grpc.NameResolver.ConfigOrError; +import io.grpc.Status; +import io.grpc.internal.JsonUtil; +import java.util.Map; + +/** + * Provider for the {@code autosharding_experimental} balancing policy. + * + *

Registering this on the classpath is what makes the policy reachable by name, both from a + * service config and from the xDS integration. + */ +@Internal +public final class AutoShardingLoadBalancerProvider extends LoadBalancerProvider { + @Override + public LoadBalancer newLoadBalancer(LoadBalancer.Helper helper) { + return new AutoShardingLoadBalancer(helper); + } + + @Override + public boolean isAvailable() { + return true; + } + + @Override + public int getPriority() { + return 5; + } + + @Override + public String getPolicyName() { + return "autosharding_experimental"; + } + + @Override + public ConfigOrError parseLoadBalancingPolicyConfig(Map rawConfig) { + try { + return parseLoadBalancingPolicyConfigInternal(rawConfig); + } catch (RuntimeException e) { + return ConfigOrError.fromError( + Status.UNAVAILABLE + .withCause(e) + .withDescription("Failed parsing configuration for " + getPolicyName())); + } + } + + /** Parses {@code AutoshardingLbConfig} from its JSON form, as specified by gRFC A119. */ + private ConfigOrError parseLoadBalancingPolicyConfigInternal(Map rawConfig) { + String channelFactoryKey = JsonUtil.getString(rawConfig, "channelFactoryKey"); + if (channelFactoryKey == null || channelFactoryKey.isEmpty()) { + return error("'channelFactoryKey' is required, LB policy config=" + rawConfig); + } + + String autoshardingTarget = JsonUtil.getString(rawConfig, "autoshardingTarget"); + if (autoshardingTarget == null || autoshardingTarget.isEmpty()) { + return error("'autoshardingTarget' is required, LB policy config=" + rawConfig); + } + + String keyHeaderName = JsonUtil.getString(rawConfig, "keyHeaderName"); + if (keyHeaderName == null || keyHeaderName.isEmpty()) { + return error("'keyHeaderName' is required, LB policy config=" + rawConfig); + } + Metadata.Key keyHeader; + try { + keyHeader = AutoShardingPicker.createKeyHeader(keyHeaderName); + } catch (IllegalArgumentException e) { + return error("'keyHeaderName' is not a valid header name: " + keyHeaderName); + } + + Boolean enableFallback = JsonUtil.getBoolean(rawConfig, "enableFallback"); + + Long initialAssignmentTimeoutNanos = + JsonUtil.getStringAsDuration(rawConfig, "initialAssignmentTimeout"); + if (initialAssignmentTimeoutNanos == null) { + initialAssignmentTimeoutNanos = + AutoShardingLoadBalancerConfig.DEFAULT_INITIAL_ASSIGNMENT_TIMEOUT_NANOS; + } else if (initialAssignmentTimeoutNanos < 0) { + return error( + "'initialAssignmentTimeout' must not be negative, LB policy config=" + rawConfig); + } + + return ConfigOrError.fromConfig( + new AutoShardingLoadBalancerConfig( + channelFactoryKey, + autoshardingTarget, + keyHeader, + enableFallback != null && enableFallback, + initialAssignmentTimeoutNanos)); + } + + private static ConfigOrError error(String description) { + return ConfigOrError.fromError( + Status.UNAVAILABLE.withDescription("autosharding: " + description)); + } +} diff --git a/autosharding/src/main/java/io/grpc/autosharding/AutoShardingPicker.java b/autosharding/src/main/java/io/grpc/autosharding/AutoShardingPicker.java index 842b88d3a52..5354f8b8853 100644 --- a/autosharding/src/main/java/io/grpc/autosharding/AutoShardingPicker.java +++ b/autosharding/src/main/java/io/grpc/autosharding/AutoShardingPicker.java @@ -29,32 +29,14 @@ import io.grpc.Status; import java.util.List; import java.util.concurrent.ThreadLocalRandom; -import javax.annotation.Nullable; import javax.annotation.concurrent.ThreadSafe; /** - * Subchannel picker for the auto-sharding load balancing policy. - * - *

Routes RPCs to backend endpoints based on a request metadata header key, matching against - * an immutable {@link SliceMap}. - * - *

This picker is intended for active routing and post-timeout fallback handling: - *

    - *
  • Pending Initial Assignment: During startup before the first assignment is received - * (and while the initial assignment timer is running), the load balancer handles RPC - * queuing polymorphically using a buffering picker in - * {@link io.grpc.ConnectivityState#CONNECTING}. - *
  • Active Routing: Once a valid assignment is received from the control plane, - * this picker routes RPCs according to the populated {@link SliceMap}. - *
  • Post-Timeout Fallback: If the initial assignment timer expires without an - * assignment, this picker is used with an empty {@link SliceMap} to either route across - * the {@code fallbackPool} (if fallback is enabled) or fail RPCs with - * {@link io.grpc.Status#UNAVAILABLE} (if fallback is disabled). - *
+ * Routes each RPC to an endpoint of the slice covering its sharding key. With fallback enabled, + * an RPC goes to any resolved endpoint instead when there is no assignment or the slice has no + * usable endpoint. A slice that the server assigned no endpoints fails the RPC either way. */ final class AutoShardingPicker extends SubchannelPicker { - private static final byte[] EMPTY_BYTES = new byte[0]; - @ThreadSafe @FunctionalInterface interface ThreadSafeRandom { @@ -81,39 +63,28 @@ public byte[] parseAsciiString(byte[] serialized) { private final ImmutableList endpoints; private final boolean[] sliceInFallback; private final boolean fallbackEnabled; - @Nullable private final Metadata.Key keyHeader; + private final Metadata.Key keyHeader; private final ThreadSafeRandom random; /** - * Pre-creates a {@link Metadata.Key} for the given key header name. + * Returns a key that reads {@code keyHeaderName}'s value as bytes: the binary value for a + * {@code -bin} header, and the ASCII bytes otherwise. * - * @param keyHeaderName the metadata header name, or {@code null}/empty if no header routing - * @return the pre-computed {@link Metadata.Key}, or {@code null} if keyHeaderName is null/empty + * @throws IllegalArgumentException if {@code keyHeaderName} is not a valid header name */ - @Nullable - static Metadata.Key createKeyHeader(@Nullable String keyHeaderName) { - if (keyHeaderName == null || keyHeaderName.isEmpty()) { - return null; - } else if (keyHeaderName.endsWith(Metadata.BINARY_HEADER_SUFFIX)) { + static Metadata.Key createKeyHeader(String keyHeaderName) { + if (keyHeaderName.endsWith(Metadata.BINARY_HEADER_SUFFIX)) { return Metadata.Key.of(keyHeaderName, Metadata.BINARY_BYTE_MARSHALLER); } else { return InternalMetadata.keyOf(keyHeaderName, RAW_ASCII_MARSHALLER); } } - /** - * Constructs an {@link AutoShardingPicker}. - * - * @param sliceMap the pre-built, immutable mapping from key ranges to endpoint indices - * @param endpoints the list of endpoint snapshots corresponding 1:1 to endpoint indices - * @param fallbackEnabled whether fallback routing to all resolved endpoints is enabled - * @param keyHeader the pre-parsed metadata header key used to extract the routing key - */ AutoShardingPicker( SliceMap sliceMap, List endpoints, boolean fallbackEnabled, - @Nullable Metadata.Key keyHeader) { + Metadata.Key keyHeader) { this(sliceMap, endpoints, fallbackEnabled, keyHeader, DEFAULT_RANDOM); } @@ -122,12 +93,12 @@ static Metadata.Key createKeyHeader(@Nullable String keyHeaderName) { SliceMap sliceMap, List endpoints, boolean fallbackEnabled, - @Nullable Metadata.Key keyHeader, + Metadata.Key keyHeader, ThreadSafeRandom random) { this.sliceMap = checkNotNull(sliceMap, "sliceMap"); this.endpoints = ImmutableList.copyOf(checkNotNull(endpoints, "endpoints")); this.fallbackEnabled = fallbackEnabled; - this.keyHeader = keyHeader; + this.keyHeader = checkNotNull(keyHeader, "keyHeader"); this.random = checkNotNull(random, "random"); boolean hasTransientFailure = false; @@ -164,7 +135,16 @@ private boolean isPoolInFallback(List indices) { @Override public PickResult pickSubchannel(PickSubchannelArgs args) { - byte[] key = extractKeyBytes(args.getHeaders()); + // The first value if the header was sent more than once; get() would return the last. + Iterable keys = args.getHeaders().getAll(keyHeader); + byte[] key = keys == null ? null : keys.iterator().next(); + if (key == null) { + // wait-for-ready RPCs keep waiting for a picker + // that can route them, and the others fail. + return PickResult.withError( + Status.UNAVAILABLE.withDescription( + "autosharding: request is missing the '" + keyHeader.name() + "' key header")); + } int sliceIdx = sliceMap.lookup(key); if (sliceIdx == -1) { @@ -178,12 +158,21 @@ public PickResult pickSubchannel(PickSubchannelArgs args) { } } + SliceMap.SliceEntry sliceEntry = sliceMap.getSlices().get(sliceIdx); + if (sliceEntry.isFallbackDisabled()) { + // A drop, so that wait-for-ready RPCs fail too instead of waiting on a range that the + // server has deliberately left unassigned. + return PickResult.withDrop( + Status.UNAVAILABLE.withDescription( + "autosharding: matching slice has fallback disabled by the sharding server" + + " (no endpoints assigned)")); + } + if (sliceInFallback[sliceIdx] && fallbackEnabled) { return pickFromEndpointIndices( sliceMap.getFallbackPool(), args, "No endpoints available in fallback pool"); } - SliceMap.SliceEntry sliceEntry = sliceMap.getSlices().get(sliceIdx); return pickFromEndpointIndices( sliceEntry.getEndpoints(), args, "No valid endpoints in slice and fallback disabled"); } @@ -223,12 +212,4 @@ private PickResult pickFromEndpointIndices( int firstEpIdx = indices.get(firstIndex); return endpoints.get(firstEpIdx).getPicker().pickSubchannel(args); } - - private byte[] extractKeyBytes(Metadata headers) { - if (keyHeader != null) { - byte[] val = headers.get(keyHeader); - return val != null ? val : EMPTY_BYTES; - } - return EMPTY_BYTES; - } } diff --git a/autosharding/src/main/java/io/grpc/autosharding/AutoshardingClient.java b/autosharding/src/main/java/io/grpc/autosharding/AutoshardingClient.java new file mode 100644 index 00000000000..04280ca6d52 --- /dev/null +++ b/autosharding/src/main/java/io/grpc/autosharding/AutoshardingClient.java @@ -0,0 +1,464 @@ +/* + * Copyright 2026 The gRPC Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.grpc.autosharding; + +import static com.google.common.base.Preconditions.checkNotNull; +import static com.google.common.base.Preconditions.checkState; + +import com.google.cloud.autosharding.v1.AssignmentAck; +import com.google.cloud.autosharding.v1.AssignmentChunk; +import com.google.cloud.autosharding.v1.AutoshardingServiceGrpc; +import com.google.cloud.autosharding.v1.InitialClientConfig; +import com.google.cloud.autosharding.v1.WatchShardingAssignmentRequest; +import com.google.cloud.autosharding.v1.WatchShardingAssignmentResponse; +import com.google.common.annotations.VisibleForTesting; +import com.google.common.base.Stopwatch; +import com.google.common.base.Supplier; +import io.grpc.Channel; +import io.grpc.Status; +import io.grpc.SynchronizationContext; +import io.grpc.SynchronizationContext.ScheduledHandle; +import io.grpc.internal.BackoffPolicy; +import io.grpc.stub.ClientCallStreamObserver; +import io.grpc.stub.ClientResponseObserver; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; +import java.util.logging.Level; +import java.util.logging.Logger; +import javax.annotation.Nullable; +import javax.annotation.concurrent.NotThreadSafe; + +/** + * Streams assignments from the sharding service over {@code WatchShardingAssignment}: reassembles, + * validates and acknowledges them, and hands valid {@link Assignment}s to an + * {@link AssignmentWatcher}. See gRFC A119, "AutoshardingClient". + * + *

Not thread-safe: every method must be called on the {@link SynchronizationContext} given to + * the constructor, which is also where the watcher is called. + */ +@NotThreadSafe +final class AutoshardingClient { + private static final Logger logger = Logger.getLogger(AutoshardingClient.class.getName()); + + /** The limit {@code autosharding.proto} places on {@code AssignmentAck.error_message}. */ + private static final int MAX_ERROR_MESSAGE_CODE_POINTS = 512; + + /** + * Receives the state this client reports: valid assignments, or an error while it has none. + * Both callbacks are invoked on the {@link SynchronizationContext}. + */ + interface AssignmentWatcher { + /** Called with a newly accepted assignment. */ + void onAssignment(Assignment assignment); + + /** + * Called when this client has no valid assignment to offer: its stream failed, the sharding + * service sent an assignment with no usable slice, or the initial assignment timer fired. + * Never called once this client has reported an assignment, since the load balancer keeps + * using that one. + */ + void onError(Status error); + } + + private final SynchronizationContext syncContext; + private final ScheduledExecutorService timerService; + private final BackoffPolicy.Provider backoffPolicyProvider; + private final Stopwatch retryStopwatch; + private final AssignmentWatcher watcher; + private final String clientUuid; + private final AutoshardingServiceGrpc.AutoshardingServiceStub stub; + private final String target; + private final long initialAssignmentTimeoutNanos; + + /** + * Generation of the most recent accepted assignment, sent to the server so that it can skip + * resending one the client already has. Zero, which the proto reads as unset, until an + * assignment is accepted; only a greater generation is accepted. + */ + private long latestGeneration; + + @Nullable private BackoffPolicy retryBackoffPolicy; + @Nullable private ScheduledHandle retryTimer; + @Nullable private ScheduledHandle initialAssignmentTimer; + @Nullable private AutoshardingStream stream; + private boolean shutdown; + + /** + * Constructs an {@link AutoshardingClient}. No stream is created until {@link #start()}. + * + * @param clientUuid a UUID generated once by the parent load balancer and reused across all + * stream restarts + * @param syncContext the context on which all state is mutated and callbacks are delivered + * @param timerService used to schedule stream retries and the initial assignment timer + * @param backoffPolicyProvider supplies the exponential backoff sequence for stream retries + * @param stopwatchSupplier supplies the stopwatch measuring time spent in a stream attempt + * @param channel the channel to the sharding service, leased from the {@link ChannelFactory} + * by the parent load balancer + * @param target the autosharding target, with any {@code %s} token already substituted + * @param initialAssignmentTimeoutNanos how long to wait for the first assignment before + * reporting an error + * @param watcher receives validated assignments and errors + */ + AutoshardingClient( + String clientUuid, + SynchronizationContext syncContext, + ScheduledExecutorService timerService, + BackoffPolicy.Provider backoffPolicyProvider, + Supplier stopwatchSupplier, + Channel channel, + String target, + long initialAssignmentTimeoutNanos, + AssignmentWatcher watcher) { + this.clientUuid = checkNotNull(clientUuid, "clientUuid"); + this.syncContext = checkNotNull(syncContext, "syncContext"); + this.timerService = checkNotNull(timerService, "timerService"); + this.backoffPolicyProvider = checkNotNull(backoffPolicyProvider, "backoffPolicyProvider"); + this.retryStopwatch = checkNotNull(stopwatchSupplier, "stopwatchSupplier").get(); + // wait_for_ready keeps the stream pending through transient connectivity failures instead + // of failing it, which recovers faster than applying backoff around stream creation. + this.stub = + AutoshardingServiceGrpc.newStub(checkNotNull(channel, "channel")).withWaitForReady(); + this.target = checkNotNull(target, "target"); + this.initialAssignmentTimeoutNanos = initialAssignmentTimeoutNanos; + this.watcher = checkNotNull(watcher, "watcher"); + } + + /** + * Starts the initial assignment timer and opens the {@code WatchShardingAssignment} stream. + * Call once, on the sync context. + */ + void start() { + syncContext.throwIfNotInThisSynchronizationContext(); + checkState(stream == null, "already started"); + // Armed before the stream opens, so that an assignment delivered right away cancels it. + initialAssignmentTimer = + syncContext.schedule( + this::onInitialAssignmentTimeout, + initialAssignmentTimeoutNanos, + TimeUnit.NANOSECONDS, + timerService); + startStream(); + } + + /** + * Cancels the stream, any pending retry and the initial assignment timer. The channel is not + * touched: the parent load balancer holds its lease. + */ + void shutdown() { + syncContext.throwIfNotInThisSynchronizationContext(); + if (shutdown) { + return; + } + shutdown = true; + cancelRetryTimer(); + cancelInitialAssignmentTimer(); + if (stream != null) { + stream.close(Status.CANCELLED.withDescription("AutoshardingClient shutdown")); + stream = null; + } + } + + /** Returns the target this client asks the sharding service for. */ + String getTarget() { + return target; + } + + @VisibleForTesting + long getLatestGeneration() { + return latestGeneration; + } + + private void onInitialAssignmentTimeout() { + initialAssignmentTimer = null; + reportError( + Status.UNAVAILABLE.withDescription( + "autosharding: timed out waiting for the initial assignment from the sharding" + + " service")); + } + + private void cancelInitialAssignmentTimer() { + if (initialAssignmentTimer != null) { + initialAssignmentTimer.cancel(); + initialAssignmentTimer = null; + } + } + + /** + * Reports an error unless this client has already reported an assignment, which gRFC A119 has + * the load balancer keep using in preference to any later error. + */ + private void reportError(Status error) { + if (shutdown || latestGeneration > 0) { + return; + } + watcher.onError(error); + } + + private void startStream() { + if (shutdown) { + return; + } + checkState(stream == null, "previous stream has not been cleared yet"); + retryStopwatch.reset().start(); + stream = new AutoshardingStream(); + stream.start(); + } + + private void cancelRetryTimer() { + if (retryTimer != null) { + if (retryTimer.isPending()) { + retryTimer.cancel(); + } + retryTimer = null; + } + } + + /** + * Schedules the next stream attempt. Backoff only applies to streams that closed without + * delivering a good logical assignment; one that did reconnects right away and the sequence + * starts over on the next failure. + */ + private void scheduleRetry(boolean receivedGoodAssignment) { + if (shutdown) { + return; + } + long delayNanos; + if (receivedGoodAssignment) { + retryBackoffPolicy = null; + delayNanos = 0; + } else { + if (retryBackoffPolicy == null) { + retryBackoffPolicy = backoffPolicyProvider.get(); + } + // The backoff sequence bounds the interval between consecutive stream starts, so the actual + // delay is reduced by however long the previous attempt lasted. + delayNanos = + Math.max( + 0, + retryBackoffPolicy.nextBackoffNanos() + - retryStopwatch.elapsed(TimeUnit.NANOSECONDS)); + } + // The retry always goes through the timer service, even when no delay remains, so that a + // channel failing calls synchronously cannot drive unbounded recursion between startStream() + // and handleStreamClosed(). + retryTimer = + syncContext.schedule(this::startStream, delayNanos, TimeUnit.NANOSECONDS, timerService); + } + + /** + * A single {@code WatchShardingAssignment} stream. Everything here runs on the sync context: + * the stream's events arrive on gRPC threads at {@link ResponseObserver}, which hands each one + * over. + */ + private final class AutoshardingStream { + + /** + * Chunks received since the last {@code AssignmentMetadata}. A chunk's slices reference + * endpoint indices into the list combined across all chunks, so chunks cannot be used until + * the assignment is terminated by an {@code AssignmentMetadata} message. + */ + private final List bufferedChunks = new ArrayList<>(); + + /** The sending half of the stream, set by {@link ResponseObserver#beforeStart}. */ + private ClientCallStreamObserver requestStream; + + /** + * Whether this stream delivered an assignment the load balancer could use, the only thing + * that resets the retry backoff. Stale assignments and ones with no usable slice don't count. + */ + private boolean receivedGoodAssignment; + private boolean closed; + + void start() { + stub.watchShardingAssignment(new ResponseObserver()); + // The call is started inside the above, so the config cannot go out from beforeStart(). + sendInitialClientConfig(); + } + + private void sendInitialClientConfig() { + WatchShardingAssignmentRequest request = + WatchShardingAssignmentRequest.newBuilder() + .setInitialClientConfig( + InitialClientConfig.newBuilder() + .setTarget(target) + .setClientUuid(clientUuid) + .setLatestGeneration(latestGeneration)) + .build(); + requestStream.onNext(request); + } + + private void handleResponse(WatchShardingAssignmentResponse response) { + if (closed) { + return; + } + if (response.hasChunk()) { + bufferedChunks.add(response.getChunk()); + } else if (response.hasMetadata()) { + handleAssignmentComplete(response.getMetadata().getGeneration()); + } else if (!response.hasConfig()) { + logger.log(Level.FINE, "Ignoring autosharding response with no field set"); + } + // LoadReportingConfig is intentionally ignored; load reporting is not yet supported. + } + + /** + * Validates and acknowledges the buffered chunks terminated by an {@code AssignmentMetadata} + * message, following the outcome table in gRFC A119, "Handling assignments from the + * Autosharding server". Every assignment is acknowledged, but only a newer one with at least + * one usable slice reaches the load balancer. + */ + private void handleAssignmentComplete(long generation) { + List chunks = new ArrayList<>(bufferedChunks); + bufferedChunks.clear(); + + // Generations are monotonically increasing, so anything not above the latest accepted one + // is stale; before anything is accepted that means zero or below. It is + // still acknowledged, so that the server does not wait on a reply that never comes. + if (generation <= latestGeneration) { + String error = + String.format( + "stale generation %s: not greater than the latest generation %s", + generation, latestGeneration); + logger.log(Level.FINE, "Dropping autosharding assignment: {0}", error); + sendAck(generation, false, error); + return; + } + + AssignmentParser.Result result = AssignmentParser.parse(chunks); + if (result.assignment == null) { + logger.log( + Level.WARNING, + "Rejecting autosharding assignment with generation {0}, no usable slices: {1}", + new Object[] {generation, result.errorMessage}); + sendAck(generation, false, result.errorMessage); + reportError( + Status.UNAVAILABLE.withDescription( + "autosharding: no usable slices in assignment with generation " + + generation + + ": " + + result.errorMessage)); + return; + } + + if (result.errorMessage != null) { + logger.log( + Level.WARNING, + "Accepting autosharding assignment with generation {0} after dropping slices: {1}", + new Object[] {generation, result.errorMessage}); + } + sendAck(generation, true, result.errorMessage); + latestGeneration = generation; + receivedGoodAssignment = true; + cancelInitialAssignmentTimer(); + watcher.onAssignment(result.assignment); + } + + private void sendAck(long generation, boolean accepted, @Nullable String errorMessage) { + AssignmentAck.Builder ack = + AssignmentAck.newBuilder().setGeneration(generation).setAccepted(accepted); + if (errorMessage != null) { + ack.setErrorMessage(truncateErrorMessage(errorMessage)); + } + requestStream.onNext( + WatchShardingAssignmentRequest.newBuilder().setAssignmentAck(ack).build()); + } + + private void handleStreamClosed(Status status) { + if (closed) { + return; + } + closed = true; + logger.log( + Level.FINE, + "Autosharding stream closed with status {0}: {1}", + new Object[] {status.getCode(), status.getDescription()}); + bufferedChunks.clear(); + if (stream == this) { + stream = null; + reportError( + Status.UNAVAILABLE + .withDescription( + "autosharding: sharding service stream failed: " + + status.getCode() + + ": " + + status.getDescription()) + .withCause(status.getCause())); + scheduleRetry(receivedGoodAssignment); + } + } + + /** Cancels the stream without scheduling a retry. Used when the client shuts down. */ + void close(Status status) { + if (closed) { + return; + } + closed = true; + bufferedChunks.clear(); + requestStream.cancel(status.getDescription(), status.getCause()); + } + + /** Receives the stream's events on gRPC threads and hands each one to the sync context. */ + private final class ResponseObserver + implements ClientResponseObserver< + WatchShardingAssignmentRequest, WatchShardingAssignmentResponse> { + @Override + public void beforeStart( + ClientCallStreamObserver requestStream) { + // Called from inside start(), so still on the sync context. + AutoshardingStream.this.requestStream = requestStream; + } + + @Override + public void onNext(WatchShardingAssignmentResponse response) { + syncContext.execute(() -> handleResponse(response)); + } + + @Override + public void onError(Throwable t) { + syncContext.execute(() -> handleStreamClosed(Status.fromThrowable(t))); + } + + @Override + public void onCompleted() { + syncContext.execute( + () -> + handleStreamClosed( + Status.UNAVAILABLE.withDescription("autosharding stream closed by server"))); + } + } + } + + /** + * Cuts {@code message} to {@link #MAX_ERROR_MESSAGE_CODE_POINTS} code points. A backstop only: + * {@link AssignmentParser} already sizes its messages to fit. + */ + private static String truncateErrorMessage(String message) { + // A string never has more code points than chars, so this settles the common case without + // walking it. + if (message.length() <= MAX_ERROR_MESSAGE_CODE_POINTS) { + return message; + } + if (message.codePointCount(0, message.length()) <= MAX_ERROR_MESSAGE_CODE_POINTS) { + return message; + } + // Cutting on a code point boundary rather than a char boundary keeps a surrogate pair from + // being split into an unpaired surrogate, which does not survive UTF-8 encoding. + return message.substring(0, message.offsetByCodePoints(0, MAX_ERROR_MESSAGE_CODE_POINTS)); + } +} diff --git a/autosharding/src/main/java/io/grpc/autosharding/ChannelFactory.java b/autosharding/src/main/java/io/grpc/autosharding/ChannelFactory.java new file mode 100644 index 00000000000..33e95b74861 --- /dev/null +++ b/autosharding/src/main/java/io/grpc/autosharding/ChannelFactory.java @@ -0,0 +1,66 @@ +/* + * Copyright 2026 The gRPC Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.grpc.autosharding; + +import io.grpc.Channel; +import io.grpc.Internal; + +/** + * Creates channels to the autosharding service. + * + *

The LB policy configuration carries only an opaque {@code channel_factory_key}; the factory + * is responsible for translating that key into a fully configured channel. Credentials and + * per-request metadata are deliberately kept out of the configuration so that a compromised + * control plane cannot escalate privileges, per gRFC A102. Implementations must therefore ensure + * the key uniquely encodes every parameter needed to create the channel. + * + *

Channels are leased rather than owned: implementations may share one channel between + * several leases, so a caller must never shut a channel down directly and must instead close its + * lease. + * + *

Injected into the LB policy through + * {@link AutoShardingAttributes#ATTR_CHANNEL_FACTORY}. In xDS deployments the + * {@code cds_experimental} LB policy supplies it; in non-xDS deployments the application does. + * + *

See gRFC A119, "Creating a gRPC Channel to the Autosharding Service". + */ +@Internal +public interface ChannelFactory { + + /** + * Returns a lease on a channel to the sharding service identified by {@code channelFactoryKey}. + * The caller must close the lease once it no longer uses the channel. + * + * @throws IllegalArgumentException if the key is not recognized or not allowed + * @throws RuntimeException if the channel cannot be created for any other reason + */ + ChannelLease createChannel(String channelFactoryKey); + + /** A claim on a channel returned by {@link #createChannel}. */ + interface ChannelLease extends AutoCloseable { + + /** Returns the leased channel, which must not be used once the lease is closed. */ + Channel channel(); + + /** + * Gives up the claim on the channel. Whether the channel is then shut down is up to the + * factory. Closing a lease that is already closed has no effect. + */ + @Override + void close(); + } +} diff --git a/autosharding/src/main/java/io/grpc/autosharding/EndpointMap.java b/autosharding/src/main/java/io/grpc/autosharding/EndpointMap.java new file mode 100644 index 00000000000..8a4615d0f81 --- /dev/null +++ b/autosharding/src/main/java/io/grpc/autosharding/EndpointMap.java @@ -0,0 +1,426 @@ +/* + * Copyright 2026 The gRPC Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.grpc.autosharding; + +import static com.google.common.base.Preconditions.checkNotNull; +import static io.grpc.ConnectivityState.CONNECTING; +import static io.grpc.ConnectivityState.IDLE; +import static io.grpc.ConnectivityState.READY; +import static io.grpc.ConnectivityState.TRANSIENT_FAILURE; + +import com.google.common.base.MoreObjects; +import com.google.common.collect.ImmutableList; +import com.google.common.net.HostAndPort; +import com.google.common.net.InetAddresses; +import io.grpc.Attributes; +import io.grpc.ConnectivityState; +import io.grpc.EquivalentAddressGroup; +import io.grpc.InternalEquivalentAddressGroup; +import io.grpc.LoadBalancer.FixedResultPicker; +import io.grpc.LoadBalancer.Helper; +import io.grpc.LoadBalancer.PickResult; +import io.grpc.LoadBalancer.ResolvedAddresses; +import io.grpc.LoadBalancer.SubchannelPicker; +import io.grpc.LoadBalancerProvider; +import io.grpc.Status; +import io.grpc.SynchronizationContext; +import io.grpc.util.ForwardingLoadBalancerHelper; +import io.grpc.util.LazyLoadBalancer; +import java.net.InetSocketAddress; +import java.net.SocketAddress; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.logging.Level; +import java.util.logging.Logger; +import javax.annotation.concurrent.NotThreadSafe; + +/** + * Owns one lazily-created {@code pick_first} child load balancer per resolved endpoint, keyed by + * endpoint hostname, and tracks the connectivity state and picker most recently reported by each + * child. + * + *

Endpoint indices

+ * + *

Endpoints are identified by a dense index in {@code [0, size)}: their position in the list + * most recently passed to {@link #updateEndpoints}, after duplicate hostnames are dropped. + * {@link #indexOf} and {@link #toPickerEndpoints} agree as long as no {@link #updateEndpoints} + * call comes between them. + * + *

Threading model

+ * + *

This class is not thread-safe. Every method must be called from the + * {@link SynchronizationContext} of the {@link Helper} supplied at construction. The sole + * exception is {@link PickerEndpoint#requestConnection}, reached from RPC threads through the + * snapshots returned by {@link #toPickerEndpoints}; it hops onto the synchronization context + * before touching any state here. + */ +@NotThreadSafe +final class EndpointMap { + private static final Logger logger = Logger.getLogger(EndpointMap.class.getName()); + + private final Helper helper; + private final LoadBalancerProvider childProvider; + private final Runnable childStateListener; + + // The endpoints, in index order: an endpoint's index is its position here, never stored. + // Rebuilt wholesale by updateEndpoints. + private final List holders = new ArrayList<>(); + + // Hostname to its position in holders. Derived from holders and rebuilt with it; exists so + // that translating an assignment's hostnames into indices stays linear in the assignment + // size, rather than scanning the endpoints once per name. + private final Map indexByHostname = new HashMap<>(); + + /** + * Set while {@link #updateEndpoints} hands children their addresses. Their state updates are + * still recorded but not forwarded, since the caller publishes once afterwards. + */ + private boolean rebuilding; + + /** + * Constructs an empty map. + * + * @param helper the parent LB policy's helper, used for its synchronization context and passed + * through to child load balancers + * @param childProvider provides the per-endpoint child load balancer, normally {@code + * pick_first}. It is wrapped in a {@link LazyLoadBalancer} here, so a child is not created + * until it is first asked to connect + * @param childStateListener run after a child reports a new connectivity state or picker. + * Invoked on the synchronization context, never during {@link #updateEndpoints} or after + * {@link #shutdown} + */ + EndpointMap(Helper helper, LoadBalancerProvider childProvider, Runnable childStateListener) { + this.helper = checkNotNull(helper, "helper"); + this.childProvider = checkNotNull(childProvider, "childProvider"); + this.childStateListener = checkNotNull(childStateListener, "childStateListener"); + } + + /** + * Replaces the set of endpoints, assigning each a new index. + * + *

An endpoint whose hostname appears in both the old and the new set keeps its child load + * balancer, along with its connections and last reported state; only its addresses and index + * are refreshed. Endpoints that disappear have their child load balancers shut down. New + * endpoints start out IDLE with no child load balancer instantiated. + * + *

If several endpoints resolve to the same hostname, the first one wins and the rest are + * dropped. + * + *

Children handed new addresses here often report a connectivity state before this method + * returns. Those reports are recorded but not forwarded to the {@code childStateListener}, so + * that one resolver update produces one picker rather than one per endpoint. The + * caller must therefore publish a picker itself once this returns, or the channel is + * left holding a picker built from the previous endpoint set. + * + * @param endpoints the endpoints from the resolver, in the order the resolver supplied them + * @param attributes the resolver attributes, forwarded to every child load balancer + */ + void updateEndpoints(List endpoints, Attributes attributes) { + Map addressesByHostname = new LinkedHashMap<>(); + for (EquivalentAddressGroup endpoint : endpoints) { + String hostname = hostnameOf(endpoint); + if (addressesByHostname.putIfAbsent(hostname, endpoint) != null) { + logger.log(Level.FINE, "Dropping duplicate endpoint for hostname {0}", hostname); + } + } + + // Children of endpoints the resolver no longer reports are shut down and dropped. + Map survivors = new HashMap<>(); + for (EndpointHolder holder : holders) { + if (addressesByHostname.containsKey(holder.hostname)) { + survivors.put(holder.hostname, holder); + } else { + holder.shutdown(); + } + } + + // Install the whole endpoint set and its indices before touching any child. A child given + // addresses in the second pass can call back in synchronously, and everything it can reach + // -- size(), indexOf(), toPickerEndpoints() -- has to already agree on the new set. + holders.clear(); + indexByHostname.clear(); + for (String hostname : addressesByHostname.keySet()) { + EndpointHolder survivor = survivors.get(hostname); + indexByHostname.put(hostname, holders.size()); + holders.add(survivor != null ? survivor : new EndpointHolder(hostname)); + } + + rebuilding = true; + try { + for (EndpointHolder holder : holders) { + holder.updateAddresses(addressesByHostname.get(holder.hostname), attributes); + } + } finally { + rebuilding = false; + } + } + + /** Returns the number of endpoints currently held. */ + int size() { + return holders.size(); + } + + /** + * Returns the index of {@code hostname}, or {@code -1} if no endpoint with that hostname is + * currently held. Used to translate the hostnames in an {@link Assignment} into the indices + * that {@link SliceMap} and {@link AutoShardingPicker} work with. + */ + int indexOf(String hostname) { + Integer index = indexByHostname.get(hostname); + return index == null ? -1 : index; + } + + /** + * Returns an immutable snapshot of the current endpoint states, where element {@code i} + * describes the endpoint with index {@code i}. + * + *

The snapshot is safe to hand to a picker running on RPC threads: it captures the + * connectivity state and picker by value, and reaches back into this class only through + * {@link PickerEndpoint#requestConnection}. + */ + ImmutableList toPickerEndpoints() { + ImmutableList.Builder snapshot = + ImmutableList.builderWithExpectedSize(holders.size()); + for (EndpointHolder holder : holders) { + snapshot.add(holder.toPickerEndpoint()); + } + return snapshot.build(); + } + + /** + * Returns the aggregated connectivity state to report for the channel, using the {@code + * ring_hash} rules from gRFC A42 that gRFC A119 adopts: + * + *

    + *
  1. at least one endpoint READY, report READY; + *
  2. two or more endpoints TRANSIENT_FAILURE, report TRANSIENT_FAILURE; + *
  3. at least one endpoint CONNECTING, report CONNECTING; + *
  4. exactly one endpoint TRANSIENT_FAILURE and more than one endpoint, report CONNECTING; + *
  5. at least one endpoint IDLE, report IDLE; + *
  6. otherwise report TRANSIENT_FAILURE. + *
+ * + *

An empty map reports TRANSIENT_FAILURE, matching rule 6. + */ + ConnectivityState aggregateConnectivityState() { + int connecting = 0; + int idle = 0; + int transientFailure = 0; + for (EndpointHolder holder : holders) { + switch (holder.state) { + case READY: + return READY; + case CONNECTING: + connecting++; + break; + case IDLE: + idle++; + break; + case TRANSIENT_FAILURE: + transientFailure++; + break; + default: + break; + } + } + if (transientFailure >= 2) { + return TRANSIENT_FAILURE; + } + if (connecting > 0) { + return CONNECTING; + } + if (transientFailure == 1 && holders.size() > 1) { + return CONNECTING; + } + if (idle > 0) { + return IDLE; + } + return TRANSIENT_FAILURE; + } + + /** + * Starts connecting on one IDLE endpoint if the aggregated state is CONNECTING or + * TRANSIENT_FAILURE and no endpoint is already CONNECTING; otherwise does nothing, so it can be + * called after every child state update and resolver update. + * + *

Because this policy only connects in response to picks, such an aggregated state could + * otherwise persist with nothing in flight to resolve it, so gRFC A119 has the policy nudge a + * single endpoint. An IDLE or READY aggregate is left alone, which keeps the policy lazy. + */ + void maybeWakeUpIdleEndpoint() { + ConnectivityState aggregate = aggregateConnectivityState(); + if (aggregate != CONNECTING && aggregate != TRANSIENT_FAILURE) { + return; + } + EndpointHolder firstIdle = null; + for (EndpointHolder holder : holders) { + if (holder.state == CONNECTING) { + return; + } + if (firstIdle == null && holder.state == IDLE) { + firstIdle = holder; + } + } + if (firstIdle != null) { + firstIdle.requestConnection(); + } + } + + /** Shuts down every child load balancer and empties the map. Idempotent. */ + void shutdown() { + for (EndpointHolder holder : holders) { + holder.shutdown(); + } + holders.clear(); + indexByHostname.clear(); + } + + /** + * Returns the hostname identifying {@code endpoint}. Falls back to the endpoint's first + * address when the hostname attribute from gRFC A81 is absent, per gRFC A119. + */ + private static String hostnameOf(EquivalentAddressGroup endpoint) { + String hostname = + endpoint.getAttributes().get(InternalEquivalentAddressGroup.ATTR_ADDRESS_NAME); + return hostname != null ? hostname : addressName(endpoint.getAddresses().get(0)); + } + + /** + * Formats an address as {@code ip:port}, with IPv6 compressed and in brackets, to match how an + * assignment names endpoints. {@link InetSocketAddress#toString()} would add a {@code /} and + * any hostname. + */ + private static String addressName(SocketAddress address) { + if (!(address instanceof InetSocketAddress)) { + return address.toString(); + } + InetSocketAddress inetAddress = (InetSocketAddress) address; + String host = + inetAddress.isUnresolved() + ? inetAddress.getHostString() + : InetAddresses.toAddrString(inetAddress.getAddress()); + return HostAndPort.fromParts(host, inetAddress.getPort()).toString(); + } + + @Override + public String toString() { + return MoreObjects.toStringHelper(this).add("endpoints", holders).toString(); + } + + /** + * The child load balancer for a single endpoint, together with the connectivity state and + * picker it most recently reported. + */ + private final class EndpointHolder { + private final String hostname; + private final LazyLoadBalancer childLb; + private ConnectivityState state = IDLE; + private SubchannelPicker picker = new FixedResultPicker(PickResult.withNoResult()); + private boolean childShutdown; + + EndpointHolder(String hostname) { + this.hostname = hostname; + this.childLb = new LazyLoadBalancer(new ChildHelper(), childProvider); + } + + /** Captures the current state for use by a picker on RPC threads. */ + PickerEndpoint toPickerEndpoint() { + return new PickerEndpoint(state, picker, this::exitIdle); + } + + void updateAddresses(EquivalentAddressGroup endpoint, Attributes attributes) { + Status status = + childLb.acceptResolvedAddresses( + ResolvedAddresses.newBuilder() + .setAddresses(ImmutableList.of(endpoint)) + .setAttributes(attributes) + .build()); + if (!status.isOk()) { + // pick_first only rejects an address list it cannot use at all, which should not happen + // for the single well-formed endpoint we pass. Report it rather than silently dropping + // it; the endpoint simply stays in whatever state it was already in. + logger.log( + Level.WARNING, + "Child load balancer for endpoint {0} rejected its addresses: {1}", + new Object[] {hostname, status}); + } + } + + /** Starts connecting if this endpoint is IDLE. */ + void requestConnection() { + if (childShutdown || state != IDLE) { + return; + } + childLb.requestConnection(); + } + + /** + * The {@link PickerEndpoint.ExitIdler} handed to pickers. Called from RPC threads, so it hops + * onto the synchronization context, where {@link #requestConnection} re-checks the state; + * that makes repeated calls, and calls for a removed endpoint, harmless. + */ + private void exitIdle() { + helper.getSynchronizationContext().execute(this::requestConnection); + } + + void shutdown() { + if (childShutdown) { + return; + } + // Set before shutting the child down: a child may report from inside its own shutdown(), + // and this flag is what keeps that report away from the listener, both here and for the + // endpoints updateEndpoints() removes before it sets rebuilding. + childShutdown = true; + childLb.shutdown(); + } + + @Override + public String toString() { + return MoreObjects.toStringHelper(this) + .add("hostname", hostname) + .add("state", state) + .toString(); + } + + /** + * Intercepts the child's balancing state so that it is recorded here instead of being + * published straight to the channel. The LB policy aggregates across all endpoints and + * publishes a single state and picker of its own. + */ + private final class ChildHelper extends ForwardingLoadBalancerHelper { + @Override + protected Helper delegate() { + return helper; + } + + @Override + public void updateBalancingState(ConnectivityState newState, SubchannelPicker newPicker) { + if (childShutdown) { + return; + } + state = newState; + picker = newPicker; + if (!rebuilding) { + childStateListener.run(); + } + } + } + } +} diff --git a/autosharding/src/main/java/io/grpc/autosharding/PickerEndpoint.java b/autosharding/src/main/java/io/grpc/autosharding/PickerEndpoint.java index d85189d222e..843112e3128 100644 --- a/autosharding/src/main/java/io/grpc/autosharding/PickerEndpoint.java +++ b/autosharding/src/main/java/io/grpc/autosharding/PickerEndpoint.java @@ -23,14 +23,10 @@ import io.grpc.LoadBalancer.SubchannelPicker; import javax.annotation.Nullable; -/** - * Immutable snapshot of endpoint state used by {@link AutoShardingPicker}. - */ +/** Immutable snapshot of endpoint state used by {@link AutoShardingPicker}. */ final class PickerEndpoint { - /** - * Callback interface to trigger connection attempts on an IDLE endpoint's child balancer. - */ + /** Callback interface to trigger connection attempts on an IDLE endpoint's child balancer. */ @FunctionalInterface interface ExitIdler { /** @@ -51,7 +47,8 @@ interface ExitIdler { * * @param state the current connectivity state of the endpoint * @param picker the latest subchannel picker for the endpoint - * @param exitIdler a callback to trigger an IDLE child balancer to start connecting + * @param exitIdler a callback to trigger an IDLE child balancer to start connecting, or null + * if the endpoint cannot be asked to connect */ PickerEndpoint( ConnectivityState state, diff --git a/autosharding/src/main/java/io/grpc/autosharding/SliceMap.java b/autosharding/src/main/java/io/grpc/autosharding/SliceMap.java index b5e640492c2..cf373f20e6c 100644 --- a/autosharding/src/main/java/io/grpc/autosharding/SliceMap.java +++ b/autosharding/src/main/java/io/grpc/autosharding/SliceMap.java @@ -20,56 +20,46 @@ import com.google.common.collect.ImmutableList; import com.google.common.primitives.UnsignedBytes; -import java.util.ArrayList; import java.util.Comparator; import java.util.List; import javax.annotation.Nullable; /** - * An immutable lookup structure mapping application routing keys to slice indices. - * - *

The assignment provider guarantees that the assignment is pre-validated, gap-free, - * non-overlapping, and covers the entire keyspace {@code ["" .. inf)}. - *

    - *
  • The first slice's {@code startKey} is expected to be {@code new byte[0]} ({@code ""}).
  • - *
  • Unassigned key ranges (gaps) returned by the autosharding server are filled as slice - * entries with an empty {@code endpoints} list.
  • - *
  • Endpoint indices in {@link SliceEntry#getEndpoints()} and {@link #getFallbackPool()} - * are non-negative indices corresponding 1:1 to the endpoint snapshot list in - * {@link AutoShardingPicker}.
  • - *
- * - *

Behavior on Invalid or Edge-case Inputs: - *

    - *
  • Empty slices list: {@link #lookup(byte[])} returns {@code -1}, allowing - * {@link AutoShardingPicker} to fall back to the fallback pool or fail with UNAVAILABLE.
  • - *
  • Key smaller than first slice start key: {@link #lookup(byte[])} returns {@code -1} - * if the first slice's {@code startKey} is not {@code ""} and the key precedes it.
  • - *
  • Null key: Treated as an empty byte array ({@code new byte[0]}).
  • - *
  • Unsorted slices: The constructor automatically sorts slices lexicographically - * using unsigned byte comparison.
  • - *
  • Null constructor arguments: Throws {@link NullPointerException} if {@code slices}, - * {@code fallbackPool}, {@code startKey}, or {@code endpoints} is {@code null}.
  • - *
+ * Immutable map from sharding keys to slices, looked up by binary search over the slices' start + * keys. The slices, if any, are sorted by start key and cover the whole keyspace; their endpoint + * indices refer to the picker's endpoint list. */ final class SliceMap { /** - * Represents a single key-range slice mapping to endpoint indices in the picker. + * Represents a single key-range slice mapping to endpoint indices in the picker. Its start key + * array is shared rather than copied, and must not be modified. */ static final class SliceEntry { private final byte[] startKey; private final ImmutableList endpoints; + private final boolean fallbackDisabled; /** - * Constructs a {@link SliceEntry}. + * Constructs a {@link SliceEntry} that may fall back. * * @param startKey the inclusive start key of the slice * @param endpoints the list of endpoint indices assigned to this slice */ SliceEntry(byte[] startKey, List endpoints) { - this.startKey = checkNotNull(startKey, "startKey").clone(); + this(startKey, endpoints, false); + } + + /** + * Constructs a {@link SliceEntry}. + * + * @param fallbackDisabled whether picks for this slice must fail rather than fall back, as + * when the server assigned the slice no endpoints + */ + SliceEntry(byte[] startKey, List endpoints, boolean fallbackDisabled) { + this.startKey = checkNotNull(startKey, "startKey"); this.endpoints = ImmutableList.copyOf(checkNotNull(endpoints, "endpoints")); + this.fallbackDisabled = fallbackDisabled; } byte[] getStartKey() { @@ -79,6 +69,10 @@ byte[] getStartKey() { ImmutableList getEndpoints() { return endpoints; } + + boolean isFallbackDisabled() { + return fallbackDisabled; + } } private static final Comparator UNSIGNED_BYTES_COMPARATOR = @@ -87,22 +81,17 @@ ImmutableList getEndpoints() { private final ImmutableList slices; private final ImmutableList fallbackPool; - private final long generation; /** * Constructs an immutable {@link SliceMap}. * - * @param slices the pre-validated list of key-range slice entries + * @param slices the pre-validated list of key-range slice entries, in ascending unsigned + * {@code startKey} order as produced by {@link AssignmentParser} * @param fallbackPool the list of all available endpoint indices for fallback routing - * @param generation the snapshot generation number from the assignment */ - SliceMap(List slices, List fallbackPool, long generation) { - List sortedSlices = new ArrayList<>(checkNotNull(slices, "slices")); - sortedSlices.sort( - (e1, e2) -> UNSIGNED_BYTES_COMPARATOR.compare(e1.getStartKey(), e2.getStartKey())); - this.slices = ImmutableList.copyOf(sortedSlices); + SliceMap(List slices, List fallbackPool) { + this.slices = ImmutableList.copyOf(checkNotNull(slices, "slices")); this.fallbackPool = ImmutableList.copyOf(checkNotNull(fallbackPool, "fallbackPool")); - this.generation = generation; } /** @@ -147,8 +136,4 @@ ImmutableList getSlices() { ImmutableList getFallbackPool() { return fallbackPool; } - - long getGeneration() { - return generation; - } } diff --git a/autosharding/src/main/resources/META-INF/services/io.grpc.LoadBalancerProvider b/autosharding/src/main/resources/META-INF/services/io.grpc.LoadBalancerProvider new file mode 100644 index 00000000000..a977316d164 --- /dev/null +++ b/autosharding/src/main/resources/META-INF/services/io.grpc.LoadBalancerProvider @@ -0,0 +1 @@ +io.grpc.autosharding.AutoShardingLoadBalancerProvider diff --git a/autosharding/src/test/java/io/grpc/autosharding/AssignmentParserTest.java b/autosharding/src/test/java/io/grpc/autosharding/AssignmentParserTest.java new file mode 100644 index 00000000000..31ec436c09a --- /dev/null +++ b/autosharding/src/test/java/io/grpc/autosharding/AssignmentParserTest.java @@ -0,0 +1,729 @@ +/* + * Copyright 2026 The gRPC Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.grpc.autosharding; + +import static com.google.common.truth.Truth.assertThat; + +import com.google.cloud.autosharding.v1.AssignmentChunk; +import com.google.cloud.autosharding.v1.EndpointState; +import com.google.cloud.autosharding.v1.PerSliceEndpointState; +import com.google.cloud.autosharding.v1.SliceAssignment; +import com.google.common.base.Strings; +import com.google.common.collect.ImmutableList; +import com.google.protobuf.ByteString; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.List; +import javax.annotation.Nullable; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** Unit tests for {@link AssignmentParser}. */ +@RunWith(JUnit4.class) +public class AssignmentParserTest { + + @Test + public void parse_singleChunkCoveringWholeKeyspace() { + AssignmentChunk chunk = + AssignmentChunk.newBuilder() + .addEndpoints(endpoint("host-a")) + .addEndpoints(endpoint("host-b")) + .addSliceAssignments(sliceAssignment("", "m", 0)) + .addSliceAssignments(sliceAssignment("m", null, 1)) + .build(); + + Assignment assignment = parseFully(ImmutableList.of(chunk)); + + assertThat(assignment.getEndpointNames()).containsExactly("host-a", "host-b").inOrder(); + assertThat(assignment.getSlices()).hasSize(2); + assertSlice(assignment.getSlices().get(0), "", "m", 0); + assertSlice(assignment.getSlices().get(1), "m", null, 1); + } + + @Test + public void parse_endpointNamesCombinedInChunkOrder() { + AssignmentChunk chunk1 = + AssignmentChunk.newBuilder() + .addEndpoints(endpoint("host-a")) + .addEndpoints(endpoint("host-b")) + .build(); + AssignmentChunk chunk2 = + AssignmentChunk.newBuilder() + .addEndpoints(endpoint("host-c")) + // Index 2 only resolves once chunk1's endpoints are prepended. + .addSliceAssignments(sliceAssignment("", null, 2)) + .build(); + + Assignment assignment = parseFully(ImmutableList.of(chunk1, chunk2)); + + assertThat(assignment.getEndpointNames()) + .containsExactly("host-a", "host-b", "host-c") + .inOrder(); + assertSlice(assignment.getSlices().get(0), "", null, 2); + } + + @Test + public void parse_slicesAcrossChunksAreSorted() { + AssignmentChunk chunk1 = + AssignmentChunk.newBuilder() + .addEndpoints(endpoint("host-a")) + .addSliceAssignments(sliceAssignment("m", null, 0)) + .build(); + AssignmentChunk chunk2 = + AssignmentChunk.newBuilder().addSliceAssignments(sliceAssignment("", "m", 0)).build(); + + Assignment assignment = parseFully(ImmutableList.of(chunk1, chunk2)); + + assertThat(assignment.getSlices()).hasSize(2); + assertSlice(assignment.getSlices().get(0), "", "m", 0); + assertSlice(assignment.getSlices().get(1), "m", null, 0); + } + + @Test + public void parse_fillsLeadingGap() { + AssignmentChunk chunk = + AssignmentChunk.newBuilder() + .addEndpoints(endpoint("host-a")) + .addSliceAssignments(sliceAssignment("d", null, 0)) + .build(); + + Assignment assignment = parseWithGaps(ImmutableList.of(chunk)); + + assertThat(assignment.getSlices()).hasSize(2); + assertSlice(assignment.getSlices().get(0), "", "d"); + assertSlice(assignment.getSlices().get(1), "d", null, 0); + // Only slices the server sent without endpoints disable fallback, never a filled gap. + assertThat(assignment.getSlices().get(0).isFallbackDisabled()).isFalse(); + } + + @Test + public void parse_fillsTrailingGap() { + AssignmentChunk chunk = + AssignmentChunk.newBuilder() + .addEndpoints(endpoint("host-a")) + .addSliceAssignments(sliceAssignment("", "d", 0)) + .build(); + + Assignment assignment = parseWithGaps(ImmutableList.of(chunk)); + + assertThat(assignment.getSlices()).hasSize(2); + assertSlice(assignment.getSlices().get(0), "", "d", 0); + assertSlice(assignment.getSlices().get(1), "d", null); + } + + @Test + public void parse_fillsInteriorGap() { + AssignmentChunk chunk = + AssignmentChunk.newBuilder() + .addEndpoints(endpoint("host-a")) + .addEndpoints(endpoint("host-b")) + .addSliceAssignments(sliceAssignment("", "d", 0)) + .addSliceAssignments(sliceAssignment("m", null, 1)) + .build(); + + Assignment assignment = parseWithGaps(ImmutableList.of(chunk)); + + assertThat(assignment.getSlices()).hasSize(3); + assertSlice(assignment.getSlices().get(0), "", "d", 0); + assertSlice(assignment.getSlices().get(1), "d", "m"); + assertSlice(assignment.getSlices().get(2), "m", null, 1); + } + + @Test + public void parse_gaps_areAcceptedAndReported() { + AssignmentChunk chunk = + AssignmentChunk.newBuilder() + .addEndpoints(endpoint("host-a")) + .addSliceAssignments(sliceAssignment("b", "d", 0)) + .addSliceAssignments(sliceAssignment("m", "p", 0)) + .build(); + + AssignmentParser.Result result = AssignmentParser.parse(ImmutableList.of(chunk)); + + assertThat(result.assignment).isNotNull(); + // ["", "b"), ["d", "m") and ["p", inf), with keys hex-encoded. + assertThat(result.errorMessage).contains("keys [, 62) are not covered by any slice"); + assertThat(result.errorMessage).contains("keys [64, 6D) are not covered by any slice"); + assertThat(result.errorMessage).contains("keys [70, inf) are not covered by any slice"); + } + + @Test + public void parse_noSlices_isRejected() { + AssignmentParser.Result result = + AssignmentParser.parse(ImmutableList.of(AssignmentChunk.getDefaultInstance())); + + // with no slice at all there is nothing to route by. + assertThat(result.assignment).isNull(); + assertThat(result.errorMessage).isEqualTo("no slice assignments received"); + } + + @Test + public void parse_noChunks_isRejected() { + AssignmentParser.Result result = AssignmentParser.parse(ImmutableList.of()); + + assertThat(result.assignment).isNull(); + assertThat(result.errorMessage).isEqualTo("no slice assignments received"); + } + + @Test + public void parse_sliceWithNoEndpoints_isPreserved() { + AssignmentChunk chunk = + AssignmentChunk.newBuilder() + .addEndpoints(endpoint("host-a")) + .addSliceAssignments(sliceAssignment("", "d")) + .addSliceAssignments(sliceAssignment("d", null, 0)) + .build(); + + Assignment assignment = parseFully(ImmutableList.of(chunk)); + + assertThat(assignment.getSlices()).hasSize(2); + assertSlice(assignment.getSlices().get(0), "", "d"); + assertSlice(assignment.getSlices().get(1), "d", null, 0); + // The server deliberately assigned ["", "d") nothing, so it must not fall back. + assertThat(assignment.getSlices().get(0).isFallbackDisabled()).isTrue(); + assertThat(assignment.getSlices().get(1).isFallbackDisabled()).isFalse(); + } + + @Test + public void parse_multipleEndpointsPerSlice() { + AssignmentChunk chunk = + AssignmentChunk.newBuilder() + .addEndpoints(endpoint("host-a")) + .addEndpoints(endpoint("host-b")) + .addSliceAssignments(sliceAssignment("", null, 0, 1)) + .build(); + + Assignment assignment = parseFully(ImmutableList.of(chunk)); + + assertSlice(assignment.getSlices().get(0), "", null, 0, 1); + } + + @Test + public void parse_unsignedByteOrderingIsUsed() { + // 0x80 is negative as a signed byte but must sort after 0x01. + AssignmentChunk chunk = + AssignmentChunk.newBuilder() + .addSliceAssignments( + SliceAssignment.newBuilder() + .setSlice( + com.google.cloud.autosharding.v1.Slice.newBuilder() + .setStartKey(ByteString.copyFrom(new byte[] {(byte) 0x80})))) + .addSliceAssignments( + SliceAssignment.newBuilder() + .setSlice( + com.google.cloud.autosharding.v1.Slice.newBuilder() + .setStartKey(ByteString.copyFrom(new byte[] {0x01})) + .setEndKey(ByteString.copyFrom(new byte[] {(byte) 0x80})))) + .build(); + + Assignment assignment = parseWithGaps(ImmutableList.of(chunk)); + + // Leading gap ["", 0x01) plus the two declared slices. + assertThat(assignment.getSlices()).hasSize(3); + assertThat(assignment.getSlices().get(1).getStartKey()).isEqualTo(new byte[] {0x01}); + assertThat(assignment.getSlices().get(2).getStartKey()).isEqualTo(new byte[] {(byte) 0x80}); + assertThat(assignment.getSlices().get(2).getEndKey()).isNull(); + } + + @Test + public void parse_resultingSlicesAreContiguous() { + AssignmentChunk chunk = + AssignmentChunk.newBuilder() + .addEndpoints(endpoint("host-a")) + .addSliceAssignments(sliceAssignment("b", "d", 0)) + .addSliceAssignments(sliceAssignment("k", "m", 0)) + .build(); + + Assignment assignment = parseWithGaps(ImmutableList.of(chunk)); + + List slices = assignment.getSlices(); + assertThat(slices.get(0).getStartKey()).isEqualTo(new byte[0]); + for (int i = 0; i + 1 < slices.size(); i++) { + assertThat(slices.get(i).getEndKey()).isEqualTo(slices.get(i + 1).getStartKey()); + } + assertThat(slices.get(slices.size() - 1).getEndKey()).isNull(); + } + + @Test + public void parse_endpointIndexOutOfRange_sliceBecomesGap() { + AssignmentChunk chunk = + AssignmentChunk.newBuilder() + .addEndpoints(endpoint("host-a")) + .addSliceAssignments(sliceAssignment("", "m", 0)) + .addSliceAssignments(sliceAssignment("m", null, 5)) + .build(); + + AssignmentParser.Result result = AssignmentParser.parse(ImmutableList.of(chunk)); + + assertThat(result.errorMessage).contains("out-of-range endpoint index 5"); + assertThat(result.assignment.getSlices()).hasSize(2); + assertSlice(result.assignment.getSlices().get(0), "", "m", 0); + assertSlice(result.assignment.getSlices().get(1), "m", null); + } + + @Test + public void parse_negativeEndpointIndex_sliceBecomesGap() { + AssignmentChunk chunk = + AssignmentChunk.newBuilder() + .addEndpoints(endpoint("host-a")) + .addSliceAssignments(sliceAssignment("", "m", 0)) + .addSliceAssignments(sliceAssignment("m", null, -1)) + .build(); + + AssignmentParser.Result result = AssignmentParser.parse(ImmutableList.of(chunk)); + + assertThat(result.errorMessage).contains("out-of-range endpoint index -1"); + assertThat(result.assignment.getSlices()).hasSize(2); + assertSlice(result.assignment.getSlices().get(1), "m", null); + } + + @Test + public void parse_endpointIndexOutOfRange_dropsTheWholeSliceNotJustThatEndpoint() { + AssignmentChunk chunk = + AssignmentChunk.newBuilder() + .addEndpoints(endpoint("host-a")) + .addSliceAssignments(sliceAssignment("", "m", 0)) + // Index 0 is valid, but the slice as a whole is rejected because index 5 is not. + .addSliceAssignments(sliceAssignment("m", null, 0, 5)) + .build(); + + AssignmentParser.Result result = AssignmentParser.parse(ImmutableList.of(chunk)); + + assertSlice(result.assignment.getSlices().get(1), "m", null); + } + + @Test + public void parse_startKeyGreaterThanEndKey_sliceBecomesGap() { + AssignmentChunk chunk = + AssignmentChunk.newBuilder() + .addEndpoints(endpoint("host-a")) + .addSliceAssignments(sliceAssignment("", "m", 0)) + .addSliceAssignments(sliceAssignment("z", "n")) + .build(); + + AssignmentParser.Result result = AssignmentParser.parse(ImmutableList.of(chunk)); + + assertThat(result.errorMessage).contains("start_key >= end_key"); + assertThat(result.assignment.getSlices()).hasSize(2); + assertSlice(result.assignment.getSlices().get(0), "", "m", 0); + assertSlice(result.assignment.getSlices().get(1), "m", null); + } + + @Test + public void parse_zeroWidthSlice_isDropped() { + AssignmentChunk chunk = + AssignmentChunk.newBuilder() + .addEndpoints(endpoint("host-a")) + .addEndpoints(endpoint("host-b")) + .addSliceAssignments(sliceAssignment("", "m", 0)) + // start_key == end_key satisfies the gRFC's "start_key <= end_key", but the slice + // covers no keys and would collide with the next slice's start key. + .addSliceAssignments(sliceAssignment("m", "m", 0)) + .addSliceAssignments(sliceAssignment("m", null, 1)) + .build(); + + AssignmentParser.Result result = AssignmentParser.parse(ImmutableList.of(chunk)); + + assertThat(result.errorMessage).contains("start_key >= end_key"); + // No gap appears where it was: its neighbours already met at "m". + assertThat(result.assignment.getSlices()).hasSize(2); + assertSlice(result.assignment.getSlices().get(0), "", "m", 0); + assertSlice(result.assignment.getSlices().get(1), "m", null, 1); + } + + /** + * A zero-width slice is dropped even when it has endpoints, and the keys on either side of it + * become a single gap. + */ + @Test + public void parse_zeroWidthSlice_withEndpointsAndNoNeighbour_leavesNoHole() { + AssignmentChunk chunk = + AssignmentChunk.newBuilder() + .addEndpoints(endpoint("host-a")) + .addEndpoints(endpoint("host-b")) + .addSliceAssignments(sliceAssignment("", "a", 0)) + .addSliceAssignments(sliceAssignment("m", "m", 1)) + .addSliceAssignments(sliceAssignment("z", null, 0)) + .build(); + + AssignmentParser.Result result = AssignmentParser.parse(ImmutableList.of(chunk)); + + assertThat(result.errorMessage).contains("start_key >= end_key"); + assertThat(result.assignment.getSlices()).hasSize(3); + assertSlice(result.assignment.getSlices().get(0), "", "a", 0); + // ["a", "z") is one gap, not two slices meeting at "m". + assertSlice(result.assignment.getSlices().get(1), "a", "z"); + assertSlice(result.assignment.getSlices().get(2), "z", null, 0); + } + + @Test + public void parse_singleKeySlice_isKept() { + AssignmentChunk chunk = + AssignmentChunk.newBuilder() + .addEndpoints(endpoint("host-a")) + // How a server actually assigns exactly one key: end_key is the successor of + // start_key, not start_key itself. + .addSliceAssignments( + SliceAssignment.newBuilder() + .setSlice( + com.google.cloud.autosharding.v1.Slice.newBuilder() + .setStartKey(ByteString.copyFromUtf8("m")) + .setEndKey(ByteString.copyFrom(new byte[] {'m', 0}))) + .addEndpoints(PerSliceEndpointState.newBuilder().setEndpointIndex(0))) + .build(); + + AssignmentParser.Result result = AssignmentParser.parse(ImmutableList.of(chunk)); + + // Only the keys either side of it are reported, as gaps; the slice itself is not dropped. + assertThat(result.errorMessage).doesNotContain("start_key >= end_key"); + assertThat(result.assignment.getSlices()).hasSize(3); + assertThat(result.assignment.getSlices().get(1).getEndpoints()).containsExactly(0); + } + + /** + * The picker looks a key up by binary search over start keys, so two slices sharing one would + * make the result depend on where the search happened to land. + */ + @Test + public void parse_startKeysAreUnique() { + AssignmentChunk chunk = + AssignmentChunk.newBuilder() + .addEndpoints(endpoint("host-a")) + .addSliceAssignments(sliceAssignment("", "", 0)) + .addSliceAssignments(sliceAssignment("", "m", 0)) + .addSliceAssignments(sliceAssignment("m", "m", 0)) + .addSliceAssignments(sliceAssignment("m", null, 0)) + .build(); + + AssignmentParser.Result result = AssignmentParser.parse(ImmutableList.of(chunk)); + + List slices = result.assignment.getSlices(); + for (int i = 0; i + 1 < slices.size(); i++) { + assertThat(slices.get(i).getStartKey()).isNotEqualTo(slices.get(i + 1).getStartKey()); + } + } + + @Test + public void parse_overlappingSlices_bothAreDropped() { + // There is no way to tell which of the two the server meant, so neither is used and the keys + // they covered become a gap. + AssignmentChunk chunk = + AssignmentChunk.newBuilder() + .addSliceAssignments(sliceAssignment("a", "m")) + .addSliceAssignments(sliceAssignment("d", null)) + .build(); + + AssignmentParser.Result result = AssignmentParser.parse(ImmutableList.of(chunk)); + + assertThat(result.errorMessage).contains("overlaps"); + assertThat(result.assignment).isNull(); + } + + @Test + public void parse_overlappingSlices_aSliceClearOfThemSurvives() { + AssignmentChunk chunk = + AssignmentChunk.newBuilder() + .addSliceAssignments(sliceAssignment("a", "m")) + .addSliceAssignments(sliceAssignment("d", "p")) + .addSliceAssignments(sliceAssignment("p", "z")) + .build(); + + AssignmentParser.Result result = AssignmentParser.parse(ImmutableList.of(chunk)); + + assertThat(result.errorMessage).contains("overlaps"); + // ["p", "z") abuts the overlap without entering it, so only it is kept. + assertThat(result.assignment.getSlices()).hasSize(3); + assertSlice(result.assignment.getSlices().get(0), "", "p"); + assertSlice(result.assignment.getSlices().get(1), "p", "z"); + assertSlice(result.assignment.getSlices().get(2), "z", null); + assertThat(result.assignment.getSlices().get(0).getEndpoints()).isEmpty(); + } + + @Test + public void parse_slicesOverlappingOnlyThroughAThird_areAllDropped() { + // ["b", "c") and ["d", "e") are disjoint, but both collide with ["a", "z"), so all three go. + AssignmentChunk chunk = + AssignmentChunk.newBuilder() + .addSliceAssignments(sliceAssignment("a", "z")) + .addSliceAssignments(sliceAssignment("b", "c")) + .addSliceAssignments(sliceAssignment("d", "e")) + .build(); + + AssignmentParser.Result result = AssignmentParser.parse(ImmutableList.of(chunk)); + + assertThat(result.errorMessage).contains("overlaps"); + assertThat(result.assignment).isNull(); + } + + @Test + public void parse_duplicateStartKeys_bothAreDropped() { + AssignmentChunk chunk = + AssignmentChunk.newBuilder() + .addSliceAssignments(sliceAssignment("a", "m")) + .addSliceAssignments(sliceAssignment("a", "z")) + .build(); + + AssignmentParser.Result result = AssignmentParser.parse(ImmutableList.of(chunk)); + + assertThat(result.errorMessage).contains("overlaps"); + assertThat(result.assignment).isNull(); + } + + @Test + public void parse_sliceExtendingToInfinityFollowedByAnother_bothAreDropped() { + AssignmentChunk chunk = + AssignmentChunk.newBuilder() + .addSliceAssignments(sliceAssignment("a", null)) + .addSliceAssignments(sliceAssignment("m", null)) + .build(); + + AssignmentParser.Result result = AssignmentParser.parse(ImmutableList.of(chunk)); + + assertThat(result.errorMessage).contains("overlaps"); + assertThat(result.assignment).isNull(); + } + + @Test + public void parse_sliceExtendingToInfinityFollowedByAFiniteOne_bothAreDropped() { + AssignmentChunk chunk = + AssignmentChunk.newBuilder() + .addEndpoints(endpoint("host-a")) + .addSliceAssignments(sliceAssignment("", "a", 0)) + .addSliceAssignments(sliceAssignment("a", null, 0)) + .addSliceAssignments(sliceAssignment("m", "p", 0)) + .build(); + + AssignmentParser.Result result = AssignmentParser.parse(ImmutableList.of(chunk)); + + // ["a", inf) overlaps ["m", "p"), so both go; only the slice clear of them survives. + assertThat(result.errorMessage).contains("overlaps"); + assertSlice(result.assignment.getSlices().get(0), "", "a", 0); + assertSlice(result.assignment.getSlices().get(1), "a", null); + } + + @Test + public void parse_everySliceInvalid_yieldsNoAssignment() { + AssignmentChunk chunk = + AssignmentChunk.newBuilder() + .addEndpoints(endpoint("host-a")) + .addSliceAssignments(sliceAssignment("", null, 1)) + .build(); + + AssignmentParser.Result result = AssignmentParser.parse(ImmutableList.of(chunk)); + + assertThat(result.assignment).isNull(); + assertThat(result.errorMessage).contains("out-of-range endpoint index 1"); + } + + @Test + public void parse_manyProblems_errorMessageStaysWithinTheAckBudget() { + AssignmentChunk.Builder chunk = AssignmentChunk.newBuilder(); + for (int i = 0; i < 40; i++) { + // Inverted key range, so every one of them is dropped. + chunk.addSliceAssignments(sliceAssignment("z" + i, "a")); + } + + AssignmentParser.Result result = AssignmentParser.parse(ImmutableList.of(chunk.build())); + + assertThat(result.assignment).isNull(); + // autosharding.proto: error_message "MUST NOT exceed 512 characters". + assertThat(result.errorMessage.length()).isAtMost(512); + assertThat(result.errorMessage).contains("start_key >= end_key"); + assertThat(result.errorMessage).containsMatch("; and \\d+ more$"); + } + + @Test + public void parse_fewProblems_allAreReported() { + AssignmentChunk.Builder chunk = AssignmentChunk.newBuilder(); + for (String startKey : new String[] {"v", "w", "x", "y", "z"}) { + chunk.addSliceAssignments(sliceAssignment(startKey, "a")); + } + + AssignmentParser.Result result = AssignmentParser.parse(ImmutableList.of(chunk.build())); + + // Five short descriptions fit comfortably, so nothing is elided. + assertThat(result.errorMessage).doesNotContain("more"); + assertThat(result.errorMessage.split("; ")).hasLength(5); + } + + @Test + public void parse_longKeysAreShortenedInTheErrorMessage() { + byte[] longKey = new byte[512]; + Arrays.fill(longKey, (byte) 0xAB); + AssignmentChunk chunk = + AssignmentChunk.newBuilder() + .addSliceAssignments( + SliceAssignment.newBuilder() + .setSlice( + com.google.cloud.autosharding.v1.Slice.newBuilder() + .setStartKey(ByteString.copyFrom(longKey)) + .setEndKey(ByteString.copyFromUtf8("a")))) + .build(); + + AssignmentParser.Result result = AssignmentParser.parse(ImmutableList.of(chunk)); + + // Hex-encoding 512 bytes in full would be 1024 characters on its own. + assertThat(result.errorMessage.length()).isAtMost(512); + assertThat(result.errorMessage).contains("..."); + } + + @Test + public void parse_startKeyLongerThan512Bytes_isDropped() { + @SuppressWarnings("InlineMeInliner") // String.repeat() requires Java 11 + String tooLongKey = Strings.repeat("m", 513); + AssignmentChunk chunk = + AssignmentChunk.newBuilder() + .addEndpoints(endpoint("host-a")) + .addSliceAssignments(sliceAssignment("", "m", 0)) + .addSliceAssignments(sliceAssignment(tooLongKey, null, 0)) + .build(); + + AssignmentParser.Result result = AssignmentParser.parse(ImmutableList.of(chunk)); + + // autosharding.proto: keys "Will be at most 512 bytes". + assertThat(result.errorMessage).contains("start_key longer than 512 bytes"); + assertSlice(result.assignment.getSlices().get(0), "", "m", 0); + assertSlice(result.assignment.getSlices().get(1), "m", null); + } + + @Test + public void parse_endKeyLongerThan512Bytes_isDropped() { + @SuppressWarnings("InlineMeInliner") // String.repeat() requires Java 11 + String tooLongKey = Strings.repeat("m", 513); + AssignmentChunk chunk = + AssignmentChunk.newBuilder() + .addEndpoints(endpoint("host-a")) + .addSliceAssignments(sliceAssignment("", tooLongKey, 0)) + .build(); + + AssignmentParser.Result result = AssignmentParser.parse(ImmutableList.of(chunk)); + + assertThat(result.assignment).isNull(); + assertThat(result.errorMessage).contains("end_key longer than 512 bytes"); + } + + @Test + public void parse_keysOf512Bytes_areKept() { + @SuppressWarnings("InlineMeInliner") // String.repeat() requires Java 11 + String key = Strings.repeat("m", 512); + AssignmentChunk chunk = + AssignmentChunk.newBuilder() + .addEndpoints(endpoint("host-a")) + .addSliceAssignments(sliceAssignment("", key, 0)) + .addSliceAssignments(sliceAssignment(key, null, 0)) + .build(); + + Assignment assignment = parseFully(ImmutableList.of(chunk)); + + assertThat(assignment.getSlices()).hasSize(2); + } + + @Test + public void parse_sliceAssignmentWithoutSlice_coversTheWholeKeyspaceAndOverlapsTheRest() { + AssignmentChunk chunk = + AssignmentChunk.newBuilder() + .addEndpoints(endpoint("host-a")) + .addEndpoints(endpoint("host-b")) + .addSliceAssignments(sliceAssignment("", "m", 0)) + // No slice set, so it reads as ["", inf), and overlaps the other one. + .addSliceAssignments( + SliceAssignment.newBuilder() + .addEndpoints(PerSliceEndpointState.newBuilder().setEndpointIndex(1))) + .build(); + + AssignmentParser.Result result = AssignmentParser.parse(ImmutableList.of(chunk)); + + assertThat(result.assignment).isNull(); + assertThat(result.errorMessage).contains("overlaps another slice"); + } + + @Test + public void parse_onlySliceAssignmentWithoutSlice_coversTheWholeKeyspace() { + AssignmentChunk chunk = + AssignmentChunk.newBuilder() + .addEndpoints(endpoint("host-a")) + .addSliceAssignments( + SliceAssignment.newBuilder() + .addEndpoints(PerSliceEndpointState.newBuilder().setEndpointIndex(0))) + .build(); + + Assignment assignment = parseFully(ImmutableList.of(chunk)); + + assertThat(assignment.getSlices()).hasSize(1); + assertSlice(assignment.getSlices().get(0), "", null, 0); + } + + @Test + public void slice_sharesItsKeyArrays() { + byte[] startKey = "a".getBytes(StandardCharsets.UTF_8); + byte[] endKey = "m".getBytes(StandardCharsets.UTF_8); + + Assignment.Slice slice = new Assignment.Slice(startKey, endKey, ImmutableList.of()); + + assertThat(slice.getStartKey()).isSameInstanceAs(startKey); + assertThat(slice.getEndKey()).isSameInstanceAs(endKey); + } + + /** Parses chunks whose only problem is gaps, which are filled and reported but accepted. */ + private static Assignment parseWithGaps(List chunks) { + AssignmentParser.Result result = AssignmentParser.parse(chunks); + assertThat(result.assignment).isNotNull(); + assertThat(result.errorMessage).contains("not covered by any slice"); + return result.assignment; + } + + /** Parses chunks that are expected to be usable in their entirety. */ + private static Assignment parseFully(List chunks) { + AssignmentParser.Result result = AssignmentParser.parse(chunks); + assertThat(result.errorMessage).isNull(); + assertThat(result.assignment).isNotNull(); + return result.assignment; + } + + private static EndpointState endpoint(String name) { + return EndpointState.newBuilder().setEndpoint(name).build(); + } + + private static SliceAssignment sliceAssignment( + String startKey, @Nullable String endKey, int... endpointIndices) { + com.google.cloud.autosharding.v1.Slice.Builder slice = + com.google.cloud.autosharding.v1.Slice.newBuilder() + .setStartKey(ByteString.copyFromUtf8(startKey)); + if (endKey != null) { + slice.setEndKey(ByteString.copyFromUtf8(endKey)); + } + SliceAssignment.Builder builder = SliceAssignment.newBuilder().setSlice(slice); + for (int index : endpointIndices) { + builder.addEndpoints(PerSliceEndpointState.newBuilder().setEndpointIndex(index)); + } + return builder.build(); + } + + private static void assertSlice( + Assignment.Slice slice, String startKey, @Nullable String endKey, int... endpoints) { + assertThat(slice.getStartKey()).isEqualTo(startKey.getBytes(StandardCharsets.UTF_8)); + if (endKey == null) { + assertThat(slice.getEndKey()).isNull(); + } else { + assertThat(slice.getEndKey()).isEqualTo(endKey.getBytes(StandardCharsets.UTF_8)); + } + assertThat(slice.getEndpoints()) + .containsExactlyElementsIn(Arrays.stream(endpoints).boxed().toArray()) + .inOrder(); + } +} diff --git a/autosharding/src/test/java/io/grpc/autosharding/AutoShardingLoadBalancerProviderTest.java b/autosharding/src/test/java/io/grpc/autosharding/AutoShardingLoadBalancerProviderTest.java new file mode 100644 index 00000000000..bd4822f2407 --- /dev/null +++ b/autosharding/src/test/java/io/grpc/autosharding/AutoShardingLoadBalancerProviderTest.java @@ -0,0 +1,217 @@ +/* + * Copyright 2026 The gRPC Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.grpc.autosharding; + +import static com.google.common.truth.Truth.assertThat; +import static org.junit.Assert.fail; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import io.grpc.InternalServiceProviders; +import io.grpc.LoadBalancer.Helper; +import io.grpc.LoadBalancerProvider; +import io.grpc.NameResolver.ConfigOrError; +import io.grpc.Status; +import io.grpc.SynchronizationContext; +import io.grpc.internal.JsonParser; +import java.io.IOException; +import java.util.Map; +import java.util.concurrent.TimeUnit; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** Unit tests for {@link AutoShardingLoadBalancerProvider}. */ +@RunWith(JUnit4.class) +public class AutoShardingLoadBalancerProviderTest { + + private final SynchronizationContext syncContext = + new SynchronizationContext((t, e) -> { + throw new AssertionError(e); + }); + + private final AutoShardingLoadBalancerProvider provider = + new AutoShardingLoadBalancerProvider(); + + @Test + public void provided() { + for (LoadBalancerProvider current : + InternalServiceProviders.getCandidatesViaServiceLoader( + LoadBalancerProvider.class, getClass().getClassLoader())) { + if (current instanceof AutoShardingLoadBalancerProvider) { + return; + } + } + fail("AutoShardingLoadBalancerProvider not registered"); + } + + @Test + public void providerProperties() { + assertThat(provider.getPolicyName()).isEqualTo("autosharding_experimental"); + assertThat(provider.isAvailable()).isTrue(); + assertThat(provider.getPriority()).isEqualTo(5); + } + + @Test + public void providesLoadBalancer() { + Helper helper = mock(Helper.class); + when(helper.getSynchronizationContext()).thenReturn(syncContext); + assertThat(provider.newLoadBalancer(helper)).isInstanceOf(AutoShardingLoadBalancer.class); + } + + @Test + public void parse_allFieldsPresent() throws IOException { + AutoShardingLoadBalancerConfig config = + parseSuccessfully( + "{" + + "\"channelFactoryKey\": \"shard-service\"," + + "\"autoshardingTarget\": \"my-service/%s\"," + + "\"keyHeaderName\": \"x-shard-key\"," + + "\"enableFallback\": true," + + "\"initialAssignmentTimeout\": \"5.5s\"" + + "}"); + + assertThat(config.getChannelFactoryKey()).isEqualTo("shard-service"); + assertThat(config.getAutoshardingTarget()).isEqualTo("my-service/%s"); + assertThat(config.getKeyHeader().name()).isEqualTo("x-shard-key"); + assertThat(config.isFallbackEnabled()).isTrue(); + assertThat(config.getInitialAssignmentTimeoutNanos()) + .isEqualTo(TimeUnit.MILLISECONDS.toNanos(5500)); + } + + @Test + public void parse_optionalFieldsAbsent_useDefaults() throws IOException { + AutoShardingLoadBalancerConfig config = + parseSuccessfully(configJson("\"keyHeaderName\": \"x-shard-key\"")); + + assertThat(config.isFallbackEnabled()).isFalse(); + assertThat(config.getInitialAssignmentTimeoutNanos()) + .isEqualTo(AutoShardingLoadBalancerConfig.DEFAULT_INITIAL_ASSIGNMENT_TIMEOUT_NANOS); + assertThat(config.getInitialAssignmentTimeoutNanos()).isEqualTo(TimeUnit.SECONDS.toNanos(60)); + } + + @Test + public void parse_binaryKeyHeaderName() throws IOException { + AutoShardingLoadBalancerConfig config = + parseSuccessfully(configJson("\"keyHeaderName\": \"x-shard-key-bin\"")); + + assertThat(config.getKeyHeader().name()).isEqualTo("x-shard-key-bin"); + } + + @Test + public void parse_missingOrEmptyChannelFactoryKey_isRejected() throws IOException { + assertThat(parseError("{\"autoshardingTarget\": \"t\", \"keyHeaderName\": \"k\"}")) + .contains("'channelFactoryKey' is required"); + assertThat( + parseError( + "{\"channelFactoryKey\": \"\", \"autoshardingTarget\": \"t\"," + + " \"keyHeaderName\": \"k\"}")) + .contains("'channelFactoryKey' is required"); + } + + @Test + public void parse_missingOrEmptyAutoshardingTarget_isRejected() throws IOException { + assertThat(parseError("{\"channelFactoryKey\": \"c\", \"keyHeaderName\": \"k\"}")) + .contains("'autoshardingTarget' is required"); + assertThat( + parseError( + "{\"channelFactoryKey\": \"c\", \"autoshardingTarget\": \"\"," + + " \"keyHeaderName\": \"k\"}")) + .contains("'autoshardingTarget' is required"); + } + + @Test + public void parse_missingKeyHeaderName_isRejected() throws IOException { + assertThat(parseError(configJson(""))).contains("'keyHeaderName' is required"); + } + + @Test + public void parse_emptyKeyHeaderName_isRejected() throws IOException { + // There would be no header to read the routing key from. + assertThat(parseError(configJson("\"keyHeaderName\": \"\""))) + .contains("'keyHeaderName' is required"); + } + + @Test + public void parse_malformedKeyHeaderName_isRejected() throws IOException { + // Reported as a config error rather than thrown out of Metadata.Key. + assertThat(parseError(configJson("\"keyHeaderName\": \"not a header\""))) + .contains("'keyHeaderName' is not a valid header name"); + } + + @Test + public void parse_zeroInitialAssignmentTimeout_isAccepted() throws IOException { + // A coherent request: skip the wait, start in fallback, and upgrade once the first assignment + // lands. The gRFC does not forbid it, so the parser does not either. + AutoShardingLoadBalancerConfig config = + parseSuccessfully( + configJson("\"keyHeaderName\": \"x-shard-key\", \"initialAssignmentTimeout\": \"0s\"")); + + assertThat(config.getInitialAssignmentTimeoutNanos()).isEqualTo(0); + } + + @Test + public void parse_negativeInitialAssignmentTimeout_isRejected() throws IOException { + assertThat( + parseError( + configJson( + "\"keyHeaderName\": \"x-shard-key\", \"initialAssignmentTimeout\": \"-1s\""))) + .contains("'initialAssignmentTimeout' must not be negative"); + } + + @Test + public void parse_unparseableInitialAssignmentTimeout_isReportedAsFailure() throws IOException { + // Durations are JSON strings ending in "s"; a bare number is a ClassCastException inside + // JsonUtil, which the provider turns into an error rather than letting it escape. + assertThat( + parseError( + configJson("\"keyHeaderName\": \"x-shard-key\", \"initialAssignmentTimeout\": 60"))) + .isEqualTo("Failed parsing configuration for autosharding_experimental"); + } + + @Test + public void parse_wronglyTypedField_isReportedAsFailure() throws IOException { + assertThat(parseError(configJson("\"keyHeaderName\": 42"))) + .isEqualTo("Failed parsing configuration for autosharding_experimental"); + } + + private AutoShardingLoadBalancerConfig parseSuccessfully(String json) throws IOException { + ConfigOrError configOrError = provider.parseLoadBalancingPolicyConfig(parseJsonObject(json)); + assertThat(configOrError.getError()).isNull(); + return (AutoShardingLoadBalancerConfig) configOrError.getConfig(); + } + + /** Parses a config expected to be rejected, returning the error description. */ + private String parseError(String json) throws IOException { + ConfigOrError configOrError = provider.parseLoadBalancingPolicyConfig(parseJsonObject(json)); + assertThat(configOrError.getConfig()).isNull(); + Status error = configOrError.getError(); + assertThat(error.getCode()).isEqualTo(Status.Code.UNAVAILABLE); + return error.getDescription(); + } + + /** Returns a JSON config with the other required fields set, plus {@code members}. */ + private static String configJson(String members) { + String required = "\"channelFactoryKey\": \"shard-service\", \"autoshardingTarget\": \"t\""; + return "{" + required + (members.isEmpty() ? "" : ", " + members) + "}"; + } + + @SuppressWarnings("unchecked") + private static Map parseJsonObject(String json) throws IOException { + return (Map) JsonParser.parse(json); + } +} diff --git a/autosharding/src/test/java/io/grpc/autosharding/AutoShardingLoadBalancerTest.java b/autosharding/src/test/java/io/grpc/autosharding/AutoShardingLoadBalancerTest.java new file mode 100644 index 00000000000..9ba9177aec8 --- /dev/null +++ b/autosharding/src/test/java/io/grpc/autosharding/AutoShardingLoadBalancerTest.java @@ -0,0 +1,1759 @@ +/* + * Copyright 2026 The gRPC Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.grpc.autosharding; + +import static com.google.common.truth.Truth.assertThat; +import static io.grpc.ConnectivityState.CONNECTING; +import static io.grpc.ConnectivityState.IDLE; +import static io.grpc.ConnectivityState.READY; +import static io.grpc.ConnectivityState.TRANSIENT_FAILURE; +import static org.junit.Assert.fail; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import com.google.cloud.autosharding.v1.AssignmentChunk; +import com.google.cloud.autosharding.v1.AssignmentMetadata; +import com.google.cloud.autosharding.v1.AutoshardingServiceGrpc; +import com.google.cloud.autosharding.v1.EndpointState; +import com.google.cloud.autosharding.v1.PerSliceEndpointState; +import com.google.cloud.autosharding.v1.SliceAssignment; +import com.google.cloud.autosharding.v1.WatchShardingAssignmentRequest; +import com.google.cloud.autosharding.v1.WatchShardingAssignmentResponse; +import com.google.common.collect.ImmutableList; +import com.google.protobuf.ByteString; +import io.grpc.Attributes; +import io.grpc.CallOptions; +import io.grpc.Channel; +import io.grpc.ClientCall; +import io.grpc.ConnectivityState; +import io.grpc.EquivalentAddressGroup; +import io.grpc.ForwardingClientCall.SimpleForwardingClientCall; +import io.grpc.InternalEquivalentAddressGroup; +import io.grpc.LoadBalancer; +import io.grpc.LoadBalancer.Helper; +import io.grpc.LoadBalancer.PickDetailsConsumer; +import io.grpc.LoadBalancer.PickResult; +import io.grpc.LoadBalancer.ResolvedAddresses; +import io.grpc.LoadBalancer.Subchannel; +import io.grpc.LoadBalancer.SubchannelPicker; +import io.grpc.LoadBalancerProvider; +import io.grpc.Metadata; +import io.grpc.MethodDescriptor; +import io.grpc.Status; +import io.grpc.SynchronizationContext; +import io.grpc.inprocess.InProcessChannelBuilder; +import io.grpc.inprocess.InProcessServerBuilder; +import io.grpc.internal.FakeClock; +import io.grpc.internal.PickSubchannelArgsImpl; +import io.grpc.stub.StreamObserver; +import io.grpc.testing.GrpcCleanupRule; +import io.grpc.testing.TestMethodDescriptors; +import java.net.SocketAddress; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import javax.annotation.Nullable; +import org.junit.After; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** + * Unit tests for {@link AutoShardingLoadBalancer}. + * + *

These drive a real {@link AutoshardingClient} against an in-process fake sharding service, + * so the path from a served assignment through to a routed pick is covered end to end. + */ +@RunWith(JUnit4.class) +public class AutoShardingLoadBalancerTest { + private static final String CHANNEL_FACTORY_KEY = "shard-service-key"; + private static final String OTHER_CHANNEL_FACTORY_KEY = "other-shard-service-key"; + private static final String UNKNOWN_CHANNEL_FACTORY_KEY = "unknown-key"; + private static final String TARGET = "autosharding-target"; + private static final String KEY_HEADER = "x-shard-key"; + private static final String OTHER_KEY_HEADER = "x-other-shard-key"; + private static final long ASSIGNMENT_TIMEOUT_NANOS = TimeUnit.SECONDS.toNanos(10); + private static final long POLL_TIMEOUT_SECONDS = 5; + private static final MethodDescriptor METHOD = TestMethodDescriptors.voidMethod(); + + @Rule public final GrpcCleanupRule grpcCleanup = new GrpcCleanupRule(); + + private final SynchronizationContext syncContext = + new SynchronizationContext( + (t, e) -> { + throw new AssertionError(e); + }); + private final FakeClock fakeClock = new FakeClock(); + private final FakeAutoshardingService service = new FakeAutoshardingService(); + private final Helper helper = mock(Helper.class); + private final FakeChildProvider childProvider = new FakeChildProvider(); + private final FakeChannelFactory channelFactory = new FakeChannelFactory(); + + private Channel shardingChannel; + private AutoShardingLoadBalancer loadBalancer; + + @Nullable private ConnectivityState currentState; + @Nullable private SubchannelPicker currentPicker; + @Nullable private StreamObserver serverStream; + private int balancingStateUpdates; + + @Before + public void setUp() throws Exception { + String serverName = InProcessServerBuilder.generateName(); + grpcCleanup.register( + InProcessServerBuilder.forName(serverName) + .directExecutor() + .addService(service) + .build() + .start()); + shardingChannel = + grpcCleanup.register(InProcessChannelBuilder.forName(serverName).directExecutor().build()); + + when(helper.getSynchronizationContext()).thenReturn(syncContext); + when(helper.getScheduledExecutorService()).thenReturn(fakeClock.getScheduledExecutorService()); + doAnswer( + invocation -> { + currentState = invocation.getArgument(0); + currentPicker = invocation.getArgument(1); + balancingStateUpdates++; + return null; + }) + .when(helper) + .updateBalancingState(any(ConnectivityState.class), any(SubchannelPicker.class)); + + loadBalancer = + new AutoShardingLoadBalancer( + helper, + childProvider, + () -> () -> TimeUnit.SECONDS.toNanos(1), + fakeClock.getStopwatchSupplier(), + "client-uuid"); + } + + @After + public void tearDown() { + // Must run before GrpcCleanupRule terminates the channel, otherwise the assignment client + // keeps retrying against a shutting-down channel. + syncContext.execute(loadBalancer::shutdown); + } + + // --------------------------------------------------------------------------------------------- + // Configuration handling + // --------------------------------------------------------------------------------------------- + + @Test + public void missingConfig_failsRpcsInsteadOfThrowing() { + // Happens when this policy is the channel's default and there is no service config. + Status status = deliverWithoutConfig("a"); + + assertThat(status.getCode()).isEqualTo(Status.Code.UNAVAILABLE); + assertThat(currentState).isEqualTo(TRANSIENT_FAILURE); + assertThat(pick("k").getStatus().getDescription()).contains("no load balancing config"); + } + + @Test + public void missingConfig_afterValidConfig_closesTheClientAndChannel() throws Exception { + deliverAddresses(config(CHANNEL_FACTORY_KEY, true), "a"); + deliverAssignment(1, slice("", "a")); + reportReady("a"); + + Status status = deliverWithoutConfig("a"); + syncContext.execute(() -> childForHost("a").reportReady()); + + assertThat(status.getCode()).isEqualTo(Status.Code.UNAVAILABLE); + assertThat(channelFactory.isReleased(0)).isTrue(); + assertThat(channelFactory.liveCallsAtRelease).containsExactly(0); + assertThat(currentState).isEqualTo(TRANSIENT_FAILURE); + assertThat(pick("k").getStatus().getDescription()).contains("no load balancing config"); + } + + @Test + public void missingChannelFactory_fallbackEnabled_failsRpcsAnyway() { + Status status = deliverWithoutChannelFactory(config(CHANNEL_FACTORY_KEY, true), "a"); + + // Fallback only covers the sharding service; without a factory the update itself fails. + assertThat(status.getCode()).isEqualTo(Status.Code.UNAVAILABLE); + assertThat(currentState).isEqualTo(TRANSIENT_FAILURE); + assertThat(pick("k").getStatus().getDescription()).contains("no channel factory"); + } + + @Test + public void missingChannelFactory_fallbackDisabled_failsRpcs() { + Status status = deliverWithoutChannelFactory(config(CHANNEL_FACTORY_KEY, false), "a"); + + assertThat(status.isOk()).isFalse(); + assertThat(currentState).isEqualTo(TRANSIENT_FAILURE); + assertThat(pick("k").getStatus().getDescription()).contains("no channel factory"); + } + + @Test + public void missingChannelFactory_closesTheClientAndChannel() throws Exception { + deliverAddresses(config(CHANNEL_FACTORY_KEY, false), "a"); + deliverAssignment(1, slice("", "a")); + reportReady("a"); + + // The factory is required on every update, even when the key is unchanged. + Status status = deliverWithoutChannelFactory(config(CHANNEL_FACTORY_KEY, false), "a"); + + assertThat(status.isOk()).isFalse(); + // The stream is cancelled before its channel is handed back. + assertThat(channelFactory.isReleased(0)).isTrue(); + assertThat(channelFactory.liveCallsAtRelease).containsExactly(0); + assertThat(currentState).isEqualTo(TRANSIENT_FAILURE); + assertThat(pick("k").getStatus().getDescription()).contains("no channel factory"); + } + + @Test + public void missingChannelFactory_thenSuppliedAgain_startsAfresh() throws Exception { + deliverAddresses(config(CHANNEL_FACTORY_KEY, false), "a"); + deliverAssignment(1, slice("", "a")); + reportReady("a"); + deliverWithoutChannelFactory(config(CHANNEL_FACTORY_KEY, false), "a"); + + Status status = deliverAddresses(config(CHANNEL_FACTORY_KEY, false), "a"); + + // A new channel and client under the same key, and the previous assignment is not reused. + assertThat(status.isOk()).isTrue(); + assertThat(channelFactory.keys).containsExactly(CHANNEL_FACTORY_KEY, CHANNEL_FACTORY_KEY); + assertThat(service.streamCount.get()).isEqualTo(2); + PickResult queued = pick("k"); + assertThat(queued.getStatus().isOk()).isTrue(); + assertThat(queued.getSubchannel()).isNull(); + + deliverAssignment(1, slice("", "a")); + + assertThat(pickedHost(pick("k"))).isEqualTo("a"); + } + + @Test + public void missingChannelFactory_inFallback_thenSuppliedAgain_queuesInsteadOfFallingBack() { + deliverAddresses(config(CHANNEL_FACTORY_KEY, true), "a"); + fakeClock.forwardNanos(ASSIGNMENT_TIMEOUT_NANOS); + reportReady("a"); + assertThat(pickedHost(pick("k"))).isEqualTo("a"); + deliverWithoutChannelFactory(config(CHANNEL_FACTORY_KEY, true), "a"); + + deliverAddresses(config(CHANNEL_FACTORY_KEY, true), "a"); + + // The previous client's error is dropped with it, so the new client gets its own wait. + PickResult queued = pick("k"); + assertThat(queued.getStatus().isOk()).isTrue(); + assertThat(queued.getSubchannel()).isNull(); + } + + @Test + public void newChannelFactoryInstance_sameKey_keepsTheChannelAndClient() throws Exception { + deliverAddresses(config(CHANNEL_FACTORY_KEY, false), "a"); + deliverAssignment(1, slice("", "a")); + reportReady("a"); + + // The key identifies the channel, so another factory for the same key changes nothing. + FakeChannelFactory otherFactory = new FakeChannelFactory(); + deliverWithChannelFactory(otherFactory, config(CHANNEL_FACTORY_KEY, false), "a"); + + assertThat(otherFactory.keys).isEmpty(); + assertThat(channelFactory.released).isEmpty(); + assertThat(service.streamCount.get()).isEqualTo(1); + assertThat(pickedHost(pick("k"))).isEqualTo("a"); + } + + @Test + public void newChannelFactoryInstance_thenKeyChange_releasesThroughTheCreatingFactory() { + deliverAddresses(config(CHANNEL_FACTORY_KEY, true), "a"); + FakeChannelFactory otherFactory = new FakeChannelFactory(); + deliverWithChannelFactory(otherFactory, config(CHANNEL_FACTORY_KEY, true), "a"); + + deliverWithChannelFactory(otherFactory, config(OTHER_CHANNEL_FACTORY_KEY, true), "a"); + + assertThat(otherFactory.keys).containsExactly(OTHER_CHANNEL_FACTORY_KEY); + assertThat(channelFactory.isReleased(0)).isTrue(); + assertThat(otherFactory.released).isEmpty(); + } + + @Test + public void unknownChannelFactoryKey_fallbackEnabled_entersFallback() { + Status status = deliverAddresses(config(UNKNOWN_CHANNEL_FACTORY_KEY, true), "a"); + reportReady("a"); + + // The failure goes to the client as a channel whose every RPC fails, so it is handled like + // any other error from the sharding service. + assertThat(status.isOk()).isTrue(); + assertThat(currentState).isEqualTo(READY); + assertThat(pickedHost(pick("k"))).isEqualTo("a"); + } + + @Test + public void unknownChannelFactoryKey_fallbackDisabled_failsRpcsWithTheFactoryError() { + Status status = deliverAddresses(config(UNKNOWN_CHANNEL_FACTORY_KEY, false), "a"); + + assertThat(status.isOk()).isTrue(); + assertThat(currentState).isEqualTo(TRANSIENT_FAILURE); + assertThat(pick("k").getStatus().getDescription()) + .contains("channel factory rejected key '" + UNKNOWN_CHANNEL_FACTORY_KEY + "'"); + } + + @Test + public void channelFactoryFailure_sameKey_isNotRetried() { + deliverAddresses(config(UNKNOWN_CHANNEL_FACTORY_KEY, false), "a"); + + Status status = deliverAddresses(config(UNKNOWN_CHANNEL_FACTORY_KEY, false), "a", "b"); + + assertThat(status.isOk()).isTrue(); + assertThat(channelFactory.attempts).isEqualTo(1); + assertThat(pick("k").getStatus().getDescription()) + .contains("channel factory rejected key '" + UNKNOWN_CHANNEL_FACTORY_KEY + "'"); + } + + @Test + public void missingChannelFactory_thenSuppliedUnderTheSameKey_createsTheChannel() { + deliverWithoutChannelFactory(config(CHANNEL_FACTORY_KEY, true), "a"); + + Status status = deliverAddresses(config(CHANNEL_FACTORY_KEY, true), "a"); + + assertThat(status.isOk()).isTrue(); + assertThat(channelFactory.keys).containsExactly(CHANNEL_FACTORY_KEY); + assertThat(service.streamCount.get()).isEqualTo(1); + } + + @Test + public void channelFactoryFailure_releasesThePreviousChannel() throws Exception { + deliverAddresses(config(CHANNEL_FACTORY_KEY, false), "a"); + deliverAssignment(1, slice("", "a")); + reportReady("a"); + + deliverAddresses(config(UNKNOWN_CHANNEL_FACTORY_KEY, false), "a"); + + assertThat(channelFactory.isReleased(0)).isTrue(); + assertThat(channelFactory.liveCallsAtRelease).containsExactly(0); + // The new client's error replaces the previous assignment. + assertThat(currentState).isEqualTo(TRANSIENT_FAILURE); + assertThat(pick("k").getStatus().getDescription()).contains("channel factory rejected key"); + } + + @Test + public void channelFactoryFailure_thenNewKey_neverReleasesTheLameChannel() throws Exception { + deliverAddresses(config(UNKNOWN_CHANNEL_FACTORY_KEY, false), "a"); + reportReady("a"); + + deliverAddresses(config(CHANNEL_FACTORY_KEY, false), "a"); + + // The factory never created the failing channel, so it is not handed back. + assertThat(channelFactory.released).isEmpty(); + assertThat(channelFactory.keys).containsExactly(CHANNEL_FACTORY_KEY); + // The previous client's error stands until the new client reports. + assertThat(pick("k").getStatus().getDescription()).contains("channel factory rejected key"); + + deliverAssignment(1, slice("", "a")); + + assertThat(pickedHost(pick("k"))).isEqualTo("a"); + } + + @Test + public void noEndpoints_reportsTransientFailureAndFailsRpcs() { + Status status = deliverAddresses(config(CHANNEL_FACTORY_KEY, true)); + + assertThat(status.getCode()).isEqualTo(Status.Code.UNAVAILABLE); + assertThat(currentState).isEqualTo(TRANSIENT_FAILURE); + assertThat(pick("anything").getStatus().getCode()).isEqualTo(Status.Code.UNAVAILABLE); + } + + @Test + public void endpointsRetracted_thenRestored_resumesServing() throws Exception { + deliverAddresses(config(CHANNEL_FACTORY_KEY, true), "a"); + deliverAssignment(1, slice("", "a")); + + deliverAddresses(config(CHANNEL_FACTORY_KEY, true)); + assertThat(currentState).isEqualTo(TRANSIENT_FAILURE); + + deliverAddresses(config(CHANNEL_FACTORY_KEY, true), "a"); + reportReady("a"); + + // The previous client was closed with the endpoints, and its assignment dropped. + assertThat(currentState).isEqualTo(IDLE); + PickResult queued = pick("k"); + assertThat(queued.getStatus().isOk()).isTrue(); + assertThat(queued.getSubchannel()).isNull(); + + deliverAssignment(1, slice("", "a")); + + assertThat(currentState).isEqualTo(READY); + assertThat(pickedHost(pick("k"))).isEqualTo("a"); + } + + @Test + public void endpointsRetracted_shutsDownTheChildren() throws Exception { + deliverAddresses(config(CHANNEL_FACTORY_KEY, true), "a"); + deliverAssignment(1, slice("", "a")); + reportReady("a"); + + Status status = deliverAddresses(config(CHANNEL_FACTORY_KEY, true)); + + assertThat(status.getCode()).isEqualTo(Status.Code.UNAVAILABLE); + assertThat(currentState).isEqualTo(TRANSIENT_FAILURE); + assertThat(childForHost("a").shutdown).isTrue(); + } + + @Test + public void endpointsRetracted_closesTheClientAndChannel() throws Exception { + deliverAddresses(config(CHANNEL_FACTORY_KEY, true), "a"); + deliverAssignment(1, slice("", "a")); + + deliverAddresses(config(OTHER_CHANNEL_FACTORY_KEY, true)); + + // The stream is cancelled before its channel is handed back, so no later assignment can + // revive the policy. Nothing is leased for the new key until an update is accepted. + assertThat(channelFactory.isReleased(0)).isTrue(); + assertThat(channelFactory.liveCallsAtRelease).containsExactly(0); + assertThat(channelFactory.keys).containsExactly(CHANNEL_FACTORY_KEY); + assertThat(pick("k").getStatus().getDescription()).contains("no endpoints"); + + deliverAddresses(config(OTHER_CHANNEL_FACTORY_KEY, true), "a"); + + assertThat(channelFactory.keys) + .containsExactly(CHANNEL_FACTORY_KEY, OTHER_CHANNEL_FACTORY_KEY) + .inOrder(); + } + + @Test + public void missingChannelFactory_stillUpdatesTheEndpoints() throws Exception { + deliverAddresses(config(CHANNEL_FACTORY_KEY, false), "a"); + reportReady("a"); + + Status status = deliverWithoutChannelFactory(config(CHANNEL_FACTORY_KEY, false), "b"); + + assertThat(status.isOk()).isFalse(); + assertThat(childForHost("a").shutdown).isTrue(); + } + + @Test + public void missingChannelFactory_laterChildUpdate_staysInTransientFailure() throws Exception { + deliverAddresses(config(CHANNEL_FACTORY_KEY, true), "a"); + deliverAssignment(1, slice("", "a")); + reportReady("a"); + + deliverWithoutChannelFactory(config(CHANNEL_FACTORY_KEY, true), "a"); + syncContext.execute(() -> childForHost("a").reportReady()); + + // The failure stands until an update is accepted, whatever the endpoints report meanwhile. + assertThat(currentState).isEqualTo(TRANSIENT_FAILURE); + assertThat(pick("k").getStatus().getDescription()).contains("no channel factory"); + } + + @Test + public void keyHeaderNameChangedWhileEndpointsEmpty_stillTakesEffect() throws Exception { + deliverAddresses(configWithKeyHeader(KEY_HEADER), "a", "b"); + deliverAssignment(1, slice("", "a"), slice("m", "b")); + + deliverAddresses(configWithKeyHeader(OTHER_KEY_HEADER)); + deliverAddresses(configWithKeyHeader(OTHER_KEY_HEADER), "a", "b"); + // The update without endpoints closed the previous client, so the new one reports afresh. + deliverAssignment(1, slice("", "a"), slice("m", "b")); + reportReady("a"); + reportReady("b"); + + // Read under the new header, "z" is past "m" and belongs to "b". Were the policy still + // reading the old header, it would find nothing and fail the pick. + assertThat(pickedHost(pick(OTHER_KEY_HEADER, "z"))).isEqualTo("b"); + } + + @Test + public void missingKeyHeader_failsPickEvenWithFallback() throws Exception { + deliverAddresses(config(CHANNEL_FACTORY_KEY, true), "a", "b"); + deliverAssignment(1, slice("", "a"), slice("m", "b")); + reportReady("a"); + reportReady("b"); + + PickResult result = pick(OTHER_KEY_HEADER, "z"); + + assertThat(result.isDrop()).isFalse(); + assertThat(result.getStatus().getCode()).isEqualTo(Status.Code.UNAVAILABLE); + assertThat(result.getStatus().getDescription()).contains(KEY_HEADER); + } + + // --------------------------------------------------------------------------------------------- + // Channel to the sharding service + // --------------------------------------------------------------------------------------------- + + @Test + public void firstUpdate_createsChannelAndOpensStream() throws Exception { + deliverAddresses(config(CHANNEL_FACTORY_KEY, true), "a"); + + assertThat(channelFactory.keys).containsExactly(CHANNEL_FACTORY_KEY); + WatchShardingAssignmentRequest request = takeRequest(); + assertThat(request.getInitialClientConfig().getTarget()).isEqualTo(TARGET); + assertThat(request.getInitialClientConfig().getClientUuid()).isEqualTo("client-uuid"); + } + + @Test + public void unchangedKey_reusesChannelAndStream() throws Exception { + deliverAddresses(config(CHANNEL_FACTORY_KEY, true), "a"); + takeRequest(); + + deliverAddresses(config(CHANNEL_FACTORY_KEY, true), "a", "b"); + + assertThat(channelFactory.keys).containsExactly(CHANNEL_FACTORY_KEY); + assertThat(service.streamCount.get()).isEqualTo(1); + } + + @Test + public void changedKey_createsNewChannelClosesOldAndRestartsStream() throws Exception { + deliverAddresses(config(CHANNEL_FACTORY_KEY, true), "a"); + takeRequest(); + + deliverAddresses(config(OTHER_CHANNEL_FACTORY_KEY, true), "a"); + + assertThat(channelFactory.keys) + .containsExactly(CHANNEL_FACTORY_KEY, OTHER_CHANNEL_FACTORY_KEY) + .inOrder(); + assertThat(channelFactory.isReleased(0)).isTrue(); + assertThat(channelFactory.isReleased(1)).isFalse(); + assertThat(service.streamCount.get()).isEqualTo(2); + } + + @Test + public void changedKey_cancelsOldStreamBeforeReleasingOldChannel() throws Exception { + deliverAddresses(config(CHANNEL_FACTORY_KEY, true), "a"); + takeRequest(); + + deliverAddresses(config(OTHER_CHANNEL_FACTORY_KEY, true), "a"); + + assertThat(channelFactory.isReleased(0)).isTrue(); + assertThat(channelFactory.liveCallsAtRelease).containsExactly(0); + } + + @Test + public void changedTarget_restartsStreamWithoutNewChannel() throws Exception { + deliverAddresses(config(CHANNEL_FACTORY_KEY, true), "a"); + takeRequest(); + + deliverAddresses(retargetedConfig("other-target"), "a"); + + assertThat(channelFactory.keys).containsExactly(CHANNEL_FACTORY_KEY); + // The new client streams on the same channel, so its lease stays open. + assertThat(channelFactory.released).isEmpty(); + assertThat(service.streamCount.get()).isEqualTo(2); + assertThat(takeRequest().getInitialClientConfig().getTarget()).isEqualTo("other-target"); + } + + @Test + public void targetWithLocalityToken_allEndpointsInOneLocality_isSubstituted() + throws Exception { + // What a child of weighted_target sees under xDS: only its own locality's endpoints. + deliverEndpoints( + retargetedConfig("target/%s"), + endpointInLocality("a", "us-central1-a"), + endpointInLocality("b", "us-central1-a")); + + assertThat(takeRequest().getInitialClientConfig().getTarget()) + .isEqualTo("target/us-central1-a"); + } + + @Test + public void targetWithTwoLocalityTokens_substitutesOnlyTheFirst() throws Exception { + deliverEndpoints(retargetedConfig("target/%s/%s"), endpointInLocality("a", "us-central1-a")); + + assertThat(takeRequest().getInitialClientConfig().getTarget()) + .isEqualTo("target/us-central1-a/%s"); + } + + @Test + public void changedLocality_createsANewClientEvenThoughTheConfigIsUnchanged() throws Exception { + AutoShardingLoadBalancerConfig localityConfig = retargetedConfig("target/%s"); + deliverEndpoints(localityConfig, endpointInLocality("a", "us-central1-a")); + takeRequest(); + + deliverEndpoints(localityConfig, endpointInLocality("a", "us-central1-b")); + + assertThat(channelFactory.keys).containsExactly(CHANNEL_FACTORY_KEY); + assertThat(service.streamCount.get()).isEqualTo(2); + assertThat(takeRequest().getInitialClientConfig().getTarget()) + .isEqualTo("target/us-central1-b"); + } + + @Test + public void targetWithLocalityToken_someEndpointsWithoutLocality_substitutesEmptyString() + throws Exception { + deliverEndpoints( + retargetedConfig("target/%s"), + endpointInLocality("a", "us-central1-a"), + endpoints("b").get(0)); + + assertThat(takeRequest().getInitialClientConfig().getTarget()).isEqualTo("target/"); + } + + @Test + public void targetWithLocalityToken_endpointsRetracted_neverTargetsTheEmptyLocality() + throws Exception { + AutoShardingLoadBalancerConfig localityConfig = retargetedConfig("target/%s"); + deliverEndpoints(localityConfig, endpointInLocality("a", "us-central1-a")); + takeRequest(); + + // An empty update carries no locality, and is rejected before a target is resolved from it. + deliverEndpoints(localityConfig); + deliverEndpoints(localityConfig, endpointInLocality("a", "us-central1-a")); + + assertThat(service.streamCount.get()).isEqualTo(2); + assertThat(takeRequest().getInitialClientConfig().getTarget()) + .isEqualTo("target/us-central1-a"); + } + + @Test + public void targetChangedWhileEndpointsRetracted_appliesOnceEndpointsReturn() + throws Exception { + deliverEndpoints(retargetedConfig("target/%s"), endpointInLocality("a", "us-central1-a")); + takeRequest(); + + deliverEndpoints(retargetedConfig("other/%s")); + + assertThat(service.streamCount.get()).isEqualTo(1); + + deliverEndpoints(retargetedConfig("other/%s"), endpointInLocality("a", "us-central1-a")); + + assertThat(takeRequest().getInitialClientConfig().getTarget()) + .isEqualTo("other/us-central1-a"); + } + + @Test + public void targetWithLocalityToken_noLocality_substitutesEmptyString() throws Exception { + deliverAddresses(retargetedConfig("target/%s"), "a"); + + assertThat(takeRequest().getInitialClientConfig().getTarget()).isEqualTo("target/"); + } + + @Test + public void targetWithLocalityToken_endpointsSpanLocalities_substitutesEmptyString() + throws Exception { + // The policy is doing its own locality picking, so it sees endpoints from every locality. + // gRFC A119 says the token is not meant to be used here; the target must not end up depending + // on which endpoint the resolver happened to list first. + deliverEndpoints( + retargetedConfig("target/%s"), + endpointInLocality("a", "us-central1-a"), + endpointInLocality("b", "us-central1-b")); + + assertThat(takeRequest().getInitialClientConfig().getTarget()).isEqualTo("target/"); + } + + @Test + public void targetWithLocalityToken_endpointReordering_doesNotRecreateTheClient() + throws Exception { + AutoShardingLoadBalancerConfig localityConfig = retargetedConfig("target/%s"); + deliverEndpoints( + localityConfig, + endpointInLocality("a", "us-central1-a"), + endpointInLocality("b", "us-central1-b")); + takeRequest(); + + // Same endpoints, other order. Sourcing the locality from the first endpoint would change the + // target here and reconnect the client to a different sharding resource. + deliverEndpoints( + localityConfig, + endpointInLocality("b", "us-central1-b"), + endpointInLocality("a", "us-central1-a")); + + assertThat(service.streamCount.get()).isEqualTo(1); + } + + // --------------------------------------------------------------------------------------------- + // Startup: queuing, timeout and fallback + // --------------------------------------------------------------------------------------------- + + @Test + public void beforeFirstAssignment_queuesRpcs() { + deliverAddresses(config(CHANNEL_FACTORY_KEY, true), "a", "b"); + + // Unlike CONNECTING, IDLE keeps a parent priority policy from failing over while the + // sharding service is still answering. + assertThat(currentState).isEqualTo(IDLE); + PickResult result = pick("anything"); + assertThat(result.getSubchannel()).isNull(); + assertThat(result.getStatus().isOk()).isTrue(); + } + + @Test + public void beforeFirstAssignment_endpointReady_staysIdleAndKeepsQueuing() { + deliverAddresses(config(CHANNEL_FACTORY_KEY, true), "a"); + activate("a"); + reportReady("a"); + + // A READY state with a picker that only queues would misdescribe the policy. + assertThat(currentState).isEqualTo(IDLE); + assertThat(pick("k").getSubchannel()).isNull(); + } + + @Test + public void beforeFirstAssignment_endpointsFailing_staysIdleAndKeepsQueuing() { + deliverAddresses(config(CHANNEL_FACTORY_KEY, true), "a", "b"); + + reportTransientFailure("a"); + reportTransientFailure("b"); + + assertThat(currentState).isEqualTo(IDLE); + assertThat(pick("k").getSubchannel()).isNull(); + assertThat(pick("k").getStatus().isOk()).isTrue(); + } + + @Test + public void beforeFirstAssignment_endpointInTransientFailure_wakesNoOtherEndpoint() { + deliverAddresses(config(CHANNEL_FACTORY_KEY, true), "a", "b", "c"); + + reportTransientFailure("a"); + + // The policy reports IDLE, not TRANSIENT_FAILURE, so there is nothing to recover from yet. + assertThat(currentState).isEqualTo(IDLE); + assertThat(pick("k").getSubchannel()).isNull(); + assertThat(activatedHostnames()).containsExactly("a"); + } + + @Test + public void beforeFirstAssignment_allEndpointsIdle_connectsNothing() { + deliverAddresses(config(CHANNEL_FACTORY_KEY, true), "a", "b"); + + pick("k"); + + assertThat(childProvider.children).isEmpty(); + } + + @Test + public void initialAssignmentTimeout_fallbackEnabled_spreadsAcrossAllEndpoints() { + deliverAddresses(config(CHANNEL_FACTORY_KEY, true), "a", "b"); + reportReady("a"); + reportReady("b"); + + fakeClock.forwardNanos(ASSIGNMENT_TIMEOUT_NANOS); + + assertThat(currentState).isEqualTo(READY); + assertThat(pickedHost(pick("k"))).isAnyOf("a", "b"); + } + + @Test + public void initialAssignmentTimeout_fallbackDisabled_failsRpcs() { + deliverAddresses(config(CHANNEL_FACTORY_KEY, false), "a"); + reportReady("a"); + + fakeClock.forwardNanos(ASSIGNMENT_TIMEOUT_NANOS); + + PickResult result = pick("k"); + assertThat(currentState).isEqualTo(TRANSIENT_FAILURE); + assertThat(result.getStatus().getCode()).isEqualTo(Status.Code.UNAVAILABLE); + assertThat(result.getStatus().getDescription()).contains("timed out"); + } + + @Test + public void assignmentBeforeTimeout_cancelsTheTimer() throws Exception { + deliverAddresses(config(CHANNEL_FACTORY_KEY, true), "a"); + assertThat(fakeClock.numPendingTasks()).isEqualTo(1); + + deliverAssignment(1, slice("", "a")); + + assertThat(fakeClock.numPendingTasks()).isEqualTo(0); + } + + @Test + public void newChannel_keepsServingPreviousAssignmentWhileTimerPending() throws Exception { + deliverAddresses(config(CHANNEL_FACTORY_KEY, true), "a", "b"); + deliverAssignment(1, slice("", "a"), slice("m", "b")); + reportReady("a"); + reportReady("b"); + assertThat(pickedHost(pick("z"))).isEqualTo("b"); + + // Switching sharding service must not interrupt traffic. + deliverAddresses(config(OTHER_CHANNEL_FACTORY_KEY, true), "a", "b"); + + assertThat(pickedHost(pick("z"))).isEqualTo("b"); + assertThat(pickedHost(pick("a"))).isEqualTo("a"); + } + + @Test + public void newChannel_restartsTheInitialAssignmentTimer() throws Exception { + deliverAddresses(config(CHANNEL_FACTORY_KEY, true), "a"); + deliverAssignment(1, slice("", "a")); + assertThat(fakeClock.numPendingTasks()).isEqualTo(0); + + deliverAddresses(config(OTHER_CHANNEL_FACTORY_KEY, true), "a"); + + assertThat(fakeClock.numPendingTasks()).isEqualTo(1); + } + + @Test + public void newChannel_timeoutOfTheNewClient_replacesThePreviousAssignment() throws Exception { + deliverAddresses(config(CHANNEL_FACTORY_KEY, false), "a"); + deliverAssignment(1, slice("", "a")); + reportReady("a"); + + deliverAddresses(config(OTHER_CHANNEL_FACTORY_KEY, false), "a"); + assertThat(pickedHost(pick("k"))).isEqualTo("a"); + + fakeClock.forwardNanos(ASSIGNMENT_TIMEOUT_NANOS); + + assertThat(currentState).isEqualTo(TRANSIENT_FAILURE); + assertThat(pick("k").getStatus().getDescription()).contains("timed out"); + } + + @Test + public void changedTarget_restartsTheInitialAssignmentTimer() throws Exception { + deliverAddresses(config(CHANNEL_FACTORY_KEY, true), "a"); + deliverAssignment(1, slice("", "a")); + + deliverAddresses(retargetedConfig("other-target"), "a"); + + assertThat(fakeClock.numPendingTasks()).isEqualTo(1); + } + + @Test + public void changedTarget_inFallback_keepsServingInsteadOfQueuing() { + deliverAddresses(config(CHANNEL_FACTORY_KEY, true), "a", "b"); + reportReady("a"); + reportReady("b"); + fakeClock.forwardNanos(ASSIGNMENT_TIMEOUT_NANOS); + assertThat(pickedHost(pick("k"))).isAnyOf("a", "b"); + + deliverAddresses(retargetedConfig("other-target"), "a", "b"); + + // The previous client's error is kept until the new client reports. + assertThat(currentState).isEqualTo(READY); + assertThat(pickedHost(pick("k"))).isAnyOf("a", "b"); + } + + @Test + public void changedTarget_whileTimerPending_restartsTheDeadline() { + deliverAddresses(config(CHANNEL_FACTORY_KEY, true), "a"); + reportReady("a"); + fakeClock.forwardNanos(ASSIGNMENT_TIMEOUT_NANOS - 1); + + deliverAddresses(retargetedConfig("other-target"), "a"); + fakeClock.forwardNanos(1); + assertThat(pick("k").getSubchannel()).isNull(); + + fakeClock.forwardNanos(ASSIGNMENT_TIMEOUT_NANOS - 1); + + assertThat(pickedHost(pick("k"))).isEqualTo("a"); + } + + @Test + public void unusableAssignment_beforeAnyAssignment_entersFallback() throws Exception { + deliverAddresses(config(CHANNEL_FACTORY_KEY, true), "a", "b"); + reportReady("a"); + reportReady("b"); + + pushUnusableAssignment(1); + + assertThat(currentState).isEqualTo(READY); + assertThat(pickedHost(pick("k"))).isAnyOf("a", "b"); + } + + @Test + public void unusableAssignment_beforeAnyAssignment_fallbackDisabled_failsRpcs() throws Exception { + deliverAddresses(config(CHANNEL_FACTORY_KEY, false), "a"); + reportReady("a"); + + pushUnusableAssignment(1); + + assertThat(currentState).isEqualTo(TRANSIENT_FAILURE); + assertThat(pick("k").getStatus().getDescription()).contains("no usable slices"); + } + + @Test + public void assignmentWithNoSlices_beforeAnyAssignment_entersFallback() throws Exception { + deliverAddresses(config(CHANNEL_FACTORY_KEY, true), "a"); + reportReady("a"); + + deliverAssignment(1); + + assertThat(currentState).isEqualTo(READY); + assertThat(pickedHost(pick("k"))).isEqualTo("a"); + } + + @Test + public void assignmentWithNoSlices_afterAGoodOne_keepsServingTheGoodOne() throws Exception { + deliverAddresses(config(CHANNEL_FACTORY_KEY, false), "a"); + deliverAssignment(1, slice("", "a")); + reportReady("a"); + + // Rejected like an unusable assignment, so the previous one keeps applying. + deliverAssignment(2); + + assertThat(pickedHost(pick("k"))).isEqualTo("a"); + } + + @Test + public void sliceAssignedNoEndpoints_fallbackEnabled_dropsPicks() throws Exception { + deliverAddresses(config(CHANNEL_FACTORY_KEY, true), "a"); + reportReady("a"); + StreamObserver serverStream = currentServerStream(); + + serverStream.onNext( + WatchShardingAssignmentResponse.newBuilder() + .setChunk( + AssignmentChunk.newBuilder() + .addEndpoints(EndpointState.newBuilder().setEndpoint("a")) + .addSliceAssignments(sliceAssignment("", "m", 0)) + .addSliceAssignments( + SliceAssignment.newBuilder() + .setSlice( + com.google.cloud.autosharding.v1.Slice.newBuilder() + .setStartKey(ByteString.copyFromUtf8("m"))))) + .build()); + serverStream.onNext( + WatchShardingAssignmentResponse.newBuilder() + .setMetadata(AssignmentMetadata.newBuilder().setGeneration(1)) + .build()); + + assertThat(pickedHost(pick("alpha"))).isEqualTo("a"); + // The server assigned ["m", inf) nothing on purpose, so it does not fall back. + PickResult result = pick("zulu"); + assertThat(result.isDrop()).isTrue(); + assertThat(result.getStatus().getCode()).isEqualTo(Status.Code.UNAVAILABLE); + } + + @Test + public void streamFailure_beforeAnyAssignment_entersFallback() throws Exception { + deliverAddresses(config(CHANNEL_FACTORY_KEY, true), "a", "b"); + reportReady("a"); + reportReady("b"); + + currentServerStream().onError(Status.UNAVAILABLE.asRuntimeException()); + + assertThat(currentState).isEqualTo(READY); + assertThat(pickedHost(pick("k"))).isAnyOf("a", "b"); + } + + @Test + public void unusableAssignment_thenGoodOneBeforeTimeout_usesTheGoodOne() throws Exception { + deliverAddresses(config(CHANNEL_FACTORY_KEY, true), "a", "b"); + reportReady("a"); + reportReady("b"); + + pushUnusableAssignment(1); + deliverAssignment(2, slice("", "a"), slice("m", "b")); + + assertThat(pickedHost(pick("alpha"))).isEqualTo("a"); + assertThat(pickedHost(pick("zulu"))).isEqualTo("b"); + assertThat(fakeClock.numPendingTasks()).isEqualTo(0); + } + + @Test + public void unusableAssignment_afterAGoodOne_keepsServingTheGoodOne() throws Exception { + deliverAddresses(config(CHANNEL_FACTORY_KEY, true), "a", "b"); + deliverAssignment(1, slice("", "a"), slice("m", "b")); + reportReady("a"); + reportReady("b"); + + pushUnusableAssignment(2); + + assertThat(pickedHost(pick("alpha"))).isEqualTo("a"); + assertThat(pickedHost(pick("zulu"))).isEqualTo("b"); + } + + // --------------------------------------------------------------------------------------------- + // Routing on assignments + // --------------------------------------------------------------------------------------------- + + @Test + public void assignmentRoutesByKeyRange() throws Exception { + deliverAddresses(config(CHANNEL_FACTORY_KEY, true), "a", "b"); + deliverAssignment(1, slice("", "a"), slice("m", "b")); + reportReady("a"); + reportReady("b"); + + assertThat(pickedHost(pick("alpha"))).isEqualTo("a"); + assertThat(pickedHost(pick("zulu"))).isEqualTo("b"); + } + + @Test + public void assignmentNamingUnknownHostname_dropsIt() throws Exception { + deliverAddresses(config(CHANNEL_FACTORY_KEY, false), "a"); + // The sharding service still believes "ghost" is serving; the resolver disagrees. + deliverAssignment(1, slice("", "ghost")); + reportReady("a"); + + PickResult result = pick("k"); + assertThat(result.getStatus().getCode()).isEqualTo(Status.Code.UNAVAILABLE); + } + + @Test + public void assignmentNamingUnknownHostname_fallbackEnabled_usesFallbackPool() throws Exception { + deliverAddresses(config(CHANNEL_FACTORY_KEY, true), "a"); + deliverAssignment(1, slice("", "ghost")); + reportReady("a"); + + assertThat(pickedHost(pick("k"))).isEqualTo("a"); + } + + @Test + public void resolverUpdateAfterAssignment_rebuildsSliceMapWithNewIndices() throws Exception { + deliverAddresses(config(CHANNEL_FACTORY_KEY, true), "a", "b"); + deliverAssignment(1, slice("", "b")); + reportReady("a"); + reportReady("b"); + assertThat(pickedHost(pick("k"))).isEqualTo("b"); + + // "b" moves from index 1 to index 0. If the slice map were not rebuilt, the stale index + // would now route to "a". + deliverAddresses(config(CHANNEL_FACTORY_KEY, true), "b", "a"); + + assertThat(pickedHost(pick("k"))).isEqualTo("b"); + } + + @Test + public void staleGenerationAssignment_isIgnored() throws Exception { + deliverAddresses(config(CHANNEL_FACTORY_KEY, true), "a", "b"); + deliverAssignment(5, slice("", "a")); + reportReady("a"); + reportReady("b"); + assertThat(pickedHost(pick("k"))).isEqualTo("a"); + + pushAssignment(3, slice("", "b")); + + assertThat(pickedHost(pick("k"))).isEqualTo("a"); + } + + // --------------------------------------------------------------------------------------------- + // Child state updates and aggregated connectivity state + // --------------------------------------------------------------------------------------------- + + @Test + public void childStateUpdate_republishesPicker() throws Exception { + deliverAddresses(config(CHANNEL_FACTORY_KEY, true), "a", "b"); + deliverAssignment(1, slice("", "a")); + int updatesBefore = balancingStateUpdates; + + reportReady("a"); + + assertThat(balancingStateUpdates).isGreaterThan(updatesBefore); + assertThat(currentState).isEqualTo(READY); + assertThat(pickedHost(pick("k"))).isEqualTo("a"); + } + + @Test + public void allEndpointsIdle_reportsIdle() throws Exception { + deliverAddresses(config(CHANNEL_FACTORY_KEY, true), "a", "b"); + deliverAssignment(1, slice("", "a")); + + assertThat(currentState).isEqualTo(IDLE); + } + + @Test + public void twoEndpointsInTransientFailure_reportsTransientFailure() throws Exception { + deliverAddresses(config(CHANNEL_FACTORY_KEY, true), "a", "b"); + deliverAssignment(1, slice("", "a"), slice("m", "b")); + + reportTransientFailure("a"); + reportTransientFailure("b"); + + assertThat(currentState).isEqualTo(TRANSIENT_FAILURE); + } + + @Test + public void oneEndpointInTransientFailure_wakesUpAnIdleEndpoint() throws Exception { + deliverAddresses(config(CHANNEL_FACTORY_KEY, true), "a", "b", "c"); + deliverAssignment(1, slice("", "a")); + + reportTransientFailure("a"); + + // Aggregated state is CONNECTING, and nothing was connecting, so exactly one IDLE endpoint + // is nudged so the policy can recover without needing a pick. + assertThat(currentState).isEqualTo(CONNECTING); + assertThat(childProvider.children).hasSize(2); + assertThat(childForHost("b").requestConnectionCount).isEqualTo(1); + } + + @Test + public void endpointAlreadyConnecting_noAdditionalWakeUp() throws Exception { + deliverAddresses(config(CHANNEL_FACTORY_KEY, true), "a", "b", "c"); + deliverAssignment(1, slice("", "a")); + activate("b"); + + reportTransientFailure("a"); + + // "b" is already CONNECTING, so "c" is left alone. + assertThat(currentState).isEqualTo(CONNECTING); + assertThat(activatedHostnames()).containsExactly("a", "b"); + } + + @Test + public void requestConnection_connectsNothing() throws Exception { + deliverAddresses(config(CHANNEL_FACTORY_KEY, true), "a", "b"); + + syncContext.execute(loadBalancer::requestConnection); + deliverAssignment(1, slice("", "a")); + syncContext.execute(loadBalancer::requestConnection); + + // Connections are made by picks, and by the wake-up on child and resolver updates. + assertThat(childProvider.children).isEmpty(); + } + + @Test + public void picksOnIdleEndpointTriggerConnection() throws Exception { + deliverAddresses(config(CHANNEL_FACTORY_KEY, true), "a"); + deliverAssignment(1, slice("", "a")); + assertThat(childProvider.children).isEmpty(); + + PickResult result = pick("k"); + + assertThat(result.getSubchannel()).isNull(); + assertThat(childProvider.children).hasSize(1); + } + + // --------------------------------------------------------------------------------------------- + // Name resolution errors and shutdown + // --------------------------------------------------------------------------------------------- + + @Test + public void nameResolutionError_withKnownEndpoints_keepsServing() throws Exception { + deliverAddresses(config(CHANNEL_FACTORY_KEY, true), "a"); + deliverAssignment(1, slice("", "a")); + reportReady("a"); + + syncContext.execute( + () -> loadBalancer.handleNameResolutionError(Status.UNAVAILABLE.withDescription("boom"))); + + assertThat(currentState).isEqualTo(READY); + assertThat(pickedHost(pick("k"))).isEqualTo("a"); + } + + @Test + public void nameResolutionError_whileIdleWithAnAssignment_keepsServing() throws Exception { + deliverAddresses(config(CHANNEL_FACTORY_KEY, true), "a"); + deliverAssignment(1, slice("", "a")); + assertThat(currentState).isEqualTo(IDLE); + + syncContext.execute( + () -> loadBalancer.handleNameResolutionError(Status.UNAVAILABLE.withDescription("boom"))); + + // IDLE endpoints report nothing until picked, so a failing picker published here would never + // be replaced; the lazy policy must keep its picker so that picks connect. + assertThat(currentState).isEqualTo(IDLE); + PickResult result = pick("k"); + assertThat(result.getStatus().isOk()).isTrue(); + assertThat(childProvider.children).hasSize(1); + } + + @Test + public void nameResolutionError_whileIdleInFallback_keepsServing() { + deliverAddresses(config(CHANNEL_FACTORY_KEY, true), "a"); + fakeClock.forwardNanos(ASSIGNMENT_TIMEOUT_NANOS); + assertThat(currentState).isEqualTo(IDLE); + + syncContext.execute( + () -> loadBalancer.handleNameResolutionError(Status.UNAVAILABLE.withDescription("boom"))); + + assertThat(currentState).isEqualTo(IDLE); + assertThat(pick("k").getStatus().isOk()).isTrue(); + assertThat(childProvider.children).hasSize(1); + } + + @Test + public void nameResolutionError_withNoEndpoints_reportsTransientFailure() { + syncContext.execute( + () -> loadBalancer.handleNameResolutionError(Status.UNAVAILABLE.withDescription("boom"))); + + assertThat(currentState).isEqualTo(TRANSIENT_FAILURE); + assertThat(pick("k").getStatus().getDescription()).contains("boom"); + } + + @Test + public void nameResolutionError_afterRejectedUpdate_reportsTheResolverError() throws Exception { + deliverAddresses(config(CHANNEL_FACTORY_KEY, true), "a"); + deliverAssignment(1, slice("", "a")); + reportReady("a"); + deliverWithoutChannelFactory(config(CHANNEL_FACTORY_KEY, true), "a"); + + syncContext.execute( + () -> loadBalancer.handleNameResolutionError(Status.UNAVAILABLE.withDescription("boom"))); + syncContext.execute(() -> childForHost("a").reportReady()); + + // Nothing is being served after a rejected update, so the newer error is reported instead, + // and it too stands until an update is accepted. + assertThat(currentState).isEqualTo(TRANSIENT_FAILURE); + assertThat(pick("k").getStatus().getDescription()).contains("boom"); + } + + @Test + public void nameResolutionError_withEndpointsButNoneReady_reportsTheResolverError() + throws Exception { + deliverAddresses(config(CHANNEL_FACTORY_KEY, true), "a"); + deliverAssignment(1, slice("", "a")); + reportTransientFailure("a"); + + syncContext.execute( + () -> loadBalancer.handleNameResolutionError(Status.UNAVAILABLE.withDescription("boom"))); + + // We are not serving, so the resolver failure is the more useful thing to report. Leaving it + // out would make RPCs blame the endpoints we can no longer refresh. + assertThat(currentState).isEqualTo(TRANSIENT_FAILURE); + assertThat(pick("k").getStatus().getDescription()).contains("boom"); + } + + @Test + public void nameResolutionError_whileAwaitingInitialAssignment_keepsQueueing() { + deliverAddresses(config(CHANNEL_FACTORY_KEY, true), "a", "b"); + // The endpoints are neither READY nor IDLE, so only the initial assignment wait can be + // holding these RPCs. + reportTransientFailure("a"); + assertThat(currentState).isEqualTo(IDLE); + + syncContext.execute( + () -> loadBalancer.handleNameResolutionError(Status.UNAVAILABLE.withDescription("boom"))); + + // gRFC A119 holds RPCs until the initial assignment timer fires; a failed refresh of + // endpoints we already have must not cut that short. + assertThat(currentState).isEqualTo(IDLE); + assertThat(pick("k").getStatus().isOk()).isTrue(); + assertThat(pick("k").getSubchannel()).isNull(); + } + + @Test + public void shutdown_closesChannelAndChildren() { + deliverAddresses(config(CHANNEL_FACTORY_KEY, true), "a"); + activate("a"); + + syncContext.execute(loadBalancer::shutdown); + + assertThat(channelFactory.isReleased(0)).isTrue(); + assertThat(childProvider.children.get(0).shutdown).isTrue(); + } + + @Test + public void shutdown_isIdempotent() { + deliverAddresses(config(CHANNEL_FACTORY_KEY, true), "a"); + + syncContext.execute(loadBalancer::shutdown); + syncContext.execute(loadBalancer::shutdown); + + assertThat(channelFactory.isReleased(0)).isTrue(); + } + + @Test + public void shutdown_cancelsInitialAssignmentTimer() { + deliverAddresses(config(CHANNEL_FACTORY_KEY, true), "a"); + assertThat(fakeClock.numPendingTasks()).isEqualTo(1); + + syncContext.execute(loadBalancer::shutdown); + + assertThat(fakeClock.numPendingTasks()).isEqualTo(0); + } + + // --------------------------------------------------------------------------------------------- + // Helpers + // --------------------------------------------------------------------------------------------- + + private AutoShardingLoadBalancerConfig config(String channelFactoryKey, boolean enableFallback) { + return new AutoShardingLoadBalancerConfig( + channelFactoryKey, + TARGET, + AutoShardingPicker.createKeyHeader(KEY_HEADER), + enableFallback, + ASSIGNMENT_TIMEOUT_NANOS); + } + + /** The default config with a different {@code autosharding_target}. */ + private AutoShardingLoadBalancerConfig retargetedConfig(String target) { + return new AutoShardingLoadBalancerConfig( + CHANNEL_FACTORY_KEY, + target, + AutoShardingPicker.createKeyHeader(KEY_HEADER), + true, + ASSIGNMENT_TIMEOUT_NANOS); + } + + /** The default config with a different {@code key_header_name}. */ + private AutoShardingLoadBalancerConfig configWithKeyHeader(String keyHeaderName) { + return new AutoShardingLoadBalancerConfig( + CHANNEL_FACTORY_KEY, + TARGET, + AutoShardingPicker.createKeyHeader(keyHeaderName), + true, + ASSIGNMENT_TIMEOUT_NANOS); + } + + private Attributes attributesWithChannelFactory() { + return Attributes.newBuilder() + .set(AutoShardingAttributes.ATTR_CHANNEL_FACTORY, channelFactory) + .build(); + } + + private Status deliverEndpoints( + AutoShardingLoadBalancerConfig config, EquivalentAddressGroup... endpoints) { + return acceptAddresses( + ResolvedAddresses.newBuilder() + .setAddresses(ImmutableList.copyOf(endpoints)) + .setAttributes(attributesWithChannelFactory()) + .setLoadBalancingPolicyConfig(config) + .build()); + } + + private Status deliverWithoutChannelFactory( + AutoShardingLoadBalancerConfig config, String... hostnames) { + return acceptAddresses( + ResolvedAddresses.newBuilder() + .setAddresses(endpoints(hostnames)) + .setAttributes(Attributes.EMPTY) + .setLoadBalancingPolicyConfig(config) + .build()); + } + + private Status deliverWithoutConfig(String... hostnames) { + return acceptAddresses( + ResolvedAddresses.newBuilder() + .setAddresses(endpoints(hostnames)) + .setAttributes(attributesWithChannelFactory()) + .build()); + } + + private Status deliverAddresses(AutoShardingLoadBalancerConfig config, String... hostnames) { + return acceptAddresses( + ResolvedAddresses.newBuilder() + .setAddresses(endpoints(hostnames)) + .setAttributes(attributesWithChannelFactory()) + .setLoadBalancingPolicyConfig(config) + .build()); + } + + private Status deliverWithChannelFactory( + ChannelFactory factory, AutoShardingLoadBalancerConfig config, String... hostnames) { + return acceptAddresses( + ResolvedAddresses.newBuilder() + .setAddresses(endpoints(hostnames)) + .setAttributes( + Attributes.newBuilder() + .set(AutoShardingAttributes.ATTR_CHANNEL_FACTORY, factory) + .build()) + .setLoadBalancingPolicyConfig(config) + .build()); + } + + private Status acceptAddresses(ResolvedAddresses resolvedAddresses) { + AtomicReference status = new AtomicReference<>(); + syncContext.execute(() -> status.set(loadBalancer.acceptResolvedAddresses(resolvedAddresses))); + return status.get(); + } + + private static List endpoints(String... hostnames) { + List eags = new ArrayList<>(); + for (String hostname : hostnames) { + eags.add( + new EquivalentAddressGroup( + new NamedAddress("addr-" + hostname), + Attributes.newBuilder() + .set(InternalEquivalentAddressGroup.ATTR_ADDRESS_NAME, hostname) + .build())); + } + return ImmutableList.copyOf(eags); + } + + private static EquivalentAddressGroup endpointInLocality(String hostname, String locality) { + return new EquivalentAddressGroup( + new NamedAddress("addr-" + hostname), + Attributes.newBuilder() + .set(InternalEquivalentAddressGroup.ATTR_ADDRESS_NAME, hostname) + .set(EquivalentAddressGroup.ATTR_LOCALITY_NAME, locality) + .build()); + } + + /** Sends an assignment from the fake service and waits for the load balancer to apply it. */ + private void deliverAssignment(long generation, SliceSpec... slices) throws Exception { + pushAssignment(generation, slices); + } + + /** + * Sends an assignment whose only slice fails validation. Nothing usable remains, so the client + * reports an error to the load balancer instead of an assignment. + */ + private void pushUnusableAssignment(long generation) throws Exception { + StreamObserver serverStream = currentServerStream(); + serverStream.onNext( + WatchShardingAssignmentResponse.newBuilder() + .setChunk( + AssignmentChunk.newBuilder() + .addEndpoints(EndpointState.newBuilder().setEndpoint("a")) + // Index 7 is past the end of the endpoint list above. + .addSliceAssignments(sliceAssignment("", null, 7))) + .build()); + serverStream.onNext( + WatchShardingAssignmentResponse.newBuilder() + .setMetadata(AssignmentMetadata.newBuilder().setGeneration(generation)) + .build()); + } + + private void pushAssignment(long generation, SliceSpec... slices) throws Exception { + StreamObserver serverStream = currentServerStream(); + List endpointNames = new ArrayList<>(); + for (SliceSpec spec : slices) { + if (!endpointNames.contains(spec.hostname)) { + endpointNames.add(spec.hostname); + } + } + + AssignmentChunk.Builder chunk = AssignmentChunk.newBuilder(); + for (String name : endpointNames) { + chunk.addEndpoints(EndpointState.newBuilder().setEndpoint(name)); + } + for (int i = 0; i < slices.length; i++) { + SliceSpec spec = slices[i]; + String endKey = i + 1 < slices.length ? slices[i + 1].startKey : null; + chunk.addSliceAssignments( + sliceAssignment(spec.startKey, endKey, endpointNames.indexOf(spec.hostname))); + } + + serverStream.onNext(WatchShardingAssignmentResponse.newBuilder().setChunk(chunk).build()); + serverStream.onNext( + WatchShardingAssignmentResponse.newBuilder() + .setMetadata(AssignmentMetadata.newBuilder().setGeneration(generation)) + .build()); + } + + private static SliceSpec slice(String startKey, String hostname) { + return new SliceSpec(startKey, hostname); + } + + private static final class SliceSpec { + final String startKey; + final String hostname; + + SliceSpec(String startKey, String hostname) { + this.startKey = startKey; + this.hostname = hostname; + } + } + + private static SliceAssignment sliceAssignment( + String startKey, @Nullable String endKey, int endpointIndex) { + com.google.cloud.autosharding.v1.Slice.Builder slice = + com.google.cloud.autosharding.v1.Slice.newBuilder() + .setStartKey(ByteString.copyFromUtf8(startKey)); + if (endKey != null) { + slice.setEndKey(ByteString.copyFromUtf8(endKey)); + } + return SliceAssignment.newBuilder() + .setSlice(slice) + .addEndpoints(PerSliceEndpointState.newBuilder().setEndpointIndex(endpointIndex)) + .build(); + } + + private PickResult pick(String key) { + return pick(KEY_HEADER, key); + } + + private PickResult pick(String headerName, String key) { + Metadata headers = new Metadata(); + headers.put(Metadata.Key.of(headerName, Metadata.ASCII_STRING_MARSHALLER), key); + return currentPicker.pickSubchannel( + new PickSubchannelArgsImpl(METHOD, headers, CallOptions.DEFAULT, new PickDetailsConsumer() { + })); + } + + /** Returns the hostname of the endpoint the pick landed on. */ + private String pickedHost(PickResult result) { + Subchannel subchannel = result.getSubchannel(); + if (subchannel == null) { + throw new AssertionError("Pick did not select a subchannel: " + result); + } + for (FakeChild child : childProvider.children) { + if (child.subchannel == subchannel) { + return child.hostname; + } + } + throw new AssertionError("Pick returned an unrecognized subchannel"); + } + + /** + * Instantiates the child load balancer for {@code hostname} by asking its endpoint to connect, + * which is how the picker brings an endpoint out of IDLE at runtime. + */ + private void activate(String hostname) { + syncContext.execute( + () -> { + EndpointMap endpointMap = loadBalancer.getEndpointMap(); + int index = endpointMap.indexOf(hostname); + if (index == -1) { + throw new AssertionError("Unknown endpoint hostname " + hostname); + } + endpointMap.toPickerEndpoints().get(index).requestConnection(); + }); + } + + private void reportReady(String hostname) { + activate(hostname); + syncContext.execute(() -> childForHost(hostname).reportReady()); + } + + private void reportTransientFailure(String hostname) { + activate(hostname); + syncContext.execute(() -> childForHost(hostname).reportTransientFailure()); + } + + private FakeChild childForHost(String hostname) { + for (FakeChild child : childProvider.children) { + if (hostname.equals(child.hostname)) { + return child; + } + } + throw new AssertionError("No child load balancer for hostname " + hostname); + } + + private WatchShardingAssignmentRequest takeRequest() throws Exception { + WatchShardingAssignmentRequest request = + service.requests.poll(POLL_TIMEOUT_SECONDS, TimeUnit.SECONDS); + if (request == null) { + fail("timed out waiting for a request to the sharding service"); + } + return request; + } + + /** + * Returns the stream the client currently has open to the sharding service, picking up a newly + * opened one if there is any. Streams are created synchronously by the in-process transport, so + * a non-blocking poll is enough once the first one exists. + */ + private StreamObserver currentServerStream() throws Exception { + StreamObserver next = service.serverStreams.poll(); + if (next != null) { + serverStream = next; + } else if (serverStream == null) { + serverStream = service.serverStreams.poll(POLL_TIMEOUT_SECONDS, TimeUnit.SECONDS); + if (serverStream == null) { + fail("timed out waiting for a stream to the sharding service"); + } + } + return serverStream; + } + + /** Hostnames whose child load balancer has been instantiated, in creation order. */ + private List activatedHostnames() { + List result = new ArrayList<>(); + for (FakeChild child : childProvider.children) { + result.add(child.hostname); + } + return result; + } + + /** A {@link SocketAddress} with a predictable {@link #toString}. */ + private static final class NamedAddress extends SocketAddress { + private static final long serialVersionUID = 0L; + private final String name; + + NamedAddress(String name) { + this.name = name; + } + + @Override + public String toString() { + return name; + } + } + + /** + * Hands out in-process channels, each wrapped so that successive leases are distinguishable + * even though they share one transport. + */ + private final class FakeChannelFactory implements ChannelFactory { + final List keys = new ArrayList<>(); + final List created = new ArrayList<>(); + final List released = new ArrayList<>(); + // Every createChannel() call, including the ones that throw. + int attempts; + + // Calls on each released channel that had not been cancelled when it was released. + final List liveCallsAtRelease = new ArrayList<>(); + + @Override + public ChannelLease createChannel(String channelFactoryKey) { + attempts++; + if (UNKNOWN_CHANNEL_FACTORY_KEY.equals(channelFactoryKey)) { + throw new IllegalArgumentException("unknown channel factory key"); + } + keys.add(channelFactoryKey); + WrappedChannel channel = new WrappedChannel(shardingChannel); + created.add(channel); + return new ChannelLease() { + private boolean closed; + + @Override + public Channel channel() { + return channel; + } + + @Override + public void close() { + if (closed) { + return; + } + closed = true; + released.add(channel); + liveCallsAtRelease.add(channel.liveCalls); + } + }; + } + + boolean isReleased(int index) { + Channel channel = created.get(index); + for (Channel released : this.released) { + if (released == channel) { + return true; + } + } + return false; + } + } + + /** Gives each lease a distinct channel over one shared transport. */ + private static final class WrappedChannel extends Channel { + private final Channel delegate; + // Calls created on this channel that the client has not cancelled. + int liveCalls; + + WrappedChannel(Channel delegate) { + this.delegate = delegate; + } + + @Override + public String authority() { + return delegate.authority(); + } + + @Override + public ClientCall newCall( + MethodDescriptor methodDescriptor, CallOptions callOptions) { + liveCalls++; + return new SimpleForwardingClientCall( + delegate.newCall(methodDescriptor, callOptions)) { + private boolean cancelled; + + @Override + public void cancel(@Nullable String message, @Nullable Throwable cause) { + if (!cancelled) { + cancelled = true; + liveCalls--; + } + super.cancel(message, cause); + } + }; + } + } + + private static final class FakeAutoshardingService + extends AutoshardingServiceGrpc.AutoshardingServiceImplBase { + final BlockingQueue requests = new LinkedBlockingQueue<>(); + final BlockingQueue> serverStreams = + new LinkedBlockingQueue<>(); + final AtomicInteger streamCount = new AtomicInteger(); + + @Override + public StreamObserver watchShardingAssignment( + StreamObserver responseObserver) { + streamCount.incrementAndGet(); + serverStreams.add(responseObserver); + return new StreamObserver() { + @Override + public void onNext(WatchShardingAssignmentRequest request) { + requests.add(request); + } + + @Override + public void onError(Throwable t) {} + + @Override + public void onCompleted() {} + }; + } + } + + private static final class FakeChildProvider extends LoadBalancerProvider { + final List children = new ArrayList<>(); + + @Override + public boolean isAvailable() { + return true; + } + + @Override + public int getPriority() { + return 5; + } + + @Override + public String getPolicyName() { + return "fake_child"; + } + + @Override + public LoadBalancer newLoadBalancer(Helper childHelper) { + FakeChild child = new FakeChild(childHelper); + children.add(child); + return child; + } + } + + /** Stands in for {@code pick_first}, reporting CONNECTING as soon as it is asked to connect. */ + private static final class FakeChild extends LoadBalancer { + private final Helper helper; + final Subchannel subchannel = mock(Subchannel.class); + @Nullable String hostname; + int requestConnectionCount; + boolean shutdown; + + FakeChild(Helper helper) { + this.helper = helper; + } + + @Override + public Status acceptResolvedAddresses(ResolvedAddresses resolvedAddresses) { + hostname = + resolvedAddresses + .getAddresses() + .get(0) + .getAttributes() + .get(InternalEquivalentAddressGroup.ATTR_ADDRESS_NAME); + return Status.OK; + } + + @Override + public void handleNameResolutionError(Status error) {} + + @Override + public void requestConnection() { + requestConnectionCount++; + helper.updateBalancingState(CONNECTING, new FixedResultPicker(PickResult.withNoResult())); + } + + @Override + public void shutdown() { + shutdown = true; + } + + void reportReady() { + helper.updateBalancingState(READY, new FixedResultPicker(PickResult.withSubchannel( + subchannel))); + } + + void reportTransientFailure() { + helper.updateBalancingState( + TRANSIENT_FAILURE, + new FixedResultPicker( + PickResult.withError(Status.UNAVAILABLE.withDescription("endpoint down")))); + } + } +} diff --git a/autosharding/src/test/java/io/grpc/autosharding/AutoShardingPickerTest.java b/autosharding/src/test/java/io/grpc/autosharding/AutoShardingPickerTest.java index eefc65959c9..c1b68e91ef6 100644 --- a/autosharding/src/test/java/io/grpc/autosharding/AutoShardingPickerTest.java +++ b/autosharding/src/test/java/io/grpc/autosharding/AutoShardingPickerTest.java @@ -54,6 +54,13 @@ private PickSubchannelArgs createArgs(Metadata headers) { return new PickSubchannelArgsImpl(METHOD, headers, CallOptions.DEFAULT, NOOP_CONSUMER); } + /** Headers carrying the key "k" under {@code headerName}. */ + private static Metadata keyed(String headerName) { + Metadata headers = new Metadata(); + headers.put(Metadata.Key.of(headerName, Metadata.ASCII_STRING_MARSHALLER), "k"); + return headers; + } + private static class FakePicker extends SubchannelPicker { private final PickResult result; @@ -74,7 +81,7 @@ public void pick_noSliceMap_fallbackEnabled_picksFromFallbackPool() { ConnectivityState.READY, new FakePicker(readyResult), NOOP_EXIT_IDLER); SliceMap emptySliceMap = new SliceMap( - Collections.emptyList(), Collections.singletonList(0), 1L); + Collections.emptyList(), Collections.singletonList(0)); AutoShardingPicker picker = new AutoShardingPicker( emptySliceMap, Collections.singletonList(ep0), @@ -95,15 +102,14 @@ public void pick_noSliceMap_fallbackDisabled_returnsUnavailableError() { ConnectivityState.READY, new FakePicker(PickResult.withNoResult()), NOOP_EXIT_IDLER); SliceMap emptySliceMap = new SliceMap( - Collections.emptyList(), Collections.singletonList(0), 1L); + Collections.emptyList(), Collections.singletonList(0)); AutoShardingPicker picker = new AutoShardingPicker( emptySliceMap, Collections.singletonList(ep0), false, AutoShardingPicker.createKeyHeader("x-slice-key")); - Metadata headers = new Metadata(); - PickResult result = picker.pickSubchannel(createArgs(headers)); + PickResult result = picker.pickSubchannel(createArgs(keyed("x-slice-key"))); assertThat(result.getStatus().getCode()).isEqualTo(Status.Code.UNAVAILABLE); assertThat(result.getStatus().getDescription()) @@ -119,7 +125,7 @@ public void pick_sliceFound_readyEndpoint_returnsPickResult() { SliceEntry slice = new SliceEntry( "".getBytes(StandardCharsets.UTF_8), Collections.singletonList(0)); SliceMap sliceMap = new SliceMap( - Collections.singletonList(slice), Collections.singletonList(0), 1L); + Collections.singletonList(slice), Collections.singletonList(0)); AutoShardingPicker picker = new AutoShardingPicker( sliceMap, @@ -146,7 +152,7 @@ public void pick_sliceFound_idleEndpoint_triggersConnectionAndQueues() { SliceEntry slice = new SliceEntry( "".getBytes(StandardCharsets.UTF_8), Collections.singletonList(0)); SliceMap sliceMap = new SliceMap( - Collections.singletonList(slice), Collections.singletonList(0), 1L); + Collections.singletonList(slice), Collections.singletonList(0)); AutoShardingPicker picker = new AutoShardingPicker( sliceMap, @@ -154,7 +160,7 @@ public void pick_sliceFound_idleEndpoint_triggersConnectionAndQueues() { false, AutoShardingPicker.createKeyHeader("x-slice-key")); - PickResult result = picker.pickSubchannel(createArgs(new Metadata())); + PickResult result = picker.pickSubchannel(createArgs(keyed("x-slice-key"))); assertThat(connectCalls.get()).isEqualTo(1); assertThat(result.hasResult()).isFalse(); @@ -171,7 +177,7 @@ public void pick_sliceFound_connectingEndpoint_queuesPick() { SliceEntry slice = new SliceEntry( "".getBytes(StandardCharsets.UTF_8), Collections.singletonList(0)); SliceMap sliceMap = new SliceMap( - Collections.singletonList(slice), Collections.singletonList(0), 1L); + Collections.singletonList(slice), Collections.singletonList(0)); AutoShardingPicker picker = new AutoShardingPicker( sliceMap, @@ -179,7 +185,7 @@ public void pick_sliceFound_connectingEndpoint_queuesPick() { false, AutoShardingPicker.createKeyHeader("x-slice-key")); - PickResult result = picker.pickSubchannel(createArgs(new Metadata())); + PickResult result = picker.pickSubchannel(createArgs(keyed("x-slice-key"))); assertThat(connectCalls.get()).isEqualTo(0); assertThat(result.hasResult()).isFalse(); @@ -200,7 +206,7 @@ public void pick_sliceFound_allTransientFailure_fallbackEnabled_picksFromFallbac "".getBytes(StandardCharsets.UTF_8), Collections.singletonList(0)); // Fallback pool has ep1 (which is ready) SliceMap sliceMap = new SliceMap( - Collections.singletonList(slice0), Collections.singletonList(1), 1L); + Collections.singletonList(slice0), Collections.singletonList(1)); AutoShardingPicker picker = new AutoShardingPicker( sliceMap, @@ -208,7 +214,7 @@ public void pick_sliceFound_allTransientFailure_fallbackEnabled_picksFromFallbac true, AutoShardingPicker.createKeyHeader("x-slice-key")); - PickResult result = picker.pickSubchannel(createArgs(new Metadata())); + PickResult result = picker.pickSubchannel(createArgs(keyed("x-slice-key"))); assertThat(result).isSameInstanceAs(fallbackReadyResult); } @@ -223,7 +229,7 @@ public void pick_sliceFound_allTransientFailure_fallbackDisabled_delegatesToEndp SliceEntry slice0 = new SliceEntry( "".getBytes(StandardCharsets.UTF_8), Collections.singletonList(0)); SliceMap sliceMap = new SliceMap( - Collections.singletonList(slice0), Collections.singletonList(0), 1L); + Collections.singletonList(slice0), Collections.singletonList(0)); AutoShardingPicker picker = new AutoShardingPicker( sliceMap, @@ -231,7 +237,7 @@ public void pick_sliceFound_allTransientFailure_fallbackDisabled_delegatesToEndp false, AutoShardingPicker.createKeyHeader("x-slice-key")); - PickResult result = picker.pickSubchannel(createArgs(new Metadata())); + PickResult result = picker.pickSubchannel(createArgs(keyed("x-slice-key"))); assertThat(result.getStatus()).isEqualTo(epError); } @@ -247,7 +253,7 @@ public void pick_binaryHeader_extractedProperly() { SliceEntry s0 = new SliceEntry(new byte[] {0x00}, Collections.singletonList(0)); SliceEntry s1 = new SliceEntry(new byte[] {0x50}, Collections.singletonList(1)); - SliceMap sliceMap = new SliceMap(Arrays.asList(s0, s1), Arrays.asList(0, 1), 1L); + SliceMap sliceMap = new SliceMap(Arrays.asList(s0, s1), Arrays.asList(0, 1)); AutoShardingPicker picker = new AutoShardingPicker( sliceMap, @@ -264,6 +270,61 @@ public void pick_binaryHeader_extractedProperly() { assertThat(result).isSameInstanceAs(ready1); } + @Test + public void pick_keyHeaderRepeated_routesByTheFirstValue() { + PickResult fromEndpoint0 = PickResult.withError(Status.UNAVAILABLE.withDescription("ep0")); + PickResult fromEndpoint1 = PickResult.withError(Status.UNAVAILABLE.withDescription("ep1")); + PickerEndpoint ep0 = new PickerEndpoint( + ConnectivityState.READY, new FakePicker(fromEndpoint0), NOOP_EXIT_IDLER); + PickerEndpoint ep1 = new PickerEndpoint( + ConnectivityState.READY, new FakePicker(fromEndpoint1), NOOP_EXIT_IDLER); + SliceEntry s0 = new SliceEntry( + "".getBytes(StandardCharsets.UTF_8), Collections.singletonList(0)); + SliceEntry s1 = new SliceEntry( + "m".getBytes(StandardCharsets.UTF_8), Collections.singletonList(1)); + AutoShardingPicker picker = new AutoShardingPicker( + new SliceMap(Arrays.asList(s0, s1), Arrays.asList(0, 1)), + Arrays.asList(ep0, ep1), + false, + AutoShardingPicker.createKeyHeader("x-slice-key")); + + Metadata headers = new Metadata(); + Metadata.Key key = Metadata.Key.of("x-slice-key", Metadata.ASCII_STRING_MARSHALLER); + headers.put(key, "a"); + headers.put(key, "z"); + + // The first value routes: "a" falls in the first slice, "z" in the second. + assertThat(picker.pickSubchannel(createArgs(headers))).isSameInstanceAs(fromEndpoint0); + } + + @Test + public void pick_missingKeyHeader_failsWithoutConnecting() { + AtomicInteger connectCalls = new AtomicInteger(0); + PickerEndpoint ep0 = new PickerEndpoint( + ConnectivityState.IDLE, + new FakePicker(PickResult.withNoResult()), + connectCalls::incrementAndGet); + + SliceEntry slice = new SliceEntry( + "".getBytes(StandardCharsets.UTF_8), Collections.singletonList(0)); + SliceMap sliceMap = new SliceMap( + Collections.singletonList(slice), Collections.singletonList(0)); + + AutoShardingPicker picker = new AutoShardingPicker( + sliceMap, + Collections.singletonList(ep0), + true, + AutoShardingPicker.createKeyHeader("x-slice-key")); + + PickResult result = picker.pickSubchannel(createArgs(new Metadata())); + + // wait-for-ready RPCs keep waiting. + assertThat(result.isDrop()).isFalse(); + assertThat(result.getStatus().getCode()).isEqualTo(Status.Code.UNAVAILABLE); + assertThat(result.getStatus().getDescription()).contains("x-slice-key"); + assertThat(connectCalls.get()).isEqualTo(0); + } + @Test public void pick_emptySliceEndpoints_fallbackDisabled_returnsUnavailable() { PickerEndpoint ep0 = new PickerEndpoint( @@ -272,7 +333,7 @@ public void pick_emptySliceEndpoints_fallbackDisabled_returnsUnavailable() { SliceEntry emptySlice = new SliceEntry( "".getBytes(StandardCharsets.UTF_8), Collections.emptyList()); SliceMap sliceMap = new SliceMap( - Collections.singletonList(emptySlice), Collections.singletonList(0), 1L); + Collections.singletonList(emptySlice), Collections.singletonList(0)); AutoShardingPicker picker = new AutoShardingPicker( sliceMap, @@ -280,7 +341,7 @@ public void pick_emptySliceEndpoints_fallbackDisabled_returnsUnavailable() { false, AutoShardingPicker.createKeyHeader("x-slice-key")); - PickResult result = picker.pickSubchannel(createArgs(new Metadata())); + PickResult result = picker.pickSubchannel(createArgs(keyed("x-slice-key"))); assertThat(result.getStatus().getCode()).isEqualTo(Status.Code.UNAVAILABLE); assertThat(result.getStatus().getDescription()) .contains("No valid endpoints in slice and fallback disabled"); @@ -297,7 +358,7 @@ public void pick_emptySliceEndpoints_fallbackEnabled_routesToFallbackPool() { "".getBytes(StandardCharsets.UTF_8), Collections.emptyList()); // Fallback pool has ep0 SliceMap sliceMap = new SliceMap( - Collections.singletonList(gapSlice), Collections.singletonList(0), 1L); + Collections.singletonList(gapSlice), Collections.singletonList(0)); AutoShardingPicker picker = new AutoShardingPicker( sliceMap, @@ -313,12 +374,51 @@ public void pick_emptySliceEndpoints_fallbackEnabled_routesToFallbackPool() { assertThat(result).isSameInstanceAs(fallbackReadyResult); } + @Test + public void pick_fallbackDisabledSlice_fallbackEnabled_dropsInsteadOfFallingBack() { + PickerEndpoint ep0 = new PickerEndpoint( + ConnectivityState.READY, new FakePicker(PickResult.withNoResult()), NOOP_EXIT_IDLER); + SliceEntry slice = new SliceEntry( + "".getBytes(StandardCharsets.UTF_8), Collections.emptyList(), true); + SliceMap sliceMap = new SliceMap( + Collections.singletonList(slice), Collections.singletonList(0)); + + AutoShardingPicker picker = new AutoShardingPicker( + sliceMap, + Collections.singletonList(ep0), + true, + AutoShardingPicker.createKeyHeader("x-key")); + + PickResult result = picker.pickSubchannel(createArgs(keyed("x-key"))); + // A drop, so that wait-for-ready RPCs fail too rather than wait. + assertThat(result.isDrop()).isTrue(); + assertThat(result.getStatus().getCode()).isEqualTo(Status.Code.UNAVAILABLE); + assertThat(result.getStatus().getDescription()).contains("fallback disabled"); + } + + @Test + public void pick_fallbackDisabledSlice_fallbackDisabled_drops() { + SliceEntry slice = new SliceEntry( + "".getBytes(StandardCharsets.UTF_8), Collections.emptyList(), true); + SliceMap sliceMap = new SliceMap( + Collections.singletonList(slice), Collections.emptyList()); + + AutoShardingPicker picker = new AutoShardingPicker( + sliceMap, + Collections.emptyList(), + false, + AutoShardingPicker.createKeyHeader("x-key")); + + PickResult result = picker.pickSubchannel(createArgs(keyed("x-key"))); + assertThat(result.isDrop()).isTrue(); + } + @Test public void pick_emptyFallbackPool_fallbackEnabled_returnsUnavailable() { SliceEntry emptySlice = new SliceEntry( "".getBytes(StandardCharsets.UTF_8), Collections.emptyList()); SliceMap sliceMap = new SliceMap( - Collections.singletonList(emptySlice), Collections.emptyList(), 1L); + Collections.singletonList(emptySlice), Collections.emptyList()); AutoShardingPicker picker = new AutoShardingPicker( sliceMap, @@ -326,7 +426,7 @@ public void pick_emptyFallbackPool_fallbackEnabled_returnsUnavailable() { true, AutoShardingPicker.createKeyHeader("x-key")); - PickResult result = picker.pickSubchannel(createArgs(new Metadata())); + PickResult result = picker.pickSubchannel(createArgs(keyed("x-key"))); assertThat(result.getStatus().getCode()).isEqualTo(Status.Code.UNAVAILABLE); assertThat(result.getStatus().getDescription()) .contains("No endpoints available in fallback pool"); @@ -347,12 +447,6 @@ public void pickerEndpoint_gettersAndToString() { assertThat(count.get()).isEqualTo(1); } - @Test - public void createKeyHeader_nullOrEmpty_returnsNull() { - assertThat(AutoShardingPicker.createKeyHeader(null)).isNull(); - assertThat(AutoShardingPicker.createKeyHeader("")).isNull(); - } - @Test public void createKeyHeader_asciiHeader() { Metadata.Key key = AutoShardingPicker.createKeyHeader("x-slice-key"); @@ -379,7 +473,7 @@ public void pick_deterministicRandom_selectsExpectedEndpoint() { SliceEntry slice = new SliceEntry( "".getBytes(StandardCharsets.UTF_8), Arrays.asList(0, 1)); SliceMap sliceMap = new SliceMap( - Collections.singletonList(slice), Arrays.asList(0, 1), 1L); + Collections.singletonList(slice), Arrays.asList(0, 1)); // Test picking index 0 AutoShardingPicker picker0 = new AutoShardingPicker( @@ -388,7 +482,7 @@ public void pick_deterministicRandom_selectsExpectedEndpoint() { false, AutoShardingPicker.createKeyHeader("x-key"), bound -> 0); - PickResult result0 = picker0.pickSubchannel(createArgs(new Metadata())); + PickResult result0 = picker0.pickSubchannel(createArgs(keyed("x-key"))); assertThat(result0).isSameInstanceAs(ready0); // Test picking index 1 @@ -398,7 +492,7 @@ public void pick_deterministicRandom_selectsExpectedEndpoint() { false, AutoShardingPicker.createKeyHeader("x-key"), bound -> 1); - PickResult result1 = picker1.pickSubchannel(createArgs(new Metadata())); + PickResult result1 = picker1.pickSubchannel(createArgs(keyed("x-key"))); assertThat(result1).isSameInstanceAs(ready1); } @@ -411,7 +505,7 @@ public void pick_invalidSliceEndpointIndex_throwsIndexOutOfBoundsException() { SliceEntry slice = new SliceEntry( "".getBytes(StandardCharsets.UTF_8), Collections.singletonList(5)); SliceMap sliceMap = new SliceMap( - Collections.singletonList(slice), Collections.singletonList(0), 1L); + Collections.singletonList(slice), Collections.singletonList(0)); AutoShardingPicker picker = new AutoShardingPicker( sliceMap, @@ -421,7 +515,7 @@ public void pick_invalidSliceEndpointIndex_throwsIndexOutOfBoundsException() { Assert.assertThrows( IndexOutOfBoundsException.class, - () -> picker.pickSubchannel(createArgs(new Metadata()))); + () -> picker.pickSubchannel(createArgs(keyed("x-key")))); } @Test @@ -433,7 +527,7 @@ public void pick_negativeSliceEndpointIndex_throwsIndexOutOfBoundsException() { SliceEntry slice = new SliceEntry( "".getBytes(StandardCharsets.UTF_8), Collections.singletonList(-1)); SliceMap sliceMap = new SliceMap( - Collections.singletonList(slice), Collections.singletonList(0), 1L); + Collections.singletonList(slice), Collections.singletonList(0)); AutoShardingPicker picker = new AutoShardingPicker( sliceMap, @@ -443,7 +537,7 @@ public void pick_negativeSliceEndpointIndex_throwsIndexOutOfBoundsException() { Assert.assertThrows( IndexOutOfBoundsException.class, - () -> picker.pickSubchannel(createArgs(new Metadata()))); + () -> picker.pickSubchannel(createArgs(keyed("x-key")))); } @Test @@ -453,7 +547,7 @@ public void pick_invalidFallbackPoolIndex_throwsIndexOutOfBoundsException() { // Fallback pool references index 10, but only 1 endpoint exists SliceMap emptySliceMap = new SliceMap( - Collections.emptyList(), Collections.singletonList(10), 1L); + Collections.emptyList(), Collections.singletonList(10)); AutoShardingPicker picker = new AutoShardingPicker( emptySliceMap, @@ -463,13 +557,14 @@ public void pick_invalidFallbackPoolIndex_throwsIndexOutOfBoundsException() { Assert.assertThrows( IndexOutOfBoundsException.class, - () -> picker.pickSubchannel(createArgs(new Metadata()))); + () -> picker.pickSubchannel(createArgs(keyed("x-key")))); } @Test public void constructor_nullInputs_throwsNullPointerException() { SliceMap sliceMap = new SliceMap( - Collections.emptyList(), Collections.emptyList(), 1L); + Collections.emptyList(), Collections.emptyList()); + Metadata.Key keyHeader = AutoShardingPicker.createKeyHeader("x-key"); Assert.assertThrows( NullPointerException.class, @@ -477,7 +572,7 @@ public void constructor_nullInputs_throwsNullPointerException() { null, Collections.emptyList(), false, - null)); + keyHeader)); Assert.assertThrows( NullPointerException.class, @@ -485,6 +580,14 @@ public void constructor_nullInputs_throwsNullPointerException() { sliceMap, null, false, + keyHeader)); + + Assert.assertThrows( + NullPointerException.class, + () -> new AutoShardingPicker( + sliceMap, + Collections.emptyList(), + false, null)); Assert.assertThrows( @@ -493,7 +596,7 @@ public void constructor_nullInputs_throwsNullPointerException() { sliceMap, Collections.emptyList(), false, - null, + keyHeader, null)); } } diff --git a/autosharding/src/test/java/io/grpc/autosharding/AutoshardingClientTest.java b/autosharding/src/test/java/io/grpc/autosharding/AutoshardingClientTest.java new file mode 100644 index 00000000000..242bfbc5aea --- /dev/null +++ b/autosharding/src/test/java/io/grpc/autosharding/AutoshardingClientTest.java @@ -0,0 +1,797 @@ +/* + * Copyright 2026 The gRPC Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.grpc.autosharding; + +import static com.google.common.truth.Truth.assertThat; +import static org.junit.Assert.fail; + +import com.google.cloud.autosharding.v1.AssignmentChunk; +import com.google.cloud.autosharding.v1.AssignmentMetadata; +import com.google.cloud.autosharding.v1.AutoshardingServiceGrpc; +import com.google.cloud.autosharding.v1.EndpointState; +import com.google.cloud.autosharding.v1.LoadReportingConfig; +import com.google.cloud.autosharding.v1.PerSliceEndpointState; +import com.google.cloud.autosharding.v1.SliceAssignment; +import com.google.cloud.autosharding.v1.WatchShardingAssignmentRequest; +import com.google.cloud.autosharding.v1.WatchShardingAssignmentResponse; +import com.google.protobuf.ByteString; +import io.grpc.CallOptions; +import io.grpc.Channel; +import io.grpc.ClientCall; +import io.grpc.ClientInterceptor; +import io.grpc.ClientInterceptors; +import io.grpc.MethodDescriptor; +import io.grpc.Status; +import io.grpc.SynchronizationContext; +import io.grpc.inprocess.InProcessChannelBuilder; +import io.grpc.inprocess.InProcessServerBuilder; +import io.grpc.internal.BackoffPolicy; +import io.grpc.internal.FakeClock; +import io.grpc.stub.StreamObserver; +import io.grpc.testing.GrpcCleanupRule; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import javax.annotation.Nullable; +import org.junit.After; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** Unit tests for {@link AutoshardingClient}. */ +@RunWith(JUnit4.class) +public class AutoshardingClientTest { + private static final String CLIENT_UUID = "client-uuid-1"; + private static final String TARGET = "autosharding-target"; + private static final String OTHER_TARGET = "other-autosharding-target"; + private static final long TIMEOUT_SECONDS = 5; + private static final long BACKOFF_NANOS = TimeUnit.SECONDS.toNanos(1); + private static final long ASSIGNMENT_TIMEOUT_NANOS = TimeUnit.MINUTES.toNanos(1); + + @Rule public final GrpcCleanupRule grpcCleanup = new GrpcCleanupRule(); + + private final SynchronizationContext syncContext = + new SynchronizationContext( + (t, e) -> { + throw new AssertionError(e); + }); + private final FakeClock fakeClock = new FakeClock(); + private final FakeAutoshardingService service = new FakeAutoshardingService(); + private final BlockingQueue assignments = new LinkedBlockingQueue<>(); + private final BlockingQueue errors = new LinkedBlockingQueue<>(); + private final RecordingBackoffPolicyProvider backoffPolicyProvider = + new RecordingBackoffPolicyProvider(); + private final List clients = new ArrayList<>(); + + private Channel channel; + private AutoshardingClient client; + + @Before + public void setUp() throws Exception { + channel = newChannelToFakeService(); + client = newClient(channel, TARGET); + } + + @After + public void tearDown() { + // Must happen before GrpcCleanupRule shuts the channels down, otherwise a client keeps + // retrying against a terminating channel. + syncContext.execute( + () -> { + for (AutoshardingClient created : clients) { + created.shutdown(); + } + }); + } + + @Test + public void start_opensStreamAndSendsInitialClientConfig() throws Exception { + start(client); + + WatchShardingAssignmentRequest request = takeRequest(); + assertThat(request.hasInitialClientConfig()).isTrue(); + assertThat(request.getInitialClientConfig().getTarget()).isEqualTo(TARGET); + assertThat(request.getInitialClientConfig().getClientUuid()).isEqualTo(CLIENT_UUID); + assertThat(request.getInitialClientConfig().getLatestGeneration()).isEqualTo(0); + } + + @Test + public void start_opensTheStreamWaitForReady() throws Exception { + List callOptions = new ArrayList<>(); + Channel recordingChannel = + ClientInterceptors.intercept( + channel, + new ClientInterceptor() { + @Override + public ClientCall interceptCall( + MethodDescriptor method, CallOptions options, Channel next) { + callOptions.add(options); + return next.newCall(method, options); + } + }); + + start(newClient(recordingChannel, TARGET)); + takeRequest(); + + // A transient connectivity failure then leaves the stream pending instead of failing it. + assertThat(callOptions).hasSize(1); + assertThat(callOptions.get(0).isWaitForReady()).isTrue(); + } + + @Test + public void chunksBufferedUntilMetadata_thenAssignmentDeliveredAndAcked() throws Exception { + start(client); + takeRequest(); + StreamObserver serverStream = takeServerStream(); + + serverStream.onNext(chunkResponse(chunkWithEndpoint("host-a", "", null, 0))); + assertThat(assignments).isEmpty(); + assertThat(service.requests).isEmpty(); + + serverStream.onNext(metadataResponse(5)); + + Assignment assignment = takeAssignment(); + assertThat(assignment.getEndpointNames()).containsExactly("host-a"); + assertThat(assignment.getSlices()).hasSize(1); + + WatchShardingAssignmentRequest ack = takeRequest(); + assertThat(ack.hasAssignmentAck()).isTrue(); + assertThat(ack.getAssignmentAck().getGeneration()).isEqualTo(5); + assertThat(ack.getAssignmentAck().getAccepted()).isTrue(); + assertThat(ack.getAssignmentAck().getErrorMessage()).isEmpty(); + } + + @Test + public void multipleChunks_combinedIntoOneLogicalAssignment() throws Exception { + start(client); + takeRequest(); + StreamObserver serverStream = takeServerStream(); + + serverStream.onNext( + chunkResponse(AssignmentChunk.newBuilder().addEndpoints(endpoint("host-a")).build())); + serverStream.onNext( + chunkResponse( + AssignmentChunk.newBuilder() + .addEndpoints(endpoint("host-b")) + .addSliceAssignments(sliceAssignment("", null, 1)) + .build())); + serverStream.onNext(metadataResponse(1)); + + Assignment assignment = takeAssignment(); + assertThat(assignment.getEndpointNames()).containsExactly("host-a", "host-b").inOrder(); + assertThat(assignment.getSlices().get(0).getEndpoints()).containsExactly(1); + } + + @Test + public void noUsableSlices_nackedAndReportedAsAnError() throws Exception { + start(client); + takeRequest(); + StreamObserver serverStream = takeServerStream(); + + // Endpoint index 3 does not exist in the combined endpoint list, so the only slice is + // dropped and nothing usable remains. + serverStream.onNext(chunkResponse(chunkWithEndpoint("host-a", "", null, 3))); + serverStream.onNext(metadataResponse(5)); + + WatchShardingAssignmentRequest nack = takeRequest(); + assertThat(nack.hasAssignmentAck()).isTrue(); + assertThat(nack.getAssignmentAck().getGeneration()).isEqualTo(5); + assertThat(nack.getAssignmentAck().getAccepted()).isFalse(); + assertThat(nack.getAssignmentAck().getErrorMessage()) + .contains("out-of-range endpoint index 3"); + assertThat(takeError().getDescription()).contains("out-of-range endpoint index 3"); + assertThat(assignments).isEmpty(); + // A rejected assignment must not advance the watermark, or the server would stop resending. + assertThat(client.getLatestGeneration()).isEqualTo(0); + } + + @Test + public void someSlicesDropped_ackedWithErrorMessageAndStillDelivered() throws Exception { + start(client); + takeRequest(); + StreamObserver serverStream = takeServerStream(); + + serverStream.onNext( + chunkResponse( + AssignmentChunk.newBuilder() + .addEndpoints(endpoint("host-a")) + .addSliceAssignments(sliceAssignment("", "m", 0)) + .addSliceAssignments(sliceAssignment("m", null, 3)) + .build())); + serverStream.onNext(metadataResponse(5)); + + Assignment assignment = takeAssignment(); + assertThat(assignment.getSlices()).hasSize(2); + assertThat(assignment.getSlices().get(0).getEndpoints()).containsExactly(0); + // The dropped slice was turned into a gap rather than invalidating the assignment. + assertThat(assignment.getSlices().get(1).getEndpoints()).isEmpty(); + + WatchShardingAssignmentRequest ack = takeRequest(); + assertThat(ack.getAssignmentAck().getAccepted()).isTrue(); + assertThat(ack.getAssignmentAck().getErrorMessage()) + .contains("out-of-range endpoint index 3"); + assertThat(errors).isEmpty(); + assertThat(client.getLatestGeneration()).isEqualTo(5); + } + + @Test + public void assignmentWithNoSlices_nackedAndReportedAsAnError() throws Exception { + start(client); + takeRequest(); + StreamObserver serverStream = takeServerStream(); + + serverStream.onNext(metadataResponse(1)); + + WatchShardingAssignmentRequest nack = takeRequest(); + assertThat(nack.getAssignmentAck().getAccepted()).isFalse(); + assertThat(nack.getAssignmentAck().getErrorMessage()) + .contains("no slice assignments received"); + assertThat(takeError().getDescription()).contains("no slice assignments received"); + assertThat(assignments).isEmpty(); + assertThat(client.getLatestGeneration()).isEqualTo(0); + } + + @Test + public void generationZero_isStaleEvenAsTheFirstAssignment() throws Exception { + start(client); + takeRequest(); + StreamObserver serverStream = takeServerStream(); + + serverStream.onNext(chunkResponse(chunkWithEndpoint("host-a", "", null, 0))); + serverStream.onNext(metadataResponse(0)); + + // A generation must exceed the latest one, which starts at zero. + WatchShardingAssignmentRequest nack = takeRequest(); + assertThat(nack.getAssignmentAck().getGeneration()).isEqualTo(0); + assertThat(nack.getAssignmentAck().getAccepted()).isFalse(); + assertThat(nack.getAssignmentAck().getErrorMessage()).contains("stale generation 0"); + assertThat(assignments).isEmpty(); + assertThat(errors).isEmpty(); + } + + @Test + public void negativeGeneration_isStale() throws Exception { + start(client); + takeRequest(); + StreamObserver serverStream = takeServerStream(); + + serverStream.onNext(chunkResponse(chunkWithEndpoint("host-a", "", null, 0))); + serverStream.onNext(metadataResponse(-3)); + + WatchShardingAssignmentRequest nack = takeRequest(); + assertThat(nack.getAssignmentAck().getAccepted()).isFalse(); + assertThat(assignments).isEmpty(); + assertThat(client.getLatestGeneration()).isEqualTo(0); + } + + @Test + public void rejectedAssignment_doesNotLeakChunksIntoTheNextOne() throws Exception { + start(client); + takeRequest(); + StreamObserver serverStream = takeServerStream(); + + serverStream.onNext(chunkResponse(chunkWithEndpoint("host-a", "", null, 3))); + serverStream.onNext(metadataResponse(5)); + takeRequest(); // NACK + takeError(); + + serverStream.onNext(chunkResponse(chunkWithEndpoint("host-b", "", null, 0))); + serverStream.onNext(metadataResponse(6)); + + Assignment assignment = takeAssignment(); + assertThat(assignment.getEndpointNames()).containsExactly("host-b"); + } + + @Test + public void staleGeneration_nackedAndNotDelivered() throws Exception { + start(client); + takeRequest(); + StreamObserver serverStream = takeServerStream(); + + serverStream.onNext(chunkResponse(chunkWithEndpoint("host-a", "", null, 0))); + serverStream.onNext(metadataResponse(5)); + takeAssignment(); + takeRequest(); // ACK for generation 5 + + serverStream.onNext(chunkResponse(chunkWithEndpoint("host-b", "", null, 0))); + serverStream.onNext(metadataResponse(5)); + + WatchShardingAssignmentRequest nack = takeRequest(); + assertThat(nack.getAssignmentAck().getGeneration()).isEqualTo(5); + assertThat(nack.getAssignmentAck().getAccepted()).isFalse(); + assertThat(nack.getAssignmentAck().getErrorMessage()).contains("stale generation"); + // A stale assignment tells the LB policy nothing it does not already know. + assertThat(assignments).isEmpty(); + assertThat(errors).isEmpty(); + assertThat(client.getLatestGeneration()).isEqualTo(5); + } + + @Test + public void olderGeneration_nackedAndNotDelivered() throws Exception { + start(client); + takeRequest(); + StreamObserver serverStream = takeServerStream(); + + serverStream.onNext(chunkResponse(chunkWithEndpoint("host-a", "", null, 0))); + serverStream.onNext(metadataResponse(5)); + takeAssignment(); + takeRequest(); + + serverStream.onNext(chunkResponse(chunkWithEndpoint("host-b", "", null, 0))); + serverStream.onNext(metadataResponse(4)); + + WatchShardingAssignmentRequest nack = takeRequest(); + assertThat(nack.getAssignmentAck().getGeneration()).isEqualTo(4); + assertThat(nack.getAssignmentAck().getAccepted()).isFalse(); + assertThat(assignments).isEmpty(); + assertThat(client.getLatestGeneration()).isEqualTo(5); + } + + @Test + public void loadReportingConfig_ignored() throws Exception { + start(client); + takeRequest(); + StreamObserver serverStream = takeServerStream(); + + serverStream.onNext( + WatchShardingAssignmentResponse.newBuilder() + .setConfig(LoadReportingConfig.newBuilder().setLoadQuantumFraction(0.5)) + .build()); + + assertThat(assignments).isEmpty(); + assertThat(service.requests).isEmpty(); + } + + @Test + public void streamFailure_reconnectsAndSendsLatestGeneration() throws Exception { + start(client); + takeRequest(); + StreamObserver serverStream = takeServerStream(); + + serverStream.onNext(chunkResponse(chunkWithEndpoint("host-a", "", null, 0))); + serverStream.onNext(metadataResponse(9)); + takeAssignment(); + takeRequest(); // ACK + + serverStream.onError(Status.UNAVAILABLE.asRuntimeException()); + fireRetryTimer(); + + WatchShardingAssignmentRequest retryRequest = takeRequest(); + assertThat(retryRequest.hasInitialClientConfig()).isTrue(); + assertThat(retryRequest.getInitialClientConfig().getLatestGeneration()).isEqualTo(9); + assertThat(retryRequest.getInitialClientConfig().getClientUuid()).isEqualTo(CLIENT_UUID); + assertThat(service.streamCount.get()).isEqualTo(2); + } + + @Test + public void streamFailure_doesNotReconnectBeforeBackoffElapses() throws Exception { + start(client); + takeRequest(); + + takeServerStream().onError(Status.UNAVAILABLE.asRuntimeException()); + + assertThat(numPendingRetries()).isEqualTo(1); + fakeClock.forwardNanos(BACKOFF_NANOS - 1); + assertThat(service.streamCount.get()).isEqualTo(1); + + fakeClock.forwardNanos(1); + takeRequest(); + assertThat(service.streamCount.get()).isEqualTo(2); + } + + @Test + public void streamCompletedByServer_reconnects() throws Exception { + start(client); + takeRequest(); + StreamObserver serverStream = takeServerStream(); + + serverStream.onCompleted(); + fireRetryTimer(); + + takeRequest(); + assertThat(service.streamCount.get()).isEqualTo(2); + } + + @Test + public void backoffSequence_onlyResetAfterGoodAssignment() throws Exception { + start(client); + takeRequest(); + + // First failure with no assignment received: a backoff sequence is created. + takeServerStream().onError(Status.UNAVAILABLE.asRuntimeException()); + fireRetryTimer(); + takeRequest(); + assertThat(backoffPolicyProvider.timesCalled).isEqualTo(1); + + // Second failure with no assignment received: the existing sequence continues. + takeServerStream().onError(Status.UNAVAILABLE.asRuntimeException()); + fireRetryTimer(); + takeRequest(); + assertThat(backoffPolicyProvider.timesCalled).isEqualTo(1); + + // A good assignment drops the sequence, so the failure after it starts a new one. + StreamObserver serverStream = takeServerStream(); + serverStream.onNext(chunkResponse(chunkWithEndpoint("host-a", "", null, 0))); + serverStream.onNext(metadataResponse(1)); + takeAssignment(); + takeRequest(); // ACK + serverStream.onError(Status.UNAVAILABLE.asRuntimeException()); + fireRetryTimer(); + takeRequest(); + takeServerStream().onError(Status.UNAVAILABLE.asRuntimeException()); + fireRetryTimer(); + takeRequest(); + assertThat(backoffPolicyProvider.timesCalled).isEqualTo(2); + } + + @Test + public void streamFailureAfterGoodAssignment_reconnectsWithoutBackoff() throws Exception { + start(client); + takeRequest(); + StreamObserver serverStream = takeServerStream(); + serverStream.onNext(chunkResponse(chunkWithEndpoint("host-a", "", null, 0))); + serverStream.onNext(metadataResponse(1)); + takeAssignment(); + takeRequest(); // ACK + + serverStream.onError(Status.UNAVAILABLE.asRuntimeException()); + fakeClock.runDueTasks(); + + assertThat(numPendingRetries()).isEqualTo(0); + takeRequest(); + assertThat(service.streamCount.get()).isEqualTo(2); + } + + @Test + public void streamFailureAfterStaleAssignmentOnly_backsOff() throws Exception { + start(client); + takeRequest(); + StreamObserver serverStream = takeServerStream(); + serverStream.onNext(chunkResponse(chunkWithEndpoint("host-a", "", null, 0))); + serverStream.onNext(metadataResponse(5)); + takeAssignment(); + takeRequest(); // ACK + serverStream.onError(Status.UNAVAILABLE.asRuntimeException()); + fireRetryTimer(); + takeRequest(); + + // Only an older generation on this stream: nothing the balancer can use, so no reset. + serverStream = takeServerStream(); + serverStream.onNext(chunkResponse(chunkWithEndpoint("host-a", "", null, 0))); + serverStream.onNext(metadataResponse(3)); + serverStream.onError(Status.UNAVAILABLE.asRuntimeException()); + fakeClock.runDueTasks(); + + assertThat(numPendingRetries()).isEqualTo(1); + } + + /** + * A new client sends a {@code latest_generation} of zero, so when the LB policy replaces the + * client, no watermark carries over to a different server or target. + */ + @Test + public void newClient_startsFromGenerationZero() throws Exception { + start(client); + takeRequest(); + StreamObserver serverStream = takeServerStream(); + serverStream.onNext(chunkResponse(chunkWithEndpoint("host-a", "", null, 0))); + serverStream.onNext(metadataResponse(9)); + takeAssignment(); + takeRequest(); // ACK + assertThat(client.getLatestGeneration()).isEqualTo(9); + syncContext.execute(client::shutdown); + + AutoshardingClient replacement = newClient(newChannelToFakeService(), OTHER_TARGET); + start(replacement); + + WatchShardingAssignmentRequest request = takeRequest(); + assertThat(request.hasInitialClientConfig()).isTrue(); + assertThat(request.getInitialClientConfig().getTarget()).isEqualTo(OTHER_TARGET); + assertThat(request.getInitialClientConfig().getLatestGeneration()).isEqualTo(0); + assertThat(replacement.getLatestGeneration()).isEqualTo(0); + assertThat(service.streamCount.get()).isEqualTo(2); + } + + @Test + public void initialAssignmentTimer_reportsAnErrorWhenItFires() throws Exception { + start(client); + takeRequest(); + + fakeClock.forwardNanos(ASSIGNMENT_TIMEOUT_NANOS - 1); + assertThat(errors).isEmpty(); + + fakeClock.forwardNanos(1); + Status error = takeError(); + assertThat(error.getCode()).isEqualTo(Status.Code.UNAVAILABLE); + assertThat(error.getDescription()).contains("timed out waiting for the initial assignment"); + } + + @Test + public void initialAssignmentTimer_cancelledByTheFirstAssignment() throws Exception { + start(client); + takeRequest(); + StreamObserver serverStream = takeServerStream(); + serverStream.onNext(chunkResponse(chunkWithEndpoint("host-a", "", null, 0))); + serverStream.onNext(metadataResponse(1)); + takeAssignment(); + + assertThat(fakeClock.numPendingTasks()).isEqualTo(0); + fakeClock.forwardNanos(ASSIGNMENT_TIMEOUT_NANOS); + assertThat(errors).isEmpty(); + } + + @Test + public void initialAssignmentTimer_notCancelledByARejectedAssignment() throws Exception { + start(client); + takeRequest(); + StreamObserver serverStream = takeServerStream(); + serverStream.onNext(chunkResponse(chunkWithEndpoint("host-a", "", null, 3))); + serverStream.onNext(metadataResponse(1)); + takeError(); + + fakeClock.forwardNanos(ASSIGNMENT_TIMEOUT_NANOS); + assertThat(takeError().getDescription()).contains("timed out"); + } + + @Test + public void streamFailure_beforeAnyAssignment_reportsAnError() throws Exception { + start(client); + takeRequest(); + + takeServerStream().onError(Status.PERMISSION_DENIED.withDescription("nope").asException()); + + Status error = takeError(); + assertThat(error.getCode()).isEqualTo(Status.Code.UNAVAILABLE); + assertThat(error.getDescription()).contains("stream failed: PERMISSION_DENIED: nope"); + } + + @Test + public void errorsAfterTheFirstAssignment_notReported() throws Exception { + start(client); + takeRequest(); + StreamObserver serverStream = takeServerStream(); + serverStream.onNext(chunkResponse(chunkWithEndpoint("host-a", "", null, 0))); + serverStream.onNext(metadataResponse(1)); + takeAssignment(); + takeRequest(); // ACK + + // A rejected assignment. + serverStream.onNext(chunkResponse(chunkWithEndpoint("host-a", "", null, 3))); + serverStream.onNext(metadataResponse(2)); + takeRequest(); // NACK + // A stream failure, and the same on the retried stream. + serverStream.onError(Status.UNAVAILABLE.asRuntimeException()); + fireRetryTimer(); + takeRequest(); + takeServerStream().onError(Status.UNAVAILABLE.asRuntimeException()); + + assertThat(errors).isEmpty(); + } + + @Test + public void shutdown_cancelsStreamAndStopsReconnecting() throws Exception { + start(client); + takeRequest(); + + syncContext.execute(client::shutdown); + + assertThat(service.streamCount.get()).isEqualTo(1); + assertThat(fakeClock.numPendingTasks()).isEqualTo(0); + } + + @Test + public void shutdown_isIdempotent() throws Exception { + start(client); + takeRequest(); + + syncContext.execute(client::shutdown); + syncContext.execute(client::shutdown); + + assertThat(service.streamCount.get()).isEqualTo(1); + } + + @Test + public void shutdown_beforeStart_leavesNothingBehind() { + syncContext.execute(client::shutdown); + + assertThat(service.streamCount.get()).isEqualTo(0); + assertThat(fakeClock.numPendingTasks()).isEqualTo(0); + } + + private Channel newChannelToFakeService() throws Exception { + String serverName = InProcessServerBuilder.generateName(); + grpcCleanup.register( + InProcessServerBuilder.forName(serverName) + .directExecutor() + .addService(service) + .build() + .start()); + return grpcCleanup.register( + InProcessChannelBuilder.forName(serverName).directExecutor().build()); + } + + /** Creates a client and registers it for shutdown, without starting it. */ + private AutoshardingClient newClient(Channel channel, String target) { + AutoshardingClient created = + new AutoshardingClient( + CLIENT_UUID, + syncContext, + fakeClock.getScheduledExecutorService(), + backoffPolicyProvider, + fakeClock.getStopwatchSupplier(), + channel, + target, + ASSIGNMENT_TIMEOUT_NANOS, + new RecordingWatcher()); + clients.add(created); + return created; + } + + private void start(AutoshardingClient target) { + syncContext.execute(target::start); + } + + /** Asserts that a retry was scheduled and advances the clock so that it runs. */ + private void fireRetryTimer() { + assertThat(numPendingRetries()).isEqualTo(1); + fakeClock.forwardNanos(BACKOFF_NANOS); + } + + /** + * Pending tasks other than the initial assignment timer, which is always much further out than + * a retry in these tests. + */ + private int numPendingRetries() { + int count = 0; + for (FakeClock.ScheduledTask task : fakeClock.getPendingTasks()) { + if (task.getDelay(TimeUnit.NANOSECONDS) <= BACKOFF_NANOS) { + count++; + } + } + return count; + } + + private WatchShardingAssignmentRequest takeRequest() throws Exception { + WatchShardingAssignmentRequest request = + service.requests.poll(TIMEOUT_SECONDS, TimeUnit.SECONDS); + if (request == null) { + fail("timed out waiting for a request from the autosharding client"); + } + return request; + } + + private StreamObserver takeServerStream() throws Exception { + StreamObserver stream = + service.serverStreams.poll(TIMEOUT_SECONDS, TimeUnit.SECONDS); + if (stream == null) { + fail("timed out waiting for the autosharding client to open a stream"); + } + return stream; + } + + private Assignment takeAssignment() throws Exception { + Assignment assignment = assignments.poll(TIMEOUT_SECONDS, TimeUnit.SECONDS); + if (assignment == null) { + fail("timed out waiting for an assignment"); + } + return assignment; + } + + private Status takeError() throws Exception { + Status error = errors.poll(TIMEOUT_SECONDS, TimeUnit.SECONDS); + if (error == null) { + fail("timed out waiting for an error"); + } + return error; + } + + private static WatchShardingAssignmentResponse chunkResponse(AssignmentChunk chunk) { + return WatchShardingAssignmentResponse.newBuilder().setChunk(chunk).build(); + } + + private static WatchShardingAssignmentResponse metadataResponse(long generation) { + return WatchShardingAssignmentResponse.newBuilder() + .setMetadata(AssignmentMetadata.newBuilder().setGeneration(generation)) + .build(); + } + + private static AssignmentChunk chunkWithEndpoint( + String endpointName, String startKey, @Nullable String endKey, int endpointIndex) { + return AssignmentChunk.newBuilder() + .addEndpoints(endpoint(endpointName)) + .addSliceAssignments(sliceAssignment(startKey, endKey, endpointIndex)) + .build(); + } + + private static EndpointState endpoint(String name) { + return EndpointState.newBuilder().setEndpoint(name).build(); + } + + private static SliceAssignment sliceAssignment( + String startKey, @Nullable String endKey, int... endpointIndices) { + com.google.cloud.autosharding.v1.Slice.Builder slice = + com.google.cloud.autosharding.v1.Slice.newBuilder() + .setStartKey(ByteString.copyFromUtf8(startKey)); + if (endKey != null) { + slice.setEndKey(ByteString.copyFromUtf8(endKey)); + } + SliceAssignment.Builder builder = SliceAssignment.newBuilder().setSlice(slice); + for (int index : endpointIndices) { + builder.addEndpoints(PerSliceEndpointState.newBuilder().setEndpointIndex(index)); + } + return builder.build(); + } + + private final class RecordingWatcher implements AutoshardingClient.AssignmentWatcher { + @Override + public void onAssignment(Assignment assignment) { + assignments.add(assignment); + } + + @Override + public void onError(Status error) { + errors.add(error); + } + } + + private static final class FakeAutoshardingService + extends AutoshardingServiceGrpc.AutoshardingServiceImplBase { + final BlockingQueue requests = new LinkedBlockingQueue<>(); + final BlockingQueue> serverStreams = + new LinkedBlockingQueue<>(); + final AtomicInteger streamCount = new AtomicInteger(); + + @Override + public StreamObserver watchShardingAssignment( + StreamObserver responseObserver) { + streamCount.incrementAndGet(); + serverStreams.add(responseObserver); + return new StreamObserver() { + @Override + public void onNext(WatchShardingAssignmentRequest request) { + requests.add(request); + } + + @Override + public void onError(Throwable t) {} + + @Override + public void onCompleted() {} + }; + } + } + + /** + * Hands out backoff policies with a fixed, non-zero delay so that retries are driven explicitly + * by the fake clock. The number of policies handed out reflects how many times the backoff + * sequence was reset. + */ + private static final class RecordingBackoffPolicyProvider implements BackoffPolicy.Provider { + int timesCalled; + + @Override + public BackoffPolicy get() { + timesCalled++; + return () -> BACKOFF_NANOS; + } + } +} diff --git a/autosharding/src/test/java/io/grpc/autosharding/EndpointMapTest.java b/autosharding/src/test/java/io/grpc/autosharding/EndpointMapTest.java new file mode 100644 index 00000000000..0ff44f9d460 --- /dev/null +++ b/autosharding/src/test/java/io/grpc/autosharding/EndpointMapTest.java @@ -0,0 +1,692 @@ +/* + * Copyright 2026 The gRPC Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.grpc.autosharding; + +import static com.google.common.truth.Truth.assertThat; +import static io.grpc.ConnectivityState.CONNECTING; +import static io.grpc.ConnectivityState.IDLE; +import static io.grpc.ConnectivityState.READY; +import static io.grpc.ConnectivityState.TRANSIENT_FAILURE; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import com.google.common.collect.ImmutableList; +import io.grpc.Attributes; +import io.grpc.ConnectivityState; +import io.grpc.EquivalentAddressGroup; +import io.grpc.InternalEquivalentAddressGroup; +import io.grpc.LoadBalancer; +import io.grpc.LoadBalancer.Helper; +import io.grpc.LoadBalancer.PickResult; +import io.grpc.LoadBalancer.ResolvedAddresses; +import io.grpc.LoadBalancer.SubchannelPicker; +import io.grpc.LoadBalancerProvider; +import io.grpc.Status; +import io.grpc.SynchronizationContext; +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.net.SocketAddress; +import java.util.ArrayList; +import java.util.List; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** Unit tests for {@link EndpointMap}. */ +@RunWith(JUnit4.class) +public class EndpointMapTest { + + private final SynchronizationContext syncContext = + new SynchronizationContext( + (t, e) -> { + throw new AssertionError("Unhandled exception in syncContext", e); + }); + private final Helper helper = mock(Helper.class); + private final FakeChildProvider childProvider = new FakeChildProvider(); + private final List stateUpdates = new ArrayList<>(); + + private EndpointMap endpointMap; + + @Before + public void setUp() { + when(helper.getSynchronizationContext()).thenReturn(syncContext); + endpointMap = new EndpointMap(helper, childProvider, () -> stateUpdates.add(1)); + } + + // --------------------------------------------------------------------------------------------- + // Endpoint set and indices + // --------------------------------------------------------------------------------------------- + + @Test + public void updateEndpoints_assignsDenseIndicesInResolverOrder() { + endpointMap.updateEndpoints(endpoints("a", "b", "c"), Attributes.EMPTY); + + assertThat(endpointMap.size()).isEqualTo(3); + assertThat(endpointMap.indexOf("a")).isEqualTo(0); + assertThat(endpointMap.indexOf("b")).isEqualTo(1); + assertThat(endpointMap.indexOf("c")).isEqualTo(2); + assertThat(endpointMap.toPickerEndpoints()).hasSize(3); + } + + @Test + public void indexOf_unknownHostname_returnsMinusOne() { + endpointMap.updateEndpoints(endpoints("a"), Attributes.EMPTY); + + assertThat(endpointMap.indexOf("nope")).isEqualTo(-1); + } + + @Test + public void updateEndpoints_duplicateHostnames_keepsOneEntry() { + endpointMap.updateEndpoints(endpoints("a", "b", "a"), Attributes.EMPTY); + + // Indices stay dense so that they remain valid offsets into toPickerEndpoints(). + assertThat(endpointMap.size()).isEqualTo(2); + assertThat(endpointMap.toPickerEndpoints()).hasSize(2); + assertThat(endpointMap.indexOf("a")).isEqualTo(0); + assertThat(endpointMap.indexOf("b")).isEqualTo(1); + } + + @Test + public void updateEndpoints_duplicateHostnames_firstEndpointSuppliesTheAddresses() { + EquivalentAddressGroup first = endpointWithHostname("first-addr", "a"); + EquivalentAddressGroup second = endpointWithHostname("second-addr", "a"); + + endpointMap.updateEndpoints(ImmutableList.of(first, second), Attributes.EMPTY); + activate(0); + + assertThat(childProvider.children).hasSize(1); + assertThat(childProvider.children.get(0).lastAddresses.getAddresses()).containsExactly(first); + } + + @Test + public void updateEndpoints_reordering_movesIndicesAndPickerEndpoints() { + endpointMap.updateEndpoints(endpoints("a", "b"), Attributes.EMPTY); + activate(0); + reportState(0, READY); + + endpointMap.updateEndpoints(endpoints("b", "a"), Attributes.EMPTY); + + assertThat(endpointMap.indexOf("a")).isEqualTo(1); + assertThat(endpointMap.indexOf("b")).isEqualTo(0); + // The state moved with the endpoint, not with the index. + assertThat(stateAt(1)).isEqualTo(READY); + assertThat(stateAt(0)).isEqualTo(IDLE); + } + + @Test + public void hostnameAttributeAbsent_otherAddressType_usesToString() { + EquivalentAddressGroup eag = new EquivalentAddressGroup(new NamedAddress("1.2.3.4:80")); + + endpointMap.updateEndpoints(ImmutableList.of(eag), Attributes.EMPTY); + + assertThat(endpointMap.indexOf("1.2.3.4:80")).isEqualTo(0); + } + + @Test + public void hostnameAttributeAbsent_inetAddress_isNamedByIpAndPort() throws Exception { + // InetSocketAddress.toString() would give "/10.0.0.1:443" and + // "my-svc.example.com/10.0.0.2:443", neither of which an assignment would use. + InetAddress resolved = + InetAddress.getByAddress("my-svc.example.com", new byte[] {10, 0, 0, 2}); + endpointMap.updateEndpoints( + ImmutableList.of( + new EquivalentAddressGroup( + new InetSocketAddress(InetAddress.getByName("10.0.0.1"), 443)), + new EquivalentAddressGroup(new InetSocketAddress(resolved, 443))), + Attributes.EMPTY); + + assertThat(endpointMap.indexOf("10.0.0.1:443")).isEqualTo(0); + assertThat(endpointMap.indexOf("10.0.0.2:443")).isEqualTo(1); + } + + @Test + public void hostnameAttributeAbsent_ipv6Address_isCompressedAndBracketed() throws Exception { + EquivalentAddressGroup eag = + new EquivalentAddressGroup( + new InetSocketAddress(InetAddress.getByName("2001:db8:0:0:0:0:0:1"), 443)); + + endpointMap.updateEndpoints(ImmutableList.of(eag), Attributes.EMPTY); + + assertThat(endpointMap.indexOf("[2001:db8::1]:443")).isEqualTo(0); + } + + @Test + public void hostnameAttributeAbsent_unresolvedAddress_isNamedByHostAndPort() { + EquivalentAddressGroup eag = + new EquivalentAddressGroup(InetSocketAddress.createUnresolved("my-svc.example.com", 443)); + + endpointMap.updateEndpoints(ImmutableList.of(eag), Attributes.EMPTY); + + assertThat(endpointMap.indexOf("my-svc.example.com:443")).isEqualTo(0); + } + + // --------------------------------------------------------------------------------------------- + // Child lifecycle across resolver updates + // --------------------------------------------------------------------------------------------- + + @Test + public void updateEndpoints_survivingHostname_keepsChildAndState() { + endpointMap.updateEndpoints(endpoints("a"), Attributes.EMPTY); + activate(0); + reportState(0, READY); + assertThat(childProvider.children).hasSize(1); + + endpointMap.updateEndpoints(endpoints("a", "b"), Attributes.EMPTY); + + // No new child for "a", and its connectivity state survived the update. + assertThat(childProvider.children).hasSize(1); + assertThat(childProvider.children.get(0).shutdown).isFalse(); + assertThat(stateAt(0)).isEqualTo(READY); + } + + @Test + public void updateEndpoints_survivingHostname_forwardsNewAddresses() { + endpointMap.updateEndpoints(endpoints("a"), Attributes.EMPTY); + activate(0); + FakeChild child = childProvider.children.get(0); + int acceptsBefore = child.acceptCount; + + endpointMap.updateEndpoints(endpoints("a"), Attributes.EMPTY); + + assertThat(child.acceptCount).isGreaterThan(acceptsBefore); + } + + @Test + public void updateEndpoints_removedHostname_shutsDownChild() { + endpointMap.updateEndpoints(endpoints("a", "b"), Attributes.EMPTY); + activate(0); + activate(1); + + endpointMap.updateEndpoints(endpoints("b"), Attributes.EMPTY); + + assertThat(childProvider.children.get(0).shutdown).isTrue(); + assertThat(childProvider.children.get(1).shutdown).isFalse(); + assertThat(endpointMap.size()).isEqualTo(1); + assertThat(endpointMap.indexOf("a")).isEqualTo(-1); + } + + @Test + public void updateEndpoints_toEmpty_shutsDownEverything() { + endpointMap.updateEndpoints(endpoints("a"), Attributes.EMPTY); + activate(0); + + endpointMap.updateEndpoints(ImmutableList.of(), Attributes.EMPTY); + + assertThat(endpointMap.size()).isEqualTo(0); + assertThat(endpointMap.toPickerEndpoints()).isEmpty(); + assertThat(childProvider.children.get(0).shutdown).isTrue(); + } + + @Test + public void updateEndpoints_doesNotNotifyListenerWhileRebuilding() { + // New children publish their initial IDLE state from inside updateEndpoints(). Forwarding + // those would make the LB policy publish one picker per endpoint for a single update. + endpointMap.updateEndpoints(endpoints("a", "b"), Attributes.EMPTY); + + assertThat(stateUpdates).isEmpty(); + } + + @Test + public void updateEndpoints_childReenteringDuringUpdate_seesTheCompleteNewEndpointSet() { + endpointMap.updateEndpoints(endpoints("a", "b"), Attributes.EMPTY); + activate(0); + activate(1); + + // Surviving children are handed their new addresses from inside updateEndpoints() and can + // call straight back in. Record how the map looks from in there. + List observedSizes = new ArrayList<>(); + List observedIndicesOfC = new ArrayList<>(); + childProvider.onAccept = + () -> { + observedSizes.add(endpointMap.size()); + observedIndicesOfC.add(endpointMap.indexOf("c")); + }; + + endpointMap.updateEndpoints(endpoints("a", "b", "c"), Attributes.EMPTY); + + // Both callbacks see all three endpoints and the final indices, never a partial rebuild. + assertThat(observedSizes).containsExactly(3, 3); + assertThat(observedIndicesOfC).containsExactly(2, 2); + } + + @Test + public void childStateUpdate_notifiesListener() { + endpointMap.updateEndpoints(endpoints("a"), Attributes.EMPTY); + activate(0); + stateUpdates.clear(); + + reportState(0, READY); + + assertThat(stateUpdates).hasSize(1); + assertThat(stateAt(0)).isEqualTo(READY); + } + + @Test + public void childStateUpdate_afterEndpointRemoved_isIgnored() { + endpointMap.updateEndpoints(endpoints("a"), Attributes.EMPTY); + activate(0); + FakeChild child = childProvider.children.get(0); + + endpointMap.updateEndpoints(ImmutableList.of(), Attributes.EMPTY); + stateUpdates.clear(); + child.report(READY, mock(SubchannelPicker.class)); + + assertThat(stateUpdates).isEmpty(); + } + + // --------------------------------------------------------------------------------------------- + // Connecting lazily + // --------------------------------------------------------------------------------------------- + + @Test + public void endpointsStartIdleWithoutCreatingChildren() { + endpointMap.updateEndpoints(endpoints("a", "b"), Attributes.EMPTY); + + assertThat(childProvider.children).isEmpty(); + assertThat(stateAt(0)).isEqualTo(IDLE); + assertThat(stateAt(1)).isEqualTo(IDLE); + } + + @Test + public void pickerEndpoint_requestConnection_createsChildAndConnects() { + endpointMap.updateEndpoints(endpoints("a"), Attributes.EMPTY); + + endpointMap.toPickerEndpoints().get(0).requestConnection(); + + assertThat(childProvider.children).hasSize(1); + assertThat(childProvider.children.get(0).requestConnectionCount).isEqualTo(1); + } + + @Test + public void pickerEndpoint_repeatedRequestConnection_connectsOnce() { + endpointMap.updateEndpoints(endpoints("a"), Attributes.EMPTY); + // A single snapshot is shared by every concurrent RPC, so the same stale IDLE endpoint can + // be asked to connect many times over. + PickerEndpoint stale = endpointMap.toPickerEndpoints().get(0); + + stale.requestConnection(); + stale.requestConnection(); + stale.requestConnection(); + + assertThat(childProvider.children).hasSize(1); + assertThat(childProvider.children.get(0).requestConnectionCount).isEqualTo(1); + } + + @Test + public void pickerEndpoint_requestConnectionAfterEndpointRemoved_isNoOp() { + endpointMap.updateEndpoints(endpoints("a"), Attributes.EMPTY); + PickerEndpoint stale = endpointMap.toPickerEndpoints().get(0); + + endpointMap.updateEndpoints(endpoints("b"), Attributes.EMPTY); + stale.requestConnection(); + + assertThat(childProvider.children).isEmpty(); + } + + @Test + public void pickerEndpoint_requestConnectionAfterShutdown_isNoOp() { + endpointMap.updateEndpoints(endpoints("a"), Attributes.EMPTY); + PickerEndpoint stale = endpointMap.toPickerEndpoints().get(0); + + endpointMap.shutdown(); + stale.requestConnection(); + + assertThat(childProvider.children).isEmpty(); + } + + // --------------------------------------------------------------------------------------------- + // Aggregated connectivity state (gRFC A42 rules) + // --------------------------------------------------------------------------------------------- + + @Test + public void aggregate_empty_isTransientFailure() { + assertThat(endpointMap.aggregateConnectivityState()).isEqualTo(TRANSIENT_FAILURE); + } + + @Test + public void aggregate_anyReady_isReady() { + setUpStates(TRANSIENT_FAILURE, TRANSIENT_FAILURE, READY); + + assertThat(endpointMap.aggregateConnectivityState()).isEqualTo(READY); + } + + @Test + public void aggregate_twoTransientFailures_isTransientFailure() { + setUpStates(TRANSIENT_FAILURE, TRANSIENT_FAILURE, IDLE); + + assertThat(endpointMap.aggregateConnectivityState()).isEqualTo(TRANSIENT_FAILURE); + } + + @Test + public void aggregate_anyConnecting_isConnecting() { + setUpStates(IDLE, CONNECTING); + + assertThat(endpointMap.aggregateConnectivityState()).isEqualTo(CONNECTING); + } + + @Test + public void aggregate_oneTransientFailureAmongMany_isConnecting() { + setUpStates(TRANSIENT_FAILURE, IDLE); + + assertThat(endpointMap.aggregateConnectivityState()).isEqualTo(CONNECTING); + } + + @Test + public void aggregate_soleEndpointInTransientFailure_isTransientFailure() { + setUpStates(TRANSIENT_FAILURE); + + assertThat(endpointMap.aggregateConnectivityState()).isEqualTo(TRANSIENT_FAILURE); + } + + @Test + public void aggregate_allIdle_isIdle() { + endpointMap.updateEndpoints(endpoints("a", "b"), Attributes.EMPTY); + + assertThat(endpointMap.aggregateConnectivityState()).isEqualTo(IDLE); + } + + // --------------------------------------------------------------------------------------------- + // Waking up an idle endpoint + // --------------------------------------------------------------------------------------------- + + @Test + public void maybeWakeUpIdleEndpoint_connectsLowestIndexedIdleEndpoint() { + setUpStates(TRANSIENT_FAILURE, IDLE, IDLE); + + endpointMap.maybeWakeUpIdleEndpoint(); + + assertThat(stateAt(1)).isEqualTo(CONNECTING); + assertThat(stateAt(2)).isEqualTo(IDLE); + } + + @Test + public void maybeWakeUpIdleEndpoint_somethingAlreadyConnecting_doesNothing() { + setUpStates(CONNECTING, IDLE); + int childrenBefore = childProvider.children.size(); + + endpointMap.maybeWakeUpIdleEndpoint(); + + assertThat(childProvider.children).hasSize(childrenBefore); + assertThat(stateAt(1)).isEqualTo(IDLE); + } + + @Test + public void maybeWakeUpIdleEndpoint_noIdleEndpoints_doesNothing() { + setUpStates(TRANSIENT_FAILURE, TRANSIENT_FAILURE); + int childrenBefore = childProvider.children.size(); + + endpointMap.maybeWakeUpIdleEndpoint(); + + assertThat(childProvider.children).hasSize(childrenBefore); + } + + @Test + public void maybeWakeUpIdleEndpoint_aggregateIdle_doesNothing() { + setUpStates(IDLE, IDLE); + + endpointMap.maybeWakeUpIdleEndpoint(); + + assertThat(childProvider.children).isEmpty(); + } + + @Test + public void maybeWakeUpIdleEndpoint_aggregateReady_doesNothing() { + setUpStates(READY, IDLE); + int childrenBefore = childProvider.children.size(); + + endpointMap.maybeWakeUpIdleEndpoint(); + + assertThat(childProvider.children).hasSize(childrenBefore); + assertThat(stateAt(1)).isEqualTo(IDLE); + } + + // --------------------------------------------------------------------------------------------- + // Shutdown + // --------------------------------------------------------------------------------------------- + + @Test + public void shutdown_shutsDownChildrenAndEmptiesMap() { + endpointMap.updateEndpoints(endpoints("a", "b"), Attributes.EMPTY); + activate(0); + activate(1); + + endpointMap.shutdown(); + + assertThat(childProvider.children.get(0).shutdown).isTrue(); + assertThat(childProvider.children.get(1).shutdown).isTrue(); + assertThat(endpointMap.size()).isEqualTo(0); + assertThat(endpointMap.indexOf("a")).isEqualTo(-1); + } + + @Test + public void shutdown_isIdempotent() { + endpointMap.updateEndpoints(endpoints("a"), Attributes.EMPTY); + activate(0); + + endpointMap.shutdown(); + endpointMap.shutdown(); + + assertThat(endpointMap.size()).isEqualTo(0); + assertThat(childProvider.children.get(0).shutdown).isTrue(); + } + + @Test + public void shutdown_childReportingWhileShuttingDown_doesNotNotifyListener() { + endpointMap.updateEndpoints(endpoints("a"), Attributes.EMPTY); + activate(0); + childProvider.reportOnShutdown = true; + stateUpdates.clear(); + + endpointMap.shutdown(); + + assertThat(stateUpdates).isEmpty(); + } + + @Test + public void shutdown_childReportingAfterShutdown_doesNotNotifyListener() { + endpointMap.updateEndpoints(endpoints("a"), Attributes.EMPTY); + activate(0); + FakeChild child = childProvider.children.get(0); + endpointMap.shutdown(); + stateUpdates.clear(); + + child.report(READY, mock(SubchannelPicker.class)); + + assertThat(stateUpdates).isEmpty(); + } + + @Test + public void updateEndpoints_removedChildReportingWhileShuttingDown_doesNotNotifyListener() { + endpointMap.updateEndpoints(endpoints("a", "b"), Attributes.EMPTY); + activate(0); + childProvider.reportOnShutdown = true; + stateUpdates.clear(); + + endpointMap.updateEndpoints(endpoints("b"), Attributes.EMPTY); + + assertThat(childProvider.children.get(0).shutdown).isTrue(); + assertThat(stateUpdates).isEmpty(); + } + + // --------------------------------------------------------------------------------------------- + // Helpers + // --------------------------------------------------------------------------------------------- + + /** Drives the endpoints at indices 0..n-1 into the given states. */ + private void setUpStates(ConnectivityState... states) { + String[] names = new String[states.length]; + for (int i = 0; i < states.length; i++) { + names[i] = "host" + i; + } + endpointMap.updateEndpoints(endpoints(names), Attributes.EMPTY); + for (int i = 0; i < states.length; i++) { + if (states[i] == IDLE) { + continue; + } + activate(i); + reportState(i, states[i]); + } + stateUpdates.clear(); + } + + /** Instantiates the child load balancer behind the endpoint at {@code index}. */ + private void activate(int index) { + endpointMap.toPickerEndpoints().get(index).requestConnection(); + } + + private void reportState(int index, ConnectivityState state) { + childForHost(hostnames.get(index)).report(state, mock(SubchannelPicker.class)); + } + + private ConnectivityState stateAt(int index) { + return endpointMap.toPickerEndpoints().get(index).getState(); + } + + /** Returns the child load balancer created for {@code hostname}. */ + private FakeChild childForHost(String hostname) { + for (FakeChild child : childProvider.children) { + if (child.lastAddresses == null) { + continue; + } + String childHostname = + child + .lastAddresses + .getAddresses() + .get(0) + .getAttributes() + .get(InternalEquivalentAddressGroup.ATTR_ADDRESS_NAME); + if (hostname.equals(childHostname)) { + return child; + } + } + throw new AssertionError("No child load balancer created for hostname " + hostname); + } + + /** Hostnames of the endpoints most recently produced by {@link #endpoints}. */ + private final List hostnames = new ArrayList<>(); + + private List endpoints(String... hostnameArgs) { + hostnames.clear(); + List eags = new ArrayList<>(); + for (String hostname : hostnameArgs) { + hostnames.add(hostname); + eags.add(endpointWithHostname("addr-" + hostname, hostname)); + } + return ImmutableList.copyOf(eags); + } + + /** An endpoint at {@code addressName} advertising {@code hostname}. */ + private static EquivalentAddressGroup endpointWithHostname(String addressName, String hostname) { + return new EquivalentAddressGroup( + new NamedAddress(addressName), + Attributes.newBuilder() + .set(InternalEquivalentAddressGroup.ATTR_ADDRESS_NAME, hostname) + .build()); + } + + /** A {@link SocketAddress} with a predictable {@link #toString}. */ + private static final class NamedAddress extends SocketAddress { + private static final long serialVersionUID = 0L; + private final String name; + + NamedAddress(String name) { + this.name = name; + } + + @Override + public String toString() { + return name; + } + } + + private static final class FakeChildProvider extends LoadBalancerProvider { + final List children = new ArrayList<>(); + + /** Run from every child's {@code acceptResolvedAddresses}, to exercise re-entrancy. */ + Runnable onAccept; + boolean reportOnShutdown; + + @Override + public boolean isAvailable() { + return true; + } + + @Override + public int getPriority() { + return 5; + } + + @Override + public String getPolicyName() { + return "fake_child"; + } + + @Override + public LoadBalancer newLoadBalancer(Helper helper) { + FakeChild child = new FakeChild(helper, this); + children.add(child); + return child; + } + } + + /** Stands in for {@code pick_first}, including its move to CONNECTING when asked to connect. */ + private static final class FakeChild extends LoadBalancer { + private final Helper helper; + private final FakeChildProvider provider; + ResolvedAddresses lastAddresses; + int acceptCount; + int requestConnectionCount; + boolean shutdown; + + FakeChild(Helper helper, FakeChildProvider provider) { + this.helper = helper; + this.provider = provider; + } + + @Override + public Status acceptResolvedAddresses(ResolvedAddresses resolvedAddresses) { + lastAddresses = resolvedAddresses; + acceptCount++; + if (provider.onAccept != null) { + provider.onAccept.run(); + } + return Status.OK; + } + + @Override + public void handleNameResolutionError(Status error) {} + + @Override + public void requestConnection() { + requestConnectionCount++; + report(CONNECTING, new FixedResultPicker(PickResult.withNoResult())); + } + + @Override + public void shutdown() { + shutdown = true; + if (provider.reportOnShutdown) { + report(TRANSIENT_FAILURE, new FixedResultPicker(PickResult.withNoResult())); + } + } + + void report(ConnectivityState state, SubchannelPicker picker) { + helper.updateBalancingState(state, picker); + } + } +} diff --git a/autosharding/src/test/java/io/grpc/autosharding/SliceMapTest.java b/autosharding/src/test/java/io/grpc/autosharding/SliceMapTest.java index 126c008d392..979b41f831f 100644 --- a/autosharding/src/test/java/io/grpc/autosharding/SliceMapTest.java +++ b/autosharding/src/test/java/io/grpc/autosharding/SliceMapTest.java @@ -33,7 +33,7 @@ public class SliceMapTest { @Test public void lookup_emptySlices_returnsInvalidIndex() { - SliceMap sliceMap = new SliceMap(Collections.emptyList(), Arrays.asList(0, 1), 1L); + SliceMap sliceMap = new SliceMap(Collections.emptyList(), Arrays.asList(0, 1)); assertThat(sliceMap.lookup(new byte[] {1, 2, 3})).isEqualTo(-1); assertThat(sliceMap.lookup(null)).isEqualTo(-1); assertThat(sliceMap.lookup(new byte[0])).isEqualTo(-1); @@ -44,7 +44,7 @@ public void lookup_singleSlice() { byte[] startKey = new byte[0]; // Covers ["" .. inf) SliceEntry slice = new SliceEntry(startKey, Arrays.asList(0, 1)); SliceMap sliceMap = new SliceMap( - Collections.singletonList(slice), Arrays.asList(0, 1), 10L); + Collections.singletonList(slice), Arrays.asList(0, 1)); assertThat(sliceMap.lookup(new byte[0])).isEqualTo(0); assertThat(sliceMap.lookup("foo".getBytes(StandardCharsets.UTF_8))).isEqualTo(0); @@ -61,7 +61,7 @@ public void lookup_multipleSlices() { SliceEntry s3 = new SliceEntry( "t".getBytes(StandardCharsets.UTF_8), Collections.singletonList(2)); - SliceMap sliceMap = new SliceMap(Arrays.asList(s3, s1, s2), Arrays.asList(0, 1, 2), 5L); + SliceMap sliceMap = new SliceMap(Arrays.asList(s1, s2, s3), Arrays.asList(0, 1, 2)); // Exact matches assertThat(sliceMap.lookup("".getBytes(StandardCharsets.UTF_8))).isEqualTo(0); @@ -83,7 +83,7 @@ public void lookup_keySmallerThanFirstSlice_returnsInvalidIndex() { SliceEntry s1 = new SliceEntry( "m".getBytes(StandardCharsets.UTF_8), Collections.singletonList(0)); SliceMap sliceMap = new SliceMap( - Collections.singletonList(s1), Collections.singletonList(0), 1L); + Collections.singletonList(s1), Collections.singletonList(0)); assertThat(sliceMap.lookup("a".getBytes(StandardCharsets.UTF_8))).isEqualTo(-1); assertThat(sliceMap.lookup("".getBytes(StandardCharsets.UTF_8))).isEqualTo(-1); @@ -105,7 +105,7 @@ public void lookup_unsignedByteComparison() { SliceEntry s4 = new SliceEntry(key3, Collections.singletonList(3)); SliceMap sliceMap = new SliceMap( - Arrays.asList(s4, s2, s1, s3), Arrays.asList(0, 1, 2, 3), 1L); + Arrays.asList(s1, s2, s3, s4), Arrays.asList(0, 1, 2, 3)); assertThat(sliceMap.lookup(new byte[] {0x10})).isEqualTo(0); assertThat(sliceMap.lookup(new byte[] {0x7F})).isEqualTo(1); @@ -122,20 +122,18 @@ public void gettersAndImmutability() { slices.add(new SliceEntry(inputKey, Arrays.asList(0, 1))); List fallback = new ArrayList<>(Arrays.asList(0, 1)); - SliceMap sliceMap = new SliceMap(slices, fallback, 42L); + SliceMap sliceMap = new SliceMap(slices, fallback); - assertThat(sliceMap.getGeneration()).isEqualTo(42L); assertThat(sliceMap.getFallbackPool()).containsExactly(0, 1).inOrder(); assertThat(sliceMap.getSlices()).hasSize(1); assertThat(sliceMap.getSlices().get(0).getStartKey()).isEqualTo(new byte[] {1}); assertThat(sliceMap.getSlices().get(0).getEndpoints()).containsExactly(0, 1).inOrder(); - // Verify defensive copying: mutating input collections and key array does not affect sliceMap - inputKey[0] = 99; + // The lists are copied; the key array is shared. slices.clear(); fallback.clear(); assertThat(sliceMap.getSlices()).hasSize(1); - assertThat(sliceMap.getSlices().get(0).getStartKey()).isEqualTo(new byte[] {1}); + assertThat(sliceMap.getSlices().get(0).getStartKey()).isSameInstanceAs(inputKey); assertThat(sliceMap.getFallbackPool()).containsExactly(0, 1).inOrder(); } @@ -145,42 +143,18 @@ public void lookup_nullKey_treatedAsEmptyBytes() { "".getBytes(StandardCharsets.UTF_8), Collections.singletonList(0)); SliceEntry s2 = new SliceEntry( "m".getBytes(StandardCharsets.UTF_8), Collections.singletonList(1)); - SliceMap sliceMap = new SliceMap(Arrays.asList(s1, s2), Arrays.asList(0, 1), 1L); + SliceMap sliceMap = new SliceMap(Arrays.asList(s1, s2), Arrays.asList(0, 1)); assertThat(sliceMap.lookup(null)).isEqualTo(0); } - @Test - public void constructor_unsortedSlices_sortedLexicographically() { - SliceEntry s1 = new SliceEntry( - "".getBytes(StandardCharsets.UTF_8), Collections.singletonList(0)); - SliceEntry s2 = new SliceEntry( - "m".getBytes(StandardCharsets.UTF_8), Collections.singletonList(1)); - SliceEntry s3 = new SliceEntry( - "z".getBytes(StandardCharsets.UTF_8), Collections.singletonList(2)); - - // Pass in reverse order - SliceMap sliceMap = new SliceMap(Arrays.asList(s3, s1, s2), Arrays.asList(0, 1, 2), 1L); - - assertThat(sliceMap.getSlices().get(0).getStartKey()) - .isEqualTo("".getBytes(StandardCharsets.UTF_8)); - assertThat(sliceMap.getSlices().get(1).getStartKey()) - .isEqualTo("m".getBytes(StandardCharsets.UTF_8)); - assertThat(sliceMap.getSlices().get(2).getStartKey()) - .isEqualTo("z".getBytes(StandardCharsets.UTF_8)); - - assertThat(sliceMap.lookup("abc".getBytes(StandardCharsets.UTF_8))).isEqualTo(0); - assertThat(sliceMap.lookup("mmm".getBytes(StandardCharsets.UTF_8))).isEqualTo(1); - assertThat(sliceMap.lookup("zzz".getBytes(StandardCharsets.UTF_8))).isEqualTo(2); - } - @Test public void lookup_duplicateStartKeys_matchesOne() { SliceEntry s1 = new SliceEntry( "a".getBytes(StandardCharsets.UTF_8), Collections.singletonList(0)); SliceEntry s2 = new SliceEntry( "a".getBytes(StandardCharsets.UTF_8), Collections.singletonList(1)); - SliceMap sliceMap = new SliceMap(Arrays.asList(s1, s2), Arrays.asList(0, 1), 1L); + SliceMap sliceMap = new SliceMap(Arrays.asList(s1, s2), Arrays.asList(0, 1)); int idx = sliceMap.lookup("a".getBytes(StandardCharsets.UTF_8)); assertThat(idx).isAnyOf(0, 1); @@ -190,11 +164,11 @@ public void lookup_duplicateStartKeys_matchesOne() { public void constructor_nullInputs_throwsNullPointerException() { org.junit.Assert.assertThrows( NullPointerException.class, - () -> new SliceMap(null, Collections.singletonList(0), 1L)); + () -> new SliceMap(null, Collections.singletonList(0))); org.junit.Assert.assertThrows( NullPointerException.class, - () -> new SliceMap(Collections.emptyList(), null, 1L)); + () -> new SliceMap(Collections.emptyList(), null)); org.junit.Assert.assertThrows( NullPointerException.class,