diff --git a/docs/services/dynamodb.md b/docs/services/dynamodb.md
index ef2a88516c..7e31d8cf26 100644
--- a/docs/services/dynamodb.md
+++ b/docs/services/dynamodb.md
@@ -258,9 +258,9 @@ With the default `single-file` layout, every table's items live in one `dynamodb
|---|---|
| `persistent` | Rewrites the one file that holds the item |
| `hybrid` | Marks that file dirty; dirty files are rewritten on the flush interval |
-| `wal` | Not supported yet: the items stay in the `single-file` layout, and a warning is logged at startup |
+| `wal` | Appends one record for the item to `dynamodb-items/journal.wal`; dirty files are rewritten and the journal emptied on `FLOCI_STORAGE_WAL_COMPACTION_INTERVAL_MS` |
-On first start with `per-table`, an existing `dynamodb-items.json` or a `wal`-mode `dynamodb-items-snapshot.json` and `dynamodb-items.wal` is migrated into the directory, and those files are renamed with a `.migrated` suffix. When both kinds exist, the one written last is migrated. The migration is written to a staging directory and moved in place in one step, so a crash leaves either no directory or a complete one. If it cannot be written, Floci fails to start and the old files stay untouched. Once the directory holds data, old files are ignored. Switching back to `single-file` does not read the directory. A write that cannot be saved where its mode promises fails with an error, instead of only being logged: in `persistent` mode the shard file must be written before the write returns. The change stays in memory and is written by the next flush. Changing the shard count rewrites the files on the next start. The other DynamoDB stores (tables, backups, point-in-time recovery history, exports, imports) keep their single files.
+On first start with `per-table`, in any storage mode, an existing `dynamodb-items.json` or a `wal`-mode `dynamodb-items-snapshot.json` and `dynamodb-items.wal` is migrated into the directory, and those files are renamed with a `.migrated` suffix. When both kinds exist, the one written last is migrated. The migration is written to a staging directory and moved in place in one step, so a crash leaves either no directory or a complete one. If it cannot be written, Floci fails to start and the old files stay untouched. Once the directory holds data, old files are ignored. Switching back to `single-file` does not read the directory. A write that cannot be saved where its mode promises fails with an error, instead of only being logged: in `persistent` mode the shard file must be written, and in `wal` mode a change the journal cannot take is written to its shard file at once. The change stays in memory and is written by the next flush. Changing the shard count rewrites the files on the next start. Starting `per-table` in `persistent` or `hybrid` mode after a `wal` run that ended without compacting writes the changes left in `journal.wal` into the shard files and removes it. If `journal.wal` cannot be read, Floci fails to start and leaves it untouched. The other DynamoDB stores (tables, backups, point-in-time recovery history, exports, imports) keep their single files.
## Examples
diff --git a/src/main/java/io/github/hectorvent/floci/core/storage/EntryJournal.java b/src/main/java/io/github/hectorvent/floci/core/storage/EntryJournal.java
new file mode 100644
index 0000000000..989729d7cd
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/core/storage/EntryJournal.java
@@ -0,0 +1,336 @@
+package io.github.hectorvent.floci.core.storage;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.JavaType;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.dataformat.cbor.CBORFactory;
+import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
+import org.jboss.logging.Logger;
+
+import java.io.BufferedInputStream;
+import java.io.BufferedOutputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.DataInputStream;
+import java.io.DataOutputStream;
+import java.io.EOFException;
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.nio.channels.FileChannel;
+import java.nio.charset.CharacterCodingException;
+import java.nio.charset.CodingErrorAction;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.StandardOpenOption;
+import java.util.Map;
+import java.util.function.Consumer;
+
+/**
+ * The append-only journal of a {@link PartitionedFileStorage} in journal mode: one record per
+ * changed map entry, so a change costs the size of that entry, not of the value it belongs to.
+ *
+ *
Record format, every string UTF-8 and every value Jackson CBOR, each length-prefixed with a
+ * 4-byte length:
+ *
+ * PUT_ENTRY: [0x01] [key] [entry key] [entry value]
+ * REMOVE_ENTRY: [0x02] [key] [entry key]
+ * PUT: [0x03] [key] [whole map]
+ * DELETE: [0x04] [key]
+ *
+ *
+ * Replay stops at the first record that cannot be framed or decoded (a tail torn by a crash)
+ * and cuts the file there, so records appended afterwards are not hidden behind the garbage.
+ *
+ * @param the type of one map entry's value
+ */
+final class EntryJournal {
+
+ private static final Logger LOG = Logger.getLogger(EntryJournal.class);
+
+ static final byte OP_PUT_ENTRY = 0x01;
+ static final byte OP_REMOVE_ENTRY = 0x02;
+ static final byte OP_PUT = 0x03;
+ static final byte OP_DELETE = 0x04;
+
+ /** One replayed change. */
+ sealed interface Change {
+ String key();
+ }
+
+ record PutEntry(String key, String entryKey, E value) implements Change {}
+
+ record RemoveEntry(String key, String entryKey) implements Change {}
+
+ record Put(String key, Map value) implements Change {}
+
+ record Delete(String key) implements Change {}
+
+ private final Path path;
+ private final ObjectMapper mapper;
+ private final JavaType entryType;
+ private final JavaType entriesType;
+ private volatile DataOutputStream writer;
+ // Runs just before a record is written to the file. Tests use it to make a write fail midway.
+ private volatile WriteHook beforeWrite = file -> { };
+
+ /** A step run against the journal file that may fail like a write to it. */
+ interface WriteHook {
+ void run(Path file) throws IOException;
+ }
+
+ EntryJournal(Path path, JavaType entryType, JavaType entriesType) {
+ this.path = path;
+ this.entryType = entryType;
+ this.entriesType = entriesType;
+ this.mapper = new ObjectMapper(new CBORFactory());
+ this.mapper.registerModule(new JavaTimeModule());
+ }
+
+ // Each append returns whether its record reached the journal file.
+
+ boolean putEntry(String key, String entryKey, E value) {
+ return append(OP_PUT_ENTRY, key, entryKey, value);
+ }
+
+ boolean removeEntry(String key, String entryKey) {
+ return append(OP_REMOVE_ENTRY, key, entryKey, null);
+ }
+
+ boolean put(String key, Map value) {
+ return append(OP_PUT, key, null, value);
+ }
+
+ boolean delete(String key) {
+ return append(OP_DELETE, key, null, null);
+ }
+
+ /** Whether the journal holds any record. */
+ boolean isEmpty() {
+ try {
+ return !Files.exists(path) || Files.size(path) == 0;
+ } catch (IOException e) {
+ LOG.warnv(e, "Failed to read the size of {0}", path);
+ return false;
+ }
+ }
+
+ /**
+ * Applies every readable record in order and returns how many were applied. A torn or
+ * undecodable tail ends replay and is cut off.
+ *
+ * @throws IOException when the file could not be read to its end: records past the failure
+ * were not applied and are kept, so the caller must not empty the journal
+ */
+ int replay(Consumer> apply) throws IOException {
+ if (!Files.exists(path)) {
+ return 0;
+ }
+ if (Files.isDirectory(path)) {
+ // Holds no records; the first append fails and compaction replaces it with a file.
+ LOG.warnv("{0} is a directory, not a journal", path);
+ return 0;
+ }
+ long fileSize = Files.size(path);
+ int replayed = 0;
+ long consumed = 0;
+ try (DataInputStream in = new DataInputStream(new BufferedInputStream(Files.newInputStream(path)))) {
+ while (consumed < fileSize) {
+ long[] position = {consumed + 1};
+ byte op = in.readByte();
+ String key = readString(in, fileSize, position);
+ Change change = switch (op) {
+ case OP_PUT_ENTRY -> {
+ String entryKey = readString(in, fileSize, position);
+ byte[] value = readFrame(in, fileSize, position);
+ E decoded = value == null ? null : mapper.readValue(value, entryType);
+ yield decoded == null || entryKey == null || key == null
+ ? null : new PutEntry<>(key, entryKey, decoded);
+ }
+ case OP_REMOVE_ENTRY -> {
+ String entryKey = readString(in, fileSize, position);
+ yield entryKey == null || key == null ? null : new RemoveEntry<>(key, entryKey);
+ }
+ case OP_PUT -> {
+ byte[] value = readFrame(in, fileSize, position);
+ Map decoded = value == null ? null : mapper.readValue(value, entriesType);
+ // A null map, or one holding a null key or value, cannot be stored: the
+ // record is as unreadable as a torn one.
+ yield decoded == null || key == null || hasNull(decoded) ? null : new Put<>(key, decoded);
+ }
+ case OP_DELETE -> key == null ? null : new Delete<>(key);
+ default -> null;
+ };
+ if (change == null) {
+ LOG.warnv("Unreadable record at offset {0} of {1}, stopping replay", consumed, path);
+ break;
+ }
+ apply.accept(change);
+ consumed = position[0];
+ replayed++;
+ }
+ } catch (EOFException | JsonProcessingException e) {
+ LOG.warnv("{0} is unreadable from offset {1}: {2}", path, consumed, e.getMessage());
+ }
+ if (consumed < fileSize) {
+ cutTail(consumed, fileSize);
+ }
+ return replayed;
+ }
+
+ void open() {
+ close();
+ try {
+ Files.createDirectories(path.getParent());
+ writer = new DataOutputStream(new BufferedOutputStream(Files.newOutputStream(path,
+ StandardOpenOption.CREATE, StandardOpenOption.APPEND)));
+ } catch (IOException e) {
+ LOG.errorv(e, "Failed to open journal {0}", path);
+ }
+ }
+
+ void close() {
+ DataOutputStream out = writer;
+ writer = null;
+ if (out != null) {
+ try {
+ out.close();
+ } catch (IOException e) {
+ LOG.errorv(e, "Failed to close journal {0}", path);
+ }
+ }
+ }
+
+ /** Drops every record; the caller holds off appends while it does. */
+ void truncate() throws IOException {
+ close();
+ try {
+ Files.deleteIfExists(path);
+ } finally {
+ // Reopen even when the delete failed, so later records are still appended.
+ open();
+ }
+ }
+
+ void deleteFile() {
+ close();
+ try {
+ Files.deleteIfExists(path);
+ } catch (IOException e) {
+ LOG.errorv(e, "Failed to delete journal {0}", path);
+ }
+ }
+
+ void setBeforeWrite(WriteHook hook) {
+ this.beforeWrite = hook;
+ }
+
+ private boolean append(byte op, String key, String entryKey, Object value) {
+ DataOutputStream out = writer;
+ if (out == null) {
+ LOG.errorv("Journal {0} is not open; a change to {1} was not journaled", path, key);
+ return false;
+ }
+ try {
+ // Encode off the shared writer so the lock is held for one write.
+ ByteArrayOutputStream bytes = new ByteArrayOutputStream();
+ DataOutputStream record = new DataOutputStream(bytes);
+ record.writeByte(op);
+ writeFrame(record, key.getBytes(StandardCharsets.UTF_8));
+ if (entryKey != null) {
+ writeFrame(record, entryKey.getBytes(StandardCharsets.UTF_8));
+ }
+ if (op == OP_PUT_ENTRY || op == OP_PUT) {
+ writeFrame(record, mapper.writeValueAsBytes(value));
+ }
+ record.flush();
+ synchronized (out) {
+ if (writer != out) {
+ LOG.errorv("Journal {0} was closed; a change to {1} was not journaled", path, key);
+ return false;
+ }
+ try {
+ beforeWrite.run(path);
+ bytes.writeTo(out);
+ out.flush();
+ } catch (IOException e) {
+ // Part of the record may be on disk. A later record appended behind it would be
+ // cut off with it on replay, so stop appending until compaction replaces the file.
+ writer = null;
+ closeQuietly(out);
+ throw e;
+ }
+ }
+ return true;
+ } catch (IOException e) {
+ LOG.errorv(e, "Failed to append to journal {0}; it takes no more records until it is compacted", path);
+ return false;
+ }
+ }
+
+ private void closeQuietly(DataOutputStream out) {
+ try {
+ out.close();
+ } catch (IOException e) {
+ LOG.warnv(e, "Failed to close journal {0} after a failed append", path);
+ }
+ }
+
+ private static void writeFrame(DataOutputStream out, byte[] bytes) throws IOException {
+ out.writeInt(bytes.length);
+ out.write(bytes);
+ }
+
+ private static boolean hasNull(Map, ?> map) {
+ for (Map.Entry, ?> entry : map.entrySet()) {
+ if (entry.getKey() == null || entry.getValue() == null) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ /** Reads one frame as strict UTF-8, or {@code null} when it is torn or not valid UTF-8. */
+ private static String readString(DataInputStream in, long fileSize, long[] position) throws IOException {
+ byte[] bytes = readFrame(in, fileSize, position);
+ if (bytes == null) {
+ return null;
+ }
+ try {
+ // A lenient decode would swap bad bytes for U+FFFD and apply the change to another key.
+ return StandardCharsets.UTF_8.newDecoder()
+ .onMalformedInput(CodingErrorAction.REPORT)
+ .onUnmappableCharacter(CodingErrorAction.REPORT)
+ .decode(ByteBuffer.wrap(bytes))
+ .toString();
+ } catch (CharacterCodingException e) {
+ return null;
+ }
+ }
+
+ /** Reads one length-prefixed frame, or {@code null} when its length runs past the file. */
+ private static byte[] readFrame(DataInputStream in, long fileSize, long[] position) throws IOException {
+ if (fileSize - position[0] < 4) {
+ return null;
+ }
+ int length = in.readInt();
+ if (length < 0 || length > fileSize - position[0] - 4) {
+ return null;
+ }
+ byte[] bytes = in.readNBytes(length);
+ if (bytes.length != length) {
+ return null;
+ }
+ position[0] += 4 + length;
+ return bytes;
+ }
+
+ private void cutTail(long lastGoodOffset, long fileSize) {
+ try (FileChannel channel = FileChannel.open(path, StandardOpenOption.WRITE)) {
+ channel.truncate(lastGoodOffset);
+ LOG.warnv("Cut {0} unreadable bytes from the end of {1} at offset {2}; the records in them are lost",
+ fileSize - lastGoodOffset, path, lastGoodOffset);
+ } catch (IOException e) {
+ LOG.errorv(e, "Failed to cut the unreadable tail of {0}", path);
+ }
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/core/storage/PartitionedFileStorage.java b/src/main/java/io/github/hectorvent/floci/core/storage/PartitionedFileStorage.java
index 921cd8d533..e88db18854 100644
--- a/src/main/java/io/github/hectorvent/floci/core/storage/PartitionedFileStorage.java
+++ b/src/main/java/io/github/hectorvent/floci/core/storage/PartitionedFileStorage.java
@@ -31,7 +31,9 @@ import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
+import java.util.function.BooleanSupplier;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;
@@ -52,7 +54,12 @@ import java.util.stream.Stream;
*
* A {@link Mode#SYNC} store writes a shard's file before the mutating call returns, like
* {@link PersistentStorage}. A {@link Mode#PERIODIC} store marks the shard dirty and writes every
- * dirty shard on the flush interval, like {@link HybridStorage}.
+ * dirty shard on the flush interval, like {@link HybridStorage}. A {@link Mode#JOURNAL} store
+ * appends one record per changed entry to {@value #JOURNAL_FILE} in the directory, like
+ * {@link WalStorage}, but its compaction rewrites only the shards changed since the last one
+ * instead of a snapshot of the whole store. Load replays the journal over the shard files. A
+ * store in another mode that finds a journal left by a journal-mode run writes its changes into
+ * the shard files on load and removes it.
*
*
While the directory holds no data, a legacy single-file store (the {@code Map>} file the other backends write, or a {@code wal} snapshot and log) is migrated:
@@ -66,6 +73,7 @@ public class PartitionedFileStorage implements StorageBackend implements StorageBackend implements StorageBackend journal;
+ // Outside journal mode: the journal a crashed journal-mode run may have left, read once on load.
+ private final EntryJournal leftoverJournal;
+ // Journal mode: changes hold the read lock while they update memory and append their record,
+ // and compaction holds the write lock while it writes dirty shards and truncates the journal,
+ // so the journal never drops a record whose change is not yet in a shard file. In every mode,
+ // shard writes hold the read lock and load and clear hold the write lock.
+ private final ReentrantReadWriteLock compactionLock = new ReentrantReadWriteLock();
+ // Journal mode: a change holds its key's lock while it updates memory and appends its record,
+ // so two changes to one key are journaled in the order they were applied. Replay follows the
+ // journal's order; changes to different keys commute, so they need no common order.
+ private final ConcurrentHashMap changeLocks = new ConcurrentHashMap<>();
+ // Runs inside a journaled change after memory was updated and before its record is appended:
+ // the moment a second change to the same key could overtake it. Tests use it to stage that.
+ private volatile Runnable beforeJournalAppend = () -> { };
+ // Runs inside compaction between the last shard write and emptying the journal: the moment a
+ // change that slipped past the lock would be lost. Tests use it to stage that change.
+ private volatile Runnable beforeJournalTruncate = () -> { };
// Runs inside a shard write after the shard was read and before its file is replaced: the
// moment a clear() that slipped past the lock would be undone. Tests use it to stage that.
private volatile Runnable beforeShardWrite = () -> { };
// Runs on load after superseded files were rewritten under their current names and before
// the old files are removed. Tests use it to make only the removal fail.
private volatile Runnable beforeSupersededDelete = () -> { };
+ // Set once load() has replayed the journal; compaction waits for it.
+ private volatile boolean loaded;
/**
* @param directory where the shard files live
@@ -133,7 +162,8 @@ public class PartitionedFileStorage implements StorageBackend entryType, int shardCount,
Mode mode, long flushIntervalMs) {
@@ -159,6 +189,10 @@ public class PartitionedFileStorage implements StorageBackend journalFile = new EntryJournal<>(directory.resolve(JOURNAL_FILE),
+ mapper.constructType(entryType), entriesType);
+ this.journal = mode == Mode.JOURNAL ? journalFile : null;
+ this.leftoverJournal = mode == Mode.JOURNAL ? null : journalFile;
this.scheduler = mode == Mode.SYNC
? null
: StorageFiles.scheduleEvery("partitioned-storage-flush", flushIntervalMs, this::flushQuietly);
@@ -168,8 +202,15 @@ public class PartitionedFileStorage implements StorageBackend value) {
- applyPut(key, value);
- persistChange(allShardsOf(key));
+ boolean journaled;
+ ReentrantLock lock = beginChange(key);
+ try {
+ applyPut(key, value);
+ journaled = journal == null || journalAppend(() -> journal.put(key, value));
+ } finally {
+ endChange(lock);
+ }
+ persistChange(journaled, allShardsOf(key));
}
@Override
@@ -186,8 +227,15 @@ public class PartitionedFileStorage implements StorageBackend journal.delete(key));
+ } finally {
+ endChange(lock);
+ }
+ persistChange(journaled, allShardsOf(key));
}
@Override
@@ -204,14 +252,14 @@ public class PartitionedFileStorage implements StorageBackend 0) {
throw new UncheckedIOException(new IOException(
"Could not write " + failed + " shards of " + directory + "; see the errors logged above"));
@@ -220,26 +268,79 @@ public class PartitionedFileStorage implements StorageBackend source) {
+ int replayed;
+ try {
+ replayed = source.replay(this::applyReplayed);
+ } catch (IOException e) {
+ // Compaction would write the partial state and empty the journal, losing the
+ // records not yet read: refuse to start instead, as a failed migration does.
+ throw new UncheckedIOException("Failed to replay the journal of " + directory
+ + "; it is untouched, fix the cause and restart", e);
+ }
+ if (replayed > 0) {
+ LOG.infov("Replayed {0} journal records into {1}", replayed, directory);
+ }
+ }
+
+ /**
+ * Folds the journal of a journal-mode run that ended without compacting into the shard files,
+ * then removes it. Ignored, its changes would be lost now and replayed as stale ones over newer
+ * shard files once the store is back in journal mode.
+ */
+ private void foldLeftoverJournal() {
+ Path file = directory.resolve(JOURNAL_FILE);
+ LOG.warnv("Found {0}, left by a wal-mode run; writing its changes into the shard files", file);
+ replayJournal(leftoverJournal);
+ writeDirtyShards();
+ if (!dirty.isEmpty()) {
+ throw new IllegalStateException("Could not write " + dirty.size() + " shards of " + directory
+ + " from " + file + "; it is kept, fix the cause and restart");
+ }
+ try {
+ Files.deleteIfExists(file);
+ } catch (IOException e) {
+ throw new UncheckedIOException("Failed to remove " + file
+ + "; its changes are in the shard files, remove it and restart", e);
}
}
@Override
public synchronized void clear() {
- fileLock.writeLock().lock();
+ compactionLock.writeLock().lock();
try {
store.clear();
dirty.clear();
+ if (journal != null) {
+ journal.deleteFile();
+ }
if (Files.isDirectory(directory)) {
try (DirectoryStream files = Files.newDirectoryStream(directory, "*" + FILE_SUFFIX)) {
for (Path file : files) {
@@ -249,8 +350,11 @@ public class PartitionedFileStorage implements StorageBackend implements StorageBackend journal.putEntry(key, entryKey, entryValue));
+ } finally {
+ endChange(lock);
+ }
+ persistChange(journaled, List.of(id));
}
@Override
public void removeEntry(String key, String entryKey) {
- ShardId id = applyRemoveEntry(key, entryKey);
+ ShardId id;
+ boolean journaled;
+ ReentrantLock lock = beginChange(key);
+ try {
+ id = applyRemoveEntry(key, entryKey);
+ journaled = id == null || journal == null || journalAppend(() -> journal.removeEntry(key, entryKey));
+ } finally {
+ endChange(lock);
+ }
if (id != null) {
- persistChange(List.of(id));
+ persistChange(journaled, List.of(id));
}
}
// ---
- /** Stops the flush schedule and writes what is still dirty. */
+ /** Stops the flush schedule and writes what is still dirty; a journal is compacted and closed. */
public void shutdown() {
if (scheduler != null) {
StorageFiles.stop(scheduler);
}
- flush();
+ try {
+ flush();
+ } finally {
+ if (journal != null) {
+ journal.close();
+ }
+ }
}
/**
- * Writes the changed shards of a sync store before the call returns; a periodic store leaves
- * them to the next flush.
+ * Makes a change that is already in memory durable where its mode promises it: a sync store
+ * writes the changed shards now, and a journal store whose record could not be appended
+ * compacts now instead, so the change still reaches a shard file before the call returns.
+ * (Writing only the changed shard would put it ahead of older records still in the journal,
+ * which a replay would then apply over it.) A periodic store leaves it to the next flush.
*
- * @throws UncheckedIOException when a shard could not be written; the change stays in memory
+ * @throws UncheckedIOException when the change could not be made durable; it stays in memory
* and dirty, so a later flush writes it
*/
- private void persistChange(List changed) {
- if (mode != Mode.SYNC) {
- return;
- }
+ private void persistChange(boolean journaled, List changed) {
int failed = 0;
- for (ShardId id : changed) {
- if (!writeShard(id)) {
- failed++;
+ if (mode == Mode.SYNC) {
+ for (ShardId id : changed) {
+ if (!writeShard(id)) {
+ failed++;
+ }
}
+ } else if (!journaled) {
+ failed = compact();
}
if (failed > 0) {
throw new UncheckedIOException(new IOException(
@@ -303,7 +434,46 @@ public class PartitionedFileStorage implements StorageBackend 0) {
+ LOG.errorv("Could not write {0} shards of {1}; keeping the journal", failed, directory);
+ return failed;
+ }
+ beforeJournalTruncate.run();
+ journal.truncate();
+ return 0;
+ } catch (IOException e) {
+ LOG.errorv(e, "Failed to truncate the journal of {0}", directory);
+ return 1;
+ } finally {
+ compactionLock.writeLock().unlock();
+ }
+ }
+
+ private void applyReplayed(EntryJournal.Change change) {
+ switch (change) {
+ case EntryJournal.PutEntry put -> applyPutEntry(put.key(), put.entryKey(), put.value());
+ case EntryJournal.RemoveEntry remove -> applyRemoveEntry(remove.key(), remove.entryKey());
+ case EntryJournal.Put put -> applyPut(put.key(), put.value());
+ case EntryJournal.Delete delete -> applyDelete(delete.key());
+ }
+ }
+
+ // The apply methods change memory and mark what they change dirty. Live changes call them
+ // under the change lock and then journal the change; replay calls them for journal records.
private ShardId applyPutEntry(String key, String entryKey, E entryValue) {
ShardId id = new ShardId(key, shardOf(entryKey));
@@ -333,6 +503,29 @@ public class PartitionedFileStorage implements StorageBackend new ReentrantLock());
+ lock.lock();
+ return lock;
+ }
+
+ private void endChange(ReentrantLock lock) {
+ if (lock != null) {
+ lock.unlock();
+ compactionLock.readLock().unlock();
+ }
+ }
+
+ private boolean journalAppend(BooleanSupplier append) {
+ beforeJournalAppend.run();
+ return append.getAsBoolean();
+ }
+
/** Writes every dirty shard and returns how many could not be written. */
private int writeDirtyShards() {
int failed = 0;
@@ -344,6 +537,18 @@ public class PartitionedFileStorage implements StorageBackend implements StorageBackend implements StorageBackend implements StorageBackend files = Files.newDirectoryStream(dir)) {
- return files.iterator().hasNext();
+ for (Path file : files) {
+ boolean emptyJournal = file.getFileName().toString().equals(JOURNAL_FILE) && Files.size(file) == 0;
+ if (!emptyJournal) {
+ return true;
+ }
+ }
+ return false;
} catch (IOException e) {
throw new UncheckedIOException("Failed to list " + dir, e);
}
diff --git a/src/main/java/io/github/hectorvent/floci/core/storage/StorageFactory.java b/src/main/java/io/github/hectorvent/floci/core/storage/StorageFactory.java
index f78d17b48c..342fa690b6 100644
--- a/src/main/java/io/github/hectorvent/floci/core/storage/StorageFactory.java
+++ b/src/main/java/io/github/hectorvent/floci/core/storage/StorageFactory.java
@@ -156,9 +156,10 @@ public class StorageFactory {
* when {@link AccountAwareStorageBackend#writesEntries()} is true.
*
* {@code persistent} writes a shard's file on every change and {@code hybrid} writes dirty
- * shards on the flush interval. {@code memory} keeps the store in memory, and {@code wal}
- * keeps its single-file {@link WalStorage} for now. An existing single-file store (a
- * {@code wal}-mode snapshot and log included) is migrated into the directory on first load.
+ * shards on the flush interval. {@code wal} journals one record per changed entry and writes
+ * dirty shards on the WAL compaction interval. {@code memory} keeps the store in memory. An
+ * existing single-file store (a {@code wal}-mode snapshot and log included) is migrated into
+ * the directory on first load.
*/
public synchronized AccountAwareStorageBackend