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:
Ben Wart authored and GitHub committed 2026-10-22 22:27:08 -04:00
1 parent 4f45541d44
commit 4c49f23c80
10 files changed
+1258 -69

No files matched your search

@@ -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.
*
* <p>Record format, every string UTF-8 and every value Jackson CBOR, each length-prefixed with a
* 4-byte length:
* <pre>
* PUT_ENTRY: [0x01] [key] [entry key] [entry value]
* REMOVE_ENTRY: [0x02] [key] [entry key]
* PUT: [0x03] [key] [whole map]
* DELETE: [0x04] [key]
* </pre>
*
* <p>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 <E> the type of one map entry's value
*/
final class EntryJournal<E> {
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<E> {
String key();
}
record PutEntry<E>(String key, String entryKey, E value) implements Change<E> {}
record RemoveEntry<E>(String key, String entryKey) implements Change<E> {}
record Put<E>(String key, Map<String, E> value) implements Change<E> {}
record Delete<E>(String key) implements Change<E> {}
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<String, E> 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<Change<E>> 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<E> 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<String, E> 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);
}
}
}
@@ -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;
*
* <p>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.
*
* <p>While the directory holds no data, a legacy single-file store (the {@code Map<String,
* Map<String, E>>} file the other backends write, or a {@code wal} snapshot and log) is migrated:
@@ -66,6 +73,7 @@ public class PartitionedFileStorage<E> implements StorageBackend<String, Map<Str
private static final Logger LOG = Logger.getLogger(PartitionedFileStorage.class);
static final String FILE_SUFFIX = ".json";
static final String JOURNAL_FILE = "journal.wal";
static final String MIGRATING_SUFFIX = ".migrating";
private static final String KEY_FIELD = "key";
private static final String ENTRIES_FIELD = "entries";
@@ -76,7 +84,12 @@ public class PartitionedFileStorage<E> implements StorageBackend<String, Map<Str
/** Its shard file is rewritten before the mutating call returns. */
SYNC,
/** Dirty shard files are rewritten on the flush interval. */
PERIODIC
PERIODIC,
/**
* One record per changed entry is appended to a journal before the mutating call returns;
* dirty shard files are rewritten and the journal emptied on the compaction interval.
*/
JOURNAL
}
/** One shard of one key: the unit that is written to a file. */
@@ -116,16 +129,32 @@ public class PartitionedFileStorage<E> implements StorageBackend<String, Map<Str
private final ObjectReader entriesReader;
private final ObjectWriter entriesWriter;
private final ScheduledExecutorService scheduler;
// Shard writes hold the read lock, and load and clear hold the write lock, so a write that
// read a shard before a clear cannot put its file back afterwards, and the flush schedule,
// which starts with the constructor, cannot write while load is filling the store.
private final ReentrantReadWriteLock fileLock = new ReentrantReadWriteLock();
private final EntryJournal<E> journal;
// Outside journal mode: the journal a crashed journal-mode run may have left, read once on load.
private final EntryJournal<E> 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<String, ReentrantLock> 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<E> implements StorageBackend<String, Map<Str
* @param entryType the type of one map entry's value
* @param shardCount how many files each key is split into, at least one
* @param mode when a change reaches disk
* @param flushIntervalMs the flush interval of a {@link Mode#PERIODIC} store
* @param flushIntervalMs the flush interval of a {@link Mode#PERIODIC} store, or the
* compaction interval of a {@link Mode#JOURNAL} store
*/
public PartitionedFileStorage(Path directory, Path legacyFile, Class<E> entryType, int shardCount,
Mode mode, long flushIntervalMs) {
@@ -159,6 +189,10 @@ public class PartitionedFileStorage<E> implements StorageBackend<String, Map<Str
JavaType entriesType = mapper.getTypeFactory().constructMapType(Map.class, String.class, entryType);
this.entriesReader = mapper.readerFor(entriesType);
this.entriesWriter = mapper.writerFor(entriesType);
EntryJournal<E> 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<E> implements StorageBackend<String, Map<Str
@Override
public void put(String key, Map<String, E> 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<E> implements StorageBackend<String, Map<Str
@Override
public void delete(String key) {
applyDelete(key);
persistChange(allShardsOf(key));
boolean journaled;
ReentrantLock lock = beginChange(key);
try {
applyDelete(key);
journaled = journal == null || journalAppend(() -> journal.delete(key));
} finally {
endChange(lock);
}
persistChange(journaled, allShardsOf(key));
}
@Override
@@ -204,14 +252,14 @@ public class PartitionedFileStorage<E> implements StorageBackend<String, Map<Str
}
/**
* Writes every dirty shard.
* Writes every dirty shard; in journal mode this is a compaction.
*
* @throws UncheckedIOException when a shard could not be written; it stays dirty and is
* written again by the next flush
*/
@Override
public void flush() {
int failed = writeDirtyShards();
int failed = journal != null ? compact() : writeDirtyShards();
if (failed > 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<E> implements StorageBackend<String, Map<Str
@Override
public synchronized void load() {
// The flush schedule starts with the constructor: hold it off while the store is filled.
fileLock.writeLock().lock();
// The flush schedule starts with the constructor: hold compaction off until the journal
// has been replayed, or it could empty a journal whose records are not yet in memory.
compactionLock.writeLock().lock();
try {
store.clear();
dirty.clear();
migrateLegacyFileIfNeeded();
if (Files.isDirectory(directory)) {
loadDirectory();
}
loadLocked();
} finally {
fileLock.writeLock().unlock();
compactionLock.writeLock().unlock();
}
}
private void loadLocked() {
loaded = false;
store.clear();
dirty.clear();
migrateLegacyFileIfNeeded();
if (Files.isDirectory(directory)) {
loadDirectory();
}
if (journal != null) {
replayJournal(journal);
journal.open();
} else if (!leftoverJournal.isEmpty()) {
foldLeftoverJournal();
}
loaded = true;
}
private void replayJournal(EntryJournal<E> 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<Path> files = Files.newDirectoryStream(directory, "*" + FILE_SUFFIX)) {
for (Path file : files) {
@@ -249,8 +350,11 @@ public class PartitionedFileStorage<E> implements StorageBackend<String, Map<Str
LOG.errorv(e, "Failed to clear {0}", directory);
}
}
if (journal != null) {
journal.open();
}
} finally {
fileLock.writeLock().unlock();
compactionLock.writeLock().unlock();
}
}
@@ -258,43 +362,70 @@ public class PartitionedFileStorage<E> implements StorageBackend<String, Map<Str
@Override
public void putEntry(String key, String entryKey, E entryValue) {
persistChange(List.of(applyPutEntry(key, entryKey, entryValue)));
ShardId id;
boolean journaled;
ReentrantLock lock = beginChange(key);
try {
id = applyPutEntry(key, entryKey, entryValue);
journaled = journal == null || journalAppend(() -> 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<ShardId> changed) {
if (mode != Mode.SYNC) {
return;
}
private void persistChange(boolean journaled, List<ShardId> 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<E> implements StorageBackend<String, Map<Str
}
}
// The apply methods change memory and mark what they change dirty.
/**
* Writes every dirty shard and then empties the journal. A shard that fails to write keeps
* the journal intact, so the next load replays what that shard file is missing.
*
* @return how many shards could not be written, plus one when the journal could not be emptied
*/
private int compact() {
compactionLock.writeLock().lock();
try {
// Before the first load the journal still holds the last run's records, unreplayed.
if (!loaded || (dirty.isEmpty() && journal.isEmpty())) {
return 0;
}
int failed = writeDirtyShards();
if (failed > 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<E> change) {
switch (change) {
case EntryJournal.PutEntry<E> put -> applyPutEntry(put.key(), put.entryKey(), put.value());
case EntryJournal.RemoveEntry<E> remove -> applyRemoveEntry(remove.key(), remove.entryKey());
case EntryJournal.Put<E> put -> applyPut(put.key(), put.value());
case EntryJournal.Delete<E> 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<E> implements StorageBackend<String, Map<Str
markAll(key);
}
/** Journal mode: takes the change side of the compaction lock, then the key's lock, and returns the latter. */
private ReentrantLock beginChange(String key) {
if (journal == null) {
return null;
}
compactionLock.readLock().lock();
ReentrantLock lock = changeLocks.computeIfAbsent(key, ignored -> 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<E> implements StorageBackend<String, Map<Str
return failed;
}
void setBeforeJournalAppend(Runnable hook) {
this.beforeJournalAppend = hook;
}
void setBeforeJournalWrite(EntryJournal.WriteHook hook) {
journal.setBeforeWrite(hook);
}
void setBeforeJournalTruncate(Runnable hook) {
this.beforeJournalTruncate = hook;
}
void setBeforeShardWrite(Runnable hook) {
this.beforeShardWrite = hook;
}
@@ -438,13 +643,13 @@ public class PartitionedFileStorage<E> implements StorageBackend<String, Map<Str
*/
private boolean writeShard(ShardId id) {
// clear() holds the write side, so a write that read a shard before the clear cannot put
// its file back after the clear removed it. Load already holds the write side, which lets
// it take the read side here.
fileLock.readLock().lock();
// its file back after the clear removed it. Compaction and load already hold the write
// side, which lets them take the read side here.
compactionLock.readLock().lock();
try {
return writeShardLocked(id);
} finally {
fileLock.readLock().unlock();
compactionLock.readLock().unlock();
}
}
@@ -606,7 +811,8 @@ public class PartitionedFileStorage<E> implements StorageBackend<String, Map<Str
}
}
if (Files.isDirectory(directory)) {
// Empty (holdsData said so): make way for the move.
// Empty apart from an empty journal (holdsData said so): make way for the move.
Files.deleteIfExists(directory.resolve(JOURNAL_FILE));
Files.delete(directory);
}
Files.move(staging, directory, StandardCopyOption.ATOMIC_MOVE);
@@ -629,13 +835,19 @@ public class PartitionedFileStorage<E> implements StorageBackend<String, Map<Str
entries.size(), sources, directory);
}
/** Whether {@code dir} holds anything at all. */
/** Whether {@code dir} holds a shard file or a journal with records in it. */
private static boolean holdsData(Path dir) {
if (!Files.isDirectory(dir)) {
return false;
}
try (DirectoryStream<Path> 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);
}
@@ -156,9 +156,10 @@ public class StorageFactory {
* when {@link AccountAwareStorageBackend#writesEntries()} is true.
*
* <p>{@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 <E> AccountAwareStorageBackend<Map<String, E>> createPartitioned(
String serviceName, String fileName, TypeReference<Map<String, Map<String, E>>> typeReference,
@@ -167,11 +168,6 @@ public class StorageFactory {
if ("memory".equals(mode)) {
return create(serviceName, fileName, typeReference);
}
if ("wal".equals(mode)) {
LOG.warnv("The per-table layout does not support wal mode yet; storing {0} for service {1} "
+ "in the single-file layout", fileName, serviceName);
return create(serviceName, fileName, typeReference);
}
Path basePath = Path.of(config.storage().persistentPath());
Path directory = basePath.resolve(fileName.replace(".json", ""));
StorageBackend<?, ?> existing = backendsByPath.get(directory);
@@ -191,6 +187,10 @@ public class StorageFactory {
writeMode = PartitionedFileStorage.Mode.PERIODIC;
interval = resolveFlushInterval(serviceName);
}
case "wal" -> {
writeMode = PartitionedFileStorage.Mode.JOURNAL;
interval = config.storage().wal().compactionIntervalMs();
}
default -> throw new IllegalArgumentException("Unknown storage mode: " + mode);
}
PartitionedFileStorage<E> inner = new PartitionedFileStorage<>(directory,