@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,517 @@
1
+ import { Effect, Predicate, Schema, Stream } from 'effect';
2
+ import { EventOriginSchema, EventStoreError, JsonValueSchema, foldRun, } from '@swirls/looms/core';
3
+ import { eventLogOps } from '../event-log-ops.js';
4
+ import { indexOpsFor } from '../index-model.js';
5
+ import { ReplicaGapError } from '../projector.js';
6
+ import { SQLITE_REPLICA_MIGRATIONS } from './sqlite-migrations.js';
7
+ const REPLICA_NAME = 'sqlite-replica';
8
+ const REPLICA_VERSION = '1';
9
+ const READ_PAGE = 500;
10
+ /** D1 batches are capped. Statements are idempotent and the cursor update is last, so a split batch resumes. */
11
+ const D1_BATCH = 100;
12
+ const terminalStatuses = new Set(['completed', 'failed', 'cancelled']);
13
+ /**
14
+ * Adapts Cloudflare D1.
15
+ * The statement type is inferred from `prepare().bind()` so `D1Database` itself is accepted:
16
+ * D1's `batch` only takes the statements its own `prepare` returns.
17
+ */
18
+ export function d1ReplicaDatabase(d1) {
19
+ const bound = (sql, params = []) => d1.prepare(sql).bind(...params);
20
+ return {
21
+ exec: (sql) => d1.exec(sql).then(() => undefined),
22
+ get: (sql, params) => bound(sql, params).first(),
23
+ all: async (sql, params = []) => {
24
+ const result = await bound(sql, params).all();
25
+ return result.results ?? [];
26
+ },
27
+ batch: async (statements) => {
28
+ for (let index = 0; index < statements.length; index += D1_BATCH) {
29
+ const slice = statements.slice(index, index + D1_BATCH);
30
+ if (slice.length === 0) {
31
+ continue;
32
+ }
33
+ await d1.batch(slice.map((statement) => bound(statement.sql, statement.params)));
34
+ }
35
+ },
36
+ };
37
+ }
38
+ const decodeJson = Schema.decodeUnknownSync(JsonValueSchema);
39
+ const decodeOrigin = Schema.decodeUnknownSync(EventOriginSchema);
40
+ function asNumber(value) {
41
+ if (Predicate.isNumber(value)) {
42
+ return value;
43
+ }
44
+ if (Predicate.isString(value)) {
45
+ return Number(value);
46
+ }
47
+ return Number(value);
48
+ }
49
+ function jsonText(value) {
50
+ return JSON.stringify(value) ?? 'null';
51
+ }
52
+ function parseJson(text) {
53
+ // SAFETY: payload and origin columns are JSON text written by jsonText.
54
+ const parsed = JSON.parse(text);
55
+ return decodeJson(parsed);
56
+ }
57
+ function isEphemeral(value) {
58
+ if (Predicate.isBoolean(value)) {
59
+ return value;
60
+ }
61
+ if (Predicate.isNumber(value)) {
62
+ return value !== 0;
63
+ }
64
+ return value === '1';
65
+ }
66
+ function epochOrNull(value) {
67
+ if (value === null) {
68
+ return null;
69
+ }
70
+ return asNumber(value);
71
+ }
72
+ function envelope(row) {
73
+ const event = {
74
+ id: row.event_id,
75
+ runId: row.run_id,
76
+ seq: asNumber(row.seq),
77
+ ts: asNumber(row.ts),
78
+ type: row.type,
79
+ payload: parseJson(row.payload),
80
+ threadId: row.thread_id,
81
+ parentThreadId: row.parent_thread_id,
82
+ origin: decodeOrigin(parseJson(row.origin)),
83
+ idempotencyKey: row.idempotency_key,
84
+ };
85
+ if (row.causation_id !== null) {
86
+ event.causationId = row.causation_id;
87
+ }
88
+ if (row.correlation_id !== null) {
89
+ event.correlationId = row.correlation_id;
90
+ }
91
+ if (row.effect_id !== null) {
92
+ event.effectId = row.effect_id;
93
+ }
94
+ if (isEphemeral(row.ephemeral)) {
95
+ event.ephemeral = true;
96
+ }
97
+ return event;
98
+ }
99
+ function groups(events) {
100
+ const byRun = new Map();
101
+ for (const event of events) {
102
+ const batch = byRun.get(event.runId);
103
+ if (batch) {
104
+ batch.push(event);
105
+ }
106
+ else {
107
+ byRun.set(event.runId, [event]);
108
+ }
109
+ }
110
+ for (const batch of byRun.values()) {
111
+ batch.sort((left, right) => left.seq - right.seq);
112
+ }
113
+ return byRun;
114
+ }
115
+ /** Sequence through which `events` extends `replicatedSeq` with no hole. Redelivered seqs are ignored. */
116
+ function contiguousSeq(runId, replicatedSeq, events) {
117
+ let cursor = replicatedSeq;
118
+ for (const event of events) {
119
+ if (event.seq <= cursor) {
120
+ continue;
121
+ }
122
+ if (event.seq !== cursor + 1) {
123
+ throw new ReplicaGapError({ runId, replicatedSeq, batchFrom: event.seq });
124
+ }
125
+ cursor = event.seq;
126
+ }
127
+ return cursor;
128
+ }
129
+ function sqlStatement(sql, params) {
130
+ return { sql, params };
131
+ }
132
+ function insertEvents(events) {
133
+ return events.map((event) => sqlStatement(`INSERT INTO looms_run_events (
134
+ run_id, seq, event_id, ts, type, payload, thread_id, parent_thread_id,
135
+ causation_id, correlation_id, effect_id, origin, idempotency_key, ephemeral
136
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
137
+ ON CONFLICT (run_id, seq) DO NOTHING`, [
138
+ event.runId,
139
+ event.seq,
140
+ event.id,
141
+ event.ts,
142
+ event.type,
143
+ jsonText(event.payload),
144
+ event.threadId,
145
+ event.parentThreadId ?? null,
146
+ event.causationId ?? null,
147
+ event.correlationId ?? null,
148
+ event.effectId ?? null,
149
+ jsonText(event.origin),
150
+ event.idempotencyKey ?? null,
151
+ event.ephemeral === true ? 1 : 0,
152
+ ]));
153
+ }
154
+ function runIndexPatches(ops) {
155
+ const patches = new Map();
156
+ for (const op of ops) {
157
+ if (op.type === 'insert') {
158
+ continue;
159
+ }
160
+ const patch = patches.get(op.runId) ?? {
161
+ runId: op.runId,
162
+ start: null,
163
+ finish: null,
164
+ completedAt: null,
165
+ updatedAt: op.at,
166
+ };
167
+ patch.updatedAt = Math.max(patch.updatedAt, op.at);
168
+ if (op.type === 'start') {
169
+ patch.start ??= op;
170
+ }
171
+ if (op.type === 'finish') {
172
+ patch.finish = op;
173
+ patch.completedAt ??= op.at;
174
+ }
175
+ patches.set(op.runId, patch);
176
+ }
177
+ return [...patches.values()];
178
+ }
179
+ function upsertRun(patch) {
180
+ const start = patch.start;
181
+ return sqlStatement(`INSERT INTO looms_run_index (
182
+ run_id, status, kind, definition_name, definition_version, root_thread_id,
183
+ parent_run_id, launched_by_effect_id, correlation_id, attributes,
184
+ tenant, project, org, started_at, updated_at, completed_at
185
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
186
+ ON CONFLICT (run_id) DO UPDATE SET
187
+ status = CASE
188
+ WHEN excluded.completed_at IS NOT NULL THEN excluded.status
189
+ WHEN looms_run_index.status IN ('completed', 'failed', 'cancelled') THEN looms_run_index.status
190
+ ELSE excluded.status
191
+ END,
192
+ kind = COALESCE(looms_run_index.kind, excluded.kind),
193
+ definition_name = COALESCE(looms_run_index.definition_name, excluded.definition_name),
194
+ definition_version = COALESCE(looms_run_index.definition_version, excluded.definition_version),
195
+ root_thread_id = COALESCE(looms_run_index.root_thread_id, excluded.root_thread_id),
196
+ parent_run_id = COALESCE(looms_run_index.parent_run_id, excluded.parent_run_id),
197
+ launched_by_effect_id = COALESCE(looms_run_index.launched_by_effect_id, excluded.launched_by_effect_id),
198
+ correlation_id = COALESCE(looms_run_index.correlation_id, excluded.correlation_id),
199
+ attributes = CASE
200
+ WHEN looms_run_index.attributes = '{}' THEN excluded.attributes
201
+ ELSE looms_run_index.attributes
202
+ END,
203
+ tenant = COALESCE(looms_run_index.tenant, excluded.tenant),
204
+ project = COALESCE(looms_run_index.project, excluded.project),
205
+ org = COALESCE(looms_run_index.org, excluded.org),
206
+ started_at = COALESCE(looms_run_index.started_at, excluded.started_at),
207
+ updated_at = MAX(looms_run_index.updated_at, excluded.updated_at),
208
+ completed_at = COALESCE(looms_run_index.completed_at, excluded.completed_at)`, [
209
+ patch.runId,
210
+ patch.finish?.status ?? 'running',
211
+ start?.kind ?? null,
212
+ start?.definitionName ?? null,
213
+ start?.definitionVersion ?? null,
214
+ start?.rootThreadId ?? null,
215
+ start?.parentRunId ?? null,
216
+ start?.launchedByEffectId ?? null,
217
+ start?.correlationId ?? null,
218
+ jsonText(start?.attributes ?? {}),
219
+ start?.tenant ?? null,
220
+ start?.project ?? null,
221
+ start?.org ?? null,
222
+ start ? start.at : null,
223
+ patch.updatedAt,
224
+ patch.completedAt,
225
+ ]);
226
+ }
227
+ function runIndexStatements(ops) {
228
+ const statements = [];
229
+ for (const patch of runIndexPatches(ops)) {
230
+ if (patch.start || patch.finish) {
231
+ statements.push(upsertRun(patch));
232
+ continue;
233
+ }
234
+ statements.push(sqlStatement(`UPDATE looms_run_index SET updated_at = MAX(updated_at, ?) WHERE run_id = ?`, [
235
+ patch.updatedAt,
236
+ patch.runId,
237
+ ]));
238
+ }
239
+ return statements;
240
+ }
241
+ function indexStatements(ops) {
242
+ return ops.map((op) => {
243
+ switch (op.type) {
244
+ case 'upsertActor':
245
+ return sqlStatement(`INSERT INTO looms_run_actors (
246
+ run_id, actor_id, kind, status, definition_name, parent_actor_id,
247
+ launched_by_run_id, launched_by_effect_id, correlation_id, updated_at
248
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
249
+ ON CONFLICT (run_id, actor_id) DO UPDATE SET
250
+ kind = excluded.kind,
251
+ status = excluded.status,
252
+ definition_name = excluded.definition_name,
253
+ parent_actor_id = excluded.parent_actor_id,
254
+ launched_by_run_id = excluded.launched_by_run_id,
255
+ launched_by_effect_id = excluded.launched_by_effect_id,
256
+ correlation_id = excluded.correlation_id,
257
+ updated_at = excluded.updated_at`, [
258
+ op.runId,
259
+ op.actorId,
260
+ op.kind,
261
+ op.status,
262
+ op.definitionName,
263
+ op.parentActorId,
264
+ op.launchedByRunId,
265
+ op.launchedByEffectId,
266
+ op.correlationId,
267
+ op.updatedAt,
268
+ ]);
269
+ case 'setActorStatus':
270
+ return sqlStatement(`INSERT INTO looms_run_actors (run_id, actor_id, status, updated_at)
271
+ VALUES (?, ?, ?, ?)
272
+ ON CONFLICT (run_id, actor_id) DO UPDATE SET
273
+ status = excluded.status,
274
+ updated_at = excluded.updated_at`, [op.runId, op.actorId, op.status, op.updatedAt]);
275
+ case 'upsertReview':
276
+ return sqlStatement(`INSERT INTO looms_run_reviews (run_id, review_id, status, title, updated_at)
277
+ VALUES (?, ?, ?, ?, ?)
278
+ ON CONFLICT (run_id, review_id) DO UPDATE SET
279
+ status = excluded.status,
280
+ updated_at = excluded.updated_at`, [op.runId, op.reviewId, op.status, op.title, op.updatedAt]);
281
+ case 'setReviewStatus':
282
+ return sqlStatement(`UPDATE looms_run_reviews SET status = ?, updated_at = ? WHERE run_id = ? AND review_id = ?`, [op.status, op.updatedAt, op.runId, op.reviewId]);
283
+ default: {
284
+ const unexpected = op;
285
+ return unexpected;
286
+ }
287
+ }
288
+ });
289
+ }
290
+ export function sqliteReplica(options) {
291
+ const database = options.database;
292
+ let ready;
293
+ const appliedMigrationIds = async () => {
294
+ const table = await database.get(`SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'looms_schema_migrations'`);
295
+ if (!table) {
296
+ return new Set();
297
+ }
298
+ const rows = await database.all(`SELECT id FROM looms_schema_migrations`);
299
+ return new Set(rows.map((row) => row.id));
300
+ };
301
+ const pendingMigrations = async () => {
302
+ const applied = await appliedMigrationIds();
303
+ return SQLITE_REPLICA_MIGRATIONS.filter((migration) => !applied.has(migration.id)).map((migration) => migration.id);
304
+ };
305
+ const migrate = async () => {
306
+ const applied = await appliedMigrationIds();
307
+ for (const migration of SQLITE_REPLICA_MIGRATIONS) {
308
+ if (!applied.has(migration.id)) {
309
+ await database.exec(migration.sql);
310
+ }
311
+ }
312
+ };
313
+ const verify = async () => {
314
+ const pending = await pendingMigrations();
315
+ if (pending.length > 0) {
316
+ throw new Error(`Looms replica is missing migrations: ${pending.join(', ')}. Generate them with \`looms replica generate --dialect sqlite\` and apply the files before starting.`);
317
+ }
318
+ };
319
+ const init = () => {
320
+ ready ??= (options.migrate === 'verify' ? verify() : migrate()).catch((cause) => {
321
+ ready = undefined;
322
+ throw cause;
323
+ });
324
+ return ready;
325
+ };
326
+ const project = async (events) => {
327
+ await init();
328
+ if (events.length === 0) {
329
+ return;
330
+ }
331
+ const statements = [];
332
+ for (const [runId, batch] of groups(events)) {
333
+ const progress = await database.get(`SELECT replicated_seq, purged_at FROM looms_run_index WHERE run_id = ?`, [runId]);
334
+ if (progress?.purged_at != null) {
335
+ continue;
336
+ }
337
+ const replicatedSeq = progress ? asNumber(progress.replicated_seq) : 0;
338
+ const next = contiguousSeq(runId, replicatedSeq, batch);
339
+ const durable = batch.filter((event) => !event.ephemeral);
340
+ const last = batch.at(-1);
341
+ statements.push(...insertEvents(batch));
342
+ statements.push(...runIndexStatements(durable.flatMap((event) => eventLogOps(event))));
343
+ statements.push(...indexStatements(durable.flatMap(indexOpsFor)));
344
+ if (next === replicatedSeq || !last) {
345
+ continue;
346
+ }
347
+ statements.push(sqlStatement(`INSERT INTO looms_run_index (run_id, status, updated_at, replicated_seq)
348
+ VALUES (?, 'running', ?, ?)
349
+ ON CONFLICT (run_id) DO UPDATE SET
350
+ replicated_seq = MAX(looms_run_index.replicated_seq, excluded.replicated_seq)
351
+ WHERE looms_run_index.purged_at IS NULL`, [runId, last.ts, next]));
352
+ }
353
+ await database.batch(statements);
354
+ };
355
+ const position = async (runId) => {
356
+ const row = await database.get(`SELECT replicated_seq, purged_at FROM looms_run_index WHERE run_id = ?`, [runId]);
357
+ if (!row) {
358
+ return 0;
359
+ }
360
+ if (row.purged_at != null) {
361
+ return null;
362
+ }
363
+ return asNumber(row.replicated_seq);
364
+ };
365
+ const readPage = async (runId, fromSeq, limit) => {
366
+ const rows = await database.all(`SELECT run_id, seq, event_id, ts, type, payload, thread_id, parent_thread_id,
367
+ causation_id, correlation_id, effect_id, origin, idempotency_key, ephemeral
368
+ FROM looms_run_events
369
+ WHERE run_id = ? AND seq >= ?
370
+ ORDER BY seq
371
+ LIMIT ?`, [runId, fromSeq, limit]);
372
+ return rows.map(envelope);
373
+ };
374
+ const readEvents = (runId, readOptions) => Effect.tryPromise({
375
+ try: async () => {
376
+ const fromSeq = readOptions?.fromSeq ?? 1;
377
+ const events = [];
378
+ let cursor = fromSeq;
379
+ let remaining = readOptions?.limit;
380
+ while (remaining === undefined || remaining > 0) {
381
+ const take = remaining === undefined ? READ_PAGE : Math.min(READ_PAGE, remaining);
382
+ const page = await readPage(runId, cursor, take);
383
+ events.push(...page);
384
+ if (remaining !== undefined) {
385
+ remaining -= page.length;
386
+ }
387
+ const last = page.at(-1);
388
+ if (!last || page.length < take) {
389
+ break;
390
+ }
391
+ cursor = last.seq + 1;
392
+ }
393
+ return events;
394
+ },
395
+ catch: (cause) => new EventStoreError('Replica read failed', cause),
396
+ });
397
+ const store = {
398
+ append: () => Effect.fail(new EventStoreError('The SQLite replica is read-only')),
399
+ read: readEvents,
400
+ readStream: (runId, readOptions) => Stream.fromIterableEffect(readEvents(runId, readOptions)),
401
+ tail: (runId) => Effect.tryPromise({
402
+ try: async () => {
403
+ const row = await database.get(`SELECT replicated_seq FROM looms_run_index WHERE run_id = ?`, [runId]);
404
+ return row ? asNumber(row.replicated_seq) : 0;
405
+ },
406
+ catch: (cause) => new EventStoreError('Replica tail failed', cause),
407
+ }),
408
+ bounds: (runId) => Effect.tryPromise({
409
+ try: async () => {
410
+ const row = await database.get(`SELECT replicated_seq,
411
+ (SELECT MIN(seq) FROM looms_run_events event WHERE event.run_id = run.run_id) AS head
412
+ FROM looms_run_index run
413
+ WHERE run.run_id = ?`, [runId]);
414
+ if (!row) {
415
+ return { head: 1, tail: 0 };
416
+ }
417
+ const tail = asNumber(row.replicated_seq);
418
+ const head = row.head === null ? tail + 1 : asNumber(row.head);
419
+ return { head, tail };
420
+ },
421
+ catch: (cause) => new EventStoreError('Replica bounds failed', cause),
422
+ }),
423
+ trim: () => Effect.fail(new EventStoreError('Trim a replica with purge()')),
424
+ subscribe: (runId, readOptions) => Stream.fromIterableEffect(readEvents(runId, readOptions)),
425
+ listRuns: Effect.tryPromise({
426
+ try: async () => {
427
+ const rows = await database.all(`SELECT run_id FROM looms_run_index WHERE purged_at IS NULL ORDER BY run_id`);
428
+ return rows.map((row) => row.run_id);
429
+ },
430
+ catch: (cause) => new EventStoreError('Replica listRuns failed', cause),
431
+ }),
432
+ };
433
+ const loadRun = async (runId, registry) => {
434
+ const events = await Effect.runPromise(readEvents(runId));
435
+ return foldRun(events, registry, { runId });
436
+ };
437
+ const status = async (runId) => {
438
+ const row = await database.get(`SELECT run.replicated_seq,
439
+ run.status,
440
+ run.purged_at,
441
+ (SELECT MAX(seq) FROM looms_run_events event WHERE event.run_id = run.run_id) AS max_seq
442
+ FROM looms_run_index run
443
+ WHERE run.run_id = ?`, [runId]);
444
+ if (!row) {
445
+ return null;
446
+ }
447
+ const replicatedSeq = asNumber(row.replicated_seq);
448
+ const finished = terminalStatuses.has(row.status);
449
+ const purgedAt = epochOrNull(row.purged_at);
450
+ const maxSeq = row.max_seq === null ? null : asNumber(row.max_seq);
451
+ const copiedThroughFinish = purgedAt !== null || (maxSeq !== null && maxSeq === replicatedSeq && replicatedSeq > 0);
452
+ return {
453
+ replicatedSeq,
454
+ finished,
455
+ complete: finished && copiedThroughFinish,
456
+ purgedAt,
457
+ };
458
+ };
459
+ const purge = async (purgeOptions) => {
460
+ const keepIndex = purgeOptions.keepIndex !== false;
461
+ const doomed = await database.all(`SELECT run_id FROM looms_run_index
462
+ WHERE purged_at IS NULL
463
+ AND status IN ('completed', 'failed', 'cancelled')
464
+ AND completed_at IS NOT NULL
465
+ AND completed_at < ?`, [purgeOptions.finishedBefore]);
466
+ if (doomed.length === 0) {
467
+ return { runs: 0 };
468
+ }
469
+ const purgedAt = Date.now();
470
+ const statements = [];
471
+ for (const row of doomed) {
472
+ statements.push(sqlStatement(`UPDATE looms_run_index SET purged_at = ? WHERE run_id = ? AND purged_at IS NULL`, [purgedAt, row.run_id]), sqlStatement(`DELETE FROM looms_run_events WHERE run_id = ?`, [row.run_id]));
473
+ if (!keepIndex) {
474
+ statements.push(sqlStatement(`DELETE FROM looms_run_actors WHERE run_id = ?`, [row.run_id]), sqlStatement(`DELETE FROM looms_run_reviews WHERE run_id = ?`, [row.run_id]), sqlStatement(`DELETE FROM looms_run_index WHERE run_id = ?`, [row.run_id]));
475
+ }
476
+ }
477
+ await database.batch(statements);
478
+ return { runs: doomed.length };
479
+ };
480
+ const rebuild = async (source) => {
481
+ await init();
482
+ const runIds = await Effect.runPromise(source.listRuns);
483
+ let copied = 0;
484
+ for (const runId of runIds) {
485
+ let fromSeq = 1;
486
+ while (true) {
487
+ const events = await Effect.runPromise(source.read(runId, { fromSeq, limit: READ_PAGE }));
488
+ if (events.length === 0) {
489
+ break;
490
+ }
491
+ await project(events);
492
+ copied += events.length;
493
+ const last = events.at(-1);
494
+ if (!last || events.length < READ_PAGE) {
495
+ break;
496
+ }
497
+ fromSeq = last.seq + 1;
498
+ }
499
+ }
500
+ return copied;
501
+ };
502
+ return {
503
+ name: REPLICA_NAME,
504
+ version: REPLICA_VERSION,
505
+ init,
506
+ position,
507
+ project,
508
+ migrate,
509
+ pendingMigrations,
510
+ eventStore: () => store,
511
+ loadRun,
512
+ status,
513
+ purge,
514
+ rebuild,
515
+ };
516
+ }
517
+ export { ReplicaGapError };
@@ -1,7 +1,8 @@
1
1
  /**
2
2
  * SQL schema for the optional Looms secondary index.
3
+ * The Postgres statements live with the replica migrations so there is one DDL source.
3
4
  */
4
- export declare const POSTGRES_SCHEMA_SQL: string;
5
+ export { POSTGRES_SCHEMA_SQL } from './replica/migrations';
5
6
  export declare const SQLITE_TABLES_SQL: string;
6
7
  /** Columns added after the first release. SQLite cannot add a column only if it is missing. */
7
8
  export declare const SQLITE_ADDED_ACTOR_COLUMNS: readonly ['launched_by_run_id', 'launched_by_effect_id', 'correlation_id'];
@@ -1,37 +1,8 @@
1
1
  /**
2
2
  * SQL schema for the optional Looms secondary index.
3
+ * The Postgres statements live with the replica migrations so there is one DDL source.
3
4
  */
4
- export const POSTGRES_SCHEMA_SQL = `
5
- CREATE TABLE IF NOT EXISTS looms_run_actors (
6
- run_id TEXT NOT NULL,
7
- actor_id TEXT NOT NULL,
8
- kind TEXT,
9
- status TEXT,
10
- definition_name TEXT,
11
- parent_actor_id TEXT,
12
- launched_by_run_id TEXT,
13
- launched_by_effect_id TEXT,
14
- correlation_id TEXT,
15
- updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
16
- PRIMARY KEY (run_id, actor_id)
17
- );
18
-
19
- ALTER TABLE looms_run_actors ADD COLUMN IF NOT EXISTS launched_by_run_id TEXT;
20
- ALTER TABLE looms_run_actors ADD COLUMN IF NOT EXISTS launched_by_effect_id TEXT;
21
- ALTER TABLE looms_run_actors ADD COLUMN IF NOT EXISTS correlation_id TEXT;
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 TIMESTAMPTZ NOT NULL DEFAULT NOW(),
32
- PRIMARY KEY (run_id, review_id)
33
- );
34
- `.trim();
5
+ export { POSTGRES_SCHEMA_SQL } from './replica/migrations.js';
35
6
  export const SQLITE_TABLES_SQL = `
36
7
  CREATE TABLE IF NOT EXISTS looms_run_actors (
37
8
  run_id TEXT NOT NULL,
@@ -103,6 +103,15 @@ export function sqliteProjectorCursorStore(exec) {
103
103
  failed_seq = NULL, next_retry_at = NULL, last_error = NULL,
104
104
  updated_at = excluded.updated_at`, [runId, projector.name, projector.version, cursor, now]);
105
105
  }),
106
+ rewind: (runId, projector, cursor, now) => query(() => {
107
+ exec.run(`INSERT INTO looms_projector_delivery
108
+ (run_id, projector_name, projector_version, cursor, state, attempts, updated_at)
109
+ VALUES (?, ?, ?, ?, 'idle', 0, ?)
110
+ ON CONFLICT (run_id, projector_name, projector_version) DO UPDATE
111
+ SET cursor = excluded.cursor, state = 'idle', attempts = 0,
112
+ failed_seq = NULL, next_retry_at = NULL, last_error = NULL,
113
+ updated_at = excluded.updated_at`, [runId, projector.name, projector.version, cursor, now]);
114
+ }),
106
115
  fail: (runId, projector, failure) => query(() => {
107
116
  exec.run(`INSERT INTO looms_projector_delivery
108
117
  (run_id, projector_name, projector_version, state, attempts, failed_seq,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@swirls/looms",
3
- "version": "0.7.0",
3
+ "version": "0.9.0",
4
4
  "description": "Pluggable event-sourced runtime for durable agents and workflows",
5
5
  "homepage": "https://github.com/ByteSliceHQ/looms#readme",
6
6
  "bugs": {
@@ -137,6 +137,46 @@
137
137
  "types": "./dist/projectors/sqlite.d.ts",
138
138
  "import": "./dist/projectors/sqlite.js"
139
139
  },
140
+ "./projectors/replica": {
141
+ "types": "./dist/projectors/replica/postgres.d.ts",
142
+ "import": "./dist/projectors/replica/postgres.js"
143
+ },
144
+ "./projectors/replica/drizzle": {
145
+ "types": "./dist/projectors/replica/drizzle.d.ts",
146
+ "import": "./dist/projectors/replica/drizzle.js"
147
+ },
148
+ "./projectors/replica/migrations": {
149
+ "types": "./dist/projectors/replica/migrations.d.ts",
150
+ "import": "./dist/projectors/replica/migrations.js"
151
+ },
152
+ "./replica": {
153
+ "types": "./dist/projectors/replica/postgres.d.ts",
154
+ "import": "./dist/projectors/replica/postgres.js"
155
+ },
156
+ "./replica/drizzle": {
157
+ "types": "./dist/projectors/replica/drizzle.d.ts",
158
+ "import": "./dist/projectors/replica/drizzle.js"
159
+ },
160
+ "./replica/migrations": {
161
+ "types": "./dist/projectors/replica/migrations.d.ts",
162
+ "import": "./dist/projectors/replica/migrations.js"
163
+ },
164
+ "./replica/sqlite": {
165
+ "types": "./dist/projectors/replica/sqlite.d.ts",
166
+ "import": "./dist/projectors/replica/sqlite.js"
167
+ },
168
+ "./replica/sqlite-bun": {
169
+ "types": "./dist/projectors/replica/sqlite-bun.d.ts",
170
+ "import": "./dist/projectors/replica/sqlite-bun.js"
171
+ },
172
+ "./projectors/replica/sqlite": {
173
+ "types": "./dist/projectors/replica/sqlite.d.ts",
174
+ "import": "./dist/projectors/replica/sqlite.js"
175
+ },
176
+ "./projectors/replica/sqlite-bun": {
177
+ "types": "./dist/projectors/replica/sqlite-bun.d.ts",
178
+ "import": "./dist/projectors/replica/sqlite-bun.js"
179
+ },
140
180
  "./s2/projector": {
141
181
  "types": "./dist/s2/projector.d.ts",
142
182
  "import": "./dist/s2/projector.js"
@@ -197,6 +237,7 @@
197
237
  "peerDependencies": {
198
238
  "@cloudflare/workers-types": "^5.20260914.1",
199
239
  "ai": "^7.0.0",
240
+ "drizzle-orm": "^0.44.0",
200
241
  "postgres": "^3.4.0",
201
242
  "react": "^19.0.0",
202
243
  "react-dom": "^19.0.0"
@@ -205,6 +246,9 @@
205
246
  "ai": {
206
247
  "optional": true
207
248
  },
249
+ "drizzle-orm": {
250
+ "optional": true
251
+ },
208
252
  "postgres": {
209
253
  "optional": true
210
254
  },