@swirls/looms 0.8.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 +6 -0
- package/dist/cli/commands.js +85 -14
- 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 +4 -68
- package/dist/projectors/event-log.js +4 -79
- package/dist/projectors/replica/migrations.d.ts +4 -6
- package/dist/projectors/replica/migrations.js +18 -1
- 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/package.json +17 -1
package/CHANGELOG.md
CHANGED
package/dist/cli/commands.js
CHANGED
|
@@ -6,7 +6,9 @@ import { decision } from '@swirls/looms/approval';
|
|
|
6
6
|
import { createLoomsClient } from '@swirls/looms/client';
|
|
7
7
|
import { stringifyJson, stringifyJsonPretty } from '@swirls/looms/core';
|
|
8
8
|
import { postgresReplica } from '@swirls/looms/projectors/replica';
|
|
9
|
-
import { generateReplicaMigrations } from '@swirls/looms/projectors/replica/migrations';
|
|
9
|
+
import { generateReplicaMigrations, } from '@swirls/looms/projectors/replica/migrations';
|
|
10
|
+
import {} from '@swirls/looms/projectors/replica/sqlite';
|
|
11
|
+
import { openSqliteReplicaFile } from '@swirls/looms/projectors/replica/sqlite-bun';
|
|
10
12
|
import { createLooms } from '@swirls/looms/runtime';
|
|
11
13
|
const VERSION = '0.0.1';
|
|
12
14
|
const urlFlag = Flag.string('url').pipe(Flag.withDescription('Looms host base URL (env LOOMS_URL)'), Flag.withFallbackConfig(Config.string('LOOMS_URL')), Flag.withDefault('http://127.0.0.1:8787'), Flag.map((url) => url.replace(/\/$/, '')));
|
|
@@ -118,21 +120,63 @@ const tail = Command.make('tail', {
|
|
|
118
120
|
yield* Stream.fromQueue(queue).pipe(Stream.runForEach((line) => Console.log(line)));
|
|
119
121
|
}));
|
|
120
122
|
})).pipe(Command.withDescription('Stream events for a run'), Command.withShortDescription('Tail run events'));
|
|
121
|
-
const databaseFlag = Flag.string('database').pipe(Flag.withDescription('Postgres connection string
|
|
123
|
+
const databaseFlag = Flag.string('database').pipe(Flag.withDescription('Postgres connection string, or a SQLite file path with --dialect sqlite (env DATABASE_URL)'), Flag.withFallbackConfig(Config.string('DATABASE_URL')));
|
|
124
|
+
const dialectFlag = Flag.string('dialect').pipe(Flag.withDescription('Replica dialect: postgres (default) or sqlite'), Flag.withDefault('postgres'));
|
|
125
|
+
function asDialect(value) {
|
|
126
|
+
switch (value) {
|
|
127
|
+
case 'postgres':
|
|
128
|
+
case 'sqlite':
|
|
129
|
+
return value;
|
|
130
|
+
default:
|
|
131
|
+
return undefined;
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
function openReplica(dialect, database, migrate) {
|
|
135
|
+
if (dialect === 'sqlite') {
|
|
136
|
+
const replica = openSqliteReplicaFile(database, migrate);
|
|
137
|
+
return {
|
|
138
|
+
pendingMigrations: () => replica.pendingMigrations(),
|
|
139
|
+
migrate: () => replica.migrate(),
|
|
140
|
+
status: (runId) => replica.status(runId),
|
|
141
|
+
dispose: () => replica.dispose?.() ?? Promise.resolve(),
|
|
142
|
+
};
|
|
143
|
+
}
|
|
144
|
+
const replica = postgresReplica({ url: database, migrate });
|
|
145
|
+
return {
|
|
146
|
+
pendingMigrations: () => replica.pendingMigrations(),
|
|
147
|
+
migrate: () => replica.migrate(),
|
|
148
|
+
status: (runId) => replica.status(runId),
|
|
149
|
+
dispose: () => replica.dispose?.() ?? Promise.resolve(),
|
|
150
|
+
};
|
|
151
|
+
}
|
|
122
152
|
const generate = Command.make('generate', {
|
|
123
153
|
out: Flag.string('out').pipe(Flag.withDescription('Directory of SQL migrations to write into')),
|
|
124
|
-
|
|
154
|
+
dialect: dialectFlag,
|
|
155
|
+
journal: Flag.optional(Flag.string('journal').pipe(Flag.withDescription('Also update a migration journal. Only `drizzle` is supported, and only for Postgres'))),
|
|
125
156
|
check: Flag.boolean('check').pipe(Flag.withDescription('Exit non-zero when a migration is pending, and write nothing'), Flag.withDefault(false)),
|
|
126
|
-
}, Effect.fn('replica.generate')(function* ({ out, journal, check }) {
|
|
157
|
+
}, Effect.fn('replica.generate')(function* ({ out, dialect, journal, check }) {
|
|
158
|
+
const parsed = asDialect(dialect);
|
|
159
|
+
if (!parsed) {
|
|
160
|
+
return yield* new CliError.UserError({
|
|
161
|
+
cause: dialect,
|
|
162
|
+
userMessage: `Unknown dialect "${dialect}". Use "postgres" or "sqlite".`,
|
|
163
|
+
});
|
|
164
|
+
}
|
|
127
165
|
if (Option.isSome(journal) && journal.value !== 'drizzle') {
|
|
128
166
|
return yield* new CliError.UserError({
|
|
129
167
|
cause: journal.value,
|
|
130
168
|
userMessage: `Unknown journal "${journal.value}". Only "drizzle" is supported.`,
|
|
131
169
|
});
|
|
132
170
|
}
|
|
171
|
+
if (parsed === 'sqlite' && Option.isSome(journal)) {
|
|
172
|
+
return yield* new CliError.UserError({
|
|
173
|
+
cause: journal.value,
|
|
174
|
+
userMessage: 'Drizzle journal output is only supported for the Postgres replica.',
|
|
175
|
+
});
|
|
176
|
+
}
|
|
133
177
|
const generateOptions = Option.isSome(journal)
|
|
134
|
-
? { out, check, journal: 'drizzle' }
|
|
135
|
-
: { out, check };
|
|
178
|
+
? { out, check, dialect: parsed, journal: 'drizzle' }
|
|
179
|
+
: { out, check, dialect: parsed };
|
|
136
180
|
const result = yield* tryClient(() => generateReplicaMigrations(generateOptions));
|
|
137
181
|
if (check && result.pending.length > 0) {
|
|
138
182
|
return yield* new CliError.UserError({
|
|
@@ -148,16 +192,43 @@ const generate = Command.make('generate', {
|
|
|
148
192
|
}
|
|
149
193
|
return yield* Effect.void;
|
|
150
194
|
})).pipe(Command.withDescription('Write replica migrations the host does not already have'), Command.withShortDescription('Write replica SQL'));
|
|
151
|
-
const migrate = Command.make('migrate', { database: databaseFlag }, Effect.fn('replica.migrate')(function* ({ database }) {
|
|
152
|
-
const
|
|
153
|
-
|
|
154
|
-
|
|
195
|
+
const migrate = Command.make('migrate', { database: databaseFlag, dialect: dialectFlag }, Effect.fn('replica.migrate')(function* ({ database, dialect }) {
|
|
196
|
+
const parsed = asDialect(dialect);
|
|
197
|
+
if (!parsed) {
|
|
198
|
+
return yield* new CliError.UserError({
|
|
199
|
+
cause: dialect,
|
|
200
|
+
userMessage: `Unknown dialect "${dialect}". Use "postgres" or "sqlite".`,
|
|
201
|
+
});
|
|
202
|
+
}
|
|
203
|
+
if (parsed === 'sqlite' && /^postgres(ql)?:\/\//.test(database)) {
|
|
204
|
+
return yield* new CliError.UserError({
|
|
205
|
+
cause: database,
|
|
206
|
+
userMessage: 'SQLite replica --database is a file path, not a Postgres URL.',
|
|
207
|
+
});
|
|
208
|
+
}
|
|
209
|
+
const replica = openReplica(parsed, database, 'auto');
|
|
210
|
+
yield* tryClient(() => replica.migrate().then(() => replica.dispose()));
|
|
211
|
+
return yield* Console.log('Looms replica migrations applied');
|
|
155
212
|
})).pipe(Command.withDescription('Apply pending replica migrations'), Command.withShortDescription('Apply replica SQL'));
|
|
156
213
|
const status = Command.make('status', {
|
|
157
214
|
database: databaseFlag,
|
|
215
|
+
dialect: dialectFlag,
|
|
158
216
|
run: Flag.optional(Flag.string('run').pipe(Flag.withDescription('Also print freshness for this run id'))),
|
|
159
|
-
}, Effect.fn('replica.status')(function* ({ database, run }) {
|
|
160
|
-
const
|
|
217
|
+
}, Effect.fn('replica.status')(function* ({ database, dialect, run }) {
|
|
218
|
+
const parsed = asDialect(dialect);
|
|
219
|
+
if (!parsed) {
|
|
220
|
+
return yield* new CliError.UserError({
|
|
221
|
+
cause: dialect,
|
|
222
|
+
userMessage: `Unknown dialect "${dialect}". Use "postgres" or "sqlite".`,
|
|
223
|
+
});
|
|
224
|
+
}
|
|
225
|
+
if (parsed === 'sqlite' && /^postgres(ql)?:\/\//.test(database)) {
|
|
226
|
+
return yield* new CliError.UserError({
|
|
227
|
+
cause: database,
|
|
228
|
+
userMessage: 'SQLite replica --database is a file path, not a Postgres URL.',
|
|
229
|
+
});
|
|
230
|
+
}
|
|
231
|
+
const replica = openReplica(parsed, database, 'verify');
|
|
161
232
|
const pending = yield* tryClient(() => replica.pendingMigrations());
|
|
162
233
|
yield* Console.log(pending.length === 0
|
|
163
234
|
? 'Looms replica schema is up to date'
|
|
@@ -166,9 +237,9 @@ const status = Command.make('status', {
|
|
|
166
237
|
const row = yield* tryClient(() => replica.status(run.value));
|
|
167
238
|
yield* Console.log(row ? stringifyJson(row) : `No replica row for ${run.value}`);
|
|
168
239
|
}
|
|
169
|
-
yield* tryClient(() => replica.dispose
|
|
240
|
+
return yield* tryClient(() => replica.dispose());
|
|
170
241
|
})).pipe(Command.withDescription('Show which replica migrations are applied'), Command.withShortDescription('Replica schema status'));
|
|
171
|
-
const replica = Command.make('replica').pipe(Command.withDescription('Copy runs into a Postgres database you own'), Command.withShortDescription('
|
|
242
|
+
const replica = Command.make('replica').pipe(Command.withDescription('Copy runs into a Postgres or SQLite database you own'), Command.withShortDescription('Event replica'), Command.withSubcommands([generate, migrate, status]));
|
|
172
243
|
export const looms = loomsBase.pipe(Command.withSubcommands([
|
|
173
244
|
serve,
|
|
174
245
|
start,
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import { type EventEnvelope, type EventOrigin, type JsonValue, type RunStatus } from '@swirls/looms/core';
|
|
2
|
+
export interface EventLogEntry {
|
|
3
|
+
readonly runId: string;
|
|
4
|
+
readonly seq: number;
|
|
5
|
+
readonly eventId: string;
|
|
6
|
+
readonly ts: number;
|
|
7
|
+
readonly type: string;
|
|
8
|
+
readonly payload: JsonValue;
|
|
9
|
+
readonly threadId: string | null;
|
|
10
|
+
readonly parentThreadId: string | null;
|
|
11
|
+
readonly causationId: string | null;
|
|
12
|
+
readonly correlationId: string | null;
|
|
13
|
+
readonly effectId: string | null;
|
|
14
|
+
readonly origin: EventOrigin;
|
|
15
|
+
readonly idempotencyKey: string | null;
|
|
16
|
+
}
|
|
17
|
+
export interface RunLogRow {
|
|
18
|
+
readonly runId: string;
|
|
19
|
+
readonly status: RunStatus;
|
|
20
|
+
readonly kind: string | null;
|
|
21
|
+
readonly definitionName: string | null;
|
|
22
|
+
readonly definitionVersion: string | null;
|
|
23
|
+
readonly rootThreadId: string | null;
|
|
24
|
+
readonly parentRunId: string | null;
|
|
25
|
+
readonly launchedByEffectId: string | null;
|
|
26
|
+
readonly correlationId: string | null;
|
|
27
|
+
readonly attributes: {
|
|
28
|
+
readonly [key: string]: string;
|
|
29
|
+
};
|
|
30
|
+
readonly tenant: string | null;
|
|
31
|
+
readonly project: string | null;
|
|
32
|
+
readonly org: string | null;
|
|
33
|
+
readonly startedAt: number | null;
|
|
34
|
+
readonly updatedAt: number;
|
|
35
|
+
readonly completedAt: number | null;
|
|
36
|
+
}
|
|
37
|
+
export type EventLogOp = {
|
|
38
|
+
readonly type: 'insert';
|
|
39
|
+
readonly entry: EventLogEntry;
|
|
40
|
+
} | {
|
|
41
|
+
readonly type: 'start';
|
|
42
|
+
readonly runId: string;
|
|
43
|
+
readonly kind: string | null;
|
|
44
|
+
readonly definitionName: string | null;
|
|
45
|
+
readonly definitionVersion: string | null;
|
|
46
|
+
readonly rootThreadId: string | null;
|
|
47
|
+
readonly parentRunId: string | null;
|
|
48
|
+
readonly launchedByEffectId: string | null;
|
|
49
|
+
readonly correlationId: string | null;
|
|
50
|
+
readonly attributes: {
|
|
51
|
+
readonly [key: string]: string;
|
|
52
|
+
};
|
|
53
|
+
readonly tenant: string | null;
|
|
54
|
+
readonly project: string | null;
|
|
55
|
+
readonly org: string | null;
|
|
56
|
+
readonly at: number;
|
|
57
|
+
} | {
|
|
58
|
+
readonly type: 'finish';
|
|
59
|
+
readonly runId: string;
|
|
60
|
+
readonly status: 'completed' | 'failed' | 'cancelled';
|
|
61
|
+
readonly at: number;
|
|
62
|
+
} | {
|
|
63
|
+
readonly type: 'touch';
|
|
64
|
+
readonly runId: string;
|
|
65
|
+
readonly at: number;
|
|
66
|
+
};
|
|
67
|
+
/** Fold one durable event into event-row and run-summary operations. Ephemeral events produce nothing. */
|
|
68
|
+
export declare function eventLogOps(event: EventEnvelope): readonly EventLogOp[];
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import { Option, Predicate, Schema } from 'effect';
|
|
2
|
+
import { completedRunStatus, isJsonObject, readRunLaunchSource, } from '@swirls/looms/core';
|
|
3
|
+
const decodeAttributes = Schema.decodeUnknownOption(Schema.Record(Schema.String, Schema.String));
|
|
4
|
+
/** Fold one durable event into event-row and run-summary operations. Ephemeral events produce nothing. */
|
|
5
|
+
export function eventLogOps(event) {
|
|
6
|
+
if (event.ephemeral) {
|
|
7
|
+
return [];
|
|
8
|
+
}
|
|
9
|
+
const entry = {
|
|
10
|
+
runId: event.runId,
|
|
11
|
+
seq: event.seq,
|
|
12
|
+
eventId: event.id,
|
|
13
|
+
ts: event.ts,
|
|
14
|
+
type: event.type,
|
|
15
|
+
payload: event.payload,
|
|
16
|
+
threadId: event.threadId,
|
|
17
|
+
parentThreadId: event.parentThreadId ?? null,
|
|
18
|
+
causationId: event.causationId ?? null,
|
|
19
|
+
correlationId: event.correlationId ?? null,
|
|
20
|
+
effectId: event.effectId ?? null,
|
|
21
|
+
origin: event.origin,
|
|
22
|
+
idempotencyKey: event.idempotencyKey ?? null,
|
|
23
|
+
};
|
|
24
|
+
const payload = isJsonObject(event.payload) ? event.payload : {};
|
|
25
|
+
switch (event.type) {
|
|
26
|
+
case 'runtime.run.started':
|
|
27
|
+
return [{ type: 'insert', entry }, startOp(event, payload)];
|
|
28
|
+
case 'runtime.run.completed':
|
|
29
|
+
return [
|
|
30
|
+
{ type: 'insert', entry },
|
|
31
|
+
{
|
|
32
|
+
type: 'finish',
|
|
33
|
+
runId: event.runId,
|
|
34
|
+
status: completedRunStatus(event.payload),
|
|
35
|
+
at: event.ts,
|
|
36
|
+
},
|
|
37
|
+
];
|
|
38
|
+
case 'runtime.run.cancelled':
|
|
39
|
+
return [
|
|
40
|
+
{ type: 'insert', entry },
|
|
41
|
+
{ type: 'finish', runId: event.runId, status: 'cancelled', at: event.ts },
|
|
42
|
+
];
|
|
43
|
+
default:
|
|
44
|
+
return [
|
|
45
|
+
{ type: 'insert', entry },
|
|
46
|
+
{ type: 'touch', runId: event.runId, at: event.ts },
|
|
47
|
+
];
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
function startOp(event, payload) {
|
|
51
|
+
const launchedBy = readRunLaunchSource(payload.launchedBy === undefined ? undefined : payload.launchedBy);
|
|
52
|
+
const attributes = readAttributes(payload.attributes);
|
|
53
|
+
return {
|
|
54
|
+
type: 'start',
|
|
55
|
+
runId: event.runId,
|
|
56
|
+
kind: readString(payload, 'kind'),
|
|
57
|
+
definitionName: readString(payload, 'definitionName'),
|
|
58
|
+
definitionVersion: readString(payload, 'definitionVersion'),
|
|
59
|
+
rootThreadId: readString(payload, 'rootThreadId'),
|
|
60
|
+
parentRunId: launchedBy?.runId ?? null,
|
|
61
|
+
launchedByEffectId: launchedBy?.effectId ?? null,
|
|
62
|
+
correlationId: event.correlationId ?? null,
|
|
63
|
+
attributes,
|
|
64
|
+
tenant: attributes.tenant ?? null,
|
|
65
|
+
project: attributes.project ?? null,
|
|
66
|
+
org: attributes.org ?? null,
|
|
67
|
+
at: event.ts,
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
function readString(payload, key) {
|
|
71
|
+
const value = payload[key];
|
|
72
|
+
return Predicate.isString(value) ? value : null;
|
|
73
|
+
}
|
|
74
|
+
function readAttributes(value) {
|
|
75
|
+
if (value === undefined) {
|
|
76
|
+
return {};
|
|
77
|
+
}
|
|
78
|
+
return Option.getOrElse(decodeAttributes(value), () => ({}));
|
|
79
|
+
}
|
|
@@ -1,73 +1,10 @@
|
|
|
1
1
|
import { type Sql, type TransactionSql } from 'postgres';
|
|
2
|
-
import { type EventEnvelope, type
|
|
2
|
+
import { type EventEnvelope, type EventStore } from '@swirls/looms/core';
|
|
3
|
+
import { eventLogOps, type EventLogEntry, type EventLogOp, type RunLogRow } from './event-log-ops';
|
|
3
4
|
import type { Projector } from './projector';
|
|
4
5
|
import { POSTGRES_EVENT_LOG_SCHEMA_SQL } from './replica/migrations';
|
|
5
|
-
export { POSTGRES_EVENT_LOG_SCHEMA_SQL };
|
|
6
|
-
export
|
|
7
|
-
readonly runId: string;
|
|
8
|
-
readonly seq: number;
|
|
9
|
-
readonly eventId: string;
|
|
10
|
-
readonly ts: number;
|
|
11
|
-
readonly type: string;
|
|
12
|
-
readonly payload: JsonValue;
|
|
13
|
-
readonly threadId: string | null;
|
|
14
|
-
readonly parentThreadId: string | null;
|
|
15
|
-
readonly causationId: string | null;
|
|
16
|
-
readonly correlationId: string | null;
|
|
17
|
-
readonly effectId: string | null;
|
|
18
|
-
readonly origin: EventOrigin;
|
|
19
|
-
readonly idempotencyKey: string | null;
|
|
20
|
-
}
|
|
21
|
-
export interface RunLogRow {
|
|
22
|
-
readonly runId: string;
|
|
23
|
-
readonly status: RunStatus;
|
|
24
|
-
readonly kind: string | null;
|
|
25
|
-
readonly definitionName: string | null;
|
|
26
|
-
readonly definitionVersion: string | null;
|
|
27
|
-
readonly rootThreadId: string | null;
|
|
28
|
-
readonly parentRunId: string | null;
|
|
29
|
-
readonly launchedByEffectId: string | null;
|
|
30
|
-
readonly correlationId: string | null;
|
|
31
|
-
readonly attributes: {
|
|
32
|
-
readonly [key: string]: string;
|
|
33
|
-
};
|
|
34
|
-
readonly tenant: string | null;
|
|
35
|
-
readonly project: string | null;
|
|
36
|
-
readonly org: string | null;
|
|
37
|
-
readonly startedAt: number | null;
|
|
38
|
-
readonly updatedAt: number;
|
|
39
|
-
readonly completedAt: number | null;
|
|
40
|
-
}
|
|
41
|
-
export type EventLogOp = {
|
|
42
|
-
readonly type: 'insert';
|
|
43
|
-
readonly entry: EventLogEntry;
|
|
44
|
-
} | {
|
|
45
|
-
readonly type: 'start';
|
|
46
|
-
readonly runId: string;
|
|
47
|
-
readonly kind: string | null;
|
|
48
|
-
readonly definitionName: string | null;
|
|
49
|
-
readonly definitionVersion: string | null;
|
|
50
|
-
readonly rootThreadId: string | null;
|
|
51
|
-
readonly parentRunId: string | null;
|
|
52
|
-
readonly launchedByEffectId: string | null;
|
|
53
|
-
readonly correlationId: string | null;
|
|
54
|
-
readonly attributes: {
|
|
55
|
-
readonly [key: string]: string;
|
|
56
|
-
};
|
|
57
|
-
readonly tenant: string | null;
|
|
58
|
-
readonly project: string | null;
|
|
59
|
-
readonly org: string | null;
|
|
60
|
-
readonly at: number;
|
|
61
|
-
} | {
|
|
62
|
-
readonly type: 'finish';
|
|
63
|
-
readonly runId: string;
|
|
64
|
-
readonly status: 'completed' | 'failed' | 'cancelled';
|
|
65
|
-
readonly at: number;
|
|
66
|
-
} | {
|
|
67
|
-
readonly type: 'touch';
|
|
68
|
-
readonly runId: string;
|
|
69
|
-
readonly at: number;
|
|
70
|
-
};
|
|
6
|
+
export { POSTGRES_EVENT_LOG_SCHEMA_SQL, eventLogOps };
|
|
7
|
+
export type { EventLogEntry, EventLogOp, RunLogRow };
|
|
71
8
|
export interface EventLogProjector extends Projector {
|
|
72
9
|
/** Replays the source log into this sink. Safe to repeat; do not run it beside live delivery. */
|
|
73
10
|
rebuild(source: EventStore, options?: {
|
|
@@ -79,7 +16,6 @@ export interface MemoryEventLog extends EventLogProjector {
|
|
|
79
16
|
events(runId: string): readonly EventLogEntry[];
|
|
80
17
|
run(runId: string): RunLogRow | null;
|
|
81
18
|
}
|
|
82
|
-
export declare function eventLogOps(event: EventEnvelope): readonly EventLogOp[];
|
|
83
19
|
export declare function memoryEventLog(): MemoryEventLog;
|
|
84
20
|
export declare function postgresEventLog(options: {
|
|
85
21
|
url: string;
|
|
@@ -1,56 +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
|
import { POSTGRES_EVENT_LOG_SCHEMA_SQL } from './replica/migrations.js';
|
|
6
|
-
export { POSTGRES_EVENT_LOG_SCHEMA_SQL };
|
|
7
|
-
const decodeAttributes = Schema.decodeUnknownOption(Schema.Record(Schema.String, Schema.String));
|
|
7
|
+
export { POSTGRES_EVENT_LOG_SCHEMA_SQL, eventLogOps };
|
|
8
8
|
const terminal = new Set(['completed', 'failed', 'cancelled']);
|
|
9
|
-
export function eventLogOps(event) {
|
|
10
|
-
if (event.ephemeral) {
|
|
11
|
-
return [];
|
|
12
|
-
}
|
|
13
|
-
const entry = {
|
|
14
|
-
runId: event.runId,
|
|
15
|
-
seq: event.seq,
|
|
16
|
-
eventId: event.id,
|
|
17
|
-
ts: event.ts,
|
|
18
|
-
type: event.type,
|
|
19
|
-
payload: event.payload,
|
|
20
|
-
threadId: event.threadId,
|
|
21
|
-
parentThreadId: event.parentThreadId ?? null,
|
|
22
|
-
causationId: event.causationId ?? null,
|
|
23
|
-
correlationId: event.correlationId ?? null,
|
|
24
|
-
effectId: event.effectId ?? null,
|
|
25
|
-
origin: event.origin,
|
|
26
|
-
idempotencyKey: event.idempotencyKey ?? null,
|
|
27
|
-
};
|
|
28
|
-
const payload = isJsonObject(event.payload) ? event.payload : {};
|
|
29
|
-
switch (event.type) {
|
|
30
|
-
case 'runtime.run.started':
|
|
31
|
-
return [{ type: 'insert', entry }, startOp(event, payload)];
|
|
32
|
-
case 'runtime.run.completed':
|
|
33
|
-
return [
|
|
34
|
-
{ type: 'insert', entry },
|
|
35
|
-
{
|
|
36
|
-
type: 'finish',
|
|
37
|
-
runId: event.runId,
|
|
38
|
-
status: completedRunStatus(event.payload),
|
|
39
|
-
at: event.ts,
|
|
40
|
-
},
|
|
41
|
-
];
|
|
42
|
-
case 'runtime.run.cancelled':
|
|
43
|
-
return [
|
|
44
|
-
{ type: 'insert', entry },
|
|
45
|
-
{ type: 'finish', runId: event.runId, status: 'cancelled', at: event.ts },
|
|
46
|
-
];
|
|
47
|
-
default:
|
|
48
|
-
return [
|
|
49
|
-
{ type: 'insert', entry },
|
|
50
|
-
{ type: 'touch', runId: event.runId, at: event.ts },
|
|
51
|
-
];
|
|
52
|
-
}
|
|
53
|
-
}
|
|
54
9
|
export function memoryEventLog() {
|
|
55
10
|
const events = new Map();
|
|
56
11
|
const runs = new Map();
|
|
@@ -184,36 +139,6 @@ function mergeFinish(existing, op) {
|
|
|
184
139
|
function utcDate(ms) {
|
|
185
140
|
return DateTime.toDateUtc(DateTime.makeUnsafe(ms));
|
|
186
141
|
}
|
|
187
|
-
function startOp(event, payload) {
|
|
188
|
-
const launchedBy = readRunLaunchSource(payload.launchedBy === undefined ? undefined : payload.launchedBy);
|
|
189
|
-
const attributes = readAttributes(payload.attributes);
|
|
190
|
-
return {
|
|
191
|
-
type: 'start',
|
|
192
|
-
runId: event.runId,
|
|
193
|
-
kind: readString(payload, 'kind'),
|
|
194
|
-
definitionName: readString(payload, 'definitionName'),
|
|
195
|
-
definitionVersion: readString(payload, 'definitionVersion'),
|
|
196
|
-
rootThreadId: readString(payload, 'rootThreadId'),
|
|
197
|
-
parentRunId: launchedBy?.runId ?? null,
|
|
198
|
-
launchedByEffectId: launchedBy?.effectId ?? null,
|
|
199
|
-
correlationId: event.correlationId ?? null,
|
|
200
|
-
attributes,
|
|
201
|
-
tenant: attributes.tenant ?? null,
|
|
202
|
-
project: attributes.project ?? null,
|
|
203
|
-
org: attributes.org ?? null,
|
|
204
|
-
at: event.ts,
|
|
205
|
-
};
|
|
206
|
-
}
|
|
207
|
-
function readString(payload, key) {
|
|
208
|
-
const value = payload[key];
|
|
209
|
-
return Predicate.isString(value) ? value : null;
|
|
210
|
-
}
|
|
211
|
-
function readAttributes(value) {
|
|
212
|
-
if (value === undefined) {
|
|
213
|
-
return {};
|
|
214
|
-
}
|
|
215
|
-
return Option.getOrElse(decodeAttributes(value), () => ({}));
|
|
216
|
-
}
|
|
217
142
|
function postgresStore(sql, ownsClient) {
|
|
218
143
|
return {
|
|
219
144
|
init: () => runProjectorPromise('postgres-event-log', () => sql.unsafe(POSTGRES_EVENT_LOG_SCHEMA_SQL)).then(() => undefined),
|
|
@@ -15,21 +15,19 @@ export interface ReplicaMigration {
|
|
|
15
15
|
}
|
|
16
16
|
/** Versioned DDL for the Postgres replica. Looms only creates and alters `looms_*` objects. */
|
|
17
17
|
export declare const POSTGRES_REPLICA_MIGRATIONS: readonly ReplicaMigration[];
|
|
18
|
+
export type ReplicaDialect = 'postgres' | 'sqlite';
|
|
18
19
|
export interface GenerateReplicaMigrationsOptions {
|
|
19
20
|
/** Directory of SQL migrations the host already applies. */
|
|
20
21
|
readonly out: string;
|
|
21
|
-
/** Append a Drizzle `_journal.json` entry for each file written. */
|
|
22
|
+
/** Append a Drizzle `_journal.json` entry for each file written. Postgres only. */
|
|
22
23
|
readonly journal?: 'drizzle';
|
|
23
24
|
/** Report pending migrations and write nothing. */
|
|
24
25
|
readonly check?: boolean;
|
|
26
|
+
/** Which replica DDL to write. Defaults to Postgres. */
|
|
27
|
+
readonly dialect?: ReplicaDialect;
|
|
25
28
|
}
|
|
26
29
|
export interface GenerateReplicaMigrationsResult {
|
|
27
30
|
readonly written: readonly string[];
|
|
28
31
|
readonly pending: readonly string[];
|
|
29
32
|
}
|
|
30
|
-
/**
|
|
31
|
-
* Writes each migration the host does not already have.
|
|
32
|
-
* A file counts as applied when it contains `-- looms-migration: <id>`.
|
|
33
|
-
* The numeric prefix continues after the highest `NNNN_` file already in `out`.
|
|
34
|
-
*/
|
|
35
33
|
export declare function generateReplicaMigrations(options: GenerateReplicaMigrationsOptions): Promise<GenerateReplicaMigrationsResult>;
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { readdir, readFile, writeFile, mkdir } from 'node:fs/promises';
|
|
2
2
|
import { join } from 'node:path';
|
|
3
3
|
import { Predicate } from 'effect';
|
|
4
|
+
import { SQLITE_REPLICA_MIGRATIONS } from './sqlite-migrations.js';
|
|
4
5
|
/**
|
|
5
6
|
* Actors and reviews. Same statements the Postgres index projector has always
|
|
6
7
|
* applied, so a database created by an older Looms keeps working.
|
|
@@ -200,9 +201,25 @@ async function appendDrizzleJournal(directory, tags) {
|
|
|
200
201
|
* A file counts as applied when it contains `-- looms-migration: <id>`.
|
|
201
202
|
* The numeric prefix continues after the highest `NNNN_` file already in `out`.
|
|
202
203
|
*/
|
|
204
|
+
function migrationsFor(dialect) {
|
|
205
|
+
switch (dialect) {
|
|
206
|
+
case 'postgres':
|
|
207
|
+
return POSTGRES_REPLICA_MIGRATIONS;
|
|
208
|
+
case 'sqlite':
|
|
209
|
+
return SQLITE_REPLICA_MIGRATIONS;
|
|
210
|
+
default: {
|
|
211
|
+
const unexpected = dialect;
|
|
212
|
+
return unexpected;
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
}
|
|
203
216
|
export async function generateReplicaMigrations(options) {
|
|
217
|
+
const dialect = options.dialect ?? 'postgres';
|
|
218
|
+
if (dialect === 'sqlite' && options.journal === 'drizzle') {
|
|
219
|
+
throw new Error('Drizzle journal output is only supported for the Postgres replica.');
|
|
220
|
+
}
|
|
204
221
|
const recorded = await recordedMigrationIds(options.out);
|
|
205
|
-
const pending =
|
|
222
|
+
const pending = migrationsFor(dialect).filter((migration) => !recorded.has(migration.id));
|
|
206
223
|
if (options.check || pending.length === 0) {
|
|
207
224
|
return { written: [], pending: pending.map((migration) => migration.id) };
|
|
208
225
|
}
|
|
@@ -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,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 };
|
|
@@ -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 };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@swirls/looms",
|
|
3
|
-
"version": "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": {
|
|
@@ -161,6 +161,22 @@
|
|
|
161
161
|
"types": "./dist/projectors/replica/migrations.d.ts",
|
|
162
162
|
"import": "./dist/projectors/replica/migrations.js"
|
|
163
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
|
+
},
|
|
164
180
|
"./s2/projector": {
|
|
165
181
|
"types": "./dist/s2/projector.d.ts",
|
|
166
182
|
"import": "./dist/s2/projector.js"
|