mirror of
https://github.com/floci-io/floci.git
synced 2026-11-27 07:39:24 -05:00
fix(storage): publish replacement batches atomically (#6324)
Signed-off-by: Andre Kurait <AndreKurait@gmail.com>
This commit is contained in:
1 parent
80e5df933b
commit
686d0b5f02
8 files changed
+515
-36
No files matched your search
@@ -82,6 +82,18 @@ public class AccountAwareStorageBackend<V> implements StorageBackend<String, V>
|
||||
delegate.putAll(prefixedEntries);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void putAllAtomically(Map<String, V> entries) {
|
||||
putAllAtomicallyForAccount(prefix(), entries);
|
||||
}
|
||||
|
||||
public void putAllAtomicallyForAccount(String accountId, Map<String, V> entries) {
|
||||
Map<String, V> prefixedEntries = new LinkedHashMap<>();
|
||||
entries.forEach((key, value) -> prefixedEntries.put(accountId + "/" + key, value));
|
||||
delegate.putAllAtomically(prefixedEntries);
|
||||
trackOwner(accountId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<V> get(String key) {
|
||||
String prefixedKey = prefixed(key);
|
||||
|
||||
@@ -10,7 +10,6 @@ import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
@@ -29,11 +28,12 @@ public class HybridStorage<K, V> implements StorageBackend<K, V> {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(HybridStorage.class);
|
||||
|
||||
private final ConcurrentHashMap<K, V> store = new ConcurrentHashMap<>();
|
||||
private volatile ConcurrentHashMap<K, V> store = new ConcurrentHashMap<>();
|
||||
private final Path filePath;
|
||||
private final ObjectMapper objectMapper;
|
||||
private final TypeReference<Map<K, V>> typeReference;
|
||||
private final ScheduledExecutorService scheduler;
|
||||
private final Object flushLock = new Object();
|
||||
private final AtomicBoolean dirty = new AtomicBoolean(false);
|
||||
|
||||
public HybridStorage(Path filePath, TypeReference<Map<K, V>> typeReference, long flushIntervalMs) {
|
||||
@@ -48,18 +48,26 @@ public class HybridStorage<K, V> implements StorageBackend<K, V> {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void put(K key, V value) {
|
||||
public synchronized void put(K key, V value) {
|
||||
store.put(key, value);
|
||||
dirty.set(true);
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized void putAllAtomically(Map<K, V> entries) {
|
||||
ConcurrentHashMap<K, V> candidate = new ConcurrentHashMap<>(store);
|
||||
candidate.putAll(Map.copyOf(entries));
|
||||
store = candidate;
|
||||
dirty.set(true);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<V> get(K key) {
|
||||
return Optional.ofNullable(store.get(key));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void delete(K key) {
|
||||
public synchronized void delete(K key) {
|
||||
store.remove(key);
|
||||
dirty.set(true);
|
||||
}
|
||||
@@ -74,7 +82,7 @@ public class HybridStorage<K, V> implements StorageBackend<K, V> {
|
||||
|
||||
@Override
|
||||
public Set<K> keys() {
|
||||
return Collections.unmodifiableSet(store.keySet());
|
||||
return Set.copyOf(store.keySet());
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -99,7 +107,7 @@ public class HybridStorage<K, V> implements StorageBackend<K, V> {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void clear() {
|
||||
public synchronized void clear() {
|
||||
store.clear();
|
||||
dirty.set(true);
|
||||
}
|
||||
@@ -115,13 +123,16 @@ public class HybridStorage<K, V> implements StorageBackend<K, V> {
|
||||
}
|
||||
}
|
||||
|
||||
private synchronized void persistToDisk() {
|
||||
try {
|
||||
StorageFiles.writeAtomically(filePath, tempFile -> objectMapper.writeValue(tempFile.toFile(), store));
|
||||
LOG.debugv("Flushed {0} entries to {1}", store.size(), filePath);
|
||||
} catch (IOException e) {
|
||||
LOG.errorv(e, "Failed to persist data to {0}", filePath);
|
||||
dirty.set(true);
|
||||
private void persistToDisk() {
|
||||
synchronized (flushLock) {
|
||||
Map<K, V> snapshot = store;
|
||||
try {
|
||||
StorageFiles.writeAtomically(filePath, tempFile -> objectMapper.writeValue(tempFile.toFile(), snapshot));
|
||||
LOG.debugv("Flushed {0} entries to {1}", snapshot.size(), filePath);
|
||||
} catch (IOException e) {
|
||||
LOG.errorv(e, "Failed to persist data to {0}", filePath);
|
||||
dirty.set(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,8 @@
|
||||
package io.github.hectorvent.floci.core.storage;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
@@ -14,20 +14,27 @@ import java.util.function.Predicate;
|
||||
*/
|
||||
public class InMemoryStorage<K, V> implements StorageBackend<K, V> {
|
||||
|
||||
private final ConcurrentHashMap<K, V> store = new ConcurrentHashMap<>();
|
||||
private volatile ConcurrentHashMap<K, V> store = new ConcurrentHashMap<>();
|
||||
|
||||
@Override
|
||||
public void put(K key, V value) {
|
||||
public synchronized void put(K key, V value) {
|
||||
store.put(key, value);
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized void putAllAtomically(Map<K, V> entries) {
|
||||
ConcurrentHashMap<K, V> candidate = new ConcurrentHashMap<>(store);
|
||||
candidate.putAll(Map.copyOf(entries));
|
||||
store = candidate;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<V> get(K key) {
|
||||
return Optional.ofNullable(store.get(key));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void delete(K key) {
|
||||
public synchronized void delete(K key) {
|
||||
store.remove(key);
|
||||
}
|
||||
|
||||
@@ -44,7 +51,7 @@ public class InMemoryStorage<K, V> implements StorageBackend<K, V> {
|
||||
|
||||
@Override
|
||||
public Set<K> keys() {
|
||||
return Collections.unmodifiableSet(store.keySet());
|
||||
return Set.copyOf(store.keySet());
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -53,12 +60,12 @@ public class InMemoryStorage<K, V> implements StorageBackend<K, V> {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void load() {
|
||||
public synchronized void load() {
|
||||
// No-op for in-memory storage
|
||||
}
|
||||
|
||||
@Override
|
||||
public void clear() {
|
||||
public synchronized void clear() {
|
||||
store.clear();
|
||||
}
|
||||
}
|
||||
@@ -7,10 +7,10 @@ import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
@@ -29,7 +29,7 @@ public class PersistentStorage<K, V> implements StorageBackend<K, V> {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(PersistentStorage.class);
|
||||
|
||||
private final ConcurrentHashMap<K, V> store = new ConcurrentHashMap<>();
|
||||
private volatile ConcurrentHashMap<K, V> store = new ConcurrentHashMap<>();
|
||||
private final Path filePath;
|
||||
private final ObjectMapper objectMapper;
|
||||
private final TypeReference<Map<K, V>> typeReference;
|
||||
@@ -44,13 +44,13 @@ public class PersistentStorage<K, V> implements StorageBackend<K, V> {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void put(K key, V value) {
|
||||
public synchronized void put(K key, V value) {
|
||||
store.put(key, value);
|
||||
persistToDisk();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void putAll(Map<K, V> entries) {
|
||||
public synchronized void putAll(Map<K, V> entries) {
|
||||
if (entries.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
@@ -58,13 +58,29 @@ public class PersistentStorage<K, V> implements StorageBackend<K, V> {
|
||||
persistToDisk();
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized void putAllAtomically(Map<K, V> entries) {
|
||||
Map<K, V> replacements = Map.copyOf(entries);
|
||||
if (replacements.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
ConcurrentHashMap<K, V> candidate = new ConcurrentHashMap<>(store);
|
||||
candidate.putAll(replacements);
|
||||
try {
|
||||
StorageFiles.writeAtomically(filePath, tempFile -> objectMapper.writeValue(tempFile.toFile(), candidate));
|
||||
} catch (IOException exception) {
|
||||
throw new UncheckedIOException("Failed to commit atomic batch to " + filePath, exception);
|
||||
}
|
||||
store = candidate;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<V> get(K key) {
|
||||
return Optional.ofNullable(store.get(key));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void delete(K key) {
|
||||
public synchronized void delete(K key) {
|
||||
store.remove(key);
|
||||
persistToDisk();
|
||||
}
|
||||
@@ -79,7 +95,7 @@ public class PersistentStorage<K, V> implements StorageBackend<K, V> {
|
||||
|
||||
@Override
|
||||
public Set<K> keys() {
|
||||
return Collections.unmodifiableSet(store.keySet());
|
||||
return Set.copyOf(store.keySet());
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -88,7 +104,7 @@ public class PersistentStorage<K, V> implements StorageBackend<K, V> {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void load() {
|
||||
public synchronized void load() {
|
||||
if (!Files.exists(filePath)) {
|
||||
LOG.debugv("No persistent file found at {0}, starting with empty store", filePath);
|
||||
return;
|
||||
@@ -108,7 +124,7 @@ public class PersistentStorage<K, V> implements StorageBackend<K, V> {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void clear() {
|
||||
public synchronized void clear() {
|
||||
store.clear();
|
||||
persistToDisk();
|
||||
}
|
||||
|
||||
@@ -25,6 +25,16 @@ public interface StorageBackend<K, V> {
|
||||
entries.forEach(this::put);
|
||||
}
|
||||
|
||||
/**
|
||||
* Publish replacement values as one batch, including in snapshots and WAL replay.
|
||||
* Callers must not mutate values already stored here. Persistent and WAL backends
|
||||
* report write failures before publishing; hybrid retains its asynchronous durability.
|
||||
* Unsupported backends reject the operation without changing any entries.
|
||||
*/
|
||||
default void putAllAtomically(Map<K, V> entries) {
|
||||
throw new UnsupportedOperationException("Atomic batches are not supported by this backend");
|
||||
}
|
||||
|
||||
Optional<V> get(K key);
|
||||
|
||||
void delete(K key);
|
||||
|
||||
@@ -8,19 +8,27 @@ import com.fasterxml.jackson.dataformat.cbor.CBORFactory;
|
||||
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.io.*;
|
||||
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.io.UncheckedIOException;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.channels.FileChannel;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.StandardOpenOption;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.*;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.locks.ReentrantReadWriteLock;
|
||||
import java.util.function.Predicate;
|
||||
import java.util.stream.Collectors;
|
||||
@@ -34,6 +42,7 @@ import java.util.stream.Collectors;
|
||||
* Binary WAL entry format:
|
||||
* PUT: [0x01] [4-byte key length] [key bytes] [4-byte value length] [value bytes]
|
||||
* DELETE: [0x02] [4-byte key length] [key bytes]
|
||||
* BATCH: [0x03] [4-byte map length] [CBOR map bytes]
|
||||
*
|
||||
* Key and value bytes are serialized via Jackson CBOR (compact binary format).
|
||||
* Snapshot files use indented JSON for debuggability.
|
||||
@@ -44,8 +53,9 @@ public class WalStorage<K, V> implements StorageBackend<K, V> {
|
||||
|
||||
static final byte OP_PUT = 0x01;
|
||||
static final byte OP_DELETE = 0x02;
|
||||
static final byte OP_BATCH = 0x03;
|
||||
|
||||
private final ConcurrentHashMap<K, V> store = new ConcurrentHashMap<>();
|
||||
private volatile ConcurrentHashMap<K, V> store = new ConcurrentHashMap<>();
|
||||
private final Path snapshotPath;
|
||||
private final Path walPath;
|
||||
private final ObjectMapper snapshotMapper;
|
||||
@@ -107,6 +117,63 @@ public class WalStorage<K, V> implements StorageBackend<K, V> {
|
||||
}
|
||||
}
|
||||
|
||||
/** A batch is one length-delimited CBOR map, applied only after the entire frame decodes. */
|
||||
@Override
|
||||
public void putAllAtomically(Map<K, V> entries) {
|
||||
Map<K, V> replacements = Map.copyOf(entries);
|
||||
if (replacements.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
byte[] payload;
|
||||
try {
|
||||
payload = walMapper.writeValueAsBytes(replacements);
|
||||
} catch (IOException exception) {
|
||||
throw new UncheckedIOException("Failed to encode atomic WAL batch", exception);
|
||||
}
|
||||
compactionLock.writeLock().lock();
|
||||
try {
|
||||
if (walWriter == null) {
|
||||
throw new IllegalStateException("WAL writer is not open");
|
||||
}
|
||||
ConcurrentHashMap<K, V> candidate = new ConcurrentHashMap<>(store);
|
||||
candidate.putAll(replacements);
|
||||
walWriter.flush();
|
||||
FileChannel channel = FileChannel.open(walPath, StandardOpenOption.WRITE);
|
||||
try {
|
||||
long offset = channel.size();
|
||||
channel.position(offset);
|
||||
ByteBuffer record = ByteBuffer.allocate(1 + Integer.BYTES + payload.length);
|
||||
record.put(OP_BATCH).putInt(payload.length).put(payload).flip();
|
||||
try {
|
||||
while (record.hasRemaining()) {
|
||||
channel.write(record);
|
||||
}
|
||||
channel.force(true);
|
||||
} catch (IOException exception) {
|
||||
try {
|
||||
channel.truncate(offset);
|
||||
channel.force(true);
|
||||
} catch (IOException rollbackFailure) {
|
||||
exception.addSuppressed(rollbackFailure);
|
||||
}
|
||||
throw exception;
|
||||
}
|
||||
} finally {
|
||||
try {
|
||||
channel.close();
|
||||
} catch (IOException exception) {
|
||||
LOG.warnv(exception, "Failed to close atomic batch channel for {0}", walPath);
|
||||
}
|
||||
}
|
||||
store = candidate;
|
||||
dirty = true;
|
||||
} catch (IOException exception) {
|
||||
throw new UncheckedIOException("Failed to commit atomic WAL batch to " + walPath, exception);
|
||||
} finally {
|
||||
compactionLock.writeLock().unlock();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<V> get(K key) {
|
||||
return Optional.ofNullable(store.get(key));
|
||||
@@ -134,7 +201,7 @@ public class WalStorage<K, V> implements StorageBackend<K, V> {
|
||||
|
||||
@Override
|
||||
public Set<K> keys() {
|
||||
return Collections.unmodifiableSet(store.keySet());
|
||||
return Set.copyOf(store.keySet());
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -190,8 +257,13 @@ public class WalStorage<K, V> implements StorageBackend<K, V> {
|
||||
|
||||
public void shutdown() {
|
||||
StorageFiles.stop(scheduler);
|
||||
compact();
|
||||
closeWalWriter();
|
||||
compactionLock.writeLock().lock();
|
||||
try {
|
||||
compact();
|
||||
closeWalWriter();
|
||||
} finally {
|
||||
compactionLock.writeLock().unlock();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -337,7 +409,15 @@ public class WalStorage<K, V> implements StorageBackend<K, V> {
|
||||
break;
|
||||
}
|
||||
long recordLength = 1 + 4 + keyBytes.length;
|
||||
if (op == OP_PUT) {
|
||||
if (op == OP_BATCH) {
|
||||
Map<K, V> batch = walMapper.readValue(keyBytes, typeReference);
|
||||
if (batch == null || batch.entrySet().stream()
|
||||
.anyMatch(entry -> entry.getKey() == null || entry.getValue() == null)) {
|
||||
LOG.warnv("Invalid WAL batch at offset {0} in {1}, stopping replay", consumed, walPath);
|
||||
break;
|
||||
}
|
||||
store.putAll(batch);
|
||||
} else if (op == OP_PUT) {
|
||||
byte[] valueBytes = readFrame(in, fileSize - consumed - recordLength);
|
||||
if (valueBytes == null) {
|
||||
break;
|
||||
|
||||
Reference in new issue
Block a user