diff --git a/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbPointInTimeRecovery.java b/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbPointInTimeRecovery.java index adcd128114..43a4e880fb 100644 --- a/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbPointInTimeRecovery.java +++ b/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbPointInTimeRecovery.java @@ -39,6 +39,8 @@ final class DynamoDbPointInTimeRecovery { private final List list = new ArrayList<>(); private long nextSequence; private boolean dropped; + // itemsAt leaves out a change recorded after it read the list, so that change must fall after its time. + private Instant notBefore = Instant.MIN; } private final StorageBackend store; @@ -97,7 +99,7 @@ final class DynamoDbPointInTimeRecovery { if (changes.dropped || !table.isPointInTimeRecoveryEnabled()) { return; } - Instant now = clock.instant().truncatedTo(ChronoUnit.MILLIS); + Instant now = later(clock.instant().truncatedTo(ChronoUnit.MILLIS), changes.notBefore); PointInTimeChange change = new PointInTimeChange(changes.nextSequence++, now, itemKey, oldItem != null ? oldItem.deepCopy() : null); changes.list.add(change); @@ -121,25 +123,44 @@ final class DynamoDbPointInTimeRecovery { /** * An item changed after {@code time} takes the value that its first change after it replaced. - * Writers record a change before they write the item, so the live items are copied first. + * Writers record a change before they write the item. So the live items are copied first, and an + * item with no change after {@code time} is read again under {@code underItemLock}, as in + * {@link #changesBetween}. */ - List itemsAt(String accountId, String storageKey, Map liveItems, Instant time) { + List itemsAt(String accountId, String storageKey, Map liveItems, Instant time, + BiFunction, JsonNode> underItemLock) { Map items = new HashMap<>(liveItems); - Changes changes = changesByTable.get(key(accountId, storageKey)); - if (changes != null) { - Set undone = new HashSet<>(); - synchronized (changes) { - for (PointInTimeChange change : changes.list) { - String itemKey = change.getItemKey(); - if (!change.getTime().isAfter(time) || !undone.add(itemKey)) { - continue; - } - if (change.getOldItem() == null) { - items.remove(itemKey); - } else { - items.put(itemKey, change.getOldItem()); - } + Changes changes = changesByTable.computeIfAbsent(key(accountId, storageKey), ignored -> new Changes()); + Set undone = new HashSet<>(); + Set written = new HashSet<>(); + long seen; + synchronized (changes) { + seen = changes.nextSequence; + changes.notBefore = later(changes.notBefore, time.truncatedTo(ChronoUnit.MILLIS).plusMillis(1)); + for (PointInTimeChange change : changes.list) { + String itemKey = change.getItemKey(); + if (!change.getTime().isAfter(time)) { + written.add(itemKey); + continue; } + if (!undone.add(itemKey)) { + continue; + } + if (change.getOldItem() == null) { + items.remove(itemKey); + } else { + items.put(itemKey, change.getOldItem()); + } + } + } + written.removeAll(undone); + ValuesBefore valuesBefore = new ValuesBefore(changes, seen, liveItems); + for (String itemKey : written) { + JsonNode item = underItemLock.apply(itemKey, () -> valuesBefore.of(itemKey)); + if (item == null) { + items.remove(itemKey); + } else { + items.put(itemKey, item); } } return new ArrayList<>(items.values()); @@ -179,24 +200,42 @@ final class DynamoDbPointInTimeRecovery { } } List result = new ArrayList<>(); + ValuesBefore valuesBefore = new ValuesBefore(changes, seen, liveItems); before.forEach((itemKey, oldItem) -> { JsonNode newItem = after.containsKey(itemKey) ? after.get(itemKey) - : underItemLock.apply(itemKey, () -> valueBefore(changes, itemKey, seen, liveItems)); + : underItemLock.apply(itemKey, () -> valuesBefore.of(itemKey)); result.add(new ItemChange(oldItem, newItem, lastWrites.get(itemKey))); }); return result; } - /** The value that the first change of the item from sequence {@code since} replaced, or the live item. */ - private static JsonNode valueBefore(Changes changes, String itemKey, long since, Map liveItems) { - synchronized (changes) { - JsonNode value = liveItems.get(itemKey); - for (int i = changes.list.size() - 1; 0 <= i && since <= changes.list.get(i).getSequence(); i--) { - if (changes.list.get(i).getItemKey().equals(itemKey)) { - value = changes.list.get(i).getOldItem(); + /** The value that the first change of each item from sequence {@code since} replaced, or the live item. */ + private static final class ValuesBefore { + private final Changes changes; + private final Map liveItems; + private final Map replaced = new HashMap<>(); + private long read; + + ValuesBefore(Changes changes, long since, Map liveItems) { + this.changes = changes; + this.liveItems = liveItems; + this.read = since; + } + + JsonNode of(String itemKey) { + synchronized (changes) { + int i = changes.list.size(); + while (0 < i && read <= changes.list.get(i - 1).getSequence()) { + i--; } + for (PointInTimeChange change : changes.list.subList(i, changes.list.size())) { + if (!replaced.containsKey(change.getItemKey())) { + replaced.put(change.getItemKey(), change.getOldItem()); + } + } + read = changes.nextSequence; + return replaced.containsKey(itemKey) ? replaced.get(itemKey) : liveItems.get(itemKey); } - return value; } } diff --git a/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbService.java b/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbService.java index 42591bdece..689b7ff1a2 100644 --- a/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbService.java +++ b/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbService.java @@ -3002,7 +3002,8 @@ public class DynamoDbService { } ConcurrentSkipListMap liveItems = itemsByTable.get(scopedItemsKey(storageKey)); List items = pointInTimeRecovery.itemsAt(accountId, storageKey, - liveItems != null ? liveItems : Map.of(), time); + liveItems != null ? liveItems : Map.of(), time, + (itemKey, read) -> withItemLock(storageKey, itemKey, read)); return new PointInTimeState(snapshotOf(table), items, time); } @@ -5095,7 +5096,8 @@ public class DynamoDbService { storageKey, liveItems, exportFromTime, exportToTime, (itemKey, read) -> withItemLock(storageKey, itemKey, read)), table, "NEW_IMAGE".equals(incremental.viewType())) - : pointInTimeRecovery.itemsAt(regionResolver.getAccountId(), storageKey, liveItems, time); + : pointInTimeRecovery.itemsAt(regionResolver.getAccountId(), storageKey, liveItems, time, + (itemKey, read) -> withItemLock(storageKey, itemKey, read)); // The worker gets its own copy so the object serialized into this response never // changes underneath the handler, and the request account so its writes land there. diff --git a/src/test/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbPointInTimeRecoveryTest.java b/src/test/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbPointInTimeRecoveryTest.java index 9cacd89d1c..5880901e4b 100644 --- a/src/test/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbPointInTimeRecoveryTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbPointInTimeRecoveryTest.java @@ -13,8 +13,10 @@ import org.junit.jupiter.api.Test; import java.time.Duration; import java.time.Instant; +import java.util.HashSet; import java.util.List; import java.util.Map; +import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -69,6 +71,95 @@ class DynamoDbPointInTimeRecoveryTest { assertEquals(item("B"), changes.getFirst().newItem()); } + @Test + void itemsAtWaitsForAWriteThatIsRecordedButNotYetWritten() { + table.setPointInTimeRecoveryEnabled(true); + live.put("k", item("A")); + recovery.recordItem(ACCOUNT, TABLE_KEY, table, "k", item("A")); + + List items = recovery.itemsAt(ACCOUNT, TABLE_KEY, live, clock.instant(), + (itemKey, read) -> { + live.put(itemKey, item("B")); + return read.get(); + }); + + assertEquals(List.of(item("B")), items); + } + + @Test + void itemsAtWaitsForADeleteThatIsRecordedButNotYetDone() { + table.setPointInTimeRecoveryEnabled(true); + live.put("k", item("A")); + recovery.recordItem(ACCOUNT, TABLE_KEY, table, "k", item("A")); + + List items = recovery.itemsAt(ACCOUNT, TABLE_KEY, live, clock.instant(), + (itemKey, read) -> { + live.remove(itemKey); + return read.get(); + }); + + assertEquals(List.of(), items); + } + + @Test + void itemsAtLeavesOutAWriteAfterTheTimeThatFinishesBeforeTheItemIsRead() { + table.setPointInTimeRecoveryEnabled(true); + recovery.recordItem(ACCOUNT, TABLE_KEY, table, "k", null); + live.put("k", item("A")); + Instant time = clock.instant(); + + List items = recovery.itemsAt(ACCOUNT, TABLE_KEY, live, time, + (itemKey, read) -> { + clock.advance(Duration.ofSeconds(1)); + recovery.recordItem(ACCOUNT, TABLE_KEY, table, itemKey, live.get(itemKey)); + live.put(itemKey, item("B")); + return read.get(); + }); + + assertEquals(List.of(item("A")), items); + } + + @Test + void itemsAtLeavesOutAWriteAfterTheTimeToAnItemThatItReadsLater() { + table.setPointInTimeRecoveryEnabled(true); + for (String itemKey : List.of("k1", "k2")) { + recovery.recordItem(ACCOUNT, TABLE_KEY, table, itemKey, null); + live.put(itemKey, item("A" + itemKey)); + } + Instant time = clock.instant(); + Set reads = new HashSet<>(); + + List items = recovery.itemsAt(ACCOUNT, TABLE_KEY, live, time, + (itemKey, read) -> { + if (reads.isEmpty()) { + String other = "k1".equals(itemKey) ? "k2" : "k1"; + clock.advance(Duration.ofSeconds(1)); + recovery.recordItem(ACCOUNT, TABLE_KEY, table, other, live.get(other)); + live.put(other, item("B")); + } + reads.add(itemKey); + return read.get(); + }); + + assertEquals(Set.of("k1", "k2"), reads); + assertEquals(Set.of(item("Ak1"), item("Ak2")), Set.copyOf(items)); + } + + @Test + void itemsAtGivesTheSameItemsLaterWhenAWriteFollowsInTheSameMillisecond() { + table.setPointInTimeRecoveryEnabled(true); + // MutableClock moves on 1 ms at each read, so the write below reads this time. + Instant time = clock.instant().plusMillis(1); + + List first = recovery.itemsAt(ACCOUNT, TABLE_KEY, live, time, (itemKey, read) -> read.get()); + recovery.recordItem(ACCOUNT, TABLE_KEY, table, "k", null); + live.put("k", item("A")); + List later = recovery.itemsAt(ACCOUNT, TABLE_KEY, live, time, (itemKey, read) -> read.get()); + + assertEquals(List.of(), first); + assertEquals(first, later); + } + private static JsonNode item(String value) { ObjectNode item = MAPPER.createObjectNode(); item.putObject("pk").put("S", "k");