mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(dynamodb): opt-in per-table item files, split into shards (#6303)
* feat(dynamodb): opt-in per-table item files, split into shards Every table's items live in one dynamodb-items.json, and any item write rewrites all of them. A small table that changes often, such as a node heartbeat table, then keeps rewriting every large table beside it. Add an opt-in item layout. With item-layout: per-table, items are stored under dynamodb-items/ as item-shards files per table, and a write saves only the items it touched: - persistent rewrites the one shard file that holds the item before the write returns, and fails the write when that file cannot be written - hybrid marks the shard dirty and writes dirty shards on the flush interval; an explicit flush or shutdown reports shards it could not write - wal keeps the single-file layout for now and logs a warning The default, single-file, is unchanged. On first start, an existing dynamodb-items.json, or a wal snapshot and log, is migrated through a staging directory moved in place in one step and then renamed .migrated; a failed migration stops startup and leaves the old files untouched. DynamoDbService writes single items through the new MapEntryWriter, and the TTL sweeper removes each item under its item lock. Part of #6293 * test(storage): skip read-only directory tests where POSIX permissions are missing
This commit is contained in:
1 parent
9eaa4404a4
commit
7635345474
17 files changed
+2327
-20
No files matched your search
+462
@@ -0,0 +1,462 @@
|
||||
package io.github.hectorvent.floci.core.storage;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.attribute.FileTime;
|
||||
import java.nio.file.attribute.PosixFilePermission;
|
||||
import java.nio.file.attribute.PosixFilePermissions;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.junit.jupiter.api.Assumptions.assumeFalse;
|
||||
|
||||
class PartitionedFileStorageTest {
|
||||
|
||||
private static final FileTime LONG_AGO = FileTime.from(Instant.parse("2020-01-01T00:00:00Z"));
|
||||
|
||||
@TempDir
|
||||
Path tempDir;
|
||||
|
||||
private final List<PartitionedFileStorage<String>> opened = new ArrayList<>();
|
||||
|
||||
@AfterEach
|
||||
void tearDown() {
|
||||
opened.forEach(PartitionedFileStorage::shutdown);
|
||||
}
|
||||
|
||||
private PartitionedFileStorage<String> open(PartitionedFileStorage.Mode mode) {
|
||||
return open(1, mode);
|
||||
}
|
||||
|
||||
private PartitionedFileStorage<String> open(int shards, PartitionedFileStorage.Mode mode) {
|
||||
PartitionedFileStorage<String> storage = new PartitionedFileStorage<>(tempDir.resolve("items"),
|
||||
tempDir.resolve("items.json"), String.class, shards, mode, 60_000);
|
||||
storage.load();
|
||||
opened.add(storage);
|
||||
return storage;
|
||||
}
|
||||
|
||||
private Set<String> fileNames() throws Exception {
|
||||
try (Stream<Path> files = Files.list(tempDir.resolve("items"))) {
|
||||
return files.map(f -> f.getFileName().toString()).collect(Collectors.toSet());
|
||||
}
|
||||
}
|
||||
|
||||
private static Map<String, String> entries(int count) {
|
||||
Map<String, String> entries = new HashMap<>();
|
||||
for (int i = 0; i < count; i++) {
|
||||
entries.put("entry-" + i, "value-" + i);
|
||||
}
|
||||
return entries;
|
||||
}
|
||||
|
||||
@Test
|
||||
void anEntryWriteRewritesOnlyItsOwnShardFile() throws Exception {
|
||||
PartitionedFileStorage<String> storage = open(8, PartitionedFileStorage.Mode.SYNC);
|
||||
storage.put("big", entries(200));
|
||||
assertEquals(8, fileNames().size());
|
||||
for (String name : fileNames()) {
|
||||
Files.setLastModifiedTime(tempDir.resolve("items").resolve(name), LONG_AGO);
|
||||
}
|
||||
Path touched = storage.fileFor("big", "entry-7");
|
||||
|
||||
storage.putEntry("big", "entry-7", "changed");
|
||||
storage.removeEntry("big", "entry-7");
|
||||
storage.putEntry("big", "entry-7", "changed-again");
|
||||
|
||||
for (String name : fileNames()) {
|
||||
Path file = tempDir.resolve("items").resolve(name);
|
||||
assertEquals(file.equals(touched), !LONG_AGO.equals(Files.getLastModifiedTime(file)), name);
|
||||
}
|
||||
Map<String, String> expected = entries(200);
|
||||
expected.put("entry-7", "changed-again");
|
||||
assertEquals(expected, open(8, PartitionedFileStorage.Mode.SYNC).get("big").orElseThrow());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anEmptyShardHasNoFile() throws Exception {
|
||||
PartitionedFileStorage<String> storage = open(16, PartitionedFileStorage.Mode.SYNC);
|
||||
storage.putEntry("small", "only", "1");
|
||||
assertEquals(Set.of(storage.fileFor("small", "only").getFileName().toString()), fileNames());
|
||||
|
||||
storage.removeEntry("small", "only");
|
||||
|
||||
assertTrue(fileNames().isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deletingAKeyRemovesEveryShardFile() throws Exception {
|
||||
PartitionedFileStorage<String> storage = open(4, PartitionedFileStorage.Mode.PERIODIC);
|
||||
storage.put("gone", entries(50));
|
||||
storage.put("kept", entries(1));
|
||||
storage.flush();
|
||||
Set<String> keptFiles = Set.of(storage.fileFor("kept", "entry-0").getFileName().toString());
|
||||
|
||||
storage.delete("gone");
|
||||
storage.flush();
|
||||
|
||||
assertEquals(keptFiles, fileNames());
|
||||
}
|
||||
|
||||
@Test
|
||||
void changingTheShardCountKeepsEveryEntryAndDropsTheOldFiles() throws Exception {
|
||||
open(1, PartitionedFileStorage.Mode.SYNC).put("big", entries(100));
|
||||
|
||||
PartitionedFileStorage<String> four = open(4, PartitionedFileStorage.Mode.SYNC);
|
||||
assertEquals(entries(100), four.get("big").orElseThrow());
|
||||
assertEquals(4, fileNames().size());
|
||||
assertTrue(fileNames().stream().allMatch(name -> name.contains("-of-4")), fileNames().toString());
|
||||
|
||||
PartitionedFileStorage<String> two = open(2, PartitionedFileStorage.Mode.PERIODIC);
|
||||
assertEquals(entries(100), two.get("big").orElseThrow());
|
||||
assertEquals(2, fileNames().size());
|
||||
assertTrue(fileNames().stream().allMatch(name -> name.contains("-of-2")), fileNames().toString());
|
||||
assertEquals(entries(100), open(2, PartitionedFileStorage.Mode.SYNC).get("big").orElseThrow());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aShardCountBelowOneIsRejected() {
|
||||
assertThrows(IllegalArgumentException.class, () -> new PartitionedFileStorage<>(tempDir.resolve("items"),
|
||||
(Path) null, String.class, 0, PartitionedFileStorage.Mode.SYNC, 60_000));
|
||||
}
|
||||
|
||||
@Test
|
||||
void syncEntryWriteRewritesOnlyItsOwnKeysFile() throws Exception {
|
||||
PartitionedFileStorage<String> storage = open(PartitionedFileStorage.Mode.SYNC);
|
||||
storage.put("big", Map.of("a", "1", "b", "2"));
|
||||
storage.putEntry("busy", "node-1", "beat-1");
|
||||
Path bigFile = storage.fileFor("big");
|
||||
Files.setLastModifiedTime(bigFile, LONG_AGO);
|
||||
|
||||
storage.putEntry("busy", "node-1", "beat-2");
|
||||
storage.removeEntry("busy", "node-1");
|
||||
storage.putEntry("busy", "node-2", "beat-1");
|
||||
|
||||
assertEquals(LONG_AGO, Files.getLastModifiedTime(bigFile));
|
||||
PartitionedFileStorage<String> reloaded = open(PartitionedFileStorage.Mode.SYNC);
|
||||
assertEquals(Map.of("node-2", "beat-1"), reloaded.get("busy").orElseThrow());
|
||||
assertEquals(Map.of("a", "1", "b", "2"), reloaded.get("big").orElseThrow());
|
||||
}
|
||||
|
||||
@Test
|
||||
void periodicStoreWritesOnlyDirtyKeysOnFlush() throws Exception {
|
||||
PartitionedFileStorage<String> storage = open(PartitionedFileStorage.Mode.PERIODIC);
|
||||
storage.put("big", Map.of("a", "1"));
|
||||
storage.putEntry("busy", "node-1", "beat-1");
|
||||
assertFalse(Files.exists(storage.fileFor("big")), "a periodic store writes nothing before a flush");
|
||||
|
||||
storage.flush();
|
||||
Path bigFile = storage.fileFor("big");
|
||||
Files.setLastModifiedTime(bigFile, LONG_AGO);
|
||||
storage.putEntry("busy", "node-1", "beat-2");
|
||||
storage.flush();
|
||||
|
||||
assertEquals(LONG_AGO, Files.getLastModifiedTime(bigFile));
|
||||
assertEquals(Map.of("node-1", "beat-2"), open(PartitionedFileStorage.Mode.PERIODIC).get("busy").orElseThrow());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aFlushThatFailsIsRetriedOnTheNextFlush() throws Exception {
|
||||
PartitionedFileStorage<String> storage = open(PartitionedFileStorage.Mode.PERIODIC);
|
||||
storage.putEntry("other", "a", "1");
|
||||
storage.flush();
|
||||
storage.putEntry("busy", "node-1", "beat-1");
|
||||
Path directory = tempDir.resolve("items");
|
||||
StorageTestFiles.assumePosixPermissions(directory);
|
||||
Set<PosixFilePermission> original = Files.getPosixFilePermissions(directory);
|
||||
Files.setPosixFilePermissions(directory, PosixFilePermissions.fromString("r-xr-xr-x"));
|
||||
try {
|
||||
// A root user writes through the read-only mode, so there is nothing to test there.
|
||||
assumeFalse(Files.isWritable(directory), "the directory stays writable for this user");
|
||||
assertThrows(UncheckedIOException.class, storage::flush, "a failed flush is reported");
|
||||
assertFalse(Files.exists(storage.fileFor("busy")));
|
||||
} finally {
|
||||
Files.setPosixFilePermissions(directory, original);
|
||||
}
|
||||
|
||||
storage.flush();
|
||||
|
||||
assertEquals(Map.of("node-1", "beat-1"), open(PartitionedFileStorage.Mode.PERIODIC).get("busy").orElseThrow());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSyncWriteThatCannotReachDiskFailsAndIsWrittenByTheNextFlush() throws Exception {
|
||||
PartitionedFileStorage<String> storage = open(PartitionedFileStorage.Mode.SYNC);
|
||||
Path file = storage.fileFor("table");
|
||||
// A non-empty directory where the write's temporary file goes makes that write fail.
|
||||
Path blocker = file.resolveSibling(file.getFileName() + ".tmp");
|
||||
Files.createDirectories(blocker);
|
||||
Files.writeString(blocker.resolve("child"), "x");
|
||||
|
||||
assertThrows(UncheckedIOException.class, () -> storage.putEntry("table", "a", "1"));
|
||||
|
||||
assertEquals(Map.of("a", "1"), storage.get("table").orElseThrow(), "the change stays in memory");
|
||||
Files.delete(blocker.resolve("child"));
|
||||
Files.delete(blocker);
|
||||
storage.flush();
|
||||
assertEquals(Map.of("a", "1"), open(PartitionedFileStorage.Mode.SYNC).get("table").orElseThrow());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deletingAKeyRemovesItsFile() {
|
||||
PartitionedFileStorage<String> storage = open(PartitionedFileStorage.Mode.SYNC);
|
||||
storage.put("gone", Map.of("a", "1"));
|
||||
Path file = storage.fileFor("gone");
|
||||
assertTrue(Files.exists(file));
|
||||
|
||||
storage.delete("gone");
|
||||
|
||||
assertFalse(Files.exists(file));
|
||||
assertTrue(open(PartitionedFileStorage.Mode.SYNC).get("gone").isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void removingAnEntryOfAMissingKeyDoesNotCreateIt() {
|
||||
PartitionedFileStorage<String> storage = open(PartitionedFileStorage.Mode.SYNC);
|
||||
storage.removeEntry("missing", "a");
|
||||
assertTrue(storage.get("missing").isEmpty());
|
||||
assertFalse(Files.exists(storage.fileFor("missing")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void keysOfAnyLengthAndCharacterMapToSafeDistinctFiles() {
|
||||
PartitionedFileStorage<String> storage = open(PartitionedFileStorage.Mode.SYNC);
|
||||
String longKey = "000000000000/us-east-1::" + "t".repeat(255);
|
||||
String otherLongKey = "000000000000/us-east-1::" + "t".repeat(254) + "u";
|
||||
storage.put(longKey, Map.of("a", "1"));
|
||||
storage.put(otherLongKey, Map.of("a", "2"));
|
||||
storage.put("../escape", Map.of("a", "3"));
|
||||
|
||||
assertNotEquals(storage.fileFor(longKey), storage.fileFor(otherLongKey));
|
||||
assertTrue(storage.fileFor(longKey).getFileName().toString().length() < 120);
|
||||
assertEquals(tempDir.resolve("items"), storage.fileFor("../escape").getParent());
|
||||
PartitionedFileStorage<String> reloaded = open(PartitionedFileStorage.Mode.SYNC);
|
||||
assertEquals("1", reloaded.get(longKey).orElseThrow().get("a"));
|
||||
assertEquals("2", reloaded.get(otherLongKey).orElseThrow().get("a"));
|
||||
assertEquals("3", reloaded.get("../escape").orElseThrow().get("a"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void firstLoadMigratesTheLegacySingleFile() throws Exception {
|
||||
Path legacy = tempDir.resolve("items.json");
|
||||
new ObjectMapper().writeValue(legacy.toFile(), Map.of(
|
||||
"000000000000/us-east-1::a", Map.of("k1", "v1"),
|
||||
"000000000000/us-east-1::b", Map.of("k2", "v2")));
|
||||
|
||||
PartitionedFileStorage<String> storage = open(PartitionedFileStorage.Mode.PERIODIC);
|
||||
|
||||
assertEquals(Map.of("k1", "v1"), storage.get("000000000000/us-east-1::a").orElseThrow());
|
||||
assertFalse(Files.exists(legacy));
|
||||
assertTrue(Files.exists(tempDir.resolve("items.json.migrated")));
|
||||
assertTrue(Files.exists(storage.fileFor("000000000000/us-east-1::b")),
|
||||
"migration writes the files at once, not on the next flush");
|
||||
assertEquals(Map.of("k2", "v2"),
|
||||
open(PartitionedFileStorage.Mode.SYNC).get("000000000000/us-east-1::b").orElseThrow());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aMigrationThatCrashedInStagingIsRedoneInFull() throws Exception {
|
||||
Path legacy = tempDir.resolve("items.json");
|
||||
new ObjectMapper().writeValue(legacy.toFile(), Map.of("a", Map.of("k", "1"), "b", Map.of("k", "2")));
|
||||
// What a crash mid-migration leaves: one key staged, nothing moved in place.
|
||||
Path staging = Files.createDirectories(tempDir.resolve("items" + PartitionedFileStorage.MIGRATING_SUFFIX));
|
||||
Files.writeString(staging.resolve("a.json"), "{\"key\":\"a\",\"entries\":{\"k\":\"1\"}}");
|
||||
|
||||
PartitionedFileStorage<String> storage = open(PartitionedFileStorage.Mode.SYNC);
|
||||
|
||||
assertEquals(Map.of("k", "1"), storage.get("a").orElseThrow());
|
||||
assertEquals(Map.of("k", "2"), storage.get("b").orElseThrow());
|
||||
assertFalse(Files.exists(staging));
|
||||
assertFalse(Files.exists(legacy));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anEmptyDirectoryLeftBehindStillMigratesTheLegacyFile() throws Exception {
|
||||
Path legacy = tempDir.resolve("items.json");
|
||||
new ObjectMapper().writeValue(legacy.toFile(), Map.of("a", Map.of("k", "1")));
|
||||
Files.createDirectories(tempDir.resolve("items"));
|
||||
|
||||
assertEquals(Map.of("k", "1"), open(PartitionedFileStorage.Mode.SYNC).get("a").orElseThrow());
|
||||
assertTrue(Files.exists(tempDir.resolve("items.json.migrated")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aMigrationThatCannotWriteFailsAndKeepsTheLegacyFile() throws Exception {
|
||||
Path legacy = tempDir.resolve("items.json");
|
||||
new ObjectMapper().writeValue(legacy.toFile(), Map.of("a", Map.of("k", "1")));
|
||||
StorageTestFiles.assumePosixPermissions(tempDir);
|
||||
Set<PosixFilePermission> original = Files.getPosixFilePermissions(tempDir);
|
||||
Files.setPosixFilePermissions(tempDir, PosixFilePermissions.fromString("r-xr-xr-x"));
|
||||
try {
|
||||
// A root user writes through the read-only mode, so there is nothing to test there.
|
||||
assumeFalse(Files.isWritable(tempDir), "the directory stays writable for this user");
|
||||
PartitionedFileStorage<String> storage = new PartitionedFileStorage<>(tempDir.resolve("items"),
|
||||
legacy, String.class, 4, PartitionedFileStorage.Mode.SYNC, 60_000);
|
||||
|
||||
assertThrows(UncheckedIOException.class, storage::load);
|
||||
storage.shutdown();
|
||||
} finally {
|
||||
Files.setPosixFilePermissions(tempDir, original);
|
||||
}
|
||||
assertTrue(Files.exists(legacy));
|
||||
assertFalse(Files.exists(tempDir.resolve("items")));
|
||||
assertEquals(Map.of("k", "1"), open(4, PartitionedFileStorage.Mode.SYNC).get("a").orElseThrow());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aLegacyFileIsIgnoredOnceTheDirectoryHoldsData() throws Exception {
|
||||
PartitionedFileStorage<String> storage = open(PartitionedFileStorage.Mode.SYNC);
|
||||
storage.put("a", Map.of("k", "new"));
|
||||
Path legacy = tempDir.resolve("items.json");
|
||||
new ObjectMapper().writeValue(legacy.toFile(), Map.of("a", Map.of("k", "old"), "b", Map.of("k", "old")));
|
||||
|
||||
PartitionedFileStorage<String> reloaded = open(PartitionedFileStorage.Mode.SYNC);
|
||||
|
||||
assertEquals(Map.of("k", "new"), reloaded.get("a").orElseThrow());
|
||||
assertTrue(reloaded.get("b").isEmpty());
|
||||
assertTrue(Files.exists(legacy), "a legacy file that was not migrated is left alone");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSupersededFileThatCannotBeRewrittenStopsTheLoad() throws Exception {
|
||||
PartitionedFileStorage<String> storage = open(PartitionedFileStorage.Mode.SYNC);
|
||||
storage.put("key", Map.of("a", "1", "b", "2"));
|
||||
Path current = storage.fileFor("key");
|
||||
Path old = current.resolveSibling("old-name.json");
|
||||
Files.move(current, old);
|
||||
// A non-empty directory where the rewrite's temporary file goes makes the rewrite fail.
|
||||
Path blocker = current.resolveSibling(current.getFileName() + ".tmp");
|
||||
Files.createDirectories(blocker);
|
||||
Files.writeString(blocker.resolve("child"), "x");
|
||||
|
||||
PartitionedFileStorage<String> blocked = new PartitionedFileStorage<>(tempDir.resolve("items"),
|
||||
tempDir.resolve("items.json"), String.class, 1, PartitionedFileStorage.Mode.SYNC, 60_000);
|
||||
opened.add(blocked);
|
||||
// Running on would let later writes change only the current file, and the next load
|
||||
// would merge the old file back in and revive what they removed.
|
||||
assertThrows(IllegalStateException.class, blocked::load);
|
||||
|
||||
assertTrue(Files.exists(old));
|
||||
Files.delete(blocker.resolve("child"));
|
||||
Files.delete(blocker);
|
||||
assertEquals(Map.of("a", "1", "b", "2"), open(PartitionedFileStorage.Mode.SYNC).get("key").orElseThrow());
|
||||
assertFalse(Files.exists(old));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSupersededFileThatCannotBeRemovedStopsTheLoad() throws Exception {
|
||||
PartitionedFileStorage<String> storage = open(PartitionedFileStorage.Mode.SYNC);
|
||||
storage.put("key", Map.of("a", "1", "b", "2"));
|
||||
Path current = storage.fileFor("key");
|
||||
Path old = current.resolveSibling("old-name.json");
|
||||
Files.move(current, old);
|
||||
Path directory = tempDir.resolve("items");
|
||||
StorageTestFiles.assumePosixPermissions(directory);
|
||||
Set<PosixFilePermission> original = Files.getPosixFilePermissions(directory);
|
||||
|
||||
PartitionedFileStorage<String> blocked = new PartitionedFileStorage<>(directory,
|
||||
tempDir.resolve("items.json"), String.class, 1, PartitionedFileStorage.Mode.SYNC, 60_000);
|
||||
opened.add(blocked);
|
||||
blocked.setBeforeSupersededDelete(() -> {
|
||||
// The keys are rewritten under their current names; now make removing the old file fail.
|
||||
try {
|
||||
Files.setPosixFilePermissions(directory, PosixFilePermissions.fromString("r-xr-xr-x"));
|
||||
} catch (IOException e) {
|
||||
throw new UncheckedIOException(e);
|
||||
}
|
||||
});
|
||||
try {
|
||||
Throwable failure = assertThrows(RuntimeException.class, blocked::load);
|
||||
// A root user deletes through the read-only mode, so there is nothing to test there.
|
||||
assumeFalse(Files.isWritable(directory), "the directory stays writable for this user");
|
||||
// Running on would let later writes change only the current file, and the next load
|
||||
// would merge the old file back in and revive what they removed.
|
||||
assertInstanceOf(UncheckedIOException.class, failure);
|
||||
assertTrue(Files.exists(current), "the rewrite landed before the removal failed");
|
||||
assertTrue(Files.exists(old));
|
||||
} finally {
|
||||
Files.setPosixFilePermissions(directory, original);
|
||||
}
|
||||
|
||||
assertEquals(Map.of("a", "1", "b", "2"), open(PartitionedFileStorage.Mode.SYNC).get("key").orElseThrow());
|
||||
assertFalse(Files.exists(old));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aWriteThatReadItsShardBeforeAClearDoesNotBringItBack() throws Exception {
|
||||
PartitionedFileStorage<String> storage = open(PartitionedFileStorage.Mode.PERIODIC);
|
||||
storage.putEntry("table", "a", "1");
|
||||
Thread[] clearer = new Thread[1];
|
||||
storage.setBeforeShardWrite(() -> {
|
||||
// The shard is read and its file is about to be written: a clear now must wait for
|
||||
// the write, or the write puts the cleared file back.
|
||||
storage.setBeforeShardWrite(() -> { });
|
||||
clearer[0] = Thread.ofPlatform().start(storage::clear);
|
||||
StorageTestThreads.awaitParkedOrDone(clearer[0]);
|
||||
});
|
||||
|
||||
storage.flush();
|
||||
clearer[0].join(TimeUnit.SECONDS.toMillis(10));
|
||||
|
||||
assertFalse(clearer[0].isAlive());
|
||||
assertTrue(open(PartitionedFileStorage.Mode.SYNC).get("table").isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUnreadableFileIsQuarantinedAndTheRestStillLoad() throws Exception {
|
||||
PartitionedFileStorage<String> storage = open(PartitionedFileStorage.Mode.SYNC);
|
||||
storage.put("good", Map.of("a", "1"));
|
||||
Files.writeString(tempDir.resolve("items").resolve("broken-0000000000000000.json"), "{not json");
|
||||
|
||||
PartitionedFileStorage<String> reloaded = open(PartitionedFileStorage.Mode.SYNC);
|
||||
|
||||
assertEquals(Map.of("a", "1"), reloaded.get("good").orElseThrow());
|
||||
try (Stream<Path> files = Files.list(tempDir.resolve("items"))) {
|
||||
assertTrue(files.noneMatch(f -> f.getFileName().toString().equals("broken-0000000000000000.json")));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void aFileUnderAnOldNameIsRewrittenUnderItsCurrentName() throws Exception {
|
||||
PartitionedFileStorage<String> storage = open(PartitionedFileStorage.Mode.SYNC);
|
||||
storage.put("key", Map.of("a", "1"));
|
||||
Path current = storage.fileFor("key");
|
||||
Path old = current.resolveSibling("old-name.json");
|
||||
Files.move(current, old);
|
||||
|
||||
PartitionedFileStorage<String> reloaded = open(PartitionedFileStorage.Mode.SYNC);
|
||||
|
||||
assertEquals(Map.of("a", "1"), reloaded.get("key").orElseThrow());
|
||||
assertTrue(Files.exists(current));
|
||||
assertFalse(Files.exists(old));
|
||||
}
|
||||
|
||||
@Test
|
||||
void clearRemovesEveryFile() throws Exception {
|
||||
PartitionedFileStorage<String> storage = open(PartitionedFileStorage.Mode.SYNC);
|
||||
storage.put("a", Map.of("x", "1"));
|
||||
storage.put("b", Map.of("x", "2"));
|
||||
|
||||
storage.clear();
|
||||
|
||||
try (Stream<Path> files = Files.list(tempDir.resolve("items"))) {
|
||||
assertEquals(0, files.count());
|
||||
}
|
||||
assertTrue(open(PartitionedFileStorage.Mode.SYNC).keys().isEmpty());
|
||||
}
|
||||
}
|
||||
+244
@@ -0,0 +1,244 @@
|
||||
package io.github.hectorvent.floci.core.storage;
|
||||
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.ServiceConfigAccess;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.attribute.FileTime;
|
||||
import java.nio.file.attribute.PosixFilePermissions;
|
||||
import java.time.Instant;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.junit.jupiter.api.Assumptions.assumeFalse;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/** How {@link StorageFactory#createPartitioned} maps each storage mode onto a backend. */
|
||||
class StorageFactoryPartitionedTest {
|
||||
|
||||
private static final TypeReference<Map<String, Map<String, String>>> TYPE = new TypeReference<>() {};
|
||||
|
||||
@TempDir
|
||||
Path tempDir;
|
||||
|
||||
@Test
|
||||
void persistentModeWritesOneFilePerKeyAsItChanges() {
|
||||
StorageFactory factory = newFactory("persistent");
|
||||
AccountAwareStorageBackend<Map<String, String>> store =
|
||||
factory.createPartitioned("svc", "svc-items.json", TYPE, String.class, 1);
|
||||
|
||||
assertTrue(store.writesEntries());
|
||||
store.putEntry("table-a", "k", "v");
|
||||
store.putEntry("table-b", "k", "v");
|
||||
|
||||
assertEquals(2, fileCount(tempDir.resolve("svc-items")));
|
||||
assertFalse(Files.exists(tempDir.resolve("svc-items.json")));
|
||||
factory.shutdownAll();
|
||||
}
|
||||
|
||||
@Test
|
||||
void hybridModeWritesDirtyKeysOnFlushAndShutdown() {
|
||||
StorageFactory factory = newFactory("hybrid");
|
||||
AccountAwareStorageBackend<Map<String, String>> store =
|
||||
factory.createPartitioned("svc", "svc-items.json", TYPE, String.class, 1);
|
||||
|
||||
store.putEntry("table-a", "k", "v");
|
||||
assertEquals(0, fileCount(tempDir.resolve("svc-items")));
|
||||
|
||||
factory.shutdownAll();
|
||||
assertEquals(1, fileCount(tempDir.resolve("svc-items")));
|
||||
AccountAwareStorageBackend<Map<String, String>> reopened = newFactory("hybrid")
|
||||
.createPartitioned("svc", "svc-items.json", TYPE, String.class, 1);
|
||||
assertEquals(Map.of("k", "v"), reopened.get("table-a").orElseThrow());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anExistingSingleFileIsMigratedOnFirstUse() throws Exception {
|
||||
new ObjectMapper().writeValue(tempDir.resolve("svc-items.json").toFile(),
|
||||
Map.of("000000000000/table-a", Map.of("k", "v")));
|
||||
|
||||
AccountAwareStorageBackend<Map<String, String>> store = newFactory("persistent")
|
||||
.createPartitioned("svc", "svc-items.json", TYPE, String.class, 1);
|
||||
|
||||
assertEquals(Map.of("k", "v"), store.get("table-a").orElseThrow());
|
||||
assertTrue(Files.exists(tempDir.resolve("svc-items.json.migrated")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void walModeKeepsTheSingleFileStoreForNow() {
|
||||
AccountAwareStorageBackend<Map<String, String>> store = newFactory("wal")
|
||||
.createPartitioned("svc", "svc-items.json", TYPE, String.class, 4);
|
||||
|
||||
assertFalse(store.writesEntries());
|
||||
store.put("table-a", Map.of("k", "v"));
|
||||
assertFalse(Files.exists(tempDir.resolve("svc-items")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void hybridModeMigratesALegacyWalStoreIncludingItsUncompactedLog() {
|
||||
WalStorage<String, Map<String, String>> legacy = new WalStorage<>(tempDir.resolve("svc-items-snapshot.json"),
|
||||
tempDir.resolve("svc-items.wal"), TYPE, Long.MAX_VALUE);
|
||||
legacy.load();
|
||||
legacy.put("000000000000/table-a", Map.of("k", "v"));
|
||||
legacy.flush();
|
||||
legacy.put("000000000000/table-b", Map.of("k", "only-in-the-log"));
|
||||
|
||||
AccountAwareStorageBackend<Map<String, String>> store = newFactory("hybrid")
|
||||
.createPartitioned("svc", "svc-items.json", TYPE, String.class, 1);
|
||||
|
||||
assertEquals(Map.of("k", "v"), store.get("table-a").orElseThrow());
|
||||
assertEquals(Map.of("k", "only-in-the-log"), store.get("table-b").orElseThrow());
|
||||
assertTrue(Files.exists(tempDir.resolve("svc-items.wal.migrated")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anEmptyDirectoryLeftBehindStillMigratesALegacyWalStore() throws Exception {
|
||||
WalStorage<String, Map<String, String>> legacy = new WalStorage<>(tempDir.resolve("svc-items-snapshot.json"),
|
||||
tempDir.resolve("svc-items.wal"), TYPE, Long.MAX_VALUE);
|
||||
legacy.load();
|
||||
legacy.put("000000000000/table-a", Map.of("k", "v"));
|
||||
legacy.shutdown();
|
||||
// What a crash right after the directory was created leaves behind.
|
||||
Files.createDirectories(tempDir.resolve("svc-items"));
|
||||
|
||||
AccountAwareStorageBackend<Map<String, String>> store = newFactory("hybrid")
|
||||
.createPartitioned("svc", "svc-items.json", TYPE, String.class, 1);
|
||||
|
||||
assertEquals(Map.of("k", "v"), store.get("table-a").orElseThrow());
|
||||
}
|
||||
|
||||
@Test
|
||||
void theLegacyStoreWrittenLastIsTheOneMigrated() throws Exception {
|
||||
WalStorage<String, Map<String, String>> legacy = new WalStorage<>(tempDir.resolve("svc-items-snapshot.json"),
|
||||
tempDir.resolve("svc-items.wal"), TYPE, Long.MAX_VALUE);
|
||||
legacy.load();
|
||||
legacy.put("000000000000/table-a", Map.of("k", "from-wal"));
|
||||
legacy.shutdown();
|
||||
Path plain = tempDir.resolve("svc-items.json");
|
||||
new ObjectMapper().writeValue(plain.toFile(), Map.of("000000000000/table-a", Map.of("k", "from-plain")));
|
||||
FileTime older = FileTime.from(Instant.parse("2020-01-01T00:00:00Z"));
|
||||
Files.setLastModifiedTime(tempDir.resolve("svc-items-snapshot.json"), older);
|
||||
Files.setLastModifiedTime(tempDir.resolve("svc-items.wal"), older);
|
||||
|
||||
AccountAwareStorageBackend<Map<String, String>> store = newFactory("hybrid")
|
||||
.createPartitioned("svc", "svc-items.json", TYPE, String.class, 1);
|
||||
|
||||
assertEquals(Map.of("k", "from-plain"), store.get("table-a").orElseThrow());
|
||||
assertTrue(Files.exists(tempDir.resolve("svc-items-snapshot.json")), "the older store is left alone");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aMigrationThatCannotWriteLeavesTheLegacyLogInPlace() throws Exception {
|
||||
StorageTestFiles.assumePosixPermissions(tempDir);
|
||||
WalStorage<String, Map<String, String>> legacy = new WalStorage<>(tempDir.resolve("svc-items-snapshot.json"),
|
||||
tempDir.resolve("svc-items.wal"), TYPE, Long.MAX_VALUE);
|
||||
legacy.load();
|
||||
legacy.put("000000000000/table-a", Map.of("k", "only-in-the-log"));
|
||||
Path log = tempDir.resolve("svc-items.wal");
|
||||
byte[] logged = Files.readAllBytes(log);
|
||||
// A non-empty file where the staging directory goes makes the migration's first write fail.
|
||||
Path staging = tempDir.resolve("svc-items" + PartitionedFileStorage.MIGRATING_SUFFIX);
|
||||
Files.createDirectories(staging.resolve("blocker"));
|
||||
Files.setPosixFilePermissions(staging, PosixFilePermissions.fromString("r-xr-xr-x"));
|
||||
try {
|
||||
assumeFalse(Files.isWritable(staging), "the directory stays writable for this user");
|
||||
assertThrows(UncheckedIOException.class, () -> newFactory("hybrid")
|
||||
.createPartitioned("svc", "svc-items.json", TYPE, String.class, 1));
|
||||
} finally {
|
||||
Files.setPosixFilePermissions(staging, PosixFilePermissions.fromString("rwxr-xr-x"));
|
||||
}
|
||||
|
||||
assertArrayEquals(logged, Files.readAllBytes(log));
|
||||
assertEquals(Map.of("k", "only-in-the-log"), newFactory("hybrid")
|
||||
.createPartitioned("svc", "svc-items.json", TYPE, String.class, 1).get("table-a").orElseThrow());
|
||||
legacy.shutdown();
|
||||
}
|
||||
|
||||
@Test
|
||||
void aBackendThatFailsToFlushDoesNotStopTheOthersShuttingDown() throws Exception {
|
||||
StorageFactory factory = newFactory("hybrid");
|
||||
AccountAwareStorageBackend<Map<String, String>> failing =
|
||||
factory.createPartitioned("svc", "svc-a.json", TYPE, String.class, 1);
|
||||
AccountAwareStorageBackend<Map<String, String>> healthy =
|
||||
factory.createPartitioned("svc", "svc-b.json", TYPE, String.class, 1);
|
||||
failing.putEntry("table", "k", "v");
|
||||
healthy.putEntry("table", "k", "v");
|
||||
Path blocker = tempDir.resolve("svc-a")
|
||||
.resolve(PartitionedFileStorage.fileNameFor("000000000000/table", 0, 1) + ".tmp");
|
||||
Files.createDirectories(blocker.resolve("child"));
|
||||
|
||||
assertThrows(UncheckedIOException.class, factory::shutdownAll);
|
||||
|
||||
assertEquals(1, fileCount(tempDir.resolve("svc-b")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void memoryModeKeepsTheSingleValueStore() {
|
||||
AccountAwareStorageBackend<Map<String, String>> store = newFactory("memory")
|
||||
.createPartitioned("svc", "svc-items.json", TYPE, String.class, 1);
|
||||
|
||||
assertFalse(store.writesEntries());
|
||||
store.put("table-a", Map.of("k", "v"));
|
||||
assertFalse(Files.exists(tempDir.resolve("svc-items")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void entriesOfTwoAccountsUnderOneKeyStaySeparate() {
|
||||
StorageFactory factory = newFactory("persistent");
|
||||
AccountAwareStorageBackend<Map<String, String>> store =
|
||||
factory.createPartitioned("svc", "svc-items.json", TYPE, String.class, 4);
|
||||
|
||||
store.putEntryForAccount("111111111111", "table", "k", "one");
|
||||
store.putEntryForAccount("222222222222", "table", "k", "two");
|
||||
store.putEntryForAccount("222222222222", "table", "gone", "x");
|
||||
store.removeEntryForAccount("111111111111", "table", "gone");
|
||||
store.removeEntryForAccount("222222222222", "table", "gone");
|
||||
factory.shutdownAll();
|
||||
|
||||
AccountAwareStorageBackend<Map<String, String>> reopened = newFactory("persistent")
|
||||
.createPartitioned("svc", "svc-items.json", TYPE, String.class, 4);
|
||||
assertEquals(Map.of(
|
||||
"111111111111/table", Map.of("k", "one"),
|
||||
"222222222222/table", Map.of("k", "two")), reopened.scanAllAccountsRaw());
|
||||
}
|
||||
|
||||
@Test
|
||||
void repeatCallsShareOneBackend() {
|
||||
StorageFactory factory = newFactory("persistent");
|
||||
assertSame(factory.createPartitioned("svc", "svc-items.json", TYPE, String.class, 1),
|
||||
factory.createPartitioned("svc", "svc-items.json", TYPE, String.class, 1));
|
||||
}
|
||||
|
||||
private static long fileCount(Path directory) {
|
||||
if (!Files.isDirectory(directory)) {
|
||||
return 0;
|
||||
}
|
||||
try (Stream<Path> files = Files.list(directory)) {
|
||||
return files.filter(f -> f.getFileName().toString().endsWith(".json")).count();
|
||||
} catch (IOException e) {
|
||||
throw new UncheckedIOException(e);
|
||||
}
|
||||
}
|
||||
|
||||
private StorageFactory newFactory(String mode) {
|
||||
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
|
||||
when(config.defaultAccountId()).thenReturn("000000000000");
|
||||
when(config.storage().persistentPath()).thenReturn(tempDir.toString());
|
||||
when(config.storage().wal().compactionIntervalMs()).thenReturn(60_000L);
|
||||
ServiceConfigAccess serviceConfigAccess = mock(ServiceConfigAccess.class);
|
||||
when(serviceConfigAccess.storageMode(anyString())).thenReturn(mode);
|
||||
when(serviceConfigAccess.storageFlushInterval(anyString())).thenReturn(60_000L);
|
||||
return new StorageFactory(config, serviceConfigAccess);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package io.github.hectorvent.floci.core.storage;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.attribute.PosixFileAttributeView;
|
||||
|
||||
import static org.junit.jupiter.api.Assumptions.assumeTrue;
|
||||
|
||||
/** File system helpers for the storage tests. */
|
||||
final class StorageTestFiles {
|
||||
|
||||
private StorageTestFiles() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Skips the calling test unless {@code path}'s file store supports POSIX permissions. Tests
|
||||
* that make a directory read-only to force a write to fail call it first, because the POSIX
|
||||
* permission calls throw on a file system without them, such as Windows.
|
||||
*/
|
||||
static void assumePosixPermissions(Path path) throws IOException {
|
||||
assumeTrue(Files.getFileStore(path).supportsFileAttributeView(PosixFileAttributeView.class),
|
||||
"POSIX file permissions are not supported here");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package io.github.hectorvent.floci.core.storage;
|
||||
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.locks.LockSupport;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.fail;
|
||||
|
||||
/** Thread helpers for the storage race tests. */
|
||||
final class StorageTestThreads {
|
||||
|
||||
private StorageTestThreads() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Waits until the thread has finished or is parked, on a lock for instance. Fails by name
|
||||
* after ten seconds, so a thread that neither finishes nor waits cannot hang the test.
|
||||
*/
|
||||
static void awaitParkedOrDone(Thread thread) {
|
||||
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10);
|
||||
while (System.nanoTime() < deadline) {
|
||||
Thread.State state = thread.getState();
|
||||
if (state == Thread.State.TERMINATED || state == Thread.State.WAITING) {
|
||||
return;
|
||||
}
|
||||
LockSupport.parkNanos(TimeUnit.MILLISECONDS.toNanos(1));
|
||||
}
|
||||
fail("the thread neither finished nor waited: " + thread.getState());
|
||||
}
|
||||
}
|
||||
+371
@@ -0,0 +1,371 @@
|
||||
package io.github.hectorvent.floci.services.dynamodb;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.common.ServiceConfigAccess;
|
||||
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.PartitionedFileStorage;
|
||||
import io.github.hectorvent.floci.core.storage.StorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
import io.github.hectorvent.floci.services.dynamodb.model.AttributeDefinition;
|
||||
import io.github.hectorvent.floci.services.dynamodb.model.KeySchemaElement;
|
||||
import io.github.hectorvent.floci.services.dynamodb.model.TableDefinition;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.attribute.FileTime;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
|
||||
import static org.mockito.Mockito.doAnswer;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/** DynamoDB items on a store that persists one table file at a time and one item at a time. */
|
||||
class DynamoDbPartitionedItemStoreTest {
|
||||
|
||||
private static final String REGION = "us-east-1";
|
||||
private static final String ACCOUNT = "111111111111";
|
||||
private static final FileTime LONG_AGO = FileTime.from(Instant.parse("2020-01-01T00:00:00Z"));
|
||||
|
||||
private final ObjectMapper mapper = new ObjectMapper();
|
||||
private final List<PartitionedFileStorage<JsonNode>> opened = new ArrayList<>();
|
||||
private final RegionResolver resolver = new RegionResolver(REGION, ACCOUNT);
|
||||
|
||||
@TempDir
|
||||
Path tempDir;
|
||||
|
||||
private StorageBackend<String, TableDefinition> tableStore;
|
||||
private DynamoDbService service;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
tableStore = AccountAwareStorageBackend.inMemory(ACCOUNT);
|
||||
service = new DynamoDbService(tableStore, openItemStore(), resolver);
|
||||
createTable(service, "Logs");
|
||||
createTable(service, "Nodes");
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void tearDown() {
|
||||
opened.forEach(PartitionedFileStorage::shutdown);
|
||||
}
|
||||
|
||||
@Test
|
||||
void writesToOneTableLeaveAnotherTablesFileUntouched() throws Exception {
|
||||
for (int i = 0; i < 50; i++) {
|
||||
service.putItem("Logs", item("entry-" + i, "payload"), REGION);
|
||||
}
|
||||
Path logsFile = tableFile("Logs");
|
||||
Files.setLastModifiedTime(logsFile, LONG_AGO);
|
||||
|
||||
service.putItem("Nodes", item("node-1", "beat-1"), REGION);
|
||||
service.updateItem("Nodes", key("node-1"), null, "SET v = :v", null,
|
||||
mapper.createObjectNode().set(":v", attribute("beat-2")), "NONE", REGION);
|
||||
service.putItem("Nodes", item("node-2", "beat-1"), REGION);
|
||||
service.deleteItem("Nodes", key("node-2"), REGION);
|
||||
|
||||
assertEquals(LONG_AGO, Files.getLastModifiedTime(logsFile));
|
||||
DynamoDbService restarted = restart();
|
||||
assertEquals("beat-2", value(restarted.getItem("Nodes", key("node-1"), REGION)));
|
||||
assertNull(restarted.getItem("Nodes", key("node-2"), REGION));
|
||||
assertEquals("payload", value(restarted.getItem("Logs", key("entry-49"), REGION)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void batchAndTransactWritesSurviveARestart() {
|
||||
service.putItem("Nodes", item("gone", "x"), REGION);
|
||||
service.batchWriteItem(Map.of("Nodes", List.of(
|
||||
putRequest(item("batch-1", "b1")),
|
||||
deleteRequest(key("gone")))), REGION);
|
||||
service.transactWriteItems(List.of(
|
||||
transactPut("Logs", item("tx-1", "t1")),
|
||||
transactPut("Nodes", item("tx-2", "t2"))), REGION);
|
||||
|
||||
DynamoDbService restarted = restart();
|
||||
|
||||
assertEquals("b1", value(restarted.getItem("Nodes", key("batch-1"), REGION)));
|
||||
assertNull(restarted.getItem("Nodes", key("gone"), REGION));
|
||||
assertEquals("t1", value(restarted.getItem("Logs", key("tx-1"), REGION)));
|
||||
assertEquals("t2", value(restarted.getItem("Nodes", key("tx-2"), REGION)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anItemStoredUnderAnOlderKeyStaysDeletedAfterARestart() {
|
||||
AccountAwareStorageBackend<Map<String, JsonNode>> itemStore = openItemStore();
|
||||
itemStore.put(REGION + "::Nodes", Map.of("legacy-address-of-node-9", item("node-9", "old")));
|
||||
DynamoDbService rekeyed = new DynamoDbService(tableStore, itemStore, resolver);
|
||||
|
||||
rekeyed.deleteItem("Nodes", key("node-9"), REGION);
|
||||
|
||||
assertNull(restart().getItem("Nodes", key("node-9"), REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
void deletingATableRemovesItsFile() throws Exception {
|
||||
service.putItem("Nodes", item("node-1", "beat-1"), REGION);
|
||||
assertTrue(Files.exists(tableFile("Nodes")));
|
||||
|
||||
service.deleteTable("Nodes", REGION);
|
||||
|
||||
try (Stream<Path> files = Files.list(tempDir.resolve("items"))) {
|
||||
assertTrue(files.noneMatch(f -> f.getFileName().toString().contains("Nodes")));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void expiredItemsTheSweeperRemovesStayRemovedAfterARestart() {
|
||||
service.updateTimeToLive("Nodes", "expires", true, REGION);
|
||||
ObjectNode expired = item("node-1", "beat-1");
|
||||
expired.set("expires", mapper.createObjectNode().put("N", "1"));
|
||||
service.putItem("Nodes", expired, REGION);
|
||||
service.putItem("Nodes", item("node-2", "beat-1"), REGION);
|
||||
|
||||
service.deleteScannedItems(service.scanExpiredItems());
|
||||
|
||||
DynamoDbService restarted = restart();
|
||||
assertNull(restarted.getItem("Nodes", key("node-1"), REGION));
|
||||
assertEquals("beat-1", value(restarted.getItem("Nodes", key("node-2"), REGION)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aWriteRightAfterTheSweeperRemovesAnItemSurvivesARestart() {
|
||||
DynamoDbStreamService streams = mock(DynamoDbStreamService.class);
|
||||
DynamoDbService swept = new DynamoDbService(tableStore, openItemStore(), resolver, streams, null);
|
||||
swept.updateTimeToLive("Nodes", "expires", true, REGION);
|
||||
ObjectNode expired = item("node-1", "beat-1");
|
||||
expired.set("expires", mapper.createObjectNode().put("N", "1"));
|
||||
swept.putItem("Nodes", expired, REGION);
|
||||
// The REMOVE event fires after the sweeper drops the item and releases its lock: the
|
||||
// moment a new write of the same key can land before the removal reaches disk.
|
||||
doAnswer(invocation -> {
|
||||
swept.putItem("Nodes", item("node-1", "beat-2"), REGION);
|
||||
return null;
|
||||
}).when(streams).captureEvent(eq("REMOVE"), any(), any(), any(), any(), eq(true));
|
||||
|
||||
swept.deleteScannedItems(swept.scanExpiredItems());
|
||||
|
||||
assertEquals("beat-2", value(swept.getItem("Nodes", key("node-1"), REGION)));
|
||||
assertEquals("beat-2", value(restart().getItem("Nodes", key("node-1"), REGION)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aWriteToAShardedTableRewritesOneOfItsFiles() throws Exception {
|
||||
Path directory = tempDir.resolve("sharded");
|
||||
DynamoDbService sharded = new DynamoDbService(tableStore, openItemStore(directory, 8), resolver);
|
||||
for (int i = 0; i < 200; i++) {
|
||||
sharded.putItem("Logs", item("entry-" + i, "payload"), REGION);
|
||||
}
|
||||
List<Path> files;
|
||||
try (Stream<Path> listed = Files.list(directory)) {
|
||||
files = listed.toList();
|
||||
}
|
||||
assertEquals(8, files.size());
|
||||
for (Path file : files) {
|
||||
Files.setLastModifiedTime(file, LONG_AGO);
|
||||
}
|
||||
|
||||
sharded.putItem("Logs", item("entry-200", "payload"), REGION);
|
||||
|
||||
assertEquals(1, files.stream().filter(f -> !isUntouched(f)).count());
|
||||
DynamoDbService restarted = new DynamoDbService(tableStore, openItemStore(directory, 8), resolver);
|
||||
assertEquals(201, restarted.scan("Logs", null, null, null, null, null, null, REGION).items().size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void failedConditionalWritesLeaveTheTableFileUntouched() throws Exception {
|
||||
service.putItem("Nodes", item("node-1", "beat-1"), REGION);
|
||||
Path nodesFile = tableFile("Nodes");
|
||||
Files.setLastModifiedTime(nodesFile, LONG_AGO);
|
||||
|
||||
assertThrows(AwsException.class, () -> service.putItem("Nodes", item("node-1", "beat-2"),
|
||||
"attribute_not_exists(id)", null, null, REGION, "NONE"));
|
||||
assertThrows(AwsException.class, () -> service.deleteItem("Nodes", key("node-1"),
|
||||
"attribute_not_exists(id)", null, null, REGION, "NONE"));
|
||||
assertThrows(AwsException.class, () -> service.updateItem("Nodes", key("node-1"), null,
|
||||
"SET v = :v", null, mapper.createObjectNode().set(":v", attribute("beat-3")), "NONE",
|
||||
"attribute_not_exists(id)", REGION, "NONE"));
|
||||
|
||||
assertEquals(LONG_AGO, Files.getLastModifiedTime(nodesFile));
|
||||
assertEquals("beat-1", value(restart().getItem("Nodes", key("node-1"), REGION)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aCancelledTransactionWritesNothing() throws Exception {
|
||||
service.putItem("Nodes", item("node-1", "beat-1"), REGION);
|
||||
Path nodesFile = tableFile("Nodes");
|
||||
Files.setLastModifiedTime(nodesFile, LONG_AGO);
|
||||
|
||||
assertThrows(TransactionCanceledException.class, () -> service.transactWriteItems(List.of(
|
||||
transactPut("Nodes", item("node-2", "new")),
|
||||
transactConditionCheck("Nodes", key("missing"), "attribute_exists(id)")), REGION));
|
||||
|
||||
assertEquals(LONG_AGO, Files.getLastModifiedTime(nodesFile));
|
||||
assertNull(restart().getItem("Nodes", key("node-2"), REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aBatchToAShardedTableRewritesOnlyTheShardsItTouches() throws Exception {
|
||||
Path directory = tempDir.resolve("sharded");
|
||||
DynamoDbService sharded = new DynamoDbService(tableStore, openItemStore(directory, 8), resolver);
|
||||
for (int i = 0; i < 200; i++) {
|
||||
sharded.putItem("Logs", item("entry-" + i, "payload"), REGION);
|
||||
}
|
||||
List<Path> files;
|
||||
try (Stream<Path> listed = Files.list(directory)) {
|
||||
files = listed.toList();
|
||||
}
|
||||
for (Path file : files) {
|
||||
Files.setLastModifiedTime(file, LONG_AGO);
|
||||
}
|
||||
|
||||
sharded.batchWriteItem(Map.of("Logs", List.of(
|
||||
putRequest(item("entry-200", "payload")),
|
||||
deleteRequest(key("entry-0")))), REGION);
|
||||
|
||||
long rewritten = files.stream().filter(f -> !isUntouched(f)).count();
|
||||
assertTrue(rewritten >= 1 && rewritten <= 2, "rewrote " + rewritten + " of 8 shard files");
|
||||
DynamoDbService restarted = new DynamoDbService(tableStore, openItemStore(directory, 8), resolver);
|
||||
assertNull(restarted.getItem("Logs", key("entry-0"), REGION));
|
||||
assertEquals("payload", value(restarted.getItem("Logs", key("entry-200"), REGION)));
|
||||
assertEquals(200, restarted.scan("Logs", null, null, null, null, null, null, REGION).items().size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRestoredTableSurvivesARestart() {
|
||||
createTable(service, "Restored");
|
||||
|
||||
service.finishRestore("Restored", List.of(item("a", "1"), item("b", "2")), REGION);
|
||||
|
||||
DynamoDbService restarted = restart();
|
||||
assertEquals("1", value(restarted.getItem("Restored", key("a"), REGION)));
|
||||
assertEquals("2", value(restarted.getItem("Restored", key("b"), REGION)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUnknownItemLayoutIsRejected() {
|
||||
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
|
||||
when(config.storage().services().dynamodb().itemLayout()).thenReturn("per-item");
|
||||
|
||||
IllegalArgumentException error = assertThrows(IllegalArgumentException.class,
|
||||
() -> DynamoDbService.itemStore(mock(StorageFactory.class), config));
|
||||
assertTrue(error.getMessage().contains("per-item"), error.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aShardCountBelowOneIsRejected() {
|
||||
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
|
||||
when(config.defaultAccountId()).thenReturn(ACCOUNT);
|
||||
when(config.storage().persistentPath()).thenReturn(tempDir.toString());
|
||||
when(config.storage().services().dynamodb().itemLayout()).thenReturn("per-table");
|
||||
when(config.storage().services().dynamodb().itemShards()).thenReturn(0);
|
||||
ServiceConfigAccess serviceConfigAccess = mock(ServiceConfigAccess.class);
|
||||
when(serviceConfigAccess.storageMode(anyString())).thenReturn("persistent");
|
||||
StorageFactory factory = new StorageFactory(config, serviceConfigAccess);
|
||||
|
||||
assertThrows(IllegalArgumentException.class, () -> DynamoDbService.itemStore(factory, config));
|
||||
}
|
||||
|
||||
private static boolean isUntouched(Path file) {
|
||||
try {
|
||||
return LONG_AGO.equals(Files.getLastModifiedTime(file));
|
||||
} catch (IOException e) {
|
||||
throw new UncheckedIOException(e);
|
||||
}
|
||||
}
|
||||
|
||||
private AccountAwareStorageBackend<Map<String, JsonNode>> openItemStore() {
|
||||
return openItemStore(tempDir.resolve("items"), 1);
|
||||
}
|
||||
|
||||
private AccountAwareStorageBackend<Map<String, JsonNode>> openItemStore(Path directory, int shards) {
|
||||
PartitionedFileStorage<JsonNode> inner = new PartitionedFileStorage<>(directory, (Path) null,
|
||||
JsonNode.class, shards, PartitionedFileStorage.Mode.SYNC, 60_000);
|
||||
inner.load();
|
||||
opened.add(inner);
|
||||
return new AccountAwareStorageBackend<>(inner, null, ACCOUNT);
|
||||
}
|
||||
|
||||
private DynamoDbService restart() {
|
||||
return new DynamoDbService(tableStore, openItemStore(), resolver);
|
||||
}
|
||||
|
||||
private Path tableFile(String table) throws Exception {
|
||||
try (Stream<Path> files = Files.list(tempDir.resolve("items"))) {
|
||||
return files.filter(f -> f.getFileName().toString().contains(table)).findFirst().orElseThrow();
|
||||
}
|
||||
}
|
||||
|
||||
private void createTable(DynamoDbService target, String name) {
|
||||
target.createTable(name, List.of(new KeySchemaElement("id", "HASH")),
|
||||
List.of(new AttributeDefinition("id", "S")), 5L, 5L, REGION);
|
||||
}
|
||||
|
||||
private ObjectNode key(String id) {
|
||||
ObjectNode key = mapper.createObjectNode();
|
||||
key.set("id", attribute(id));
|
||||
return key;
|
||||
}
|
||||
|
||||
private ObjectNode item(String id, String value) {
|
||||
ObjectNode item = key(id);
|
||||
item.set("v", attribute(value));
|
||||
return item;
|
||||
}
|
||||
|
||||
private ObjectNode attribute(String value) {
|
||||
return mapper.createObjectNode().put("S", value);
|
||||
}
|
||||
|
||||
private ObjectNode putRequest(ObjectNode item) {
|
||||
ObjectNode request = mapper.createObjectNode();
|
||||
request.putObject("PutRequest").set("Item", item);
|
||||
return request;
|
||||
}
|
||||
|
||||
private ObjectNode deleteRequest(ObjectNode key) {
|
||||
ObjectNode request = mapper.createObjectNode();
|
||||
request.putObject("DeleteRequest").set("Key", key);
|
||||
return request;
|
||||
}
|
||||
|
||||
private ObjectNode transactPut(String table, ObjectNode item) {
|
||||
ObjectNode request = mapper.createObjectNode();
|
||||
ObjectNode put = request.putObject("Put");
|
||||
put.put("TableName", table);
|
||||
put.set("Item", item);
|
||||
return request;
|
||||
}
|
||||
|
||||
private ObjectNode transactConditionCheck(String table, ObjectNode key, String condition) {
|
||||
ObjectNode request = mapper.createObjectNode();
|
||||
ObjectNode check = request.putObject("ConditionCheck");
|
||||
check.put("TableName", table);
|
||||
check.set("Key", key);
|
||||
check.put("ConditionExpression", condition);
|
||||
return request;
|
||||
}
|
||||
|
||||
private static String value(JsonNode item) {
|
||||
assertNotNull(item);
|
||||
return item.path("v").path("S").asText();
|
||||
}
|
||||
}
|
||||
+112
@@ -0,0 +1,112 @@
|
||||
package io.github.hectorvent.floci.services.dynamodb;
|
||||
|
||||
import io.github.hectorvent.floci.testing.DynamoDbPartitionedStorageProfile;
|
||||
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static io.github.hectorvent.floci.testing.DynamoDbPartitionedStorageProfile.STORAGE_DIR;
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
|
||||
/**
|
||||
* The {@code per-table} item layout in {@code persistent} mode, end to end through the
|
||||
* application: the configuration selects the partitioned item store, and a write lands in shard
|
||||
* files rather than in a single items file, one set per account.
|
||||
*/
|
||||
@QuarkusTest
|
||||
@TestProfile(DynamoDbPartitionedStorageProfile.class)
|
||||
class DynamoDbPartitionedStorageIntegrationTest {
|
||||
|
||||
private static final String DYNAMODB_CONTENT_TYPE = "application/x-amz-json-1.0";
|
||||
private static final String AUTH_ACCOUNT_1 =
|
||||
"AWS4-HMAC-SHA256 Credential=000000000001/20260215/us-east-1/dynamodb/aws4_request, SignedHeaders=host, Signature=abc";
|
||||
private static final String AUTH_ACCOUNT_2 =
|
||||
"AWS4-HMAC-SHA256 Credential=000000000002/20260215/us-east-1/dynamodb/aws4_request, SignedHeaders=host, Signature=abc";
|
||||
|
||||
@BeforeAll
|
||||
static void configureRestAssured() {
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
}
|
||||
|
||||
@Test
|
||||
void itemsAreWrittenToPerAccountShardFiles() throws IOException {
|
||||
// The directory outlives a run, so each run uses its own table name.
|
||||
String table = "partitioned-" + UUID.randomUUID();
|
||||
Path itemsDirectory = Path.of(STORAGE_DIR, "dynamodb-items");
|
||||
try {
|
||||
for (String auth : List.of(AUTH_ACCOUNT_1, AUTH_ACCOUNT_2)) {
|
||||
call(auth, "CreateTable", """
|
||||
{"TableName": "%s", "BillingMode": "PAY_PER_REQUEST",
|
||||
"KeySchema": [{"AttributeName": "pk", "KeyType": "HASH"}],
|
||||
"AttributeDefinitions": [{"AttributeName": "pk", "AttributeType": "S"}]}
|
||||
""".formatted(table));
|
||||
}
|
||||
call(AUTH_ACCOUNT_1, "PutItem", item(table, "one"));
|
||||
call(AUTH_ACCOUNT_2, "PutItem", item(table, "two"));
|
||||
|
||||
assertEquals(2, shardFilesOf(itemsDirectory, table), "one shard file per account's table");
|
||||
assertFalse(Files.exists(Path.of(STORAGE_DIR, "dynamodb-items.json")));
|
||||
getItem(AUTH_ACCOUNT_1, table, "one");
|
||||
getItem(AUTH_ACCOUNT_2, table, "two");
|
||||
} finally {
|
||||
for (String auth : List.of(AUTH_ACCOUNT_1, AUTH_ACCOUNT_2)) {
|
||||
given()
|
||||
.header("X-Amz-Target", "DynamoDB_20120810.DeleteTable")
|
||||
.header("Authorization", auth)
|
||||
.contentType(DYNAMODB_CONTENT_TYPE)
|
||||
.body("{\"TableName\": \"%s\"}".formatted(table))
|
||||
.when().post("/");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static String item(String table, String value) {
|
||||
return """
|
||||
{"TableName": "%s", "Item": {"pk": {"S": "item"}, "v": {"S": "%s"}}}
|
||||
""".formatted(table, value);
|
||||
}
|
||||
|
||||
private static void call(String auth, String action, String body) {
|
||||
given()
|
||||
.header("X-Amz-Target", "DynamoDB_20120810." + action)
|
||||
.header("Authorization", auth)
|
||||
.contentType(DYNAMODB_CONTENT_TYPE)
|
||||
.body(body)
|
||||
.when().post("/")
|
||||
.then().statusCode(200);
|
||||
}
|
||||
|
||||
private static void getItem(String auth, String table, String expected) {
|
||||
given()
|
||||
.header("X-Amz-Target", "DynamoDB_20120810.GetItem")
|
||||
.header("Authorization", auth)
|
||||
.contentType(DYNAMODB_CONTENT_TYPE)
|
||||
.body("{\"TableName\": \"%s\", \"Key\": {\"pk\": {\"S\": \"item\"}}}".formatted(table))
|
||||
.when().post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("Item.v.S", equalTo(expected));
|
||||
}
|
||||
|
||||
/** Shard files whose readable name prefix carries the table name, under any account. */
|
||||
private static long shardFilesOf(Path directory, String table) throws IOException {
|
||||
String safeName = table.replaceAll("[^A-Za-z0-9._-]", "_");
|
||||
try (Stream<Path> files = Files.list(directory)) {
|
||||
return files.map(f -> f.getFileName().toString())
|
||||
.filter(name -> name.endsWith(".json") && name.contains(safeName))
|
||||
.count();
|
||||
}
|
||||
}
|
||||
}
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
package io.github.hectorvent.floci.testing;
|
||||
|
||||
import io.quarkus.test.junit.QuarkusTestProfile;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* DynamoDB in {@code persistent} mode with its items in the {@code per-table} layout, split into
|
||||
* four shards, on a directory of its own. Every other service stays on the test default, memory.
|
||||
* {@code DynamoDbPartitionedStorageIntegrationTest} relies on all of it: it checks that the
|
||||
* configuration reaches the item store and that a write lands in shard files.
|
||||
*/
|
||||
public class DynamoDbPartitionedStorageProfile implements QuarkusTestProfile {
|
||||
|
||||
public static final String STORAGE_DIR = "target/dynamodb-partitioned-it";
|
||||
|
||||
@Override
|
||||
public Map<String, String> getConfigOverrides() {
|
||||
return Map.of(
|
||||
"floci.storage.services.dynamodb.mode", "persistent",
|
||||
"floci.storage.services.dynamodb.item-layout", "per-table",
|
||||
"floci.storage.services.dynamodb.item-shards", "4",
|
||||
"floci.storage.persistent-path", STORAGE_DIR);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user