mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(dynamodb): journal per-table items one record per item in wal mode (#6310)
* feat(dynamodb): journal per-table items one record per item in wal mode With the per-table item layout, wal mode still kept the single-file WalStorage, whose log record for any item write is the whole table and whose compaction rewrites a snapshot of every table. Give the partitioned item store a journal mode for wal. Each write appends one record per changed item to dynamodb-items/journal.wal, and compaction, on the WAL compaction interval, rewrites only the shards changed since the last one and then empties the journal. Load replays the journal over the shard files. - Writes hold off compaction while they change memory and append their record, so the journal never drops a record whose change is not yet in a shard file; compaction waits until load has replayed the journal - A change the journal cannot take is compacted into its shard at once, and the write fails if that fails too - Replay stops at a torn or unreadable record, including one that decodes to null, and cuts it off - A journal that cannot be emptied is reopened, so later writes are still appended Part of #6293 * fix(dynamodb): journal changes to one key in the order they were applied Changes held only the shared side of the compaction lock, so a second write to the same item could update memory after the first and still append its record ahead of it. Replay follows the journal, so a restart before compaction restored the older value. Hold a per-key lock across the in-memory update and the journal append. Changes to different keys commute and stay concurrent. * fix(dynamodb): stop appending to a journal after a failed write A failed append could leave part of its record in the file while the writer stayed open. If the fallback compaction also failed, the next append succeeded behind the torn record, and replay cut it off with it, losing a write the caller saw succeed. Close the writer when a write fails, so every later change falls back to compaction until a compaction replaces the file and reopens the journal. * fix(dynamodb): treat a journal key that is not UTF-8 as unreadable Replay decoded keys leniently, so corrupt key bytes became U+FFFD and the record was applied to a different key, then kept by the next compaction. Decode journal strings with a strict UTF-8 decoder and end replay at a record whose key or entry key does not decode, like any torn record. * fix(dynamodb): fail load when the journal cannot be read Replay logged an I/O error (or a failure to read the journal's size) and returned normally, so load marked the store ready with records left unapplied. The next compaction then wrote the partial state to the shard files and emptied the journal, deleting writes that had been acknowledged. Replay now throws on any failure other than a torn or undecodable tail, and load turns that into a startup failure that leaves the journal untouched, as a failed migration does. A directory where the journal goes still counts as holding no records. * fix(dynamodb): fold a leftover wal journal when per-table runs in another mode Only wal mode read journal.wal. A wal-mode run that ended without compacting left its changes there, and a restart in persistent or hybrid mode ignored them: they were lost, and a later return to wal replayed them as stale changes over newer shard files. On load in another mode, replay a non-empty journal.wal, write the shards it changed and remove it. Fail to start, keeping the file, if a shard cannot be written or the file cannot be removed.
This commit is contained in:
1 parent
4f45541d44
commit
4c49f23c80
10 files changed
+1258
-69
No files matched your search
+466
@@ -0,0 +1,466 @@
|
||||
package io.github.hectorvent.floci.core.storage;
|
||||
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.EnumSource;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.DataOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.StandardOpenOption;
|
||||
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.Stream;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.junit.jupiter.api.Assumptions.assumeFalse;
|
||||
|
||||
/** {@link PartitionedFileStorage} in {@link PartitionedFileStorage.Mode#JOURNAL} mode. */
|
||||
class PartitionedFileStorageJournalTest {
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
/** Opens the store the way a restart after a crash would: whatever an earlier instance left. */
|
||||
private PartitionedFileStorage<String> open(int shards) {
|
||||
PartitionedFileStorage<String> storage = new PartitionedFileStorage<>(tempDir.resolve("items"),
|
||||
tempDir.resolve("items.json"), String.class, shards, PartitionedFileStorage.Mode.JOURNAL,
|
||||
Long.MAX_VALUE);
|
||||
storage.load();
|
||||
opened.add(storage);
|
||||
return storage;
|
||||
}
|
||||
|
||||
private Path journal() {
|
||||
return tempDir.resolve("items").resolve(PartitionedFileStorage.JOURNAL_FILE);
|
||||
}
|
||||
|
||||
private long shardFileCount() throws Exception {
|
||||
try (Stream<Path> files = Files.list(tempDir.resolve("items"))) {
|
||||
return files.filter(f -> f.getFileName().toString().endsWith(".json")).count();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void aWriteCostsOneRecordWhateverTheSizeOfItsKey() throws Exception {
|
||||
PartitionedFileStorage<String> storage = open(4);
|
||||
for (int i = 0; i < 100; i++) {
|
||||
storage.putEntry("big", "entry-" + i, "value");
|
||||
}
|
||||
long before = Files.size(journal());
|
||||
storage.putEntry("big", "entry-x", "value");
|
||||
long costAtOneHundred = Files.size(journal()) - before;
|
||||
|
||||
for (int i = 100; i < 10_000; i++) {
|
||||
storage.putEntry("big", "entry-" + i, "value");
|
||||
}
|
||||
before = Files.size(journal());
|
||||
storage.putEntry("big", "entry-y", "value");
|
||||
long costAtTenThousand = Files.size(journal()) - before;
|
||||
|
||||
assertTrue(costAtOneHundred > 0);
|
||||
assertEquals(costAtOneHundred, costAtTenThousand);
|
||||
assertEquals(0, shardFileCount(), "shard files are only written by compaction");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRestartWithoutCompactionReplaysEveryChange() {
|
||||
PartitionedFileStorage<String> crashed = open(4);
|
||||
crashed.put("table", Map.of("a", "1", "b", "2", "c", "3"));
|
||||
crashed.putEntry("table", "d", "4");
|
||||
crashed.removeEntry("table", "a");
|
||||
crashed.putEntry("gone", "x", "1");
|
||||
crashed.delete("gone");
|
||||
|
||||
PartitionedFileStorage<String> restarted = open(4);
|
||||
|
||||
assertEquals(Map.of("b", "2", "c", "3", "d", "4"), restarted.get("table").orElseThrow());
|
||||
assertTrue(restarted.get("gone").isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aCompactionBeforeTheFirstLoadKeepsTheJournal() {
|
||||
PartitionedFileStorage<String> crashed = open(1);
|
||||
crashed.putEntry("table", "a", "1");
|
||||
|
||||
// The compaction schedule starts with the constructor, so it can run before load().
|
||||
PartitionedFileStorage<String> restarting = new PartitionedFileStorage<>(tempDir.resolve("items"),
|
||||
tempDir.resolve("items.json"), String.class, 1, PartitionedFileStorage.Mode.JOURNAL, Long.MAX_VALUE);
|
||||
opened.add(restarting);
|
||||
restarting.flush();
|
||||
restarting.load();
|
||||
|
||||
assertEquals(Map.of("a", "1"), restarting.get("table").orElseThrow());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRecordThatDecodesToNullEndsReplayInsteadOfFailingLoad() throws Exception {
|
||||
byte[] cborNull = {(byte) 0xF6};
|
||||
byte[] mapWithNullValue = {(byte) 0xA1, 0x61, 'k', (byte) 0xF6};
|
||||
List<byte[]> badRecords = List.of(
|
||||
record(EntryJournal.OP_PUT_ENTRY, "table".getBytes(), "k".getBytes(), cborNull),
|
||||
record(EntryJournal.OP_PUT, "table".getBytes(), cborNull),
|
||||
record(EntryJournal.OP_PUT, "table".getBytes(), mapWithNullValue));
|
||||
open(1).putEntry("table", "a", "1");
|
||||
|
||||
for (byte[] bad : badRecords) {
|
||||
long goodLength = Files.size(journal());
|
||||
Files.write(journal(), bad, StandardOpenOption.APPEND);
|
||||
|
||||
PartitionedFileStorage<String> restarted = open(1);
|
||||
|
||||
assertEquals(Map.of("a", "1"), restarted.get("table").orElseThrow());
|
||||
assertEquals(goodLength, Files.size(journal()), "the unreadable record is cut off");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRecordWithAKeyThatIsNotUtf8EndsReplay() throws Exception {
|
||||
byte[] cborX = {0x61, 'x'};
|
||||
byte[] notUtf8 = {'t', 'a', 'b', 'l', (byte) 0xFF};
|
||||
List<byte[]> badRecords = List.of(
|
||||
record(EntryJournal.OP_PUT_ENTRY, notUtf8, "k".getBytes(), cborX),
|
||||
record(EntryJournal.OP_PUT_ENTRY, "table".getBytes(), new byte[]{(byte) 0xC3, 0x28}, cborX));
|
||||
open(1).putEntry("table", "a", "1");
|
||||
|
||||
for (byte[] bad : badRecords) {
|
||||
long goodLength = Files.size(journal());
|
||||
Files.write(journal(), bad, StandardOpenOption.APPEND);
|
||||
|
||||
PartitionedFileStorage<String> restarted = open(1);
|
||||
|
||||
assertEquals(Set.of("table"), restarted.keys());
|
||||
assertEquals(Map.of("a", "1"), restarted.get("table").orElseThrow());
|
||||
assertEquals(goodLength, Files.size(journal()), "the unreadable record is cut off");
|
||||
}
|
||||
}
|
||||
|
||||
/** One journal record: the op byte, then each part as a length-prefixed frame. */
|
||||
private static byte[] record(byte op, byte[]... parts) throws IOException {
|
||||
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
|
||||
DataOutputStream out = new DataOutputStream(bytes);
|
||||
out.writeByte(op);
|
||||
for (byte[] part : parts) {
|
||||
out.writeInt(part.length);
|
||||
out.write(part);
|
||||
}
|
||||
out.flush();
|
||||
return bytes.toByteArray();
|
||||
}
|
||||
|
||||
@Test
|
||||
void compactionRewritesOnlyChangedShardsAndEmptiesTheJournal() throws Exception {
|
||||
PartitionedFileStorage<String> storage = open(8);
|
||||
Map<String, String> entries = new HashMap<>();
|
||||
for (int i = 0; i < 200; i++) {
|
||||
entries.put("entry-" + i, "value-" + i);
|
||||
}
|
||||
storage.put("big", entries);
|
||||
storage.flush();
|
||||
assertEquals(8, shardFileCount());
|
||||
assertEquals(0, Files.size(journal()));
|
||||
try (Stream<Path> files = Files.list(tempDir.resolve("items"))) {
|
||||
for (Path file : files.toList()) {
|
||||
Files.setLastModifiedTime(file, LONG_AGO);
|
||||
}
|
||||
}
|
||||
Path touched = storage.fileFor("big", "entry-7");
|
||||
|
||||
storage.putEntry("big", "entry-7", "changed");
|
||||
storage.flush();
|
||||
|
||||
try (Stream<Path> files = Files.list(tempDir.resolve("items"))) {
|
||||
for (Path file : files.filter(f -> f.getFileName().toString().endsWith(".json")).toList()) {
|
||||
assertEquals(file.equals(touched), !LONG_AGO.equals(Files.getLastModifiedTime(file)),
|
||||
file.getFileName().toString());
|
||||
}
|
||||
}
|
||||
assertEquals(0, Files.size(journal()));
|
||||
entries.put("entry-7", "changed");
|
||||
assertEquals(entries, open(8).get("big").orElseThrow());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anIdleCompactionWritesNothing() throws Exception {
|
||||
PartitionedFileStorage<String> storage = open(1);
|
||||
storage.putEntry("table", "a", "1");
|
||||
storage.flush();
|
||||
Path file = storage.fileFor("table");
|
||||
Files.setLastModifiedTime(file, LONG_AGO);
|
||||
|
||||
storage.flush();
|
||||
|
||||
assertEquals(LONG_AGO, Files.getLastModifiedTime(file));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aTornTailIsCutAndLaterRecordsSurvive() throws Exception {
|
||||
PartitionedFileStorage<String> crashed = open(1);
|
||||
crashed.putEntry("table", "a", "1");
|
||||
crashed.putEntry("table", "b", "2");
|
||||
Files.write(journal(), new byte[]{0x01, 0x00, 0x00, 0x7f}, StandardOpenOption.APPEND);
|
||||
|
||||
PartitionedFileStorage<String> restarted = open(1);
|
||||
assertEquals(Map.of("a", "1", "b", "2"), restarted.get("table").orElseThrow());
|
||||
restarted.putEntry("table", "c", "3");
|
||||
|
||||
assertEquals(Map.of("a", "1", "b", "2", "c", "3"), open(1).get("table").orElseThrow());
|
||||
}
|
||||
|
||||
@Test
|
||||
void replayOverShardFilesAppliesOnlyTheNewerChanges() {
|
||||
PartitionedFileStorage<String> storage = open(2);
|
||||
storage.put("table", Map.of("a", "1", "b", "2"));
|
||||
storage.flush();
|
||||
storage.putEntry("table", "a", "changed");
|
||||
storage.removeEntry("table", "b");
|
||||
|
||||
assertEquals(Map.of("a", "changed"), open(2).get("table").orElseThrow());
|
||||
}
|
||||
|
||||
@Test
|
||||
void clearRemovesTheJournalAndEveryFile() throws Exception {
|
||||
PartitionedFileStorage<String> storage = open(2);
|
||||
storage.put("table", Map.of("a", "1"));
|
||||
storage.flush();
|
||||
storage.putEntry("table", "b", "2");
|
||||
|
||||
storage.clear();
|
||||
|
||||
assertEquals(0, shardFileCount());
|
||||
assertTrue(open(2).keys().isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void shutdownCompacts() throws Exception {
|
||||
PartitionedFileStorage<String> storage = open(1);
|
||||
storage.putEntry("table", "a", "1");
|
||||
|
||||
storage.shutdown();
|
||||
opened.remove(storage);
|
||||
|
||||
assertEquals(0, Files.size(journal()));
|
||||
assertEquals(1, shardFileCount());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aWriteRacingCompactionIsNeverLost() throws Exception {
|
||||
PartitionedFileStorage<String> live = open(1);
|
||||
live.putEntry("table", "early", "1");
|
||||
Thread[] writer = new Thread[1];
|
||||
live.setBeforeJournalTruncate(() -> {
|
||||
// The shards are written and the journal is about to be emptied. A write now must
|
||||
// wait for the compaction to finish, or its journal record is dropped unwritten.
|
||||
writer[0] = Thread.ofPlatform().start(() -> live.putEntry("table", "late", "2"));
|
||||
StorageTestThreads.awaitParkedOrDone(writer[0]);
|
||||
});
|
||||
|
||||
live.flush();
|
||||
live.setBeforeJournalTruncate(() -> { });
|
||||
writer[0].join(TimeUnit.SECONDS.toMillis(10));
|
||||
|
||||
assertFalse(writer[0].isAlive());
|
||||
assertEquals(Map.of("early", "1", "late", "2"), recoverCopy().get("table").orElseThrow());
|
||||
}
|
||||
|
||||
@Test
|
||||
void twoWritesToOneEntryReplayInTheOrderTheyWereApplied() throws Exception {
|
||||
PartitionedFileStorage<String> live = open(1);
|
||||
Thread[] second = new Thread[1];
|
||||
live.setBeforeJournalAppend(() -> {
|
||||
// The first write is in memory and about to be journaled. A second write to the same
|
||||
// entry must wait, or its record lands first and a replay ends on the older value.
|
||||
live.setBeforeJournalAppend(() -> { });
|
||||
second[0] = Thread.ofPlatform().start(() -> live.putEntry("table", "a", "second"));
|
||||
StorageTestThreads.awaitParkedOrDone(second[0]);
|
||||
});
|
||||
|
||||
live.putEntry("table", "a", "first");
|
||||
second[0].join(TimeUnit.SECONDS.toMillis(10));
|
||||
|
||||
assertFalse(second[0].isAlive());
|
||||
assertEquals(Map.of("a", "second"), live.get("table").orElseThrow());
|
||||
assertEquals(Map.of("a", "second"), recoverCopy().get("table").orElseThrow());
|
||||
}
|
||||
|
||||
/**
|
||||
* What a restart would recover right now, read from a copy of the directory so that opening
|
||||
* it, which replays and later compacts, cannot change the files the live store is using.
|
||||
*/
|
||||
private PartitionedFileStorage<String> recoverCopy() throws Exception {
|
||||
Path copy = tempDir.resolve("recovered");
|
||||
Files.createDirectories(copy);
|
||||
try (Stream<Path> files = Files.list(tempDir.resolve("items"))) {
|
||||
for (Path file : files.toList()) {
|
||||
Files.copy(file, copy.resolve(file.getFileName()));
|
||||
}
|
||||
}
|
||||
PartitionedFileStorage<String> recovered = new PartitionedFileStorage<>(copy, (Path) null, String.class, 1,
|
||||
PartitionedFileStorage.Mode.JOURNAL, Long.MAX_VALUE);
|
||||
recovered.load();
|
||||
opened.add(recovered);
|
||||
return recovered;
|
||||
}
|
||||
|
||||
@Test
|
||||
void aChangeTheJournalCannotTakeIsCompactedIntoItsShardAtOnce() throws Exception {
|
||||
// An empty directory where the journal goes: it cannot be opened, so the first append
|
||||
// fails, while the compaction that follows can remove it and start a real journal.
|
||||
Files.createDirectories(journal());
|
||||
PartitionedFileStorage<String> storage = open(1);
|
||||
|
||||
storage.putEntry("table", "a", "1");
|
||||
|
||||
assertTrue(Files.exists(storage.fileFor("table")), "the change reached its shard file");
|
||||
assertTrue(Files.isRegularFile(journal()));
|
||||
storage.putEntry("table", "b", "2");
|
||||
assertTrue(Files.size(journal()) > 0, "later changes are journaled again");
|
||||
assertEquals(Map.of("a", "1", "b", "2"), recoverCopy().get("table").orElseThrow());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aWriteAfterATornAppendIsNeverAcknowledgedBehindIt() throws Exception {
|
||||
PartitionedFileStorage<String> crashed = open(1);
|
||||
crashed.putEntry("table", "a", "1");
|
||||
// A non-empty directory where the shard file goes makes every fallback compaction fail.
|
||||
Path blocker = crashed.fileFor("table");
|
||||
Files.createDirectories(blocker);
|
||||
Files.writeString(blocker.resolve("child"), "x");
|
||||
crashed.setBeforeJournalWrite(file -> {
|
||||
// The write fails after part of the record reached the file.
|
||||
crashed.setBeforeJournalWrite(ignored -> { });
|
||||
Files.write(file, new byte[]{EntryJournal.OP_PUT_ENTRY, 0x00, 0x00, 0x7f}, StandardOpenOption.APPEND);
|
||||
throw new IOException("disk full");
|
||||
});
|
||||
|
||||
assertThrows(UncheckedIOException.class, () -> crashed.putEntry("table", "b", "2"));
|
||||
assertThrows(UncheckedIOException.class, () -> crashed.putEntry("table", "c", "3"),
|
||||
"a record appended behind the torn one would be lost on replay, so it is not acknowledged");
|
||||
|
||||
Files.delete(blocker.resolve("child"));
|
||||
Files.delete(blocker);
|
||||
crashed.putEntry("table", "d", "4");
|
||||
|
||||
assertEquals(Map.of("a", "1", "b", "2", "c", "3", "d", "4"), open(1).get("table").orElseThrow());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aJournalThatCannotBeReadFailsLoadAndIsNeverCompactedAway() throws Exception {
|
||||
PartitionedFileStorage<String> crashed = open(1);
|
||||
crashed.putEntry("table", "a", "1");
|
||||
StorageTestFiles.assumePosixPermissions(journal());
|
||||
Set<PosixFilePermission> original = Files.getPosixFilePermissions(journal());
|
||||
PartitionedFileStorage<String> restarting = new PartitionedFileStorage<>(tempDir.resolve("items"),
|
||||
tempDir.resolve("items.json"), String.class, 1, PartitionedFileStorage.Mode.JOURNAL, Long.MAX_VALUE);
|
||||
opened.add(restarting);
|
||||
Files.setPosixFilePermissions(journal(), PosixFilePermissions.fromString("---------"));
|
||||
try {
|
||||
// A root user reads through the mode, so there is nothing to test there.
|
||||
assumeFalse(Files.isReadable(journal()), "the journal stays readable for this user");
|
||||
|
||||
assertThrows(UncheckedIOException.class, restarting::load);
|
||||
restarting.flush();
|
||||
} finally {
|
||||
Files.setPosixFilePermissions(journal(), original);
|
||||
}
|
||||
|
||||
assertTrue(Files.size(journal()) > 0, "the unreplayed records are kept");
|
||||
assertEquals(Map.of("a", "1"), open(1).get("table").orElseThrow());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@EnumSource(value = PartitionedFileStorage.Mode.class, names = {"SYNC", "PERIODIC"})
|
||||
void anotherModeWritesALeftoverJournalIntoItsShardsAndRemovesIt(PartitionedFileStorage.Mode mode) {
|
||||
PartitionedFileStorage<String> crashed = open(1);
|
||||
crashed.put("table", Map.of("a", "1", "b", "2"));
|
||||
crashed.flush();
|
||||
crashed.putEntry("table", "a", "journaled");
|
||||
|
||||
PartitionedFileStorage<String> switched = new PartitionedFileStorage<>(tempDir.resolve("items"),
|
||||
tempDir.resolve("items.json"), String.class, 1, mode, Long.MAX_VALUE);
|
||||
opened.add(switched);
|
||||
switched.load();
|
||||
|
||||
assertEquals(Map.of("a", "journaled", "b", "2"), switched.get("table").orElseThrow());
|
||||
assertFalse(Files.exists(journal()), "the journal is folded into the shard files and removed");
|
||||
switched.putEntry("table", "a", "newer");
|
||||
switched.flush();
|
||||
|
||||
// Back in journal mode, nothing stale is replayed over the newer shard file.
|
||||
assertEquals(Map.of("a", "newer", "b", "2"), open(1).get("table").orElseThrow());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aShardThatCannotBeWrittenKeepsTheJournal() throws Exception {
|
||||
PartitionedFileStorage<String> crashed = open(1);
|
||||
crashed.putEntry("table", "a", "1");
|
||||
// A non-empty directory where the shard file goes makes only that write fail.
|
||||
Path blocker = crashed.fileFor("table");
|
||||
Files.createDirectories(blocker);
|
||||
Files.writeString(blocker.resolve("child"), "x");
|
||||
|
||||
assertThrows(UncheckedIOException.class, crashed::flush, "a shard left unwritten is reported");
|
||||
|
||||
assertTrue(Files.size(journal()) > 0, "the journal still holds the unwritten change");
|
||||
Files.delete(blocker.resolve("child"));
|
||||
Files.delete(blocker);
|
||||
assertEquals(Map.of("a", "1"), open(1).get("table").orElseThrow());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aJournalThatCannotBeEmptiedStaysOpenForLaterChanges() throws Exception {
|
||||
PartitionedFileStorage<String> crashed = open(1);
|
||||
crashed.putEntry("table", "a", "1");
|
||||
Path directory = tempDir.resolve("items");
|
||||
StorageTestFiles.assumePosixPermissions(directory);
|
||||
Set<PosixFilePermission> original = Files.getPosixFilePermissions(directory);
|
||||
crashed.setBeforeJournalTruncate(() -> {
|
||||
// The shards are written; now make emptying the journal fail.
|
||||
try {
|
||||
Files.setPosixFilePermissions(directory, PosixFilePermissions.fromString("r-xr-xr-x"));
|
||||
} catch (IOException e) {
|
||||
throw new UncheckedIOException(e);
|
||||
}
|
||||
});
|
||||
try {
|
||||
UncheckedIOException failure = null;
|
||||
try {
|
||||
crashed.flush();
|
||||
} catch (UncheckedIOException e) {
|
||||
failure = e;
|
||||
}
|
||||
// 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");
|
||||
assertNotNull(failure, "a journal left unemptied is reported");
|
||||
} finally {
|
||||
crashed.setBeforeJournalTruncate(() -> { });
|
||||
Files.setPosixFilePermissions(directory, original);
|
||||
}
|
||||
|
||||
crashed.putEntry("table", "b", "2");
|
||||
|
||||
assertEquals(Map.of("a", "1", "b", "2"), open(1).get("table").orElseThrow());
|
||||
}
|
||||
}
|
||||
@@ -290,6 +290,7 @@ class PartitionedFileStorageTest {
|
||||
Path legacy = tempDir.resolve("items.json");
|
||||
new ObjectMapper().writeValue(legacy.toFile(), Map.of("a", Map.of("k", "1")));
|
||||
Files.createDirectories(tempDir.resolve("items"));
|
||||
Files.createFile(tempDir.resolve("items").resolve(PartitionedFileStorage.JOURNAL_FILE));
|
||||
|
||||
assertEquals(Map.of("k", "1"), open(PartitionedFileStorage.Mode.SYNC).get("a").orElseThrow());
|
||||
assertTrue(Files.exists(tempDir.resolve("items.json.migrated")));
|
||||
|
||||
+34
-10
@@ -76,13 +76,37 @@ class StorageFactoryPartitionedTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void walModeKeepsTheSingleFileStoreForNow() {
|
||||
AccountAwareStorageBackend<Map<String, String>> store = newFactory("wal")
|
||||
.createPartitioned("svc", "svc-items.json", TYPE, String.class, 4);
|
||||
void walModeJournalsChangesAndCompactsOnShutdown() {
|
||||
StorageFactory factory = newFactory("wal");
|
||||
AccountAwareStorageBackend<Map<String, String>> store =
|
||||
factory.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")));
|
||||
store.putEntry("table-a", "k", "v");
|
||||
assertEquals(0, fileCount(tempDir.resolve("svc-items")));
|
||||
assertTrue(Files.exists(tempDir.resolve("svc-items").resolve(PartitionedFileStorage.JOURNAL_FILE)));
|
||||
|
||||
factory.shutdownAll();
|
||||
assertEquals(1, fileCount(tempDir.resolve("svc-items")));
|
||||
assertEquals(Map.of("k", "v"), newFactory("wal")
|
||||
.createPartitioned("svc", "svc-items.json", TYPE, String.class, 1).get("table-a").orElseThrow());
|
||||
}
|
||||
|
||||
@Test
|
||||
void walModeMigratesALegacyWalStoreIncludingItsUncompactedLog() {
|
||||
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("wal")
|
||||
.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());
|
||||
assertFalse(Files.exists(tempDir.resolve("svc-items.wal")));
|
||||
assertTrue(Files.exists(tempDir.resolve("svc-items-snapshot.json.migrated")));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -112,7 +136,7 @@ class StorageFactoryPartitionedTest {
|
||||
// What a crash right after the directory was created leaves behind.
|
||||
Files.createDirectories(tempDir.resolve("svc-items"));
|
||||
|
||||
AccountAwareStorageBackend<Map<String, String>> store = newFactory("hybrid")
|
||||
AccountAwareStorageBackend<Map<String, String>> store = newFactory("wal")
|
||||
.createPartitioned("svc", "svc-items.json", TYPE, String.class, 1);
|
||||
|
||||
assertEquals(Map.of("k", "v"), store.get("table-a").orElseThrow());
|
||||
@@ -131,7 +155,7 @@ class StorageFactoryPartitionedTest {
|
||||
Files.setLastModifiedTime(tempDir.resolve("svc-items-snapshot.json"), older);
|
||||
Files.setLastModifiedTime(tempDir.resolve("svc-items.wal"), older);
|
||||
|
||||
AccountAwareStorageBackend<Map<String, String>> store = newFactory("hybrid")
|
||||
AccountAwareStorageBackend<Map<String, String>> store = newFactory("wal")
|
||||
.createPartitioned("svc", "svc-items.json", TYPE, String.class, 1);
|
||||
|
||||
assertEquals(Map.of("k", "from-plain"), store.get("table-a").orElseThrow());
|
||||
@@ -153,14 +177,14 @@ class StorageFactoryPartitionedTest {
|
||||
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")
|
||||
assertThrows(UncheckedIOException.class, () -> newFactory("wal")
|
||||
.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")
|
||||
assertEquals(Map.of("k", "only-in-the-log"), newFactory("wal")
|
||||
.createPartitioned("svc", "svc-items.json", TYPE, String.class, 1).get("table-a").orElseThrow());
|
||||
legacy.shutdown();
|
||||
}
|
||||
|
||||
+124
@@ -0,0 +1,124 @@
|
||||
package io.github.hectorvent.floci.services.dynamodb;
|
||||
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
import io.github.hectorvent.floci.testing.DynamoDbPartitionedWalStorageProfile;
|
||||
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import jakarta.inject.Inject;
|
||||
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.DynamoDbPartitionedWalStorageProfile.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;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/**
|
||||
* The {@code per-table} item layout in {@code wal} mode, end to end through the application:
|
||||
* the configuration selects the partitioned item store, a write lands in its journal rather than
|
||||
* in a single items file, and a compaction moves it into shard files, one set per account.
|
||||
*/
|
||||
@QuarkusTest
|
||||
@TestProfile(DynamoDbPartitionedWalStorageProfile.class)
|
||||
class DynamoDbPartitionedWalStorageIntegrationTest {
|
||||
|
||||
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";
|
||||
|
||||
@Inject
|
||||
StorageFactory storageFactory;
|
||||
|
||||
@BeforeAll
|
||||
static void configureRestAssured() {
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
}
|
||||
|
||||
@Test
|
||||
void itemsGoThroughTheJournalIntoPerAccountShardFiles() throws IOException {
|
||||
// The directory outlives a run, so each run uses its own table name.
|
||||
String table = "partitioned-wal-" + UUID.randomUUID();
|
||||
Path itemsDirectory = Path.of(STORAGE_DIR, "dynamodb-items");
|
||||
Path journal = itemsDirectory.resolve("journal.wal");
|
||||
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"));
|
||||
|
||||
assertTrue(Files.size(journal) > 0, "the writes are in the journal");
|
||||
assertFalse(Files.exists(Path.of(STORAGE_DIR, "dynamodb-items.json")));
|
||||
|
||||
storageFactory.flushAll();
|
||||
|
||||
assertEquals(0, Files.size(journal), "compaction empties the journal");
|
||||
assertEquals(2, shardFilesOf(itemsDirectory, table), "one shard file per account's table");
|
||||
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 wal} 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 DynamoDbPartitionedWalStorageIntegrationTest} relies on all of it: it checks that the
|
||||
* configuration reaches the item store and that the item store writes the journal and shards.
|
||||
*/
|
||||
public class DynamoDbPartitionedWalStorageProfile implements QuarkusTestProfile {
|
||||
|
||||
public static final String STORAGE_DIR = "target/dynamodb-partitioned-wal-it";
|
||||
|
||||
@Override
|
||||
public Map<String, String> getConfigOverrides() {
|
||||
return Map.of(
|
||||
"floci.storage.services.dynamodb.mode", "wal",
|
||||
"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