@swirls/looms 0.7.0 → 0.8.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 };
@@ -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.8.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,30 @@
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
+ },
140
164
  "./s2/projector": {
141
165
  "types": "./dist/s2/projector.d.ts",
142
166
  "import": "./dist/s2/projector.js"
@@ -197,6 +221,7 @@
197
221
  "peerDependencies": {
198
222
  "@cloudflare/workers-types": "^5.20260914.1",
199
223
  "ai": "^7.0.0",
224
+ "drizzle-orm": "^0.44.0",
200
225
  "postgres": "^3.4.0",
201
226
  "react": "^19.0.0",
202
227
  "react-dom": "^19.0.0"
@@ -205,6 +230,9 @@
205
230
  "ai": {
206
231
  "optional": true
207
232
  },
233
+ "drizzle-orm": {
234
+ "optional": true
235
+ },
208
236
  "postgres": {
209
237
  "optional": true
210
238
  },