fix(cloudwatchlogs): journal log events instead of rewriting the store under persistent mode (#4187)

* perf(storage): append WAL batches once and skip compaction of an unchanged store

A putAll batch was N locked appends and N flushes; it is now one contiguous run of records and one flush. Compaction rewrote the snapshot on every tick even when nothing had changed since the last one, so an idle store kept rewriting its file; the store now tracks whether it changed and compaction returns early otherwise. Entries replayed from the log at load mark the store changed so the next compaction folds them in.

* fix(storage): recover from a corrupt WAL tail instead of failing boot

The replay reader trusted the signed length headers it read: a negative length threw IllegalArgumentException out of load() and failed the owning service at boot, and a length past the end of the file read to EOF. After any stop, the writer reopened behind the unreadable bytes, so every entry appended after a torn tail was lost on the next load until a compaction happened. Lengths are now bounded by the bytes left in the file, every framing or decode failure stops replay with a warning, and the unreadable tail is cut off before the writer reopens. An unreadable snapshot is quarantined to a .corrupt sibling like the other file-backed stores do, instead of being overwritten by the next compaction.

* fix(storage): journal append-heavy stores under persistent mode

PersistentStorage rewrites the whole store file on every mutation, so the cost of a write grows with the store. A store can now declare an APPEND_HEAVY write profile on StorageFactory.create; under persistent mode such a store is backed by WalStorage with the store's own JSON file as the snapshot and a .wal file next to it. The snapshot layout means an existing store file is picked up as the first snapshot and the file is current again after a clean shutdown, so no migration is needed in either direction. The other modes ignore the profile.

* fix(cloudwatchlogs): journal log events under persistent storage

Every PutLogEvents batch rewrote the whole cwlogs-events.json file under persistent mode, so the cost of one batch grew with the number of stored events. The events store now declares the APPEND_HEAVY write profile: a batch is appended to cwlogs-events.wal and the JSON file is rewritten on the WAL compaction interval and at shutdown. Groups, streams, filters and policies keep the file that is rewritten on every call.

Closes #2500

* docs(storage): describe journaled stores under persistent mode

Explain that CloudWatch Logs events are journaled to cwlogs-events.wal under persistent mode, that the compaction interval now governs that store too, and that the JSON file is current after a clean shutdown and up to one interval behind while running. Also corrects the documented CloudWatch Logs flush interval default from 5000 to 15000, which is what EmulatorConfig ships.

* docs(storage): describe journaled stores as append-heavy

The pages said the CloudWatch Logs event store only ever grows, but the 20,000-event cap, retention pruning and DeleteLogStream all remove events. What qualifies a store for journaling is its write pattern, which is what WriteProfile.APPEND_HEAVY says, so the pages now say that.
This commit is contained in:
Niels Kootstra authored and GitHub committed 2026-09-23 00:08:45 -04:00
1 parent 024c2cbe27
commit a0cb86cc13
14 files changed
+668 -37

No files matched your search

@@ -0,0 +1,129 @@
package io.github.hectorvent.floci.core.storage;
import com.fasterxml.jackson.core.type.TypeReference;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.ServiceConfigAccess;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Stream;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* How {@link StorageFactory} maps a store's {@link WriteProfile} onto a backend: under
* {@code persistent} mode an append-heavy store is journaled instead of rewritten on every
* mutation, while its snapshot stays at the store's own JSON file so the data can be read by a
* plain persistent store and back.
*/
class StorageFactoryWriteProfileTest {
private static final TypeReference<Map<String, String>> TYPE = new TypeReference<>() {};
@TempDir
Path tempDir;
@Test
void persistentModeJournalsAppendHeavyStoresSoAWriteCostsTheWriteNotTheStore() throws IOException {
StorageFactory factory = newFactory("persistent");
AccountAwareStorageBackend<String> events =
factory.create("svc", "svc.json", TYPE, WriteProfile.APPEND_HEAVY);
fill(events, 0, 1_000);
long smallStore = walSize();
events.put(key(1_000), "value");
long costAtOneThousand = walSize() - smallStore;
fill(events, 1_001, 10_000);
long largeStore = walSize();
events.put(key(10_000), "value");
long costAtTenThousand = walSize() - largeStore;
assertTrue(costAtOneThousand > 0, "a put must reach the journal");
assertEquals(costAtOneThousand, costAtTenThousand, "the cost of one put must not grow with the store");
assertFalse(Files.exists(tempDir.resolve("svc.json")), "the store file is only written by compaction");
factory.shutdownAll();
assertTrue(Files.readString(tempDir.resolve("svc.json")).contains(key(10_000)),
"shutdown must fold the journal into the store file");
}
@Test
void persistentModeStillRewritesDefaultProfileStores() {
StorageFactory factory = newFactory("persistent");
factory.create("svc", "svc.json", TYPE).put("only", "v1");
assertTrue(Files.exists(tempDir.resolve("svc.json")), "a default-profile store is written on every mutation");
assertFalse(Files.exists(tempDir.resolve("svc.wal")));
factory.shutdownAll();
}
@Test
void aPersistentStoreIsReadByTheJournaledBackendAndBack() {
StorageFactory before = newFactory("persistent");
before.create("svc", "svc.json", TYPE).put("first", "v1");
before.shutdownAll();
StorageFactory journaled = newFactory("persistent");
AccountAwareStorageBackend<String> upgraded =
journaled.create("svc", "svc.json", TYPE, WriteProfile.APPEND_HEAVY);
assertEquals(Optional.of("v1"), upgraded.get("first"));
upgraded.put("second", "v2");
journaled.shutdownAll();
StorageFactory after = newFactory("persistent");
AccountAwareStorageBackend<String> downgraded = after.create("svc", "svc.json", TYPE);
assertEquals(Optional.of("v1"), downgraded.get("first"));
assertEquals(Optional.of("v2"), downgraded.get("second"));
after.shutdownAll();
}
@Test
void memoryModeIgnoresTheWriteProfile() throws IOException {
StorageFactory factory = newFactory("memory");
factory.create("svc", "svc.json", TYPE, WriteProfile.APPEND_HEAVY).put("only", "v1");
factory.shutdownAll();
try (Stream<Path> files = Files.list(tempDir)) {
assertEquals(0, files.count(), "memory mode must not touch the filesystem");
}
}
private static void fill(AccountAwareStorageBackend<String> store, int from, int toExclusive) {
for (int i = from; i < toExclusive; i++) {
store.put(key(i), "value");
}
}
/** Fixed-width keys, so every journal record has the same size. */
private static String key(int i) {
return String.format("k%05d", i);
}
private long walSize() throws IOException {
Path wal = tempDir.resolve("svc.wal");
return Files.exists(wal) ? Files.size(wal) : 0L;
}
private StorageFactory newFactory(String mode) {
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
when(config.defaultAccountId()).thenReturn("000000000000");
when(config.storage().persistentPath()).thenReturn(tempDir.toString());
when(config.storage().wal().compactionIntervalMs()).thenReturn(60_000L);
ServiceConfigAccess serviceConfigAccess = mock(ServiceConfigAccess.class);
when(serviceConfigAccess.storageMode(anyString())).thenReturn(mode);
when(serviceConfigAccess.storageFlushInterval(anyString())).thenReturn(60_000L);
return new StorageFactory(config, serviceConfigAccess);
}
}
@@ -9,6 +9,7 @@ import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.file.Files;
@@ -196,4 +197,198 @@ class WalStorageTest {
store1.shutdown();
store2.shutdown();
}
@Test
void putAllEntriesAreReplayedByAFreshInstance() {
Path snapshotPath = tempDir.resolve("batch-snapshot.json");
Path walPath = tempDir.resolve("batch-data.wal");
WalStorage<String, String> store1 = new WalStorage<>(snapshotPath, walPath,
new TypeReference<Map<String, String>>() {}, 600000);
store1.load();
store1.put("key1", "old");
store1.putAll(Map.of("key1", "new", "key2", "value2", "key3", "value3"));
WalStorage<String, String> store2 = new WalStorage<>(snapshotPath, walPath,
new TypeReference<Map<String, String>>() {}, 600000);
store2.load();
assertEquals("new", store2.get("key1").orElseThrow());
assertEquals("value2", store2.get("key2").orElseThrow());
assertEquals("value3", store2.get("key3").orElseThrow());
store1.shutdown();
store2.shutdown();
}
@Test
void putAllOfAnEmptyBatchLeavesTheWalUntouched() throws IOException {
Path walPath = tempDir.resolve("data.wal");
storage.put("key1", "value1");
long sizeBeforeEmptyBatch = Files.size(walPath);
storage.putAll(Map.of());
assertEquals(sizeBeforeEmptyBatch, Files.size(walPath));
}
@Test
void flushOfAnUnchangedStoreLeavesTheSnapshotUntouched() throws IOException {
Path snapshotPath = tempDir.resolve("idle-snapshot.json");
Path walPath = tempDir.resolve("idle-data.wal");
WalStorage<String, String> store = new WalStorage<>(snapshotPath, walPath,
new TypeReference<Map<String, String>>() {}, 600000);
store.load();
store.put("key1", "value1");
store.flush();
// Nothing changed since the last snapshot, so a flush has nothing to write: a marker
// placed in the file afterwards must survive it.
Files.writeString(snapshotPath, "left alone");
store.flush();
assertEquals("left alone", Files.readString(snapshotPath));
store.put("key2", "value2");
store.flush();
assertTrue(Files.readString(snapshotPath).contains("key2"));
store.delete("key2");
store.flush();
assertFalse(Files.readString(snapshotPath).contains("key2"));
store.shutdown();
}
@Test
void entriesReplayedFromTheWalAreCompactedByTheNextFlush() throws IOException {
Path snapshotPath = tempDir.resolve("replayed-snapshot.json");
Path walPath = tempDir.resolve("replayed-data.wal");
WalStorage<String, String> store1 = new WalStorage<>(snapshotPath, walPath,
new TypeReference<Map<String, String>>() {}, 600000);
store1.load();
store1.put("key1", "value1");
WalStorage<String, String> store2 = new WalStorage<>(snapshotPath, walPath,
new TypeReference<Map<String, String>>() {}, 600000);
store2.load();
store2.flush();
assertTrue(Files.readString(snapshotPath).contains("key1"));
assertEquals(0L, Files.size(walPath));
store1.shutdown();
store2.shutdown();
}
@Test
void appendsAfterATornTailAreReplayedOnTheNextLoad() throws IOException {
Path walPath = tempDir.resolve("torn.wal");
Path snapshotPath = tempDir.resolve("torn-snapshot.json");
WalStorage<String, String> store1 = new WalStorage<>(snapshotPath, walPath,
new TypeReference<Map<String, String>>() {}, 600000);
store1.load();
store1.put("good", "data");
store1.put("another", "entry");
try (RandomAccessFile raf = new RandomAccessFile(walPath.toFile(), "rw")) {
raf.setLength(Files.size(walPath) - 3);
}
// A restart after the crash keeps running and appends behind the torn record.
WalStorage<String, String> store2 = new WalStorage<>(snapshotPath, walPath,
new TypeReference<Map<String, String>>() {}, 600000);
store2.load();
store2.put("later", "write");
WalStorage<String, String> store3 = new WalStorage<>(snapshotPath, walPath,
new TypeReference<Map<String, String>>() {}, 600000);
store3.load();
assertEquals("data", store3.get("good").orElseThrow());
assertEquals("write", store3.get("later").orElseThrow());
store1.shutdown();
store2.shutdown();
store3.shutdown();
}
@Test
void aNegativeRecordLengthStopsReplayInsteadOfFailingLoad() throws IOException {
Path walPath = tempDir.resolve("negative.wal");
Path snapshotPath = tempDir.resolve("negative-snapshot.json");
try (DataOutputStream out = new DataOutputStream(Files.newOutputStream(walPath))) {
writePutRecord(out, "good", "data");
out.writeByte(WalStorage.OP_PUT);
out.writeInt(Integer.MIN_VALUE);
}
WalStorage<String, String> store = new WalStorage<>(snapshotPath, walPath,
new TypeReference<Map<String, String>>() {}, 600000);
assertDoesNotThrow(store::load);
assertEquals("data", store.get("good").orElseThrow());
assertEquals(1, store.keys().size());
store.shutdown();
}
@Test
void aRecordLengthBeyondTheFileEndIsTreatedAsATornTail() throws IOException {
Path walPath = tempDir.resolve("oversized.wal");
Path snapshotPath = tempDir.resolve("oversized-snapshot.json");
try (DataOutputStream out = new DataOutputStream(Files.newOutputStream(walPath))) {
writePutRecord(out, "good", "data");
out.writeByte(WalStorage.OP_PUT);
out.writeInt(Integer.MAX_VALUE);
out.write(new byte[] {0x61, 0x78});
}
WalStorage<String, String> store1 = new WalStorage<>(snapshotPath, walPath,
new TypeReference<Map<String, String>>() {}, 600000);
assertDoesNotThrow(store1::load);
assertEquals("data", store1.get("good").orElseThrow());
assertEquals(1, store1.keys().size());
store1.put("later", "write");
WalStorage<String, String> store2 = new WalStorage<>(snapshotPath, walPath,
new TypeReference<Map<String, String>>() {}, 600000);
store2.load();
assertEquals("data", store2.get("good").orElseThrow());
assertEquals("write", store2.get("later").orElseThrow());
store1.shutdown();
store2.shutdown();
}
@Test
void loadQuarantinesAnUnreadableSnapshot() throws IOException {
Path snapshotPath = tempDir.resolve("corrupt-snapshot.json");
Path walPath = tempDir.resolve("corrupt-data.wal");
String unreadableContents = "{ not valid json";
Path quarantinePath = tempDir.resolve("corrupt-snapshot.json.corrupt");
Files.writeString(snapshotPath, unreadableContents);
WalStorage<String, String> store = new WalStorage<>(snapshotPath, walPath,
new TypeReference<Map<String, String>>() {}, 600000);
try {
store.load();
assertTrue(store.keys().isEmpty());
assertFalse(Files.exists(snapshotPath));
assertEquals(unreadableContents, Files.readString(quarantinePath));
} finally {
store.shutdown();
}
}
/** Writes one PUT record in the documented WAL layout, independent of the store's writer. */
private static void writePutRecord(DataOutputStream out, String key, String value) throws IOException {
ObjectMapper cbor = new ObjectMapper(new CBORFactory());
byte[] keyBytes = cbor.writeValueAsBytes(key);
byte[] valueBytes = cbor.writeValueAsBytes(value);
out.writeByte(WalStorage.OP_PUT);
out.writeInt(keyBytes.length);
out.write(keyBytes);
out.writeInt(valueBytes.length);
out.write(valueBytes);
}
}
@@ -82,6 +82,8 @@ class LogsMetricFilterCfnProvisionerTest {
"cwlogs-metric-filters.json".equals(i.getArgument(1))
? canonicalStore
: AccountAwareStorageBackend.inMemory("000000000000"));
when(storage.create(any(), any(), any(), any())).thenAnswer(i ->
AccountAwareStorageBackend.inMemory("000000000000"));
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
when(config.services().cloudwatchlogs().maxStoredEvents()).thenReturn(Integer.MAX_VALUE);
logs = new CloudWatchLogsService(storage, config, resolver, null, null);
@@ -0,0 +1,107 @@
package io.github.hectorvent.floci.services.cloudwatch.logs;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.ServiceConfigAccess;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.cloudwatch.logs.model.LogEvent;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* Under {@code persistent} storage a PutLogEvents batch is appended to the events journal instead
* of rewriting the whole events store on every call, while the definition stores keep their
* rewritten-on-every-call file (issue #2500).
*/
class CloudWatchLogsEventJournalTest {
private static final String ACCOUNT = "000000000000";
private static final String REGION = "eu-west-1";
private static final String GROUP = "/journal";
private static final String STREAM = "s";
private static final int EVENTS_PER_BATCH = 10;
@TempDir
Path directory;
@Test
void putLogEventsUnderPersistentModeAppendsToTheJournalInsteadOfRewritingTheStore() throws IOException {
Path journal = directory.resolve("cwlogs-events.wal");
Path eventStore = directory.resolve("cwlogs-events.json");
Path groupStore = directory.resolve("cwlogs-groups.json");
StorageFactory first = newFactory();
CloudWatchLogsService logs = newService(first);
logs.createLogGroup(GROUP, null, null, REGION);
logs.createLogStream(GROUP, STREAM, REGION);
assertTrue(Files.readString(groupStore).contains(GROUP), "definition stores are still written on every call");
Set<String> written = new HashSet<>();
long journalSize = 0;
for (int batch = 0; batch < 3; batch++) {
List<Map<String, Object>> events = batch(batch);
logs.putLogEvents(GROUP, STREAM, events, REGION);
events.forEach(event -> written.add((String) event.get("message")));
assertTrue(journalSize(journal) > journalSize, "every batch must append to the journal");
journalSize = journalSize(journal);
assertFalse(Files.exists(eventStore), "a batch must not rewrite the events store");
}
first.shutdownAll();
assertTrue(Files.exists(eventStore), "a clean shutdown folds the journal into the events store");
StorageFactory second = newFactory();
CloudWatchLogsService reopened = newService(second);
List<LogEvent> read = reopened.getLogEvents(GROUP, STREAM, null, null, 100, true, null, REGION).events();
assertEquals(written, read.stream().map(LogEvent::getMessage).collect(Collectors.toSet()));
second.shutdownAll();
}
private static long journalSize(Path journal) throws IOException {
return Files.exists(journal) ? Files.size(journal) : 0L;
}
private static List<Map<String, Object>> batch(int batch) {
long now = System.currentTimeMillis();
List<Map<String, Object>> events = new ArrayList<>();
for (int i = 0; i < EVENTS_PER_BATCH; i++) {
events.add(Map.of("timestamp", now + i, "message", "batch " + batch + " event " + i));
}
return events;
}
private CloudWatchLogsService newService(StorageFactory factory) {
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
when(config.services().cloudwatchlogs().maxEventsPerQuery()).thenReturn(10_000);
when(config.services().cloudwatchlogs().maxStoredEvents()).thenReturn(10_000);
return new CloudWatchLogsService(factory, config, new RegionResolver(REGION, ACCOUNT), null, null);
}
private StorageFactory newFactory() {
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
when(config.defaultAccountId()).thenReturn(ACCOUNT);
when(config.storage().persistentPath()).thenReturn(directory.toString());
when(config.storage().wal().compactionIntervalMs()).thenReturn(3_600_000L);
ServiceConfigAccess access = mock(ServiceConfigAccess.class);
when(access.storageMode(anyString())).thenReturn("persistent");
when(access.storageFlushInterval(anyString())).thenReturn(3_600_000L);
return new StorageFactory(config, access);
}
}