@swirls/looms 0.7.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,356 @@
1
+ import { DateTime, Effect, Predicate, Stream } from 'effect';
2
+ import createPostgresClient, {} from 'postgres';
3
+ import { EventStoreError, foldRun, } from '@swirls/looms/core';
4
+ import { applyRunIndexOps, eventLogOps, insertRunEvents } from '../event-log.js';
5
+ import { indexOpsFor } from '../index-model.js';
6
+ import { applyIndexOps } from '../postgres.js';
7
+ import { ReplicaGapError } from '../projector.js';
8
+ import { POSTGRES_REPLICA_MIGRATIONS } from './migrations.js';
9
+ const REPLICA_NAME = 'postgres-replica';
10
+ const REPLICA_VERSION = '1';
11
+ const ADVISORY_LOCK_KEY = 814_764;
12
+ const READ_PAGE = 500;
13
+ const terminalStatuses = new Set(['completed', 'failed', 'cancelled']);
14
+ function replicaClient(options) {
15
+ if ('sql' in options) {
16
+ return { sql: options.sql, owned: false };
17
+ }
18
+ return { sql: createPostgresClient(options.url), owned: true };
19
+ }
20
+ function utcDate(millis) {
21
+ return DateTime.toDateUtc(DateTime.makeUnsafe(millis));
22
+ }
23
+ function asNumber(value) {
24
+ if (Predicate.isNumber(value)) {
25
+ return value;
26
+ }
27
+ return Number(value);
28
+ }
29
+ function epoch(value) {
30
+ if (Predicate.isDate(value)) {
31
+ return value.getTime();
32
+ }
33
+ if (Predicate.isNumber(value)) {
34
+ return value;
35
+ }
36
+ return new Date(value).getTime();
37
+ }
38
+ function envelope(row) {
39
+ const event = {
40
+ id: row.event_id,
41
+ runId: row.run_id,
42
+ seq: asNumber(row.seq),
43
+ ts: epoch(row.ts),
44
+ type: row.type,
45
+ payload: row.payload,
46
+ threadId: row.thread_id,
47
+ parentThreadId: row.parent_thread_id,
48
+ origin: row.origin,
49
+ idempotencyKey: row.idempotency_key,
50
+ };
51
+ if (row.causation_id !== null) {
52
+ event.causationId = row.causation_id;
53
+ }
54
+ if (row.correlation_id !== null) {
55
+ event.correlationId = row.correlation_id;
56
+ }
57
+ if (row.effect_id !== null) {
58
+ event.effectId = row.effect_id;
59
+ }
60
+ if (row.ephemeral) {
61
+ event.ephemeral = true;
62
+ }
63
+ return event;
64
+ }
65
+ function groups(events) {
66
+ const byRun = new Map();
67
+ for (const event of events) {
68
+ const batch = byRun.get(event.runId);
69
+ if (batch) {
70
+ batch.push(event);
71
+ }
72
+ else {
73
+ byRun.set(event.runId, [event]);
74
+ }
75
+ }
76
+ for (const batch of byRun.values()) {
77
+ batch.sort((left, right) => left.seq - right.seq);
78
+ }
79
+ return byRun;
80
+ }
81
+ /** Sequence through which `events` extends `replicatedSeq` with no hole. Redelivered seqs are ignored. */
82
+ function contiguousSeq(runId, replicatedSeq, events) {
83
+ let cursor = replicatedSeq;
84
+ for (const event of events) {
85
+ if (event.seq <= cursor) {
86
+ continue;
87
+ }
88
+ if (event.seq !== cursor + 1) {
89
+ throw new ReplicaGapError({ runId, replicatedSeq, batchFrom: event.seq });
90
+ }
91
+ cursor = event.seq;
92
+ }
93
+ return cursor;
94
+ }
95
+ async function appliedMigrationIds(sql) {
96
+ const [table] = await sql `
97
+ SELECT to_regclass('public.looms_schema_migrations') AS name
98
+ `;
99
+ if (!table?.name) {
100
+ return new Set();
101
+ }
102
+ const rows = await sql `SELECT id FROM looms_schema_migrations`;
103
+ return new Set(rows.map((row) => row.id));
104
+ }
105
+ async function readPage(sql, runId, fromSeq, limit) {
106
+ const rows = await sql `
107
+ SELECT run_id, seq, event_id, ts, type, payload, thread_id, parent_thread_id,
108
+ causation_id, correlation_id, effect_id, origin, idempotency_key, ephemeral
109
+ FROM looms_run_events
110
+ WHERE run_id = ${runId} AND seq >= ${fromSeq}
111
+ ORDER BY seq
112
+ LIMIT ${limit}
113
+ `;
114
+ return rows.map(envelope);
115
+ }
116
+ export function postgresReplica(options) {
117
+ const { sql, owned } = replicaClient(options);
118
+ let ready;
119
+ const pendingMigrations = async () => {
120
+ const applied = await appliedMigrationIds(sql);
121
+ return POSTGRES_REPLICA_MIGRATIONS.filter((migration) => !applied.has(migration.id)).map((migration) => migration.id);
122
+ };
123
+ const migrate = async () => {
124
+ await sql.begin(async (tx) => {
125
+ await tx `SELECT pg_advisory_xact_lock(${ADVISORY_LOCK_KEY})`;
126
+ const applied = await appliedMigrationIds(tx);
127
+ for (const migration of POSTGRES_REPLICA_MIGRATIONS) {
128
+ if (!applied.has(migration.id)) {
129
+ await tx.unsafe(migration.sql);
130
+ }
131
+ }
132
+ });
133
+ };
134
+ const init = () => {
135
+ ready ??= (options.migrate === 'verify' ? verify() : migrate()).catch((cause) => {
136
+ ready = undefined;
137
+ throw cause;
138
+ });
139
+ return ready;
140
+ };
141
+ const verify = async () => {
142
+ const pending = await pendingMigrations();
143
+ if (pending.length > 0) {
144
+ throw new Error(`Looms replica is missing migrations: ${pending.join(', ')}. Generate them with \`looms replica generate\` and apply the files before starting.`);
145
+ }
146
+ };
147
+ const project = async (events) => {
148
+ await init();
149
+ if (events.length === 0) {
150
+ return;
151
+ }
152
+ await sql.begin(async (tx) => {
153
+ for (const [runId, batch] of groups(events)) {
154
+ const [progress] = await tx `
155
+ SELECT replicated_seq, purged_at
156
+ FROM looms_run_index
157
+ WHERE run_id = ${runId}
158
+ FOR UPDATE
159
+ `;
160
+ if (progress?.purged_at) {
161
+ continue;
162
+ }
163
+ const replicatedSeq = progress ? asNumber(progress.replicated_seq) : 0;
164
+ const next = contiguousSeq(runId, replicatedSeq, batch);
165
+ const durable = batch.filter((event) => !event.ephemeral);
166
+ const last = batch.at(-1);
167
+ await insertRunEvents(tx, batch);
168
+ await applyRunIndexOps(tx, durable.flatMap((event) => eventLogOps(event)));
169
+ await applyIndexOps(tx, durable.flatMap(indexOpsFor));
170
+ if (next === replicatedSeq || !last) {
171
+ continue;
172
+ }
173
+ await tx `
174
+ INSERT INTO looms_run_index (run_id, status, updated_at, replicated_seq)
175
+ VALUES (${runId}, 'running', ${utcDate(last.ts)}, ${next})
176
+ ON CONFLICT (run_id) DO UPDATE SET
177
+ replicated_seq = GREATEST(looms_run_index.replicated_seq, EXCLUDED.replicated_seq)
178
+ WHERE looms_run_index.purged_at IS NULL
179
+ `;
180
+ }
181
+ });
182
+ };
183
+ const position = async (runId) => {
184
+ const [row] = await sql `
185
+ SELECT replicated_seq, purged_at
186
+ FROM looms_run_index
187
+ WHERE run_id = ${runId}
188
+ `;
189
+ if (!row) {
190
+ return 0;
191
+ }
192
+ if (row.purged_at) {
193
+ return null;
194
+ }
195
+ return asNumber(row.replicated_seq);
196
+ };
197
+ const readEvents = (runId, readOptions) => Effect.tryPromise({
198
+ try: async () => {
199
+ const fromSeq = readOptions?.fromSeq ?? 1;
200
+ const events = [];
201
+ let cursor = fromSeq;
202
+ let remaining = readOptions?.limit;
203
+ while (remaining === undefined || remaining > 0) {
204
+ const take = remaining === undefined ? READ_PAGE : Math.min(READ_PAGE, remaining);
205
+ const page = await readPage(sql, runId, cursor, take);
206
+ events.push(...page);
207
+ if (remaining !== undefined) {
208
+ remaining -= page.length;
209
+ }
210
+ const last = page.at(-1);
211
+ if (!last || page.length < take) {
212
+ break;
213
+ }
214
+ cursor = last.seq + 1;
215
+ }
216
+ return events;
217
+ },
218
+ catch: (cause) => new EventStoreError('Replica read failed', cause),
219
+ });
220
+ const store = {
221
+ append: () => Effect.fail(new EventStoreError('The Postgres replica is read-only')),
222
+ read: readEvents,
223
+ readStream: (runId, readOptions) => Stream.fromIterableEffect(readEvents(runId, readOptions)),
224
+ tail: (runId) => Effect.tryPromise({
225
+ try: async () => {
226
+ const [row] = await sql `
227
+ SELECT replicated_seq FROM looms_run_index WHERE run_id = ${runId}
228
+ `;
229
+ return row ? asNumber(row.replicated_seq) : 0;
230
+ },
231
+ catch: (cause) => new EventStoreError('Replica tail failed', cause),
232
+ }),
233
+ bounds: (runId) => Effect.tryPromise({
234
+ try: async () => {
235
+ const [row] = await sql `
236
+ SELECT replicated_seq,
237
+ (SELECT MIN(seq) FROM looms_run_events event WHERE event.run_id = run.run_id) AS head
238
+ FROM looms_run_index run
239
+ WHERE run.run_id = ${runId}
240
+ `;
241
+ if (!row) {
242
+ return { head: 1, tail: 0 };
243
+ }
244
+ const tail = asNumber(row.replicated_seq);
245
+ const head = row.head === null ? tail + 1 : asNumber(row.head);
246
+ return { head, tail };
247
+ },
248
+ catch: (cause) => new EventStoreError('Replica bounds failed', cause),
249
+ }),
250
+ trim: () => Effect.fail(new EventStoreError('Trim a replica with purge()')),
251
+ subscribe: (runId, readOptions) => Stream.fromIterableEffect(readEvents(runId, readOptions)),
252
+ listRuns: Effect.tryPromise({
253
+ try: async () => {
254
+ const rows = await sql `
255
+ SELECT run_id FROM looms_run_index
256
+ WHERE purged_at IS NULL
257
+ ORDER BY run_id
258
+ `;
259
+ return rows.map((row) => row.run_id);
260
+ },
261
+ catch: (cause) => new EventStoreError('Replica listRuns failed', cause),
262
+ }),
263
+ };
264
+ const loadRun = async (runId, registry) => {
265
+ const events = await Effect.runPromise(readEvents(runId));
266
+ return foldRun(events, registry, { runId });
267
+ };
268
+ const status = async (runId) => {
269
+ const [row] = await sql `
270
+ SELECT run.replicated_seq,
271
+ run.status,
272
+ run.purged_at,
273
+ (SELECT MAX(seq) FROM looms_run_events event WHERE event.run_id = run.run_id) AS max_seq
274
+ FROM looms_run_index run
275
+ WHERE run.run_id = ${runId}
276
+ `;
277
+ if (!row) {
278
+ return null;
279
+ }
280
+ const replicatedSeq = asNumber(row.replicated_seq);
281
+ const finished = terminalStatuses.has(row.status);
282
+ const purgedAt = row.purged_at === null ? null : epoch(row.purged_at);
283
+ const maxSeq = row.max_seq === null ? null : asNumber(row.max_seq);
284
+ const copiedThroughFinish = purgedAt !== null || (maxSeq !== null && maxSeq === replicatedSeq && replicatedSeq > 0);
285
+ return {
286
+ replicatedSeq,
287
+ finished,
288
+ complete: finished && copiedThroughFinish,
289
+ purgedAt,
290
+ };
291
+ };
292
+ const purge = async (purgeOptions) => {
293
+ const cutoff = utcDate(purgeOptions.finishedBefore);
294
+ const keepIndex = purgeOptions.keepIndex !== false;
295
+ return sql.begin(async (tx) => {
296
+ const doomed = await tx `
297
+ UPDATE looms_run_index
298
+ SET purged_at = NOW()
299
+ WHERE purged_at IS NULL
300
+ AND status IN ('completed', 'failed', 'cancelled')
301
+ AND completed_at IS NOT NULL
302
+ AND completed_at < ${cutoff}
303
+ RETURNING run_id
304
+ `;
305
+ const ids = doomed.map((row) => row.run_id);
306
+ if (ids.length === 0) {
307
+ return { runs: 0 };
308
+ }
309
+ await tx `DELETE FROM looms_run_events WHERE run_id IN ${tx(ids)}`;
310
+ if (!keepIndex) {
311
+ await tx `DELETE FROM looms_run_actors WHERE run_id IN ${tx(ids)}`;
312
+ await tx `DELETE FROM looms_run_reviews WHERE run_id IN ${tx(ids)}`;
313
+ await tx `DELETE FROM looms_run_index WHERE run_id IN ${tx(ids)}`;
314
+ }
315
+ return { runs: ids.length };
316
+ });
317
+ };
318
+ const rebuild = async (source) => {
319
+ await init();
320
+ const runIds = await Effect.runPromise(source.listRuns);
321
+ let copied = 0;
322
+ for (const runId of runIds) {
323
+ let fromSeq = 1;
324
+ while (true) {
325
+ const events = await Effect.runPromise(source.read(runId, { fromSeq, limit: READ_PAGE }));
326
+ if (events.length === 0) {
327
+ break;
328
+ }
329
+ await project(events);
330
+ copied += events.length;
331
+ const last = events.at(-1);
332
+ if (!last || events.length < READ_PAGE) {
333
+ break;
334
+ }
335
+ fromSeq = last.seq + 1;
336
+ }
337
+ }
338
+ return copied;
339
+ };
340
+ return {
341
+ name: REPLICA_NAME,
342
+ version: REPLICA_VERSION,
343
+ init,
344
+ position,
345
+ project,
346
+ migrate,
347
+ pendingMigrations,
348
+ eventStore: () => store,
349
+ loadRun,
350
+ status,
351
+ purge,
352
+ rebuild,
353
+ dispose: owned ? () => sql.end() : undefined,
354
+ };
355
+ }
356
+ export { ReplicaGapError };
@@ -0,0 +1,5 @@
1
+ import { Database } from 'bun:sqlite';
2
+ import { type SqliteReplica, type SqliteReplicaDatabase, type SqliteReplicaMigrate } from './sqlite';
3
+ /** Opens a SQLite file. The replica closes it on `dispose`. */
4
+ export declare function openSqliteReplicaFile(filename: string, migrate: SqliteReplicaMigrate): SqliteReplica;
5
+ export declare function bunSqliteReplicaDatabase(db: Database): SqliteReplicaDatabase;
@@ -0,0 +1,39 @@
1
+ import { Database } from 'bun:sqlite';
2
+ import { sqliteReplica, } from './sqlite.js';
3
+ /** Opens a SQLite file. The replica closes it on `dispose`. */
4
+ export function openSqliteReplicaFile(filename, migrate) {
5
+ const db = new Database(filename);
6
+ const replica = sqliteReplica({ database: bunSqliteReplicaDatabase(db), migrate });
7
+ return {
8
+ ...replica,
9
+ dispose: () => {
10
+ db.close();
11
+ return Promise.resolve();
12
+ },
13
+ };
14
+ }
15
+ export function bunSqliteReplicaDatabase(db) {
16
+ return {
17
+ exec: (sql) => {
18
+ db.exec(sql);
19
+ return Promise.resolve();
20
+ },
21
+ get: (sql, params = []) => {
22
+ const row = db.query(sql).get(...params);
23
+ return Promise.resolve(row ?? null);
24
+ },
25
+ all: (sql, params = []) => Promise.resolve(db.query(sql).all(...params)),
26
+ batch: (statements) => {
27
+ if (statements.length === 0) {
28
+ return Promise.resolve();
29
+ }
30
+ const apply = db.transaction((batch) => {
31
+ for (const entry of batch) {
32
+ db.run(entry.sql, [...entry.params]);
33
+ }
34
+ });
35
+ apply(statements);
36
+ return Promise.resolve();
37
+ },
38
+ };
39
+ }
@@ -0,0 +1,5 @@
1
+ /** Versioned DDL for the SQLite replica, including D1. Looms only creates `looms_*` objects. */
2
+ export declare const SQLITE_REPLICA_MIGRATIONS: {
3
+ id: string;
4
+ sql: string;
5
+ }[];
@@ -0,0 +1,99 @@
1
+ /**
2
+ * Same tables as the Postgres replica, in SQLite types.
3
+ * Timestamps are epoch milliseconds. JSON is text. Booleans are 0 or 1.
4
+ * A fresh database gets every column from `CREATE TABLE`. SQLite has no
5
+ * `ADD COLUMN IF NOT EXISTS` we want to depend on, so later migrations should
6
+ * add columns the way the index projector does: read `PRAGMA table_info` first.
7
+ */
8
+ const SQLITE_REPLICA_SCHEMA_SQL = `
9
+ CREATE TABLE IF NOT EXISTS looms_run_actors (
10
+ run_id TEXT NOT NULL,
11
+ actor_id TEXT NOT NULL,
12
+ kind TEXT,
13
+ status TEXT,
14
+ definition_name TEXT,
15
+ parent_actor_id TEXT,
16
+ launched_by_run_id TEXT,
17
+ launched_by_effect_id TEXT,
18
+ correlation_id TEXT,
19
+ updated_at INTEGER NOT NULL,
20
+ PRIMARY KEY (run_id, actor_id)
21
+ );
22
+
23
+ CREATE INDEX IF NOT EXISTS looms_run_actors_launched_by ON looms_run_actors (launched_by_run_id);
24
+ CREATE INDEX IF NOT EXISTS looms_run_actors_correlation ON looms_run_actors (correlation_id);
25
+
26
+ CREATE TABLE IF NOT EXISTS looms_run_reviews (
27
+ run_id TEXT NOT NULL,
28
+ review_id TEXT NOT NULL,
29
+ status TEXT NOT NULL,
30
+ title TEXT NOT NULL,
31
+ updated_at INTEGER NOT NULL,
32
+ PRIMARY KEY (run_id, review_id)
33
+ );
34
+
35
+ CREATE TABLE IF NOT EXISTS looms_run_events (
36
+ run_id TEXT NOT NULL,
37
+ seq INTEGER NOT NULL,
38
+ event_id TEXT NOT NULL,
39
+ ts INTEGER NOT NULL,
40
+ type TEXT NOT NULL,
41
+ payload TEXT NOT NULL,
42
+ thread_id TEXT,
43
+ parent_thread_id TEXT,
44
+ causation_id TEXT,
45
+ correlation_id TEXT,
46
+ effect_id TEXT,
47
+ origin TEXT NOT NULL,
48
+ idempotency_key TEXT,
49
+ ephemeral INTEGER NOT NULL DEFAULT 0,
50
+ PRIMARY KEY (run_id, seq)
51
+ );
52
+
53
+ CREATE INDEX IF NOT EXISTS looms_run_events_type_ts ON looms_run_events (type, ts);
54
+
55
+ CREATE TABLE IF NOT EXISTS looms_run_index (
56
+ run_id TEXT PRIMARY KEY,
57
+ status TEXT NOT NULL,
58
+ kind TEXT,
59
+ definition_name TEXT,
60
+ definition_version TEXT,
61
+ root_thread_id TEXT,
62
+ parent_run_id TEXT,
63
+ launched_by_effect_id TEXT,
64
+ correlation_id TEXT,
65
+ attributes TEXT NOT NULL DEFAULT '{}',
66
+ tenant TEXT,
67
+ project TEXT,
68
+ org TEXT,
69
+ started_at INTEGER,
70
+ updated_at INTEGER NOT NULL,
71
+ completed_at INTEGER,
72
+ replicated_seq INTEGER NOT NULL DEFAULT 0,
73
+ purged_at INTEGER
74
+ );
75
+
76
+ CREATE INDEX IF NOT EXISTS looms_run_index_tenant ON looms_run_index (tenant);
77
+ CREATE INDEX IF NOT EXISTS looms_run_index_project ON looms_run_index (project);
78
+ CREATE INDEX IF NOT EXISTS looms_run_index_org ON looms_run_index (org);
79
+ CREATE INDEX IF NOT EXISTS looms_run_index_parent ON looms_run_index (parent_run_id);
80
+ CREATE INDEX IF NOT EXISTS looms_run_index_status ON looms_run_index (status);
81
+
82
+ CREATE TABLE IF NOT EXISTS looms_schema_migrations (
83
+ id TEXT PRIMARY KEY,
84
+ applied_at INTEGER NOT NULL
85
+ );
86
+ `.trim();
87
+ function sqliteReplicaMigration(id, sql) {
88
+ return {
89
+ id,
90
+ sql: [
91
+ sql,
92
+ `INSERT INTO looms_schema_migrations (id, applied_at) VALUES ('${id}', unixepoch() * 1000) ON CONFLICT (id) DO NOTHING;`,
93
+ ].join('\n\n'),
94
+ };
95
+ }
96
+ /** Versioned DDL for the SQLite replica, including D1. Looms only creates `looms_*` objects. */
97
+ export const SQLITE_REPLICA_MIGRATIONS = [
98
+ sqliteReplicaMigration('0001_replica', SQLITE_REPLICA_SCHEMA_SQL),
99
+ ];
@@ -0,0 +1,95 @@
1
+ import { type EventStore, type FoldRegistry, type RunState } from '@swirls/looms/core';
2
+ import { ReplicaGapError, type Projector } from '../projector';
3
+ export interface ReplicaStatus {
4
+ /** Highest sequence copied with no hole in front of it. */
5
+ readonly replicatedSeq: number;
6
+ /** The run summary says the run has finished. */
7
+ readonly finished: boolean;
8
+ /** Finished, and every event through that finish has been copied. */
9
+ readonly complete: boolean;
10
+ /** Set once retention has deleted the event copy. */
11
+ readonly purgedAt: number | null;
12
+ }
13
+ export interface ReplicaPurgeOptions {
14
+ /** Delete event copies for runs that finished before this epoch millisecond. */
15
+ readonly finishedBefore: number;
16
+ /** Keep the run summary row. Defaults to true. */
17
+ readonly keepIndex?: boolean;
18
+ }
19
+ export interface ReplicaPurgeResult {
20
+ readonly runs: number;
21
+ }
22
+ export type SqliteReplicaMigrate = 'auto' | 'verify';
23
+ export type SqlValue = string | number | null;
24
+ export interface SqlStatement {
25
+ readonly sql: string;
26
+ readonly params: readonly SqlValue[];
27
+ }
28
+ /**
29
+ * Async SQL used by the replica.
30
+ * `bun:sqlite` and Cloudflare D1 both adapt to this. One writer per run is assumed:
31
+ * D1 cannot interleave a read and the following writes in one interactive transaction.
32
+ */
33
+ export interface SqliteReplicaDatabase {
34
+ exec(sql: string): Promise<void>;
35
+ get<T>(sql: string, params?: readonly SqlValue[]): Promise<T | null>;
36
+ all<T>(sql: string, params?: readonly SqlValue[]): Promise<readonly T[]>;
37
+ batch(statements: readonly SqlStatement[]): Promise<void>;
38
+ }
39
+ /**
40
+ * Enough of a prepared statement for the replica.
41
+ * Cloudflare's `D1PreparedStatement` satisfies this.
42
+ */
43
+ export interface D1BoundStatement {
44
+ all<T>(): Promise<{
45
+ readonly results?: readonly T[];
46
+ }>;
47
+ first<T>(): Promise<T | null>;
48
+ }
49
+ export type SqliteReplicaOptions = {
50
+ readonly database: SqliteReplicaDatabase;
51
+ /**
52
+ * `auto` applies pending migrations on init.
53
+ * `verify` refuses to start when a migration has not been applied, and names
54
+ * `looms replica generate --dialect sqlite` so the host can commit the SQL.
55
+ */
56
+ readonly migrate: SqliteReplicaMigrate;
57
+ };
58
+ /**
59
+ * Adapts Cloudflare D1.
60
+ * The statement type is inferred from `prepare().bind()` so `D1Database` itself is accepted:
61
+ * D1's `batch` only takes the statements its own `prepare` returns.
62
+ */
63
+ export declare function d1ReplicaDatabase<Statement extends D1BoundStatement>(d1: {
64
+ exec(query: string): Promise<{
65
+ readonly count: number;
66
+ readonly duration: number;
67
+ }>;
68
+ prepare(query: string): {
69
+ bind(...values: readonly SqlValue[]): Statement;
70
+ };
71
+ batch(statements: readonly Statement[]): Promise<readonly object[]>;
72
+ }): SqliteReplicaDatabase;
73
+ /**
74
+ * A complete, gap-checked copy of every run, plus the run summary folded in the same batch.
75
+ * Reading an event back returns the envelope the source returned.
76
+ * Targets a shared SQLite database or D1, not the per-run actor store.
77
+ */
78
+ export interface SqliteReplica extends Projector {
79
+ readonly position: (runId: string) => Promise<number | null>;
80
+ /** Apply pending migrations. `init` does this only when `migrate` is `auto`. */
81
+ readonly migrate: () => Promise<void>;
82
+ readonly pendingMigrations: () => Promise<readonly string[]>;
83
+ /** Read-only view of the event copy. Folds and replay run against it unchanged. */
84
+ readonly eventStore: () => EventStore;
85
+ /** Fold the copied events with the same registry the runtime used. */
86
+ readonly loadRun: (runId: string, registry: FoldRegistry) => Promise<RunState>;
87
+ /** How far the copy has got, and whether it is safe to treat as complete. */
88
+ readonly status: (runId: string) => Promise<ReplicaStatus | null>;
89
+ /** Delete event copies for finished runs. Later deliveries for those runs are skipped. */
90
+ readonly purge: (options: ReplicaPurgeOptions) => Promise<ReplicaPurgeResult>;
91
+ /** Copy every run in `source`. Purged runs are left alone. */
92
+ readonly rebuild: (source: EventStore) => Promise<number>;
93
+ }
94
+ export declare function sqliteReplica(options: SqliteReplicaOptions): SqliteReplica;
95
+ export { ReplicaGapError };