diff --git a/docs/services/dynamodb.md b/docs/services/dynamodb.md index 0cb06bffac..1bca6bae3d 100644 --- a/docs/services/dynamodb.md +++ b/docs/services/dynamodb.md @@ -180,9 +180,11 @@ Disabling a stream closes its open shards, each with an `EndingSequenceNumber`, stays readable. A `GetRecords` call that reaches the end of a closed shard returns no `NextShardIterator`. `GetShardIterator` for a shard the stream does not have answers `ResourceNotFoundException`. The 1,000-record limit is for the whole stream: the oldest record goes -first, whichever shard holds it. A closed shard that holds no records is dropped once the shard that -replaced it has closed too, so a stream that rolls over lists at most two generations of shards while -idle, and otherwise only the shards that still hold records. +first, whichever shard holds it. AWS has no such limit, so if a consumer can fall more than 1,000 +records behind, for example one that starts at `LATEST` before a large seed, raise it with +`FLOCI_SERVICES_DYNAMODB_STREAM_MAX_RECORDS`. A closed shard that holds no records is dropped once +the shard that replaced it has closed too, so a stream that rolls over lists at most two generations +of shards while idle, and otherwise only the shards that still hold records. ## Time to Live @@ -315,6 +317,7 @@ region is rejected. | `FLOCI_SERVICES_DYNAMODB_STREAM_SHARD_ROLLOVER_SECONDS` | `0` | Seconds a stream shard stays open before a child shard takes its keys. `0` keeps shards open | | `FLOCI_SERVICES_DYNAMODB_STREAM_ITERATOR_EXPIRY_ENABLED` | `false` | Expire stream shard iterators 15 minutes after they are returned, as AWS does | | `FLOCI_SERVICES_DYNAMODB_STREAM_RETENTION_ENABLED` | `false` | Keep stream records, and shards once closed, for 24 hours, as AWS does | +| `FLOCI_SERVICES_DYNAMODB_STREAM_MAX_RECORDS` | `1000` | Most records each stream keeps across its shards; the oldest goes first. Must be at least `1` | | `FLOCI_SERVICES_DYNAMODB_BACKEND` | `native` | Engine behind the DynamoDB API: `native` or `local`, case-insensitive. Any other value fails startup. See [DynamoDB Local backend](#dynamodb-local-backend) | | `FLOCI_SERVICES_DYNAMODB_LOCAL_ENDPOINT` | *(none)* | Base URL of DynamoDB Local, for example `http://dynamodb-local:8000`. Required when the backend is `local`. Must be `http` or `https` with a host. AWS endpoints (hosts under `amazonaws.com`, `amazonaws.com.cn` or `api.aws`) are rejected | | `FLOCI_SERVICES_DYNAMODB_LOCAL_CONNECT_TIMEOUT_SECONDS` | `2` | Seconds to wait for a connection to DynamoDB Local | diff --git a/src/main/java/io/floci/aws/config/EmulatorConfig.java b/src/main/java/io/floci/aws/config/EmulatorConfig.java index 14bef21494..85c1de2ad5 100644 --- a/src/main/java/io/floci/aws/config/EmulatorConfig.java +++ b/src/main/java/io/floci/aws/config/EmulatorConfig.java @@ -1724,6 +1724,14 @@ public interface EmulatorConfig { @WithDefault("false") boolean streamRetentionEnabled(); + /** + * The most records a DynamoDB stream of the native engine keeps across its shards; the oldest goes first. + * AWS limits a stream by age rather than by count, so raise this when a consumer can fall far behind. + * Env: FLOCI_SERVICES_DYNAMODB_STREAM_MAX_RECORDS + */ + @WithDefault("1000") + int streamMaxRecords(); + /** The engine behind the DynamoDB API: {@code native} or {@code local}. Env: FLOCI_SERVICES_DYNAMODB_BACKEND. */ @WithDefault("native") String backend(); diff --git a/src/main/java/io/floci/aws/services/dynamodb/DynamoDbStreamService.java b/src/main/java/io/floci/aws/services/dynamodb/DynamoDbStreamService.java index 3a65d87318..ae754ad803 100644 --- a/src/main/java/io/floci/aws/services/dynamodb/DynamoDbStreamService.java +++ b/src/main/java/io/floci/aws/services/dynamodb/DynamoDbStreamService.java @@ -25,7 +25,6 @@ import java.time.Duration; import java.time.Instant; import java.time.ZoneOffset; import java.time.format.DateTimeFormatter; -import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Base64; import java.util.List; @@ -41,7 +40,7 @@ public class DynamoDbStreamService { /** The first shard of every stream, which a stream with one shard that never rolls over keeps for good. */ static final String SHARD_ID = shardId(1, 0); - /** The most records a stream keeps across its shards; the oldest goes first. */ + /** The most records a stream keeps across its shards unless configured otherwise; the oldest goes first. */ static final int MAX_RECORDS = 1000; /** How long a shard iterator can be used when iterator expiry is on, as on AWS. */ static final Duration ITERATOR_LIFETIME = Duration.ofMinutes(15); @@ -56,9 +55,11 @@ public class DynamoDbStreamService { /** * How the native engine shapes its streams: the open shards each has, how long a shard stays open before a child - * takes its keys (null for good), and whether iterators expire and records age out as on AWS. + * takes its keys (null for good), whether iterators expire and records age out as on AWS, and how many records a + * stream keeps. */ - record Settings(int shardCount, Duration shardRollover, boolean iteratorExpiry, boolean retention) { + record Settings(int shardCount, Duration shardRollover, boolean iteratorExpiry, boolean retention, + int maxRecords) { static final Settings DEFAULTS = new Settings(1, null, false, false); @@ -69,12 +70,19 @@ public class DynamoDbStreamService { if (shardRollover != null && (shardRollover.isZero() || shardRollover.isNegative())) { shardRollover = null; } + if (maxRecords < 1) { + throw new IllegalArgumentException("A DynamoDB stream keeps at least one record, not " + maxRecords); + } + } + + Settings(int shardCount, Duration shardRollover, boolean iteratorExpiry, boolean retention) { + this(shardCount, shardRollover, iteratorExpiry, retention, MAX_RECORDS); } static Settings from(EmulatorConfig.DynamoDbServiceConfig config) { long rollover = config.streamShardRolloverSeconds(); return new Settings(config.streamShardCount(), rollover > 0 ? Duration.ofSeconds(rollover) : null, - config.streamIteratorExpiryEnabled(), config.streamRetentionEnabled()); + config.streamIteratorExpiryEnabled(), config.streamRetentionEnabled(), config.streamMaxRecords()); } } @@ -277,7 +285,7 @@ public class DynamoDbStreamService { shard.records.addLast(record); shard.lastSequence = record.getSequenceNumber(); state.retained++; - while (state.retained > MAX_RECORDS) { + while (state.retained > settings.maxRecords()) { state.trimOldest(); } } @@ -445,12 +453,12 @@ public class DynamoDbStreamService { if (shard.trimmedThrough != null && requested.compareTo(new BigInteger(shard.trimmedThrough)) <= 0) { throw trimmed(); } - for (DynamoDbStreamRecord record : shard.records) { - if (requested.compareTo(new BigInteger(record.getSequenceNumber())) == 0) { - return; - } + int index = shard.records.firstIndexWhere( + record -> new BigInteger(record.getSequenceNumber()).compareTo(requested) >= 0); + if (index == shard.records.size() + || new BigInteger(shard.records.get(index).getSequenceNumber()).compareTo(requested) != 0) { + throw invalidSequenceNumber(); } - throw invalidSequenceNumber(); } GetRecordsResult getRecords(String shardIterator, Integer limit) { @@ -482,25 +490,36 @@ public class DynamoDbStreamService { throw trimmed(); } } - List held = new ArrayList<>(shard.records); - int position = held.size(); - for (int i = 0; i < held.size(); i++) { - int againstCursor = held.get(i).getSequenceNumber().compareTo(cursor.sequence()); - if (cursor.inclusive() ? againstCursor >= 0 : againstCursor > 0) { - position = i; - break; - } - } - int effectiveLimit = limit != null ? limit : 100; - page = new ArrayList<>(held.subList(position, Math.min(position + effectiveLimit, held.size()))); + page = readFrom(shard.records, cursor, limit != null ? limit : 100); next = page.isEmpty() ? cursor : new Cursor(page.getLast().getSequenceNumber(), false); // A closed shard read to its end has no next iterator, which is how a reader learns it is done. - ended = !shard.open() && position >= held.size(); + ended = !shard.open() && page.isEmpty(); } return new GetRecordsResult(page, ended ? null : encodeIterator(new IteratorToken(iterator.streamArn(), iterator.shardId(), next, now))); } + /** + * Up to {@code limit} of {@code records}, oldest first, from where {@code cursor} reads. Records are kept in + * sequence order, so a binary search finds the first one without walking or copying the shard. + */ + private static List readFrom(RingBuffer records, Cursor cursor, + int limit) { + int from = records.firstIndexWhere(record -> reads(cursor, record)); + int to = from + Math.min(limit, records.size() - from); + List page = new ArrayList<>(to - from); + for (int i = from; i < to; i++) { + page.add(records.get(i)); + } + return page; + } + + /** Whether {@code record} is at or past where {@code cursor} reads from. */ + private static boolean reads(Cursor cursor, DynamoDbStreamRecord record) { + int againstCursor = record.getSequenceNumber().compareTo(cursor.sequence()); + return cursor.inclusive() ? againstCursor >= 0 : againstCursor > 0; + } + /** * Applies the passage of time to a stream: with retention on, records past 24 hours are trimmed and shards closed * longer ago are dropped; with a rollover, each open shard that has been open that long closes and a child takes @@ -621,7 +640,7 @@ public class DynamoDbStreamService { private static final class StreamState { final List shards = new ArrayList<>(); final AtomicLong counter; - /** Records kept across every shard, held to {@link #MAX_RECORDS}. */ + /** Records kept across every shard, held to {@link Settings#maxRecords()}. */ int retained; StreamState(AtomicLong counter) { @@ -686,7 +705,7 @@ public class DynamoDbStreamService { final int slot; final String startingSequenceNumber; final Instant openedAt; - final ArrayDeque records = new ArrayDeque<>(); + final RingBuffer records = new RingBuffer<>(); /** The sequence number of the newest record ever added, or null. */ String lastSequence; /** The sequence number of the newest record trimmed away, or null: a cursor at or before it lost records. */ diff --git a/src/main/java/io/floci/aws/services/dynamodb/RingBuffer.java b/src/main/java/io/floci/aws/services/dynamodb/RingBuffer.java new file mode 100644 index 0000000000..11e11d4ae7 --- /dev/null +++ b/src/main/java/io/floci/aws/services/dynamodb/RingBuffer.java @@ -0,0 +1,127 @@ +package io.floci.aws.services.dynamodb; + +import java.util.Iterator; +import java.util.NoSuchElementException; +import java.util.function.Predicate; + +/** + * A first-in, first-out buffer over a circular array. Adding at the tail and removing from the head take constant + * time, as in {@link java.util.ArrayDeque}, but any element can also be read by its position, so a buffer kept in + * order can be binary searched. Not thread-safe. + */ +final class RingBuffer implements Iterable { + + private static final int INITIAL_CAPACITY = 16; + + private Object[] elements = new Object[INITIAL_CAPACITY]; + /** Where the oldest element sits in {@link #elements}. */ + private int head; + private int size; + + void addLast(T element) { + if (element == null) { + throw new NullPointerException("A ring buffer holds no nulls"); + } + if (size == elements.length) { + grow(); + } + elements[slot(size)] = element; + size++; + } + + T removeFirst() { + T first = getFirst(); + elements[head] = null; + head = head + 1 == elements.length ? 0 : head + 1; + size--; + return first; + } + + T getFirst() { + if (size == 0) { + throw new NoSuchElementException(); + } + return element(head); + } + + T getLast() { + if (size == 0) { + throw new NoSuchElementException(); + } + return element(slot(size - 1)); + } + + /** The element {@code index} places after the oldest. */ + T get(int index) { + if (index < 0 || index >= size) { + throw new IndexOutOfBoundsException("Index " + index + " out of bounds for size " + size); + } + return element(slot(index)); + } + + int size() { + return size; + } + + boolean isEmpty() { + return size == 0; + } + + /** + * The position of the first element {@code reached} accepts, or {@link #size()} when it accepts none. The buffer + * must be ordered for it: once an element is accepted, every newer one is too. + */ + int firstIndexWhere(Predicate reached) { + int low = 0; + int high = size; + while (low < high) { + int middle = (low + high) >>> 1; + if (reached.test(element(slot(middle)))) { + high = middle; + } else { + low = middle + 1; + } + } + return low; + } + + /** Oldest first. The buffer must not change while it is iterated. */ + @Override + public Iterator iterator() { + return new Iterator<>() { + private int next; + + @Override + public boolean hasNext() { + return next < size; + } + + @Override + public T next() { + if (next >= size) { + throw new NoSuchElementException(); + } + return element(slot(next++)); + } + }; + } + + private int slot(int index) { + int slot = head + index; + return slot < elements.length ? slot : slot - elements.length; + } + + private void grow() { + Object[] larger = new Object[elements.length * 2]; + for (int i = 0; i < size; i++) { + larger[i] = elements[slot(i)]; + } + elements = larger; + head = 0; + } + + @SuppressWarnings("unchecked") + private T element(int slot) { + return (T) elements[slot]; + } +} diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index 8e23e8c2f1..6df36a2c61 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -479,6 +479,7 @@ floci: stream-shard-rollover-seconds: 0 # FLOCI_SERVICES_DYNAMODB_STREAM_SHARD_ROLLOVER_SECONDS. 0: shards stay open. stream-iterator-expiry-enabled: false # FLOCI_SERVICES_DYNAMODB_STREAM_ITERATOR_EXPIRY_ENABLED. 15-minute iterators. stream-retention-enabled: false # FLOCI_SERVICES_DYNAMODB_STREAM_RETENTION_ENABLED. 24-hour records and shards. + stream-max-records: 1000 # FLOCI_SERVICES_DYNAMODB_STREAM_MAX_RECORDS. Records kept per stream. backend: native # FLOCI_SERVICES_DYNAMODB_BACKEND: native or local # local-endpoint: http://dynamodb-local:8000 # FLOCI_SERVICES_DYNAMODB_LOCAL_ENDPOINT local-connect-timeout-seconds: 2 # FLOCI_SERVICES_DYNAMODB_LOCAL_CONNECT_TIMEOUT_SECONDS diff --git a/src/test/java/io/floci/aws/services/dynamodb/DynamoDbStreamLifecycleTest.java b/src/test/java/io/floci/aws/services/dynamodb/DynamoDbStreamLifecycleTest.java index 492b28b3e5..40b3a2bc99 100644 --- a/src/test/java/io/floci/aws/services/dynamodb/DynamoDbStreamLifecycleTest.java +++ b/src/test/java/io/floci/aws/services/dynamodb/DynamoDbStreamLifecycleTest.java @@ -345,6 +345,58 @@ class DynamoDbStreamLifecycleTest { "once trimming empties it, the closed shard goes"); } + @Test + void aConfiguredRecordCapReplacesTheDefault() { + DynamoDbStreamService streams = streams(new Settings(1, null, false, false, 1500)); + String streamArn = enable(streams); + String horizon = streams.getShardIterator(streamArn, DynamoDbStreamService.SHARD_ID, "TRIM_HORIZON", null); + + for (int i = 0; i < 1200; i++) { + put(streams, "item-" + i); + } + assertEquals(1200, readAll(streams, streamArn, DynamoDbStreamService.SHARD_ID).size()); + assertEquals(10, streams.getRecords(horizon, 10).records().size(), "nothing was trimmed under the cap"); + + for (int i = 1200; i < 1501; i++) { + put(streams, "item-" + i); + } + List kept = keys(readAll(streams, streamArn, DynamoDbStreamService.SHARD_ID)); + assertEquals(1500, kept.size()); + assertEquals("item-1", kept.getFirst()); + AwsException trimmed = assertThrows(AwsException.class, () -> streams.getRecords(horizon, 10)); + assertEquals("TrimmedDataAccessException", trimmed.getErrorCode()); + } + + @Test + void aPageStartsAtTheCursorWhereverItSitsInTheShard() { + DynamoDbStreamService streams = streams(Settings.DEFAULTS); + String streamArn = enable(streams); + List expected = new ArrayList<>(); + for (int i = 0; i < 40; i++) { + put(streams, "item-" + i); + expected.add("item-" + i); + } + List held = readAll(streams, streamArn, DynamoDbStreamService.SHARD_ID); + assertEquals(expected, keys(held)); + + for (int i = 0; i < held.size(); i++) { + String sequence = held.get(i).getSequenceNumber(); + String at = streams.getShardIterator(streamArn, DynamoDbStreamService.SHARD_ID, "AT_SEQUENCE_NUMBER", + sequence); + assertEquals(expected.subList(i, Math.min(i + 3, expected.size())), + keys(streams.getRecords(at, 3).records()), "at record " + i); + String after = streams.getShardIterator(streamArn, DynamoDbStreamService.SHARD_ID, + "AFTER_SEQUENCE_NUMBER", sequence); + assertEquals(expected.subList(i + 1, Math.min(i + 4, expected.size())), + keys(streams.getRecords(after, 3).records()), "after record " + i); + } + } + + @Test + void aStreamMustKeepAtLeastOneRecord() { + assertThrows(IllegalArgumentException.class, () -> new Settings(1, null, false, false, 0)); + } + @Test void theRecordCapTrimsTheStreamsOldestRecordWhicheverShardHoldsIt() { DynamoDbStreamService streams = streams(new Settings(2, null, false, false)); diff --git a/src/test/java/io/floci/aws/services/dynamodb/RingBufferTest.java b/src/test/java/io/floci/aws/services/dynamodb/RingBufferTest.java new file mode 100644 index 0000000000..cfdd4311d3 --- /dev/null +++ b/src/test/java/io/floci/aws/services/dynamodb/RingBufferTest.java @@ -0,0 +1,151 @@ +package io.floci.aws.services.dynamodb; + +import org.junit.jupiter.api.Test; + +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.List; +import java.util.NoSuchElementException; +import java.util.Random; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class RingBufferTest { + + @Test + void anEmptyBufferHasNothingToGiveBack() { + RingBuffer buffer = new RingBuffer<>(); + + assertTrue(buffer.isEmpty()); + assertEquals(0, buffer.size()); + assertThrows(NoSuchElementException.class, buffer::getFirst); + assertThrows(NoSuchElementException.class, buffer::getLast); + assertThrows(NoSuchElementException.class, buffer::removeFirst); + assertThrows(IndexOutOfBoundsException.class, () -> buffer.get(0)); + assertEquals(0, buffer.firstIndexWhere(element -> true)); + assertFalse(buffer.iterator().hasNext()); + } + + @Test + void elementsLeaveInTheOrderTheyCame() { + RingBuffer buffer = new RingBuffer<>(); + for (int i = 0; i < 5; i++) { + buffer.addLast(i); + } + + assertEquals(0, buffer.getFirst()); + assertEquals(4, buffer.getLast()); + assertEquals(0, buffer.removeFirst()); + assertEquals(1, buffer.removeFirst()); + assertEquals(List.of(2, 3, 4), contents(buffer)); + assertEquals(3, buffer.size()); + } + + @Test + void positionsCountFromTheOldestAcrossTheWrapAround() { + RingBuffer buffer = new RingBuffer<>(); + for (int i = 0; i < 16; i++) { + buffer.addLast(i); + } + for (int i = 0; i < 10; i++) { + buffer.removeFirst(); + } + for (int i = 16; i < 24; i++) { + buffer.addLast(i); + } + + assertEquals(14, buffer.size()); + for (int i = 0; i < buffer.size(); i++) { + assertEquals(10 + i, buffer.get(i)); + } + assertEquals(10, buffer.getFirst()); + assertEquals(23, buffer.getLast()); + assertThrows(IndexOutOfBoundsException.class, () -> buffer.get(14)); + assertThrows(IndexOutOfBoundsException.class, () -> buffer.get(-1)); + } + + @Test + void growingKeepsTheOrderEvenWhenTheElementsHadWrapped() { + RingBuffer buffer = new RingBuffer<>(); + for (int i = 0; i < 12; i++) { + buffer.addLast(i); + } + for (int i = 0; i < 8; i++) { + buffer.removeFirst(); + } + for (int i = 12; i < 100; i++) { + buffer.addLast(i); + } + + List expected = new ArrayList<>(); + for (int i = 8; i < 100; i++) { + expected.add(i); + } + assertEquals(expected, contents(buffer)); + } + + @Test + void aNullIsRefused() { + RingBuffer buffer = new RingBuffer<>(); + + assertThrows(NullPointerException.class, () -> buffer.addLast(null)); + assertTrue(buffer.isEmpty()); + } + + @Test + void theBinarySearchFindsTheFirstElementPastAThreshold() { + RingBuffer buffer = new RingBuffer<>(); + for (int i = 0; i < 40; i++) { + buffer.addLast(i * 2); + } + for (int i = 0; i < 7; i++) { + buffer.removeFirst(); + buffer.addLast(80 + i * 2); + } + + for (int threshold = 0; threshold <= 100; threshold++) { + int bound = threshold; + int expected = 0; + while (expected < buffer.size() && buffer.get(expected) < bound) { + expected++; + } + assertEquals(expected, buffer.firstIndexWhere(element -> element >= bound), "threshold " + threshold); + } + } + + @Test + void itBehavesLikeAnArrayDequeUnderAnyMixOfAddsAndRemoves() { + Random random = new Random(8787); + RingBuffer buffer = new RingBuffer<>(); + ArrayDeque reference = new ArrayDeque<>(); + int next = 0; + for (int step = 0; step < 20_000; step++) { + if (reference.isEmpty() || random.nextInt(5) < 3) { + buffer.addLast(next); + reference.addLast(next); + next++; + } else { + assertEquals(reference.removeFirst(), buffer.removeFirst()); + } + assertEquals(reference.size(), buffer.size()); + if (!reference.isEmpty()) { + assertEquals(reference.getFirst(), buffer.getFirst()); + assertEquals(reference.getLast(), buffer.getLast()); + int bound = reference.getFirst() + random.nextInt(reference.size() + 1); + assertEquals(bound - reference.getFirst(), buffer.firstIndexWhere(element -> element >= bound)); + } + } + assertEquals(new ArrayList<>(reference), contents(buffer)); + } + + private static List contents(RingBuffer buffer) { + List elements = new ArrayList<>(); + for (T element : buffer) { + elements.add(element); + } + return elements; + } +} diff --git a/src/test/java/io/floci/aws/services/dynamodb/backend/DynamoDbNativeBackendTest.java b/src/test/java/io/floci/aws/services/dynamodb/backend/DynamoDbNativeBackendTest.java index 3038ac9b14..56937769e3 100644 --- a/src/test/java/io/floci/aws/services/dynamodb/backend/DynamoDbNativeBackendTest.java +++ b/src/test/java/io/floci/aws/services/dynamodb/backend/DynamoDbNativeBackendTest.java @@ -72,6 +72,7 @@ class DynamoDbNativeBackendTest { }); EmulatorConfig streamConfig = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS); when(streamConfig.services().dynamodb().streamShardCount()).thenReturn(1); + when(streamConfig.services().dynamodb().streamMaxRecords()).thenReturn(1000); DynamoDbStreamService streams = new DynamoDbStreamService(mapper, storageFactory, streamConfig); DynamoDbService service = new DynamoDbService(storageFactory, new RegionResolver(REGION, ACCOUNT), streams, forwarder, null, mapper, mock(EmulatorConfig.class, RETURNS_DEEP_STUBS));