diff --git a/topic/pom.xml b/topic/pom.xml index 9eedc9d80..00d57f725 100644 --- a/topic/pom.xml +++ b/topic/pom.xml @@ -40,7 +40,6 @@ zstd-jni 1.5.7-2 - junit junit diff --git a/topic/src/main/java/tech/ydb/topic/write/impl/multi/IncompleteTopologyException.java b/topic/src/main/java/tech/ydb/topic/write/impl/multi/IncompleteTopologyException.java new file mode 100644 index 000000000..e578092c6 --- /dev/null +++ b/topic/src/main/java/tech/ydb/topic/write/impl/multi/IncompleteTopologyException.java @@ -0,0 +1,10 @@ +package tech.ydb.topic.write.impl.multi; + +/** The described partitions do not provide enough evidence to accept a topology. */ +final class IncompleteTopologyException extends IllegalArgumentException { + private static final long serialVersionUID = 1L; + + IncompleteTopologyException(String message) { + super(message); + } +} diff --git a/topic/src/main/java/tech/ydb/topic/write/impl/multi/KeyHash.java b/topic/src/main/java/tech/ydb/topic/write/impl/multi/KeyHash.java new file mode 100644 index 000000000..d118e30f1 --- /dev/null +++ b/topic/src/main/java/tech/ydb/topic/write/impl/multi/KeyHash.java @@ -0,0 +1,76 @@ +package tech.ydb.topic.write.impl.multi; + +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; + +final class KeyHash { + private static final long MULTIPLIER_64 = 0xc6a4a7935bd1e995L; + private static final int MULTIPLIER_32 = 0x5bd1e995; + private static final int KAFKA_SEED = 0x9747b28c; + + private KeyHash() { } + + static byte[] boundKey(String key) { + return ByteBuffer.allocate(Long.BYTES).putLong(murmur64(key.getBytes(StandardCharsets.UTF_8))).array(); + } + + static int kafkaHash(String key) { + return murmur32(key.getBytes(StandardCharsets.UTF_8)) & 0x7fffffff; + } + + static long murmur64(byte[] data) { + long hash = data.length * MULTIPLIER_64; + int offset = 0; + while (offset <= data.length - Long.BYTES) { + long block = 0; + for (int index = 0; index < Long.BYTES; index++) { + block |= (data[offset + index] & 0xffL) << (index * Byte.SIZE); + } + block *= MULTIPLIER_64; + block ^= block >>> 47; + block *= MULTIPLIER_64; + hash ^= block; + hash *= MULTIPLIER_64; + offset += Long.BYTES; + } + int remaining = data.length - offset; + for (int index = 0; index < remaining; index++) { + hash ^= (data[offset + index] & 0xffL) << (index * Byte.SIZE); + } + if (remaining > 0) { + hash *= MULTIPLIER_64; + } + hash ^= hash >>> 47; + hash *= MULTIPLIER_64; + hash ^= hash >>> 47; + return hash; + } + + static int murmur32(byte[] data) { + int hash = KAFKA_SEED ^ data.length; + int offset = 0; + while (offset <= data.length - Integer.BYTES) { + int block = 0; + for (int index = 0; index < Integer.BYTES; index++) { + block |= (data[offset + index] & 0xff) << (index * Byte.SIZE); + } + block *= MULTIPLIER_32; + block ^= block >>> 24; + block *= MULTIPLIER_32; + hash *= MULTIPLIER_32; + hash ^= block; + offset += Integer.BYTES; + } + int remaining = data.length - offset; + for (int index = 0; index < remaining; index++) { + hash ^= (data[offset + index] & 0xff) << (index * Byte.SIZE); + } + if (remaining > 0) { + hash *= MULTIPLIER_32; + } + hash ^= hash >>> 13; + hash *= MULTIPLIER_32; + hash ^= hash >>> 15; + return hash; + } +} diff --git a/topic/src/main/java/tech/ydb/topic/write/impl/multi/RoutingMode.java b/topic/src/main/java/tech/ydb/topic/write/impl/multi/RoutingMode.java new file mode 100644 index 000000000..b6b6f1ad0 --- /dev/null +++ b/topic/src/main/java/tech/ydb/topic/write/impl/multi/RoutingMode.java @@ -0,0 +1,8 @@ +package tech.ydb.topic.write.impl.multi; + +enum RoutingMode { + AUTO, + BOUND, + HASH, + EXPLICIT +} diff --git a/topic/src/main/java/tech/ydb/topic/write/impl/multi/Topology.java b/topic/src/main/java/tech/ydb/topic/write/impl/multi/Topology.java new file mode 100644 index 000000000..d12326d30 --- /dev/null +++ b/topic/src/main/java/tech/ydb/topic/write/impl/multi/Topology.java @@ -0,0 +1,392 @@ +package tech.ydb.topic.write.impl.multi; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.TreeMap; +import java.util.function.Consumer; + +import javax.annotation.Nullable; + +import tech.ydb.topic.description.PartitionInfo; +import tech.ydb.topic.settings.AutoPartitioningStrategy; + +/** + * Immutable, validated topic snapshot. Only a compatible successor can replace + * it. In BOUND mode, the active descendants of a split must cover the old range; + * partition merges are not supported. + */ +final class Topology { + private static final String NO_ACTIVE_PARTITIONS = "Topology has no active partitions"; + + private final Map partitions; + private final List active = new ArrayList<>(); + private final List ranges = new ArrayList<>(); + private final RoutingMode routingMode; + + Topology(List description, RoutingMode requested, AutoPartitioningStrategy strategy) { + this(description, requested, strategy, null); + } + + private Topology(List description, RoutingMode requested, AutoPartitioningStrategy strategy, + Topology previous) { + Objects.requireNonNull(description, "partitions"); + Objects.requireNonNull(requested, "routing mode"); + if (previous != null && requested != RoutingMode.AUTO) { + requireSameRoutingMode(previous.routingMode, requested); + } + if (description.isEmpty()) { + throw new IncompleteTopologyException(NO_ACTIVE_PARTITIONS); + } + RoutingMode mode = requested; + if (mode == RoutingMode.AUTO && ((previous != null && previous.routingMode == RoutingMode.BOUND) + || (strategy != null && strategy != AutoPartitioningStrategy.DISABLED))) { + mode = RoutingMode.BOUND; + } + this.partitions = readPartitions(description, mode); + if (active.isEmpty()) { + throw new IncompleteTopologyException(NO_ACTIVE_PARTITIONS); + } + this.routingMode = mode == RoutingMode.AUTO ? (ranges.isEmpty() ? RoutingMode.HASH : RoutingMode.BOUND) : mode; + if (routingMode == RoutingMode.HASH && previous != null && previous.routingMode == RoutingMode.HASH + && !sameActiveIds(previous.active, active)) { + throw new IncompatibleTransformationException("Hash partition set changed; ordering cannot be preserved"); + } + if (routingMode == RoutingMode.BOUND) { + ranges.sort(Comparator.comparing(range -> range.from, Topology::compareUnsigned)); + validateBoundRanges(); + } + } + + private Map readPartitions(List description, RoutingMode mode) { + Consumer readActive = activePartitionReader(mode, description.size() == 1); + Map indexed = new TreeMap<>(); + for (PartitionInfo partition : description) { + if (partition == null || partition.getPartitionId() < 0) { + throw new IllegalArgumentException("Partition IDs must be nonnegative"); + } + long id = partition.getPartitionId(); + if (indexed.put(id, partition) != null) { + throw new IllegalArgumentException("Duplicate partition ID " + id); + } + if (readActive != null && partition.isActive()) { + readActive.accept(partition); + } + } + for (PartitionInfo partition : indexed.values()) { + if (partition.isActive()) { + active.add(partition); + } + } + return Collections.unmodifiableMap(indexed); + } + + @Nullable + private Consumer activePartitionReader(RoutingMode mode, boolean singlePartition) { + switch (mode) { + case HASH: + return Topology::validateHashPartition; + case BOUND: + return partition -> readBoundRange(partition, singlePartition); + case AUTO: + return autoRangeReader(); + case EXPLICIT: + return null; + default: + throw new IllegalArgumentException("Unknown routing mode: " + mode); + } + } + + private static void validateHashPartition(PartitionInfo partition) { + if (partition.hasKeyRange()) { + throw new IllegalArgumentException("Hash routing requires partitions without key ranges"); + } + } + + private void readBoundRange(PartitionInfo partition, boolean singlePartition) { + if (partition.hasKeyRange()) { + ranges.add(new Range(partition)); + } else if (singlePartition) { + ranges.add(new Range(partition.getPartitionId(), Range.WHOLE.from, Range.WHOLE.to)); + } else { + throw missingKeyRange(partition.getPartitionId()); + } + } + + private Consumer autoRangeReader() { + return new Consumer() { + private long firstPartitionWithoutRange = -1; + + @Override + public void accept(PartitionInfo partition) { + if (partition.hasKeyRange()) { + if (firstPartitionWithoutRange >= 0) { + throw missingKeyRange(firstPartitionWithoutRange); + } + ranges.add(new Range(partition)); + return; + } + if (!ranges.isEmpty()) { + throw missingKeyRange(partition.getPartitionId()); + } + if (firstPartitionWithoutRange < 0) { + firstPartitionWithoutRange = partition.getPartitionId(); + } + } + }; + } + + private void validateBoundRanges() { + Range previous = ranges.get(0); + if (previous.from.length != 0) { + throw missingCoverage(); + } + for (int i = 1; i < ranges.size(); i++) { + if (previous.to.length == 0) { + throw new IllegalArgumentException("Key ranges overlap"); + } + Range next = ranges.get(i); + int order = compareUnsigned(previous.to, next.from); + if (order > 0) { + throw new IllegalArgumentException("Key ranges overlap"); + } + if (order < 0) { + throw missingCoverage(); + } + previous = next; + } + if (previous.to.length != 0) { + throw missingCoverage(); + } + } + + private static IllegalArgumentException missingKeyRange(long id) { + return new IllegalArgumentException("Missing key range for active partition " + id); + } + + private static IncompleteTopologyException missingCoverage() { + return new IncompleteTopologyException("Key ranges do not cover the whole key space"); + } + + static Topology refresh(Topology previous, List description, RoutingMode requested, + AutoPartitioningStrategy strategy) { + Objects.requireNonNull(previous, "previous topology"); + Topology candidate = new Topology(description, requested, strategy, previous); + if (requested == RoutingMode.AUTO) { + requireSameRoutingMode(previous.routingMode, candidate.routingMode); + } + if (candidate.routingMode == RoutingMode.BOUND) { + candidate.validateSplits(previous); + } else if (candidate.routingMode == RoutingMode.EXPLICIT) { + for (PartitionInfo old : previous.active) { + if (!candidate.partitions.containsKey(old.getPartitionId())) { + throw new IncompleteTopologyException( + "Missing previously active partition " + old.getPartitionId()); + } + } + } + return candidate; + } + + private void validateSplits(Topology previous) { + Map retiring = new HashMap<>(); + for (Range old : previous.ranges) { + PartitionInfo current = partitions.get(old.id); + if (current == null || !current.isActive()) { + retiring.put(old.id, old); + } + } + if (retiring.isEmpty()) { + return; + } + + Map coveredTo = new HashMap<>(); + for (Range child : ranges) { + Range parent = findSplitParent(child.id, previous, retiring); + if (parent == null) { + continue; + } + if (!parent.contains(child)) { + throw new IncompatibleTransformationException( + "Partition range outside its expected parent: " + child.id); + } + if (!Arrays.equals(coveredTo.getOrDefault(parent.id, parent.from), child.from)) { + throw new IncompleteTopologyException("Children do not cover the range of partition " + parent.id); + } + coveredTo.put(parent.id, child.to); + } + for (Range parent : retiring.values()) { + if (!Arrays.equals(coveredTo.get(parent.id), parent.to)) { + throw new IncompleteTopologyException("Children do not cover the range of partition " + parent.id); + } + } + } + + @Nullable + private Range findSplitParent(long childId, Topology previous, Map retiring) { + Set visited = null; + PartitionInfo current = partitions.get(childId); + while (current != null) { + long id = current.getPartitionId(); + List parents = current.getParentPartitionIds(); + if (parents.isEmpty()) { + return null; + } + if (parents.size() > 1) { + throw new IncompatibleTransformationException("Split child has multiple parents: " + id); + } + long parentId = parents.get(0); + Range parent = retiring.get(parentId); + if (parent != null) { + return parent; + } + PartitionInfo old = previous.partitions.get(id); + if (old != null && old.isActive()) { + // This branch was already active in the previous snapshot. + return null; + } + if (visited == null) { + visited = new HashSet<>(); + visited.add(childId); + } + if (!visited.add(parentId)) { + throw new IncompatibleTransformationException("Cycle in split parents of partition " + childId); + } + current = partitions.get(parentId); + } + return null; + } + + private static void requireSameRoutingMode(RoutingMode previous, RoutingMode current) { + if (current != previous) { + throw new IncompatibleTransformationException("Routing mode must not change during writer lifetime"); + } + } + + Route route(String key, Long explicitId) { + if (routingMode == RoutingMode.EXPLICIT) { + if (explicitId == null) { + throw new IllegalArgumentException("Explicit routing requires a partition ID"); + } + PartitionInfo selected = partitions.get(explicitId); + if (selected == null || !selected.isActive()) { + throw new IllegalArgumentException("Explicit partition is not active: " + explicitId); + } + return new Route(explicitId, null); + } + if (explicitId != null) { + throw new IllegalArgumentException("Partition ID requires explicit routing"); + } + Objects.requireNonNull(key, "key"); + if (routingMode == RoutingMode.BOUND) { + byte[] partitionKey = KeyHash.boundKey(key); + return new Route(routeBound(partitionKey), partitionKey); + } + long partitionId = active.get(KeyHash.kafkaHash(key) % active.size()).getPartitionId(); + return new Route(partitionId, null); + } + + long routeBound(byte[] hashedKey) { + if (routingMode != RoutingMode.BOUND) { + throw new IllegalStateException("Bound routing is not selected"); + } + int low = 0; + int high = ranges.size(); + while (low < high) { + int middle = (low + high) >>> 1; + if (compareUnsigned(ranges.get(middle).from, hashedKey) <= 0) { + low = middle + 1; + } else { + high = middle; + } + } + return ranges.get(low - 1).id; + } + + private static boolean sameActiveIds(List previous, List current) { + if (previous.size() != current.size()) { + return false; + } + // Both lists follow partition ID order from the map. + for (int i = 0; i < previous.size(); i++) { + if (previous.get(i).getPartitionId() != current.get(i).getPartitionId()) { + return false; + } + } + return true; + } + + static int compareUnsigned(byte[] left, byte[] right) { + int count = Math.min(left.length, right.length); + for (int index = 0; index < count; index++) { + int difference = (left[index] & 0xff) - (right[index] & 0xff); + if (difference != 0) { + return difference; + } + } + return Integer.compare(left.length, right.length); + } + + /** The incoming topology conflicts with the accepted routing. */ + static final class IncompatibleTransformationException extends IllegalArgumentException { + private static final long serialVersionUID = 1L; + + private IncompatibleTransformationException(String message) { + super(message); + } + } + + private static final class Range { + private static final Range WHOLE = new Range(-1, new byte[0], new byte[0]); + + private final long id; + private final byte[] from; + private final byte[] to; + + private Range(PartitionInfo partition) { + this(partition.getPartitionId(), partition.getFromBound(), partition.getToBound()); + } + + private Range(long id, byte[] from, byte[] to) { + if (from.length != 0 && to.length != 0 && compareUnsigned(from, to) >= 0) { + throw new IllegalArgumentException("Empty or inverted key range for partition " + id); + } + this.id = id; + this.from = from; + this.to = to; + } + + private boolean contains(Range child) { + return (from.length == 0 || compareUnsigned(child.from, from) >= 0) + && (to.length == 0 || (child.to.length != 0 && compareUnsigned(child.to, to) <= 0)); + } + } + + static final class Route { + private final long partitionId; + @Nullable + private final byte[] partitionKey; + + private Route(long partitionId, @Nullable byte[] partitionKey) { + this.partitionId = partitionId; + this.partitionKey = partitionKey; + } + + long getPartitionId() { + return partitionId; + } + + /** Returns a copy of the BOUND key, or null for other routing modes. */ + @Nullable + byte[] getPartitionKey() { + return partitionKey == null ? null : partitionKey.clone(); + } + } +} diff --git a/topic/src/main/java/tech/ydb/topic/write/impl/multi/TopologyLoader.java b/topic/src/main/java/tech/ydb/topic/write/impl/multi/TopologyLoader.java new file mode 100644 index 000000000..3ac05cc48 --- /dev/null +++ b/topic/src/main/java/tech/ydb/topic/write/impl/multi/TopologyLoader.java @@ -0,0 +1,76 @@ +package tech.ydb.topic.write.impl.multi; + +import java.time.Duration; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.RejectedExecutionException; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; +import java.util.function.Function; + +import javax.annotation.Nullable; + +import tech.ydb.core.Result; +import tech.ydb.core.utils.FutureTools; +import tech.ydb.topic.TopicClient; +import tech.ydb.topic.description.TopicDescription; +import tech.ydb.topic.settings.AutoPartitioningStrategy; +import tech.ydb.topic.settings.DescribeTopicSettings; + +final class TopologyLoader { + private static final int DESCRIBE_ATTEMPTS = 4; + private static final long RETRY_DELAY_MS = 250; + private static final DescribeTopicSettings DESCRIBE_SETTINGS = DescribeTopicSettings.newBuilder() + .withRequestTimeout(Duration.ofSeconds(30)) + .build(); + + private final TopicClient client; + private final String path; + private final ScheduledExecutorService scheduler; + + TopologyLoader(TopicClient client, String path, ScheduledExecutorService scheduler) { + this.client = client; + this.path = path; + this.scheduler = scheduler; + } + + CompletableFuture load(RoutingMode mode, @Nullable Topology previous) { + CompletableFuture result = new CompletableFuture<>(); + describe(result, DESCRIBE_ATTEMPTS, snapshot -> { + AutoPartitioningStrategy strategy = snapshot.getPartitioningSettings().getAutoPartitioningStrategy(); + return previous == null ? new Topology(snapshot.getPartitions(), mode, strategy) + : Topology.refresh(previous, snapshot.getPartitions(), mode, strategy); + }); + return result; + } + + private void describe(CompletableFuture result, int attempts, + Function build) { + if (result.isDone()) { + return; + } + CompletableFuture described; + try { + described = client.describeTopic(path, DESCRIBE_SETTINGS).thenApply(Result::getValue).thenApply(build); + } catch (RuntimeException error) { + result.completeExceptionally(error); + return; + } + described.whenComplete((topology, error) -> { + if (error == null) { + result.complete(topology); + return; + } + Throwable cause = FutureTools.unwrapCompletionException(error); + if (!(cause instanceof IncompleteTopologyException) || attempts == 1) { + result.completeExceptionally(cause); + } else if (!result.isDone()) { + try { + scheduler.schedule(() -> describe(result, attempts - 1, build), RETRY_DELAY_MS, + TimeUnit.MILLISECONDS); + } catch (RejectedExecutionException rejected) { + result.completeExceptionally(rejected); + } + } + }); + } +} diff --git a/topic/src/test/java/tech/ydb/topic/write/impl/multi/MultiWriterRoutingTest.java b/topic/src/test/java/tech/ydb/topic/write/impl/multi/MultiWriterRoutingTest.java new file mode 100644 index 000000000..42d286000 --- /dev/null +++ b/topic/src/test/java/tech/ydb/topic/write/impl/multi/MultiWriterRoutingTest.java @@ -0,0 +1,612 @@ +package tech.ydb.topic.write.impl.multi; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +import com.google.protobuf.ByteString; +import org.junit.Assert; +import org.junit.Test; +import org.junit.function.ThrowingRunnable; + +import tech.ydb.proto.topic.YdbTopic; +import tech.ydb.topic.description.PartitionInfo; +import tech.ydb.topic.settings.AutoPartitioningStrategy; +import tech.ydb.topic.write.impl.multi.Topology.Route; + +public class MultiWriterRoutingTest { + @Test + public void hashesMatchReferenceVectors() { + // Columns: raw input hex, Murmur2Hash32(seed 0x9747b28c), Murmur2Hash64A(seed + // 0). + String[][] vectors = { + { "", "106e08d9", "0000000000000000" }, + { "61", "a2d0b27c", "071717d2d36b6b11" }, + { "6162", "12d8262a", "62be85b2fe53d1f8" }, + { "616263", "1c94221b", "9cc9c33498a95efb" }, + { "61626364", "b11ab5f4", "ec1044c45cc5097a" }, + { "6162636465", "1b897edd", "1182974836d6dbb7" }, + { "616263646566", "6f7fdafc", "b78e3425fc996779" }, + { "61626364656667", "eb595499", "241aa52b0a62005d" }, + { "6162636465666768", "c70d55dd", "afdb0257ff41aa98" }, + { "616263646566676869", "db106fbe", "c9b9d84356146ac2" }, + { "68656c6c6f", "7f1ddbbd", "1e68d17c457bf117" }, + { "726573756d65", "e9bd9132", "9af1db2d8aa0f1b0" }, + { "f09f9a80", "2d67d1c1", "1670199edc5ecaa3" }, + { "610062", "fed14e49", "f24435ae2d6f1cac" }, + { "80ff007f", "fcb12a3c", "da44aab3968cfbbe" }, + { "70726f64756365722d707265666978", "15dc366d", "4f45737d1188fc48" } + }; + for (String[] vector : vectors) { + byte[] input = hex(vector[0]); + Assert.assertEquals(vector[0], Integer.parseUnsignedInt(vector[1], 16), KeyHash.murmur32(input)); + Assert.assertEquals(vector[0], Long.parseUnsignedLong(vector[2], 16), KeyHash.murmur64(input)); + } + } + + @Test + public void stringKeysUseUtf8AndNetworkByteOrder() { + Assert.assertArrayEquals(hex("9af1db2d8aa0f1b0"), KeyHash.boundKey("resume")); + Assert.assertArrayEquals(hex("1670199edc5ecaa3"), KeyHash.boundKey("\uD83D\uDE80")); + Assert.assertArrayEquals(hex("f24435ae2d6f1cac"), KeyHash.boundKey("a\0b")); + Assert.assertArrayEquals(new byte[8], KeyHash.boundKey("")); + Assert.assertEquals(0x7ed14e49, KeyHash.kafkaHash("a\0b")); + } + + @Test + public void kafkaRoutingSortsPartitionIdsAndMasksSignBit() { + Topology topology = fixed(RoutingMode.HASH, plain(90), plain(2), plain(30)); + Route route = topology.route("a", null); + Assert.assertEquals(30, route.getPartitionId()); + Assert.assertNull(route.getPartitionKey()); + Assert.assertEquals(2, topology.route("", null).getPartitionId()); + Assert.assertEquals(2, topology.route("abc", null).getPartitionId()); + Assert.assertEquals(90, topology.route("resume-key", null).getPartitionId()); + Assert.assertThrows(IllegalArgumentException.class, () -> topology.route("a", 2L)); + Assert.assertThrows(NullPointerException.class, () -> topology.route(null, null)); + } + + @Test + public void boundRoutingUsesUnsignedInclusiveLowerExclusiveUpper() { + Topology topology = split(); + Assert.assertEquals(1, topology.routeBound(hex("7fffffffffffffff"))); + Assert.assertEquals(2, topology.routeBound(hex("8000000000000000"))); + Assert.assertEquals(2, topology.routeBound(hex("ffffffffffffffff"))); + } + + @Test + public void boundRoutesStringKeysBelowAndAtTheSplitBoundary() { + String boundary = "9af1db2d8aa0f1b0"; + Topology topology = fixed(RoutingMode.BOUND, bounded(1, "", boundary), bounded(2, boundary, "")); + Route lower = topology.route("a", null); + Route upper = topology.route("resume", null); + Route empty = topology.route("", null); + + Assert.assertEquals(1, lower.getPartitionId()); + Assert.assertArrayEquals(hex("071717d2d36b6b11"), lower.getPartitionKey()); + Assert.assertEquals(2, upper.getPartitionId()); + Assert.assertArrayEquals(hex(boundary), upper.getPartitionKey()); + Assert.assertEquals(1, empty.getPartitionId()); + Assert.assertArrayEquals(hex("0000000000000000"), empty.getPartitionKey()); + Assert.assertThrows(NullPointerException.class, () -> topology.route(null, null)); + Assert.assertThrows(IllegalArgumentException.class, () -> topology.route("a", 2L)); + } + + @Test + public void explicitRefreshIgnoresRangeChanges() { + Topology previous = fixed(RoutingMode.EXPLICIT, bounded(7, "", "")); + + for (PartitionInfo row : Arrays.asList(plain(7), bounded(7, "80", ""), bounded(7, "", ""))) { + Topology updated = Topology.refresh(previous, Collections.singletonList(row), + RoutingMode.EXPLICIT, AutoPartitioningStrategy.DISABLED); + + Route route = updated.route(null, 7L); + Assert.assertEquals(7, route.getPartitionId()); + Assert.assertNull(route.getPartitionKey()); + previous = updated; + } + } + + @Test + public void explicitRoutesWithOverlappingChildRanges() { + PartitionInfo parent = node(0, false, "", "", longs(), longs(1, 2)); + PartitionInfo left = node(1, true, "", "c0", longs(0), longs()); + PartitionInfo right = node(2, true, "80", "", longs(0), longs()); + + Topology topology = fixed(RoutingMode.EXPLICIT, parent, left, right); + + Assert.assertEquals(1, topology.route(null, 1L).getPartitionId()); + Assert.assertEquals(2, topology.route(null, 2L).getPartitionId()); + } + + @Test + public void autoUsesTopicStrategyAndExplicitRanges() { + PartitionInfo unranged = plain(0); + Assert.assertNull(fixed(RoutingMode.AUTO, unranged).route("resume", null).getPartitionKey()); + Assert.assertArrayEquals(hex("9af1db2d8aa0f1b0"), + fixed(RoutingMode.AUTO, bounded(0, "", "")).route("resume", null).getPartitionKey()); + for (AutoPartitioningStrategy strategy : Arrays.asList(AutoPartitioningStrategy.SCALE_UP, + AutoPartitioningStrategy.SCALE_UP_AND_DOWN, AutoPartitioningStrategy.PAUSED)) { + Topology initial = new Topology(Collections.singletonList(unranged), RoutingMode.AUTO, strategy); + Route route = initial.route("resume", null); + Assert.assertEquals(strategy.name(), 0, route.getPartitionId()); + Assert.assertArrayEquals(strategy.name(), hex("9af1db2d8aa0f1b0"), route.getPartitionKey()); + } + Assert.assertThrows(IllegalArgumentException.class, + () -> fixed(RoutingMode.HASH, bounded(0, "", ""))); + } + + @Test + public void autoUsesHashForMissingStrategyWithoutRanges() { + Topology topology = new Topology(Arrays.asList(plain(90), plain(2)), RoutingMode.AUTO, null); + + Route route = topology.route("a", null); + Assert.assertEquals(2, route.getPartitionId()); + Assert.assertNull(route.getPartitionKey()); + Assert.assertEquals(90, topology.route("abc", null).getPartitionId()); + } + + @Test + public void autoUsesBoundForMissingStrategyWithRanges() { + Topology topology = new Topology(Arrays.asList(bounded(0, "", "80"), bounded(1, "80", "")), + RoutingMode.AUTO, null); + + Assert.assertEquals(0, topology.route("a", null).getPartitionId()); + Route route = topology.route("resume", null); + Assert.assertEquals(1, route.getPartitionId()); + Assert.assertArrayEquals(hex("9af1db2d8aa0f1b0"), route.getPartitionKey()); + } + + @Test + public void boundRoutesByRangeWhenPartitionIdsAndRowsAreOutOfOrder() { + PartitionInfo root = node(0, false, "", "", longs(), longs(2, 90)); + PartitionInfo left = node(90, true, "", "80", longs(0), longs()); + PartitionInfo right = node(2, true, "80", "", longs(0), longs()); + List rows = Arrays.asList(right, root, left); + Topology topology = new Topology(rows, RoutingMode.BOUND, AutoPartitioningStrategy.DISABLED); + + Assert.assertEquals(90, topology.routeBound(hex("7fffffffffffffff"))); + Assert.assertEquals(2, topology.routeBound(hex("8000000000000000"))); + } + + @Test + public void autoRoutesBeforeAndAfterTheFirstSplitWithOrWithoutRootBounds() { + Topology initial = auto(plain(0)); + Topology describedWithRange = auto(bounded(0, "", "")); + Topology refreshedWithRange = Topology.refresh(initial, Collections.singletonList(bounded(0, "", "")), + RoutingMode.AUTO, AutoPartitioningStrategy.SCALE_UP); + Topology refreshedWithoutRange = Topology.refresh(describedWithRange, Collections.singletonList(plain(0)), + RoutingMode.AUTO, null); + for (Topology whole : Arrays.asList(initial, describedWithRange, refreshedWithRange, refreshedWithoutRange)) { + Route route = whole.route("resume", null); + Assert.assertEquals(0, route.getPartitionId()); + Assert.assertArrayEquals(hex("9af1db2d8aa0f1b0"), route.getPartitionKey()); + } + PartitionInfo left = node(1, true, "", "8000000000000000", longs(0), longs()); + PartitionInfo right = node(2, true, "8000000000000000", "", longs(0), longs()); + for (PartitionInfo root : Arrays.asList(node(0, false, null, null, longs(), longs(1, 2)), + node(0, false, "", "", longs(), longs(1, 2)))) { + Route before = initial.route("resume", null); + Topology successor = Topology.refresh(initial, Arrays.asList(root, left, right), + RoutingMode.AUTO, null); + Route after = successor.route("resume", null); + + Assert.assertEquals(0, before.getPartitionId()); + Assert.assertEquals(2, after.getPartitionId()); + Assert.assertArrayEquals(before.getPartitionKey(), after.getPartitionKey()); + Assert.assertEquals(1, successor.route("a", null).getPartitionId()); + } + } + + @Test + public void boundRequiresRangesWithMultipleRows() { + PartitionInfo root = node(0, false, null, null, longs(), longs(1, 2)); + PartitionInfo left = node(1, true, "", "80", longs(0), longs()); + assertPermanent(() -> auto( + root, left, node(2, true, null, null, longs(0), longs()))); + assertPermanent(() -> auto(plain(0), plain(1))); + assertPermanent(() -> fixed(RoutingMode.BOUND, root, plain(1))); + } + + @Test + public void explicitPartitionDoesNotGuessChildAfterSplit() { + Topology previous = fixed(RoutingMode.EXPLICIT, plain(0)); + Assert.assertEquals(0, previous.route("", 0L).getPartitionId()); + Topology topology = Topology.refresh(previous, Arrays.asList(splitRows()), RoutingMode.EXPLICIT, + AutoPartitioningStrategy.SCALE_UP); + Route route = topology.route("", 2L); + Assert.assertEquals(2, route.getPartitionId()); + Assert.assertNull(route.getPartitionKey()); + Assert.assertThrows(IllegalArgumentException.class, () -> topology.route("", 0L)); + Assert.assertThrows(IllegalArgumentException.class, () -> topology.route("", 3L)); + Assert.assertThrows(IllegalArgumentException.class, () -> topology.route("", null)); + } + + @Test + public void rejectsGapsAndMissingEndpointsAsIncompleteAtStartup() { + Assert.assertThrows(IncompleteTopologyException.class, + () -> auto(bounded(0, "", "40"), bounded(1, "80", ""))); + Assert.assertThrows(IncompleteTopologyException.class, () -> auto(bounded(0, "01", ""))); + Assert.assertThrows(IncompleteTopologyException.class, () -> auto(bounded(0, "", "ff"))); + } + + @Test + public void rejectsOverlapsAndInvalidRangesAsMalformed() { + assertInvalid(bounded(0, "", "c0"), bounded(1, "80", "")); + assertInvalid(bounded(0, "", ""), bounded(1, "80", "")); + assertInvalid(bounded(0, "", "80"), bounded(1, "80", "80"), bounded(2, "80", "")); + assertInvalid(bounded(0, "80", "40")); + } + + @Test + public void boundRefreshRejectsOverlapAsMalformed() { + Topology previous = fixed(RoutingMode.BOUND, bounded(0, "", "")); + + assertPermanent(() -> refreshBound(previous, bounded(1, "", "80"), bounded(2, "40", ""))); + } + + @Test + public void autoRejectsMixedRangedAndUnrangedActivePartitions() { + PartitionInfo left = bounded(0, "", "80"); + PartitionInfo right = plain(1); + for (List rows : Arrays.asList(Arrays.asList(left, right), Arrays.asList(right, left))) { + assertPermanent(() -> new Topology(rows, RoutingMode.AUTO, null)); + } + } + + @Test + public void rejectsDuplicateAndNegativePartitionIds() { + assertInvalid(plain(0), plain(0)); + assertInvalid(plain(-1)); + } + + @Test + public void bootstrapsWithDanglingHistoricalParent() { + PartitionInfo left = node(1, true, "", "80", longs(10), longs()); + PartitionInfo right = node(2, true, "80", "", longs(20), longs()); + + Topology topology = fixed(RoutingMode.BOUND, right, left); + + Assert.assertEquals(1, topology.routeBound(hex("7f"))); + Assert.assertEquals(2, topology.routeBound(hex("80"))); + } + + @Test + public void onlyRequiresCoverageOfAParentWhenItWasPreviouslyActive() { + PartitionInfo parent = node(0, false, "", "", longs(), longs(1)); + PartitionInfo left = node(1, true, "", "80", longs(0), longs()); + PartitionInfo right = bounded(2, "80", ""); + Topology initial = fixed(RoutingMode.BOUND, parent, left, right); + Assert.assertEquals(1, initial.routeBound(hex("7f"))); + Assert.assertEquals(2, initial.routeBound(hex("80"))); + + Topology previous = fixed(RoutingMode.BOUND, bounded(0, "", "")); + Assert.assertThrows(IncompleteTopologyException.class, () -> refreshBound(previous, parent, left, right)); + Assert.assertEquals(0, previous.routeBound(hex("80"))); + } + + @Test + public void rejectsChangedHashPartitionSetAndAlgorithm() { + Topology original = fixed(RoutingMode.HASH, plain(0), plain(1)); + assertIncompatible(() -> Topology.refresh(original, Arrays.asList(plain(0), plain(1), plain(2)), + RoutingMode.HASH, AutoPartitioningStrategy.DISABLED)); + Topology hash = fixed(RoutingMode.HASH, plain(0)); + assertIncompatible(() -> refreshBound(hash, bounded(0, "", ""))); + } + + @Test + public void hashRefreshRejectsReplacementWithSameActiveCount() { + Topology previous = fixed(RoutingMode.HASH, plain(0)); + + assertIncompatible(() -> Topology.refresh(previous, Collections.singletonList(plain(1)), RoutingMode.HASH, + AutoPartitioningStrategy.DISABLED)); + } + + @Test + public void hashRefreshKeepsRoutesWhenHistoricalRangeAppears() { + PartitionInfo parent = node(0, false, null, null, longs(), longs(1, 2)); + PartitionInfo left = node(1, true, null, null, longs(0), longs()); + PartitionInfo right = node(2, true, null, null, longs(0), longs()); + Topology previous = fixed(RoutingMode.HASH, parent, left, right); + PartitionInfo parentWithRange = node(0, false, "", "", longs(), longs(1, 2)); + + Topology updated = Topology.refresh(previous, Arrays.asList(right, parentWithRange, left), + RoutingMode.HASH, AutoPartitioningStrategy.DISABLED); + + Assert.assertEquals(1, updated.route("a", null).getPartitionId()); + Assert.assertEquals(2, updated.route("abc", null).getPartitionId()); + } + + @Test + public void refreshesSplitWhenOnlyChildrenNameTheMissingParent() { + Topology original = auto(plain(0)); + PartitionInfo right = node(2, true, "80", "", longs(0), longs()); + Topology direct = refreshBound(original, right, node(1, true, "", "80", longs(0), longs())); + Assert.assertEquals(1, direct.routeBound(hex("7f"))); + Assert.assertEquals(2, direct.routeBound(hex("80"))); + } + + @Test + public void prunesHistoricalParentWithoutChangingActiveRoutes() { + Topology previous = split(); + for (List parents : Arrays.asList(longs(0), longs())) { + Topology pruned = refreshBound(previous, + node(1, true, "", "8000000000000000", parents, longs()), + node(2, true, "8000000000000000", "", parents, longs())); + + for (String key : Arrays.asList("a", "resume")) { + Route before = previous.route(key, null); + Route after = pruned.route(key, null); + Assert.assertEquals(before.getPartitionId(), after.getPartitionId()); + Assert.assertArrayEquals(before.getPartitionKey(), after.getPartitionKey()); + } + } + } + + @Test + public void boundRoutesWithoutAnAnnouncedHistoricalChild() { + PartitionInfo left = node(1, true, "", "80", longs(0), longs()); + PartitionInfo right = bounded(2, "80", ""); + PartitionInfo oldParent = node(0, false, "", "", longs(), longs(1, 9)); + Topology previous = fixed(RoutingMode.BOUND, left, right); + + Topology initial = fixed(RoutingMode.BOUND, oldParent, left, right); + Topology refreshed = refreshBound(previous, oldParent, left, right); + + for (Topology topology : Arrays.asList(initial, refreshed)) { + Assert.assertEquals(1, topology.routeBound(hex("7f"))); + Assert.assertEquals(2, topology.routeBound(hex("80"))); + } + } + + @Test + public void simultaneousSplitsRequireEachChildToMatchItsParentRange() { + Topology previous = fixed(RoutingMode.BOUND, bounded(0, "", "80"), bounded(1, "80", "")); + PartitionInfo first = node(2, true, "", "40", longs(0), longs()); + PartitionInfo second = node(3, true, "40", "80", longs(0), longs()); + PartitionInfo third = node(4, true, "80", "c0", longs(1), longs()); + PartitionInfo fourth = node(5, true, "c0", "", longs(1), longs()); + Topology updated = refreshBound(previous, fourth, second, first, third); + + Assert.assertEquals(2, updated.routeBound(hex("3f"))); + Assert.assertEquals(3, updated.routeBound(hex("40"))); + Assert.assertEquals(4, updated.routeBound(hex("80"))); + Assert.assertEquals(5, updated.routeBound(hex("c0"))); + + assertIncompatible(() -> refreshBound(previous, first, node(3, true, "40", "80", longs(1), longs()), + node(4, true, "80", "c0", longs(0), longs()), fourth)); + } + + @Test + public void rejectsMissingExplicitDestinationWithoutGuessingAReplacement() { + Topology original = fixed(RoutingMode.EXPLICIT, plain(0)); + PartitionInfo replacement = node(1, true, null, null, longs(0), longs()); + Assert.assertThrows(IncompleteTopologyException.class, () -> Topology.refresh(original, + Collections.singletonList(replacement), RoutingMode.EXPLICIT, AutoPartitioningStrategy.DISABLED)); + Assert.assertEquals(0, original.route("", 0L).getPartitionId()); + } + + @Test + public void refreshWaitsForActiveRangesWithoutRelyingOnAnnouncements() { + Topology previous = fixed(RoutingMode.BOUND, bounded(0, "", "")); + PartitionInfo root = node(0, false, "", "", longs(), longs()); + PartitionInfo left = node(1, true, "", "80", longs(0), longs()); + PartitionInfo right = node(2, true, "80", "", longs(0), longs()); + + Topology complete = refreshBound(previous, right, root, left); + Assert.assertEquals(1, complete.routeBound(hex("7f"))); + Assert.assertEquals(2, complete.routeBound(hex("80"))); + Assert.assertThrows(IncompleteTopologyException.class, () -> refreshBound(previous, root, right)); + Assert.assertThrows(IncompleteTopologyException.class, () -> refreshBound(previous, root)); + Assert.assertEquals(0, previous.routeBound(hex("80"))); + } + + @Test + public void validButIncompatibleSnapshotsAreDistinguishableFromMalformedSnapshots() { + Topology previous = fixed(RoutingMode.HASH, plain(0)); + PartitionInfo left = bounded(0, "", "80"); + PartitionInfo right = bounded(1, "80", ""); + Assert.assertEquals(1, fixed(RoutingMode.AUTO, left, right).routeBound(hex("80"))); + assertIncompatible(() -> Topology.refresh(previous, Arrays.asList(left, right), RoutingMode.AUTO, null)); + assertPermanent(() -> Topology.refresh(previous, Arrays.asList(left, plain(1)), RoutingMode.AUTO, null)); + Assert.assertEquals(0, previous.route("key", null).getPartitionId()); + } + + @Test + public void boundUsesWholeRangeForASingleRowWithoutBounds() { + PartitionInfo singleton = node(7, true, null, null, longs(0), longs()); + Topology before = fixed(RoutingMode.BOUND, bounded(7, "", "")); + + Topology initial = fixed(RoutingMode.BOUND, singleton); + Topology updated = refreshBound(before, singleton); + + for (Topology topology : Arrays.asList(initial, updated)) { + Assert.assertEquals(7, topology.routeBound(hex("00"))); + Assert.assertEquals(7, topology.routeBound(hex("ff"))); + } + } + + @Test + public void acceptsEachDirectSplitInSequence() { + Topology original = fixed(RoutingMode.BOUND, plain(0)); + Topology split = refreshBound(original, splitRows()); + + Topology next = refreshBound(split, cascadeRows()); + + Assert.assertEquals(0, original.routeBound(hex("3f"))); + Assert.assertEquals(1, split.routeBound(hex("3f"))); + Assert.assertEquals(3, next.routeBound(hex("3f"))); + Assert.assertEquals(4, next.routeBound(hex("4000000000000000"))); + Assert.assertEquals(2, next.routeBound(hex("8000000000000000"))); + } + + @Test + public void acceptsCascadedSplitWithoutIntermediateSnapshot() { + Topology original = fixed(RoutingMode.BOUND, plain(0)); + + Topology updated = refreshBound(original, cascadeRows()); + + Assert.assertEquals(3, updated.routeBound(hex("3f"))); + Assert.assertEquals(4, updated.routeBound(hex("4000000000000000"))); + Assert.assertEquals(2, updated.routeBound(hex("8000000000000000"))); + } + + @Test + public void rejectsCascadeWhenAnIntermediateParentLinkIsMissing() { + Topology original = fixed(RoutingMode.BOUND, plain(0)); + PartitionInfo[] rows = cascadeRows(); + rows[1] = node(1, false, "", "8000000000000000", longs(), longs(3, 4)); + + Assert.assertThrows(IncompleteTopologyException.class, () -> refreshBound(original, rows)); + Assert.assertEquals(0, original.routeBound(hex("40"))); + } + + @Test + public void rejectsCyclesAndMergesInSplitParentChain() { + Topology original = fixed(RoutingMode.BOUND, plain(0)); + + for (List parents : Arrays.asList(longs(3), longs(0, 9))) { + PartitionInfo[] rows = cascadeRows(); + rows[1] = node(1, false, "", "8000000000000000", parents, longs(3, 4)); + + assertIncompatible(() -> refreshBound(original, rows)); + } + } + + @Test + public void splitRoutesWhenTheRetiredParentHasNoBoundsOrChildLinks() { + PartitionInfo retained = bounded(9, "80", ""); + Topology before = fixed(RoutingMode.BOUND, bounded(0, "", "80"), retained); + PartitionInfo retiring = node(0, false, null, null, longs(), longs()); + PartitionInfo left = node(1, true, "", "40", longs(0), longs()); + PartitionInfo right = node(2, true, "40", "80", longs(0), longs()); + + Topology updated = refreshBound(before, retiring, right, retained, left); + + Assert.assertEquals(1, updated.routeBound(hex("3f"))); + Assert.assertEquals(2, updated.routeBound(hex("40"))); + Assert.assertEquals(9, updated.routeBound(hex("80"))); + } + + @Test + public void unrelatedRouteCannotFillAGapBetweenDirectChildren() { + Topology before = fixed(RoutingMode.BOUND, plain(0)); + PartitionInfo left = node(1, true, "", "40", longs(0), longs()); + PartitionInfo middle = bounded(2, "40", "80"); + PartitionInfo right = node(3, true, "80", "", longs(0), longs()); + + Assert.assertThrows(IncompleteTopologyException.class, () -> refreshBound(before, right, middle, left)); + } + + @Test + public void refreshDoesNotRecoverMissingRangesFromPreviousRows() { + PartitionInfo left = bounded(1, "", "80"); + Topology before = fixed(RoutingMode.BOUND, left, bounded(2, "80", "")); + + assertPermanent(() -> refreshBound(before, left, plain(2))); + } + + @Test + public void boundRefreshRejectsMergingTwoActivePartitions() { + Topology before = fixed(RoutingMode.BOUND, bounded(1, "", "80"), bounded(2, "80", "")); + PartitionInfo child = node(3, true, "", "", longs(1, 2), longs()); + + assertIncompatible(() -> refreshBound(before, child)); + } + + @Test + public void splitRefreshRejectsAnActivePartitionWithMultipleParents() { + PartitionInfo retained = node(9, true, "80", "", longs(7, 8), longs()); + Topology before = fixed(RoutingMode.BOUND, bounded(0, "", "80"), retained); + PartitionInfo left = node(1, true, "", "40", longs(0), longs()); + PartitionInfo right = node(2, true, "40", "80", longs(0), longs()); + + assertIncompatible(() -> refreshBound(before, left, right, retained)); + } + + private static Topology split() { + return fixed(RoutingMode.BOUND, splitRows()); + } + + private static PartitionInfo[] splitRows() { + return new PartitionInfo[] { + node(0, false, "", "", longs(), longs(1, 2)), + node(1, true, "", "8000000000000000", longs(0), longs()), + node(2, true, "8000000000000000", "", longs(0), longs()) + }; + } + + private static PartitionInfo[] cascadeRows() { + return new PartitionInfo[] { + node(0, false, "", "", longs(), longs(1, 2)), + node(1, false, "", "8000000000000000", longs(0), longs(3, 4)), + node(2, true, "8000000000000000", "", longs(0), longs()), + node(3, true, "", "4000000000000000", longs(1), longs()), + node(4, true, "4000000000000000", "8000000000000000", longs(1), longs()) + }; + } + + private static void assertInvalid(PartitionInfo... partitions) { + assertPermanent(() -> fixed(RoutingMode.AUTO, partitions)); + } + + private static void assertPermanent(ThrowingRunnable action) { + Assert.assertEquals(IllegalArgumentException.class, + Assert.assertThrows(IllegalArgumentException.class, action).getClass()); + } + + private static void assertIncompatible(ThrowingRunnable action) { + Assert.assertThrows(Topology.IncompatibleTransformationException.class, action); + } + + private static Topology refreshBound(Topology previous, PartitionInfo... partitions) { + return Topology.refresh(previous, Arrays.asList(partitions), RoutingMode.BOUND, + AutoPartitioningStrategy.DISABLED); + } + + private static Topology fixed(RoutingMode mode, PartitionInfo... partitions) { + return new Topology(Arrays.asList(partitions), mode, AutoPartitioningStrategy.DISABLED); + } + + private static Topology auto(PartitionInfo... partitions) { + return new Topology(Arrays.asList(partitions), RoutingMode.AUTO, AutoPartitioningStrategy.SCALE_UP); + } + + private static PartitionInfo plain(long id) { + return node(id, true, null, null, longs(), longs()); + } + + private static PartitionInfo bounded(long id, String from, String to) { + return node(id, true, from, to, longs(), longs()); + } + + private static PartitionInfo node(long id, boolean active, String from, String to, + List parents, List children) { + YdbTopic.DescribeTopicResult.PartitionInfo.Builder info = YdbTopic.DescribeTopicResult.PartitionInfo + .newBuilder() + .setPartitionId(id).setActive(active) + .addAllParentPartitionIds(parents).addAllChildPartitionIds(children); + if (from != null) { + info.setKeyRange(YdbTopic.PartitionKeyRange.newBuilder() + .setFromBound(ByteString.copyFrom(hex(from))).setToBound(ByteString.copyFrom(hex(to)))); + } + return new PartitionInfo(info.build()); + } + + private static List longs(long... ids) { + List result = new ArrayList<>(); + for (long id : ids) { + result.add(id); + } + return result; + } + + private static byte[] hex(String value) { + byte[] bytes = new byte[value.length() / 2]; + for (int index = 0; index < bytes.length; index++) { + bytes[index] = (byte) Integer.parseInt(value.substring(index * 2, index * 2 + 2), 16); + } + return bytes; + } +} diff --git a/topic/src/test/java/tech/ydb/topic/write/impl/multi/TopologyLoaderTest.java b/topic/src/test/java/tech/ydb/topic/write/impl/multi/TopologyLoaderTest.java new file mode 100644 index 000000000..2598d05d7 --- /dev/null +++ b/topic/src/test/java/tech/ydb/topic/write/impl/multi/TopologyLoaderTest.java @@ -0,0 +1,176 @@ +package tech.ydb.topic.write.impl.multi; + +import java.util.ArrayDeque; +import java.util.Deque; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionException; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; + +import com.google.protobuf.ByteString; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mockito; + +import tech.ydb.core.Result; +import tech.ydb.proto.topic.YdbTopic; +import tech.ydb.topic.TopicRpc; +import tech.ydb.topic.impl.TopicClientImpl; + +public class TopologyLoaderTest { + private static final String TOPIC_PATH = "/topic"; + + private final TopicRpc rpc = Mockito.mock(TopicRpc.class); + private final ScheduledExecutorService scheduler = Mockito.mock(ScheduledExecutorService.class); + private final TopologyLoader loader = + new TopologyLoader(TopicClientImpl.newClient(rpc).build(), TOPIC_PATH, scheduler); + private final Deque snapshots = new ArrayDeque<>(); + private final Deque retries = new ArrayDeque<>(); + + @Before + public void setUp() { + Mockito.when(rpc.describeTopic( + Mockito.argThat(request -> TOPIC_PATH.equals(request.getPath())), Mockito.any())).thenAnswer(call -> + CompletableFuture.completedFuture(Result.success(snapshots.removeFirst()))); + Mockito.when(scheduler.schedule(Mockito.any(Runnable.class), Mockito.anyLong(), Mockito.any(TimeUnit.class))) + .thenAnswer(call -> { + retries.addLast(call.getArgument(0)); + return null; + }); + } + + @Test + public void startsAfterEmptySnapshotAndIncompleteKeySpace() { + YdbTopic.DescribeTopicResult.PartitionInfo left = partition(1, "", "m"); + YdbTopic.DescribeTopicResult.PartitionInfo right = partition(2, "m", ""); + snapshots.add(snapshot()); + snapshots.add(snapshot(right)); + snapshots.add(snapshot(left, right)); + + CompletableFuture loaded = loader.load(RoutingMode.AUTO, null); + Assert.assertFalse(loaded.isDone()); + retries.removeFirst().run(); + Assert.assertFalse(loaded.isDone()); + retries.removeFirst().run(); + + Assert.assertTrue(loaded.isDone()); + Assert.assertEquals(1, loaded.join().route("a", null).getPartitionId()); + Assert.assertEquals(2, loaded.join().route("resume", null).getPartitionId()); + } + + @Test + public void startsWithBoundRoutingWhenTheAutoSplittingTopicHasNoInitialRange() { + snapshots.add(snapshot(YdbTopic.DescribeTopicResult.PartitionInfo.newBuilder() + .setPartitionId(0).setActive(true).build())); + + Topology.Route route = loader.load(RoutingMode.AUTO, null).join().route("resume", null); + + Assert.assertEquals(0, route.getPartitionId()); + Assert.assertNotNull(route.getPartitionKey()); + } + + @Test + public void routesToTheRequestedPartitionWhenExplicitRoutingIsSelected() { + snapshots.add(snapshot(partition(0, "", "m"), partition(1, "m", ""))); + + Topology.Route route = loader.load(RoutingMode.EXPLICIT, null).join().route("a", 1L); + + Assert.assertEquals(1, route.getPartitionId()); + Assert.assertNull(route.getPartitionKey()); + } + + @Test + public void waitsForParentLinksBeforeRoutingToSplitChildren() { + snapshots.add(snapshot(partition(0, "", ""))); + CompletableFuture started = loader.load(RoutingMode.AUTO, null); + Assert.assertTrue(started.isDone()); + Topology previous = started.join(); + YdbTopic.DescribeTopicResult.PartitionInfo left = partition(1, "", "m"); + YdbTopic.DescribeTopicResult.PartitionInfo right = partition(2, "m", ""); + snapshots.add(snapshot(left, right)); + snapshots.add(snapshot(left.toBuilder().addParentPartitionIds(0).build(), + right.toBuilder().addParentPartitionIds(0).build())); + + CompletableFuture loaded = loader.load(RoutingMode.AUTO, previous); + + Assert.assertFalse(loaded.isDone()); + Assert.assertEquals(0, previous.route("a", null).getPartitionId()); + retries.removeFirst().run(); + Assert.assertTrue(loaded.isDone()); + Assert.assertEquals(1, loaded.join().route("a", null).getPartitionId()); + Assert.assertEquals(2, loaded.join().route("resume", null).getPartitionId()); + } + + @Test + public void givesUpAfterFourIncompleteDescriptions() { + for (int attempt = 0; attempt < 4; attempt++) { + snapshots.add(snapshot()); + } + + CompletableFuture loaded = loader.load(RoutingMode.AUTO, null); + for (int attempt = 0; attempt < 3; attempt++) { + Assert.assertFalse(loaded.isDone()); + retries.removeFirst().run(); + } + + Assert.assertTrue(loaded.isCompletedExceptionally()); + Assert.assertTrue(Assert.assertThrows(CompletionException.class, loaded::join).getCause() + instanceof IncompleteTopologyException); + runPendingRetries(); + Mockito.verify(rpc, Mockito.times(4)).describeTopic(Mockito.any(), Mockito.any()); + } + + @Test + public void doesNotRetryOverlappingRanges() { + snapshots.add(snapshot(partition(1, "", "z"), partition(2, "m", ""))); + + CompletableFuture loaded = loader.load(RoutingMode.AUTO, null); + + Assert.assertTrue(loaded.isCompletedExceptionally()); + Assert.assertEquals(IllegalArgumentException.class, + Assert.assertThrows(CompletionException.class, loaded::join).getCause().getClass()); + runPendingRetries(); + Mockito.verify(rpc).describeTopic(Mockito.any(), Mockito.any()); + } + + @Test + public void cancellationPreventsTheNextDescribe() { + snapshots.add(snapshot()); + snapshots.add(snapshot(partition(0, "", ""))); + + CompletableFuture loaded = loader.load(RoutingMode.AUTO, null); + loaded.cancel(false); + retries.removeFirst().run(); + + Assert.assertTrue(loaded.isCancelled()); + Assert.assertEquals(1, snapshots.size()); + } + + private void runPendingRetries() { + while (!retries.isEmpty()) { + retries.removeFirst().run(); + } + } + + private static YdbTopic.DescribeTopicResult snapshot(YdbTopic.DescribeTopicResult.PartitionInfo... partitions) { + YdbTopic.DescribeTopicResult.Builder result = YdbTopic.DescribeTopicResult.newBuilder() + .setPartitioningSettings(YdbTopic.PartitioningSettings.newBuilder() + .setAutoPartitioningSettings(YdbTopic.AutoPartitioningSettings.newBuilder() + .setStrategy(YdbTopic.AutoPartitioningStrategy.AUTO_PARTITIONING_STRATEGY_SCALE_UP))); + for (YdbTopic.DescribeTopicResult.PartitionInfo partition : partitions) { + result.addPartitions(partition); + } + return result.build(); + } + + private static YdbTopic.DescribeTopicResult.PartitionInfo partition(long id, String from, String to) { + return YdbTopic.DescribeTopicResult.PartitionInfo.newBuilder() + .setPartitionId(id) + .setActive(true) + .setKeyRange(YdbTopic.PartitionKeyRange.newBuilder() + .setFromBound(ByteString.copyFromUtf8(from)) + .setToBound(ByteString.copyFromUtf8(to))) + .build(); + } +}