diff --git a/docs/services/dynamodb.md b/docs/services/dynamodb.md index a76eafba05..9e1bd5dc8d 100644 --- a/docs/services/dynamodb.md +++ b/docs/services/dynamodb.md @@ -146,6 +146,35 @@ Stream records are held in memory. `POST /_floci/state/reset` removes every stre tables, so `ListStreams` and `DescribeStream` no longer return the streams of tables created before the reset. +### Shards, iterators and retention + +By default a stream has one shard, `shardId-0000000001-00000000001`, which stays open until the +stream is disabled, and keeps its latest 1,000 records. Shard iterators do not expire and records do +not age out. Four settings bring a stream closer to AWS. Each is off unless you set it: + +- `FLOCI_SERVICES_DYNAMODB_STREAM_SHARD_COUNT` gives each stream that many open shards. An item's + changes go to the shard its partition key picks, so they stay in order, as on AWS, where each table + partition writes to a shard of its own. Changes to different items can land on different shards. +- `FLOCI_SERVICES_DYNAMODB_STREAM_SHARD_ROLLOVER_SECONDS` closes each open shard once it has been + open that long, and a child shard, whose `ParentShardId` names it, takes its keys. A consumer reads + a parent to its end before its children, as Floci's Lambda event source mappings, EventBridge Pipes + and Redshift zero-ETL integrations do. On AWS, shards close and split on their own. +- `FLOCI_SERVICES_DYNAMODB_STREAM_ITERATOR_EXPIRY_ENABLED` expires a shard iterator 15 minutes after + it is returned, as AWS does, and `GetRecords` then answers `ExpiredIteratorException`. The + `NextShardIterator` of each `GetRecords` call has 15 minutes of its own. +- `FLOCI_SERVICES_DYNAMODB_STREAM_RETENTION_ENABLED` trims records 24 hours after they are written and + drops a closed shard 24 hours after it closes, as AWS does. `GetShardIterator` then refuses a + sequence number the shard has trimmed with `TrimmedDataAccessException`, and one it never held with + `ValidationException`, as AWS does. + +Disabling a stream closes its open shards, each with an `EndingSequenceNumber`, and what they hold +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. + ## Time to Live With TTL enabled, a sweep runs every 60 seconds and deletes the items whose TTL attribute holds an @@ -273,6 +302,10 @@ region is rejected. | `FLOCI_SERVICES_DYNAMODB_VECTOR_INDEX_ALLOCATION_SECONDS` | `4` | Seconds a vector index added by `UpdateTable` spends in resource allocation | | `FLOCI_SERVICES_DYNAMODB_VECTOR_INDEX_BACKFILL_SECONDS` | `10` | Seconds that index then spends backfilling before it goes `ACTIVE` | | `FLOCI_SERVICES_DYNAMODB_LATEST_RESTORABLE_LAG_SECONDS` | `300` | Seconds `LatestRestorableDateTime` of point-in-time recovery trails the current time. Set `0` to restore the latest writes with `UseLatestRestorableTime` | +| `FLOCI_SERVICES_DYNAMODB_STREAM_SHARD_COUNT` | `1` | Open shards in each stream. See [Shards, iterators and retention](#shards-iterators-and-retention) | +| `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_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 b5eb6240a6..1b1631b9d9 100644 --- a/src/main/java/io/floci/aws/config/EmulatorConfig.java +++ b/src/main/java/io/floci/aws/config/EmulatorConfig.java @@ -1669,6 +1669,37 @@ public interface EmulatorConfig { @WithDefault("300") int latestRestorableLagSeconds(); + /** + * Open shards in each DynamoDB stream of the native engine. An item's changes always go to the shard its + * partition key picks, so they stay in order. AWS gives each table partition a shard of its own. + * Env: FLOCI_SERVICES_DYNAMODB_STREAM_SHARD_COUNT + */ + @WithDefault("1") + int streamShardCount(); + + /** + * Seconds a stream shard of the native engine stays open before it closes and a child shard, which names it + * as its parent, takes its keys. 0 keeps shards open until the stream is disabled. + * Env: FLOCI_SERVICES_DYNAMODB_STREAM_SHARD_ROLLOVER_SECONDS + */ + @WithDefault("0") + long streamShardRolloverSeconds(); + + /** + * Expire a stream shard iterator 15 minutes after it is returned, as AWS does. + * Env: FLOCI_SERVICES_DYNAMODB_STREAM_ITERATOR_EXPIRY_ENABLED + */ + @WithDefault("false") + boolean streamIteratorExpiryEnabled(); + + /** + * Keep stream records, and shards after they close, for 24 hours as AWS does, and refuse a shard iterator + * for a sequence number the shard no longer holds or never held. + * Env: FLOCI_SERVICES_DYNAMODB_STREAM_RETENTION_ENABLED + */ + @WithDefault("false") + boolean streamRetentionEnabled(); + /** 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 91bfa838de..3a65d87318 100644 --- a/src/main/java/io/floci/aws/services/dynamodb/DynamoDbStreamService.java +++ b/src/main/java/io/floci/aws/services/dynamodb/DynamoDbStreamService.java @@ -4,6 +4,7 @@ import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; +import io.floci.aws.config.EmulatorConfig; import io.floci.aws.core.common.AwsArnUtils; import io.floci.aws.core.common.AwsException; import io.floci.aws.core.storage.AccountAwareStorageBackend; @@ -17,16 +18,20 @@ import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import org.jboss.logging.Logger; +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.time.Clock; +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; import java.util.Map; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentLinkedDeque; import java.util.concurrent.atomic.AtomicLong; @ApplicationScoped @@ -34,35 +39,90 @@ public class DynamoDbStreamService { private static final Logger LOG = Logger.getLogger(DynamoDbStreamService.class); - static final String SHARD_ID = "shardId-0000000001-00000000001"; + /** 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. */ 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); + /** How long records, and shards once closed, are kept when retention is on, as on AWS. */ + static final Duration RETENTION = Duration.ofHours(24); + /** The most shards one DescribeStream page lists, AWS's upper limit. */ + static final int MAX_SHARDS_PER_PAGE = 100; private static final String ZERO_SEQUENCE_NUMBER = "000000000000000000000"; private static final DateTimeFormatter STREAM_LABEL_FORMAT = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS").withZone(ZoneOffset.UTC); + /** + * 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. + */ + record Settings(int shardCount, Duration shardRollover, boolean iteratorExpiry, boolean retention) { + + static final Settings DEFAULTS = new Settings(1, null, false, false); + + Settings { + if (shardCount < 1) { + throw new IllegalArgumentException("A DynamoDB stream needs at least one shard, not " + shardCount); + } + if (shardRollover != null && (shardRollover.isZero() || shardRollover.isNegative())) { + shardRollover = null; + } + } + + 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()); + } + } + + /** A shard as DescribeStream lists it. Its ending sequence number is null while it is open. */ + record ShardDescription(String shardId, String parentShardId, String startingSequenceNumber, + String endingSequenceNumber) {} + + record ShardsPage(List shards, String lastEvaluatedShardId) {} + + record GetRecordsResult(List records, String nextShardIterator) {} + + /** Where an iterator reads from: at {@code sequence} when inclusive, else just after it. */ + private record Cursor(String sequence, boolean inclusive) {} + + /** What a shard iterator carries: the shard it reads, where, and when it was returned. */ + private record IteratorToken(String streamArn, String shardId, Cursor cursor, Instant issuedAt) {} + /** Keyed by table ARN, which is unique per partition, region, account and table. */ private final ConcurrentHashMap streams = new ConcurrentHashMap<>(); - private final ConcurrentHashMap> records = - new ConcurrentHashMap<>(); - private final ConcurrentHashMap streamRecordCounts = new ConcurrentHashMap<>(); + /** Keyed by stream ARN. */ + private final ConcurrentHashMap states = new ConcurrentHashMap<>(); /** Per stream (the stream ARN embeds account + region + table) so accounts never share a counter. */ private final ConcurrentHashMap sequenceCounters = new ConcurrentHashMap<>(); private final ObjectMapper objectMapper; + private final Settings settings; + private final Clock clock; @Inject - public DynamoDbStreamService(ObjectMapper objectMapper, StorageFactory storageFactory) { + public DynamoDbStreamService(ObjectMapper objectMapper, StorageFactory storageFactory, EmulatorConfig config) { this(objectMapper, storageFactory.create("dynamodb", "dynamodb-tables.json", - new TypeReference>() {})); + new TypeReference>() {}), + Settings.from(config.services().dynamodb()), Clock.systemUTC()); } /** Package-private constructor for testing. */ DynamoDbStreamService(ObjectMapper objectMapper, StorageBackend tableStore) { - this.objectMapper = objectMapper; - loadPersistedStreams(tableStore); + this(objectMapper, tableStore, Settings.DEFAULTS, Clock.systemUTC()); } + /** Package-private constructor for testing streams shaped by {@code settings}, on {@code clock}. */ + DynamoDbStreamService(ObjectMapper objectMapper, StorageBackend tableStore, + Settings settings, Clock clock) { + this.objectMapper = objectMapper; + this.settings = settings; + this.clock = clock; + loadPersistedStreams(tableStore); + } private void loadPersistedStreams(StorageBackend tableStore) { if (tableStore == null) { @@ -104,7 +164,7 @@ public class DynamoDbStreamService { } String streamArn = streamArnInput; - Instant now = Instant.now(); + Instant now = clock.instant(); String label; if (streamArn == null){ label = STREAM_LABEL_FORMAT.format(now); @@ -123,17 +183,32 @@ public class DynamoDbStreamService { sd.setCreationDateTime(now); sd.setStartingSequenceNumber(String.format("%021d", 1)); + StreamState state = new StreamState(counter(streamArn)); + synchronized (state) { + for (int slot = 0; slot < settings.shardCount(); slot++) { + state.open(1, slot, null, now); + } + } + // Shards first, so a write that already sees the stream has somewhere to land. + states.put(streamArn, state); streams.put(tableArn, sd); - records.put(streamArn, new ConcurrentLinkedDeque<>()); - streamRecordCounts.put(streamArn, new AtomicLong()); - LOG.infov("Enabled stream for table {0} in region {1}: {2}", tableName, region, streamArn); + LOG.infov("Enabled stream for table {0} in region {1}: {2} ({3} shards)", + tableName, region, streamArn, settings.shardCount()); return sd; } + /** Disabling a stream closes its open shards, as on AWS; what they hold stays readable. */ public void disableStream(String tableArn) { StreamDescription sd = streams.get(tableArn); if (sd != null) { sd.setStreamStatus("DISABLED"); + StreamState state = states.get(sd.getStreamArn()); + if (state != null) { + synchronized (state) { + Instant now = clock.instant(); + state.shards.stream().filter(Shard::open).toList().forEach(shard -> state.close(shard, now)); + } + } LOG.infov("Disabled stream for table {0}", tableArn); } } @@ -141,8 +216,7 @@ public class DynamoDbStreamService { public void deleteStream(String tableArn) { StreamDescription sd = streams.remove(tableArn); if (sd != null) { - records.remove(sd.getStreamArn()); - streamRecordCounts.remove(sd.getStreamArn()); + states.remove(sd.getStreamArn()); sequenceCounters.remove(sd.getStreamArn()); LOG.infov("Deleted stream for table {0}", tableArn); } @@ -151,8 +225,7 @@ public class DynamoDbStreamService { /** Emulator reset: drops every stream and its records. Sequence numbers stay monotonic. */ public void clear() { streams.clear(); - records.clear(); - streamRecordCounts.clear(); + states.clear(); } public void captureEvent(String eventName, JsonNode oldItem, JsonNode newItem, @@ -181,29 +254,52 @@ public class DynamoDbStreamService { record.setEventName(eventName); record.setEventSource("aws:dynamodb"); record.setAwsRegion(region); - record.setApproximateCreationDateTime(Instant.now().getEpochSecond()); + record.setApproximateCreationDateTime(clock.instant().getEpochSecond()); record.setKeys(keys); record.setNewImage(newImage); record.setOldImage(oldImage); record.setStreamViewType(viewType); record.setTtlDeletion(ttlDeletion); - ConcurrentLinkedDeque deque = records.get(sd.getStreamArn()); - if (deque != null) { - synchronized (deque) { - long seq = sequenceCounters.computeIfAbsent(sd.getStreamArn(), k -> new AtomicLong()) - .incrementAndGet(); - record.setSequenceNumber(String.format("%021d", seq)); - streamRecordCounts.computeIfAbsent(sd.getStreamArn(), ignored -> new AtomicLong()) - .incrementAndGet(); - deque.addLast(record); - while (deque.size() > MAX_RECORDS) { - deque.pollFirst(); - } + StreamState state = states.get(sd.getStreamArn()); + if (state == null) { + return; + } + int slot = slotOf(keys, table); + synchronized (state) { + maintain(state, clock.instant()); + Shard shard = state.openShard(slot); + if (shard == null) { + // Disabled since the status check above, which closed every shard. + return; + } + record.setSequenceNumber(sequence(state.counter.incrementAndGet())); + shard.records.addLast(record); + shard.lastSequence = record.getSequenceNumber(); + state.retained++; + while (state.retained > MAX_RECORDS) { + state.trimOldest(); } } } + /** + * The slot whose open shard takes an item's changes, from its partition key, so one item's changes always land + * on one shard and stay in order. + */ + private int slotOf(ObjectNode keys, TableDefinition table) { + if (settings.shardCount() == 1) { + return 0; + } + for (KeySchemaElement element : table.getKeySchema()) { + if ("HASH".equals(element.getKeyType()) && keys.has(element.getAttributeName())) { + return Math.floorMod(keys.get(element.getAttributeName()).toString().hashCode(), + settings.shardCount()); + } + } + return 0; + } + private ObjectNode buildKeys(JsonNode item, TableDefinition table) { ObjectNode keys = objectMapper.createObjectNode(); if (item == null) { @@ -256,6 +352,34 @@ public class DynamoDbStreamService { "Stream not found: " + streamArn, 400); } + /** The stream's shards after {@code exclusiveStartShardId}, in shard ID order, a page of at most {@code limit}. */ + ShardsPage describeShards(String streamArn, String exclusiveStartShardId, Integer limit) { + describeStream(streamArn); + StreamState state = states.get(streamArn); + if (state == null) { + return new ShardsPage(List.of(), null); + } + requirePositiveLimit(limit); + int pageSize = limit == null ? MAX_SHARDS_PER_PAGE : Math.min(limit, MAX_SHARDS_PER_PAGE); + List page = new ArrayList<>(); + boolean more = false; + synchronized (state) { + maintain(state, clock.instant()); + for (Shard shard : state.shards) { + if (exclusiveStartShardId != null && shard.id.compareTo(exclusiveStartShardId) <= 0) { + continue; + } + if (page.size() == pageSize) { + more = true; + break; + } + page.add(new ShardDescription(shard.id, shard.parentId, shard.startingSequenceNumber, + shard.endingSequenceNumber)); + } + } + return new ShardsPage(List.copyOf(page), more ? page.get(page.size() - 1).shardId() : null); + } + String getShardIterator(String streamArn, String shardId, String iteratorType, String sequenceNumber) { StreamDescription sd = describeStream(streamArn); @@ -263,140 +387,336 @@ public class DynamoDbStreamService { throw new AwsException("ResourceNotFoundException", "Stream not found: " + streamArn, 400); } - - ConcurrentLinkedDeque deque = records.get(streamArn); - List snapshot; - long recordCount; - if (deque == null) { - snapshot = List.of(); - recordCount = 0; - } else { - synchronized (deque) { - snapshot = new ArrayList<>(deque); - recordCount = streamRecordCounts.getOrDefault(streamArn, new AtomicLong()).get(); - } + boolean bySequence = "AT_SEQUENCE_NUMBER".equals(iteratorType) || "AFTER_SEQUENCE_NUMBER".equals(iteratorType); + if (!bySequence && !"TRIM_HORIZON".equals(iteratorType) && !"LATEST".equals(iteratorType)) { + throw new AwsException("ValidationException", "Unknown iterator type: " + iteratorType, 400); + } + if (bySequence && (sequenceNumber == null || sequenceNumber.isBlank())) { + throw new AwsException("ValidationException", + "One or more parameter values were invalid: SequenceNumber cannot be null", 400); } - String cursorSequence = switch (iteratorType) { - case "TRIM_HORIZON" -> snapshot.isEmpty() ? zeroSequence() : snapshot.get(0).getSequenceNumber(); - case "LATEST" -> snapshot.isEmpty() ? zeroSequence() : snapshot.get(snapshot.size() - 1).getSequenceNumber(); - case "AT_SEQUENCE_NUMBER", "AFTER_SEQUENCE_NUMBER" -> { - if (sequenceNumber == null || sequenceNumber.isBlank()) { - throw new AwsException("ValidationException", - "Sequence number is required for this iterator type", 400); + StreamState state = states.get(streamArn); + if (state == null) { + throw shardNotFound(); + } + Instant now = clock.instant(); + Cursor cursor; + synchronized (state) { + maintain(state, now); + Shard shard = state.find(shardId); + if (shard == null) { + throw shardNotFound(); + } + cursor = switch (iteratorType) { + case "TRIM_HORIZON" -> shard.records.isEmpty() + ? shard.afterTrimmed() : new Cursor(shard.records.getFirst().getSequenceNumber(), true); + case "LATEST" -> shard.records.isEmpty() + ? shard.afterTrimmed() : new Cursor(shard.records.getLast().getSequenceNumber(), false); + default -> { + if (settings.retention()) { + requireHeld(state, shard, sequenceNumber); + } + yield new Cursor(sequenceNumber, "AT_SEQUENCE_NUMBER".equals(iteratorType)); } - yield sequenceNumber; - } - default -> throw new AwsException("ValidationException", - "Unknown iterator type: " + iteratorType, 400); - }; - - boolean inclusive = "TRIM_HORIZON".equals(iteratorType) || "AT_SEQUENCE_NUMBER".equals(iteratorType); - long cursorRecordCount = zeroSequence().equals(cursorSequence) ? recordCount : -1; - return encodeIterator(streamArn, cursorSequence, inclusive, cursorRecordCount); + }; + } + return encodeIterator(new IteratorToken(streamArn, shardId, cursor, now)); } - private int findSequencePosition(List records, String targetSeq, boolean inclusive) { - for (int i = 0; i < records.size(); i++) { - String seq = records.get(i).getSequenceNumber(); - int cmp = seq.compareTo(targetSeq); - if (inclusive ? cmp >= 0 : cmp > 0) { - return i; + /** + * Refuses a sequence number the shard never held, as AWS does with ValidationException, and one it held but has + * trimmed, with TrimmedDataAccessException. A sequence number at or below the shard's trim point cannot be told + * apart from another shard's, so it is taken as trimmed. A shard's starting sequence number is no exception: the + * first shards of a stream all start at the same one, and only the shard whose record it is holds it. + */ + private static void requireHeld(StreamState state, Shard shard, String sequenceNumber) { + BigInteger requested; + try { + requested = new BigInteger(sequenceNumber); + } catch (NumberFormatException e) { + throw invalidSequenceNumber(); + } + if (requested.compareTo(new BigInteger(shard.startingSequenceNumber)) < 0 + || requested.compareTo(BigInteger.valueOf(state.counter.get())) > 0 + || (!shard.open() && requested.compareTo(new BigInteger(shard.endingSequenceNumber)) > 0)) { + throw invalidSequenceNumber(); + } + 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; } } - return records.size(); + throw invalidSequenceNumber(); } - record GetRecordsResult(List records, String nextShardIterator) {} - GetRecordsResult getRecords(String shardIterator, Integer limit) { - String[] parts = decodeIterator(shardIterator); - String streamArn = parts[0]; - String cursorSequence = parts[1]; - boolean inclusive = Boolean.parseBoolean(parts[2]); - long cursorRecordCount = parseRecordCount(parts[3]); - - ConcurrentLinkedDeque deque = records.get(streamArn); - List snapshot; - long currentRecordCount; - if (deque == null) { - snapshot = List.of(); - currentRecordCount = 0; - } else { - synchronized (deque) { - snapshot = new ArrayList<>(deque); - currentRecordCount = streamRecordCounts.getOrDefault(streamArn, new AtomicLong()).get(); + requirePositiveLimit(limit); + IteratorToken iterator = decodeIterator(shardIterator); + Instant now = clock.instant(); + if (settings.iteratorExpiry() && now.isAfter(iterator.issuedAt().plus(ITERATOR_LIFETIME))) { + throw new AwsException("ExpiredIteratorException", "The provided iterator exceeds the maximum age allowed.", + 400); + } + StreamState state = states.get(iterator.streamArn()); + if (state == null) { + return new GetRecordsResult(List.of(), encodeIterator( + new IteratorToken(iterator.streamArn(), iterator.shardId(), iterator.cursor(), now))); + } + Cursor cursor = iterator.cursor(); + List page; + Cursor next; + boolean ended; + synchronized (state) { + maintain(state, now); + Shard shard = state.find(iterator.shardId()); + if (shard == null) { + throw shardNotFound(); } + if (shard.trimmedThrough != null) { + int trimmedAgainstCursor = shard.trimmedThrough.compareTo(cursor.sequence()); + if (cursor.inclusive() ? trimmedAgainstCursor >= 0 : trimmedAgainstCursor > 0) { + 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()))); + 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(); } - int position = findSequencePosition(snapshot, cursorSequence, inclusive); - if (zeroSequence().equals(cursorSequence) && cursorRecordCount >= 0 - && currentRecordCount - cursorRecordCount > MAX_RECORDS) { - throw new AwsException("TrimmedDataAccessException", - "The requested sequence number has been trimmed", 400); - } - if (!snapshot.isEmpty() && !zeroSequence().equals(cursorSequence) - && cursorSequence.compareTo(snapshot.get(0).getSequenceNumber()) < 0) { - throw new AwsException("TrimmedDataAccessException", - "The requested sequence number has been trimmed", 400); - } - - int effectiveLimit = limit != null ? limit : 100; - int end = Math.min(position + effectiveLimit, snapshot.size()); - List page = snapshot.subList(position, end); - - String nextSequence = page.isEmpty() - ? cursorSequence - : page.get(page.size() - 1).getSequenceNumber(); - long nextRecordCount = zeroSequence().equals(nextSequence) ? cursorRecordCount : -1; - String nextIterator = encodeIterator(streamArn, nextSequence, page.isEmpty() && inclusive, nextRecordCount); - return new GetRecordsResult(new ArrayList<>(page), nextIterator); + return new GetRecordsResult(page, ended ? null + : encodeIterator(new IteratorToken(iterator.streamArn(), iterator.shardId(), next, now))); } - private String encodeIterator(String streamArn, String sequenceNumber, boolean inclusive, long recordCount) { - String raw = streamArn + "|" + sequenceNumber + "|" + inclusive + "|" + recordCount; - return Base64.getEncoder().encodeToString(raw.getBytes()); + /** + * 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 + * its keys. Done on every use of the stream rather than on a timer, so it costs nothing while idle. A closed shard + * that holds no records is dropped once the shard that replaced it has closed too: nothing is left to read in it, + * and a reader has had a whole rollover to reach its end. That keeps an idle stream at two generations of shards, + * and a busy one at the shards that still hold records. + */ + private void maintain(StreamState state, Instant now) { + if (settings.retention()) { + long oldestKept = now.minus(RETENTION).getEpochSecond(); + for (Shard shard : state.shards) { + while (!shard.records.isEmpty() && shard.records.getFirst().getApproximateCreationDateTime() < oldestKept) { + state.trimFirst(shard); + } + } + Instant closedBefore = now.minus(RETENTION); + state.shards.removeIf(shard -> { + boolean expired = !shard.open() && shard.closedAt.isBefore(closedBefore); + if (expired) { + state.retained -= shard.records.size(); + } + return expired; + }); + } + if (settings.shardRollover() != null) { + for (int i = 0, existing = state.shards.size(); i < existing; i++) { + Shard shard = state.shards.get(i); + if (shard.open() && !now.isBefore(shard.openedAt.plus(settings.shardRollover()))) { + state.close(shard, now); + state.open(shard.generation + 1, shard.slot, shard.id, now); + } + } + } + state.shards.removeIf(shard -> !shard.open() && shard.records.isEmpty() && shard.replacementClosed); + } + + private String encodeIterator(IteratorToken iterator) { + String raw = iterator.streamArn() + "|" + iterator.shardId() + "|" + iterator.cursor().sequence() + "|" + + iterator.cursor().inclusive() + "|" + iterator.issuedAt().toEpochMilli(); + return Base64.getEncoder().encodeToString(raw.getBytes(StandardCharsets.UTF_8)); } /** The stream an iterator reads, rejecting a malformed iterator as GetRecords does. */ String streamArnOf(String shardIterator) { - return decodeIterator(shardIterator)[0]; + return decodeIterator(shardIterator).streamArn(); } - private String[] decodeIterator(String iterator) { + /** Fields are read from the right, so the stream ARN keeps whatever it holds. */ + private IteratorToken decodeIterator(String token) { + String raw; try { - String raw = new String(Base64.getDecoder().decode(iterator)); - int lastPipe = raw.lastIndexOf('|'); - int sequencePipe = raw.lastIndexOf('|', lastPipe - 1); - int inclusivePipe = raw.lastIndexOf('|', sequencePipe - 1); - if (inclusivePipe < 0 || sequencePipe < 0 || lastPipe < 0 || lastPipe == raw.length() - 1) { - throw new AwsException("ValidationException", "Invalid shard iterator", 400); - } - String inclusive = raw.substring(sequencePipe + 1, lastPipe); - String recordCount = raw.substring(lastPipe + 1); - if (!"true".equals(inclusive) && !"false".equals(inclusive)) { - throw new AwsException("ValidationException", "Invalid shard iterator", 400); - } - try { - Long.parseLong(recordCount); - } catch (NumberFormatException e) { - throw new AwsException("ValidationException", "Invalid shard iterator", 400); - } - return new String[]{raw.substring(0, inclusivePipe), raw.substring(inclusivePipe + 1, sequencePipe), - inclusive, recordCount}; + raw = new String(Base64.getDecoder().decode(token), StandardCharsets.UTF_8); } catch (IllegalArgumentException e) { - throw new AwsException("ValidationException", "Invalid shard iterator", 400); + throw invalidIterator(); + } + String[] fields = new String[5]; + int end = raw.length(); + for (int field = 4; field > 0; field--) { + int pipe = raw.lastIndexOf('|', end - 1); + if (pipe < 0) { + throw invalidIterator(); + } + fields[field] = raw.substring(pipe + 1, end); + end = pipe; + } + fields[0] = raw.substring(0, end); + if (fields[0].isEmpty() || fields[1].isEmpty() || fields[2].isEmpty() + || !("true".equals(fields[3]) || "false".equals(fields[3]))) { + throw invalidIterator(); } - } - - private long parseRecordCount(String recordCount) { try { - return Long.parseLong(recordCount); + return new IteratorToken(fields[0], fields[1], new Cursor(fields[2], Boolean.parseBoolean(fields[3])), + Instant.ofEpochMilli(Long.parseLong(fields[4]))); } catch (NumberFormatException e) { - throw new AwsException("ValidationException", "Invalid shard iterator", 400); + throw invalidIterator(); } } - private String zeroSequence() { - return ZERO_SEQUENCE_NUMBER; + private AtomicLong counter(String streamArn) { + return sequenceCounters.computeIfAbsent(streamArn, ignored -> new AtomicLong()); + } + + /** Generation 1, slot 0 is {@code shardId-0000000001-00000000001}; IDs sort in generation, then slot, order. */ + private static String shardId(int generation, int slot) { + return String.format("shardId-%010d-%011d", generation, slot + 1); + } + + private static String sequence(long value) { + return String.format("%021d", value); + } + + /** {@code Limit} of DescribeStream and GetRecords is at least 1; AWS refuses less before reading anything. */ + private static void requirePositiveLimit(Integer limit) { + if (limit != null && limit < 1) { + throw new AwsException("ValidationException", "1 validation error detected: Value at 'limit' failed to " + + "satisfy constraint: Member must have value greater than or equal to 1", 400); + } + } + + private static AwsException shardNotFound() { + return new AwsException("ResourceNotFoundException", "Requested resource not found: Shard does not exist", 400); + } + + private static AwsException trimmed() { + return new AwsException("TrimmedDataAccessException", "The data you are trying to access has been trimmed.", 400); + } + + private static AwsException invalidSequenceNumber() { + return new AwsException("ValidationException", "Invalid SequenceNumber for the shard", 400); + } + + private static AwsException invalidIterator() { + return new AwsException("ValidationException", "Invalid shard iterator", 400); + } + + /** A stream's shards, oldest first, and the records they keep. Guarded by its own monitor. */ + private static final class StreamState { + final List shards = new ArrayList<>(); + final AtomicLong counter; + /** Records kept across every shard, held to {@link #MAX_RECORDS}. */ + int retained; + + StreamState(AtomicLong counter) { + this.counter = counter; + } + + void open(int generation, int slot, String parentId, Instant now) { + shards.add(new Shard(generation, slot, parentId, sequence(counter.get() + 1), now)); + } + + Shard find(String shardId) { + for (Shard shard : shards) { + if (shard.id.equals(shardId)) { + return shard; + } + } + return null; + } + + /** Closes {@code shard} and tells its parent, which no reader needs once it is empty and this has closed. */ + void close(Shard shard, Instant now) { + shard.close(now); + Shard parent = shard.parentId == null ? null : find(shard.parentId); + if (parent != null) { + parent.replacementClosed = true; + } + } + + Shard openShard(int slot) { + for (Shard shard : shards) { + if (shard.slot == slot && shard.open()) { + return shard; + } + } + return null; + } + + /** Trims the stream's oldest record, whichever shard holds it. */ + void trimOldest() { + Shard oldest = null; + for (Shard shard : shards) { + if (!shard.records.isEmpty() && (oldest == null || shard.records.getFirst().getSequenceNumber() + .compareTo(oldest.records.getFirst().getSequenceNumber()) < 0)) { + oldest = shard; + } + } + if (oldest != null) { + trimFirst(oldest); + } + } + + void trimFirst(Shard shard) { + shard.trimmedThrough = shard.records.removeFirst().getSequenceNumber(); + retained--; + } + } + + private static final class Shard { + final String id; + final String parentId; + final int generation; + final int slot; + final String startingSequenceNumber; + final Instant openedAt; + final ArrayDeque records = new ArrayDeque<>(); + /** 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. */ + String trimmedThrough; + String endingSequenceNumber; + Instant closedAt; + /** Whether the child shard that took this one's keys has closed in turn. */ + boolean replacementClosed; + + Shard(int generation, int slot, String parentId, String startingSequenceNumber, Instant openedAt) { + this.id = shardId(generation, slot); + this.parentId = parentId; + this.generation = generation; + this.slot = slot; + this.startingSequenceNumber = startingSequenceNumber; + this.openedAt = openedAt; + } + + boolean open() { + return closedAt == null; + } + + void close(Instant now) { + closedAt = now; + endingSequenceNumber = lastSequence != null ? lastSequence : startingSequenceNumber; + } + + /** Where TRIM_HORIZON and LATEST read an empty shard: after anything it trimmed, so no trim is reported. */ + Cursor afterTrimmed() { + return new Cursor(trimmedThrough != null ? trimmedThrough : ZERO_SEQUENCE_NUMBER, false); + } } } diff --git a/src/main/java/io/floci/aws/services/dynamodb/NativeDynamoDbStreamsJsonHandler.java b/src/main/java/io/floci/aws/services/dynamodb/NativeDynamoDbStreamsJsonHandler.java index d23bead24e..314a8cf913 100644 --- a/src/main/java/io/floci/aws/services/dynamodb/NativeDynamoDbStreamsJsonHandler.java +++ b/src/main/java/io/floci/aws/services/dynamodb/NativeDynamoDbStreamsJsonHandler.java @@ -92,12 +92,18 @@ public class NativeDynamoDbStreamsJsonHandler { sd.getTableName(), streamArn); } + String exclusiveStartShardId = request.hasNonNull("ExclusiveStartShardId") + ? request.get("ExclusiveStartShardId").asText() : null; + Integer limit = request.hasNonNull("Limit") ? request.get("Limit").asInt() : null; + DynamoDbStreamService.ShardsPage shards = streamService.describeShards(streamArn, exclusiveStartShardId, limit); + ObjectNode response = objectMapper.createObjectNode(); - response.set("StreamDescription", describeStreamToNode(sd, keySchema)); + response.set("StreamDescription", describeStreamToNode(sd, keySchema, shards)); return Response.ok(response).build(); } - private ObjectNode describeStreamToNode(StreamDescription sd, List keySchema) { + private ObjectNode describeStreamToNode(StreamDescription sd, List keySchema, + DynamoDbStreamService.ShardsPage page) { ObjectNode node = objectMapper.createObjectNode(); node.put("StreamArn", sd.getStreamArn()); node.put("StreamLabel", sd.getStreamLabel()); @@ -116,15 +122,27 @@ public class NativeDynamoDbStreamsJsonHandler { node.set("KeySchema", keySchemaArray); ArrayNode shards = objectMapper.createArrayNode(); - ObjectNode shard = objectMapper.createObjectNode(); - shard.put("ShardId", DynamoDbStreamService.SHARD_ID); - ObjectNode seqRange = objectMapper.createObjectNode(); - seqRange.put("StartingSequenceNumber", sd.getStartingSequenceNumber()); - shard.set("SequenceNumberRange", seqRange); - shards.add(shard); + for (DynamoDbStreamService.ShardDescription description : page.shards()) { + ObjectNode shard = objectMapper.createObjectNode(); + shard.put("ShardId", description.shardId()); + if (description.parentShardId() != null) { + shard.put("ParentShardId", description.parentShardId()); + } + ObjectNode seqRange = objectMapper.createObjectNode(); + seqRange.put("StartingSequenceNumber", description.startingSequenceNumber()); + if (description.endingSequenceNumber() != null) { + seqRange.put("EndingSequenceNumber", description.endingSequenceNumber()); + } + shard.set("SequenceNumberRange", seqRange); + shards.add(shard); + } node.set("Shards", shards); - node.putNull("LastEvaluatedShardId"); + if (page.lastEvaluatedShardId() != null) { + node.put("LastEvaluatedShardId", page.lastEvaluatedShardId()); + } else { + node.putNull("LastEvaluatedShardId"); + } return node; } @@ -156,8 +174,11 @@ public class NativeDynamoDbStreamsJsonHandler { recordsArray.add(recordToNode(record)); } response.set("Records", recordsArray); - response.put("NextShardIterator", result.nextShardIterator()); - + // A closed shard read to its end has none, which tells the reader it is done. + if (result.nextShardIterator() != null) { + response.put("NextShardIterator", result.nextShardIterator()); + } + return Response.ok(response).build(); } diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index 3a3bdb96ba..a7c6746722 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -458,6 +458,10 @@ floci: vector-index-allocation-seconds: 4 # FLOCI_SERVICES_DYNAMODB_VECTOR_INDEX_ALLOCATION_SECONDS. Resource allocation phase of a vector index added by UpdateTable. vector-index-backfill-seconds: 10 # FLOCI_SERVICES_DYNAMODB_VECTOR_INDEX_BACKFILL_SECONDS. Backfilling phase that follows it. latest-restorable-lag-seconds: 300 # FLOCI_SERVICES_DYNAMODB_LATEST_RESTORABLE_LAG_SECONDS. How far LatestRestorableDateTime trails now. + stream-shard-count: 1 # FLOCI_SERVICES_DYNAMODB_STREAM_SHARD_COUNT. Open shards per stream (native engine). + 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. 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 new file mode 100644 index 0000000000..492b28b3e5 --- /dev/null +++ b/src/test/java/io/floci/aws/services/dynamodb/DynamoDbStreamLifecycleTest.java @@ -0,0 +1,493 @@ +package io.floci.aws.services.dynamodb; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import io.floci.aws.core.common.AwsException; +import io.floci.aws.core.common.RegionResolver; +import io.floci.aws.core.storage.InMemoryStorage; +import io.floci.aws.services.dynamodb.DynamoDbStreamService.Settings; +import io.floci.aws.services.dynamodb.DynamoDbStreamService.ShardDescription; +import io.floci.aws.services.dynamodb.backend.DynamoDbApiStreamReader; +import io.floci.aws.services.dynamodb.backend.DynamoDbOperations; +import io.floci.aws.services.dynamodb.backend.DynamoDbStreamReader; +import io.floci.aws.services.dynamodb.model.AttributeDefinition; +import io.floci.aws.services.dynamodb.model.DynamoDbStreamRecord; +import io.floci.aws.services.dynamodb.model.KeySchemaElement; +import io.floci.aws.services.dynamodb.model.TableDefinition; +import jakarta.ws.rs.core.Response; +import org.junit.jupiter.api.Test; + +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.time.ZoneId; +import java.time.ZoneOffset; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +/** Iterator expiry, time-based retention, several shards and shard lineage in the native stream engine. */ +class DynamoDbStreamLifecycleTest { + + private static final String ACCOUNT = "000000000000"; + private static final String REGION = "us-east-1"; + private static final Settings EXPIRY = new Settings(1, null, true, false); + private static final Settings RETENTION = new Settings(1, null, false, true); + + private final ObjectMapper mapper = new ObjectMapper(); + private final MovableClock clock = new MovableClock(Instant.parse("2026-11-17T12:00:00Z")); + private final TableDefinition table = new TableDefinition("Orders", + List.of(new KeySchemaElement("pk", "HASH")), List.of(new AttributeDefinition("pk", "S")), REGION, ACCOUNT); + + @Test + void byDefaultIteratorsNeverExpireRecordsNeverAgeOutAndAnySequenceNumberIsAccepted() { + DynamoDbStreamService streams = streams(Settings.DEFAULTS); + String streamArn = enable(streams); + put(streams, "a"); + String iterator = streams.getShardIterator(streamArn, DynamoDbStreamService.SHARD_ID, "TRIM_HORIZON", null); + + clock.advance(Duration.ofHours(25)); + + assertEquals(1, streams.getRecords(iterator, 10).records().size()); + assertNotNull(streams.getShardIterator(streamArn, DynamoDbStreamService.SHARD_ID, "AT_SEQUENCE_NUMBER", + "000000000000000000000")); + assertEquals(List.of(new ShardDescription(DynamoDbStreamService.SHARD_ID, null, "000000000000000000001", null)), + streams.describeShards(streamArn, null, null).shards()); + } + + @Test + void anIteratorExpiresFifteenMinutesAfterItIsReturned() { + DynamoDbStreamService streams = streams(EXPIRY); + String streamArn = enable(streams); + put(streams, "a"); + String iterator = streams.getShardIterator(streamArn, DynamoDbStreamService.SHARD_ID, "TRIM_HORIZON", null); + + clock.advance(Duration.ofMinutes(15)); + DynamoDbStreamService.GetRecordsResult read = streams.getRecords(iterator, 10); + assertEquals(1, read.records().size()); + + clock.advance(Duration.ofSeconds(1)); + AwsException expired = assertThrows(AwsException.class, () -> streams.getRecords(iterator, 10)); + assertEquals("ExpiredIteratorException", expired.getErrorCode()); + assertEquals("The provided iterator exceeds the maximum age allowed.", expired.getMessage()); + // The iterator a read returns gets 15 minutes of its own. + assertEquals(0, streams.getRecords(read.nextShardIterator(), 10).records().size()); + } + + @Test + void recordsAreTrimmedTwentyFourHoursAfterTheyAreWritten() { + DynamoDbStreamService streams = streams(RETENTION); + String streamArn = enable(streams); + put(streams, "first"); + String openedEarly = streams.getShardIterator(streamArn, DynamoDbStreamService.SHARD_ID, "TRIM_HORIZON", null); + clock.advance(Duration.ofHours(12)); + put(streams, "second"); + + clock.advance(Duration.ofHours(12).plusSeconds(1)); + + AwsException trimmed = assertThrows(AwsException.class, () -> streams.getRecords(openedEarly, 10)); + assertEquals("TrimmedDataAccessException", trimmed.getErrorCode()); + assertEquals("The data you are trying to access has been trimmed.", trimmed.getMessage()); + String horizon = streams.getShardIterator(streamArn, DynamoDbStreamService.SHARD_ID, "TRIM_HORIZON", null); + assertEquals(List.of("second"), keys(streams.getRecords(horizon, 10).records())); + } + + @Test + void anIteratorOpenedOnAShardThatTrimmingEmptiedReadsWhatComesNext() { + DynamoDbStreamService streams = streams(RETENTION); + String streamArn = enable(streams); + put(streams, "gone"); + clock.advance(Duration.ofHours(25)); + + String horizon = streams.getShardIterator(streamArn, DynamoDbStreamService.SHARD_ID, "TRIM_HORIZON", null); + DynamoDbStreamService.GetRecordsResult empty = streams.getRecords(horizon, 10); + put(streams, "next"); + + assertEquals(List.of(), empty.records()); + assertEquals(List.of("next"), keys(streams.getRecords(empty.nextShardIterator(), 10).records())); + } + + @Test + void aTrimmedSequenceNumberIsRefusedWhenTheIteratorIsRequested() { + DynamoDbStreamService streams = streams(RETENTION); + String streamArn = enable(streams); + put(streams, "first"); + put(streams, "second"); + + clock.advance(Duration.ofHours(24).plusSeconds(1)); + put(streams, "third"); + + AwsException trimmed = assertThrows(AwsException.class, () -> streams.getShardIterator(streamArn, + DynamoDbStreamService.SHARD_ID, "AFTER_SEQUENCE_NUMBER", "000000000000000000001")); + assertEquals("TrimmedDataAccessException", trimmed.getErrorCode()); + assertNotNull(streams.getShardIterator(streamArn, DynamoDbStreamService.SHARD_ID, "AT_SEQUENCE_NUMBER", + "000000000000000000003")); + } + + @Test + void aSequenceNumberTheShardNeverHeldIsRefusedWhenRetentionIsOn() { + DynamoDbStreamService streams = streams(new Settings(2, null, false, true)); + String streamArn = enable(streams); + Map> sequencesByShard = new HashMap<>(); + for (String key : List.of("a", "b", "c", "d", "e", "f")) { + put(streams, key); + } + for (ShardDescription shard : streams.describeShards(streamArn, null, null).shards()) { + sequencesByShard.put(shard.shardId(), readAll(streams, streamArn, shard.shardId()).stream() + .map(DynamoDbStreamRecord::getSequenceNumber).toList()); + } + // Both shards start at the stream's first sequence number, but only one holds that record. + String holder = sequencesByShard.entrySet().stream() + .filter(entry -> entry.getValue().contains("000000000000000000001")).findFirst().orElseThrow().getKey(); + String other = sequencesByShard.keySet().stream().filter(shard -> !shard.equals(holder)).findFirst() + .orElseThrow(); + assertTrue(!sequencesByShard.get(other).isEmpty(), "both shards hold records: " + sequencesByShard); + + for (String foreign : List.of("000000000000000000000", "000000000000000000099", "000000000000000000001", + sequencesByShard.get(holder).getLast())) { + AwsException invalid = assertThrows(AwsException.class, + () -> streams.getShardIterator(streamArn, other, "AT_SEQUENCE_NUMBER", foreign), foreign); + assertEquals("ValidationException", invalid.getErrorCode()); + assertEquals("Invalid SequenceNumber for the shard", invalid.getMessage()); + } + for (String own : List.of(sequencesByShard.get(other).getFirst(), sequencesByShard.get(other).getLast())) { + String at = streams.getShardIterator(streamArn, other, "AT_SEQUENCE_NUMBER", own); + assertEquals(own, streams.getRecords(at, 1).records().getFirst().getSequenceNumber()); + } + String startOfHolder = streams.getShardIterator(streamArn, holder, "AT_SEQUENCE_NUMBER", + "000000000000000000001"); + assertEquals("000000000000000000001", + streams.getRecords(startOfHolder, 1).records().getFirst().getSequenceNumber()); + } + + @Test + void aLimitBelowOneIsRefusedAsAwsDoes() { + DynamoDbStreamService streams = streams(Settings.DEFAULTS); + String streamArn = enable(streams); + String iterator = streams.getShardIterator(streamArn, DynamoDbStreamService.SHARD_ID, "TRIM_HORIZON", null); + NativeDynamoDbStreamsJsonHandler handler = handler(streams); + + for (int limit : new int[]{0, -1}) { + for (Runnable call : List.of( + () -> streams.describeShards(streamArn, null, limit), + () -> streams.getRecords(iterator, limit), + () -> handler.handle("DescribeStream", + mapper.createObjectNode().put("StreamArn", streamArn).put("Limit", limit), REGION))) { + AwsException invalid = assertThrows(AwsException.class, call::run); + assertEquals("ValidationException", invalid.getErrorCode()); + assertEquals("1 validation error detected: Value at 'limit' failed to satisfy constraint: " + + "Member must have value greater than or equal to 1", invalid.getMessage()); + } + } + } + + @Test + void aSequenceIteratorWithoutASequenceNumberIsRefusedAsAwsDoes() { + DynamoDbStreamService streams = streams(Settings.DEFAULTS); + String streamArn = enable(streams); + + AwsException missing = assertThrows(AwsException.class, () -> streams.getShardIterator(streamArn, + DynamoDbStreamService.SHARD_ID, "AT_SEQUENCE_NUMBER", null)); + + assertEquals("ValidationException", missing.getErrorCode()); + assertEquals("One or more parameter values were invalid: SequenceNumber cannot be null", missing.getMessage()); + } + + @Test + void anItemsChangesStayInOrderOnTheShardItsPartitionKeyPicks() { + DynamoDbStreamService streams = streams(new Settings(4, null, false, false)); + String streamArn = enable(streams); + for (int round = 0; round < 3; round++) { + for (int key = 0; key < 12; key++) { + put(streams, "item-" + key); + } + } + + List shards = streams.describeShards(streamArn, null, null).shards(); + assertEquals(List.of("shardId-0000000001-00000000001", "shardId-0000000001-00000000002", + "shardId-0000000001-00000000003", "shardId-0000000001-00000000004"), + shards.stream().map(ShardDescription::shardId).toList()); + Map shardOfKey = new HashMap<>(); + Set used = new HashSet<>(); + for (ShardDescription shard : shards) { + List records = readAll(streams, streamArn, shard.shardId()); + for (int i = 1; i < records.size(); i++) { + assertTrue(records.get(i - 1).getSequenceNumber().compareTo(records.get(i).getSequenceNumber()) < 0); + } + for (String key : keys(records)) { + String earlier = shardOfKey.put(key, shard.shardId()); + assertTrue(earlier == null || earlier.equals(shard.shardId()), key + " is on two shards"); + used.add(shard.shardId()); + } + } + assertEquals(12, shardOfKey.size()); + assertTrue(used.size() > 1, "the items spread over the shards: " + shardOfKey); + } + + @Test + void aShardTheStreamDoesNotHaveIsNotFound() { + DynamoDbStreamService streams = streams(Settings.DEFAULTS); + String streamArn = enable(streams); + + AwsException missing = assertThrows(AwsException.class, () -> streams.getShardIterator(streamArn, + "shardId-0000000009-00000000001", "TRIM_HORIZON", null)); + + assertEquals("ResourceNotFoundException", missing.getErrorCode()); + assertEquals("Requested resource not found: Shard does not exist", missing.getMessage()); + } + + @Test + void anOpenShardRollsOverToAChildThatNamesItAsItsParent() { + DynamoDbStreamService streams = streams(new Settings(1, Duration.ofHours(1), false, false)); + String streamArn = enable(streams); + put(streams, "before"); + String parentIterator = streams.getShardIterator(streamArn, DynamoDbStreamService.SHARD_ID, + "TRIM_HORIZON", null); + + clock.advance(Duration.ofHours(1)); + put(streams, "after"); + + String child = "shardId-0000000002-00000000001"; + assertEquals(List.of( + new ShardDescription(DynamoDbStreamService.SHARD_ID, null, "000000000000000000001", + "000000000000000000001"), + new ShardDescription(child, DynamoDbStreamService.SHARD_ID, "000000000000000000002", null)), + streams.describeShards(streamArn, null, null).shards()); + DynamoDbStreamService.GetRecordsResult parentPage = streams.getRecords(parentIterator, 10); + assertEquals(List.of("before"), keys(parentPage.records())); + DynamoDbStreamService.GetRecordsResult end = streams.getRecords(parentPage.nextShardIterator(), 10); + assertEquals(List.of(), end.records()); + assertNull(end.nextShardIterator(), "a closed shard read to its end has no next iterator"); + assertEquals(List.of("after"), keys(readAll(streams, streamArn, child))); + } + + @Test + void disablingAStreamClosesItsShardsWhichStayReadable() { + DynamoDbStreamService streams = streams(Settings.DEFAULTS); + String streamArn = enable(streams); + put(streams, "a"); + put(streams, "b"); + + streams.disableStream(table.getTableArn()); + + assertEquals(List.of(new ShardDescription(DynamoDbStreamService.SHARD_ID, null, "000000000000000000001", + "000000000000000000002")), streams.describeShards(streamArn, null, null).shards()); + assertEquals(List.of("a", "b"), keys(readAll(streams, streamArn, DynamoDbStreamService.SHARD_ID))); + } + + @Test + void aClosedShardIsDroppedTwentyFourHoursAfterItClosesWhenRetentionIsOn() { + DynamoDbStreamService streams = streams(new Settings(1, Duration.ofHours(1), false, true)); + String streamArn = enable(streams); + put(streams, "a"); + clock.advance(Duration.ofHours(1)); + put(streams, "b"); + + clock.advance(Duration.ofMinutes(30)); + assertEquals(2, streams.describeShards(streamArn, null, null).shards().size()); + clock.advance(Duration.ofHours(24)); + + List shards = streams.describeShards(streamArn, null, null).shards(); + assertEquals(DynamoDbStreamService.SHARD_ID, shards.getFirst().parentShardId(), + "the child keeps naming the parent it replaced"); + assertTrue(shards.stream().noneMatch(shard -> DynamoDbStreamService.SHARD_ID.equals(shard.shardId()))); + } + + @Test + void anIdleStreamThatRollsOverKeepsTwoGenerationsOfShards() { + DynamoDbStreamService streams = streams(new Settings(1, Duration.ofHours(1), false, false)); + String streamArn = enable(streams); + + for (int hour = 1; hour <= 5; hour++) { + clock.advance(Duration.ofHours(1)); + streams.describeShards(streamArn, null, null); + } + + assertEquals(List.of( + new ShardDescription("shardId-0000000005-00000000001", "shardId-0000000004-00000000001", + "000000000000000000001", "000000000000000000001"), + new ShardDescription("shardId-0000000006-00000000001", "shardId-0000000005-00000000001", + "000000000000000000001", null)), + streams.describeShards(streamArn, null, null).shards()); + } + + @Test + void aClosedShardStaysListedWhileItHoldsRecords() { + DynamoDbStreamService streams = streams(new Settings(1, Duration.ofHours(1), false, false)); + String streamArn = enable(streams); + put(streams, "kept"); + for (int hour = 1; hour <= 3; hour++) { + clock.advance(Duration.ofHours(1)); + streams.describeShards(streamArn, null, null); + } + + List shards = streams.describeShards(streamArn, null, null).shards(); + assertEquals(DynamoDbStreamService.SHARD_ID, shards.getFirst().shardId()); + assertEquals(List.of("kept"), keys(readAll(streams, streamArn, DynamoDbStreamService.SHARD_ID))); + + for (int i = 0; i < DynamoDbStreamService.MAX_RECORDS; i++) { + put(streams, "newer-" + i); + } + assertTrue(streams.describeShards(streamArn, null, null).shards().stream() + .noneMatch(shard -> DynamoDbStreamService.SHARD_ID.equals(shard.shardId())), + "once trimming empties it, the closed shard goes"); + } + + @Test + void theRecordCapTrimsTheStreamsOldestRecordWhicheverShardHoldsIt() { + DynamoDbStreamService streams = streams(new Settings(2, null, false, false)); + String streamArn = enable(streams); + put(streams, "first"); + String holder = null; + Map horizons = new HashMap<>(); + for (ShardDescription shard : streams.describeShards(streamArn, null, null).shards()) { + horizons.put(shard.shardId(), streams.getShardIterator(streamArn, shard.shardId(), "TRIM_HORIZON", null)); + if (!readAll(streams, streamArn, shard.shardId()).isEmpty()) { + holder = shard.shardId(); + } + } + + for (int i = 0; i < DynamoDbStreamService.MAX_RECORDS; i++) { + put(streams, "next-" + i); + } + + int retained = 0; + for (Map.Entry horizon : horizons.entrySet()) { + if (horizon.getKey().equals(holder)) { + AwsException trimmed = assertThrows(AwsException.class, () -> streams.getRecords(horizon.getValue(), + 10)); + assertEquals("TrimmedDataAccessException", trimmed.getErrorCode()); + } else { + assertEquals(10, streams.getRecords(horizon.getValue(), 10).records().size(), + "the shard that lost nothing reads from its start"); + } + retained += readAll(streams, streamArn, horizon.getKey()).size(); + } + assertEquals(DynamoDbStreamService.MAX_RECORDS, retained); + } + + @Test + void describeStreamPagesThroughTheShards() { + DynamoDbStreamService streams = streams(new Settings(3, null, false, false)); + String streamArn = enable(streams); + + DynamoDbStreamService.ShardsPage first = streams.describeShards(streamArn, null, 2); + DynamoDbStreamService.ShardsPage second = streams.describeShards(streamArn, first.lastEvaluatedShardId(), 2); + + assertEquals(List.of("shardId-0000000001-00000000001", "shardId-0000000001-00000000002"), + first.shards().stream().map(ShardDescription::shardId).toList()); + assertEquals("shardId-0000000001-00000000002", first.lastEvaluatedShardId()); + assertEquals(List.of("shardId-0000000001-00000000003"), + second.shards().stream().map(ShardDescription::shardId).toList()); + assertNull(second.lastEvaluatedShardId()); + } + + @Test + void flocisOwnStreamReaderReadsTheParentToItsEndAndThenTheChild() throws Exception { + DynamoDbStreamService streams = streams(new Settings(1, Duration.ofHours(1), false, false)); + String streamArn = enable(streams); + NativeDynamoDbStreamsJsonHandler handler = handler(streams); + DynamoDbStreamReader reader = new DynamoDbApiStreamReader(call -> { + Response response = handler.handle(call.action(), call.body(), call.scope().region()); + return new DynamoDbOperations.Reply(response.getStatus(), (JsonNode) response.getEntity(), Map.of()); + }, DynamoDbStreamReader.CheckpointLifetime.PROCESS); + DynamoDbStreamReader.Stream stream = DynamoDbStreamReader.Stream.of(streamArn); + put(streams, "parent-1"); + put(streams, "parent-2"); + clock.advance(Duration.ofHours(1)); + put(streams, "child-1"); + + List shards = reader.shards(stream); + assertEquals(DynamoDbStreamService.SHARD_ID, shards.get(1).parentShardId()); + assertNotNull(shards.get(0).endingSequenceNumber()); + assertEquals(List.of(shards.get(0)), DynamoDbStreamReader.readable(shards, Set.of()), + "the child waits for its parent"); + + DynamoDbStreamReader.RecordsPage parent = reader.readAfter(stream, shards.get(0).shardId(), null, 10); + assertEquals(2, parent.records().size()); + DynamoDbStreamReader.RecordsPage end = reader.readAfter(stream, shards.get(0).shardId(), + parent.records().getLast().sequenceNumber(), 10); + assertTrue(end.closed(), "the parent reads as finished"); + assertEquals(List.of(shards.get(1)), DynamoDbStreamReader.readable(shards, Set.of(shards.get(0).shardId()))); + assertEquals(1, reader.readAfter(stream, shards.get(1).shardId(), null, 10).records().size()); + } + + private DynamoDbStreamService streams(Settings settings) { + return new DynamoDbStreamService(mapper, new InMemoryStorage<>(), settings, clock); + } + + private NativeDynamoDbStreamsJsonHandler handler(DynamoDbStreamService streams) { + DynamoDbService tables = mock(DynamoDbService.class); + when(tables.describeTable(any(), any())).thenReturn(table); + return new NativeDynamoDbStreamsJsonHandler(streams, tables, new RegionResolver(REGION, ACCOUNT), mapper); + } + + private String enable(DynamoDbStreamService streams) { + return streams.enableStream(table.getTableName(), table.getTableArn(), "KEYS_ONLY", REGION).getStreamArn(); + } + + private void put(DynamoDbStreamService streams, String key) { + streams.captureEvent("INSERT", null, mapper.createObjectNode().set("pk", mapper.createObjectNode().put("S", key)), + table, REGION); + } + + /** Every record the shard holds, from its trim horizon to its tip. */ + private static List readAll(DynamoDbStreamService streams, String streamArn, + String shardId) { + List records = new ArrayList<>(); + String iterator = streams.getShardIterator(streamArn, shardId, "TRIM_HORIZON", null); + while (iterator != null) { + DynamoDbStreamService.GetRecordsResult page = streams.getRecords(iterator, 100); + if (page.records().isEmpty()) { + break; + } + records.addAll(page.records()); + iterator = page.nextShardIterator(); + } + return records; + } + + private static List keys(List records) { + return records.stream().map(record -> record.getKeys().path("pk").path("S").asText()).toList(); + } + + /** A clock the test moves by hand. */ + private static final class MovableClock extends Clock { + private Instant now; + + MovableClock(Instant start) { + now = start; + } + + void advance(Duration by) { + now = now.plus(by); + } + + @Override + public ZoneId getZone() { + return ZoneOffset.UTC; + } + + @Override + public Clock withZone(ZoneId zone) { + return this; + } + + @Override + public Instant instant() { + return now; + } + } +} diff --git a/src/test/java/io/floci/aws/services/dynamodb/DynamoDbStreamServiceTest.java b/src/test/java/io/floci/aws/services/dynamodb/DynamoDbStreamServiceTest.java index 87059c4b23..680d69b66b 100644 --- a/src/test/java/io/floci/aws/services/dynamodb/DynamoDbStreamServiceTest.java +++ b/src/test/java/io/floci/aws/services/dynamodb/DynamoDbStreamServiceTest.java @@ -89,7 +89,7 @@ class DynamoDbStreamServiceTest { service.captureEvent("INSERT", null, item, table, "us-east-1"); String iterator = service.getShardIterator( - sd.getStreamArn(), "shardId-000000000000", "TRIM_HORIZON", null); + sd.getStreamArn(), DynamoDbStreamService.SHARD_ID, "TRIM_HORIZON", null); List records = service.getRecords(iterator, 10).records(); assertEquals(1, records.size()); 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 31cedc34b1..3038ac9b14 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 @@ -70,7 +70,9 @@ class DynamoDbNativeBackendTest { stores.add(store); return store; }); - DynamoDbStreamService streams = new DynamoDbStreamService(mapper, storageFactory); + EmulatorConfig streamConfig = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS); + when(streamConfig.services().dynamodb().streamShardCount()).thenReturn(1); + 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)); NativeDynamoDbTableService tables = new NativeDynamoDbTableService(service, streams, mock(KinesisService.class));