@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.
- package/CHANGELOG.md +14 -0
- package/dist/cli/commands.js +136 -1
- package/dist/projectors/delivery.d.ts +8 -3
- package/dist/projectors/delivery.js +29 -2
- package/dist/projectors/event-log-ops.d.ts +68 -0
- package/dist/projectors/event-log-ops.js +79 -0
- package/dist/projectors/event-log.d.ts +11 -69
- package/dist/projectors/event-log.js +50 -139
- package/dist/projectors/index.d.ts +1 -0
- package/dist/projectors/index.js +1 -0
- package/dist/projectors/postgres.d.ts +4 -1
- package/dist/projectors/postgres.js +6 -4
- package/dist/projectors/projector.d.ts +16 -0
- package/dist/projectors/projector.js +3 -0
- package/dist/projectors/replica/drizzle.d.ts +1192 -0
- package/dist/projectors/replica/drizzle.js +119 -0
- package/dist/projectors/replica/migrations.d.ts +33 -0
- package/dist/projectors/replica/migrations.js +247 -0
- package/dist/projectors/replica/postgres.d.ts +57 -0
- package/dist/projectors/replica/postgres.js +356 -0
- package/dist/projectors/replica/sqlite-bun.d.ts +5 -0
- package/dist/projectors/replica/sqlite-bun.js +39 -0
- package/dist/projectors/replica/sqlite-migrations.d.ts +5 -0
- package/dist/projectors/replica/sqlite-migrations.js +99 -0
- package/dist/projectors/replica/sqlite.d.ts +95 -0
- package/dist/projectors/replica/sqlite.js +517 -0
- package/dist/projectors/schema.d.ts +2 -1
- package/dist/projectors/schema.js +2 -31
- package/dist/projectors/sqlite-delivery.js +9 -0
- package/package.json +45 -1
|
@@ -1,97 +1,11 @@
|
|
|
1
|
-
import { DateTime, Effect
|
|
1
|
+
import { DateTime, Effect } from 'effect';
|
|
2
2
|
import createPostgresClient, {} from 'postgres';
|
|
3
|
-
import {
|
|
3
|
+
import {} from '@swirls/looms/core';
|
|
4
|
+
import { eventLogOps } from './event-log-ops.js';
|
|
4
5
|
import { runProjectorPromise } from './projector.js';
|
|
5
|
-
|
|
6
|
-
export
|
|
7
|
-
CREATE TABLE IF NOT EXISTS looms_run_events (
|
|
8
|
-
run_id TEXT NOT NULL,
|
|
9
|
-
seq BIGINT NOT NULL,
|
|
10
|
-
event_id TEXT NOT NULL,
|
|
11
|
-
ts TIMESTAMPTZ NOT NULL,
|
|
12
|
-
type TEXT NOT NULL,
|
|
13
|
-
payload JSONB NOT NULL,
|
|
14
|
-
thread_id TEXT,
|
|
15
|
-
parent_thread_id TEXT,
|
|
16
|
-
causation_id TEXT,
|
|
17
|
-
correlation_id TEXT,
|
|
18
|
-
effect_id TEXT,
|
|
19
|
-
origin JSONB NOT NULL,
|
|
20
|
-
idempotency_key TEXT,
|
|
21
|
-
PRIMARY KEY (run_id, seq)
|
|
22
|
-
);
|
|
23
|
-
|
|
24
|
-
CREATE TABLE IF NOT EXISTS looms_run_index (
|
|
25
|
-
run_id TEXT PRIMARY KEY,
|
|
26
|
-
status TEXT NOT NULL,
|
|
27
|
-
kind TEXT,
|
|
28
|
-
definition_name TEXT,
|
|
29
|
-
definition_version TEXT,
|
|
30
|
-
root_thread_id TEXT,
|
|
31
|
-
parent_run_id TEXT,
|
|
32
|
-
launched_by_effect_id TEXT,
|
|
33
|
-
correlation_id TEXT,
|
|
34
|
-
attributes JSONB NOT NULL DEFAULT '{}'::jsonb,
|
|
35
|
-
tenant TEXT,
|
|
36
|
-
project TEXT,
|
|
37
|
-
org TEXT,
|
|
38
|
-
started_at TIMESTAMPTZ,
|
|
39
|
-
updated_at TIMESTAMPTZ NOT NULL,
|
|
40
|
-
completed_at TIMESTAMPTZ
|
|
41
|
-
);
|
|
42
|
-
|
|
43
|
-
CREATE INDEX IF NOT EXISTS looms_run_index_tenant ON looms_run_index (tenant);
|
|
44
|
-
CREATE INDEX IF NOT EXISTS looms_run_index_project ON looms_run_index (project);
|
|
45
|
-
CREATE INDEX IF NOT EXISTS looms_run_index_org ON looms_run_index (org);
|
|
46
|
-
CREATE INDEX IF NOT EXISTS looms_run_index_parent ON looms_run_index (parent_run_id);
|
|
47
|
-
CREATE INDEX IF NOT EXISTS looms_run_index_status ON looms_run_index (status);
|
|
48
|
-
`.trim();
|
|
6
|
+
import { POSTGRES_EVENT_LOG_SCHEMA_SQL } from './replica/migrations.js';
|
|
7
|
+
export { POSTGRES_EVENT_LOG_SCHEMA_SQL, eventLogOps };
|
|
49
8
|
const terminal = new Set(['completed', 'failed', 'cancelled']);
|
|
50
|
-
export function eventLogOps(event) {
|
|
51
|
-
if (event.ephemeral) {
|
|
52
|
-
return [];
|
|
53
|
-
}
|
|
54
|
-
const entry = {
|
|
55
|
-
runId: event.runId,
|
|
56
|
-
seq: event.seq,
|
|
57
|
-
eventId: event.id,
|
|
58
|
-
ts: event.ts,
|
|
59
|
-
type: event.type,
|
|
60
|
-
payload: event.payload,
|
|
61
|
-
threadId: event.threadId,
|
|
62
|
-
parentThreadId: event.parentThreadId ?? null,
|
|
63
|
-
causationId: event.causationId ?? null,
|
|
64
|
-
correlationId: event.correlationId ?? null,
|
|
65
|
-
effectId: event.effectId ?? null,
|
|
66
|
-
origin: event.origin,
|
|
67
|
-
idempotencyKey: event.idempotencyKey ?? null,
|
|
68
|
-
};
|
|
69
|
-
const payload = isJsonObject(event.payload) ? event.payload : {};
|
|
70
|
-
switch (event.type) {
|
|
71
|
-
case 'runtime.run.started':
|
|
72
|
-
return [{ type: 'insert', entry }, startOp(event, payload)];
|
|
73
|
-
case 'runtime.run.completed':
|
|
74
|
-
return [
|
|
75
|
-
{ type: 'insert', entry },
|
|
76
|
-
{
|
|
77
|
-
type: 'finish',
|
|
78
|
-
runId: event.runId,
|
|
79
|
-
status: completedRunStatus(event.payload),
|
|
80
|
-
at: event.ts,
|
|
81
|
-
},
|
|
82
|
-
];
|
|
83
|
-
case 'runtime.run.cancelled':
|
|
84
|
-
return [
|
|
85
|
-
{ type: 'insert', entry },
|
|
86
|
-
{ type: 'finish', runId: event.runId, status: 'cancelled', at: event.ts },
|
|
87
|
-
];
|
|
88
|
-
default:
|
|
89
|
-
return [
|
|
90
|
-
{ type: 'insert', entry },
|
|
91
|
-
{ type: 'touch', runId: event.runId, at: event.ts },
|
|
92
|
-
];
|
|
93
|
-
}
|
|
94
|
-
}
|
|
95
9
|
export function memoryEventLog() {
|
|
96
10
|
const events = new Map();
|
|
97
11
|
const runs = new Map();
|
|
@@ -225,36 +139,6 @@ function mergeFinish(existing, op) {
|
|
|
225
139
|
function utcDate(ms) {
|
|
226
140
|
return DateTime.toDateUtc(DateTime.makeUnsafe(ms));
|
|
227
141
|
}
|
|
228
|
-
function startOp(event, payload) {
|
|
229
|
-
const launchedBy = readRunLaunchSource(payload.launchedBy === undefined ? undefined : payload.launchedBy);
|
|
230
|
-
const attributes = readAttributes(payload.attributes);
|
|
231
|
-
return {
|
|
232
|
-
type: 'start',
|
|
233
|
-
runId: event.runId,
|
|
234
|
-
kind: readString(payload, 'kind'),
|
|
235
|
-
definitionName: readString(payload, 'definitionName'),
|
|
236
|
-
definitionVersion: readString(payload, 'definitionVersion'),
|
|
237
|
-
rootThreadId: readString(payload, 'rootThreadId'),
|
|
238
|
-
parentRunId: launchedBy?.runId ?? null,
|
|
239
|
-
launchedByEffectId: launchedBy?.effectId ?? null,
|
|
240
|
-
correlationId: event.correlationId ?? null,
|
|
241
|
-
attributes,
|
|
242
|
-
tenant: attributes.tenant ?? null,
|
|
243
|
-
project: attributes.project ?? null,
|
|
244
|
-
org: attributes.org ?? null,
|
|
245
|
-
at: event.ts,
|
|
246
|
-
};
|
|
247
|
-
}
|
|
248
|
-
function readString(payload, key) {
|
|
249
|
-
const value = payload[key];
|
|
250
|
-
return Predicate.isString(value) ? value : null;
|
|
251
|
-
}
|
|
252
|
-
function readAttributes(value) {
|
|
253
|
-
if (value === undefined) {
|
|
254
|
-
return {};
|
|
255
|
-
}
|
|
256
|
-
return Option.getOrElse(decodeAttributes(value), () => ({}));
|
|
257
|
-
}
|
|
258
142
|
function postgresStore(sql, ownsClient) {
|
|
259
143
|
return {
|
|
260
144
|
init: () => runProjectorPromise('postgres-event-log', () => sql.unsafe(POSTGRES_EVENT_LOG_SCHEMA_SQL)).then(() => undefined),
|
|
@@ -297,15 +181,16 @@ function runIndexPatches(ops) {
|
|
|
297
181
|
}
|
|
298
182
|
return [...patches.values()];
|
|
299
183
|
}
|
|
300
|
-
function applySqlOps(sql, ops) {
|
|
301
|
-
const
|
|
184
|
+
export function applySqlOps(sql, ops) {
|
|
185
|
+
const events = ops.flatMap((op) => (op.type === 'insert' ? [envelopeFromEntry(op.entry)] : []));
|
|
186
|
+
return Promise.all([insertRunEvents(sql, events), applyRunIndexOps(sql, ops)]).then(() => undefined);
|
|
187
|
+
}
|
|
188
|
+
/** Fold run-summary ops. Event rows are written by {@link insertRunEvents}. */
|
|
189
|
+
export function applyRunIndexOps(sql, ops) {
|
|
302
190
|
const patches = runIndexPatches(ops);
|
|
303
191
|
const upserts = patches.filter((patch) => patch.start !== null || patch.finish !== null);
|
|
304
192
|
const touches = patches.filter((patch) => patch.start === null && patch.finish === null);
|
|
305
193
|
const statements = [];
|
|
306
|
-
for (let index = 0; index < entries.length; index += INSERT_CHUNK_ROWS) {
|
|
307
|
-
statements.push(insertEvents(sql, entries.slice(index, index + INSERT_CHUNK_ROWS)));
|
|
308
|
-
}
|
|
309
194
|
if (upserts.length > 0) {
|
|
310
195
|
statements.push(upsertRuns(sql, upserts));
|
|
311
196
|
}
|
|
@@ -314,21 +199,47 @@ function applySqlOps(sql, ops) {
|
|
|
314
199
|
}
|
|
315
200
|
return Promise.all(statements).then(() => undefined);
|
|
316
201
|
}
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
202
|
+
/** Insert event envelopes, including ephemeral ones. Durable callers pass events that are already filtered. */
|
|
203
|
+
export function insertRunEvents(sql, events) {
|
|
204
|
+
const statements = [];
|
|
205
|
+
for (let index = 0; index < events.length; index += INSERT_CHUNK_ROWS) {
|
|
206
|
+
statements.push(insertEventChunk(sql, events.slice(index, index + INSERT_CHUNK_ROWS)));
|
|
207
|
+
}
|
|
208
|
+
return Promise.all(statements).then(() => undefined);
|
|
209
|
+
}
|
|
210
|
+
function envelopeFromEntry(entry) {
|
|
211
|
+
return {
|
|
212
|
+
id: entry.eventId,
|
|
213
|
+
runId: entry.runId,
|
|
320
214
|
seq: entry.seq,
|
|
321
|
-
|
|
322
|
-
ts: utcDate(entry.ts),
|
|
215
|
+
ts: entry.ts,
|
|
323
216
|
type: entry.type,
|
|
324
|
-
payload:
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
origin:
|
|
331
|
-
|
|
217
|
+
payload: entry.payload,
|
|
218
|
+
threadId: entry.threadId,
|
|
219
|
+
parentThreadId: entry.parentThreadId,
|
|
220
|
+
causationId: entry.causationId,
|
|
221
|
+
correlationId: entry.correlationId,
|
|
222
|
+
effectId: entry.effectId,
|
|
223
|
+
origin: entry.origin,
|
|
224
|
+
idempotencyKey: entry.idempotencyKey,
|
|
225
|
+
};
|
|
226
|
+
}
|
|
227
|
+
function insertEventChunk(sql, events) {
|
|
228
|
+
const rows = events.map((event) => ({
|
|
229
|
+
run_id: event.runId,
|
|
230
|
+
seq: event.seq,
|
|
231
|
+
event_id: event.id,
|
|
232
|
+
ts: utcDate(event.ts),
|
|
233
|
+
type: event.type,
|
|
234
|
+
payload: sql.json(event.payload),
|
|
235
|
+
thread_id: event.threadId,
|
|
236
|
+
parent_thread_id: event.parentThreadId ?? null,
|
|
237
|
+
causation_id: event.causationId ?? null,
|
|
238
|
+
correlation_id: event.correlationId ?? null,
|
|
239
|
+
effect_id: event.effectId ?? null,
|
|
240
|
+
origin: sql.json(event.origin),
|
|
241
|
+
idempotency_key: event.idempotencyKey ?? null,
|
|
242
|
+
ephemeral: event.ephemeral === true,
|
|
332
243
|
}));
|
|
333
244
|
return sql `
|
|
334
245
|
INSERT INTO looms_run_events ${sql(rows)}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
export type { Projector, ProjectorErrorHandler } from './projector';
|
|
2
|
+
export { ReplicaGapError } from './projector';
|
|
2
3
|
export { createProjectorDelivery, ProjectorCursorError, UnknownProjectorError, type ProjectorCursorStore, type ProjectorDeliveryFailure, type ProjectorDelivery, type ProjectorDeliveryOptions, type ProjectorDeliveryState, type ProjectorDeliveryStatus, type ProjectorObservation, type ProjectorObserver, type ProjectorOperationalStatus, } from './delivery';
|
|
3
4
|
export { sqliteProjectorCursorStore, SQLITE_PROJECTOR_DELIVERY_SCHEMA } from './sqlite-delivery';
|
|
4
5
|
export { withProjectors, projectEvents, ProjectorsStoreLive, type WithProjectorsOptions, } from './with-projectors';
|
package/dist/projectors/index.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
export { ReplicaGapError } from './projector.js';
|
|
1
2
|
export { createProjectorDelivery, ProjectorCursorError, UnknownProjectorError, } from './delivery.js';
|
|
2
3
|
export { sqliteProjectorCursorStore, SQLITE_PROJECTOR_DELIVERY_SCHEMA } from './sqlite-delivery.js';
|
|
3
4
|
export { withProjectors, projectEvents, ProjectorsStoreLive, } from './with-projectors.js';
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { type Sql } from 'postgres';
|
|
2
|
-
import { type IndexProjector } from './index-model';
|
|
2
|
+
import { type IndexOp, type IndexProjector } from './index-model';
|
|
3
3
|
export { POSTGRES_SCHEMA_SQL } from './schema';
|
|
4
4
|
export { memoryEventLog, postgresEventLog, POSTGRES_EVENT_LOG_SCHEMA_SQL, type EventLogEntry, type EventLogProjector, type MemoryEventLog, type RunLogRow, } from './event-log';
|
|
5
5
|
export type PostgresProjectorOptions = {
|
|
@@ -7,4 +7,7 @@ export type PostgresProjectorOptions = {
|
|
|
7
7
|
} | {
|
|
8
8
|
sql: Sql;
|
|
9
9
|
};
|
|
10
|
+
type SqlTag = (strings: TemplateStringsArray, ...values: readonly any[]) => PromiseLike<void>;
|
|
11
|
+
/** Apply actor and review index operations on an existing connection or transaction. */
|
|
12
|
+
export declare function applyIndexOps(sql: SqlTag, ops: readonly IndexOp[]): Promise<void>;
|
|
10
13
|
export declare function postgres(options: PostgresProjectorOptions): IndexProjector;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { DateTime
|
|
1
|
+
import { DateTime } from 'effect';
|
|
2
2
|
import createPostgresClient, {} from 'postgres';
|
|
3
3
|
import { createIndexProjector, } from './index-model.js';
|
|
4
4
|
import { runProjectorPromise } from './projector.js';
|
|
@@ -72,14 +72,16 @@ function applyOp(sql, op) {
|
|
|
72
72
|
}
|
|
73
73
|
}
|
|
74
74
|
}
|
|
75
|
+
/** Apply actor and review index operations on an existing connection or transaction. */
|
|
76
|
+
export function applyIndexOps(sql, ops) {
|
|
77
|
+
return ops.reduce((chain, op) => chain.then(() => Promise.resolve(applyOp(sql, op)).then(() => undefined)), Promise.resolve());
|
|
78
|
+
}
|
|
75
79
|
export function postgres(options) {
|
|
76
80
|
const createdClient = ownsClient(options);
|
|
77
81
|
const sql = createdClient ? createPostgresClient(options.url) : options.sql;
|
|
78
82
|
const backend = {
|
|
79
83
|
init: () => runProjectorPromise('postgres', () => sql.unsafe(POSTGRES_SCHEMA_SQL)).then(() => undefined),
|
|
80
|
-
applyOps: (ops) => runProjectorPromise('postgres', () => sql.begin((tx) =>
|
|
81
|
-
discard: true,
|
|
82
|
-
})))).then(() => undefined),
|
|
84
|
+
applyOps: (ops) => runProjectorPromise('postgres', () => sql.begin((tx) => applyIndexOps(tx, ops))).then(() => undefined),
|
|
83
85
|
getActor: (runId, actorId) => runProjectorPromise('postgres', () => sql `
|
|
84
86
|
SELECT * FROM looms_run_actors WHERE run_id = ${runId} AND actor_id = ${actorId}
|
|
85
87
|
`).then((rows) => {
|
|
@@ -13,6 +13,16 @@ export declare class ProjectorError extends ProjectorError_base<{
|
|
|
13
13
|
export declare function runProjectorEffect<A>(projector: string, operation: () => PromiseLike<A>): Effect.Effect<A, ProjectorError>;
|
|
14
14
|
export declare function runProjectorSync<A>(projector: string, operation: () => A): Promise<A>;
|
|
15
15
|
export declare function runProjectorPromise<A>(projector: string, operation: () => PromiseLike<A>): Promise<A>;
|
|
16
|
+
declare const ReplicaGapError_base: new <A extends Record<string, any> = {}>(args: import("effect/Types").VoidIfEmpty<{ readonly [P in keyof A as P extends "_tag" ? never : P]: A[P]; }>) => import("effect/Cause").YieldableError & {
|
|
17
|
+
readonly _tag: "ReplicaGapError";
|
|
18
|
+
} & Readonly<A>;
|
|
19
|
+
/** A replica batch started after a hole. `project` refuses it and leaves the copy unchanged. */
|
|
20
|
+
export declare class ReplicaGapError extends ReplicaGapError_base<{
|
|
21
|
+
readonly runId: string;
|
|
22
|
+
readonly replicatedSeq: number;
|
|
23
|
+
readonly batchFrom: number;
|
|
24
|
+
}> {
|
|
25
|
+
}
|
|
16
26
|
export interface Projector {
|
|
17
27
|
/** Used in error reporting / diagnostics. */
|
|
18
28
|
readonly name: string;
|
|
@@ -20,6 +30,12 @@ export interface Projector {
|
|
|
20
30
|
readonly version: string;
|
|
21
31
|
/** Optional one-time setup (open connection, create tables). Runtime calls this before the first `project`. */
|
|
22
32
|
readonly init?: () => Promise<void>;
|
|
33
|
+
/**
|
|
34
|
+
* How far this projector has applied `runId` with no hole in front of it.
|
|
35
|
+
* When the number is behind the delivery cursor, delivery rewinds once and catches up.
|
|
36
|
+
* `null` means the run is closed and delivery must not rewind it.
|
|
37
|
+
*/
|
|
38
|
+
readonly position?: (runId: string) => Promise<number | null>;
|
|
23
39
|
/** Apply a batch of events in log order. Must be idempotent (a batch may be redelivered). */
|
|
24
40
|
readonly project: (events: ReadonlyArray<EventEnvelope>) => Promise<void>;
|
|
25
41
|
readonly dispose?: () => Promise<void>;
|
|
@@ -24,3 +24,6 @@ export function runProjectorSync(projector, operation) {
|
|
|
24
24
|
export function runProjectorPromise(projector, operation) {
|
|
25
25
|
return Effect.runPromise(runProjectorEffect(projector, operation));
|
|
26
26
|
}
|
|
27
|
+
/** A replica batch started after a hole. `project` refuses it and leaves the copy unchanged. */
|
|
28
|
+
export class ReplicaGapError extends Data.TaggedError('ReplicaGapError') {
|
|
29
|
+
}
|