From a92db31b904a2ff1dce41d271becf4fe2ed501aa Mon Sep 17 00:00:00 2001 From: Tim Date: Wed, 21 Oct 2026 14:09:18 +1300 Subject: [PATCH] Add encrypted remote compaction to the event log (#9571) --- .../eventlog-encrypted-remote-compaction.md | 5 + packages/effect/src/encoding/SchemaBinary.ts | 44 +- packages/effect/src/eventlog/EventLog.ts | 355 ++++- .../effect/src/eventlog/EventLogEncryption.ts | 24 +- .../effect/src/eventlog/EventLogMessage.ts | 274 +++- .../effect/src/eventlog/EventLogRemote.ts | 388 ++++- .../effect/src/eventlog/EventLogServer.ts | 31 +- .../src/eventlog/EventLogServerEncrypted.ts | 1197 +++++++++++++- packages/effect/src/eventlog/EventRow.ts | 15 +- .../eventlog/SqlEventLogServerEncrypted.ts | 1373 +++++++++++++++-- .../effect/src/eventlog/internal/batches.ts | 30 + .../src/eventlog/internal/compaction.ts | 64 + .../src/eventlog/internal/remoteCompaction.ts | 92 ++ .../effect/test/eventlog/EventLog.test.ts | 168 ++ .../test/eventlog/EventLogRemote.test.ts | 172 ++- .../eventlog/EventLogRemoteCompaction.test.ts | 225 +++ .../eventlog/EventLogServerEncrypted.test.ts | 451 ++++++ .../EventLogServerEncryptedCompactionTest.ts | 351 +++++ .../effect/test/eventlog/EventRow.test.ts | 71 + .../SqlEventLogServerEncryptedStorageTest.ts | 506 +++++- packages/sql/mssql/test/Binary.test.ts | 19 + .../sql/mssql/test/Client.integration.test.ts | 27 + ...ventLogServerEncrypted.integration.test.ts | 9 + packages/sql/mssql/test/utils.ts | 34 +- ...ventLogServerEncrypted.integration.test.ts | 9 + ...ventLogServerEncrypted.integration.test.ts | 9 + .../test/SqlEventLogServerEncrypted.test.ts | 10 + 27 files changed, 5660 insertions(+), 293 deletions(-) create mode 100644 .changeset/eventlog-encrypted-remote-compaction.md create mode 100644 packages/effect/src/eventlog/internal/batches.ts create mode 100644 packages/effect/src/eventlog/internal/compaction.ts create mode 100644 packages/effect/src/eventlog/internal/remoteCompaction.ts create mode 100644 packages/effect/test/eventlog/EventLogRemoteCompaction.test.ts create mode 100644 packages/effect/test/eventlog/EventLogServerEncryptedCompactionTest.ts create mode 100644 packages/sql/mssql/test/Client.integration.test.ts diff --git a/.changeset/eventlog-encrypted-remote-compaction.md b/.changeset/eventlog-encrypted-remote-compaction.md new file mode 100644 index 0000000000..393966d1da --- /dev/null +++ b/.changeset/eventlog-encrypted-remote-compaction.md @@ -0,0 +1,5 @@ +--- +"effect": minor +--- + +Add encrypted remote compaction to the event log. diff --git a/packages/effect/src/encoding/SchemaBinary.ts b/packages/effect/src/encoding/SchemaBinary.ts index 4e0eae5bed..ecefe368e0 100644 --- a/packages/effect/src/encoding/SchemaBinary.ts +++ b/packages/effect/src/encoding/SchemaBinary.ts @@ -80,6 +80,7 @@ const codecCache = new WeakMap>() const fingerprintCodecCache = new WeakMap>() const directCodecCache = new WeakMap>() const directFingerprintCodecCache = new WeakMap>() +const strictCodecCache = new WeakMap>() /** * Derives a compact binary codec from a schema. @@ -135,6 +136,27 @@ export function toCodec(schema: S, options?: Option return codec } +/** + * Derives the default-mode {@link toCodec} codec, except that decoding rejects + * struct fields the schema does not know instead of skipping them. + * + * @internal + */ +export function toCodecStrict(schema: S): toCodec { + const cached = strictCodecCache.get(schema) + if (cached !== undefined) return cached + const { exact, layout, recursive, target } = compileTarget(schema) + const trusted: Trusted | undefined = exact ? { value: undefined } : undefined + const codec = assembleCodec( + trusted === undefined ? target : withTrustedDecode(target, trusted, !recursive), + layout, + strictMode, + trusted + ) + strictCodecCache.set(schema, codec) + return codec +} + /** * Derives the {@link toCodec} codec without the schema pass around the binary * layer. @@ -571,7 +593,7 @@ function makeParser( issuePathLen = 0 const bodyStart = pos + headerLen indexSignatures.beginFrame() - body.reset(buf, bodyStart, bodyStart + frameLen, parseOptions, indexSignatures, mode.positional, dict) + body.reset(buf, bodyStart, bodyStart + frameLen, parseOptions, indexSignatures, mode, dict) const value = decodeFrameBody(layout, body, mode) out.push((decodeEncoded === undefined ? value : decodeEncoded(value)) as T) } catch (e) { @@ -1515,6 +1537,7 @@ class Reader { options: SchemaAST.ParseOptions = SchemaAST.defaultParseOptions indexSignatures: IndexSignatureCache | undefined positional = false + rejectUnknownFields = false // Handed to the row-run field's immediate consumer, then cleared. intern: Array | undefined // String tables shared by every frame on one connection; `undefined` for a @@ -1526,7 +1549,7 @@ class Reader { end: number, options: SchemaAST.ParseOptions, indexSignatures: IndexSignatureCache | undefined, - positional: boolean, + mode: Mode, dict: DictRead | undefined ) { this.nesting = 0 @@ -1536,7 +1559,8 @@ class Reader { this.end = end this.options = options this.indexSignatures = indexSignatures - this.positional = positional + this.positional = mode.positional + this.rejectUnknownFields = mode.rejectUnknownFields this.intern = undefined this.dict = dict } @@ -1550,6 +1574,7 @@ class Reader { this.options = SchemaAST.defaultParseOptions this.indexSignatures = undefined this.positional = false + this.rejectUnknownFields = false this.intern = undefined this.dict = undefined } @@ -2882,6 +2907,7 @@ function fingerprintBytes(lo: number, hi: number): Uint8Array { interface Mode { readonly positional: boolean + readonly rejectUnknownFields: boolean readonly envelope: number readonly expectedEnvelope: string readonly fingerprint: Uint8Array @@ -2889,15 +2915,19 @@ interface Mode { const defaultMode: Mode = { positional: false, + rejectUnknownFields: false, envelope: ENVELOPE, expectedEnvelope: "version 2 envelope, flags 0", fingerprint: new Uint8Array(8) } +const strictMode: Mode = { ...defaultMode, rejectUnknownFields: true } + function fingerprintMode(layout: Layout): Mode { const fingerprint = layoutFingerprint(layout) return { positional: true, + rejectUnknownFields: false, envelope: ENVELOPE_FINGERPRINT, expectedEnvelope: "version 2 envelope, flags 1", fingerprint: fingerprintBytes( @@ -4249,6 +4279,7 @@ function decodeExtraPair( const signature = layout.extraAll ?? (r.indexSignatures ??= new IndexSignatureCache(r.options)).find(layout, key) if (signature === undefined) { + if (r.rejectUnknownFields) invalid("a key matching an index signature", key, r.options) skipFieldPayload(kind, r) return } @@ -4345,6 +4376,7 @@ function decodeScalarField(kind: number, r: Reader): unknown { function decodeFieldPayload(layout: Layout, wireMask: number, kind: number, r: Reader): unknown { if ((wireMask & (1 << kind)) === 0) { + if (r.rejectUnknownFields) invalid("matching field wire kind", kind, r.options) skipFieldPayload(kind, r) return ABSENT } @@ -4401,6 +4433,7 @@ function decodeStruct(layout: StructLayout, r: Reader): unknown { if (field !== undefined) cursor = field.index + 1 } if (field === undefined) { + if (r.rejectUnknownFields) invalid("a known field id", id, r.options) if (seenUnknown === undefined) seenUnknown = new Set() else if (seenUnknown.has(id)) invalid("unique field ids", undefined, r.options) seenUnknown.add(id) @@ -4620,6 +4653,7 @@ function decodeRunRow( } else { slot = struct.byId.get(id) if (slot === undefined) { + if (r.rejectUnknownFields) invalid("a known field id", id, r.options) if (seenIds === undefined) seenIds = new Set([id]) else if (seenIds.has(id)) invalid("unique field ids", undefined, r.options) else seenIds.add(id) @@ -4817,6 +4851,7 @@ function decodeUnion(layout: UnionLayout, r: Reader): unknown { const tag = r.u32le() const variant = layout.byTag.get(tag) if (variant === undefined) { + if (r.rejectUnknownFields) invalid("known union member", tag, r.options) r.take(r.remaining) return ABSENT } @@ -4831,6 +4866,7 @@ function decodeUnion(layout: UnionLayout, r: Reader): unknown { } const member = layout.byKind.get(kind) if (member === undefined) { + if (r.rejectUnknownFields) invalid("known union member", kind, r.options) r.take(r.remaining) return ABSENT } @@ -5064,7 +5100,7 @@ function decodeOneShot( const r = pooledReader ?? new Reader() const pooled = r === pooledReader if (pooled) pooledReader = undefined - r.reset(bytes, 0, bytes.length, options, undefined, mode.positional, undefined) + r.reset(bytes, 0, bytes.length, options, undefined, mode, undefined) const savedPathLen = issuePathLen issuePathLen = 0 try { diff --git a/packages/effect/src/eventlog/EventLog.ts b/packages/effect/src/eventlog/EventLog.ts index a9909f6814..23ed689553 100644 --- a/packages/effect/src/eventlog/EventLog.ts +++ b/packages/effect/src/eventlog/EventLog.ts @@ -7,6 +7,45 @@ * committed only after the handler succeeds. This module also contains the * layers and helpers needed to assemble that runtime. * + * **Remote compaction** + * + * An encrypted remote whose server sets `HelloResponse.compaction` can store a + * compacted snapshot of its history, so a new device replays the snapshot and + * a recent tail instead of every write. Clients build the snapshots because + * only they can decrypt the entries. + * + * Only a client with a `remote: true` compactor, on a remote not built with + * `compaction: false`, calls the compaction RPCs. It polls the status on + * connect and about hourly. When the server wants compaction and the journal + * has caught up, it starts a background run after a random delay of a few + * minutes. The run reads the input, taking entries from the journal where it + * can and fetching the rest, runs the opted-in compactors and uploads the + * entries they keep. The server lets one run per store hold a stage and + * answers the others `Busy`, so devices that start together download the + * input once. `EventLog.compact` starts a run immediately, for example from + * a worker holding the identity. + * + * An operator can roll back a bad snapshot on the server. The server then + * re-appends the snapshot's input at the head, so every client, including + * ones from before remote compaction, receives the dropped entries through + * `changes` and skips the ones it already holds. + * + * Known limitations: + * + * - A run holds every kept entry in memory. A device with a large store can + * opt out with `compaction: false` and leave compaction to a device or + * worker with more memory. + * - The library can't check that a compactor keeps the `remote` contract (see + * `groupCompaction`). The drop-only and idempotence checks catch common + * mistakes. A snapshot that drops too much can only be undone by a rollback + * before the server prunes the history. + * - Changes to a field's meaning between schema versions aren't detected. + * Strict decoding only catches unknown fields. + * - A new device still replays the newest day or so of writes, because the + * server only compacts data older than its lag. + * - A client that stops partway through a run holds the server's busy claim + * until its stage expires. + * * @stability unstable * @since 4.0.0 */ @@ -14,15 +53,20 @@ import * as Arr from "../Array.ts" import * as Cause from "../Cause.ts" import * as Context from "../Context.ts" import * as Effect from "../Effect.ts" +import * as SchemaBinary from "../encoding/SchemaBinary.ts" +import * as Equal from "../Equal.ts" +import * as FiberHandle from "../FiberHandle.ts" import * as FiberMap from "../FiberMap.ts" import { constant, identity } from "../Function.ts" import * as InternalRecord from "../internal/record.ts" +import * as Uuid from "../internal/uuid.ts" import * as Layer from "../Layer.ts" import type { Pipeable } from "../Pipeable.ts" import { pipeArguments } from "../Pipeable.ts" import * as Predicate from "../Predicate.ts" import * as PubSub from "../PubSub.ts" import * as Queue from "../Queue.ts" +import * as Random from "../Random.ts" import { Reactivity } from "../reactivity/Reactivity.ts" import * as ReactivityLayer from "../reactivity/Reactivity.ts" import type * as Record from "../Record.ts" @@ -33,14 +77,22 @@ import * as Schedule from "../Schedule.ts" import * as Schema from "../Schema.ts" import * as SchemaGetter from "../SchemaGetter.ts" import type * as Scope from "../Scope.ts" +import * as Stream from "../Stream.ts" import type { Covariant } from "../Types.ts" import type * as Event from "./Event.ts" import type * as EventGroup from "./EventGroup.ts" import { Entry, EventJournal, type EventJournalError, makeEntryIdUnsafe, type RemoteId } from "./EventJournal.ts" import * as EventLogEncryption from "./EventLogEncryption.ts" -import { StoreId } from "./EventLogMessage.ts" -import type { EventLogRemote } from "./EventLogRemote.ts" +import { type CompactionInputHeader, EventLogProtocolError, StoreId } from "./EventLogMessage.ts" +import type { + CompactionStage, + EventLogRemote, + EventLogRemoteCompaction, + EventLogRemoteError +} from "./EventLogRemote.ts" +import { maxBatchEntries } from "./internal/batches.ts" import { setAnchor } from "./internal/conflicts.ts" +import * as RemoteCompaction from "./internal/remoteCompaction.ts" /** * Service for writing typed event-log events through registered handlers. @@ -87,6 +139,30 @@ export class EventLog extends Context.Service readonly entries: Effect.Effect, EventJournalError> readonly destroy: Effect.Effect + /** + * Runs one remote compaction now, on every registered remote that offers + * compaction or only on `remoteId`. + * + * Unlike the background trigger, it doesn't wait for the journal to catch + * up, and it works from an empty journal. Remotes built with + * `compaction: false` are skipped, and nothing runs when no compactor is + * registered with `remote: true`. + * + * `Committed` and `Superseded` mean a snapshot was uploaded, `NoOp` that + * nothing was dropped, and `NotWanted` and `Busy` come from the server. + * `Aborted` means nothing was uploaded and the stage was released, because + * a compactor died, the idempotence check failed, every entry was dropped + * or the input was pruned during the run. + */ + readonly compact: (options?: { + readonly remoteId?: RemoteId | undefined + }) => Effect.Effect< + ReadonlyArray<{ + readonly remoteId: RemoteId + readonly result: "Committed" | "Superseded" | "NoOp" | "NotWanted" | "Busy" | "Aborted" + }>, + EventJournalError | EventLogRemoteError + > }>()("effect/eventlog/EventLog") {} /** @@ -107,8 +183,18 @@ export class Registry extends Context.Service + /** + * Also run this compactor over a remote's history to build snapshots. The + * kept entries must depend only on the set of input entries and compose: + * `drop(drop(a) ++ b)` keeps the same entries as `drop(a ++ b)`, even when + * `b` holds entries older than `a`. A call that writes an entry it wasn't + * given keeps its whole input. + */ + readonly remote?: boolean | undefined readonly effect: (options: { readonly entries: ReadonlyArray + /** True during a remote compaction, which only drops entries. */ + readonly remote?: boolean | undefined // Pass an input entry as source to anchor replacements during remote replay. // Without it, matching IDs retain their position; new IDs use the group start. readonly write: (entry: Entry, source?: Entry) => Effect.Effect @@ -117,13 +203,16 @@ export class Registry extends Context.Service + readonly remote: boolean readonly effect: (options: { readonly entries: ReadonlyArray + readonly remote?: boolean | undefined readonly write: (entry: Entry, source?: Entry) => Effect.Effect }) => Effect.Effect }> readonly registerRemote: (remote: EventLogRemote["Service"]) => Effect.Effect + readonly remotes: ReadonlyMap readonly handleRemote: (handler: (remote: EventLogRemote["Service"]) => Effect.Effect) => Effect.Effect readonly registerReactivity: (keys: Record>) => Effect.Effect @@ -145,8 +234,10 @@ export const layerRegistry = Layer.effect( const handlers = new Map>() const compactors = new Map + readonly remote: boolean readonly effect: (options: { readonly entries: ReadonlyArray + readonly remote?: boolean | undefined readonly write: (entry: Entry, source?: Entry) => Effect.Effect }) => Effect.Effect }>() @@ -166,6 +257,7 @@ export const layerRegistry = Layer.effect( const events = new Set(options.events) const compactor = { events, + remote: options.remote ?? false, effect: options.effect } for (const event of options.events) { @@ -184,6 +276,7 @@ export const layerRegistry = Layer.effect( return FiberMap.remove(remoteFiberMap, remote.id) } ), + remotes, handleRemote(handler) { remoteHandler = handler return Effect.forEach(remotes, ([id, remote]) => FiberMap.run(remoteFiberMap, id, handler(remote)), { @@ -684,7 +777,8 @@ const registerBatchCompaction = ( payload: Event.PayloadWithTag ) => Effect.Effect["EncodingServices"]> readonly forward: (entry: Entry) => Effect.Effect - }) => Effect.Effect + }) => Effect.Effect, + options: { readonly remote?: boolean | undefined } | undefined ): Layer.Layer["DecodingServices"] | Registry> => Layer.effectDiscard( Effect.gen(function*() { @@ -693,10 +787,15 @@ const registerBatchCompaction = ( yield* registry.registerCompaction({ events: Object.keys(group.events), - effect: Effect.fnUntraced(function*({ entries, write }): Effect.fn.Return { + remote: options?.remote, + effect: Effect.fnUntraced(function*({ entries, remote = false, write }): Effect.fn.Return { + // In a remote compaction, unknown fields make an entry undecodable, + // and undecodable entries are always kept. const isEventTag = (tag: string): tag is Event.Tag => Object.hasOwn(group.events, tag) const decodePayload = >(tag: Tag, payload: Uint8Array) => - Schema.decodeUnknownEffect(group.events[tag].payloadSchemaBinary)(payload).pipe( + Schema.decodeUnknownEffect( + remote ? SchemaBinary.toCodecStrict(group.events[tag].payload) : group.events[tag].payloadSchemaBinary + )(payload).pipe( Effect.updateContext((input) => Context.merge(services, input)) ) as unknown as Effect.Effect, Schema.SchemaError> const writeFrom = Effect.fnUntraced(function*>( @@ -726,6 +825,7 @@ const registerBatchCompaction = ( continue } const payload = yield* Effect.result(decodePayload(entry.event, entry.payload)) + if (remote && Result.isFailure(payload)) yield* forward(entry) batch.push({ entry, event: Result.isFailure(payload) @@ -794,14 +894,36 @@ export const groupBatchCompaction = ( payload: Event.PayloadWithTag ) => Effect.Effect["EncodingServices"]> readonly forward: (entry: Entry) => Effect.Effect - }) => Effect.Effect + }) => Effect.Effect, + options?: { + /** + * Also run this compactor over a remote's history to build snapshots. + * + * Opting in promises a contract the library can't check. The kept entries + * depend only on the set of input entries, never on services, the clock + * or input order, and compaction composes: `drop(drop(a) ++ b)` keeps the + * same entries as `drop(a ++ b)`, even when `b` holds entries older than + * `a`. + * + * Remote compaction only drops entries. A call that uses `write` keeps its + * whole input, and entries that fail to decode, including ones with fields + * the schema doesn't know, are always kept. Before uploading, a run passes + * the kept entries through the compactors again and uploads nothing if + * that drops more or a compactor dies. + * + * A snapshot that drops too much can be rolled back on the server until + * the history it replaced is pruned. The module docs cover when runs start + * and other limitations. + */ + readonly remote?: boolean | undefined + } ): Layer.Layer["DecodingServices"] | Registry> => registerBatchCompaction(group, ({ entries, writeFrom, forward }) => effect({ entries, write: (tag, payload) => writeFrom(entries[0].entry, tag, payload), forward - })) + }), options) /** * Registers a compaction handler for an event group. @@ -848,7 +970,29 @@ export const groupCompaction = ( payload: Event.PayloadWithTag ) => Effect.Effect["EncodingServices"]> readonly forward: (entry: Entry) => Effect.Effect - }) => Effect.Effect + }) => Effect.Effect, + options?: { + /** + * Also run this compactor over a remote's history to build snapshots. + * + * Opting in promises a contract the library can't check. The kept entries + * depend only on the set of input entries, never on services, the clock + * or input order, and compaction composes: `drop(drop(a) ++ b)` keeps the + * same entries as `drop(a ++ b)`, even when `b` holds entries older than + * `a`. + * + * Remote compaction only drops entries. A call that uses `write` keeps its + * whole input, and entries that fail to decode, including ones with fields + * the schema doesn't know, are always kept. Before uploading, a run passes + * the kept entries through the compactors again and uploads nothing if + * that drops more or a compactor dies. + * + * A snapshot that drops too much can be rolled back on the server until + * the history it replaced is pruned. The module docs cover when runs start + * and other limitations. + */ + readonly remote?: boolean | undefined + } ): Layer.Layer["DecodingServices"] | Registry> => registerBatchCompaction( group, @@ -883,7 +1027,8 @@ export const groupCompaction = ( forward }) } - }) + }), + options ) type ReactivityKeyName = [keyof ReactivityLayer.Keys] extends [never] ? string : keyof ReactivityLayer.Keys @@ -1074,6 +1219,20 @@ const remoteRetrySchedule = Schedule.min([ Schedule.spaced({ seconds: 10 }) ]) +type CompactionResult = Effect.Success>[number]["result"] + +// Status is polled on each connect and then hourly, jittered. +const compactionPollMillis = 60 * 60 * 1000 + +// Spreads out devices that see `wanted` at the same time. +const compactionDelayMillis = { min: 60 * 1000, max: 5 * 60 * 1000 } + +// How many input batch headers share one journal lookup and one fetch. +const compactionLookupBatches = 16 + +const isNotFound = (error: EventLogRemoteError): boolean => + EventLogProtocolError.is(error.cause) && error.cause.code === "NotFound" + const make = Effect.gen(function*() { const storeId = yield* CurrentStoreId const identity = yield* Identity @@ -1097,13 +1256,160 @@ const make = Effect.gen(function*() { const invalidateReactivityEntries = (entries: ReadonlyArray) => Effect.forEach(entries, (entry) => invalidateEntry(reactivity, registry.reactivityKeys, entry), { discard: true }) + const hasRemoteCompactor = () => { + for (const compactor of registry.compactors.values()) { + if (compactor.remote) return true + } + return false + } + + // Resolves input headers to entries in input order, skipping ids seen at a + // lower input sequence. Only batches with an id the journal lacks are + // fetched. + const resolveInput = Effect.fnUntraced(function*( + compaction: EventLogRemoteCompaction, + stage: CompactionStage, + headers: ReadonlyArray, + seen: Set + ) { + const known = yield* journal.entriesById(headers.flatMap((header) => header.entryIds)).pipe( + journal.withLock(storeId) + ) + const missing: Array = [] + let offset = 0 + for (const header of headers) { + for (let i = 0; i < header.entryIds.length; i++) { + if (known[offset + i] === undefined) { + missing.push(header.sequence) + break + } + } + offset += header.entryIds.length + } + const fetched = new Map() + if (missing.length > 0) { + yield* Stream.runForEach(compaction.fetch(stage, missing), (remoteEntry) => + Effect.sync(() => { + fetched.set(remoteEntry.remoteSequence, remoteEntry.entry) + })) + } + const entries: Array = [] + offset = 0 + for (const header of headers) { + for (let i = 0; i < header.entryIds.length; i++) { + const entry = known[offset + i] ?? fetched.get(header.sequence + i) + if (entry === undefined) { + return yield* Effect.die(new Error(`Compaction input sequence ${header.sequence + i} was not fetched`)) + } + if (seen.has(entry.idString)) continue + seen.add(entry.idString) + entries.push(entry) + } + offset += header.entryIds.length + } + return entries + }) + + const runStage = Effect.fnUntraced(function*(compaction: EventLogRemoteCompaction, stage: CompactionStage) { + const seen = new Set() + const kept = yield* RemoteCompaction.run({ + compactors: registry.compactors, + entries: compaction.input(stage).pipe( + Stream.grouped(compactionLookupBatches), + Stream.mapEffect((headers) => resolveInput(compaction, stage, headers, seen)), + Stream.flattenIterable + ), + chunkSize: maxBatchEntries + }) + if (kept.length === seen.size) { + const result = yield* compaction.commit(stage, { _tag: "NoOp" }) + return result === "Committed" ? "NoOp" : result + } + if (kept.length === 0) { + yield* Effect.logWarning("Remote compaction dropped every entry, so nothing is uploaded") + yield* compaction.abort(stage) + return "Aborted" + } + const { segmentCount } = yield* compaction.upload(stage, kept) + const result = yield* compaction.commit(stage, { _tag: "Snapshot", segmentCount }) + yield* Effect.logDebug(`Remote compaction kept ${kept.length} of ${seen.size} entries: ${result}`) + return result + }) + + // Shared by the background trigger and `compact`. The server's busy claim + // keeps runs on a store apart, so the journal lock is held only for id + // lookups. + const runCompaction = ( + remote: EventLogRemote["Service"], + compaction: EventLogRemoteCompaction + ): Effect.Effect => + Effect.gen(function*() { + const begin = yield* compaction.begin({ identity, storeId }) + if (begin._tag !== "Started") return begin._tag + const stage: CompactionStage = { identity, storeId, stageId: begin.stageId } + return yield* runStage(compaction, stage).pipe( + Effect.onError(() => compaction.abort(stage)), + Effect.catchTag("IdempotenceError", (error) => + Effect.as( + Effect.logError( + `A remote compactor dropped ${error.entries.length} more entries from its own output, so nothing is uploaded` + ), + "Aborted" as const + )), + Effect.catchIf( + (error): error is EventLogRemoteError => error._tag === "EventLogRemoteError" && isNotFound(error), + (error) => + Effect.as( + Effect.logWarning("The compaction input was pruned during the run", error), + "Aborted" as const + ) + ), + Effect.catchDefect((defect) => + Effect.as(Effect.logError("Remote compaction died, so nothing is uploaded", defect), "Aborted" as const) + ) + ) + }).pipe( + Effect.annotateLogs({ + service: "EventLog", + effect: "compact", + remoteId: Uuid.stringify(remote.id) + }) + ) + const runRemote = Effect.fnUntraced( function*(remote: EventLogRemote["Service"]) { - yield* Effect.gen(function*() { - const startSequence = yield* journal.nextRemoteSequence(remote.id) + const compaction = remote.compaction + const trigger = yield* FiberHandle.make() + + // Caught up means the journal holds the remote up to the status head. + const pollStatus = Effect.fnUntraced( + function*(compaction: EventLogRemoteCompaction) { + if (!hasRemoteCompactor()) return + const status = yield* compaction.status({ identity, storeId }) + if (!status.wanted || (yield* journal.nextRemoteSequence(remote.id)) <= status.head) return + yield* FiberHandle.run( + trigger, + Random.nextIntBetween(compactionDelayMillis.min, compactionDelayMillis.max).pipe( + Effect.flatMap((millis) => Effect.sleep(millis)), + Effect.andThen(runCompaction(remote, compaction)), + Effect.flatMap((result) => Effect.logDebug(`Remote compaction finished: ${result}`)), + Effect.catchCause(Effect.logWarning) + ), + { onlyIfMissing: true } + ) + }, + Effect.catchCause(Effect.logWarning), + Effect.annotateLogs({ + service: "EventLog", + effect: "runRemote compaction status" + }) + ) + + const consume: Effect.Effect = Effect.gen(function*() { + if (compaction !== undefined) yield* pollStatus(compaction) const changes = yield* remote.changes({ identity, - startSequence, + startSequence: yield* journal.nextRemoteSequence(remote.id), storeId, knownEntries: journal.entriesById }) @@ -1178,9 +1484,16 @@ const make = Effect.gen(function*() { Effect.annotateLogs({ service: "EventLog", effect: "runRemote consume" - }), - Effect.forkScoped + }) ) + yield* Effect.forkScoped(consume) + + if (compaction !== undefined) { + yield* pollStatus(compaction).pipe( + Effect.schedule(Schedule.jittered(Schedule.spaced(compactionPollMillis))), + Effect.forkScoped + ) + } const write = journal.withRemoteUncommited( remote.id, @@ -1263,7 +1576,19 @@ const make = Effect.gen(function*() { writeMany: ((options: { readonly events: Arr.NonEmptyReadonlyArray }) => writeEvents(options.events)) as EventLog["Service"]["writeMany"], entries: journal.entries, - destroy: journal.destroy + destroy: journal.destroy, + compact: (options) => + Effect.suspend(() => { + if (!hasRemoteCompactor()) { + return Effect.succeed([]) + } + const remoteId = options?.remoteId + const remotes = Array.from(registry.remotes.values()).filter((remote) => + remote.compaction !== undefined && (remoteId === undefined || Equal.equals(remote.id, remoteId)) + ) + return Effect.forEach(remotes, (remote) => + Effect.map(runCompaction(remote, remote.compaction!), (result) => ({ remoteId: remote.id, result }))) + }) }) }) diff --git a/packages/effect/src/eventlog/EventLogEncryption.ts b/packages/effect/src/eventlog/EventLogEncryption.ts index 02317d7102..59d40d65bb 100644 --- a/packages/effect/src/eventlog/EventLogEncryption.ts +++ b/packages/effect/src/eventlog/EventLogEncryption.ts @@ -23,6 +23,7 @@ import * as Schema from "../Schema.ts" import * as Transferable from "../workers/Transferable.ts" import { type Entry, EntryFields, entryFromFields, EntryId, RemoteEntry } from "./EventJournal.ts" import type { Identity } from "./EventLog.ts" +import { toBatches } from "./internal/batches.ts" import { cachedByIdentity, deriveEncryptionKey } from "./internal/identityRootSecretDerivation.ts" /** @@ -81,29 +82,6 @@ export const EncryptedRemoteBatch = Schema.Struct({ ...EncryptedBatch.fields }) -const maxBatchEntries = 100 -const maxBatchPayloadBytes = 256 * 1024 - -// A batch holds at most `maxBatchEntries` entries or `maxBatchPayloadBytes` of -// payload, whichever comes first. A single larger entry is a batch on its own. -const toBatches = (entries: ReadonlyArray): Array> => { - const batches: Array> = [] - let current: Array = [] - let bytes = 0 - for (const entry of entries) { - const size = entry.payload.byteLength - if (current.length > 0 && (current.length === maxBatchEntries || bytes + size > maxBatchPayloadBytes)) { - batches.push(current as NonEmptyArray) - current = [] - bytes = 0 - } - current.push(entry) - bytes += size - } - if (current.length > 0) batches.push(current as NonEmptyArray) - return batches -} - const textEncoder = new TextEncoder() // The store id is length-prefixed, followed by the 16-byte entry ids. diff --git a/packages/effect/src/eventlog/EventLogMessage.ts b/packages/effect/src/eventlog/EventLogMessage.ts index 92011259a7..87ec1fa062 100644 --- a/packages/effect/src/eventlog/EventLogMessage.ts +++ b/packages/effect/src/eventlog/EventLogMessage.ts @@ -113,6 +113,7 @@ export class EventLogAuthentication extends RpcMiddleware.Service("effect/eventlog/EventLogRemote/HelloResponse")({ remoteId: RemoteId, challenge: Transferable.Uint8Array, - firstSequence: Schema.optional(Schema.Natural) + firstSequence: Schema.optional(Schema.Natural), + compaction: Schema.optional(Schema.Literal(true)) }) {} /** @@ -441,3 +443,273 @@ export class EventLogRemoteRpcs extends RpcGroup.make( WriteSingleRpc, ChangesRpc ) {} + +const compactionScope = { + publicKey: Schema.String, + storeId: StoreId +} + +const compactionStage = { + ...compactionScope, + stageId: Schema.String +} + +/** + * The compaction state of a store, as reported to clients. + * + * **Details** + * + * `wanted` is `true` when the server would open a compaction stage. `head` is + * the highest stored sequence. + * + * @stability unstable + * @category protocols + * @since 4.0.0 + */ +export class CompactionStatus + extends Schema.Class("effect/eventlog/EventLogRemote/CompactionStatus")({ + wanted: Schema.Boolean, + head: Schema.Int + }) +{} + +/** + * RPC that reports a store's compaction state. + * + * @stability unstable + * @category protocols + * @since 4.0.0 + */ +export class CompactionStatusRpc extends Rpc.make("EventLog.CompactionStatus", { + payload: compactionScope, + success: CompactionStatus, + error: EventLogProtocolError +}).middleware(EventLogAuthentication) {} + +/** + * Schema for the result of opening a compaction stage. + * + * **Details** + * + * `Started` pins the stage to the active generation and to the last input + * sequence. `Busy` means another stage is open on the store. `NotWanted` means + * the store doesn't need compacting. + * + * @stability unstable + * @category protocols + * @since 4.0.0 + */ +export const CompactionBeginResult = Schema.Union([ + Schema.TaggedStruct("Started", { + stageId: Schema.String + }), + Schema.TaggedStruct("Busy", {}), + Schema.TaggedStruct("NotWanted", {}) +]) + +/** + * The result of opening a compaction stage. + * + * @stability unstable + * @category protocols + * @since 4.0.0 + */ +export type CompactionBeginResult = typeof CompactionBeginResult.Type + +/** + * RPC that opens a compaction stage. + * + * @stability unstable + * @category protocols + * @since 4.0.0 + */ +export class CompactionBeginRpc extends Rpc.make("EventLog.CompactionBegin", { + payload: compactionScope, + success: CompactionBeginResult, + error: EventLogProtocolError +}).middleware(EventLogAuthentication) {} + +/** + * Schema for the header of one compaction input batch. + * + * **Details** + * + * An entry's input sequence is the batch `sequence` plus its position in + * `entryIds`. + * + * @stability unstable + * @category protocols + * @since 4.0.0 + */ +export const CompactionInputHeader = Schema.Struct({ + sequence: Schema.Natural, + entryIds: Schema.NonEmptyArray(EntryId) +}) + +/** + * The header of one compaction input batch. + * + * @stability unstable + * @category protocols + * @since 4.0.0 + */ +export type CompactionInputHeader = typeof CompactionInputHeader.Type + +/** + * RPC that streams a stage's input batch headers in input order. + * + * **Details** + * + * The input is the pinned snapshot, then the originals up to the stage's + * `through`. Headers are framed as `SingleMessage` values or `ChunkedMessage` + * parts, as in `ChangesRpc`. It fails with a `NotFound` error once the stage + * or its pin is gone. + * + * @stability unstable + * @category protocols + * @since 4.0.0 + */ +export class CompactionInputRpc extends Rpc.make("EventLog.CompactionInput", { + payload: compactionStage, + success: Schema.Union([SingleMessage, ChunkedMessage]), + error: EventLogProtocolError, + stream: true +}).middleware(EventLogAuthentication) { + static HeadersFromSchemaBinary = SchemaBinary.toCodec(Schema.NonEmptyArray(CompactionInputHeader)) + static encodeHeaders = Schema.encodeEffect(CompactionInputRpc.HeadersFromSchemaBinary) + static decodeHeaders = Schema.decodeEffect(CompactionInputRpc.HeadersFromSchemaBinary) +} + +/** + * RPC that streams the encrypted input batches at the given input sequences. + * + * **Details** + * + * `batches` holds the input sequence of each batch to fetch. Batches are framed + * and encoded as in `ChangesRpc`. It fails with a `NotFound` error once the + * stage or its pin is gone. + * + * @stability unstable + * @category protocols + * @since 4.0.0 + */ +export class CompactionFetchRpc extends Rpc.make("EventLog.CompactionFetch", { + payload: { + ...compactionStage, + batches: Schema.Array(Schema.Natural) + }, + success: Schema.Union([SingleMessage, ChunkedMessage]), + error: EventLogProtocolError, + stream: true +}).middleware(EventLogAuthentication) {} + +/** + * RPC that uploads one piece of a compaction snapshot segment. + * + * **Details** + * + * A segment is an encoded non-empty array of encrypted batches, indexed by + * `chunk.id`, and is split into pieces when larger than + * `ChunkedMessage.chunkSize`. Re-uploading a stored segment is acknowledged + * without storing it again. A segment that fails validation aborts the stage + * with an `InvalidRequest` error. + * + * @stability unstable + * @category protocols + * @since 4.0.0 + */ +export class CompactionPartRpc extends Rpc.make("EventLog.CompactionPart", { + payload: { + ...compactionStage, + chunk: ChunkedMessage + }, + error: EventLogProtocolError +}).middleware(EventLogAuthentication) { + static SegmentFromSchemaBinary = SchemaBinary.toCodec(Schema.NonEmptyArray(EncryptedBatch)) + static encodeSegment = Schema.encodeEffect(CompactionPartRpc.SegmentFromSchemaBinary) + static decodeSegment = Schema.decodeEffect(CompactionPartRpc.SegmentFromSchemaBinary) +} + +/** + * RPC that releases an open compaction stage. A late abort is a no-op. + * + * @stability unstable + * @category protocols + * @since 4.0.0 + */ +export class CompactionAbortRpc extends Rpc.make("EventLog.CompactionAbort", { + payload: compactionStage, + error: EventLogProtocolError +}).middleware(EventLogAuthentication) {} + +/** + * Schema for the outcome of a compaction run reported at commit. + * + * **Details** + * + * `Snapshot` activates the `segmentCount` uploaded segments. `NoOp` reports a + * run that dropped nothing. + * + * @stability unstable + * @category protocols + * @since 4.0.0 + */ +export const CompactionResult = Schema.Union([ + Schema.TaggedStruct("Snapshot", { segmentCount: Schema.Natural }), + Schema.TaggedStruct("NoOp", {}) +]) + +/** + * The outcome of a compaction run reported at commit. + * + * @stability unstable + * @category protocols + * @since 4.0.0 + */ +export type CompactionResult = typeof CompactionResult.Type + +/** + * RPC that commits a compaction stage. + * + * **Details** + * + * Answers `Superseded` when the stage's pinned generation is no longer active. + * Fails with `InvalidRequest`, aborting the stage, when the segments are + * incomplete or the kept ids are not a non-empty, repeat-free subsequence of + * the pinned input. Fails with `NotFound` when the stage expired, was aborted + * or committed, or is unknown, so a retried commit fails too. + * + * @stability unstable + * @category protocols + * @since 4.0.0 + */ +export class CompactionCommitRpc extends Rpc.make("EventLog.CompactionCommit", { + payload: { + ...compactionStage, + result: CompactionResult + }, + success: Schema.Literals(["Committed", "Superseded"]), + error: EventLogProtocolError +}).middleware(EventLogAuthentication) {} + +/** + * RPC group for encrypted remote compaction. + * + * **Details** + * + * Served by the encrypted server alongside `EventLogRemoteRpcs`. Clients call + * it only when `HelloResponse.compaction` is set. + * + * @stability unstable + * @category protocols + * @since 4.0.0 + */ +export class EventLogCompactionRpcs extends RpcGroup.make( + CompactionStatusRpc, + CompactionBeginRpc, + CompactionInputRpc, + CompactionFetchRpc, + CompactionPartRpc, + CompactionAbortRpc, + CompactionCommitRpc +) {} diff --git a/packages/effect/src/eventlog/EventLogRemote.ts b/packages/effect/src/eventlog/EventLogRemote.ts index be9e5ff829..92d7b17395 100644 --- a/packages/effect/src/eventlog/EventLogRemote.ts +++ b/packages/effect/src/eventlog/EventLogRemote.ts @@ -11,6 +11,7 @@ * @stability unstable * @since 4.0.0 */ +import * as Arr from "../Array.ts" import * as Cache from "../Cache.ts" import * as Context from "../Context.ts" import * as Data from "../Data.ts" @@ -19,27 +20,38 @@ import * as Layer from "../Layer.ts" import * as Predicate from "../Predicate.ts" import * as Queue from "../Queue.ts" import * as Redacted from "../Redacted.ts" +import * as Result from "../Result.ts" import * as RpcClient from "../rpc/RpcClient.ts" import type { RpcClientError } from "../rpc/RpcClientError.ts" import type * as RpcGroup from "../rpc/RpcGroup.ts" import type * as Schema from "../Schema.ts" import type * as Scope from "../Scope.ts" +import * as Stream from "../Stream.ts" import { type Entry, type EventJournal, type EventJournalError, RemoteEntry, type RemoteId } from "./EventJournal.ts" import { type Identity, Registry } from "./EventLog.ts" -import { EventLogEncryption, layerSubtle } from "./EventLogEncryption.ts" +import { type EncryptedBatch, EventLogEncryption, layerSubtle } from "./EventLogEncryption.ts" import { Authenticate, ChangesRpc, ChunkedMessage, + type CompactionBeginResult, + type CompactionInputHeader, + CompactionInputRpc, + CompactionPartRpc, + type CompactionResult, + type CompactionStatus, + EventLogCompactionRpcs, EventLogProtocolError, EventLogRemoteRpcs, type HelloResponse, + type SingleMessage, type StoreId, type WriteAck, WriteEntries, WriteEntriesUnencrypted } from "./EventLogMessage.ts" import { encodeSessionAuthPayload, signSessionAuthPayloadBytes } from "./EventLogSessionAuth.ts" +import { toBatches } from "./internal/batches.ts" import { makeGetIdentityRootSecretMaterial } from "./internal/identityRootSecretDerivation.ts" /** @@ -87,8 +99,82 @@ export class EventLogRemote extends Context.Service( effect: Effect.Effect ) => Effect.Effect + /** + * Encrypted remote compaction. Present when the remote advertises + * `HelloResponse.compaction` and the RPC client includes + * `EventLogCompactionRpcs`. + */ + readonly compaction?: EventLogRemoteCompaction | undefined }>()("effect/eventlog/EventLogRemote") {} +/** + * A stage opened by `EventLogRemoteCompaction.begin`, with the identity and + * store it belongs to. + * + * @stability unstable + * @category models + * @since 4.0.0 + */ +export interface CompactionStage { + readonly identity: Identity["Service"] + readonly storeId: StoreId + readonly stageId: string +} + +/** + * Client side of encrypted remote compaction. + * + * **Details** + * + * A run opens a stage with `begin`, reads its input headers with `input`, + * fetches the batches it needs with `fetch`, uploads the kept entries with + * `upload` and calls `commit`. `abort` releases a stage that won't be + * committed. + * + * @stability unstable + * @category models + * @since 4.0.0 + */ +export interface EventLogRemoteCompaction { + readonly status: (options: { + readonly identity: Identity["Service"] + readonly storeId: StoreId + }) => Effect.Effect + readonly begin: (options: { + readonly identity: Identity["Service"] + readonly storeId: StoreId + }) => Effect.Effect + /** + * Streams the stage's input batch headers in input order. + */ + readonly input: (stage: CompactionStage) => Stream.Stream + /** + * Fetches and decrypts the input batches at the given input sequences. + */ + readonly fetch: ( + stage: CompactionStage, + sequences: ReadonlyArray + ) => Stream.Stream + /** + * Encrypts the kept entries, in input-sequence order, and uploads them in + * segments of about `ChunkedMessage.chunkSize`. An oversized segment is + * split into pieces, and a segment is resent in full after a dropped + * connection. + */ + readonly upload: ( + stage: CompactionStage, + entries: ReadonlyArray + ) => Effect.Effect<{ readonly segmentCount: number }, EventLogRemoteError> + readonly commit: ( + stage: CompactionStage, + result: CompactionResult + ) => Effect.Effect<"Committed" | "Superseded", EventLogRemoteError> + /** + * Releases the stage. Failures are ignored. + */ + readonly abort: (stage: CompactionStage) => Effect.Effect +} + /** * Error raised by `EventLogRemote` operations, recording the failed method and * underlying cause. @@ -146,24 +232,36 @@ const makeAuthenticate = Effect.fnUntraced(function*(options: { * Use to provide the RPC client used by remote event-log replicas to * authenticate, write entries, and subscribe to changes. * + * **Details** + * + * The `EventLogCompactionRpcs` methods are optional. The encrypted remote + * offers compaction only when the client has them. `layer` builds the client + * from both groups. + * * @stability unstable * @category services * @since 4.0.0 */ export class EventLogRemoteClient extends Context.Service< EventLogRemoteClient, - RpcClient.RpcClient, RpcClientError> + & RpcClient.RpcClient, RpcClientError> + & Partial >()( "effect/eventlog/EventLogRemote/EventLogRemoteClient" ) { static readonly layer = Layer.effect( EventLogRemoteClient, - RpcClient.make(EventLogRemoteRpcs, { + RpcClient.make(EventLogRemoteRpcs.merge(EventLogCompactionRpcs), { disableTracing: true }) ) } +type CompactionClient = RpcClient.RpcClient, RpcClientError> + +const getCompactionClient = (client: EventLogRemoteClient["Service"]): CompactionClient | undefined => + client["EventLog.CompactionStatus"] === undefined ? undefined : client as CompactionClient + /** * Creates an `EventLogRemote` from custom write encoding and change decoding * functions. @@ -178,7 +276,7 @@ export class EventLogRemoteClient extends Context.Service< * @category constructors * @since 4.0.0 */ -export const makeWith = Effect.fnUntraced(function*({ encodeWrite, decodeChanges }: { +export const makeWith = (options: { readonly encodeWrite: (options: { readonly identity: Identity["Service"] readonly entries: ReadonlyArray @@ -190,6 +288,39 @@ export const makeWith = Effect.fnUntraced(function*({ encodeWrite, decodeChanges data: Uint8Array, knownEntries?: EventJournal["Service"]["entriesById"] ) => Effect.Effect, Schema.SchemaError | EventJournalError> +}): Effect.Effect => + makeRemote(options) + +interface RemoteSession { + readonly client: EventLogRemoteClient["Service"] + /** Authenticates, runs the request, and authenticates again after a refusal. */ + readonly request: ( + method: string, + identity: Identity["Service"], + effect: Effect.Effect + ) => Effect.Effect + /** Authenticates, then joins and decodes a framed response stream. */ + readonly framed: ( + method: string, + identity: Identity["Service"], + frames: () => Stream.Stream, + decode: (data: Uint8Array) => Effect.Effect, E2> + ) => Stream.Stream +} + +const makeRemote = Effect.fnUntraced(function*({ encodeWrite, decodeChanges, makeCompaction }: { + readonly encodeWrite: (options: { + readonly identity: Identity["Service"] + readonly entries: ReadonlyArray + readonly storeId: StoreId + }) => Effect.Effect, Schema.SchemaError> + readonly decodeChanges: ( + identity: Identity["Service"], + storeId: StoreId, + data: Uint8Array, + knownEntries?: EventJournal["Service"]["entriesById"] + ) => Effect.Effect, Schema.SchemaError | EventJournalError> + readonly makeCompaction?: ((session: RemoteSession) => EventLogRemoteCompaction | undefined) | undefined }): Effect.fn.Return { const client = yield* EventLogRemoteClient const registry = yield* Registry @@ -228,6 +359,12 @@ export const makeWith = Effect.fnUntraced(function*({ encodeWrite, decodeChanges return Cache.get(authCache, identity.publicKey) } + // The next request says hello and authenticates again. + const resetAuthentication = (identity: Identity["Service"]) => { + hello = null + return Cache.invalidate(authCache, identity.publicKey) + } + const retryForbidden = ( effect: Effect.Effect, options: { @@ -235,19 +372,47 @@ export const makeWith = Effect.fnUntraced(function*({ encodeWrite, decodeChanges } ) => Effect.retry(effect, { - while(e) { - hello = null - const error = EventLogRemoteError.is(e) && e.method === "authenticate" - ? e.cause - : e - const isForbidden = EventLogProtocolError.is(error) && error.code === "Forbidden" - return Cache.invalidate(authCache, options.identity.publicKey).pipe( - Effect.as(isForbidden) - ) - }, + while: (e) => Effect.as(resetAuthentication(options.identity), isForbidden(e)), times: 5 }) + const toRemoteError = (method: string) => (cause: unknown) => + EventLogRemoteError.is(cause) ? cause : new EventLogRemoteError({ method, cause }) + + const request = ( + method: string, + identity: Identity["Service"], + effect: Effect.Effect + ): Effect.Effect => + ensureAuthenticated(identity).pipe( + Effect.andThen(effect), + (effect) => retryForbidden(effect, { identity }), + Effect.mapError(toRemoteError(method)) + ) + + // Not retried like `request`; a refused identity authenticates again on the + // next request. + const framed = ( + method: string, + identity: Identity["Service"], + frames: () => Stream.Stream, + decode: (data: Uint8Array) => Effect.Effect, E2> + ): Stream.Stream => + Stream.unwrap(Effect.map(ensureAuthenticated(identity), () => { + const state = ChunkedMessage.initialJoinState() + return frames().pipe( + Stream.filterMap((frame) => { + const data = frame._tag === "Single" ? frame.data : ChunkedMessage.join(state, frame) + return data === undefined ? Result.failVoid : Result.succeed(data) + }), + Stream.mapEffect(decode), + Stream.flattenIterable + ) + })).pipe( + Stream.tapError((error) => isForbidden(error) ? resetAuthentication(identity) : Effect.void), + Stream.mapError(toRemoteError(method)) + ) + let chunkedIdCounter = 0 const remote = EventLogRemote.of({ @@ -325,7 +490,8 @@ export const makeWith = Effect.fnUntraced(function*({ encodeWrite, decodeChanges return outgoing }), whenAuthenticated: (effect) => - IdentityService.use((identity) => Effect.flatMap(ensureAuthenticated(identity), () => effect)) + IdentityService.use((identity) => Effect.flatMap(ensureAuthenticated(identity), () => effect)), + compaction: hello.compaction === true ? makeCompaction?.({ client, request, framed }) : undefined }) yield* registry.registerRemote(remote) @@ -333,6 +499,11 @@ export const makeWith = Effect.fnUntraced(function*({ encodeWrite, decodeChanges return remote }) +const isForbidden = (e: unknown): boolean => { + const error = EventLogRemoteError.is(e) && e.method === "authenticate" ? e.cause : e + return EventLogProtocolError.is(error) && error.code === "Forbidden" +} + /** @effect-diagnostics-next-line classSelfMismatch:off */ class IdentityService extends Context.Service()( "effect/eventlog/EventLog/Identity" satisfies Identity["key"] @@ -342,11 +513,19 @@ class IdentityService extends Context.Service()( * Creates an `EventLogRemote` that encrypts outgoing entries and decrypts * incoming changes with `EventLogEncryption`. * + * **Details** + * + * The remote has a `compaction` member when the server advertises compaction + * and the RPC client includes `EventLogCompactionRpcs`, unless built with + * `compaction: false`. Without it the client never calls the compaction RPCs. + * * @stability unstable * @category constructors * @since 4.0.0 */ -export const makeEncrypted = Effect.gen(function*(): Effect.fn.Return< +export const makeEncryptedWith = Effect.fnUntraced(function*(options: { + readonly compaction?: boolean | undefined +}): Effect.fn.Return< EventLogRemote["Service"], EventLogRemoteError, Scope.Scope | EventLogRemoteClient | EventLogEncryption | Registry @@ -385,7 +564,7 @@ export const makeEncrypted = Effect.gen(function*(): Effect.fn.Return< }) }) - return yield* makeWith({ + return yield* makeRemote({ encodeWrite: (options) => encryption.encrypt(options.identity, options.storeId, options.entries).pipe( Effect.flatMap((batches) => @@ -396,10 +575,151 @@ export const makeEncrypted = Effect.gen(function*(): Effect.fn.Return< }).encoded ) ), - decodeChanges + decodeChanges, + makeCompaction: options.compaction === false ? undefined : (session) => { + const client = getCompactionClient(session.client) + return client === undefined ? undefined : makeEncryptedCompaction({ session, client, encryption }) + } }) }) +/** + * Creates an `EventLogRemote` that encrypts outgoing entries and decrypts + * incoming changes with `EventLogEncryption`. + * + * @see {@link makeEncryptedWith} for opting out of running compaction + * + * @stability unstable + * @category constructors + * @since 4.0.0 + */ +export const makeEncrypted: Effect.Effect< + EventLogRemote["Service"], + EventLogRemoteError, + Scope.Scope | EventLogRemoteClient | EventLogEncryption | Registry +> = makeEncryptedWith({}) + +// How many times a segment is sent before a dropped connection, an +// `RpcClientError`, fails the upload. +const segmentAttempts = 3 + +const makeEncryptedCompaction = ({ client, encryption, session: { framed, request } }: { + readonly session: RemoteSession + readonly client: CompactionClient + readonly encryption: EventLogEncryption["Service"] +}): EventLogRemoteCompaction => { + const stageRequest = (stage: CompactionStage) => ({ + publicKey: stage.identity.publicKey, + storeId: stage.storeId, + stageId: stage.stageId + }) + + return { + status: ({ identity, storeId }) => + request( + "compactionStatus", + identity, + client["EventLog.CompactionStatus"]({ publicKey: identity.publicKey, storeId }) + ), + begin: ({ identity, storeId }) => + request( + "compactionBegin", + identity, + client["EventLog.CompactionBegin"]({ publicKey: identity.publicKey, storeId }) + ), + input: (stage) => + framed( + "compactionInput", + stage.identity, + () => client["EventLog.CompactionInput"](stageRequest(stage)), + CompactionInputRpc.decodeHeaders + ), + fetch: (stage, sequences) => + framed( + "compactionFetch", + stage.identity, + () => client["EventLog.CompactionFetch"]({ ...stageRequest(stage), batches: sequences }), + (data) => + Effect.flatMap( + ChangesRpc.decodeEncrypted(data), + (batches) => encryption.decrypt(stage.identity, stage.storeId, batches) + ) + ), + upload: (stage, entries) => + Effect.suspend(() => { + let segment: Array = [] + let segmentBytes = 0 + let segmentCount = 0 + + // The server forgets a segment's pieces when the connection drops, so a + // retry resends all of them. + const sendSegment = Effect.suspend(() => { + if (!Arr.isArrayNonEmpty(segment)) return Effect.void + const batches = segment + const id = segmentCount++ + segment = [] + segmentBytes = 0 + return Effect.flatMap(CompactionPartRpc.encodeSegment(batches), (data) => { + const pieces = ChunkedMessage.split(id, data) + return request( + "compactionUpload", + stage.identity, + Effect.forEach( + pieces, + (chunk) => client["EventLog.CompactionPart"]({ ...stageRequest(stage), chunk }), + { discard: true } + ).pipe( + Effect.retry({ while: (error) => error._tag === "RpcClientError", times: segmentAttempts - 1 }) + ) + ) + }) + }) + + // Whole batches go into a segment until the next one would take it + // past `ChunkedMessage.chunkSize`. + const addBatch = (batch: Arr.NonEmptyArray) => + Effect.flatMap(encryption.encrypt(stage.identity, stage.storeId, batch), (encrypted) => + Effect.forEach(encrypted, (batch) => { + const size = encodedBatchSize(batch) + const send = segment.length > 0 && segmentBytes + size > ChunkedMessage.chunkSize + ? sendSegment + : Effect.void + return Effect.andThen( + send, + Effect.sync(() => { + segment.push(batch) + segmentBytes += size + }) + ) + }, { discard: true })) + + return Effect.forEach(toBatches(entries), addBatch, { discard: true }).pipe( + Effect.andThen(sendSegment), + Effect.map(() => ({ segmentCount })), + Effect.mapError((cause) => + EventLogRemoteError.is(cause) ? cause : new EventLogRemoteError({ method: "compactionUpload", cause }) + ) + ) + }), + commit: (stage, result) => + request( + "compactionCommit", + stage.identity, + client["EventLog.CompactionCommit"]({ ...stageRequest(stage), result }) + ), + abort: (stage) => + request( + "compactionAbort", + stage.identity, + client["EventLog.CompactionAbort"](stageRequest(stage)) + ).pipe(Effect.ignore) + } +} + +// Ignores the segment framing. +const encodedBatchSize = (batch: EncryptedBatch): number => + batch.encryptedBatch.byteLength + batch.iv.byteLength + batch.entryIds.length * 16 + /** * Creates an `EventLogRemote` that sends and receives plaintext entry payloads. * @@ -425,6 +745,33 @@ export const makeUnencrypted: Effect.Effect< * Provides an encrypted `EventLogRemote` using the remote RPC client and the * default Web Crypto encryption layer. * + * **Details** + * + * `compaction: false` leaves the remote without its `compaction` member, so + * this client never calls the compaction RPCs. + * + * @stability unstable + * @category layers + * @since 4.0.0 + */ +export const layerEncryptedWith = (options: { + readonly compaction?: boolean | undefined +}): Layer.Layer< + EventLogRemote, + EventLogRemoteError, + RpcClient.Protocol | Registry +> => + Layer.effect(EventLogRemote, makeEncryptedWith(options)).pipe( + Layer.provide(EventLogRemoteClient.layer), + Layer.provide(layerSubtle) + ) + +/** + * Provides an encrypted `EventLogRemote` using the remote RPC client and the + * default Web Crypto encryption layer. + * + * @see {@link layerEncryptedWith} for opting out of running compaction + * * @stability unstable * @category layers * @since 4.0.0 @@ -433,10 +780,7 @@ export const layerEncrypted: Layer.Layer< EventLogRemote, EventLogRemoteError, RpcClient.Protocol | Registry -> = Layer.effect(EventLogRemote, makeEncrypted).pipe( - Layer.provide(EventLogRemoteClient.layer), - Layer.provide(layerSubtle) -) +> = layerEncryptedWith({}) /** * Provides an unencrypted `EventLogRemote` using the remote RPC client. diff --git a/packages/effect/src/eventlog/EventLogServer.ts b/packages/effect/src/eventlog/EventLogServer.ts index a7690e9098..093f8d734a 100644 --- a/packages/effect/src/eventlog/EventLogServer.ts +++ b/packages/effect/src/eventlog/EventLogServer.ts @@ -78,6 +78,8 @@ export const layerAuthMiddleware: Layer.Layer< * * Use the connection's `ConnectionWrites.track` in `onWrite` and * `ConnectionWrites.filter` in `changes` to suppress its own write echoes. + * `compaction` sets `HelloResponse.compaction`, advertising that the server + * also serves `EventLogCompactionRpcs`. * * @stability unstable * @category layers @@ -86,6 +88,7 @@ export const layerAuthMiddleware: Layer.Layer< export const layerRpcHandlers = (options: { readonly remoteId: RemoteId readonly firstSequence?: number | undefined + readonly compaction?: boolean | undefined readonly authorizeIdentity?: (publicKey: string) => Effect.Effect readonly getOrCreateSessionAuthBinding: ( publicKey: string, @@ -111,7 +114,7 @@ export const layerRpcHandlers = (options: { capacity: Number.MAX_SAFE_INTEGER, timeToLive: EventLogSessionAuth.SessionAuthChallengeTimeToLiveMillis }) - let chunkedIdCounter = 0 + const toFrames = makeFramer() const persistedSigningPublicKeys = yield* Cache.makeWith( (key: SessionAuthCacheKey) => @@ -139,7 +142,8 @@ export const layerRpcHandlers = (options: { return new HelloResponse({ remoteId: options.remoteId, challenge, - firstSequence: options.firstSequence + firstSequence: options.firstSequence, + compaction: options.compaction === true ? true : undefined }) }), "EventLog.Authenticate": Effect.fnUntraced(function*(request, { client }) { @@ -229,12 +233,7 @@ export const layerRpcHandlers = (options: { startSequence: request.startSequence, writes: getConnectionWrites(client) }).pipe( - Stream.mapArray(Arr.flatMap((data): NonEmptyReadonlyArray => { - if (data.byteLength <= ChunkedMessage.chunkSize) { - return [new SingleMessage({ data })] - } - return ChunkedMessage.split(chunkedIdCounter++, data) - })), + Stream.mapArray(Arr.flatMap(toFrames)), Stream.catchCause((_) => Stream.fail( new EventLogProtocolError({ @@ -424,4 +423,20 @@ class SessionAuthCacheKey extends Data.Class<{ } } +/** + * Frames one encoded message for a response stream: a `SingleMessage` when it + * fits, or the pieces of a `ChunkedMessage` with the next id otherwise. + * + * @internal + */ +export const makeFramer = (): ( + data: Uint8Array +) => NonEmptyReadonlyArray => { + let chunkedIdCounter = 0 + return (data) => + data.byteLength <= ChunkedMessage.chunkSize + ? [new SingleMessage({ data })] + : ChunkedMessage.split(chunkedIdCounter++, data) +} + const constEmptyPrivateKey = Redacted.make(new Uint8Array(32)) diff --git a/packages/effect/src/eventlog/EventLogServerEncrypted.ts b/packages/effect/src/eventlog/EventLogServerEncrypted.ts index bef13abd54..bafe5b0d16 100644 --- a/packages/effect/src/eventlog/EventLogServerEncrypted.ts +++ b/packages/effect/src/eventlog/EventLogServerEncrypted.ts @@ -12,13 +12,22 @@ * @since 4.0.0 */ import * as Arr from "../Array.ts" +import * as Cause from "../Cause.ts" +import * as Clock from "../Clock.ts" import * as Context from "../Context.ts" +import * as SecureRandom from "../crypto/SecureRandom.ts" +import * as Data from "../Data.ts" +import * as Duration from "../Duration.ts" import * as Effect from "../Effect.ts" import * as Equal from "../Equal.ts" import * as Uuid from "../internal/uuid.ts" +import * as Latch from "../Latch.ts" import * as Layer from "../Layer.ts" import * as PubSub from "../PubSub.ts" +import * as Pull from "../Pull.ts" import * as RcMap from "../RcMap.ts" +import type * as Rpc from "../rpc/Rpc.ts" +import type * as RpcGroup from "../rpc/RpcGroup.ts" import * as RpcServer from "../rpc/RpcServer.ts" import type * as Scope from "../Scope.ts" import * as Stream from "../Stream.ts" @@ -26,6 +35,13 @@ import { type EntryId, makeRemoteIdUnsafe, type RemoteId } from "./EventJournal. import type { EncryptedBatch, EncryptedRemoteBatch } from "./EventLogEncryption.ts" import { ChangesRpc, + ChunkedMessage, + type CompactionInputHeader, + CompactionInputRpc, + CompactionPartRpc, + CompactionStatus, + type EventLogAuthentication, + EventLogCompactionRpcs, EventLogProtocolError, EventLogRemoteRpcs, type StoreId, @@ -33,6 +49,15 @@ import { WriteEntries } from "./EventLogMessage.ts" import * as EventLogServer from "./EventLogServer.ts" +import { + hourMillis, + lagHour, + logCommit, + logNoOp, + logRollback, + maxSegments, + positionsPerSegment +} from "./internal/compaction.ts" /** * Provides RPC handlers for the encrypted event-log server. @@ -43,72 +68,87 @@ import * as EventLogServer from "./EventLogServer.ts" * sequences. Change streams encode stored batches, excluding this connection's * writes. * + * It also serves `EventLogCompactionRpcs`. If `Storage` provides `compaction`, + * it sets `HelloResponse.compaction` and applies the compaction policy; + * otherwise those handlers fail with `NotFound`. + * * @stability unstable * @category layers * @since 4.0.0 */ -export const layerRpcHandlers = Layer.unwrap(Effect.gen(function*() { +export const layerRpcHandlers: Layer.Layer< + | Rpc.ToHandler> + | Rpc.ToHandler> + | EventLogAuthentication, + never, + Storage +> = Layer.unwrap(Effect.gen(function*() { const storage = yield* Storage const remoteId = yield* storage.getId - return EventLogServer.layerRpcHandlers({ - remoteId, - firstSequence: storage.firstSequence, - getOrCreateSessionAuthBinding: (publicKey, signingPublicKey) => - storage.getOrCreateSessionAuthBinding(publicKey, signingPublicKey), - onWrite: Effect.fnUntraced(function*(data, authenticatedPublicKeys, writes) { - const request = yield* WriteEntries.decode(data).pipe( - Effect.mapError((_) => - new EventLogProtocolError({ - requestTag: "WriteEntries", - publicKey: undefined, - code: "InternalServerError", - message: "Decoding failure" - }) - ) - ) - if (!authenticatedPublicKeys.has(request.publicKey)) { - return yield* new EventLogProtocolError({ - requestTag: "WriteEntries", - publicKey: request.publicKey, - code: "Forbidden", - message: "Identity is not authenticated" - }) - } - if (request.batches.length === 0) return [] - const entryIds = request.batches.flatMap((batch) => batch.entryIds) - return yield* storage.write(request.publicKey, request.storeId, request.batches).pipe( - Effect.flatMap((stored) => toWriteAcks(storage, request.publicKey, request.storeId, request.batches, stored)), - (write) => writes.track({ publicKey: request.publicKey, storeId: request.storeId, entryIds }, write), - Effect.catchCause((_) => - Effect.fail( + return Layer.merge( + EventLogServer.layerRpcHandlers({ + remoteId, + firstSequence: storage.firstSequence, + compaction: storage.compaction !== undefined, + getOrCreateSessionAuthBinding: (publicKey, signingPublicKey) => + storage.getOrCreateSessionAuthBinding(publicKey, signingPublicKey), + onWrite: Effect.fnUntraced(function*(data, authenticatedPublicKeys, writes) { + const request = yield* WriteEntries.decode(data).pipe( + Effect.mapError((_) => new EventLogProtocolError({ requestTag: "WriteEntries", - publicKey: request.publicKey, + publicKey: undefined, code: "InternalServerError", - message: "Persistence failure" + message: "Decoding failure" }) ) ) - ) + if (!authenticatedPublicKeys.has(request.publicKey)) { + return yield* new EventLogProtocolError({ + requestTag: "WriteEntries", + publicKey: request.publicKey, + code: "Forbidden", + message: "Identity is not authenticated" + }) + } + if (request.batches.length === 0) return [] + const entryIds = request.batches.flatMap((batch) => batch.entryIds) + return yield* storage.write(request.publicKey, request.storeId, request.batches).pipe( + Effect.flatMap((stored) => toWriteAcks(storage, request.publicKey, request.storeId, request.batches, stored)), + (write) => writes.track({ publicKey: request.publicKey, storeId: request.storeId, entryIds }, write), + Effect.catchCause((_) => + Effect.fail( + new EventLogProtocolError({ + requestTag: "WriteEntries", + publicKey: request.publicKey, + code: "InternalServerError", + message: "Persistence failure" + }) + ) + ) + ) + }), + changes: ({ publicKey, startSequence, storeId, writes }) => + writes.filter( + { + publicKey, + storeId, + entryIds: (batch) => batch.entryIds, + sequence: (batch) => batch.sequence + batch.entryIds.length - 1 + }, + storage.changes(publicKey, storeId, startSequence) + ).pipe( + Stream.mapArrayEffect((batches) => Effect.map(ChangesRpc.encodeEncrypted(batches), Arr.of)) + ) }), - changes: ({ publicKey, startSequence, storeId, writes }) => - writes.filter( - { - publicKey, - storeId, - entryIds: (batch) => batch.entryIds, - sequence: (batch) => batch.sequence + batch.entryIds.length - 1 - }, - storage.changes(publicKey, storeId, startSequence) - ).pipe( - Stream.mapArrayEffect((batches) => Effect.map(ChangesRpc.encodeEncrypted(batches), Arr.of)) - ) - }) + layerCompactionRpcHandlers(storage) + ) })) // Acknowledges each entry occurrence in request order: at its position in the -// batch this write stored, or, for a skipped batch, where it was first stored. +// batch this write stored, or, for a skipped batch, where it was first stored +// if that is above the active compaction base. const toWriteAcks = Effect.fnUntraced(function*( storage: Storage["Service"], publicKey: string, @@ -125,8 +165,13 @@ const toWriteAcks = Effect.fnUntraced(function*( const skipped = batches.flatMap((batch, i) => storedAt[i] === undefined ? batch.entryIds : []) const firstStored = new Map() if (skipped.length > 0) { + // An id first stored at or below the active base may have been dropped, so + // acking it would move the client's cursor past kept entries. + const base = storage.compaction === undefined + ? -Infinity + : (yield* storage.compaction.status(publicKey, storeId)).base for (const ack of yield* storage.entrySequences(publicKey, storeId, skipped)) { - firstStored.set(Uuid.stringify(ack.entryId), ack.sequence) + if (ack.sequence > base) firstStored.set(Uuid.stringify(ack.entryId), ack.sequence) } } const acks: Array = [] @@ -139,6 +184,260 @@ const toWriteAcks = Effect.fnUntraced(function*( return acks }) +const layerCompactionRpcHandlers = (storage: Storage["Service"]) => + EventLogCompactionRpcs.toLayer(Effect.sync(() => { + const compaction = storage.compaction + const toFrames = EventLogServer.makeFramer() + + type Request = { readonly publicKey: string; readonly storeId: StoreId } + const protocolError = ( + requestTag: string, + request: Request, + code: EventLogProtocolError["code"], + message: string + ) => + new EventLogProtocolError({ requestTag, publicKey: request.publicKey, storeId: request.storeId, code, message }) + const fromCompactionError = + (requestTag: string, request: Request) => (error: CompactionNotFound | CompactionInvalidRequest) => + error._tag === "CompactionNotFound" + ? protocolError(requestTag, request, "NotFound", "Compaction stage not found") + : protocolError(requestTag, request, "InvalidRequest", error.message) + + const withCompaction = ( + requestTag: string, + request: Request, + client: Rpc.ServerClient, + f: (compaction: StorageCompaction) => Effect.Effect + ): Effect.Effect => { + if (!Context.getOrUndefined(client.annotations, EventLogServer.AuthenticatedIdentities)?.has(request.publicKey)) { + return Effect.fail(protocolError(requestTag, request, "Forbidden", "Identity is not authenticated")) + } + if (compaction === undefined) { + return Effect.fail(protocolError(requestTag, request, "NotFound", "Compaction is not supported")) + } + return Effect.mapError(f(compaction), fromCompactionError(requestTag, request)) + } + const withCompactionStream = ( + requestTag: string, + request: Request, + client: Rpc.ServerClient, + f: (compaction: StorageCompaction) => Stream.Stream + ): Stream.Stream => + Stream.unwrap( + withCompaction( + requestTag, + request, + client, + (compaction) => Effect.succeed(Stream.mapError(f(compaction), fromCompactionError(requestTag, request))) + ) + ) + + const getStatus = Effect.fnUntraced(function*(compaction: StorageCompaction, publicKey: string, storeId: StoreId) { + const status = yield* compaction.status(publicKey, storeId) + return { status, wanted: isCompactionWanted(status, compaction.config.thresholdFloor) } + }) + + return EventLogCompactionRpcs.of({ + "EventLog.CompactionStatus": (request, { client }) => + withCompaction("CompactionStatus", request, client, (compaction) => + Effect.map(getStatus(compaction, request.publicKey, request.storeId), ({ status, wanted }) => + new CompactionStatus({ wanted, head: status.head }))), + "EventLog.CompactionBegin": (request, { client }) => + withCompaction("CompactionBegin", request, client, (compaction) => + Effect.gen(function*() { + const { status, wanted } = yield* getStatus(compaction, request.publicKey, request.storeId) + if (!wanted) { + return { _tag: "NotWanted" } as const + } + const result = yield* compaction.begin(request.publicKey, request.storeId, { through: status.lagHead }) + return result._tag === "Busy" + ? { _tag: "Busy" } as const + : { _tag: "Started", stageId: result.stageId } as const + })), + "EventLog.CompactionInput": (request, { client }) => + withCompactionStream("CompactionInput", request, client, (compaction) => + compaction.inputHeaders(request.publicKey, request.storeId, request.stageId).pipe( + Stream.mapArrayEffect((headers) => + Effect.map( + Effect.orDie( + CompactionInputRpc.encodeHeaders(headers as Arr.NonEmptyReadonlyArray) + ), + toFrames + ) + ) + )), + "EventLog.CompactionFetch": (request, { client }) => + withCompactionStream("CompactionFetch", request, client, (compaction) => + compaction.fetch(request.publicKey, request.storeId, request.stageId, request.batches).pipe( + Stream.mapArrayEffect((batches) => + Effect.map(Effect.orDie(ChangesRpc.encodeEncrypted(batches)), toFrames) + ) + )), + "EventLog.CompactionPart": (request, { client }) => + withCompaction("CompactionPart", request, client, (compaction) => + Effect.gen(function*() { + const { publicKey, stageId, storeId } = request + const data = ChunkedMessage.join(getPendingSegments(client, request), request.chunk) + if (data === undefined) { + return + } + const batches = yield* CompactionPartRpc.decodeSegment(data).pipe( + Effect.catch(() => + Effect.andThen( + compaction.abort(publicKey, storeId, stageId), + Effect.fail(new CompactionInvalidRequest({ stageId, message: "Invalid segment" })) + ) + ) + ) + yield* compaction.stagePart(publicKey, storeId, stageId, request.chunk.id, batches) + })), + "EventLog.CompactionAbort": (request, { client }) => + withCompaction("CompactionAbort", request, client, (compaction) => { + releasePendingSegments(client, request) + return compaction.abort(request.publicKey, request.storeId, request.stageId) + }), + "EventLog.CompactionCommit": (request, { client }) => + withCompaction("CompactionCommit", request, client, (compaction) => { + const { publicKey, stageId, storeId } = request + releasePendingSegments(client, request) + if (request.result._tag === "NoOp") { + return Effect.as(compaction.recordNoOp(publicKey, storeId, stageId), "Committed" as const) + } + return checkSnapshot(compaction, publicKey, storeId, stageId, request.result.segmentCount).pipe( + Effect.tapError((error) => + error._tag === "CompactionInvalidRequest" ? compaction.abort(publicKey, storeId, stageId) : Effect.void + ), + Effect.flatMap((virtualSequences) => + compaction.commit(publicKey, storeId, stageId, virtualSequences) + ) + ) + }) + }) + })) + +// The input past the lag must reach the threshold. After `k` consecutive +// no-ops, the lag head must also have moved `threshold * 2^(k-1)` past the +// latest one. +const isCompactionWanted = (status: CompactionStoreStatus, thresholdFloor: number): boolean => { + const threshold = Math.max(status.activeKeptCount, thresholdFloor) + const pending = status.lagHead - status.base + if (pending <= 0 || pending < threshold) return false + if (status.noOp === undefined) return true + return status.lagHead - status.noOp.at >= threshold * 2 ** (status.noOp.count - 1) +} + +// Checks the staged batches against the stage's input in one pass over both +// and returns each batch's virtual start sequence. The kept ids, read in +// segments 0 to segmentCount - 1, must be a non-empty, repeat-free +// subsequence of the input's ids. +const checkSnapshot = Effect.fnUntraced(function*( + compaction: StorageCompaction, + publicKey: string, + storeId: StoreId, + stageId: string, + segmentCount: number +) { + const invalid = (message: string) => Effect.fail(new CompactionInvalidRequest({ stageId, message })) + const pullInput = yield* Stream.toPull(compaction.inputHeaders(publicKey, storeId, stageId)) + let headers: ReadonlyArray = [] + let headerIndex = 0 + let entryIndex = 0 + let lastInputSequence = -1 + const nextInput = Effect.gen(function*() { + while (true) { + const header = headers[headerIndex] + if (header === undefined) { + const chunk = yield* Pull.catchDone(pullInput, () => Effect.succeed(undefined)) + if (chunk === undefined) return undefined + headers = chunk + headerIndex = 0 + continue + } + if (entryIndex === header.entryIds.length) { + headerIndex++ + entryIndex = 0 + continue + } + const sequence = header.sequence + entryIndex + const id = Uuid.stringify(header.entryIds[entryIndex++]) + lastInputSequence = sequence + return { id, sequence } + } + }) + + // The input sequence of each batch's last kept entry, and its size. + const ends: Array = [] + const sizes: Array = [] + let segment = -1 + yield* Stream.runForEach(compaction.stagedHeaders(publicKey, storeId, stageId), (header) => + Effect.gen(function*() { + const headerSegment = Math.floor(header.position / positionsPerSegment) + if (headerSegment !== segment) { + if (headerSegment !== segment + 1 || headerSegment >= segmentCount) { + return yield* invalid("Unexpected segment") + } + segment = headerSegment + } + let last = -1 + for (const entryId of header.entryIds) { + const id = Uuid.stringify(entryId) + let input = yield* nextInput + while (input !== undefined && input.id !== id) input = yield* nextInput + if (input === undefined) return yield* invalid("Kept entry is not in the input, or is out of order") + last = input.sequence + } + ends.push(last) + sizes.push(header.entryIds.length) + })) + if (ends.length === 0) return yield* invalid("Snapshot is empty") + if (segment !== segmentCount - 1) return yield* invalid("Missing segment") + while ((yield* nextInput) !== undefined) { + // Drain the input to learn its last sequence. + } + + // Each batch ends at its last kept entry's input sequence, and the final one + // at the end of the input, so no batch starts below its entries' input. + return ends.map((end, i) => (i === ends.length - 1 ? lastInputSequence : end) - sizes[i] + 1) +}, Effect.scoped) + +// One connection's unjoined segment pieces, keyed by identity, store and +// stage. The JSON tuple key keeps the components unambiguous. +class PendingSegments extends Context.Service< + PendingSegments, + Map> +>()("effect/eventlog/EventLogServerEncrypted/PendingSegments") {} + +const pendingSegmentsKey = ( + request: { readonly publicKey: string; readonly storeId: StoreId; readonly stageId: string } +) => JSON.stringify([request.publicKey, request.storeId, request.stageId]) + +const getPendingSegments = (client: Rpc.ServerClient, request: { + readonly publicKey: string + readonly storeId: StoreId + readonly stageId: string +}) => { + let stages = Context.getOrUndefined(client.annotations, PendingSegments) + if (stages === undefined) { + stages = new Map() + client.annotate(PendingSegments, stages) + } + const key = pendingSegmentsKey(request) + let pending = stages.get(key) + if (pending === undefined) { + pending = ChunkedMessage.initialJoinState() + stages.set(key, pending) + } + return pending +} + +const releasePendingSegments = (client: Rpc.ServerClient, request: { + readonly publicKey: string + readonly storeId: StoreId + readonly stageId: string +}) => { + Context.getOrUndefined(client.annotations, PendingSegments)?.delete(pendingSegmentsKey(request)) +} + /** * Provides an encrypted event-log RPC server using `EventLogRemoteRpcs` and the * encrypted server RPC handlers. @@ -153,7 +452,8 @@ const toWriteAcks = Effect.fnUntraced(function*( * This layer installs `EventLogRemoteRpcs` on the provided RPC server protocol * and wires those RPCs to `layerRpcHandlers`. Encrypted batches, session * authentication bindings, remote ids, and change streams are delegated to - * `Storage`. + * `Storage`. It also installs `EventLogCompactionRpcs`, which clients call + * only when `Storage` provides `compaction`. * * @see {@link layerRpcHandlers} for the encrypted handler layer without installing an RPC server protocol * @see {@link Storage} for the storage service required by this layer @@ -163,9 +463,9 @@ const toWriteAcks = Effect.fnUntraced(function*( * @category layers * @since 4.0.0 */ -export const layer: Layer.Layer = RpcServer.layer(EventLogRemoteRpcs).pipe( - Layer.provide(layerRpcHandlers) -) +export const layer: Layer.Layer = RpcServer.layer( + EventLogRemoteRpcs.merge(EventLogCompactionRpcs) +).pipe(Layer.provide(layerRpcHandlers)) /** * Defines the backing store service used by the encrypted event-log server. @@ -189,6 +489,10 @@ export const layer: Layer.Layer = Rp * whose last sequence is at or after `startSequence`, followed by newly stored * batches. * + * Storages that support remote compaction provide `compaction`. With an active + * snapshot, `changes` serves snapshot batches by their virtual sequences for a + * start sequence at or below the snapshot base, then the originals above it. + * * @stability unstable * @category services * @since 4.0.0 @@ -218,33 +522,372 @@ export class Storage extends Context.Service Stream.Stream + readonly compaction?: StorageCompaction | undefined }>()("effect/eventlog/EventLogServer/Storage") {} +/** + * Storage primitives for encrypted remote compaction. + * + * **Details** + * + * The server owns the policy: trigger threshold, lag, no-op backoff, commit + * checks and virtual sequences. Each primitive is atomic per store. + * + * A store always has one active activation. Before the first commit it is the + * originals, with base `firstSequence - 1`. `begin` opens a stage pinned to the + * active activation and to `through`. The stage claim expires `stageTtl` after + * begin or the latest stored Part, and `begin` takes over an expired claim. + * Stage-scoped primitives fail with `CompactionNotFound` once the stage has + * expired, been aborted or committed, or when it belongs to another store, so + * a commit is answered only once. + * + * `stagePart` stores one segment of encrypted snapshot batches, or answers + * `AlreadyStored` for a segment it already has. It doesn't check entry ids: + * the server's commit checks reject repeats, and readers dedupe by id. + * `commit` takes every staged batch's virtual + * start sequence in position order, and activates the staged set only if the + * pinned activation is still active. + * + * `rollback` reactivates the previous generation under a new activation id + * and re-appends, at the head, the input of the stage that built the withdrawn + * one: the previous batch set, then the originals between the two bases. + * Clients that read the withdrawn snapshot get what it dropped through + * `changes`. A sweep on `Clock` prunes a generation, and the originals it + * replaced, `grace` after it was superseded or withdrawn. + * + * @stability unstable + * @category models + * @since 4.0.0 + */ +export interface StorageCompaction { + readonly config: CompactionConfig + readonly status: (publicKey: string, storeId: StoreId) => Effect.Effect + readonly begin: ( + publicKey: string, + storeId: StoreId, + options: { readonly through: number } + ) => Effect.Effect + /** + * Batch headers in input order: the pinned batch set, then the originals in + * `(base, through]`. + */ + readonly inputHeaders: ( + publicKey: string, + storeId: StoreId, + stageId: string + ) => Stream.Stream + /** + * Input batches by their input sequence: snapshot batches at or below the + * pinned base, originals above it. + */ + readonly fetch: ( + publicKey: string, + storeId: StoreId, + stageId: string, + sequences: ReadonlyArray + ) => Stream.Stream + readonly stagePart: ( + publicKey: string, + storeId: StoreId, + stageId: string, + segment: number, + batches: Arr.NonEmptyReadonlyArray + ) => Effect.Effect<"Stored" | "AlreadyStored", CompactionInvalidRequest | CompactionNotFound> + /** + * Staged batch headers in position order (segment, then batch index). + */ + readonly stagedHeaders: ( + publicKey: string, + storeId: StoreId, + stageId: string + ) => Stream.Stream<{ readonly position: number; readonly entryIds: ReadonlyArray }, CompactionNotFound> + /** + * Logs the outcome with this commit's own activation id, not the one active + * when the log runs. + */ + readonly commit: ( + publicKey: string, + storeId: StoreId, + stageId: string, + virtualSequences: ReadonlyArray + ) => Effect.Effect<"Committed" | "Superseded", CompactionNotFound> + /** + * Records a no-op for the stage and logs it. + */ + readonly recordNoOp: (publicKey: string, storeId: StoreId, stageId: string) => Effect.Effect + /** + * Releases an open stage and discards what it staged. Aborting a stage that + * has left `open` is a no-op. + */ + readonly abort: (publicKey: string, storeId: StoreId, stageId: string) => Effect.Effect + readonly rollback: ( + publicKey: string, + storeId: StoreId, + expectedActivationId: string + ) => Effect.Effect + /** + * Every activation of the store, oldest first. + */ + readonly history: (publicKey: string, storeId: StoreId) => Effect.Effect> +} + +/** + * The compaction state of one store. + * + * **Details** + * + * `base` is `firstSequence - 1` while the originals are active. `lagHead` is + * the highest last sequence in a storage-time hour that ended before + * `now - lag`. + * + * @stability unstable + * @category models + * @since 4.0.0 + */ +export interface CompactionStoreStatus { + readonly head: number + readonly base: number + readonly activeKeptCount: number + readonly lagHead: number + readonly noOp: { readonly at: number; readonly count: number } | undefined +} + +/** + * The result of opening a compaction stage. + * + * @stability unstable + * @category models + * @since 4.0.0 + */ +export type CompactionBeginResult = { + readonly _tag: "Started" + readonly stageId: string +} | { + readonly _tag: "Busy" + readonly expiresAt: number +} + +/** + * The header of one compaction input batch. + * + * @stability unstable + * @category models + * @since 4.0.0 + */ +export interface CompactionBatchHeader { + readonly sequence: number + readonly entryIds: ReadonlyArray +} + +/** + * One entry of a store's activation log. + * + * **Details** + * + * `keptCount` is `undefined` for the originals. `restorable` is `false` once + * the generation's prune has started. + * + * @stability unstable + * @category models + * @since 4.0.0 + */ +export interface CompactionActivation { + readonly activationId: string + readonly base: number + readonly keptCount: number | undefined + readonly active: boolean + readonly supersededAt: number | undefined + readonly restorable: boolean +} + +/** + * Error raised when a compaction stage has expired, was aborted or committed, + * or is unknown to the store. + * + * @stability unstable + * @category errors + * @since 4.0.0 + */ +export class CompactionNotFound extends Data.TaggedError("CompactionNotFound")<{ + readonly stageId: string +}> {} + +/** + * Error raised when a compaction Part fails validation. + * + * @stability unstable + * @category errors + * @since 4.0.0 + */ +export class CompactionInvalidRequest extends Data.TaggedError("CompactionInvalidRequest")<{ + readonly stageId: string + readonly message: string +}> {} + +/** + * Error raised when a rollback is refused. + * + * **Details** + * + * `NotActive` means the expected activation is not the active one, + * `NoPrevious` that there is no earlier generation, and `PruneStarted` that + * the previous generation has started to be pruned. + * + * @stability unstable + * @category errors + * @since 4.0.0 + */ +export class CompactionRollbackError extends Data.TaggedError("CompactionRollbackError")<{ + readonly reason: "NotActive" | "NoPrevious" | "PruneStarted" +}> {} + +/** + * Tuning for encrypted remote compaction. + * + * **Details** + * + * `grace` is how long a superseded or withdrawn generation is kept before it + * is pruned (default 30 days). `lag` is how old data must be, by storage time, + * before it can be compacted (default 24 hours). `stageTtl` is how long a stage + * claim lasts after its latest Part (default 10 minutes). `thresholdFloor` is + * the smallest number of new entries that makes compaction wanted (default + * 1,000). `sweepInterval` is how often pruning runs (default 1 hour). + * + * @stability unstable + * @category models + * @since 4.0.0 + */ +export interface CompactionOptions { + readonly grace?: Duration.Input | undefined + readonly lag?: Duration.Input | undefined + readonly stageTtl?: Duration.Input | undefined + readonly thresholdFloor?: number | undefined + readonly sweepInterval?: Duration.Input | undefined +} + +/** + * Resolved compaction tuning, shared by a storage and the server using it. + * + * @stability unstable + * @category models + * @since 4.0.0 + */ +export interface CompactionConfig { + readonly grace: Duration.Duration + readonly lag: Duration.Duration + readonly stageTtl: Duration.Duration + readonly thresholdFloor: number + readonly sweepInterval: Duration.Duration +} + +/** + * Resolves compaction options against their defaults. + * + * **Details** + * + * Dies with an `IllegalArgumentError` unless `grace` is longer than both `lag` + * and `stageTtl`, `stageTtl` and `sweepInterval` are positive, and + * `thresholdFloor` is a non-negative integer. + * + * @stability unstable + * @category constructors + * @since 4.0.0 + */ +export const makeCompactionConfig = (options?: CompactionOptions | undefined): Effect.Effect => + Effect.suspend(() => { + const config: CompactionConfig = { + grace: Duration.fromInputUnsafe(options?.grace ?? "30 days"), + lag: Duration.fromInputUnsafe(options?.lag ?? "24 hours"), + stageTtl: Duration.fromInputUnsafe(options?.stageTtl ?? "10 minutes"), + thresholdFloor: options?.thresholdFloor ?? 1000, + sweepInterval: Duration.fromInputUnsafe(options?.sweepInterval ?? "1 hour") + } + if ( + !Duration.isGreaterThan(config.grace, config.lag) || + !Duration.isGreaterThan(config.grace, config.stageTtl) + ) { + return Effect.die(new Cause.IllegalArgumentError("Compaction grace must be longer than lag and stageTtl")) + } + if (!Duration.isGreaterThan(config.stageTtl, Duration.zero)) { + return Effect.die(new Cause.IllegalArgumentError("Compaction stageTtl must be positive")) + } + if (!Duration.isGreaterThan(config.sweepInterval, Duration.zero)) { + return Effect.die(new Cause.IllegalArgumentError("Compaction sweepInterval must be positive")) + } + if (!Number.isSafeInteger(config.thresholdFloor) || config.thresholdFloor < 0) { + return Effect.die(new Cause.IllegalArgumentError("Compaction thresholdFloor must be a non-negative integer")) + } + return Effect.succeed(config) + }) + +/** + * Creates an in-memory encrypted server `Storage` with default compaction + * tuning. + * + * **Details** + * + * Data, session authentication bindings, and streams are process-local and are + * released with the surrounding scope. + * + * @see {@link makeStorageMemoryWith} to configure compaction + * + * @stability unstable + * @category constructors + * @since 4.0.0 + */ +export const makeStorageMemory: Effect.Effect = Effect.suspend(() => + makeStorageMemoryWith({}) +) + /** * Creates an in-memory encrypted server `Storage`. * * **Details** * * Data, session authentication bindings, and streams are process-local and are - * released with the surrounding scope. + * released with the surrounding scope. The storage always provides + * `compaction`. Its sweep runs on `Clock` only while some store has a + * generation to prune or a stage to expire. + * + * Dies when the compaction options are invalid (see {@link makeCompactionConfig}). * * @stability unstable * @category constructors * @since 4.0.0 */ -export const makeStorageMemory: Effect.Effect = Effect.gen(function*() { - const journals = new Map - readonly batches: Array - nextSequence: number - }>() +export const makeStorageMemoryWith = Effect.fnUntraced(function*(options: { + readonly compaction?: CompactionOptions | undefined +}): Effect.fn.Return { + const config = yield* makeCompactionConfig(options.compaction) + const graceMillis = Duration.toMillis(config.grace) + const lagMillis = Duration.toMillis(config.lag) + const stageTtlMillis = Duration.toMillis(config.stageTtl) + const journals = new Map() const sessionAuthBindings = new Map>() const remoteId = makeRemoteIdUnsafe() const ensureJournal = (scopeKey: string) => { let journal = journals.get(scopeKey) if (journal) return journal - journal = { knownIds: new Map(), batches: [], nextSequence: 0 } + const originals: MemoryActivation = { + id: SecureRandom.uuidV4Unsafe(), + set: undefined, + base: -1, + keptCount: undefined, + previous: undefined, + supersededAt: undefined, + pruneStartedAt: undefined + } + journal = { + knownIds: new Map(), + batches: [], + nextSequence: 0, + buckets: new Map(), + activations: [originals], + active: originals, + noOp: undefined, + openStage: undefined, + nextSweepAt: undefined + } journals.set(scopeKey, journal) return journal } @@ -257,6 +900,346 @@ export const makeStorageMemory: Effect.Effect { + journal.nextSweepAt = journal.nextSweepAt === undefined ? at : Math.min(journal.nextSweepAt, at) + sweepPending.openUnsafe() + } + const closeStage = (journal: MemoryJournal, stage: MemoryStage) => { + if (journal.openStage === stage) journal.openStage = undefined + } + const sweep = (now: number) => { + let pending = false + for (const journal of journals.values()) { + if (journal.openStage !== undefined && journal.openStage.expiresAt <= now) closeStage(journal, journal.openStage) + if (journal.nextSweepAt !== undefined && journal.nextSweepAt <= now) prune(journal, now) + pending ||= journal.openStage !== undefined || journal.nextSweepAt !== undefined + } + if (!pending) sweepPending.closeUnsafe() + } + // Keeps what the active generation and every generation still within grace + // need, which is their batch sets and the originals above their bases. + const prune = (journal: MemoryJournal, now: number) => { + const kept = journal.activations.filter((activation) => + activation === journal.active || + (activation.pruneStartedAt === undefined && activation.supersededAt! + graceMillis > now) + ) + const keptSets = new Set(kept.map((activation) => activation.set)) + for (const activation of journal.activations) { + if (kept.includes(activation) || activation.pruneStartedAt !== undefined) continue + activation.pruneStartedAt = now + if (activation.set !== undefined && !keptSets.has(activation.set)) activation.set.batches = [] + } + const keptBase = Math.min(...kept.map((activation) => activation.base)) + const first = journal.batches.findIndex((batch) => batch.sequence + batch.entryIds.length - 1 > keptBase) + journal.batches.splice(0, first === -1 ? journal.batches.length : first) + journal.nextSweepAt = undefined + for (const activation of journal.activations) { + if (activation !== journal.active && activation.pruneStartedAt === undefined) { + schedulePrune(journal, activation.supersededAt! + graceMillis) + } + } + } + yield* Effect.forkScoped( + Effect.forever( + sweepPending.await.pipe( + Effect.andThen(Effect.sleep(config.sweepInterval)), + Effect.andThen(Clock.currentTimeMillis), + Effect.flatMap((now) => Effect.sync(() => sweep(now))) + ) + ) + ) + + // The highest last sequence stored in an hour that ended before now - lag. + const lagHead = (journal: MemoryJournal, now: number) => { + const pastLag = lagHour(now, lagMillis) + let head = -1 + for (const [hour, lastSequence] of journal.buckets) { + if (hour <= pastLag) head = Math.max(head, lastSequence) + } + return head + } + const recordBucket = (journal: MemoryJournal, now: number, lastSequence: number) => { + const hour = Math.floor(now / hourMillis) + const existing = journal.buckets.get(hour) + if (existing !== undefined) { + journal.buckets.set(hour, Math.max(existing, lastSequence)) + return + } + journal.buckets.set(hour, lastSequence) + // Only the newest bucket past the lag matters for the lag head. + const pastLag = Array.from(journal.buckets.keys()).filter((bucket) => bucket <= lagHour(now, lagMillis)) + const newest = Math.max(...pastLag) + for (const bucket of pastLag) { + if (bucket < newest) journal.buckets.delete(bucket) + } + } + // The input of a stage: its pinned batch set, then originals in (base, through]. + const inputBatches = (journal: MemoryJournal, stage: MemoryStage): ReadonlyArray => [ + ...(stage.pinned.set?.batches ?? []), + ...journal.batches.filter((batch) => + batch.sequence > stage.pinned.base && batch.sequence + batch.entryIds.length - 1 <= stage.through + ) + ] + // A stage that Part, NoOp and Commit can act on. + const findOpenStage = (publicKey: string, storeId: StoreId, stageId: string, now: number) => { + const journal = journals.get(makeEncryptedScopeKey({ publicKey, storeId })) + const stage = journal?.openStage + if (journal === undefined || stage === undefined || stage.id !== stageId) return undefined + if (stage.expiresAt <= now) { + closeStage(journal, stage) + return undefined + } + return { stage, journal } + } + // Call within the same execution-time block that captures the input rows. + const findInputStage = ( + publicKey: string, + storeId: StoreId, + stageId: string, + now: number + ) => { + const found = findOpenStage(publicKey, storeId, stageId, now) + return found?.stage.pinned.pruneStartedAt === undefined ? found : undefined + } + + const compaction: StorageCompaction = { + config, + status: (publicKey, storeId) => + Effect.map(Clock.currentTimeMillis, (now) => { + const journal = ensureJournal(makeEncryptedScopeKey({ publicKey, storeId })) + return { + head: journal.nextSequence - 1, + base: journal.active.base, + activeKeptCount: journal.active.keptCount ?? 0, + lagHead: lagHead(journal, now), + noOp: journal.noOp + } + }), + begin: (publicKey, storeId, { through }) => + Effect.map(Clock.currentTimeMillis, (now): CompactionBeginResult => { + const scopeKey = makeEncryptedScopeKey({ publicKey, storeId }) + const journal = ensureJournal(scopeKey) + const open = journal.openStage + if (open !== undefined) { + if (open.expiresAt > now) return { _tag: "Busy", expiresAt: open.expiresAt } + closeStage(journal, open) + } + const stage: MemoryStage = { + id: SecureRandom.uuidV4Unsafe(), + pinned: journal.active, + through, + expiresAt: now + stageTtlMillis, + staged: new Map() + } + journal.openStage = stage + sweepPending.openUnsafe() + return { _tag: "Started", stageId: stage.id } + }), + inputHeaders: (publicKey, storeId, stageId) => + Clock.currentTimeMillis.pipe( + Effect.flatMap((now) => { + const found = findInputStage(publicKey, storeId, stageId, now) + if (found === undefined) return Effect.fail(new CompactionNotFound({ stageId })) + const { journal, stage } = found + return Effect.succeed(Stream.fromArray( + inputBatches(journal, stage).map((batch): CompactionBatchHeader => ({ + sequence: batch.sequence, + entryIds: batch.entryIds + })) + )) + }), + Stream.unwrap + ), + fetch: (publicKey, storeId, stageId, sequences) => + Clock.currentTimeMillis.pipe( + Effect.flatMap((now) => { + const found = findInputStage(publicKey, storeId, stageId, now) + if (found === undefined) return Effect.fail(new CompactionNotFound({ stageId })) + const { journal, stage } = found + const fetched: Array = [] + for (const sequence of sequences) { + const batch = sequence <= stage.pinned.base + ? findBatch(stage.pinned.set?.batches ?? [], sequence) + : sequence <= stage.through + ? findBatch(journal.batches, sequence) + : undefined + if (batch !== undefined) fetched.push(batch) + } + return Effect.succeed(Stream.fromArray(fetched)) + }), + Stream.unwrap + ), + stagePart: (publicKey, storeId, stageId, segment, batches) => + Effect.flatMap(Clock.currentTimeMillis, (now): ReturnType => { + const found = findOpenStage(publicKey, storeId, stageId, now) + if (found === undefined) return Effect.fail(new CompactionNotFound({ stageId })) + const { journal, stage } = found + const reject = (message: string) => { + closeStage(journal, stage) + return Effect.fail(new CompactionInvalidRequest({ stageId, message })) + } + if (!Number.isSafeInteger(segment) || segment < 0 || segment >= maxSegments) { + return reject("Invalid segment index") + } + if (batches.length > positionsPerSegment) return reject("Too many batches in a segment") + // Positions are the staged rows' key, so a retried segment inserts nothing. + let inserted = 0 + batches.forEach((batch, i) => { + const position = segment * positionsPerSegment + i + if (stage.staged.has(position)) return + stage.staged.set(position, batch) + inserted++ + }) + if (inserted === 0) return Effect.succeed("AlreadyStored" as const) + stage.expiresAt = now + stageTtlMillis + return Effect.succeed("Stored" as const) + }), + stagedHeaders: (publicKey, storeId, stageId) => + Effect.flatMap(Clock.currentTimeMillis, (now) => { + const found = findOpenStage(publicKey, storeId, stageId, now) + if (found === undefined) { + return Effect.fail(new CompactionNotFound({ stageId })) + } + return Effect.succeed(Stream.fromArray( + stagedBatches(found.stage).map(({ batch, position }) => ({ + position, + entryIds: batch.entryIds + })) + )) + }).pipe(Stream.unwrap), + commit: (publicKey, storeId, stageId, virtualSequences) => + Effect.flatMap(Clock.currentTimeMillis, (now) => { + const found = findOpenStage(publicKey, storeId, stageId, now) + if (found === undefined) return Effect.fail(new CompactionNotFound({ stageId })) + const { journal, stage } = found + if (stage.pinned !== journal.active) { + const keptCount = stagedBatches(stage).reduce((count, { batch }) => count + batch.entryIds.length, 0) + closeStage(journal, stage) + return Effect.as( + logCommit({ + publicKey, + storeId, + result: "Superseded", + through: stage.through, + keptCount, + activationId: undefined + }), + "Superseded" as const + ) + } + const staged = stagedBatches(stage) + if (staged.length !== virtualSequences.length) { + return Effect.die(new Cause.IllegalArgumentError("Expected one virtual sequence per staged batch")) + } + const keptCount = staged.reduce((count, { batch }) => count + batch.entryIds.length, 0) + const activation: MemoryActivation = { + id: SecureRandom.uuidV4Unsafe(), + set: { + batches: staged.map(({ batch }, i): EncryptedRemoteBatch => ({ ...batch, sequence: virtualSequences[i] })) + }, + base: stage.through, + keptCount, + previous: journal.active, + supersededAt: undefined, + pruneStartedAt: undefined + } + journal.active.supersededAt = now + journal.activations.push(activation) + journal.active = activation + journal.noOp = undefined + schedulePrune(journal, now + graceMillis) + closeStage(journal, stage) + // Log this commit's activation id. A concurrent rollback could change + // the active one before the logger runs. + return Effect.as( + logCommit({ + publicKey, + storeId, + result: "Committed", + through: stage.through, + keptCount, + activationId: activation.id + }), + "Committed" as const + ) + }), + recordNoOp: (publicKey, storeId, stageId) => + Effect.flatMap(Clock.currentTimeMillis, (now) => { + const found = findOpenStage(publicKey, storeId, stageId, now) + if (found === undefined) return Effect.fail(new CompactionNotFound({ stageId })) + const { journal, stage } = found + // A rollback since begin cleared the no-op state, so a stale run leaves it. + if (stage.pinned === journal.active) { + journal.noOp = { at: stage.through, count: (journal.noOp?.count ?? 0) + 1 } + } + closeStage(journal, stage) + return logNoOp({ publicKey, storeId, stageId, through: stage.through }) + }), + abort: (publicKey, storeId, stageId) => + Effect.sync(() => { + const journal = journals.get(makeEncryptedScopeKey({ publicKey, storeId })) + if (journal?.openStage?.id === stageId) closeStage(journal, journal.openStage) + }), + rollback: Effect.fnUntraced(function*(publicKey, storeId, expectedActivationId) { + const scopeKey = makeEncryptedScopeKey({ publicKey, storeId }) + const pubsub = yield* RcMap.get(pubsubs, scopeKey) + const now = yield* Clock.currentTimeMillis + return yield* Effect.suspend(() => { + const journal = ensureJournal(scopeKey) + const withdrawn = journal.active + if (withdrawn.id !== expectedActivationId) { + return Effect.fail(new CompactionRollbackError({ reason: "NotActive" })) + } + const target = withdrawn.previous + if (target === undefined) return Effect.fail(new CompactionRollbackError({ reason: "NoPrevious" })) + if (target.pruneStartedAt !== undefined) { + return Effect.fail(new CompactionRollbackError({ reason: "PruneStarted" })) + } + const activation: MemoryActivation = { + ...target, + id: SecureRandom.uuidV4Unsafe(), + supersededAt: undefined, + pruneStartedAt: undefined + } + // The input of the stage that built the withdrawn generation. + const input = [ + ...(target.set?.batches ?? []), + ...journal.batches.filter((batch) => + batch.sequence > target.base && batch.sequence + batch.entryIds.length - 1 <= withdrawn.base + ) + ] + withdrawn.supersededAt = now + journal.activations.push(activation) + journal.active = activation + journal.noOp = undefined + schedulePrune(journal, now + graceMillis) + for (const { encryptedBatch, entryIds, iv } of input) { + const batch: EncryptedRemoteBatch = { sequence: journal.nextSequence, entryIds, iv, encryptedBatch } + journal.nextSequence += entryIds.length + journal.batches.push(batch) + PubSub.publishUnsafe(pubsub, batch) + } + if (input.length > 0) recordBucket(journal, now, journal.nextSequence - 1) + return Effect.as(logRollback({ publicKey, storeId, activation, withdrawn }), activation.id) + }) + }, Effect.scoped), + history: (publicKey, storeId) => + Effect.sync(() => { + const journal = ensureJournal(makeEncryptedScopeKey({ publicKey, storeId })) + return journal.activations.map((activation): CompactionActivation => ({ + activationId: activation.id, + base: activation.base, + keptCount: activation.keptCount, + active: activation === journal.active, + supersededAt: activation === journal.active ? undefined : activation.supersededAt, + restorable: activation.pruneStartedAt === undefined + })) + }) + } + return Storage.of({ getId: Effect.succeed(remoteId), getOrCreateSessionAuthBinding: (publicKey, signingPublicKey) => @@ -269,6 +1252,7 @@ export const makeStorageMemory: Effect.Effect = [] for (const batch of batches) { @@ -283,6 +1267,7 @@ export const makeStorageMemory: Effect.Effect 0) recordBucket(journal, now, journal.nextSequence - 1) return stored }, Effect.scoped), entrySequences: (publicKey, storeId, entryIds) => @@ -299,15 +1284,42 @@ export const makeStorageMemory: Effect.Effect batch.sequence > base) + return Stream.fromArray([ + ...set.batches.filter((batch) => batch.sequence + batch.entryIds.length > startSequence), + ...tail + ]).pipe(Stream.concat(live)) + } + const batches = journal.batches const first = batches.findIndex((batch) => batch.sequence + batch.entryIds.length > startSequence) return Stream.fromArray(first === -1 ? [] : batches.slice(first)).pipe( - Stream.concat(Stream.fromSubscription(subscription)) + Stream.concat(live) ) - }, Stream.unwrap) + }, Stream.unwrap), + compaction }) }) +/** + * Provides encrypted server `Storage` using the in-memory implementation with + * default compaction tuning. + * + * @see {@link layerStorageMemoryWith} to configure compaction + * + * @stability unstable + * @category layers + * @since 4.0.0 + */ +export const layerStorageMemory: Layer.Layer = Layer.effect(Storage)(makeStorageMemory) + /** * Provides encrypted server `Storage` using the in-memory implementation. * @@ -315,7 +1327,58 @@ export const makeStorageMemory: Effect.Effect = Layer.effect(Storage)(makeStorageMemory) +export const layerStorageMemoryWith = (options: { + readonly compaction?: CompactionOptions | undefined +}): Layer.Layer => Layer.effect(Storage)(makeStorageMemoryWith(options)) + +interface MemoryActivation { + readonly id: string + // undefined while the originals are active. + readonly set: { batches: ReadonlyArray } | undefined + readonly base: number + readonly keptCount: number | undefined + readonly previous: MemoryActivation | undefined + supersededAt: number | undefined + pruneStartedAt: number | undefined +} + +interface MemoryStage { + readonly id: string + readonly pinned: MemoryActivation + readonly through: number + expiresAt: number + // Staged batches by position. + readonly staged: Map +} + +interface MemoryJournal { + // Entry id to the sequence it was first stored at. Never pruned. + readonly knownIds: Map + // Originals, in sequence order. + readonly batches: Array + nextSequence: number + // Storage-time hour to the highest last sequence stored in it. + readonly buckets: Map + readonly activations: Array + active: MemoryActivation + noOp: { readonly at: number; readonly count: number } | undefined + openStage: MemoryStage | undefined + nextSweepAt: number | undefined +} + +const stagedBatches = (stage: MemoryStage) => + Array.from(stage.staged, ([position, batch]) => ({ batch, position })).sort((a, b) => a.position - b.position) + +const findBatch = (batches: ReadonlyArray, sequence: number) => { + let low = 0 + let high = batches.length + while (low < high) { + const mid = (low + high) >>> 1 + if (batches[mid].sequence < sequence) low = mid + 1 + else high = mid + } + return batches[low]?.sequence === sequence ? batches[low] : undefined +} const makeEncryptedScopeKey = ({ publicKey, storeId }: { readonly publicKey: string diff --git a/packages/effect/src/eventlog/EventRow.ts b/packages/effect/src/eventlog/EventRow.ts index 9d09e93686..c6cf0d6b49 100644 --- a/packages/effect/src/eventlog/EventRow.ts +++ b/packages/effect/src/eventlog/EventRow.ts @@ -524,6 +524,10 @@ export const handler = < * patches would apply to a different row, or to none. Entries that fail to * decode are kept. * + * The compactor opts into remote compaction (see the `remote` option of + * `EventLog.groupCompaction`). There it also keeps entries with fields the row + * schema does not know. + * * Leaves other events' compactors unchanged. Register one compactor per row * event. * @@ -545,14 +549,19 @@ export const compaction = < Layer.effectDiscard(Effect.gen(function*() { const registry = yield* EventLog.Registry const services = yield* Effect.context>() - const decode = Schema.decodeUnknownEffect(group.events[row.tag].payloadSchemaBinary) + const event = group.events[row.tag] + const decode = Schema.decodeUnknownEffect(event.payloadSchemaBinary) + // A remote compaction treats entries with unknown fields as undecodable. + const decodeStrict = Schema.decodeUnknownEffect(SchemaBinary.toCodecStrict(event.payload)) yield* registry.registerCompaction({ events: [row.tag], - effect: Effect.fnUntraced(function*({ entries, write }) { + remote: true, + effect: Effect.fnUntraced(function*({ entries, remote, write }) { + const decodePayload = remote ? decodeStrict : decode const ops = new Map() for (const entry of entries) { const payload = yield* Effect.result( - decode(entry.payload).pipe(Effect.updateContext((input) => Context.merge(services, input))) + decodePayload(entry.payload).pipe(Effect.updateContext((input) => Context.merge(services, input))) ) as Effect.Effect> if (Result.isSuccess(payload)) ops.set(entry, payload.success) } diff --git a/packages/effect/src/eventlog/SqlEventLogServerEncrypted.ts b/packages/effect/src/eventlog/SqlEventLogServerEncrypted.ts index fb412ae918..51180e06ef 100644 --- a/packages/effect/src/eventlog/SqlEventLogServerEncrypted.ts +++ b/packages/effect/src/eventlog/SqlEventLogServerEncrypted.ts @@ -5,30 +5,45 @@ * `EventLogServerEncrypted` when entries should be stored without exposing * plaintext event data to the database. It persists the server remote id, * session authentication bindings, and encrypted batch tables, assigns stable - * sequence numbers, and streams changes. Clients remain responsible for - * encrypting writes and decrypting reads. + * sequence numbers, streams changes, and stores encrypted compaction snapshots. + * Clients remain responsible for encrypting writes and decrypting reads. * * @stability unstable * @since 4.0.0 */ import * as Arr from "../Array.ts" import type { NonEmptyArray } from "../Array.ts" +import * as Cause from "../Cause.ts" +import * as Clock from "../Clock.ts" import * as Digest from "../crypto/Digest.ts" +import * as SecureRandom from "../crypto/SecureRandom.ts" +import * as Duration from "../Duration.ts" import * as Effect from "../Effect.ts" import * as Layer from "../Layer.ts" +import * as Option from "../Option.ts" import * as PubSub from "../PubSub.ts" import * as RcMap from "../RcMap.ts" +import * as Schedule from "../Schedule.ts" import * as Schema from "../Schema.ts" import type * as Scope from "../Scope.ts" import * as Semaphore from "../Semaphore.ts" import * as SqlClient from "../sql/SqlClient.ts" -import type * as SqlError from "../sql/SqlError.ts" +import * as SqlError from "../sql/SqlError.ts" import type * as Statement from "../sql/Statement.ts" import * as Stream from "../Stream.ts" import { type EntryId, makeRemoteIdUnsafe, type RemoteId } from "./EventJournal.ts" import type * as EventLogEncryption from "./EventLogEncryption.ts" -import type { WriteAck } from "./EventLogMessage.ts" +import type { StoreId, WriteAck } from "./EventLogMessage.ts" import * as EventLogServerEncrypted from "./EventLogServerEncrypted.ts" +import { + hourMillis, + lagHour, + logCommit, + logNoOp, + logRollback, + maxSegments, + positionsPerSegment +} from "./internal/compaction.ts" /** * Creates encrypted event-log server `Storage` backed by SQL. @@ -39,6 +54,11 @@ import * as EventLogServerEncrypted from "./EventLogServerEncrypted.ts" * batches in dialect-specific tables, creating per-identity/store batch and entry * id tables as needed. * + * The storage always provides `compaction`. Its tables are created on startup + * and when a store is first opened. A sweep in the surrounding scope prunes + * superseded generations every `sweepInterval`. Startup dies on invalid + * compaction options (see `EventLogServerEncrypted.makeCompactionConfig`). + * * **Gotchas** * * Storage does not retry sequence conflicts between competing instances. @@ -47,6 +67,14 @@ import * as EventLogServerEncrypted from "./EventLogServerEncrypted.ts" * are local to each storage instance; clients on other instances must reconnect * to read those writes. * + * Inside a caller's transaction, `write` and `compaction.rollback` publish to + * live readers after the outermost commit, and not at all if it rolls back. + * Concurrent caller transactions may reach live readers out of sequence order. + * `changes` always reads in committed order. + * + * Instances sharing a database should share compaction options. The instance + * that writes a generation or stage fixes its prune time or expiry. + * * @stability unstable * @category constructors * @since 4.0.0 @@ -54,6 +82,7 @@ import * as EventLogServerEncrypted from "./EventLogServerEncrypted.ts" export const makeStorage = (options?: { readonly entryTablePrefix?: string readonly remoteIdTable?: string + readonly compaction?: EventLogServerEncrypted.CompactionOptions | undefined }): Effect.Effect< EventLogServerEncrypted.Storage["Service"], SqlError.SqlError, @@ -62,6 +91,11 @@ export const makeStorage = (options?: { Effect.gen(function*() { const digest = yield* Digest.Digest const sql = (yield* SqlClient.SqlClient).withoutTransforms() + const config = yield* EventLogServerEncrypted.makeCompactionConfig(options?.compaction) + const graceMillis = Duration.toMillis(config.grace) + const lagMillis = Duration.toMillis(config.lag) + const stageTtlMillis = Duration.toMillis(config.stageTtl) + const sweepIntervalMillis = Duration.toMillis(config.sweepInterval) const tablePrefix = options?.entryTablePrefix ?? "effect_events" const remoteIdTable = options?.remoteIdTable ?? "effect_remote_id" @@ -122,6 +156,120 @@ export const makeStorage = (options?: { )` }) + const types = sql.onDialectOrElse({ + pg: () => ({ id: "TEXT", int: "INTEGER", bigint: "BIGINT", bytes: "BYTEA", entryId: "BYTEA", iv: "BYTEA" }), + mysql: () => ({ + id: "VARCHAR(36)", + int: "INT", + bigint: "BIGINT", + bytes: "LONGBLOB", + entryId: "BINARY(16)", + iv: "BINARY(12)" + }), + mssql: () => ({ + id: "NVARCHAR(36)", + int: "INT", + bigint: "BIGINT", + bytes: "VARBINARY(MAX)", + entryId: "VARBINARY(16)", + iv: "VARBINARY(12)" + }), + orElse: () => ({ id: "TEXT", int: "INTEGER", bigint: "INTEGER", bytes: "BLOB", entryId: "BLOB", iv: "BLOB" }) + }) + // Two instances can open the same table at once, and PostgreSQL and SQL + // Server can fail the loser of a concurrent create, so creation retries. + const createTable = (name: string, columns: string, indexes: ReadonlyArray = []) => + sql.onDialectOrElse({ + mysql: () => { + const definitions = [columns, ...indexes.map((index) => `INDEX (${index})`)].join(", ") + return Effect.asVoid(sql`CREATE TABLE IF NOT EXISTS ${sql(name)} (${sql.literal(definitions)})`) + }, + mssql: () => + sql`IF OBJECT_ID(${name}, N'U') IS NULL CREATE TABLE ${sql(name)} (${sql.literal(columns)})`.pipe( + Effect.andThen(Effect.forEach(indexes, (index, i) => { + const indexName = `${name}_i${i}` + return sql` + IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE name = ${indexName} AND object_id = OBJECT_ID(${name})) + CREATE INDEX ${sql(indexName)} ON ${sql(name)} (${sql.literal(index)})` + }, { discard: true })) + ), + orElse: () => + sql`CREATE TABLE IF NOT EXISTS ${sql(name)} (${sql.literal(columns)})`.pipe( + Effect.andThen(Effect.forEach( + indexes, + (index, i) => + sql`CREATE INDEX IF NOT EXISTS ${sql(`${name}_i${i}`)} ON ${sql(name)} (${sql.literal(index)})`, + { discard: true } + )) + ) + }).pipe(Effect.retry({ times: 3 })) + + const storesTable = `${tablePrefix}_compaction_stores` + const bucketsTable = `${tablePrefix}_compaction_buckets` + const activationsTable = `${tablePrefix}_compaction_activations` + const stagesTable = `${tablePrefix}_compaction_stages` + const storesSql = sql(storesTable) + const bucketsSql = sql(bucketsTable) + const activationsSql = sql(activationsTable) + const stagesSql = sql(stagesTable) + + // One row per store, keyed by the scope hash its tables are named after. + // "Nothing" is 0 for the base, `pruned_through` and the lag head. + yield* createTable( + storesTable, + `scope ${types.id} PRIMARY KEY, + next_sequence ${types.int} NOT NULL, + active_activation ${types.id} NOT NULL, + active_batch_set ${types.id} NULL, + base_sequence ${types.int} NOT NULL, + active_kept_count ${types.int} NOT NULL, + no_op_at ${types.int} NULL, + no_op_count ${types.int} NOT NULL, + open_stage ${types.id} NULL, + next_sweep_at ${types.bigint} NULL, + sweep_lease_until ${types.bigint} NULL, + sweep_lease_owner ${types.id} NULL, + pruned_through ${types.int} NOT NULL`, + ["next_sweep_at"] + ) + // The highest last sequence stored in each storage-time hour. + yield* createTable( + bucketsTable, + `scope ${types.id} NOT NULL, + bucket_hour ${types.bigint} NOT NULL, + last_sequence ${types.int} NOT NULL, + PRIMARY KEY (scope, bucket_hour)` + ) + // A `batch_set` of null means the originals only. `prunable_at` is set when + // the activation is superseded or withdrawn. + yield* createTable( + activationsTable, + `id ${types.id} PRIMARY KEY, + scope ${types.id} NOT NULL, + ordinal ${types.int} NOT NULL, + batch_set ${types.id} NULL, + base_sequence ${types.int} NOT NULL, + kept_count ${types.int} NULL, + previous ${types.id} NULL, + superseded_at ${types.bigint} NULL, + prunable_at ${types.bigint} NULL, + prune_started_at ${types.bigint} NULL`, + ["scope, ordinal"] + ) + // A stage's pending batch set is its own id. A committed stage's row is + // deleted at commit. Other stages go from `open` to `closed`, and the + // sweep deletes what they staged, then the row. + yield* createTable( + stagesTable, + `id ${types.id} PRIMARY KEY, + scope ${types.id} NOT NULL, + state ${types.id} NOT NULL, + pinned ${types.id} NOT NULL, + through_sequence ${types.int} NOT NULL, + expires_at ${types.bigint} NOT NULL`, + ["scope, state", "state, expires_at"] + ) + const remoteId = yield* sql<{ remote_id: Uint8Array }>`SELECT remote_id FROM ${remoteIdTableSql}`.pipe( Effect.flatMap((results) => { if (results.length > 0) { @@ -135,120 +283,348 @@ export const makeStorage = (options?: { }) ) - const resources = yield* RcMap.make({ - lookup: Effect.fnUntraced(function*(scopeKey: string) { - const scopeHash = (yield* digest.digestHex(Digest.sha256, new TextEncoder().encode(scopeKey))).slice(0, 16) - const table = `${tablePrefix}_${scopeHash}` - const tableSql = sql(table) - const idsTableSql = sql(`${table}_ids`) - const indexSql = sql(`${table}_last_sequence`) + const scopeTables = (scope: string) => { + const table = `${tablePrefix}_${scope}` + return { + tableSql: sql(table), + idsTableSql: sql(`${table}_ids`), + snapshotTableSql: sql(`${table}_snapshot`) + } + } + type ScopeTables = ReturnType - yield* sql.onDialectOrElse({ - pg: () => - sql` - CREATE TABLE IF NOT EXISTS ${tableSql} ( - sequence INTEGER PRIMARY KEY, - last_sequence INTEGER NOT NULL, - iv BYTEA NOT NULL, - entry_ids BYTEA NOT NULL, - encrypted_batch BYTEA NOT NULL - )`.pipe( - Effect.andThen(sql`CREATE INDEX IF NOT EXISTS ${indexSql} ON ${tableSql} (last_sequence)`), - Effect.andThen(sql` - CREATE TABLE IF NOT EXISTS ${idsTableSql} ( - entry_id BYTEA PRIMARY KEY, - sequence INTEGER NOT NULL - )`) - ), - mysql: () => - sql` - CREATE TABLE IF NOT EXISTS ${tableSql} ( - sequence INT PRIMARY KEY, - last_sequence INT NOT NULL, - iv BINARY(12) NOT NULL, - entry_ids LONGBLOB NOT NULL, - encrypted_batch LONGBLOB NOT NULL, - INDEX (last_sequence) - )`.pipe( - Effect.andThen(sql` - CREATE TABLE IF NOT EXISTS ${idsTableSql} ( - entry_id BINARY(16) PRIMARY KEY, - sequence INT NOT NULL - )`) - ), - mssql: () => - sql` - IF OBJECT_ID(${table}, N'U') IS NULL - CREATE TABLE ${tableSql} ( - sequence INT PRIMARY KEY, - last_sequence INT NOT NULL, - iv VARBINARY(12) NOT NULL, - entry_ids VARBINARY(MAX) NOT NULL, - encrypted_batch VARBINARY(MAX) NOT NULL, - INDEX ${indexSql} NONCLUSTERED (last_sequence) - )`.pipe( - Effect.andThen(sql` - IF OBJECT_ID(${`${table}_ids`}, N'U') IS NULL - CREATE TABLE ${idsTableSql} ( - entry_id VARBINARY(16) PRIMARY KEY, - sequence INT NOT NULL - )`) - ), - orElse: () => - sql` - CREATE TABLE IF NOT EXISTS ${tableSql} ( - sequence INTEGER PRIMARY KEY, - last_sequence INTEGER NOT NULL, - iv BLOB NOT NULL, - entry_ids BLOB NOT NULL, - encrypted_batch BLOB NOT NULL - )`.pipe( - Effect.andThen(sql`CREATE INDEX IF NOT EXISTS ${indexSql} ON ${tableSql} (last_sequence)`), - Effect.andThen(sql` - CREATE TABLE IF NOT EXISTS ${idsTableSql} ( - entry_id BLOB PRIMARY KEY, - sequence INTEGER NOT NULL - )`) - ) - }) + const ensureTables = Effect.fnUntraced(function*(scope: string, tables: ScopeTables) { + const table = `${tablePrefix}_${scope}` + const { idsTableSql, tableSql } = tables + const indexSql = sql(`${table}_last_sequence`) - const pubsub = yield* Effect.acquireRelease( - PubSub.unbounded(), - PubSub.shutdown - ) - // Serializes writes within this storage instance. - const semaphore = yield* Semaphore.make(1) - return { pubsub, semaphore, tableSql, idsTableSql } as const - }, withTracerDisabled), - idleTimeToLive: "5 minutes" - }) - - // Returns how many of the ids were not stored yet. Stored ids keep their - // first sequence. - const insertNewIds = (idsTableSql: Statement.Identifier, rows: Arr.NonEmptyReadonlyArray) => - sql.onDialectOrElse({ + yield* sql.onDialectOrElse({ + pg: () => + sql` + CREATE TABLE IF NOT EXISTS ${tableSql} ( + sequence INTEGER PRIMARY KEY, + last_sequence INTEGER NOT NULL, + iv BYTEA NOT NULL, + entry_ids BYTEA NOT NULL, + encrypted_batch BYTEA NOT NULL + )`.pipe( + Effect.andThen(sql`CREATE INDEX IF NOT EXISTS ${indexSql} ON ${tableSql} (last_sequence)`), + Effect.andThen(sql` + CREATE TABLE IF NOT EXISTS ${idsTableSql} ( + entry_id BYTEA PRIMARY KEY, + sequence INTEGER NOT NULL + )`) + ), mysql: () => - sql`INSERT IGNORE INTO ${idsTableSql} ${sql.insert(rows)}`.raw.pipe( - Effect.map((result) => (result as { affectedRows: number }).affectedRows) + sql` + CREATE TABLE IF NOT EXISTS ${tableSql} ( + sequence INT PRIMARY KEY, + last_sequence INT NOT NULL, + iv BINARY(12) NOT NULL, + entry_ids LONGBLOB NOT NULL, + encrypted_batch LONGBLOB NOT NULL, + INDEX (last_sequence) + )`.pipe( + Effect.andThen(sql` + CREATE TABLE IF NOT EXISTS ${idsTableSql} ( + entry_id BINARY(16) PRIMARY KEY, + sequence INT NOT NULL + )`) ), mssql: () => sql` - MERGE ${idsTableSql} WITH (HOLDLOCK) AS target - USING (VALUES ${ - sql.join(",", false)(rows.map((row) => sql`(${row.entry_id}, ${row.sequence})`)) - }) AS source (entry_id, sequence) - ON target.entry_id = source.entry_id - WHEN NOT MATCHED THEN - INSERT (entry_id, sequence) VALUES (source.entry_id, source.sequence) - OUTPUT inserted.entry_id; - `.pipe(Effect.map((inserted) => inserted.length)), + IF OBJECT_ID(${table}, N'U') IS NULL + CREATE TABLE ${tableSql} ( + sequence INT PRIMARY KEY, + last_sequence INT NOT NULL, + iv VARBINARY(12) NOT NULL, + entry_ids VARBINARY(MAX) NOT NULL, + encrypted_batch VARBINARY(MAX) NOT NULL, + INDEX ${indexSql} NONCLUSTERED (last_sequence) + )`.pipe( + Effect.andThen(sql` + IF OBJECT_ID(${`${table}_ids`}, N'U') IS NULL + CREATE TABLE ${idsTableSql} ( + entry_id VARBINARY(16) PRIMARY KEY, + sequence INT NOT NULL + )`) + ), orElse: () => sql` - INSERT INTO ${idsTableSql} ${sql.insert(rows)} - ON CONFLICT DO NOTHING RETURNING entry_id + CREATE TABLE IF NOT EXISTS ${tableSql} ( + sequence INTEGER PRIMARY KEY, + last_sequence INTEGER NOT NULL, + iv BLOB NOT NULL, + entry_ids BLOB NOT NULL, + encrypted_batch BLOB NOT NULL + )`.pipe( + Effect.andThen(sql`CREATE INDEX IF NOT EXISTS ${indexSql} ON ${tableSql} (last_sequence)`), + Effect.andThen(sql` + CREATE TABLE IF NOT EXISTS ${idsTableSql} ( + entry_id BLOB PRIMARY KEY, + sequence INTEGER NOT NULL + )`) + ) + }).pipe(Effect.retry({ times: 3 })) + // Staged and committed snapshot batches. `sequence` and + // `last_sequence` stay null until commit. + yield* createTable( + `${table}_snapshot`, + `batch_set ${types.id} NOT NULL, + batch_position ${types.bigint} NOT NULL, + sequence ${types.int} NULL, + last_sequence ${types.int} NULL, + entry_count ${types.int} NOT NULL, + iv ${types.iv} NOT NULL, + entry_ids ${types.bytes} NOT NULL, + encrypted_batch ${types.bytes} NOT NULL, + PRIMARY KEY (batch_set, batch_position)`, + ["batch_set, last_sequence"] + ) + yield* ensureStore(scope, tables) + }) + + // Stores whose tables and row this instance has ensured, so a store + // reopened after idling skips the DDL. + const ensured = new Set() + const lookup = Effect.fnUntraced(function*(scopeKey: string) { + const scope = (yield* digest.digestHex(Digest.sha256, new TextEncoder().encode(scopeKey))).slice(0, 16) + const tables = scopeTables(scope) + if (!ensured.has(scope)) { + yield* ensureTables(scope, tables) + ensured.add(scope) + } + + const pubsub = yield* Effect.acquireRelease( + PubSub.unbounded(), + PubSub.shutdown + ) + const semaphore = yield* Semaphore.make(1) + return { pubsub, semaphore, scope, ...tables } as const + }, withTracerDisabled) + type StoreResources = Effect.Success> + const resources = yield* RcMap.make({ lookup, idleTimeToLive: "5 minutes" }) + + // Statements that return rows the caller decodes. + const query = (statement: Statement.Statement) => + statement as unknown as Effect.Effect>, SqlError.SqlError> + + // Inserts the rows whose `keys` are not stored yet, leaving stored rows as + // they are, and returns how many were inserted. Every row has the same + // columns, and SQL Server's MERGE needs them unique by key. + const insertNew = ( + tableSql: Statement.Identifier, + rows: Arr.NonEmptyReadonlyArray>, + keys: ReadonlyArray + ) => + sql.onDialectOrElse({ + mysql: () => + sql`INSERT IGNORE INTO ${tableSql} ${sql.insert(rows)}`.raw.pipe( + Effect.map((result) => (result as { affectedRows: number }).affectedRows) + ), + mssql: () => { + const columns = Object.keys(rows[0]) + const values = sql.join(", ", false)( + rows.map((row) => sql`(${sql.join(", ", false)(columns.map((column) => sql`${row[column]}`))})`) + ) + return sql` + MERGE ${tableSql} WITH (HOLDLOCK) AS target + USING (VALUES ${values}) AS source (${sql.literal(columns.join(", "))}) + ON ${sql.literal(keys.map((key) => `target.${key} = source.${key}`).join(" AND "))} + WHEN NOT MATCHED THEN + INSERT (${sql.literal(columns.join(", "))}) + VALUES (${sql.literal(columns.map((column) => `source.${column}`).join(", "))}) + OUTPUT inserted.${sql.literal(keys[0])}; `.pipe(Effect.map((inserted) => inserted.length)) + }, + orElse: () => + sql`INSERT INTO ${tableSql} ${sql.insert(rows)} ON CONFLICT DO NOTHING RETURNING ${sql(keys[0])}`.pipe( + Effect.map((inserted) => inserted.length) + ) }) + const upsertBucket = (scope: string, hour: number, lastSequence: number) => + sql.onDialectOrElse({ + pg: () => + sql` + INSERT INTO ${bucketsSql} (scope, bucket_hour, last_sequence) VALUES (${scope}, ${hour}, ${lastSequence}) + ON CONFLICT (scope, bucket_hour) + DO UPDATE SET last_sequence = GREATEST(${bucketsSql}.last_sequence, EXCLUDED.last_sequence)`, + mysql: () => + sql` + INSERT INTO ${bucketsSql} (scope, bucket_hour, last_sequence) VALUES (${scope}, ${hour}, ${lastSequence}) + ON DUPLICATE KEY UPDATE last_sequence = GREATEST(last_sequence, VALUES(last_sequence))`, + mssql: () => + sql` + MERGE ${bucketsSql} WITH (HOLDLOCK) AS target + USING (VALUES (${scope}, ${hour}, ${lastSequence})) AS source (scope, bucket_hour, last_sequence) + ON target.scope = source.scope AND target.bucket_hour = source.bucket_hour + WHEN MATCHED AND source.last_sequence > target.last_sequence THEN + UPDATE SET last_sequence = source.last_sequence + WHEN NOT MATCHED THEN + INSERT (scope, bucket_hour, last_sequence) + VALUES (source.scope, source.bucket_hour, source.last_sequence);`, + orElse: () => + sql` + INSERT INTO ${bucketsSql} (scope, bucket_hour, last_sequence) VALUES (${scope}, ${hour}, ${lastSequence}) + ON CONFLICT (scope, bucket_hour) + DO UPDATE SET last_sequence = MAX(${bucketsSql}.last_sequence, excluded.last_sequence)` + }) + + const maxLastSequence = (tableSql: Statement.Identifier) => + Effect.map( + query(sql`SELECT MAX(last_sequence) AS last_sequence FROM ${tableSql}`), + ([row]) => Number(row?.last_sequence ?? 0) + ) + + // Creates the store row on first open. The first instance to insert it + // also records the originals activation and seeds a bucket at the current + // last sequence, so data written before the upgrade becomes compactable. + const ensureStore = Effect.fnUntraced(function*(scope: string, tables: ScopeTables) { + const existing = yield* query(sql`SELECT scope FROM ${storesSql} WHERE scope = ${scope}`) + if (existing.length > 0) return + const now = yield* Clock.currentTimeMillis + yield* sql.withTransaction(Effect.gen(function*() { + const lastSequence = yield* maxLastSequence(tables.tableSql) + const originals = SecureRandom.uuidV4Unsafe() + const inserted = yield* insertNew(storesSql, [{ + scope, + next_sequence: lastSequence + 1, + active_activation: originals, + active_batch_set: null, + base_sequence: 0, + active_kept_count: 0, + no_op_at: null, + no_op_count: 0, + open_stage: null, + next_sweep_at: null, + sweep_lease_until: null, + sweep_lease_owner: null, + pruned_through: 0 + }], ["scope"]) + if (inserted === 0) return + yield* sql`INSERT INTO ${activationsSql} ${ + sql.insert({ + id: originals, + scope, + ordinal: 0, + batch_set: null, + base_sequence: 0, + kept_count: null, + previous: null, + superseded_at: null, + prunable_at: null, + prune_started_at: null + }) + }` + if (lastSequence > 0) yield* upsertBucket(scope, Math.floor(now / hourMillis), lastSequence) + })) + }) + + const storeColumns = sql.literal( + "next_sequence, active_activation, active_batch_set, base_sequence, active_kept_count, no_op_at, " + + "no_op_count, open_stage, next_sweep_at, sweep_lease_until, sweep_lease_owner, pruned_through" + ) + const selectStore = (scope: string) => + Effect.map( + query(sql`SELECT ${storeColumns} FROM ${storesSql} WHERE scope = ${scope}`), + ([row]) => row === undefined ? undefined : toStoreRow(row) + ) + // Row locks held for the rest of the transaction. SQLite transactions take + // the database write lock instead. + const lockHint = sql.onDialectOrElse({ + mssql: () => sql.literal("WITH (UPDLOCK, ROWLOCK, HOLDLOCK)"), + orElse: () => sql.literal("") + }) + const forUpdate = sql.onDialectOrElse({ + pg: () => sql.literal("FOR UPDATE"), + mysql: () => sql.literal("FOR UPDATE"), + orElse: () => sql.literal("") + }) + const noClause = sql.literal("") + // Locks the store row for the rest of the transaction. Lock order is store + // row, then stage row, then snapshot rows. + const lockStore = (scope: string) => + query(sql`SELECT ${storeColumns} FROM ${storesSql} ${lockHint} WHERE scope = ${scope} ${forUpdate}`).pipe( + Effect.flatMap(([row]) => + row === undefined + ? Effect.die(new Cause.NoSuchElementError(`No compaction store row for scope ${scope}`)) + : Effect.succeed(toStoreRow(row)) + ) + ) + + const stageColumns = sql.literal("id, scope, state, pinned, through_sequence, expires_at") + const selectStage = (scope: string, stageId: string, lock: boolean) => + query(sql` + SELECT ${stageColumns} FROM ${stagesSql} ${lock ? lockHint : noClause} + WHERE id = ${stageId} ${lock ? forUpdate : noClause}`).pipe( + Effect.map(([row]) => { + if (row === undefined) return undefined + const stage = toStageRow(row) + return stage.scope === scope ? stage : undefined + }) + ) + + const selectActivation = (id: string) => + Effect.map( + query(sql`SELECT ${activationColumns} FROM ${activationsSql} WHERE id = ${id}`), + ([row]) => row === undefined ? undefined : toActivationRow(row) + ) + const selectActivations = (scope: string) => + Effect.map( + query(sql`SELECT ${activationColumns} FROM ${activationsSql} WHERE scope = ${scope} ORDER BY ordinal`), + (rows) => rows.map(toActivationRow) + ) + const activationColumns = sql.literal( + "id, ordinal, batch_set, base_sequence, kept_count, previous, superseded_at, prunable_at, prune_started_at" + ) + + const releaseClaim = (scope: string, stageId: string) => + sql`UPDATE ${storesSql} SET open_stage = NULL WHERE scope = ${scope} AND open_stage = ${stageId}` + // Closes an open stage, leaving what it staged to the sweep, and releases + // the store's busy claim. + const closeStage = (scope: string, stageId: string) => + sql`UPDATE ${stagesSql} SET state = ${"closed"} WHERE id = ${stageId} AND state = ${"open"}`.pipe( + Effect.andThen(releaseClaim(scope, stageId)) + ) + + const scheduleSweep = (scope: string, at: number) => + sql` + UPDATE ${storesSql} + SET next_sweep_at = CASE WHEN next_sweep_at IS NULL OR next_sweep_at > ${at} THEN ${at} ELSE next_sweep_at END + WHERE scope = ${scope}` + + // The clauses that cap a statement at `rows` rows, for `SELECT ${top} ... ${limit}`. + const rowCap = (rows: number) => ({ + top: sql.onDialectOrElse({ mssql: () => sql.literal(`TOP (${rows})`), orElse: () => noClause }), + limit: sql.onDialectOrElse({ mssql: () => noClause, orElse: () => sql.literal(`LIMIT ${rows}`) }) + }) + const { limit, top } = rowCap(pageSize) + const { limit: chunkLimit, top: chunkTop } = rowCap(pruneChunkRows) + // Streams rows in key order, one page per statement. + const paged = ( + first: number, + page: (after: number) => Effect.Effect, SqlError.SqlError>, + key: (row: A) => number + ) => + Stream.paginate(first, (after) => + Effect.map(page(after), (rows) => + [ + rows, + rows.length < pageSize ? Option.none() : Option.some(key(rows[rows.length - 1])) + ] as const)) + + const setRows = (snapshotTableSql: Statement.Identifier, batchSet: string) => + paged( + -1, + (after) => + query(sql` + SELECT ${top} batch_position, sequence, entry_ids FROM ${snapshotTableSql} + WHERE batch_set = ${batchSet} AND batch_position > ${after} + ORDER BY batch_position ${limit}`), + (row) => Number(row.batch_position) + ) + const getSessionAuthBinding = (publicKey: string) => sql` SELECT public_key, signing_public_key @@ -263,6 +639,644 @@ export const makeStorage = (options?: { Effect.orDie ) + // Runs `f` with the store's resources and the time, read before any + // transaction starts. SQL failures are defects. + const withStore = ( + publicKey: string, + storeId: StoreId, + f: (store: StoreResources, now: number) => Effect.Effect + ): Effect.Effect> => + Effect.zip(RcMap.get(resources, makeEncryptedScopeKey(publicKey, storeId)), Clock.currentTimeMillis).pipe( + Effect.flatMap(([store, now]) => f(store, now)), + dieOnSqlError, + Effect.scoped, + withTracerDisabled + ) + + const notFound = (stageId: string) => Effect.fail(new EventLogServerEncrypted.CompactionNotFound({ stageId })) + + // An open stage whose pin isn't being pruned yet, for Input and Fetch. + const findInputStage = Effect.fnUntraced(function*(scope: string, stageId: string, now: number) { + const stage = yield* selectStage(scope, stageId, false) + if (stage === undefined || stage.state !== "open" || stage.expiresAt <= now) return undefined + const pinned = yield* selectActivation(stage.pinned) + if (pinned === undefined || pinned.pruneStartedAt !== undefined) return undefined + return { stage, pinned } + }) + // Fails a read that may have been truncated by a prune of its pin. + const recheckPin = (stageId: string, pinned: string) => + Effect.flatMap( + selectActivation(pinned), + (activation) => + activation === undefined || activation.pruneStartedAt !== undefined ? notFound(stageId) : Effect.void + ) + + const status = Effect.fnUntraced(function*({ scope, tableSql }: StoreResources, now: number) { + const store = (yield* selectStore(scope))! + const lastSequence = yield* maxLastSequence(tableSql) + const [lag] = yield* query(sql` + SELECT MAX(last_sequence) AS last_sequence FROM ${bucketsSql} + WHERE scope = ${scope} AND bucket_hour <= ${lagHour(now, lagMillis)}`) + return { + head: Math.max(store.nextSequence - 1, lastSequence), + base: store.base, + activeKeptCount: store.activeKeptCount, + lagHead: Number(lag?.last_sequence ?? 0), + noOp: store.noOpAt === undefined ? undefined : { at: store.noOpAt, count: store.noOpCount } + } + }) + + const begin = Effect.fnUntraced(function*({ scope }: StoreResources, now: number, through: number) { + const store = yield* lockStore(scope) + if (store.openStage !== undefined) { + const open = yield* selectStage(scope, store.openStage, true) + if (open !== undefined && open.state === "open") { + if (open.expiresAt > now) { + return { _tag: "Busy", expiresAt: open.expiresAt } as const + } + yield* closeStage(scope, open.id) + } + } + const stageId = SecureRandom.uuidV4Unsafe() + yield* sql`INSERT INTO ${stagesSql} ${ + sql.insert({ + id: stageId, + scope, + state: "open", + pinned: store.activeActivation, + through_sequence: through, + expires_at: now + stageTtlMillis + }) + }` + yield* sql`UPDATE ${storesSql} SET open_stage = ${stageId} WHERE scope = ${scope}` + return { _tag: "Started", stageId } as const + }, sql.withTransaction) + + const inputHeaders = Effect.fnUntraced(function*( + { scope, snapshotTableSql, tableSql }: StoreResources, + now: number, + stageId: string + ) { + const found = yield* findInputStage(scope, stageId, now) + if (found === undefined) { + return yield* notFound(stageId) + } + const { pinned, stage } = found + // Membership comes from the batch rows, never from the id table. + const snapshot = pinned.batchSet === undefined ? Stream.empty : setRows(snapshotTableSql, pinned.batchSet) + const tail = paged(pinned.base, (after) => + query(sql` + SELECT ${top} sequence, entry_ids FROM ${tableSql} + WHERE sequence > ${after} AND last_sequence <= ${stage.through} + ORDER BY sequence ${limit}`), (row) => Number(row.sequence)) + return snapshot.pipe( + Stream.concat(tail), + Stream.map((row): EventLogServerEncrypted.CompactionBatchHeader => ({ + sequence: Number(row.sequence), + entryIds: toEntryIds(row.entry_ids as Uint8Array) + })), + Stream.orDie, + Stream.concat(Stream.fromEffectDrain(dieOnSqlError(recheckPin(stageId, pinned.id)))) + ) + }) + + const fetch = Effect.fnUntraced(function*( + { scope, snapshotTableSql, tableSql }: StoreResources, + now: number, + stageId: string, + sequences: ReadonlyArray + ) { + const found = yield* findInputStage(scope, stageId, now) + if (found === undefined) { + return yield* notFound(stageId) + } + const { pinned, stage } = found + const bySequence = new Map() + if (pinned.batchSet !== undefined) { + for (const chunk of Arr.chunksOf(sequences.filter((sequence) => sequence <= pinned.base), 200)) { + const rows = yield* sql` + SELECT sequence, iv, entry_ids, encrypted_batch FROM ${snapshotTableSql} + WHERE batch_set = ${pinned.batchSet} AND ${sql.in("sequence", chunk)} + `.pipe(Effect.flatMap(decodeBatches), Effect.orDie) + for (const batch of rows) bySequence.set(batch.sequence, batch) + } + } + const originals = sequences.filter((sequence) => sequence > pinned.base && sequence <= stage.through) + for (const chunk of Arr.chunksOf(originals, 200)) { + const rows = yield* sql` + SELECT sequence, iv, entry_ids, encrypted_batch FROM ${tableSql} + WHERE ${sql.in("sequence", chunk)} + `.pipe(Effect.flatMap(decodeBatches), Effect.orDie) + for (const batch of rows) bySequence.set(batch.sequence, batch) + } + yield* recheckPin(stageId, pinned.id) + return Stream.fromArray(sequences.flatMap((sequence) => { + const batch = bySequence.get(sequence) + return batch === undefined ? [] : [batch] + })) + }) + + const stagePart = ( + store: StoreResources, + now: number, + stageId: string, + segment: number, + batches: Arr.NonEmptyReadonlyArray + ): Effect.Effect< + "Stored" | "AlreadyStored", + EventLogServerEncrypted.CompactionInvalidRequest | EventLogServerEncrypted.CompactionNotFound | SqlError.SqlError + > => { + const invalid = !Number.isSafeInteger(segment) || segment < 0 || segment >= maxSegments + ? "Invalid segment index" + : batches.length > positionsPerSegment + ? "Too many batches in a segment" + : undefined + // A Part that fails validation closes the stage. + if (invalid !== undefined) { + return Effect.andThen( + abort(store, stageId), + Effect.fail(new EventLogServerEncrypted.CompactionInvalidRequest({ stageId, message: invalid })) + ) + } + const { scope, snapshotTableSql } = store + return sql.withTransaction(Effect.gen(function*() { + yield* lockStore(scope) + const stage = yield* selectStage(scope, stageId, true) + if (stage === undefined || stage.state !== "open" || stage.expiresAt <= now) { + return yield* notFound(stageId) + } + // The snapshot table's key makes a retried segment insert nothing. + // `sequence` and `last_sequence` stay null until commit. + const rows = batches.map((batch, i) => ({ + batch_set: stageId, + batch_position: segment * positionsPerSegment + i, + entry_count: batch.entryIds.length, + iv: batch.iv, + entry_ids: concatEntryIds(batch.entryIds), + encrypted_batch: batch.encryptedBatch + })) + let inserted = 0 + for (const chunk of Arr.chunksOf(rows, 200)) { + inserted += yield* insertNew(snapshotTableSql, chunk, ["batch_set", "batch_position"]) + } + if (inserted === 0) return "AlreadyStored" as const + yield* sql`UPDATE ${stagesSql} SET expires_at = ${now + stageTtlMillis} WHERE id = ${stageId}` + return "Stored" as const + })) + } + + const stagedHeaders = Effect.fnUntraced(function*( + { scope, snapshotTableSql }: StoreResources, + now: number, + stageId: string + ) { + const stage = yield* selectStage(scope, stageId, false) + if (stage === undefined || stage.state !== "open" || stage.expiresAt <= now) { + return yield* notFound(stageId) + } + return setRows(snapshotTableSql, stageId).pipe( + Stream.map((row) => ({ + position: Number(row.batch_position), + entryIds: toEntryIds(row.entry_ids as Uint8Array) + })), + Stream.orDie + ) + }) + + const commit = Effect.fnUntraced(function*( + { scope, snapshotTableSql }: StoreResources, + now: number, + stageId: string, + virtualSequences: ReadonlyArray + ) { + const store = yield* lockStore(scope) + const stage = yield* selectStage(scope, stageId, true) + if (stage === undefined || stage.state !== "open" || stage.expiresAt <= now) { + return yield* notFound(stageId) + } + const staged = yield* query(sql` + SELECT batch_position, entry_count FROM ${snapshotTableSql} + WHERE batch_set = ${stageId} ORDER BY batch_position`) + let keptCount = 0 + for (const row of staged) keptCount += Number(row.entry_count) + const audit = { through: stage.through, keptCount } + if (stage.pinned !== store.activeActivation) { + yield* closeStage(scope, stageId) + return { result: "Superseded", activationId: undefined, ...audit } as const + } + if (staged.length !== virtualSequences.length) { + return yield* Effect.die(new Cause.IllegalArgumentError("Expected one virtual sequence per staged batch")) + } + for (let i = 0; i < staged.length; i++) { + const sequence = virtualSequences[i] + const lastSequence = sequence + Number(staged[i].entry_count) - 1 + yield* sql` + UPDATE ${snapshotTableSql} SET sequence = ${sequence}, last_sequence = ${lastSequence} + WHERE batch_set = ${stageId} AND batch_position = ${Number(staged[i].batch_position)}` + } + const activationId = SecureRandom.uuidV4Unsafe() + yield* insertActivation(scope, { + id: activationId, + batch_set: stageId, + base_sequence: stage.through, + kept_count: keptCount, + previous: store.activeActivation + }) + yield* supersede(store.activeActivation, now) + yield* sql` + UPDATE ${storesSql} + SET active_activation = ${activationId}, active_batch_set = ${stageId}, + base_sequence = ${stage.through}, active_kept_count = ${keptCount}, + no_op_at = NULL, no_op_count = 0 + WHERE scope = ${scope}` + yield* scheduleSweep(scope, now + graceMillis) + // The staged rows are now the active batch set. + yield* sql`DELETE FROM ${stagesSql} WHERE id = ${stageId}` + yield* releaseClaim(scope, stageId) + return { result: "Committed", activationId, ...audit } as const + }, sql.withTransaction) + + const recordNoOp = Effect.fnUntraced(function*({ scope }: StoreResources, now: number, stageId: string) { + const store = yield* lockStore(scope) + const stage = yield* selectStage(scope, stageId, true) + if (stage === undefined || stage.state !== "open" || stage.expiresAt <= now) { + return yield* notFound(stageId) + } + // A rollback since begin cleared the no-op state, so a stale run leaves it. + if (stage.pinned === store.activeActivation) { + yield* sql` + UPDATE ${storesSql} SET no_op_at = ${stage.through}, no_op_count = ${store.noOpCount + 1} + WHERE scope = ${scope}` + } + yield* closeStage(scope, stageId) + return stage.through + }, sql.withTransaction) + + const rollbackTransaction = Effect.fnUntraced(function*( + { pubsub, scope, snapshotTableSql, tableSql }: StoreResources, + now: number, + expectedActivationId: string + ) { + const refuse = (reason: EventLogServerEncrypted.CompactionRollbackError["reason"]) => + Effect.fail(new EventLogServerEncrypted.CompactionRollbackError({ reason })) + const store = yield* lockStore(scope) + if (store.activeActivation !== expectedActivationId) return yield* refuse("NotActive") + const withdrawn = (yield* selectActivation(store.activeActivation))! + const target = withdrawn.previous === undefined ? undefined : yield* selectActivation(withdrawn.previous) + if (target === undefined) return yield* refuse("NoPrevious") + if (target.pruneStartedAt !== undefined) return yield* refuse("PruneStarted") + const activationId = SecureRandom.uuidV4Unsafe() + yield* insertActivation(scope, { + id: activationId, + batch_set: target.batchSet ?? null, + base_sequence: target.base, + kept_count: target.keptCount ?? null, + previous: target.previous ?? null + }) + yield* supersede(withdrawn.id, now) + yield* sql` + UPDATE ${storesSql} + SET active_activation = ${activationId}, active_batch_set = ${target.batchSet ?? null}, + base_sequence = ${target.base}, active_kept_count = ${target.keptCount ?? 0}, + no_op_at = NULL, no_op_count = 0 + WHERE scope = ${scope}` + yield* scheduleSweep(scope, now + graceMillis) + + // Re-appends the input of the stage that built the withdrawn generation, + // the target's batch set and then the originals between the two bases, + // at sequences taken as `write` takes them. + let nextSequence = Math.max(store.nextSequence, (yield* maxLastSequence(tableSql)) + 1) + const reappended: Array = [] + const reappend = (rows: ReadonlyArray>) => { + const inserted: Array = [] + for (const row of rows) { + const entry_ids = row.entry_ids as Uint8Array + const batch: EventLogEncryption.EncryptedRemoteBatch = { + sequence: nextSequence, + entryIds: toEntryIds(entry_ids), + iv: row.iv as Uint8Array, + encryptedBatch: row.encrypted_batch as Uint8Array + } + nextSequence += batch.entryIds.length + reappended.push(batch) + inserted.push({ + sequence: batch.sequence, + last_sequence: nextSequence - 1, + iv: batch.iv, + entry_ids, + encrypted_batch: batch.encryptedBatch + }) + } + return Effect.forEach( + Arr.chunksOf(inserted, 200), + (chunk) => sql`INSERT INTO ${tableSql} ${sql.insert(chunk)}`, + { discard: true } + ) + } + if (target.batchSet !== undefined) { + yield* Stream.runForEachArray( + paged( + -1, + (after) => + query(sql` + SELECT ${top} batch_position, iv, entry_ids, encrypted_batch FROM ${snapshotTableSql} + WHERE batch_set = ${target.batchSet} AND batch_position > ${after} + ORDER BY batch_position ${limit}`), + (row) => Number(row.batch_position) + ), + reappend + ) + } + // The copies land above `withdrawn.base`, so the pages never reach them. + yield* Stream.runForEachArray( + paged( + target.base, + (after) => + query(sql` + SELECT ${top} sequence, iv, entry_ids, encrypted_batch FROM ${tableSql} + WHERE sequence > ${after} AND last_sequence <= ${withdrawn.base} + ORDER BY sequence ${limit}`), + (row) => Number(row.sequence) + ), + reappend + ) + if (reappended.length > 0) { + yield* sql`UPDATE ${storesSql} SET next_sequence = ${nextSequence} WHERE scope = ${scope}` + yield* upsertBucket(scope, Math.floor(now / hourMillis), nextSequence - 1) + yield* sql.afterCommit(Effect.asVoid(PubSub.publishAll(pubsub, reappended))) + } + return { activationId, target, withdrawn } + }, sql.withTransaction) + + // The re-appended batches are published after the outermost commit. When + // the storage owns the transaction, that happens before the semaphore is + // released, so live readers get them in sequence order. + const rollback = (store: StoreResources, now: number, expectedActivationId: string) => + store.semaphore.withPermits(1)(rollbackTransaction(store, now, expectedActivationId)) + + const history = Effect.fnUntraced(function*({ scope }: StoreResources) { + const store = (yield* selectStore(scope))! + const activations = yield* selectActivations(scope) + return activations.map((activation): EventLogServerEncrypted.CompactionActivation => { + const active = activation.id === store.activeActivation + return { + activationId: activation.id, + base: activation.base, + keptCount: activation.keptCount, + active, + supersededAt: active ? undefined : activation.supersededAt, + restorable: activation.pruneStartedAt === undefined + } + }) + }) + + const abort = Effect.fnUntraced(function*({ scope }: StoreResources, stageId: string) { + yield* lockStore(scope) + const stage = yield* selectStage(scope, stageId, true) + if (stage?.state === "open") yield* closeStage(scope, stageId) + }, sql.withTransaction) + + const compaction: EventLogServerEncrypted.StorageCompaction = { + config, + status: (publicKey, storeId) => withStore(publicKey, storeId, status), + begin: (publicKey, storeId, { through }) => + withStore(publicKey, storeId, (store, now) => begin(store, now, through)), + inputHeaders: (publicKey, storeId, stageId) => + Stream.unwrap(withStore(publicKey, storeId, (store, now) => inputHeaders(store, now, stageId))), + fetch: (publicKey, storeId, stageId, sequences) => + Stream.unwrap(withStore(publicKey, storeId, (store, now) => fetch(store, now, stageId, sequences))), + stagePart: (publicKey, storeId, stageId, segment, batches) => + withStore(publicKey, storeId, (store, now) => stagePart(store, now, stageId, segment, batches)), + stagedHeaders: (publicKey, storeId, stageId) => + Stream.unwrap(withStore(publicKey, storeId, (store, now) => stagedHeaders(store, now, stageId))), + commit: (publicKey, storeId, stageId, virtualSequences) => + withStore(publicKey, storeId, (store, now) => commit(store, now, stageId, virtualSequences)).pipe( + Effect.tap((outcome) => logCommit({ publicKey, storeId, ...outcome })), + Effect.map((outcome) => outcome.result) + ), + recordNoOp: (publicKey, storeId, stageId) => + withStore(publicKey, storeId, (store, now) => recordNoOp(store, now, stageId)).pipe( + Effect.flatMap((through) => logNoOp({ publicKey, storeId, stageId, through })) + ), + abort: (publicKey, storeId, stageId) => withStore(publicKey, storeId, (store) => abort(store, stageId)), + rollback: (publicKey, storeId, expectedActivationId) => + withStore(publicKey, storeId, (store, now) => rollback(store, now, expectedActivationId)).pipe( + Effect.tap(({ activationId, target, withdrawn }) => + logRollback({ publicKey, storeId, activation: { ...target, id: activationId }, withdrawn }) + ), + Effect.map((outcome) => outcome.activationId) + ), + history: (publicKey, storeId) => withStore(publicKey, storeId, (store) => history(store)) + } + + const insertActivation = Effect.fnUntraced(function*(scope: string, activation: { + readonly id: string + readonly batch_set: string | null + readonly base_sequence: number + readonly kept_count: number | null + readonly previous: string | null + }) { + const [last] = yield* query(sql`SELECT MAX(ordinal) AS ordinal FROM ${activationsSql} WHERE scope = ${scope}`) + yield* sql`INSERT INTO ${activationsSql} ${ + sql.insert({ + ...activation, + scope, + ordinal: Number(last?.ordinal ?? 0) + 1, + superseded_at: null, + prunable_at: null, + prune_started_at: null + }) + }` + }) + // Supersedes or withdraws an activation, prunable `grace` later. + const supersede = (activationId: string, now: number) => + sql` + UPDATE ${activationsSql} SET superseded_at = ${now}, prunable_at = ${now + graceMillis} + WHERE id = ${activationId}` + + // Deletes up to `pruneChunkRows` rows matching `where` in key order and + // returns whether it found any. No new rows match `where`, so a later call + // resumes an interrupted one. + const deleteChunk = Effect.fnUntraced(function*( + tableSql: Statement.Identifier, + key: string, + where: Statement.Fragment + ) { + const keys = yield* query(sql` + SELECT ${chunkTop} ${sql(key)} AS chunk_key FROM ${tableSql} + WHERE ${where} ORDER BY ${sql(key)} ${chunkLimit}`) + if (keys.length === 0) return false + yield* sql`DELETE FROM ${tableSql} WHERE ${where} AND ${sql(key)} <= ${keys[keys.length - 1].chunk_key}` + return true + }) + + // Runs one chunk of a prune under the store row lock, if this sweeper + // still holds the lease and the active activation hasn't changed. + const pruneChunk = ( + scope: string, + now: number, + lease: { readonly owner: string; readonly activeActivation: string }, + f: Effect.Effect + ) => + sql.withTransaction(Effect.gen(function*() { + const store = yield* lockStore(scope) + if (store.sweepLeaseOwner !== lease.owner || store.activeActivation !== lease.activeActivation) { + return Option.none() + } + const value = yield* f + yield* sql`UPDATE ${storesSql} SET sweep_lease_until = ${now + sweepIntervalMillis} WHERE scope = ${scope}` + return Option.some(value) + })) + + // Prunes what no activation still needs: the batch sets of generations + // past their grace, and the originals at or below the lowest base still + // kept. Deletes are idempotent, so a later sweep finishes one that died. + const pruneStore = Effect.fnUntraced(function*(scope: string, now: number) { + const { snapshotTableSql, tableSql } = scopeTables(scope) + const owner = SecureRandom.uuidV4Unsafe() + // Claim the store and mark what this prune removes before deleting anything. + const plan = yield* sql.withTransaction(Effect.gen(function*() { + const store = yield* lockStore(scope) + if (store.nextSweepAt === undefined || store.nextSweepAt > now) return undefined + if (store.sweepLeaseUntil !== undefined && store.sweepLeaseUntil > now) return undefined + const activations = yield* selectActivations(scope) + const isKept = (activation: ActivationRow) => + activation.id === store.activeActivation || + (activation.pruneStartedAt === undefined && (activation.prunableAt ?? Infinity) > now) + const kept = activations.filter(isKept) + const pruned = activations.filter((activation) => !isKept(activation)) + const starting = pruned.filter((activation) => activation.pruneStartedAt === undefined) + for (const chunk of Arr.chunksOf(starting.map((activation) => activation.id), 200)) { + yield* sql`UPDATE ${activationsSql} SET prune_started_at = ${now} WHERE ${sql.in("id", chunk)}` + } + const keptSets = new Set(kept.map((activation) => activation.batchSet)) + yield* sql` + UPDATE ${storesSql} SET sweep_lease_until = ${now + sweepIntervalMillis}, sweep_lease_owner = ${owner} + WHERE scope = ${scope}` + return { + lease: { owner, activeActivation: store.activeActivation }, + sets: Array.from( + new Set(pruned.flatMap((activation) => + activation.batchSet === undefined || keptSets.has(activation.batchSet) ? [] : [activation.batchSet] + )) + ), + keptBase: kept.reduce((base, activation) => + Math.min(base, activation.base), Infinity), + prunedThrough: store.prunedThrough + } + })) + if (plan === undefined) return + for (const set of plan.sets) { + while (true) { + const deleted = yield* pruneChunk( + scope, + now, + plan.lease, + deleteChunk(snapshotTableSql, "batch_position", sql`batch_set = ${set}`) + ) + if (Option.isNone(deleted)) return + if (!deleted.value) break + } + } + for (let start = plan.prunedThrough; start < plan.keptBase; start += pruneChunkSequences) { + const end = Math.min(start + pruneChunkSequences, plan.keptBase) + const held = yield* pruneChunk( + scope, + now, + plan.lease, + sql`DELETE FROM ${tableSql} WHERE last_sequence <= ${end}`.pipe( + Effect.andThen(sql` + UPDATE ${storesSql} + SET pruned_through = CASE WHEN pruned_through < ${end} THEN ${end} ELSE pruned_through END + WHERE scope = ${scope}`) + ) + ) + if (Option.isNone(held)) return + } + yield* sql.withTransaction(Effect.gen(function*() { + const store = yield* lockStore(scope) + if (store.sweepLeaseOwner !== owner) return + const [next] = yield* query(sql` + SELECT MIN(prunable_at) AS next_sweep_at FROM ${activationsSql} + WHERE scope = ${scope} AND id <> ${store.activeActivation} AND prune_started_at IS NULL`) + yield* sql` + UPDATE ${storesSql} + SET next_sweep_at = ${next?.next_sweep_at ?? null}, sweep_lease_until = NULL, sweep_lease_owner = NULL + WHERE scope = ${scope}` + })) + }) + + // Deletes a closed stage's rows matching `where`, one chunk per + // transaction, each under the store row lock to keep the lock order. + const deleteStaged = Effect.fnUntraced(function*( + scope: string, + tableSql: Statement.Identifier, + key: string, + where: Statement.Fragment + ) { + while (yield* sql.withTransaction(Effect.andThen(lockStore(scope), deleteChunk(tableSql, key, where)))) { + // Each chunk commits on its own. + } + }) + + // Closes stages past their claim, then deletes closed stages. A closed + // stage's staged rows are read by nothing, so they go first in short + // chunks, and the stage row last. + const sweepStages = Effect.fnUntraced(function*(now: number) { + const expired = yield* query(sql` + SELECT id, scope FROM ${stagesSql} WHERE state = ${"open"} AND expires_at <= ${now}`) + for (const row of expired) { + const scope = String(row.scope) + const stageId = String(row.id) + yield* sql.withTransaction(Effect.gen(function*() { + yield* lockStore(scope) + const stage = yield* selectStage(scope, stageId, true) + if (stage?.state === "open" && stage.expiresAt <= now) { + yield* closeStage(scope, stageId) + } + })) + } + const closed = yield* query(sql`SELECT id, scope FROM ${stagesSql} WHERE state = ${"closed"}`) + for (const row of closed) { + const scope = String(row.scope) + const stageId = String(row.id) + yield* deleteStaged(scope, scopeTables(scope).snapshotTableSql, "batch_position", sql`batch_set = ${stageId}`) + yield* sql.withTransaction( + Effect.andThen(lockStore(scope), sql`DELETE FROM ${stagesSql} WHERE id = ${stageId}`) + ) + } + }) + + // Only the newest bucket past the lag matters for the lag head. + const sweepBuckets = Effect.fnUntraced(function*(now: number) { + const rows = yield* query(sql` + SELECT scope, MAX(bucket_hour) AS newest FROM ${bucketsSql} + WHERE bucket_hour <= ${lagHour(now, lagMillis)} + GROUP BY scope HAVING COUNT(*) > 1`) + for (const row of rows) { + yield* sql`DELETE FROM ${bucketsSql} WHERE scope = ${String(row.scope)} AND bucket_hour < ${Number(row.newest)}` + } + }) + + const logSweepFailure = (cause: Cause.Cause) => + Effect.logWarning("Compaction sweep failed", cause).pipe( + Effect.annotateLogs({ service: "SqlEventLogServerEncrypted" }) + ) + const sweep = Effect.gen(function*() { + const now = yield* Clock.currentTimeMillis + yield* Effect.catchCause(sweepStages(now), logSweepFailure) + const due = yield* query(sql`SELECT scope FROM ${storesSql} WHERE next_sweep_at <= ${now}`) + for (const row of due) { + yield* Effect.catchCause(pruneStore(String(row.scope), now), logSweepFailure) + } + yield* Effect.catchCause(sweepBuckets(now), logSweepFailure) + }).pipe(Effect.catchCause(logSweepFailure), withTracerDisabled) + // A fixed schedule starts an overdue sweep straight away, so slow queries + // don't push sweeps back. + yield* Effect.forkScoped( + Effect.delay(Effect.repeat(sweep, Schedule.fixed(config.sweepInterval)), config.sweepInterval) + ) + return EventLogServerEncrypted.Storage.of({ getId: Effect.succeed(remoteId), // Auto-increment sequences start at 1. @@ -288,15 +1302,17 @@ export const makeStorage = (options?: { function*(publicKey, storeId, batches) { if (batches.length === 0) return [] const scopeKey = makeEncryptedScopeKey(publicKey, storeId) - const { idsTableSql, pubsub, semaphore, tableSql } = yield* RcMap.get(resources, scopeKey) + const { idsTableSql, pubsub, scope, semaphore, tableSql } = yield* RcMap.get(resources, scopeKey) + const now = yield* Clock.currentTimeMillis const writeBatches = Effect.gen(function*() { const stored: Array = [] + // The store row lock makes sequence order commit order. The row's + // `next_sequence` survives pruning, and `MAX(last_sequence)` covers + // instances that predate the row. + const store = yield* lockStore(scope) // Read before inserting ids, which record the sequence they are stored at. - const [last] = yield* sql<{ last_sequence: number | string | null }>` - SELECT MAX(last_sequence) AS last_sequence FROM ${tableSql} - ` - let nextSequence = Number(last?.last_sequence ?? 0) + 1 + let nextSequence = Math.max(store.nextSequence, (yield* maxLastSequence(tableSql)) + 1) for (const batch of batches) { // Inserting the ids decides whether the batch is new. SQL Server's // MERGE also requires unique source ids. @@ -308,7 +1324,8 @@ export const makeStorage = (options?: { } let inserted = 0 for (const chunk of Arr.chunksOf(ids.values(), 200)) { - inserted += yield* insertNewIds(idsTableSql, chunk) + // Stored ids keep their first sequence. + inserted += yield* insertNew(idsTableSql, chunk, ["entry_id"]) } if (inserted === 0) continue const row: BatchRow = { @@ -322,14 +1339,16 @@ export const makeStorage = (options?: { stored.push({ sequence: nextSequence, ...batch }) nextSequence += batch.entryIds.length } + if (stored.length > 0) { + yield* sql`UPDATE ${storesSql} SET next_sequence = ${nextSequence} WHERE scope = ${scope}` + yield* upsertBucket(scope, Math.floor(now / hourMillis), nextSequence - 1) + // Published after the outermost commit, as `rollback` publishes. + yield* sql.afterCommit(Effect.asVoid(PubSub.publishAll(pubsub, stored))) + } return stored }) - return yield* semaphore.withPermits(1)(Effect.gen(function*() { - const stored = yield* sql.withTransaction(writeBatches) - yield* PubSub.publishAll(pubsub, stored) - return stored - })) + return yield* semaphore.withPermits(1)(sql.withTransaction(writeBatches)) }, Effect.orDie, Effect.scoped, @@ -351,11 +1370,34 @@ export const makeStorage = (options?: { Effect.scoped, withTracerDisabled ), + // Reads the store row, the active set and the tail as separate + // statements. A transaction would take the SQLite write lock on every + // stream open, and set rows never change before they are pruned. changes: Effect.fnUntraced( function*(publicKey, storeId, startSequence) { const scopeKey = makeEncryptedScopeKey(publicKey, storeId) - const { pubsub, tableSql } = yield* RcMap.get(resources, scopeKey) + const { pubsub, scope, snapshotTableSql, tableSql } = yield* RcMap.get(resources, scopeKey) const subscription = yield* PubSub.subscribe(pubsub) + const live = Stream.fromSubscription(subscription) + const store = (yield* selectStore(scope))! + // Below the base an active snapshot replaces the originals. + if (store.activeBatchSet !== undefined && startSequence <= store.base) { + const set = yield* sql` + SELECT sequence, iv, entry_ids, encrypted_batch FROM ${snapshotTableSql} + WHERE batch_set = ${store.activeBatchSet} AND last_sequence >= ${startSequence} + ORDER BY batch_position ASC + `.pipe(Effect.flatMap(decodeBatches)) + // The final batch ends at the base, so only an empty set reads nothing. + if (set.length === 0) { + return Stream.die(new Error(`The active compaction snapshot of store ${storeId} has no batches`)) + } + const tail = yield* sql` + SELECT sequence, iv, entry_ids, encrypted_batch FROM ${tableSql} + WHERE sequence > ${store.base} + ORDER BY sequence ASC + `.pipe(Effect.flatMap(decodeBatches)) + return Stream.fromArray([...set, ...tail]).pipe(Stream.concat(live)) + } const initial = yield* sql` SELECT sequence, iv, entry_ids, encrypted_batch FROM ${tableSql} WHERE last_sequence >= ${startSequence} @@ -363,15 +1405,76 @@ export const makeStorage = (options?: { `.pipe( Effect.flatMap(decodeBatches) ) - return Stream.fromArray(initial).pipe(Stream.concat(Stream.fromSubscription(subscription))) + return Stream.fromArray(initial).pipe(Stream.concat(live)) }, Effect.orDie, withTracerDisabled, Stream.unwrap - ) + ), + compaction }) }).pipe(withTracerDisabled) +// Rows per statement when streaming compaction input or staged batches. +const pageSize = 500 +// Sequences of originals deleted per prune chunk. +const pruneChunkSequences = 10_000 +// Snapshot or staged rows deleted per prune chunk. +const pruneChunkRows = 200 + +type StageState = "open" | "closed" + +// SQL failures are defects for the compaction primitives. +const dieOnSqlError = ( + effect: Effect.Effect +): Effect.Effect, R> => + Effect.catchIf( + effect, + (error): error is SqlError.SqlError => SqlError.isSqlError(error), + (error) => Effect.die(error) + ) as Effect.Effect, R> + +const optionalNumber = (value: unknown) => value === null || value === undefined ? undefined : Number(value) +const optionalString = (value: unknown) => value === null || value === undefined ? undefined : String(value) + +const toStoreRow = (row: Record) => ({ + nextSequence: Number(row.next_sequence), + activeActivation: String(row.active_activation), + activeBatchSet: optionalString(row.active_batch_set), + base: Number(row.base_sequence), + activeKeptCount: Number(row.active_kept_count), + noOpAt: optionalNumber(row.no_op_at), + noOpCount: Number(row.no_op_count), + openStage: optionalString(row.open_stage), + nextSweepAt: optionalNumber(row.next_sweep_at), + sweepLeaseUntil: optionalNumber(row.sweep_lease_until), + sweepLeaseOwner: optionalString(row.sweep_lease_owner), + prunedThrough: Number(row.pruned_through) +}) + +const toStageRow = (row: Record) => ({ + id: String(row.id), + scope: String(row.scope), + state: String(row.state) as StageState, + pinned: String(row.pinned), + through: Number(row.through_sequence), + expiresAt: Number(row.expires_at) +}) + +type ActivationRow = ReturnType + +const toActivationRow = (row: Record) => ({ + id: String(row.id), + ordinal: Number(row.ordinal), + batchSet: optionalString(row.batch_set), + base: Number(row.base_sequence), + keptCount: optionalNumber(row.kept_count), + previous: optionalString(row.previous), + supersededAt: optionalNumber(row.superseded_at), + prunableAt: optionalNumber(row.prunable_at), + pruneStartedAt: optionalNumber(row.prune_started_at) +}) + type IdRow = { readonly entry_id: Uint8Array readonly sequence: number @@ -396,6 +1499,14 @@ const concatEntryIds = (entryIds: ReadonlyArray): Uint8Array => { return data } +const toEntryIds = (data: Uint8Array): NonEmptyArray => { + const entryIds: Array = [] + for (let offset = 0; offset < data.byteLength; offset += 16) { + entryIds.push(data.subarray(offset, offset + 16) as EntryId) + } + return entryIds as NonEmptyArray +} + const EncryptedRemoteBatchSql = Schema.Struct({ sequence: Schema.Natural, iv: Schema.Uint8Array, @@ -415,18 +1526,12 @@ type SessionAuthBindingSql = Schema.Schema.Type const decodeBatchRows = Schema.decodeUnknownEffect(Schema.Array(EncryptedRemoteBatchSql)) const decodeSessionAuthBindingRows = Schema.decodeUnknownEffect(Schema.Array(SessionAuthBindingSql)) -const toEncryptedRemoteBatch = (row: EncryptedRemoteBatchSql): EventLogEncryption.EncryptedRemoteBatch => { - const entryIds: Array = [] - for (let offset = 0; offset < row.entry_ids.byteLength; offset += 16) { - entryIds.push(row.entry_ids.subarray(offset, offset + 16) as EntryId) - } - return { - sequence: row.sequence, - entryIds: entryIds as NonEmptyArray, - iv: row.iv as Uint8Array, - encryptedBatch: row.encrypted_batch as Uint8Array - } -} +const toEncryptedRemoteBatch = (row: EncryptedRemoteBatchSql): EventLogEncryption.EncryptedRemoteBatch => ({ + sequence: row.sequence, + entryIds: toEntryIds(row.entry_ids), + iv: row.iv as Uint8Array, + encryptedBatch: row.encrypted_batch as Uint8Array +}) const decodeBatches = ( rows: unknown @@ -447,6 +1552,7 @@ const decodeSessionAuthBindings = ( export const layerStorage = (options?: { readonly entryTablePrefix?: string readonly remoteIdTable?: string + readonly compaction?: EventLogServerEncrypted.CompactionOptions | undefined }): Layer.Layer< EventLogServerEncrypted.Storage, SqlError.SqlError, @@ -464,6 +1570,7 @@ export const layerStorage = (options?: { export const layerStorageSubtle = (options?: { readonly entryTablePrefix?: string readonly remoteIdTable?: string + readonly compaction?: EventLogServerEncrypted.CompactionOptions | undefined }): Layer.Layer => layerStorage(options).pipe( Layer.provide(Digest.layerWebCrypto) diff --git a/packages/effect/src/eventlog/internal/batches.ts b/packages/effect/src/eventlog/internal/batches.ts new file mode 100644 index 0000000000..2e9b47e72e --- /dev/null +++ b/packages/effect/src/eventlog/internal/batches.ts @@ -0,0 +1,30 @@ +import type { NonEmptyArray } from "../../Array.ts" +import type { Entry } from "../EventJournal.ts" + +/** The most entries a remote batch holds. */ +export const maxBatchEntries = 100 + +/** The most payload bytes a remote batch holds, unless it is a single entry. */ +export const maxBatchPayloadBytes = 256 * 1024 + +/** + * Packs entries into batches of at most `maxBatchEntries` entries and + * `maxBatchPayloadBytes` of payload. A larger entry is a batch on its own. + */ +export const toBatches = (entries: ReadonlyArray): Array> => { + const batches: Array> = [] + let current: Array = [] + let bytes = 0 + for (const entry of entries) { + const size = entry.payload.byteLength + if (current.length > 0 && (current.length === maxBatchEntries || bytes + size > maxBatchPayloadBytes)) { + batches.push(current as NonEmptyArray) + current = [] + bytes = 0 + } + current.push(entry) + bytes += size + } + if (current.length > 0) batches.push(current as NonEmptyArray) + return batches +} diff --git a/packages/effect/src/eventlog/internal/compaction.ts b/packages/effect/src/eventlog/internal/compaction.ts new file mode 100644 index 0000000000..f29f519963 --- /dev/null +++ b/packages/effect/src/eventlog/internal/compaction.ts @@ -0,0 +1,64 @@ +import * as Effect from "../../Effect.ts" +import type { StoreId } from "../EventLogMessage.ts" + +/** Rules and audit logs shared by the memory and SQL compaction storages. */ + +export const hourMillis = 60 * 60 * 1000 + +/** The newest storage-time hour that ended at least `lagMillis` ago. */ +export const lagHour = (now: number, lagMillis: number): number => Math.floor((now - lagMillis) / hourMillis) - 1 + +/** A staged batch's position packs its segment index and its index in the segment. */ +export const positionsPerSegment = 2 ** 20 +export const maxSegments = Math.floor(Number.MAX_SAFE_INTEGER / positionsPerSegment) + +const service = "EventLogServerEncrypted" + +export const logCommit = (options: { + readonly publicKey: string + readonly storeId: StoreId + readonly result: "Committed" | "Superseded" + readonly through: number + readonly keptCount: number + readonly activationId: string | undefined +}): Effect.Effect => + Effect.logInfo( + options.result === "Committed" ? "Committed compaction snapshot" : "Compaction snapshot superseded" + ).pipe( + Effect.annotateLogs({ + service, + publicKey: options.publicKey, + storeId: options.storeId, + keptCount: options.keptCount, + through: options.through, + activationId: options.activationId + }) + ) + +export const logNoOp = (options: { + readonly publicKey: string + readonly storeId: StoreId + readonly stageId: string + readonly through: number +}): Effect.Effect => + Effect.logInfo("Committed compaction no-op").pipe(Effect.annotateLogs({ service, ...options })) + +export const logRollback = (options: { + readonly publicKey: string + readonly storeId: StoreId + readonly activation: { readonly id: string; readonly base: number; readonly keptCount: number | undefined } + readonly withdrawn: { readonly id: string; readonly base: number; readonly keptCount: number | undefined } +}): Effect.Effect => + Effect.logInfo("Rolled back compaction snapshot").pipe( + Effect.annotateLogs({ + service, + publicKey: options.publicKey, + storeId: options.storeId, + keptCount: options.activation.keptCount, + base: options.activation.base, + activationId: options.activation.id, + withdrawnActivationId: options.withdrawn.id, + withdrawnBase: options.withdrawn.base, + withdrawnKeptCount: options.withdrawn.keptCount + }) + ) diff --git a/packages/effect/src/eventlog/internal/remoteCompaction.ts b/packages/effect/src/eventlog/internal/remoteCompaction.ts new file mode 100644 index 0000000000..af035fe80d --- /dev/null +++ b/packages/effect/src/eventlog/internal/remoteCompaction.ts @@ -0,0 +1,92 @@ +import * as Data from "../../Data.ts" +import * as Effect from "../../Effect.ts" +import * as Stream from "../../Stream.ts" +import type { Entry } from "../EventJournal.ts" +import type { Registry } from "../EventLog.ts" + +/** A second pass over the kept set dropped `entries`, so a compactor does not compose. */ +export class IdempotenceError extends Data.TaggedError("IdempotenceError")<{ + readonly entries: ReadonlyArray +}> {} + +type Compactor = Registry["Service"]["compactors"] extends ReadonlyMap ? A : never + +/** + * Folds the opted-in compactors over `entries`, which arrive in input order + * without repeated ids, and returns the kept entries in input order. + * + * Each step folds a chunk into the kept set. The chunk starts at `chunkSize` + * and grows to the size of the kept set, so a run stays linear when little is + * dropped and memory stays at about twice the kept set. A compactor that + * composes keeps the same entries at any chunking. + * + * Fails with `IdempotenceError` when a second pass over the kept set drops + * more. A compactor defect fails the run. + */ +export const run = (options: { + readonly compactors: Registry["Service"]["compactors"] + readonly entries: Stream.Stream + readonly chunkSize: number +}): Effect.Effect, E | IdempotenceError, R> => { + const drop = Effect.fnUntraced(function*(entries: ReadonlyArray) { + const kept = new Set() + const calls = new Map>() + for (const entry of entries) { + const compactor = options.compactors.get(entry.event) + if (compactor === undefined || !compactor.remote) { + kept.add(entry) + continue + } + const input = calls.get(compactor) + if (input === undefined) calls.set(compactor, [entry]) + else input.push(entry) + } + for (const [compactor, input] of calls) { + const inputs = new Set(input) + const forwarded = new Set() + let replaced = false + yield* compactor.effect({ + entries: input, + remote: true, + write: (entry) => + Effect.sync(() => { + if (inputs.has(entry)) forwarded.add(entry) + else replaced = true + }) + }) + // Only forwarded input entries can be kept verbatim, so a call that + // outputs anything else keeps its whole input. + if (replaced) { + yield* Effect.logWarning("A remote compactor wrote an entry it was not given, so its input is kept").pipe( + Effect.annotateLogs({ events: [...compactor.events] }) + ) + } + for (const entry of replaced ? input : forwarded) kept.add(entry) + } + return entries.filter((entry) => kept.has(entry)) + }) + + return Effect.gen(function*() { + let kept: ReadonlyArray = [] + let pending: Array = [] + yield* options.entries.pipe( + Stream.grouped(options.chunkSize), + Stream.runForEach((group) => { + for (const entry of group) pending.push(entry) + if (pending.length < Math.max(options.chunkSize, kept.length)) return Effect.void + const input = kept.concat(pending) + pending = [] + return Effect.map(drop(input), (next) => { + kept = next + }) + }) + ) + if (pending.length > 0) kept = yield* drop(kept.concat(pending)) + const again = yield* drop(kept) + if (again.length !== kept.length) { + const survivors = new Set(again) + return yield* new IdempotenceError({ entries: kept.filter((entry) => !survivors.has(entry)) }) + } + return kept + }) +} diff --git a/packages/effect/test/eventlog/EventLog.test.ts b/packages/effect/test/eventlog/EventLog.test.ts index 1bc9e0029f..457b1aafd5 100644 --- a/packages/effect/test/eventlog/EventLog.test.ts +++ b/packages/effect/test/eventlog/EventLog.test.ts @@ -3,6 +3,7 @@ import { Array, Context, Effect, + Exit, Layer, Logger, Option, @@ -13,6 +14,7 @@ import { References, Schema, SchemaGetter, + Scope, Stream } from "effect" import * as EventGroup from "effect/eventlog/EventGroup" @@ -21,7 +23,12 @@ import * as EventLog from "effect/eventlog/EventLog" import * as EventLogEncryption from "effect/eventlog/EventLogEncryption" import * as EventLogMessage from "effect/eventlog/EventLogMessage" import * as EventLogRemote from "effect/eventlog/EventLogRemote" +import * as EventLogServerEncrypted from "effect/eventlog/EventLogServerEncrypted" import { Reactivity } from "effect/reactivity" +import * as RpcClient from "effect/rpc/RpcClient" +import type * as RpcGroup from "effect/rpc/RpcGroup" +import type { FromServer } from "effect/rpc/RpcMessage" +import * as RpcServer from "effect/rpc/RpcServer" import * as RpcTest from "effect/rpc/RpcTest" import { TestClock } from "effect/testing" @@ -1395,3 +1402,164 @@ describe("EventLog", () => { assert.deepStrictEqual(second.duplicateEntries.map((_) => _.idString), [entry.idString]) }).pipe(Effect.provide(EventJournal.layerMemory))) }) + +const ValueGroup = EventGroup.empty.add({ + tag: "ValueSet", + primaryKey: (payload) => payload.id, + payload: Schema.Struct({ id: Schema.String, value: Schema.Number }) +}) +const valueSchema = EventLog.schema(ValueGroup) + +const keepLatest = EventLog.groupBatchCompaction(ValueGroup, ({ entries, forward }) => { + const newest = new Map() + for (const { entry } of entries) { + const current = newest.get(entry.primaryKey) + if (current === undefined || EventJournal.Entry.Order(current, entry) < 0) newest.set(entry.primaryKey, entry) + } + return Effect.forEach(newest.values(), forward, { discard: true }) +}, { remote: true }) + +const CompactionRpcs = EventLogMessage.EventLogRemoteRpcs.merge(EventLogMessage.EventLogCompactionRpcs) +type CompactionRpcs = RpcGroup.Rpcs +const defaultStoreId = EventLogMessage.StoreId.make("default") + +// An encrypted server on memory storage, serving both RPC groups. +const makeCompactionServer = Effect.fnUntraced(function*() { + const storage = EventLogServerEncrypted.layerStorageMemoryWith({ + compaction: { thresholdFloor: 1, stageTtl: "12 hours" } + }) + const context = yield* Layer.build(Layer.provideMerge(EventLogServerEncrypted.layerRpcHandlers, storage)) + const compaction = Context.get(context, EventLogServerEncrypted.Storage).compaction! + const connections: Array<(response: FromServer) => Effect.Effect> = [] + const server = yield* RpcServer.makeNoSerialization(CompactionRpcs, { + onFromServer: (response) => connections[response.clientId](response) + }).pipe(Effect.provide(context)) + + const connect = Effect.gen(function*() { + const clientId = connections.length + const { client, write } = yield* RpcClient.makeNoSerialization(CompactionRpcs, { + supportsAck: true, + onFromClient: ({ message }) => server.write(clientId, message) + }) + connections.push(write) + return client + }) + + const snapshots = (publicKey: string) => + compaction.history(publicKey, defaultStoreId).pipe( + Effect.map((history) => history.filter((activation) => activation.keptCount !== undefined).length) + ) + + return { compaction, connect, snapshots } +}) + +type CompactionServer = Effect.Success> + +// A device running `EventLog` over `journal`, connected to `server`. Its +// handler records each replayed or written value as `id=value` in `handled`. +const makeDevice = Effect.fnUntraced(function*( + server: CompactionServer, + identity: EventLog.Identity["Service"], + options?: { + readonly journal?: EventJournal.EventJournal["Service"] | undefined + readonly compactor?: Layer.Layer | undefined + readonly handled?: Array | undefined + } +) { + const handled = options?.handled ?? [] + const journal = options?.journal ?? (yield* EventJournal.makeMemory) + const handlers = Layer.mergeAll( + EventLog.group(ValueGroup, (handlers) => + handlers.handle("ValueSet", ({ payload }) => + Effect.sync(() => { + handled.push(`${payload.id}=${payload.value}`) + }))), + options?.compactor ?? Layer.empty + ).pipe(Layer.provide(EventLog.layerRegistry)) + const context = yield* Layer.build( + EventLog.layer(valueSchema, handlers).pipe( + Layer.provide(Layer.succeed(EventJournal.EventJournal, journal)), + Layer.provide(Layer.succeed(EventLog.Identity, identity)) + ) + ) + const remote = yield* EventLogRemote.makeEncrypted.pipe( + Effect.provideService(EventLogRemote.EventLogRemoteClient, yield* server.connect), + Effect.provide(context) + ) + const log = Context.get(context, EventLog.EventLog) + return { + log, + journal, + remote, + handled, + write: (id: string, value: number) => log.write({ schema: valueSchema, event: "ValueSet", payload: { id, value } }) + } +}) + +// Advances the TestClock 15 minutes, then gives fibers waiting on Web Crypto +// some real time. +const step = TestClock.adjust("15 minutes").pipe(Effect.andThen(TestClock.withLive(Effect.sleep(5)))) + +// Steps until `done` holds, for at most 50 hours. +const advanceUntil = Effect.fnUntraced(function*(done: Effect.Effect, waitingFor: string) { + for (let i = 0; i < 200; i++) { + if (yield* done) return + yield* step + } + return assert.fail(`timed out waiting until ${waitingFor}`) +}) + +describe("EventLog remote compaction", () => { + it.effect("bootstraps a new device from the snapshot a background run commits, ending with the state of a full replay", () => + Effect.gen(function*() { + const server = yield* makeCompactionServer() + const identity = yield* EventLog.makeIdentity + const writer = yield* makeDevice(server, identity, { compactor: keepLatest }) + for (const [id, value] of [["a", 1], ["b", 1], ["a", 2], ["a", 3], ["b", 2]] as const) { + yield* writer.write(id, value) + } + + yield* advanceUntil( + Effect.map(server.snapshots(identity.publicKey), (count) => count === 1), + "a snapshot commits" + ) + yield* writer.write("a", 4) + const reader = yield* makeDevice(server, identity) + yield* advanceUntil(Effect.sync(() => reader.handled.includes("a=4")), "the reader replays the tail") + + // A full replay ends with a=4 and b=2 too, after handling all six writes. + assert.deepStrictEqual(reader.handled, ["a=3", "b=2", "a=4"]) + }).pipe(Effect.provide(EventLogEncryption.layerSubtle))) + + it.effect("serves a device whose cursor is inside one snapshot everything kept by the next", () => + Effect.gen(function*() { + const server = yield* makeCompactionServer() + const identity = yield* EventLog.makeIdentity + const writer = yield* makeDevice(server, identity, { compactor: keepLatest }) + const journal = yield* EventJournal.makeMemory + const handled: Array = [] + yield* writer.write("k1", 1) + yield* writer.write("k2", 1) + const readerScope = yield* Scope.make() + const reader = yield* makeDevice(server, identity, { journal, handled }).pipe(Scope.provide(readerScope)) + yield* advanceUntil(Effect.sync(() => handled.includes("k2=1")), "the reader reads sequence 1") + yield* Scope.close(readerScope, Exit.void) + const cursor = yield* journal.nextRemoteSequence(reader.remote.id) + + // Snapshot g+1 covers sequences 0 to 3, so the reader's cursor is inside it. + yield* writer.write("k1", 2) + yield* writer.write("k3", 1) + yield* advanceUntil(Effect.map(server.snapshots(identity.publicKey), (count) => count === 1), "g+1 commits") + yield* writer.write("k3", 2) + yield* writer.write("k4", 1) + yield* writer.write("k4", 2) + yield* advanceUntil(Effect.map(server.snapshots(identity.publicKey), (count) => count === 2), "g+2 commits") + yield* makeDevice(server, identity, { journal, handled }) + yield* advanceUntil(Effect.sync(() => handled.includes("k4=2")), "the reader catches up") + + assert.deepStrictEqual({ cursor, handled }, { + cursor: 2, + handled: ["k1=1", "k2=1", "k1=2", "k3=2", "k4=2"] + }) + }).pipe(Effect.provide(EventLogEncryption.layerSubtle))) +}) diff --git a/packages/effect/test/eventlog/EventLogRemote.test.ts b/packages/effect/test/eventlog/EventLogRemote.test.ts index 900f61aa3c..c56c841c90 100644 --- a/packages/effect/test/eventlog/EventLogRemote.test.ts +++ b/packages/effect/test/eventlog/EventLogRemote.test.ts @@ -1,5 +1,5 @@ import { assert, describe, it } from "@effect/vitest" -import { Array, Context, Deferred, Effect, Fiber, Layer, Option, Queue, type Scope, Stream } from "effect" +import { Array, Context, Deferred, Effect, Exit, Fiber, Layer, Option, Queue, type Scope, Stream } from "effect" import * as EventJournal from "effect/eventlog/EventJournal" import * as EventLog from "effect/eventlog/EventLog" import * as EventLogEncryption from "effect/eventlog/EventLogEncryption" @@ -12,10 +12,12 @@ import * as EventLogSessionAuth from "effect/eventlog/EventLogSessionAuth" import { makeGetIdentityRootSecretMaterial } from "effect/eventlog/internal/identityRootSecretDerivation" import type * as Rpc from "effect/rpc/Rpc" import * as RpcClient from "effect/rpc/RpcClient" +import * as RpcClientError from "effect/rpc/RpcClientError" import type * as RpcGroup from "effect/rpc/RpcGroup" import type { FromServer } from "effect/rpc/RpcMessage" import * as RpcServer from "effect/rpc/RpcServer" import * as RpcTest from "effect/rpc/RpcTest" +import * as Socket from "effect/socket/Socket" import { TestClock } from "effect/testing" describe("EventLogRemote", () => { @@ -503,3 +505,171 @@ describe("EventLogRemote write acknowledgements", () => { }) }).pipe(Effect.provide(EventLogEncryption.layerSubtle))) }) + +const CompactionRpcs = EventLogMessage.EventLogRemoteRpcs.merge(EventLogMessage.EventLogCompactionRpcs) +type CompactionRpcs = RpcGroup.Rpcs + +// The memory storage without its compaction sub-service, like a third-party +// storage that predates compaction. +const layerStorageWithoutCompaction = Layer.effect(EventLogServerEncrypted.Storage)( + Effect.map(EventLogServerEncrypted.makeStorageMemory, ({ compaction: _, ...storage }) => storage) +) + +// An encrypted server on memory storage, serving both RPC groups. +const makeCompactionServer = Effect.fnUntraced(function*( + storage: Layer.Layer = EventLogServerEncrypted.layerStorageMemoryWith({ + compaction: { thresholdFloor: 1 } + }) +) { + const handlers = yield* Layer.build(EventLogServerEncrypted.layerRpcHandlers.pipe(Layer.provide(storage))) + const connections = new Map) => Effect.Effect>() + const server = yield* RpcServer.makeNoSerialization(CompactionRpcs, { + onFromServer: (response) => connections.get(response.clientId)!(response) + }).pipe(Effect.provide(handlers)) + let nextClientId = 0 + + // `dropPart` replaces the response to that Part request, counted from 0 in + // send order, with the failure a closed socket gives it. + const connect = Effect.fnUntraced(function*(identity: EventLog.Identity["Service"], options?: { + readonly dropPart?: number | undefined + }) { + const clientId = nextClientId++ + const parts: Array = [] + let dropped: unknown = undefined + const { client, write } = yield* RpcClient.makeNoSerialization(CompactionRpcs, { + supportsAck: true, + onFromClient: ({ message }) => { + if (message._tag === "Request" && message.tag === "EventLog.CompactionPart") { + const payload = message.payload as Rpc.Payload + if (parts.push(payload.chunk) - 1 === options?.dropPart) dropped = message.id + } + return server.write(clientId, message) + } + }) + connections.set(clientId, (response) => + response._tag === "Exit" && response.requestId === dropped + ? write({ + ...response, + exit: Exit.fail( + new RpcClientError.RpcClientError({ reason: new Socket.SocketCloseError({ code: 1006 }) }) + ) as any + }) + : write(response)) + const remote = yield* EventLogRemote.makeEncrypted.pipe( + Effect.provideService(EventLogRemote.EventLogRemoteClient, client), + Effect.provide(EventLog.layerRegistry) + ) + yield* remote.whenAuthenticated(Effect.void).pipe(Effect.provideService(EventLog.Identity, identity)) + return { remote, parts } + }) + + return { connect } +}) + +const entryFields = (entry: EventJournal.Entry) => ({ + id: entry.idString, + event: entry.event, + primaryKey: entry.primaryKey, + payload: entry.payload +}) + +// Writes `entries`, lets them pass the default 24 hour lag, opens a stage and +// fetches its whole input. +const beginWith = Effect.fnUntraced(function*( + writer: EventLogRemote.EventLogRemote["Service"], + identity: EventLog.Identity["Service"], + entries: ReadonlyArray +) { + const compaction = writer.compaction ?? assert.fail("expected the remote to support compaction") + yield* writer.write({ identity, storeId: defaultStoreId, entries }) + yield* TestClock.adjust("26 hours") + const begun = yield* compaction.begin({ identity, storeId: defaultStoreId }) + assert(begun._tag === "Started", `expected Started, got ${begun._tag}`) + const stage = { ...begun, identity, storeId: defaultStoreId } + const headers = yield* Stream.runCollect(compaction.input(stage)) + const input = yield* Stream.runCollect(compaction.fetch(stage, headers.map((header) => header.sequence))) + assert.deepStrictEqual(input.map(({ entry }) => entry.idString), entries.map((entry) => entry.idString)) + return { compaction, stage, input: input.map(({ entry }) => entry) } +}) + +const kb = 1024 + +describe("EventLogRemote compaction", () => { + it.effect("is absent when the server does not advertise compaction", () => + Effect.gen(function*() { + const server = yield* makeCompactionServer(layerStorageWithoutCompaction) + const { remote } = yield* server.connect(yield* EventLog.makeIdentity) + + assert.isUndefined(remote.compaction) + }).pipe(Effect.provide(EventLogEncryption.layerSubtle))) + + it.effect("uploads kept entries in segments of about 512 KB, splitting an oversized one, with their original bytes", () => + Effect.gen(function*() { + const server = yield* makeCompactionServer() + const identity = yield* EventLog.makeIdentity + const writer = yield* server.connect(identity) + const entries = [ + makeEntry({ primaryKey: "dropped" }), + makeEntry({ payloadSize: 200 * kb }), + makeEntry({ payloadSize: 200 * kb }), + makeEntry({ payloadSize: 200 * kb }), + makeEntry({ payloadSize: 600 * kb }), + makeEntry() + ] + const { compaction, input, stage } = yield* beginWith(writer.remote, identity, entries) + + const kept = input.slice(1) + const { segmentCount } = yield* compaction.upload(stage, kept) + const committed = yield* compaction.commit(stage, { _tag: "Snapshot", segmentCount }) + const reader = yield* server.connect(identity) + const changes = yield* reader.remote.changes({ + identity, + storeId: defaultStoreId, + startSequence: reader.remote.firstSequence ?? 0 + }) + const served = yield* Queue.takeN(changes, kept.length) + + // Each 200 KB entry fills its own batch. Two of them fit in one segment, + // the 600 KB batch is a segment of its own split in two, and the last + // small batch doesn't fit after it. + const pieces = new Map() + for (const part of writer.parts) pieces.set(part.id, (pieces.get(part.id) ?? 0) + 1) + assert.deepStrictEqual({ + segmentCount, + pieces: [...pieces].sort(([a], [b]) => a - b), + largestPiece: Math.max(...writer.parts.map((part) => part.data.byteLength)), + committed + }, { + segmentCount: 4, + pieces: [[0, 1], [1, 1], [2, 2], [3, 1]], + largestPiece: EventLogMessage.ChunkedMessage.chunkSize, + committed: "Committed" + }) + assert.deepStrictEqual(served.map(({ entry }) => entryFields(entry)), entries.slice(1).map(entryFields)) + }).pipe(Effect.provide(EventLogEncryption.layerSubtle))) + + it.effect("resends a whole segment after a dropped connection", () => + Effect.gen(function*() { + const server = yield* makeCompactionServer() + const identity = yield* EventLog.makeIdentity + // The response to the piece that completes the segment is lost. + const writer = yield* server.connect(identity, { dropPart: 1 }) + const { compaction, input, stage } = yield* beginWith(writer.remote, identity, [ + makeEntry({ primaryKey: "dropped" }), + makeEntry({ payloadSize: 600 * kb }) + ]) + + const { segmentCount } = yield* compaction.upload(stage, input.slice(1)) + const committed = yield* compaction.commit(stage, { _tag: "Snapshot", segmentCount }) + + assert.deepStrictEqual({ + segmentCount, + pieces: writer.parts.map((part) => `${part.id}:${part.part[0]}/${part.part[1]}`).sort(), + committed + }, { + segmentCount: 1, + pieces: ["0:0/2", "0:0/2", "0:1/2", "0:1/2"], + committed: "Committed" + }) + }).pipe(Effect.provide(EventLogEncryption.layerSubtle))) +}) diff --git a/packages/effect/test/eventlog/EventLogRemoteCompaction.test.ts b/packages/effect/test/eventlog/EventLogRemoteCompaction.test.ts new file mode 100644 index 0000000000..b679cceca4 --- /dev/null +++ b/packages/effect/test/eventlog/EventLogRemoteCompaction.test.ts @@ -0,0 +1,225 @@ +import { assert, describe, it } from "@effect/vitest" +import { Effect, Exit, Layer, Schema, Stream } from "effect" +import type * as Event from "effect/eventlog/Event" +import * as EventGroup from "effect/eventlog/EventGroup" +import * as EventJournal from "effect/eventlog/EventJournal" +import * as EventLog from "effect/eventlog/EventLog" +import * as RemoteCompaction from "effect/eventlog/internal/remoteCompaction" + +const Item = Schema.Struct({ id: Schema.String, value: Schema.Number }) +const Items = EventGroup.empty.add({ tag: "ItemSet", primaryKey: (payload) => payload.id, payload: Item }) +const Notes = EventGroup.empty.add({ tag: "NoteSet", primaryKey: (payload) => payload.id, payload: Item }) +// A newer client's schema, with a field this client does not know. +const SkewedItems = EventGroup.empty.add({ + tag: "ItemSet", + primaryKey: (payload) => payload.id, + payload: Schema.Struct({ ...Item.fields, note: Schema.String }) +}) + +const makeEntry = Effect.fnUntraced(function*( + msecs: number, + event: string, + codec: Schema.Codec>, + payload: { readonly id: string; readonly [key: string]: unknown } +) { + return new EventJournal.Entry({ + id: EventJournal.makeEntryIdUnsafe({ msecs }), + event, + primaryKey: payload.id, + payload: yield* Schema.encodeUnknownEffect(codec)(payload) + }, { disableChecks: true }) +}) + +// Runs the engine over `entries`, in input-sequence order, with the +// compactors `layer` registers. +const run = ( + layer: Layer.Layer, + entries: ReadonlyArray, + chunkSize = 100 +) => + Effect.gen(function*() { + const registry = yield* EventLog.Registry + return yield* RemoteCompaction.run({ + compactors: registry.compactors, + entries: Stream.fromIterable(entries), + chunkSize + }) + }).pipe(Effect.provide(layer.pipe(Layer.provideMerge(EventLog.layerRegistry)))) + +const keepLatest = (group: EventGroup.EventGroup, options = { remote: true }) => + EventLog.groupBatchCompaction(group, ({ entries, forward }) => { + const latest = new Map() + for (const { entry, event } of entries) { + if (event === undefined) continue + const current = latest.get(entry.primaryKey) + if (current === undefined || EventJournal.Entry.Order(current, entry) < 0) latest.set(entry.primaryKey, entry) + } + return Effect.forEach(latest.values(), forward, { discard: true }) + }, options) + +// An `ItemSet` group whose payload also has `fields`. +const itemsWith = (fields: Record>) => + EventGroup.empty.add({ + tag: "ItemSet", + primaryKey: (payload: { readonly id: string }) => payload.id, + payload: Schema.Struct({ ...Item.fields, ...fields }) + }) + +describe("RemoteCompaction", () => { + it.effect("keeps the whole input of a call that outputs a new entry and carries on", () => + Effect.gen(function*() { + const items = [ + yield* makeEntry(1000, "ItemSet", Items.events.ItemSet.payloadSchemaBinary, { id: "a", value: 1 }), + yield* makeEntry(2000, "ItemSet", Items.events.ItemSet.payloadSchemaBinary, { id: "a", value: 2 }) + ] + const notes = [ + yield* makeEntry(1000, "NoteSet", Notes.events.NoteSet.payloadSchemaBinary, { id: "a", value: 1 }), + yield* makeEntry(2000, "NoteSet", Notes.events.NoteSet.payloadSchemaBinary, { id: "a", value: 2 }) + ] + const kept = yield* run( + Layer.mergeAll( + EventLog.groupCompaction(Items, ({ events, write }) => write("ItemSet", events[events.length - 1].payload), { + remote: true + }), + keepLatest(Notes) + ), + [items[0], notes[0], items[1], notes[1]] + ) + assert.deepStrictEqual(kept, [items[0], items[1], notes[1]]) + })) + + it.effect("keeps entries with fields the schema does not know, even when the compactor drops them", () => + Effect.gen(function*() { + const older = yield* makeEntry(1000, "ItemSet", Items.events.ItemSet.payloadSchemaBinary, { id: "a", value: 1 }) + const skewed = yield* makeEntry(2000, "ItemSet", SkewedItems.events.ItemSet.payloadSchemaBinary, { + id: "a", + value: 2, + note: "n" + }) + const newer = yield* makeEntry(3000, "ItemSet", Items.events.ItemSet.payloadSchemaBinary, { id: "a", value: 3 }) + const kept = yield* run(keepLatest(Items), [older, skewed, newer]) + assert.deepStrictEqual(kept, [skewed, newer]) + })) + + it.effect("keeps entries holding values the schema cannot read", () => + Effect.gen(function*() { + const A = Schema.Struct({ _tag: Schema.Literal("A"), n: Schema.Number }) + const B = Schema.Struct({ _tag: Schema.Literal("B"), text: Schema.String }) + // Each case: reader fields, newer writer fields, and the newer value. + const cases: ReadonlyArray< + readonly [string, Record>, Record>, object] + > = [ + [ + "a record key no index signature matches", + { attrs: Schema.optionalKey(Schema.Record(Schema.TemplateLiteral(["keep", Schema.String]), Schema.String)) }, + { attrs: Schema.optionalKey(Schema.Record(Schema.String, Schema.String)) }, + { attrs: { keep1: "a", drop: "b" } } + ], + [ + "an unknown union member", + { event: Schema.optionalKey(Schema.Union([A])) }, + { event: Schema.optionalKey(Schema.Union([A, B])) }, + { event: { _tag: "B", text: "new" } } + ], + [ + "an unknown field in an array of structs", + { rows: Schema.optionalKey(Schema.Array(Schema.Struct({ n: Schema.Number }))) }, + { rows: Schema.optionalKey(Schema.Array(Schema.Struct({ n: Schema.Number, later: Schema.String }))) }, + { rows: [{ n: 1, later: "x" }, { n: 2, later: "y" }] } + ], + [ + "a field whose wire type changed", + { size: Schema.optionalKey(Schema.String) }, + { size: Schema.optionalKey(Schema.Number) }, + { size: 5 } + ] + ] + for (const [name, readerFields, writerFields, value] of cases) { + const Reader = itemsWith(readerFields) + const Writer = itemsWith(writerFields) + const older = yield* makeEntry(1000, "ItemSet", Reader.events.ItemSet.payloadSchemaBinary, { + id: "a", + value: 1 + }) + const skewed = yield* makeEntry(2000, "ItemSet", Writer.events.ItemSet.payloadSchemaBinary, { + id: "a", + value: 2, + ...value + }) + const newer = yield* makeEntry(3000, "ItemSet", Reader.events.ItemSet.payloadSchemaBinary, { + id: "a", + value: 3 + }) + const kept = yield* run(keepLatest(Reader), [older, skewed, newer]) + assert.deepStrictEqual(kept, [skewed, newer], name) + } + })) + + it.effect("folds chunks that grow with the kept set into the entries kept so far", () => + Effect.gen(function*() { + const item = (msecs: number, id: string) => + makeEntry(msecs, "ItemSet", Items.events.ItemSet.payloadSchemaBinary, { id, value: msecs }) + const note = (msecs: number) => + makeEntry(msecs, "NoteSet", Notes.events.NoteSet.payloadSchemaBinary, { id: "a", value: msecs }) + const entries = [ + yield* item(3000, "a"), + // No compactor is registered for this event. + yield* makeEntry(1000, "Observed", Items.events.ItemSet.payloadSchemaBinary, { id: "a", value: 1 }), + // Older than the kept entry for "a", in a later chunk. + yield* item(1000, "a"), + yield* note(1000), + yield* note(2000), + yield* item(500, "b"), + yield* item(2000, "a") + ] + // How many items each call to the opted-in compactor received. + const calls: Array = [] + const kept = yield* run( + Layer.mergeAll( + EventLog.groupBatchCompaction(Items, ({ entries, forward }) => { + calls.push(entries.length) + const latest = new Map() + for (const { entry } of entries) { + const current = latest.get(entry.primaryKey) + if (current === undefined || EventJournal.Entry.Order(current, entry) < 0) { + latest.set(entry.primaryKey, entry) + } + } + return Effect.forEach(latest.values(), forward, { discard: true }) + }, { remote: true }), + keepLatest(Notes, { remote: false }) + ), + entries, + 2 + ) + assert.deepStrictEqual(kept, [entries[0], entries[1], entries[3], entries[4], entries[5]]) + // The chunk is at least 2 entries and at least the kept set: the first + // two chunks hold 2 entries, the third waits for 3, and the last call is + // the pass over the kept set. + assert.deepStrictEqual(calls, [1, 2, 3, 2]) + })) + + it.effect("fails the run when the kept set does not survive another pass", () => + Effect.gen(function*() { + const entries = yield* Effect.forEach([1, 2, 3], (value) => + makeEntry(1000 * value, "ItemSet", Items.events.ItemSet.payloadSchemaBinary, { id: "a", value })) + // Drops the oldest entry of every call, so a second pass drops again. + const dropFirst = EventLog.groupBatchCompaction( + Items, + ({ entries, forward }) => + Effect.forEach(entries.slice(1), ({ entry }) => forward(entry), { discard: true }), + { remote: true } + ) + const error = yield* Effect.flip(run(dropFirst, entries)) + assert.strictEqual(error._tag, "IdempotenceError") + })) + + it.effect("fails the run when a compactor dies", () => + Effect.gen(function*() { + const entry = yield* makeEntry(1000, "ItemSet", Items.events.ItemSet.payloadSchemaBinary, { id: "a", value: 1 }) + const exit = yield* Effect.exit( + run(EventLog.groupBatchCompaction(Items, () => Effect.die("boom"), { remote: true }), [entry]) + ) + assert.isTrue(Exit.hasDies(exit)) + })) +}) diff --git a/packages/effect/test/eventlog/EventLogServerEncrypted.test.ts b/packages/effect/test/eventlog/EventLogServerEncrypted.test.ts index 1723b7452c..948df4a76c 100644 --- a/packages/effect/test/eventlog/EventLogServerEncrypted.test.ts +++ b/packages/effect/test/eventlog/EventLogServerEncrypted.test.ts @@ -1,4 +1,455 @@ +import { assert, it } from "@effect/vitest" +import { Context, Effect, Exit, Layer, Logger, Queue, Redacted, Schema, Stream } from "effect" +import * as SchemaBinary from "effect/encoding/SchemaBinary" +import * as EventJournal from "effect/eventlog/EventJournal" +import * as EventLog from "effect/eventlog/EventLog" +import * as EventLogEncryption from "effect/eventlog/EventLogEncryption" +import * as EventLogMessage from "effect/eventlog/EventLogMessage" import * as EventLogServerEncrypted from "effect/eventlog/EventLogServerEncrypted" +import * as EventLogSessionAuth from "effect/eventlog/EventLogSessionAuth" +import { makeGetIdentityRootSecretMaterial } from "effect/eventlog/internal/identityRootSecretDerivation" +import * as RpcTest from "effect/rpc/RpcTest" +import { TestClock } from "effect/testing" +import * as CompactionTest from "./EventLogServerEncryptedCompactionTest.ts" import * as EncryptedTest from "./EventLogServerEncryptedTest.ts" EncryptedTest.suite("memory", EventLogServerEncrypted.layerStorageMemory) +CompactionTest.suite("memory", EventLogServerEncrypted.layerStorageMemoryWith, Layer.empty) + +it.effect("memory storage fails to start unless grace is longer than the lag and the stage TTL", () => + Effect.gen(function*() { + const start = (compaction: EventLogServerEncrypted.CompactionOptions) => + Effect.exit(Effect.scoped(Layer.build(EventLogServerEncrypted.layerStorageMemoryWith({ compaction })))) + + const exits = [ + yield* start({ grace: "24 hours", lag: "24 hours" }), + yield* start({ grace: "10 minutes", stageTtl: "10 minutes", lag: "1 minute" }), + yield* start({ grace: "25 hours", lag: "24 hours", stageTtl: "24 hours" }) + ] + + assert.deepStrictEqual(exits.map(Exit.isSuccess), [false, false, true]) + })) + +const storeId = EventLogMessage.StoreId.make("store-a") +const hour = 60 * 60_000 +// Long enough for a write's storage hour to pass the default 24 hour lag. +const pastLag = 26 * hour + +// An upload segment is an encoded non-empty array of encrypted batches. +const encodeSegment = Schema.encodeEffect(SchemaBinary.toCodec(Schema.NonEmptyArray(EventLogEncryption.EncryptedBatch))) +const getIdentityRootSecretMaterial = makeGetIdentityRootSecretMaterial(globalThis.crypto) + +type EntryIds = ReadonlyArray + +const makeIds = (count: number) => Array.from({ length: count }, () => EventJournal.makeEntryIdUnsafe()) + +const key = (id: EventJournal.EntryId) => Array.from(id).join(",") + +// The server never decrypts, so a batch only needs its ids and a fresh iv. +const makeBatch = (entryIds: EntryIds): EventLogEncryption.EncryptedBatch => ({ + entryIds: entryIds as [EventJournal.EntryId, ...Array], + iv: globalThis.crypto.getRandomValues(new Uint8Array(12)), + encryptedBatch: new Uint8Array(entryIds.length) +}) + +const started = (result: A) => + result._tag === "Started" ? result as Extract : assert.fail(`got ${result._tag}`) + +const makeServer = Effect.fnUntraced(function*(compaction: EventLogServerEncrypted.CompactionOptions) { + const context = yield* Layer.build( + Layer.provideMerge( + EventLogServerEncrypted.layerRpcHandlers, + EventLogServerEncrypted.layerStorageMemoryWith({ compaction }) + ) + ) + const storage = Context.get(context, EventLogServerEncrypted.Storage) + const identity = yield* EventLog.makeIdentity.pipe(Effect.provide(EventLogEncryption.layerSubtle)) + const scope = { publicKey: identity.publicKey, storeId } + + // Each connection authenticates the same identity. + const connect = Effect.gen(function*() { + const client = yield* RpcTest.makeClient( + EventLogMessage.EventLogRemoteRpcs.merge(EventLogMessage.EventLogCompactionRpcs) + ).pipe(Effect.provide(context)) + const hello = yield* client["EventLog.Hello"]() + const material = yield* getIdentityRootSecretMaterial(identity) + yield* client["EventLog.Authenticate"]( + new EventLogMessage.Authenticate({ + publicKey: identity.publicKey, + signingPublicKey: material.signingPublicKey, + signature: yield* EventLogSessionAuth.signSessionAuthPayload({ + remoteId: hello.remoteId, + challenge: hello.challenge, + publicKey: identity.publicKey, + signingPublicKey: material.signingPublicKey, + signingPrivateKey: Redacted.value(material.signingPrivateKey) + }), + algorithm: "Ed25519" + }) + ) + const write = Effect.fnUntraced(function*(...batches: ReadonlyArray) { + const data = yield* new EventLogMessage.WriteEntries({ ...scope, batches: batches.map(makeBatch) }).encoded + return yield* client["EventLog.WriteSingle"]({ data }) + }) + const commit = ( + stageId: string, + result: { readonly _tag: "Snapshot"; readonly segmentCount: number } | { + readonly _tag: "NoOp" + } + ) => client["EventLog.CompactionCommit"]({ ...scope, stageId, result }) + const upload = Effect.fnUntraced(function*(stageId: string, segments: ReadonlyArray>) { + for (let segment = 0; segment < segments.length; segment++) { + const batches = segments[segment].map(makeBatch) as [ + EventLogEncryption.EncryptedBatch, + ...Array + ] + const data = yield* Effect.orDie(encodeSegment(batches)) + for (const chunk of EventLogMessage.ChunkedMessage.split(segment, data)) { + yield* client["EventLog.CompactionPart"]({ ...scope, stageId, chunk }) + } + } + }) + const snapshot = (stageId: string, segments: ReadonlyArray>) => + Effect.andThen(upload(stageId, segments), commit(stageId, { _tag: "Snapshot", segmentCount: segments.length })) + return { + client, + hello, + write, + commit, + upload, + snapshot, + status: client["EventLog.CompactionStatus"](scope), + begin: client["EventLog.CompactionBegin"](scope), + input: (stageId: string) => client["EventLog.CompactionInput"]({ ...scope, stageId }), + abort: (stageId: string) => client["EventLog.CompactionAbort"]({ ...scope, stageId }), + // Subscribes to changes, returning an effect that takes the next frame's batches. + changes: (startSequence: number) => + client["EventLog.Changes"]({ ...scope, startSequence }, { asQueue: true }).pipe( + Effect.map((queue) => + Queue.take(queue).pipe( + Effect.flatMap((frame) => + frame._tag === "Single" + ? Effect.orDie(EventLogMessage.ChangesRpc.decodeEncrypted(frame.data)) + : Effect.die("expected a single frame") + ) + ) + ) + ) + } + }) + return { storage, scope, connect } +}) + +// Writes A = [e0, e1]@0, [e2, e3]@2, [e4]@4, [e5]@5, then two hours later +// B = [e6, e7, e8, e9]@6, and commits a snapshot keeping e1 and e3 once A +// has passed the lag but B has not, so its base is 5. +const withSnapshot = Effect.fnUntraced(function*(compaction: EventLogServerEncrypted.CompactionOptions) { + const server = yield* makeServer(compaction) + const conn = yield* server.connect + const ids = makeIds(10) + yield* conn.write([ids[0], ids[1]], [ids[2], ids[3]], [ids[4]], [ids[5]]) + yield* TestClock.adjust(2 * hour) + yield* conn.write(ids.slice(6)) + yield* TestClock.adjust(23 * hour) + const { stageId } = started(yield* conn.begin) + const committed = yield* conn.snapshot(stageId, [[[ids[1]], [ids[3]]]]) + const compactionStorage = server.storage.compaction ?? assert.fail("Storage does not provide compaction") + const rollback = Effect.gen(function*() { + const active = (yield* compactionStorage.history(server.scope.publicKey, storeId)).find((a) => a.active)! + yield* compactionStorage.rollback(server.scope.publicKey, storeId, active.activationId) + }) + return { conn, ids, committed, rollback } +}) + +it.effect("isolates pending segment pieces and aborts by store on the same connection", () => + Effect.gen(function*() { + const server = yield* makeServer({ thresholdFloor: 1 }) + const conn = yield* server.connect + const ids = makeIds(2) + yield* conn.write(ids) + yield* TestClock.adjust(pastLag) + const { stageId } = started(yield* conn.begin) + const data = yield* encodeSegment([makeBatch([ids[1]])]) + const split = Math.floor(data.length / 2) + const part = (storeId: EventLogMessage.StoreId, index: number, data: Uint8Array) => + conn.client["EventLog.CompactionPart"]({ + ...server.scope, + storeId, + stageId, + chunk: new EventLogMessage.ChunkedMessage({ id: 0, part: [index, 2], data }) + }) + const otherStore = EventLogMessage.StoreId.make("store-b") + + yield* part(storeId, 0, data.slice(0, split)) + // A foreign scope must not join these junk bytes or clear A's pending piece. + // The server may reject the unknown stage now or when it assembles the segment. + yield* Effect.exit(part(otherStore, 1, new Uint8Array([255]))) + yield* Effect.exit(conn.client["EventLog.CompactionAbort"]({ ...server.scope, storeId: otherStore, stageId })) + yield* part(storeId, 1, data.slice(split)) + + assert.strictEqual(yield* conn.commit(stageId, { _tag: "Snapshot", segmentCount: 1 }), "Committed") + })) + +it.effect("logs snapshot commit counts and the committed and rollback activation ids", () => { + const logs: Array> = [] + return Effect.gen(function*() { + const server = yield* makeServer({ thresholdFloor: 1 }) + const conn = yield* server.connect + const ids = makeIds(3) + yield* conn.write(ids) + yield* TestClock.adjust(pastLag) + const { stageId } = started(yield* conn.begin) + assert.strictEqual(yield* conn.snapshot(stageId, [[[ids[1]]]]), "Committed") + const compaction = server.storage.compaction! + const active = (yield* compaction.history(server.scope.publicKey, storeId)).find((a) => a.active)! + const rollbackId = yield* compaction.rollback(server.scope.publicKey, storeId, active.activationId) + const commitLog = logs.find((log) => log.annotations.activationId === active.activationId) + const rollbackLog = logs.find((log) => log.annotations.activationId === rollbackId) + + assert.isDefined(commitLog) + assert.strictEqual(commitLog!.level, "INFO") + assert.containsSubset(commitLog!.annotations, { + ...server.scope, + keptCount: 1, + through: 2, + activationId: active.activationId + }) + assert.isDefined(rollbackLog) + assert.strictEqual(rollbackLog!.level, "INFO") + assert.containsSubset(rollbackLog!.annotations, { + ...server.scope, + activationId: rollbackId, + withdrawnActivationId: active.activationId, + withdrawnBase: 2, + withdrawnKeptCount: 1, + base: -1, + keptCount: undefined + }) + }).pipe(Effect.provide(Logger.layer([Logger.formatStructured.pipe(Logger.map((log) => { + logs.push(log) + }))]))) +}) + +it.effect("loses the compare-and-swap after a rollback and frees busy on abort", () => + Effect.gen(function*() { + const { committed, conn, ids, rollback } = yield* withSnapshot({ thresholdFloor: 1 }) + + // B passes the lag, so the next input is the snapshot plus B. + yield* TestClock.adjust(2 * hour) + const second = started(yield* conn.begin) + const busy = yield* conn.begin + yield* conn.abort(second.stageId) + const third = started(yield* conn.begin) + yield* rollback + const lost = yield* conn.snapshot(third.stageId, [[[ids[7]]]]) + + assert.isTrue(conn.hello.compaction) + assert.strictEqual(committed, "Committed") + assert.strictEqual(busy._tag, "Busy") + assert.strictEqual(lost, "Superseded") + })) + +it.effect("fails Input with NotFound once the stage's pin was pruned", () => + Effect.gen(function*() { + const { conn, ids, rollback } = yield* withSnapshot({ + grace: "25 hours", + lag: "24 hours", + stageTtl: "24 hours", + thresholdFloor: 1 + }) + const outcome = (stageId: string) => + Stream.runDrain(conn.input(stageId)).pipe(Effect.match({ onFailure: (e) => e.code, onSuccess: () => "ok" })) + + yield* TestClock.adjust(2 * hour) + const { stageId } = started(yield* conn.begin) + yield* rollback + const beforePrune = yield* outcome(stageId) + // A Part keeps the stage open past the withdrawn snapshot's grace. + yield* TestClock.adjust(23 * hour) + yield* conn.upload(stageId, [[[ids[1]]]]) + yield* TestClock.adjust(3 * hour) + const afterPrune = yield* outcome(stageId) + + assert.deepStrictEqual({ beforePrune, afterPrune }, { beforePrune: "ok", afterPrune: "NotFound" }) + })) + +it.effect("rejects a commit whose kept ids are not a non-empty, in-order subsequence of the pinned input", () => + Effect.gen(function*() { + const server = yield* makeServer({ thresholdFloor: 1 }) + const conn = yield* server.connect + const ids = makeIds(7) + yield* conn.write([ids[0], ids[1]], [ids[2], ids[3]], [ids[4]], [ids[5]]) + yield* TestClock.adjust(pastLag) + // Stored after the pin's H. + yield* conn.write([ids[6]]) + + const cases: ReadonlyArray>> = [ + [[[ids[1]], [ids[6]]]], + [[[ids[1]], [ids[1], ids[3]]]], + [[[ids[1], makeIds(1)[0]]]], + [[[ids[3]], [ids[1]]]], + [] + ] + const rejections = yield* Effect.forEach(cases, (segments) => + Effect.gen(function*() { + const { stageId } = started(yield* conn.begin) + const error = yield* Effect.flip(conn.snapshot(stageId, segments)) + yield* conn.abort(stageId) + return error.code + })) + + assert.deepStrictEqual(rejections, [ + "InvalidRequest", + "InvalidRequest", + "InvalidRequest", + "InvalidRequest", + "InvalidRequest" + ]) + })) + +it.effect("accepts kept ids matched to a later occurrence of a repeated input id", () => + Effect.gen(function*() { + const server = yield* makeServer({ thresholdFloor: 1 }) + const conn = yield* server.connect + const [a, b, c] = makeIds(3) + // A partly known batch stores a again, so the input is a@0, b@1, a@2, c@3. + yield* conn.write([a, b]) + yield* conn.write([a, c]) + yield* TestClock.adjust(pastLag) + + const { stageId } = started(yield* conn.begin) + const committed = yield* conn.snapshot(stageId, [[[b], [a], [c]]]) + const served = yield* server.storage.changes(server.scope.publicKey, storeId, 0).pipe( + Stream.take(3), + Stream.runCollect + ) + const sequenceOfA = served.find((batch) => key(batch.entryIds[0]) === key(a))!.sequence + + assert.strictEqual(committed, "Committed") + assert.isAtLeast(sequenceOfA, 2) + })) + +it.effect("answers Begin with NotWanted below the threshold and logs no-ops while backing off multiplicatively", () => { + const logs: Array> = [] + return Effect.gen(function*() { + const server = yield* makeServer({ thresholdFloor: 4 }) + const conn = yield* server.connect + // Commits NoOp for any stage it opens. + const noOps: Array = [] + const begin = Effect.gen(function*() { + const result = yield* conn.begin + if (result._tag === "Started") { + assert.strictEqual(yield* conn.commit(result.stageId, { _tag: "NoOp" }), "Committed") + noOps.push(result.stageId) + } + return result._tag + }) + const writePastLag = Effect.gen(function*() { + yield* conn.write(makeIds(4)) + yield* TestClock.adjust(pastLag) + return yield* begin + }) + + yield* conn.write(makeIds(6)) + const results = [yield* begin] + yield* TestClock.adjust(pastLag) + // H = 5, then 9 (4 past the first no-op), 13 and 17 (8 past the second). + results.push(yield* begin, yield* begin, yield* writePastLag, yield* writePastLag, yield* writePastLag) + + assert.deepStrictEqual(results, ["NotWanted", "Started", "NotWanted", "Started", "NotWanted", "Started"]) + for (const [index, stageId] of noOps.entries()) { + const stageLogs = logs.filter((log) => log.annotations.stageId === stageId && log.level === "INFO") + assert.lengthOf(stageLogs, 1, "NoOp commit must emit exactly one audit record per stage") + assert.containsSubset(stageLogs[0].annotations, { ...server.scope, stageId, through: [5, 9, 17][index] }) + } + }).pipe(Effect.provide(Logger.layer([Logger.formatStructured.pipe(Logger.map((log) => { + logs.push(log) + }))]))) +}) + +it.effect("keeps activation off live changes and omits acks for re-uploads at or below the base", () => + Effect.gen(function*() { + const server = yield* makeServer({ thresholdFloor: 1 }) + const writer = yield* server.connect + const reader = yield* server.connect + const ids = makeIds(8) + yield* writer.write([ids[0], ids[1]], [ids[2], ids[3]], [ids[4]], [ids[5]]) + yield* TestClock.adjust(pastLag) + yield* writer.write([ids[6]]) + const next = yield* reader.changes(6) + const caughtUp = yield* next + + const { stageId } = started(yield* writer.begin) + const committed = yield* writer.snapshot(stageId, [[[ids[1]], [ids[3]]]]) + // e0 was dropped and e6 is in the tail. + const acks = yield* writer.write([ids[0]], [ids[6]]) + yield* writer.write([ids[7]]) + const live = yield* next + + const summarize = (batches: ReadonlyArray) => + batches.map((batch) => ({ sequence: batch.sequence, entryIds: batch.entryIds.map(key) })) + assert.deepStrictEqual(summarize(caughtUp), [{ sequence: 6, entryIds: [key(ids[6])] }]) + assert.strictEqual(committed, "Committed") + assert.deepStrictEqual(acks.map((ack) => ({ entryId: key(ack.entryId), sequence: ack.sequence })), [ + { entryId: key(ids[6]), sequence: 6 } + ]) + assert.deepStrictEqual(summarize(live), [{ sequence: 7, entryIds: [key(ids[7])] }]) + })) + +it.effect.prop( + "places every snapshot entry at or after its input sequence and at or below the base, without overlap", + { + // Each input batch, as whether each of its entries is kept. + input: Schema.Array(Schema.Array(Schema.Boolean).check(Schema.isMinLength(1), Schema.isMaxLength(4))).check( + Schema.isMinLength(1), + Schema.isMaxLength(6) + ), + // Sizes of the snapshot batches, cycled over the kept entries. + batchSizes: Schema.Array(Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 3 }))).check( + Schema.isMinLength(1), + Schema.isMaxLength(4) + ) + }, + Effect.fnUntraced( + function*({ batchSizes, input }) { + const server = yield* makeServer({ thresholdFloor: 1 }) + const conn = yield* server.connect + const batches = input.map((flags) => flags.map(() => EventJournal.makeEntryIdUnsafe())) + const ids = batches.flat() + const flags = input.flat() + const kept = ids.filter((_, i) => flags[i]) + if (kept.length === 0) return + const firstSequence = conn.hello.firstSequence ?? 0 + const inputSequence = new Map(ids.map((id, i) => [key(id), firstSequence + i])) + const base = firstSequence + ids.length - 1 + const snapshotBatches: Array = [] + for (let i = 0, b = 0; i < kept.length; b++) { + const size = batchSizes[b % batchSizes.length] + snapshotBatches.push(kept.slice(i, i + size)) + i += size + } + + yield* conn.write(...batches) + yield* TestClock.adjust(pastLag) + const { stageId } = started(yield* conn.begin) + yield* conn.snapshot(stageId, [snapshotBatches]) + const served = yield* server.storage.changes(server.scope.publicKey, storeId, firstSequence).pipe( + Stream.take(snapshotBatches.length), + Stream.runCollect + ) + + let previousLast = firstSequence - 1 + for (const batch of served) { + assert.isAbove(batch.sequence, previousLast) + batch.entryIds.forEach((id, i) => { + assert.isAtLeast(batch.sequence + i, inputSequence.get(key(id))!) + assert.isAtMost(batch.sequence + i, base) + }) + previousLast = batch.sequence + batch.entryIds.length - 1 + } + assert.deepStrictEqual(served.flatMap((batch) => batch.entryIds.map(key)), kept.map(key)) + }, + Effect.scoped + ), + { arbitrary: { runs: 50 } } +) diff --git a/packages/effect/test/eventlog/EventLogServerEncryptedCompactionTest.ts b/packages/effect/test/eventlog/EventLogServerEncryptedCompactionTest.ts new file mode 100644 index 0000000000..c743b88841 --- /dev/null +++ b/packages/effect/test/eventlog/EventLogServerEncryptedCompactionTest.ts @@ -0,0 +1,351 @@ +import { assert, it } from "@effect/vitest" +import { Clock, Effect, Exit, Fiber, Layer, Stream } from "effect" +import * as EventJournal from "effect/eventlog/EventJournal" +import type * as EventLogEncryption from "effect/eventlog/EventLogEncryption" +import * as EventLogMessage from "effect/eventlog/EventLogMessage" +import * as EventLogServerEncrypted from "effect/eventlog/EventLogServerEncrypted" +import { TestClock } from "effect/testing" + +const storeId = EventLogMessage.StoreId.make("store-a") +const minute = 60_000 +const hour = 60 * minute +const day = 24 * hour + +// `marker` identifies the stored bytes, so a test can tell a snapshot batch +// from the original holding the same ids. +const makeBatch = (marker: number, ...entryIds: Array): EventLogEncryption.EncryptedBatch => ({ + entryIds: entryIds as [EventJournal.EntryId, ...Array], + iv: new Uint8Array(12), + encryptedBatch: Uint8Array.of(marker) +}) + +const makeIds = (count: number) => Array.from({ length: count }, () => EventJournal.makeEntryIdUnsafe()) + +const key = (id: EventJournal.EntryId) => Array.from(id).join(",") + +const summarize = ( + batches: ReadonlyArray<{ + readonly sequence: number + readonly entryIds: ReadonlyArray + readonly encryptedBatch?: Uint8Array + }> +) => + batches.map((batch) => ({ + sequence: batch.sequence, + entryIds: batch.entryIds.map(key), + marker: batch.encryptedBatch?.[0] + })) + +const header = (sequence: number, entryIds: ReadonlyArray, marker?: number) => ({ + sequence, + entryIds: entryIds.map(key), + marker +}) + +const started = (result: EventLogServerEncrypted.CompactionBeginResult) => + result._tag === "Started" ? result : assert.fail(`expected Started, got ${result._tag}`) + +// A store holding [e0, e1] at 0, [e2, e3] at 2, [e4] at 4 and [e5] at 5, +// counted from the storage's first sequence by `seq`. +const makeStore = Effect.gen(function*() { + const storage = yield* EventLogServerEncrypted.Storage + const compaction = storage.compaction ?? assert.fail("Storage does not provide compaction") + const first = storage.firstSequence ?? 0 + const seq = (offset: number) => first + offset + const publicKey = crypto.randomUUID() + const ids = makeIds(6) + yield* storage.write(publicKey, storeId, [ + makeBatch(0, ids[0], ids[1]), + makeBatch(2, ids[2], ids[3]), + makeBatch(4, ids[4]), + makeBatch(5, ids[5]) + ]) + const changes = (startSequence: number, count: number) => + storage.changes(publicKey, storeId, seq(startSequence)).pipe(Stream.take(count), Stream.runCollect) + // Keeps e1, e3 and e4 of the input through 4, as [e1] ending at its input + // sequence 1 and [e3, e4] ending at the base. + const commitSnapshot = Effect.gen(function*() { + const { stageId } = started(yield* compaction.begin(publicKey, storeId, { through: seq(4) })) + yield* compaction.stagePart(publicKey, storeId, stageId, 0, [makeBatch(11, ids[1]), makeBatch(13, ids[3], ids[4])]) + return yield* compaction.commit(publicKey, storeId, stageId, [seq(1), seq(3)]) + }) + return { compaction, publicKey, ids, changes, commitSnapshot, seq } +}) + +// Reads a stream, reporting the error tag it fails with or how many items it held. +const outcome = (stream: Stream.Stream) => + Stream.runCollect(stream).pipe( + Effect.match({ onFailure: (error) => error._tag, onSuccess: (items) => `${items.length} items` }) + ) + +// A sweep that waits on I/O can finish after `TestClock.adjust` returns, so a +// read that depends on it retries for a while on the live clock. +const eventually = Effect.fnUntraced(function*(read: Effect.Effect, done: (value: A) => boolean) { + for (let attempt = 0; attempt < 200; attempt++) { + const value = yield* read + if (done(value)) return value + yield* TestClock.withLive(Effect.sleep(10)) + } + return yield* read +}) + +// The tests share one TestClock, so they run one at a time. A test that needs +// its own config or sweep schedule provides a fresh storage from `storage`, +// built on the same `dependencies` as the shared one. +export const suite = ( + name: string, + storage: (options: { + readonly compaction?: EventLogServerEncrypted.CompactionOptions | undefined + }) => Layer.Layer, + dependencies: Layer.Layer +) => + it.layer( + Layer.provideMerge( + storage({}), + // Client connection deadlines use real time; storage and sweeps use TestClock. + Layer.provide(dependencies, Layer.succeed(Clock.Clock)(Clock.Clock.defaultValue())) + ), + { concurrent: false, timeout: "60 seconds" } + )( + `Encrypted compaction storage (${name})`, + (it) => { + it.effect("slides a stage's claim on each Part and rejects a stale Part after a steal", () => + Effect.gen(function*() { + const { compaction, ids, publicKey, seq } = yield* makeStore + const begunAt = yield* Clock.currentTimeMillis + const first = started(yield* compaction.begin(publicKey, storeId, { through: seq(1) })) + + yield* TestClock.adjust(5 * minute) + yield* compaction.stagePart(publicKey, storeId, first.stageId, 0, [makeBatch(11, ids[1])]) + yield* TestClock.adjust(6 * minute) + const busy = yield* compaction.begin(publicKey, storeId, { through: seq(1) }) + yield* TestClock.adjust(5 * minute) + const second = started(yield* compaction.begin(publicKey, storeId, { through: seq(1) })) + const stale = yield* compaction.stagePart(publicKey, storeId, first.stageId, 1, [makeBatch(10, ids[0])]).pipe( + Effect.flip + ) + + assert.deepStrictEqual(busy, { _tag: "Busy", expiresAt: begunAt + 15 * minute }) + assert.notStrictEqual(second.stageId, first.stageId) + assert.strictEqual(stale._tag, "CompactionNotFound") + })) + + it.effect("acknowledges a retried segment without staging it twice", () => + Effect.gen(function*() { + const { compaction, ids, publicKey, seq } = yield* makeStore + const { stageId } = started(yield* compaction.begin(publicKey, storeId, { through: seq(4) })) + const part = [makeBatch(11, ids[1])] as const + + const results = [ + yield* compaction.stagePart(publicKey, storeId, stageId, 0, part), + yield* compaction.stagePart(publicKey, storeId, stageId, 0, part) + ] + const staged = yield* Stream.runCollect(compaction.stagedHeaders(publicKey, storeId, stageId)) + + assert.deepStrictEqual(results, ["Stored", "AlreadyStored"]) + assert.deepStrictEqual(staged.map((header) => header.entryIds), [[ids[1]]]) + })) + + it.effect("releases the claim on abort and no-op, and clears the no-op state on commit", () => + Effect.gen(function*() { + const { compaction, ids, publicKey, seq } = yield* makeStore + const aborted = started(yield* compaction.begin(publicKey, storeId, { through: seq(4) })) + yield* compaction.abort(publicKey, storeId, aborted.stageId) + const noOp = started(yield* compaction.begin(publicKey, storeId, { through: seq(4) })) + yield* compaction.recordNoOp(publicKey, storeId, noOp.stageId) + const afterNoOp = (yield* compaction.status(publicKey, storeId)).noOp + const { stageId } = started(yield* compaction.begin(publicKey, storeId, { through: seq(4) })) + yield* compaction.stagePart(publicKey, storeId, stageId, 0, [makeBatch(11, ids[1])]) + const commit = yield* compaction.commit(publicKey, storeId, stageId, [seq(1)]) + const afterCommit = (yield* compaction.status(publicKey, storeId)).noOp + + assert.deepStrictEqual(afterNoOp, { at: seq(4), count: 1 }) + assert.strictEqual(commit, "Committed") + assert.strictEqual(afterCommit, undefined) + })) + + it.effect("reports as the lag head the last sequence of each storage hour once it ended a lag ago", () => + Effect.gen(function*() { + const now = yield* Clock.currentTimeMillis + // 30 minutes into an hour, so the store's first writes share it. + yield* TestClock.adjust(hour - (now % hour) + 30 * minute) + const { compaction, publicKey, seq } = yield* makeStore + const storage = yield* EventLogServerEncrypted.Storage + yield* TestClock.adjust(hour) + yield* storage.write(publicKey, storeId, [makeBatch(6, ...makeIds(1))]) + const lagHead = Effect.map(compaction.status(publicKey, storeId), (status) => status.lagHead) + + // 30 minutes into the second hour: the first hour passes the lag in + // 23 hours and 30 minutes. + yield* TestClock.adjust(23 * hour + 29 * minute) + const beforeFirst = yield* lagHead + yield* TestClock.adjust(2 * minute) + const afterFirst = yield* lagHead + yield* TestClock.adjust(hour - 2 * minute) + const beforeSecond = yield* lagHead + yield* TestClock.adjust(2 * minute) + const afterSecond = yield* lagHead + + assert.deepStrictEqual( + { beforeFirst, afterFirst, beforeSecond, afterSecond }, + { beforeFirst: seq(-1), afterFirst: seq(5), beforeSecond: seq(5), afterSecond: seq(6) } + ) + })) + + it.effect("fails reads of an expired stage before the sweep closes it", () => + Effect.gen(function*() { + const { compaction, publicKey, seq } = yield* makeStore + const { stageId } = started(yield* compaction.begin(publicKey, storeId, { through: seq(4) })) + + // Past the 10 minute stage TTL, well before the hourly sweep. + yield* TestClock.adjust(11 * minute) + const reads = [ + yield* outcome(compaction.inputHeaders(publicKey, storeId, stageId)), + yield* outcome(compaction.fetch(publicKey, storeId, stageId, [seq(0)])), + yield* outcome(compaction.stagedHeaders(publicKey, storeId, stageId)) + ] + + assert.deepStrictEqual(reads, ["CompactionNotFound", "CompactionNotFound", "CompactionNotFound"]) + }).pipe(Effect.provide(storage({})))) + + it.effect("fails an Input or Fetch read again after its stage's pin was pruned", () => + Effect.gen(function*() { + const { commitSnapshot, compaction, ids, publicKey, seq } = yield* makeStore + yield* commitSnapshot + const { stageId } = started(yield* compaction.begin(publicKey, storeId, { through: seq(5) })) + const active = (yield* compaction.history(publicKey, storeId)).find((activation) => activation.active)! + yield* compaction.rollback(publicKey, storeId, active.activationId) + const input = compaction.inputHeaders(publicKey, storeId, stageId) + const fetch = compaction.fetch(publicKey, storeId, stageId, [seq(1), seq(3), seq(5)]) + const beforePrune = [yield* outcome(input), yield* outcome(fetch)] + + // A Part keeps the stage alive past the withdrawn snapshot's grace. + yield* TestClock.adjust(23 * hour) + yield* compaction.stagePart(publicKey, storeId, stageId, 0, [makeBatch(11, ids[1])]) + yield* TestClock.adjust(3 * hour) + const afterPrune = [ + yield* eventually(outcome(input), (result) => result === "CompactionNotFound"), + yield* outcome(fetch) + ] + + assert.deepStrictEqual(beforePrune, ["3 items", "3 items"]) + assert.deepStrictEqual(afterPrune, ["CompactionNotFound", "CompactionNotFound"]) + }).pipe(Effect.provide(storage({ compaction: { grace: "25 hours", lag: "24 hours", stageTtl: "24 hours" } })))) + + it.effect("serves the snapshot at or below the base and the originals above it", () => + Effect.gen(function*() { + const { changes, commitSnapshot, compaction, ids, publicKey, seq } = yield* makeStore + assert.strictEqual(yield* commitSnapshot, "Committed") + + const fromBelow = yield* changes(0, 3) + const fromInside = yield* changes(2, 2) + const fromAbove = yield* changes(5, 1) + const { stageId } = started(yield* compaction.begin(publicKey, storeId, { through: seq(5) })) + const input = yield* Stream.runCollect(compaction.inputHeaders(publicKey, storeId, stageId)) + const fetched = yield* Stream.runCollect(compaction.fetch(publicKey, storeId, stageId, [seq(3), seq(5)])) + + const snapshotFirst = header(seq(1), [ids[1]], 11) + const snapshotSecond = header(seq(3), [ids[3], ids[4]], 13) + const tail = header(seq(5), [ids[5]], 5) + assert.deepStrictEqual(summarize(fromBelow), [snapshotFirst, snapshotSecond, tail]) + assert.deepStrictEqual(summarize(fromInside), [snapshotSecond, tail]) + assert.deepStrictEqual(summarize(fromAbove), [tail]) + assert.deepStrictEqual(summarize(input), [ + header(seq(1), [ids[1]]), + header(seq(3), [ids[3], ids[4]]), + header(seq(5), [ids[5]]) + ]) + assert.deepStrictEqual(summarize(fetched), [snapshotSecond, tail]) + })) + + it.effect("fails changes when the active snapshot has no rows", () => + Effect.gen(function*() { + const { changes, compaction, publicKey, seq } = yield* makeStore + const { stageId } = started(yield* compaction.begin(publicKey, storeId, { through: seq(4) })) + yield* compaction.commit(publicKey, storeId, stageId, []) + + const exit = yield* Effect.exit(changes(0, 1)) + + assert.isTrue(Exit.isFailure(exit)) + })) + + it.effect("rolls back to the originals within grace, and the sweep leaves them", () => + Effect.gen(function*() { + const { changes, commitSnapshot, compaction, ids, publicKey, seq } = yield* makeStore + yield* commitSnapshot + yield* TestClock.adjust(29 * day) + const pinned = started(yield* compaction.begin(publicKey, storeId, { through: seq(5) })) + const active = (yield* compaction.history(publicKey, storeId)).find((activation) => activation.active)! + + yield* compaction.rollback(publicKey, storeId, active.activationId) + const commit = yield* compaction.commit(publicKey, storeId, pinned.stageId, []) + const status = yield* compaction.status(publicKey, storeId) + yield* TestClock.adjust(2 * day) + const served = yield* changes(0, 4) + + assert.strictEqual(commit, "Superseded") + assert.strictEqual(status.base, seq(-1)) + assert.deepStrictEqual(summarize(served), [ + header(seq(0), [ids[0], ids[1]], 0), + header(seq(2), [ids[2], ids[3]], 2), + header(seq(4), [ids[4]], 4), + header(seq(5), [ids[5]], 5) + ]) + })) + + it.effect("re-appends the withdrawn snapshot's input on rollback, so its readers end with every entry", () => + Effect.gen(function*() { + const { changes, commitSnapshot, compaction, ids, publicKey, seq } = yield* makeStore + const storage = yield* EventLogServerEncrypted.Storage + yield* commitSnapshot + const [sentinel] = makeIds(1) + const all = [...ids, sentinel].map(key) + // Follows changes until the sentinel, written after the rollback, arrives. + const follow = (startSequence: number, received: Array) => + storage.changes(publicKey, storeId, startSequence).pipe( + Stream.tap((batch) => Effect.sync(() => received.push(...batch.entryIds.map(key)))), + Stream.takeUntil((batch) => batch.entryIds.some((id) => key(id) === key(sentinel))), + Stream.runDrain + ) + // One reader has read the whole snapshot, [e1] [e3, e4] [e5], and stays subscribed. + const whole: Array = [] + const wholeFiber = yield* Effect.forkChild(follow(seq(0), whole)) + const beforeRollback = yield* eventually(Effect.sync(() => [...whole]), (read) => read.length === 4) + // The other stopped after the snapshot's first batch. + const [first] = yield* changes(0, 1) + const partway = first.entryIds.map(key) + + const active = (yield* compaction.history(publicKey, storeId)).find((activation) => activation.active)! + yield* compaction.rollback(publicKey, storeId, active.activationId) + yield* storage.write(publicKey, storeId, [makeBatch(6, sentinel)]) + yield* follow(first.sequence + first.entryIds.length, partway) + yield* Fiber.join(wholeFiber) + + assert.sameMembers(beforeRollback, [ids[1], ids[3], ids[4], ids[5]].map(key)) + assert.sameMembers([...new Set(whole)], all) + assert.sameMembers([...new Set(partway)], all) + })) + + it.effect("prunes the superseded originals after grace and then refuses to roll back to them", () => + Effect.gen(function*() { + const { changes, commitSnapshot, compaction, publicKey, seq } = yield* makeStore + yield* commitSnapshot + const [originals, snapshot] = yield* compaction.history(publicKey, storeId) + + yield* TestClock.adjust(30 * day - minute) + const beforeGrace = (yield* compaction.history(publicKey, storeId))[0].restorable + yield* TestClock.adjust(2 * hour) + const afterGrace = yield* eventually( + Effect.map(compaction.history(publicKey, storeId), (history) => history[0].restorable), + (restorable) => !restorable + ) + const rollback = yield* compaction.rollback(publicKey, storeId, snapshot.activationId).pipe(Effect.flip) + const served = yield* changes(0, 3) + + assert.deepStrictEqual({ base: originals.base, active: originals.active }, { base: seq(-1), active: false }) + assert.deepStrictEqual({ beforeGrace, afterGrace }, { beforeGrace: true, afterGrace: false }) + assert.deepStrictEqual(rollback.reason, "PruneStarted") + assert.deepStrictEqual(summarize(served).map((batch) => batch.marker), [11, 13, 5]) + })) + } + ) diff --git a/packages/effect/test/eventlog/EventRow.test.ts b/packages/effect/test/eventlog/EventRow.test.ts index a73b01b038..f9f982bdb1 100644 --- a/packages/effect/test/eventlog/EventRow.test.ts +++ b/packages/effect/test/eventlog/EventRow.test.ts @@ -137,6 +137,43 @@ const toPayload = (op: typeof Op.Type): Payload => { } } +// An entry to compact. `rank` picks its position in a shuffled batch. +const Draft = Schema.Struct({ + msecs: Schema.Int.check(Schema.isBetween({ minimum: 0, maximum: 3 })), + rank: Schema.Int, + op: Op +}) +const Drafts = Schema.Array(Draft).check(Schema.isMaxLength(8)) + +const toEntries = (drafts: ReadonlyArray) => + Effect.forEach(drafts, ({ msecs, op }) => + Effect.map( + Schema.encodeUnknownEffect(Groceries.events.grocery.payloadSchemaBinary)(toPayload(op)), + (payload) => + new EventJournal.Entry({ + id: EventJournal.makeEntryIdUnsafe({ msecs: 1000 + msecs }), + event: "grocery", + primaryKey: op.key, + payload + }, { disableChecks: true }) + )) + +// Gives the ids `EventRow.compaction` keeps from a batch. +const makeDrop = Effect.fnUntraced(function*() { + const registry = yield* EventLog.Registry + yield* Layer.build( + EventRow.compaction(Groceries, Grocery).pipe(Layer.provide(Layer.succeed(EventLog.Registry, registry))) + ) + const compactor = registry.compactors.get("grocery")! + return Effect.fnUntraced(function*(entries: ReadonlyArray) { + const kept: Array = [] + yield* compactor.effect({ entries, write: (entry) => Effect.sync(() => kept.push(entry)) }) + return kept + }) +}) + +const ids = (entries: ReadonlyArray) => entries.map((entry) => entry.idString).sort() + type Replica = Effect.Success> // An `EventLog` on a memory journal whose storage is a map of rows, fed by a @@ -317,6 +354,7 @@ describe("EventRow", () => { yield* register(EventRow.compaction(group, Other)) assert.deepStrictEqual([...registry.compactors.get("grocery")!.events], ["grocery"]) assert.deepStrictEqual([...registry.compactors.get("other")!.events], ["other"]) + assert.isTrue(registry.compactors.get("grocery")!.remote) type Input = readonly ["grocery" | "other", Payload] const cases: ReadonlyArray, ReadonlyArray]> = [ @@ -524,6 +562,39 @@ describe("EventRow", () => { assert.isTrue(Exit.isFailure(none)) })) + it.effect.prop( + "compaction composes, including with older entries", + { a: Drafts, b: Drafts }, + Effect.fnUntraced( + function*({ a, b }) { + const drop = yield* makeDrop() + const older = yield* toEntries(a) + const later = yield* toEntries(b) + assert.deepStrictEqual( + ids(yield* drop([...(yield* drop(older)), ...later])), + ids(yield* drop([...older, ...later])) + ) + }, + Effect.scoped, + Effect.provide(EventLog.layerRegistry) + ) + ) + + it.effect.prop( + "compaction is independent of input order", + { drafts: Drafts }, + Effect.fnUntraced( + function*({ drafts }) { + const drop = yield* makeDrop() + const entries = yield* toEntries(drafts) + const shuffled = entries.map((entry, i) => [drafts[i].rank, entry] as const).sort(([x], [y]) => x - y) + assert.deepStrictEqual(ids(yield* drop(shuffled.map(([, entry]) => entry))), ids(yield* drop(entries))) + }, + Effect.scoped, + Effect.provide(EventLog.layerRegistry) + ) + ) + it.effect.prop( "replicas converge to the fold of every entry in id order", { commands: Schema.Array(Command).check(Schema.isMaxLength(24)) }, diff --git a/packages/effect/test/eventlog/SqlEventLogServerEncryptedStorageTest.ts b/packages/effect/test/eventlog/SqlEventLogServerEncryptedStorageTest.ts index 6c041db88c..45561eda9e 100644 --- a/packages/effect/test/eventlog/SqlEventLogServerEncryptedStorageTest.ts +++ b/packages/effect/test/eventlog/SqlEventLogServerEncryptedStorageTest.ts @@ -1,12 +1,15 @@ import { assert, it } from "@effect/vitest" -import { Deferred, Effect, Exit, Fiber, Layer, Stream } from "effect" +import { Array as Arr, Clock, Deferred, Effect, Exit, Fiber, Layer, Scope, Stream } from "effect" import * as Digest from "effect/crypto/Digest" import * as EventJournal from "effect/eventlog/EventJournal" import * as EventLogEncryption from "effect/eventlog/EventLogEncryption" import type { StoreId } from "effect/eventlog/EventLogMessage" +import type * as EventLogServerEncrypted from "effect/eventlog/EventLogServerEncrypted" import * as SqlEventLogServerEncrypted from "effect/eventlog/SqlEventLogServerEncrypted" import { Reactivity } from "effect/reactivity" import * as SqlClient from "effect/sql/SqlClient" +import * as Statement from "effect/sql/Statement" +import { TestClock } from "effect/testing" const storeId = "store-a" as StoreId let nextNamespace = 0 @@ -139,3 +142,504 @@ export const suite = (name: string, layer: Layer.Layer Array.from({ length: count }, () => EventJournal.makeEntryIdUnsafe()) + +// Every compaction test gets its own tables, the global ones included, so +// stores and sweeps from other tests stay out of its way. +const makeNamespace = Effect.fnUntraced(function*(compaction?: EventLogServerEncrypted.CompactionOptions) { + const digest = yield* Digest.Digest + const publicKey = crypto.randomUUID() + const namespace = `compaction_${++nextNamespace}` + const entryTablePrefix = `${namespace}_events` + const scopeHash = (yield* digest.digestHex(Digest.sha256, new TextEncoder().encode(`${publicKey}/${storeId}`))) + .slice(0, 16) + return { + publicKey, + options: { entryTablePrefix, remoteIdTable: `${namespace}_remote_id`, compaction }, + // The scope's batch table `T`, named as every version of the storage names it. + table: `${entryTablePrefix}_${scopeHash}` + } +}) + +// `T` and `T_ids` as the storage created them before compaction. +const createLegacyTables = Effect.fnUntraced(function*(table: string) { + const sql = yield* SqlClient.SqlClient + const tableSql = sql(table) + const idsTableSql = sql(`${table}_ids`) + const indexSql = sql(`${table}_last_sequence`) + yield* sql.onDialectOrElse({ + pg: () => + sql` + CREATE TABLE ${tableSql} ( + sequence INTEGER PRIMARY KEY, + last_sequence INTEGER NOT NULL, + iv BYTEA NOT NULL, + entry_ids BYTEA NOT NULL, + encrypted_batch BYTEA NOT NULL + )`.pipe( + Effect.andThen(sql`CREATE INDEX ${indexSql} ON ${tableSql} (last_sequence)`), + Effect.andThen(sql`CREATE TABLE ${idsTableSql} (entry_id BYTEA PRIMARY KEY, sequence INTEGER NOT NULL)`) + ), + mysql: () => + sql` + CREATE TABLE ${tableSql} ( + sequence INT PRIMARY KEY, + last_sequence INT NOT NULL, + iv BINARY(12) NOT NULL, + entry_ids LONGBLOB NOT NULL, + encrypted_batch LONGBLOB NOT NULL, + INDEX (last_sequence) + )`.pipe( + Effect.andThen(sql`CREATE TABLE ${idsTableSql} (entry_id BINARY(16) PRIMARY KEY, sequence INT NOT NULL)`) + ), + mssql: () => + sql` + CREATE TABLE ${tableSql} ( + sequence INT PRIMARY KEY, + last_sequence INT NOT NULL, + iv VARBINARY(12) NOT NULL, + entry_ids VARBINARY(MAX) NOT NULL, + encrypted_batch VARBINARY(MAX) NOT NULL, + INDEX ${indexSql} NONCLUSTERED (last_sequence) + )`.pipe( + Effect.andThen(sql`CREATE TABLE ${idsTableSql} (entry_id VARBINARY(16) PRIMARY KEY, sequence INT NOT NULL)`) + ), + orElse: () => + sql` + CREATE TABLE ${tableSql} ( + sequence INTEGER PRIMARY KEY, + last_sequence INTEGER NOT NULL, + iv BLOB NOT NULL, + entry_ids BLOB NOT NULL, + encrypted_batch BLOB NOT NULL + )`.pipe( + Effect.andThen(sql`CREATE INDEX ${indexSql} ON ${tableSql} (last_sequence)`), + Effect.andThen(sql`CREATE TABLE ${idsTableSql} (entry_id BLOB PRIMARY KEY, sequence INTEGER NOT NULL)`) + ) + }) +}) + +// Writes a batch of new ids as an instance from before compaction does, at +// MAX(last_sequence) + 1 and without touching the store row or the buckets. +const legacyWrite = Effect.fnUntraced(function*(table: string, batch: EventLogEncryption.EncryptedBatch) { + const sql = yield* SqlClient.SqlClient + return yield* sql.withTransaction(Effect.gen(function*() { + const [last] = yield* sql<{ last_sequence: number | string | null }>` + SELECT MAX(last_sequence) AS last_sequence FROM ${sql(table)} + ` + const sequence = Number(last?.last_sequence ?? 0) + 1 + yield* sql`INSERT INTO ${sql(`${table}_ids`)} ${ + sql.insert(Arr.map(batch.entryIds, (entry_id, i) => ({ entry_id, sequence: sequence + i }))) + }` + yield* sql`INSERT INTO ${sql(table)} ${ + sql.insert({ + sequence, + last_sequence: sequence + batch.entryIds.length - 1, + iv: batch.iv, + entry_ids: new Uint8Array(batch.entryIds.flatMap((id) => Array.from(id))), + encrypted_batch: batch.encryptedBatch + }) + }` + return sequence + })) +}) + +const countRows = Effect.fnUntraced(function*(table: string) { + const sql = yield* SqlClient.SqlClient + const [row] = yield* sql<{ n: number | string }>`SELECT COUNT(*) AS n FROM ${sql(table)}` + return Number(row.n) +}) + +// Advances the clock an hour at a time until `done` holds. A sweep the clock +// wakes finishes its queries in real time, so each hour polls on the live clock. +const sweepUntil = Effect.fnUntraced(function*(read: Effect.Effect, done: (value: A) => boolean) { + for (let hour = 0; hour < 24; hour++) { + yield* TestClock.adjust("1 hour") + for (let attempt = 0; attempt < 50; attempt++) { + const value = yield* read + if (done(value)) return value + yield* TestClock.withLive(Effect.sleep(10)) + } + } + return yield* read +}) + +const snapshotMarker = 99 + +// Commits a snapshot of the whole store that keeps only `kept`, as one batch +// ending at the base. +const commitSnapshot = Effect.fnUntraced(function*( + storage: EventLogServerEncrypted.Storage["Service"], + publicKey: string, + kept: EventJournal.EntryId +) { + const compaction = storage.compaction ?? assert.fail("Storage does not provide compaction") + const { head } = yield* compaction.status(publicKey, storeId) + const begun = yield* compaction.begin(publicKey, storeId, { through: head }) + if (begun._tag !== "Started") return assert.fail(`expected Started, got ${begun._tag}`) + yield* compaction.stagePart(publicKey, storeId, begun.stageId, 0, [{ + entryIds: [kept], + iv: new Uint8Array(12), + encryptedBatch: Uint8Array.of(snapshotMarker) + }]) + return yield* compaction.commit(publicKey, storeId, begun.stageId, [head]) +}) + +// Hangs the selected statement that deletes from `table`, as a sweeper whose +// process dies mid-prune, and signals that it got there. +const hangOnDelete = (table: string, reached: Deferred.Deferred, deleteNumber = 1): Statement.Transformer => { + let deletes = 0 + return (statement, sql) => { + const [text] = statement.compile() + const [target] = sql`${sql(table)}`.compile() + if (!/\bDELETE\b/i.test(text) || !text.includes(target) || ++deletes !== deleteNumber) { + return Effect.succeed(statement) + } + return Effect.andThen(Deferred.succeed(reached, undefined), Effect.never) + } +} + +const served = (batches: ReadonlyArray) => + batches.map((batch) => ({ sequence: batch.sequence, marker: batch.encryptedBatch[0] })) + +// Follows `changes` from `startSequence` up to the batch carrying `last`, +// returning once the live subscription is open. +const followChanges = Effect.fnUntraced(function*( + storage: EventLogServerEncrypted.Storage["Service"], + publicKey: string, + startSequence: number, + last: EventJournal.EntryId +) { + const subscribed = yield* Deferred.make() + const lastKey = Array.from(last).join(",") + const fiber = yield* storage.changes(publicKey, storeId, startSequence).pipe( + Stream.tap(() => Deferred.succeed(subscribed, undefined)), + Stream.takeUntil((batch) => ids([batch])[0].includes(lastKey)), + Stream.runCollect, + Effect.forkChild + ) + // The first batch comes from the initial query, which runs after subscribing. + yield* Deferred.await(subscribed) + return fiber +}) + +// SQL-only compaction scenarios, run under the TestClock. +export const compactionSuite = (name: string, layer: Layer.Layer) => + it.layer( + Layer.mergeAll( + Reactivity.layer, + EventLogEncryption.layerSubtle, + Digest.layerWebCrypto, + // Only the SQL client uses real time; storage still observes TestClock. + Layer.provide(layer, Layer.succeed(Clock.Clock)(Clock.Clock.defaultValue())) + ), + // Tests share TestClock, so advancing one must not expire another test's stage. + { concurrent: false, timeout: "60 seconds" } + )(`SqlEventLogServerEncrypted compaction storage (${name})`, (it) => { + it.effect("seeds a store written before the upgrade once when two instances open it together", () => + Effect.gen(function*() { + const { options, publicKey, table } = yield* makeNamespace() + const entries = makeIds(4) + yield* createLegacyTables(table) + yield* legacyWrite(table, makeBatch(entries[0], entries[1])) + const legacyLast = yield* legacyWrite(table, makeBatch(entries[2])) + // Startup creates the global tables, so only opening the store races. + const storageA = yield* SqlEventLogServerEncrypted.makeStorage(options) + const storageB = yield* SqlEventLogServerEncrypted.makeStorage(options) + const nothing = (storageA.firstSequence ?? 0) - 1 + const instances = [storageA, storageB].map((storage) => + storage.compaction ?? assert.fail("Storage does not provide compaction") + ) + + const opened = yield* Effect.all( + instances.map((compaction) => compaction.status(publicKey, storeId)), + { concurrency: "unbounded" } + ) + const histories = yield* Effect.forEach(instances, (compaction) => compaction.history(publicKey, storeId)) + // The seed bucket is in the hour the store was first opened. + yield* TestClock.adjust("25 hours") + const lagHeads = yield* Effect.forEach( + instances, + (compaction) => Effect.map(compaction.status(publicKey, storeId), (status) => status.lagHead) + ) + const next = yield* storageB.write(publicKey, storeId, [makeBatch(entries[3])]) + + const expected = { head: legacyLast, base: nothing, lagHead: nothing } + assert.deepStrictEqual(opened.map(({ base, head, lagHead }) => ({ head, base, lagHead })), [expected, expected]) + assert.strictEqual(histories[0].length, 1) + assert.isTrue(histories[0][0].active) + assert.deepStrictEqual(histories[1], histories[0]) + assert.deepStrictEqual(lagHeads, [legacyLast, legacyLast]) + assert.deepStrictEqual(next.map((batch) => batch.sequence), [legacyLast + 1]) + })) + + it.effect("allocates sequences after an old instance's writes during a rolling deploy", () => + Effect.gen(function*() { + const { options, publicKey, table } = yield* makeNamespace() + const storage = yield* SqlEventLogServerEncrypted.makeStorage(options) + const entries = makeIds(6) + const write = (batch: EventLogEncryption.EncryptedBatch) => + Effect.map(storage.write(publicKey, storeId, [batch]), (stored) => stored[0].sequence) + + const sequences = [ + yield* write(makeBatch(entries[0])), + yield* legacyWrite(table, makeBatch(entries[1], entries[2])), + yield* write(makeBatch(entries[3])), + yield* legacyWrite(table, makeBatch(entries[4])), + yield* write(makeBatch(entries[5])) + ] + const persisted = yield* storage.changes(publicKey, storeId, 0).pipe(Stream.take(5), Stream.runCollect) + + const first = sequences[0] + assert.deepStrictEqual(sequences, [first, first + 1, first + 3, first + 4, first + 5]) + assert.deepStrictEqual(persisted.map((batch) => batch.sequence), sequences) + assert.deepStrictEqual( + ids(persisted), + ids([ + makeBatch(entries[0]), + makeBatch(entries[1], entries[2]), + makeBatch(entries[3]), + makeBatch(entries[4]), + makeBatch(entries[5]) + ]) + ) + })) + + it.effect("keeps sequences increasing after every original is pruned", () => + Effect.gen(function*() { + const { options, publicKey, table } = yield* makeNamespace({ grace: "2 hours", lag: "1 hour" }) + const storage = yield* SqlEventLogServerEncrypted.makeStorage(options) + const entries = makeIds(5) + const written = yield* storage.write(publicKey, storeId, [ + makeBatch(entries[0], entries[1]), + makeBatch(entries[2]) + ]) + yield* commitSnapshot(storage, publicKey, entries[2]) + + const remaining = yield* sweepUntil(countRows(table), (count) => count === 0) + const afterPrune = yield* storage.write(publicKey, storeId, [makeBatch(entries[3])]) + // A second instance learns the next sequence from the store row. + const other = yield* SqlEventLogServerEncrypted.makeStorage(options) + const fromOther = yield* other.write(publicKey, storeId, [makeBatch(entries[4])]) + const acks = yield* storage.entrySequences(publicKey, storeId, entries) + const persisted = yield* storage.changes(publicKey, storeId, 0).pipe(Stream.take(3), Stream.runCollect) + + const first = written[0].sequence + assert.strictEqual(remaining, 0) + assert.deepStrictEqual(afterPrune.map((batch) => batch.sequence), [first + 3]) + assert.deepStrictEqual(fromOther.map((batch) => batch.sequence), [first + 4]) + // `T_ids` keeps the pruned ids as tombstones. + assert.sameDeepMembers( + acks.map((ack) => ack.sequence), + [first, first + 1, first + 2, first + 3, first + 4] + ) + assert.deepStrictEqual(served(persisted), [ + { sequence: first + 2, marker: snapshotMarker }, + { sequence: first + 3, marker: 1 }, + { sequence: first + 4, marker: 1 } + ]) + })) + + it.effect("re-appends the withdrawn input in order at the head, before later writes", () => + Effect.gen(function*() { + const { options, publicKey } = yield* makeNamespace() + const storage = yield* SqlEventLogServerEncrypted.makeStorage(options) + const compaction = storage.compaction ?? assert.fail("Storage does not provide compaction") + const snapshotBatch = (marker: number, ...entryIds: Array) => ({ + ...makeBatch(...entryIds), + encryptedBatch: Uint8Array.of(marker) + }) + const commit = Effect.fnUntraced(function*( + batches: ReadonlyArray, + virtualSequences: ReadonlyArray + ) { + const { head } = yield* compaction.status(publicKey, storeId) + const begun = yield* compaction.begin(publicKey, storeId, { through: head }) + if (begun._tag !== "Started") { + return assert.fail(`expected Started, got ${begun._tag}`) + } + yield* compaction.stagePart( + publicKey, + storeId, + begun.stageId, + 0, + batches as Arr.NonEmptyReadonlyArray + ) + return yield* compaction.commit(publicKey, storeId, begun.stageId, virtualSequences) + }) + // More than one 500-row page, each kept by g+1 as its own snapshot batch. + const entries = makeIds(501) + const originals = entries.map((id) => makeBatch(id)) + const written = yield* storage.write(publicKey, storeId, originals) + yield* commit( + entries.map((id) => snapshotBatch(snapshotMarker, id)), + written.map((batch) => batch.sequence) + ) + const [t1, t2, after] = makeIds(3) + const [tail] = yield* storage.write(publicKey, storeId, [makeBatch(t1, t2)]) + const head = tail.sequence + 1 + yield* commit([snapshotBatch(snapshotMarker + 1, t2)], [head]) + const active = (yield* compaction.history(publicKey, storeId)).find((activation) => activation.active)! + + // Withdraws g+2, whose input is g+1's batches, then the original [t1, t2]. + yield* compaction.rollback(publicKey, storeId, active.activationId) + const [later] = yield* storage.write(publicKey, storeId, [makeBatch(after)]) + const reappended = yield* storage.changes(publicKey, storeId, head + 1).pipe( + Stream.takeUntil((batch) => batch.sequence === later.sequence), + Stream.runCollect + ) + + assert.deepStrictEqual(served(reappended), [ + ...entries.map((_, i) => ({ sequence: head + 1 + i, marker: snapshotMarker })), + { sequence: head + entries.length + 1, marker: 2 }, + { sequence: head + entries.length + 3, marker: 1 } + ]) + assert.deepStrictEqual(ids(reappended), ids([...originals, tail, makeBatch(after)])) + }), { timeout: 60_000 }) + + it.effect("publishes nothing from a write whose outer transaction aborts", () => + Effect.gen(function*() { + const sql = yield* SqlClient.SqlClient + const { options, publicKey } = yield* makeNamespace() + const storage = yield* SqlEventLogServerEncrypted.makeStorage(options) + const [first, reverted, after] = makeIds(3) + const [written] = yield* storage.write(publicKey, storeId, [makeBatch(first)]) + const live = yield* followChanges(storage, publicKey, written.sequence, after) + + const aborted = yield* sql.withTransaction( + Effect.andThen(storage.write(publicKey, storeId, [makeBatch(reverted)]), Effect.fail("abort")) + ).pipe(Effect.exit) + const next = yield* storage.write(publicKey, storeId, [makeBatch(after)]) + const published = yield* Fiber.join(live) + + assert.isTrue(Exit.isFailure(aborted)) + assert.deepStrictEqual(next.map((batch) => batch.sequence), [written.sequence + 1]) + assert.deepStrictEqual(ids(published), ids([makeBatch(first), makeBatch(after)])) + assert.deepStrictEqual(published.map((batch) => batch.sequence), [written.sequence, written.sequence + 1]) + })) + + it.effect("publishes nothing from a rollback whose outer transaction aborts", () => + Effect.gen(function*() { + const sql = yield* SqlClient.SqlClient + const { options, publicKey } = yield* makeNamespace() + const storage = yield* SqlEventLogServerEncrypted.makeStorage(options) + const compaction = storage.compaction ?? assert.fail("Storage does not provide compaction") + const [first, kept, after] = makeIds(3) + yield* storage.write(publicKey, storeId, [makeBatch(first), makeBatch(kept)]) + yield* commitSnapshot(storage, publicKey, kept) + const { head } = yield* compaction.status(publicKey, storeId) + const snapshot = (yield* compaction.history(publicKey, storeId)).find((activation) => activation.active)! + const live = yield* followChanges(storage, publicKey, head, after) + + const aborted = yield* sql.withTransaction( + Effect.andThen(compaction.rollback(publicKey, storeId, snapshot.activationId), Effect.fail("abort")) + ).pipe(Effect.exit) + const next = yield* storage.write(publicKey, storeId, [makeBatch(after)]) + const published = yield* Fiber.join(live) + const history = yield* compaction.history(publicKey, storeId) + + assert.isTrue(Exit.isFailure(aborted)) + assert.deepStrictEqual(next.map((batch) => batch.sequence), [head + 1]) + assert.deepStrictEqual(served(published), [ + { sequence: head, marker: snapshotMarker }, + { sequence: head + 1, marker: 1 } + ]) + assert.isTrue(history.find((activation) => activation.activationId === snapshot.activationId)!.active) + })) + + it.effect("resumes a partially pruned snapshot after its sweeper dies without deleting originals", () => + Effect.gen(function*() { + const sql = yield* SqlClient.SqlClient + const { options, publicKey, table } = yield* makeNamespace({ grace: "2 hours", lag: "1 hour" }) + const snapshotTable = `${table}_snapshot` + const reached = yield* Deferred.make() + // Registered first, so a failing test still stops the sweeper and + // releases the transaction its hung DELETE holds. + const scopeA = yield* Effect.acquireRelease(Scope.make(), (scope) => + Scope.close(scope, Exit.void)) + const storageA = yield* SqlEventLogServerEncrypted.makeStorage(options).pipe( + Effect.provideService(Statement.CurrentTransformer, hangOnDelete(snapshotTable, reached, 2)), + Scope.provide(scopeA) + ) + const compactionA = storageA.compaction ?? assert.fail("Storage does not provide compaction") + // More than two 200-row chunks, with one entry per snapshot row. + const batches = makeIds(401).map((id) => makeBatch(id)) + const written = yield* storageA.write(publicKey, storeId, batches) + const begun = yield* compactionA.begin(publicKey, storeId, { through: written[400].sequence }) + if (begun._tag !== "Started") return assert.fail(`expected Started, got ${begun._tag}`) + yield* compactionA.stagePart(publicKey, storeId, begun.stageId, 0, [batches[0], ...batches.slice(1)]) + assert.strictEqual( + yield* compactionA.commit(publicKey, storeId, begun.stageId, written.map((batch) => batch.sequence)), + "Committed" + ) + const snapshot = (yield* compactionA.history(publicKey, storeId)).find((activation) => activation.active)! + yield* compactionA.rollback(publicKey, storeId, snapshot.activationId) + + // Poll only the signal while A holds a transaction (SQLite cannot query + // through that lock). sweepUntil bounds the missing-second-delete case. + const interrupted = yield* sweepUntil(Deferred.isDone(reached), (done) => done) + yield* Scope.close(scopeA, Exit.void) + assert.isTrue(interrupted, "snapshot pruning never reached a second DELETE") + + const storageB = yield* SqlEventLogServerEncrypted.makeStorage(options) + const compactionB = storageB.compaction ?? assert.fail("Storage does not provide compaction") + const withdrawn = (yield* compactionB.history(publicKey, storeId)).find((activation) => + activation.activationId === snapshot.activationId + )! + const remainingRows = Effect.map( + sql<{ n: number | string }>` + SELECT COUNT(*) AS n FROM ${sql(snapshotTable)} WHERE batch_set = ${begun.stageId}`, + ([row]) => Number(row.n) + ) + const beforeB = yield* remainingRows + assert.isFalse(withdrawn.restorable) + assert.isAbove(beforeB, 0) + assert.isBelow(beforeB, batches.length) + // The originals, and their copies the rollback re-appended. + assert.strictEqual(yield* countRows(table), 2 * batches.length) + + assert.strictEqual(yield* sweepUntil(remainingRows, (count) => count === 0), 0) + assert.strictEqual(yield* countRows(table), 2 * batches.length) + const persisted = yield* storageB.changes(publicKey, storeId, storageB.firstSequence ?? 0).pipe( + Stream.take(batches.length), + Stream.runCollect + ) + assert.deepStrictEqual(ids(persisted), ids(batches)) + assert.deepStrictEqual(served(persisted), served(written)) + }), { timeout: 60_000 }) + + it.effect("finishes the prune of a sweeper that died in the middle of it", () => + Effect.gen(function*() { + const { options, publicKey, table } = yield* makeNamespace({ grace: "2 hours", lag: "1 hour" }) + const reached = yield* Deferred.make() + const scopeA = yield* Scope.make() + const storageA = yield* SqlEventLogServerEncrypted.makeStorage(options).pipe( + Effect.provideService(Statement.CurrentTransformer, hangOnDelete(table, reached)), + Scope.provide(scopeA) + ) + const entries = makeIds(3) + const written = yield* storageA.write(publicKey, storeId, [ + makeBatch(entries[0], entries[1]), + makeBatch(entries[2]) + ]) + yield* commitSnapshot(storageA, publicKey, entries[2]) + + const died = yield* sweepUntil(Deferred.isDone(reached), (done) => + done) + yield* Scope.close(scopeA, Exit.void) + const storageB = yield* SqlEventLogServerEncrypted.makeStorage(options) + const compaction = storageB.compaction ?? assert.fail("Storage does not provide compaction") + const [originals] = yield* compaction.history(publicKey, storeId) + const beforeB = yield* countRows(table) + const afterB = yield* sweepUntil(countRows(table), (count) => + count === 0) + const persisted = yield* storageB.changes(publicKey, storeId, 0).pipe(Stream.take(1), Stream.runCollect) + + assert.isTrue(died) + assert.isFalse(originals.restorable) + assert.strictEqual(beforeB, 2) + assert.strictEqual(afterB, 0) + assert.deepStrictEqual(served(persisted), [{ sequence: written[1].sequence, marker: snapshotMarker }]) + })) + }) diff --git a/packages/sql/mssql/test/Binary.test.ts b/packages/sql/mssql/test/Binary.test.ts index 9c04869474..c06e0b808d 100644 --- a/packages/sql/mssql/test/Binary.test.ts +++ b/packages/sql/mssql/test/Binary.test.ts @@ -55,6 +55,25 @@ vi.mock("tedious", async (importOriginal) => { request.callback(null, 0, []) return } + // The store row the storage locks before each write. + if (query.startsWith("SELECT next_sequence")) { + const store = { + next_sequence: 1, + active_activation: "originals", + active_batch_set: null, + base_sequence: 0, + active_kept_count: 0, + no_op_at: null, + no_op_count: 0, + open_stage: null, + next_sweep_at: null, + sweep_lease_until: null, + sweep_lease_owner: null, + pruned_through: 0 + } + request.callback(null, 1, [Object.entries(store).map(([colName, value]) => ({ metadata: { colName }, value }))]) + return + } if (query.startsWith("SELECT MAX(last_sequence)")) { request.callback(null, 1, [[{ metadata: { colName: "last_sequence" }, value: null }]]) return diff --git a/packages/sql/mssql/test/Client.integration.test.ts b/packages/sql/mssql/test/Client.integration.test.ts new file mode 100644 index 0000000000..14b512163d --- /dev/null +++ b/packages/sql/mssql/test/Client.integration.test.ts @@ -0,0 +1,27 @@ +import { assert, it } from "@effect/vitest" +import { Effect, Fiber } from "effect" +import * as SqlClient from "effect/sql/SqlClient" +import { MssqlContainer } from "./utils.ts" + +// One connection, so the statement after the interruption runs on the +// connection whose request was cancelled. +it.layer(MssqlContainer.layerClientWith({ maxConnections: 1 }), { + timeout: "120 seconds", + excludeTestServices: true +})("MssqlClient (integration)", (it) => { + it.effect( + "runs the next statement on a connection whose running statement was interrupted", + () => + Effect.gen(function*() { + const sql = yield* SqlClient.SqlClient + const running = yield* Effect.forkChild(sql`WAITFOR DELAY '00:00:05'`) + yield* Effect.sleep("200 millis") + yield* Fiber.interrupt(running) + + const rows = yield* sql<{ n: number }>`SELECT 1 AS n` + + assert.deepStrictEqual(rows, [{ n: 1 }]) + }), + { timeout: 30_000 } + ) +}) diff --git a/packages/sql/mssql/test/SqlEventLogServerEncrypted.integration.test.ts b/packages/sql/mssql/test/SqlEventLogServerEncrypted.integration.test.ts index fd5ec14167..970f2c073b 100644 --- a/packages/sql/mssql/test/SqlEventLogServerEncrypted.integration.test.ts +++ b/packages/sql/mssql/test/SqlEventLogServerEncrypted.integration.test.ts @@ -1,4 +1,5 @@ import { Layer } from "effect" +import * as CompactionTest from "effect-test/eventlog/EventLogServerEncryptedCompactionTest" import * as EncryptedTest from "effect-test/eventlog/EventLogServerEncryptedTest" import * as SqlEventLogServerEncryptedStorageTest from "effect-test/eventlog/SqlEventLogServerEncryptedStorageTest" import * as Digest from "effect/crypto/Digest" @@ -15,3 +16,11 @@ EncryptedTest.suite( ) SqlEventLogServerEncryptedStorageTest.suite("mssql", MssqlContainer.layerClient) + +CompactionTest.suite( + "mssql", + (options) => SqlEventLogServerEncrypted.layerStorage(options).pipe(Layer.provide(Digest.layerWebCrypto)), + MssqlContainer.layerClient +) + +SqlEventLogServerEncryptedStorageTest.compactionSuite("mssql", MssqlContainer.layerClient) diff --git a/packages/sql/mssql/test/utils.ts b/packages/sql/mssql/test/utils.ts index f1379457ed..8fe5b09357 100644 --- a/packages/sql/mssql/test/utils.ts +++ b/packages/sql/mssql/test/utils.ts @@ -20,20 +20,24 @@ export class MssqlContainer extends Context.Service()("test/Mssq }) { static readonly layer = Layer.effect(this)(this.make) - static layerClient = Layer.unwrap( - Effect.gen(function*() { - const container = yield* MssqlContainer - return MssqlClient.layer({ - server: container.getHost(), - port: container.getPort(), - database: container.getDatabase(), - username: container.getUsername(), - password: Redacted.make(container.getPassword()), - // Deno does not enforce TLS fragment limits required by Tedious for large TDS writes. - // Disable transport encryption only for the local Deno fixture; keep Node TLS coverage. - encrypt: !("Deno" in globalThis), - trustServer: true + static layerClientWith = (options: { readonly maxConnections?: number }) => + Layer.unwrap( + Effect.gen(function*() { + const container = yield* MssqlContainer + return MssqlClient.layer({ + ...options, + server: container.getHost(), + port: container.getPort(), + database: container.getDatabase(), + username: container.getUsername(), + password: Redacted.make(container.getPassword()), + // Deno doesn't enforce the TLS fragment limits Tedious needs for large + // TDS writes, so only the Deno fixture runs unencrypted. Node keeps TLS. + encrypt: !("Deno" in globalThis), + trustServer: true + }) }) - }) - ).pipe(Layer.provideMerge(this.layer)) + ).pipe(Layer.provideMerge(this.layer)) + + static layerClient = this.layerClientWith({}) } diff --git a/packages/sql/mysql2/test/SqlEventLogServerEncrypted.integration.test.ts b/packages/sql/mysql2/test/SqlEventLogServerEncrypted.integration.test.ts index 939c954592..6177462d7d 100644 --- a/packages/sql/mysql2/test/SqlEventLogServerEncrypted.integration.test.ts +++ b/packages/sql/mysql2/test/SqlEventLogServerEncrypted.integration.test.ts @@ -1,4 +1,5 @@ import { Layer } from "effect" +import * as CompactionTest from "effect-test/eventlog/EventLogServerEncryptedCompactionTest" import * as EncryptedTest from "effect-test/eventlog/EventLogServerEncryptedTest" import * as SqlEventLogServerEncryptedStorageTest from "effect-test/eventlog/SqlEventLogServerEncryptedStorageTest" import * as Digest from "effect/crypto/Digest" @@ -15,3 +16,11 @@ EncryptedTest.suite( ) SqlEventLogServerEncryptedStorageTest.suite("mysql2", MysqlContainer.layerClientRoot) + +CompactionTest.suite( + "mysql2", + (options) => SqlEventLogServerEncrypted.layerStorage(options).pipe(Layer.provide(Digest.layerWebCrypto)), + MysqlContainer.layerClient +) + +SqlEventLogServerEncryptedStorageTest.compactionSuite("mysql2", MysqlContainer.layerClient) diff --git a/packages/sql/pg/test/SqlEventLogServerEncrypted.integration.test.ts b/packages/sql/pg/test/SqlEventLogServerEncrypted.integration.test.ts index d7907bb33d..d1ff2392a8 100644 --- a/packages/sql/pg/test/SqlEventLogServerEncrypted.integration.test.ts +++ b/packages/sql/pg/test/SqlEventLogServerEncrypted.integration.test.ts @@ -1,4 +1,5 @@ import { Layer } from "effect" +import * as CompactionTest from "effect-test/eventlog/EventLogServerEncryptedCompactionTest" import * as EncryptedTest from "effect-test/eventlog/EventLogServerEncryptedTest" import * as SqlEventLogServerEncryptedStorageTest from "effect-test/eventlog/SqlEventLogServerEncryptedStorageTest" import * as Digest from "effect/crypto/Digest" @@ -15,3 +16,11 @@ EncryptedTest.suite( ) SqlEventLogServerEncryptedStorageTest.suite("pg", PgContainer.layerClient) + +CompactionTest.suite( + "pg", + (options) => SqlEventLogServerEncrypted.layerStorage(options).pipe(Layer.provide(Digest.layerWebCrypto)), + PgContainer.layerClient +) + +SqlEventLogServerEncryptedStorageTest.compactionSuite("pg", PgContainer.layerClient) diff --git a/packages/sql/sqlite-node/test/SqlEventLogServerEncrypted.test.ts b/packages/sql/sqlite-node/test/SqlEventLogServerEncrypted.test.ts index b7e837722e..ac4f613277 100644 --- a/packages/sql/sqlite-node/test/SqlEventLogServerEncrypted.test.ts +++ b/packages/sql/sqlite-node/test/SqlEventLogServerEncrypted.test.ts @@ -1,7 +1,9 @@ import { SqliteClient } from "@effect/sql-sqlite-node" import { assert, describe, it } from "@effect/vitest" import { Effect, Layer, Queue, Redacted, Stream } from "effect" +import * as CompactionTest from "effect-test/eventlog/EventLogServerEncryptedCompactionTest" import * as EncryptedTest from "effect-test/eventlog/EventLogServerEncryptedTest" +import * as SqlEventLogServerEncryptedStorageTest from "effect-test/eventlog/SqlEventLogServerEncryptedStorageTest" import * as Digest from "effect/crypto/Digest" import * as EventJournal from "effect/eventlog/EventJournal" import * as EventLog from "effect/eventlog/EventLog" @@ -26,6 +28,14 @@ EncryptedTest.suite( ) ) +CompactionTest.suite( + "SQLite", + (options) => SqlEventLogServer.layerStorage(options).pipe(Layer.provide(Digest.layerWebCrypto)), + SqliteClient.layer({ filename: ":memory:" }) +) + +SqlEventLogServerEncryptedStorageTest.compactionSuite("SQLite", SqliteClient.layer({ filename: ":memory:" })) + const storeIdA = "store-a" as StoreId const storeIdB = "store-b" as StoreId