@operad-io/engine 0.0.0-stage → 0.1.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.
Files changed (102) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +11 -2
  3. package/config.schema.json +188 -0
  4. package/keys.schema.json +12 -0
  5. package/package.json +22 -4
  6. package/src/config/config.ts +627 -0
  7. package/src/config/index.ts +1 -0
  8. package/src/flow/define-flow.ts +57 -0
  9. package/src/flow/index.ts +5 -0
  10. package/src/flow/load.ts +41 -0
  11. package/src/flow/types.ts +107 -0
  12. package/src/flow/validate.ts +296 -0
  13. package/src/http/address.ts +142 -0
  14. package/src/http/index.ts +25 -0
  15. package/src/http/link.ts +20 -0
  16. package/src/http/server.ts +920 -0
  17. package/src/http/token.ts +90 -0
  18. package/src/index.ts +18 -0
  19. package/src/kernel/decide.ts +689 -0
  20. package/src/kernel/index.ts +3 -0
  21. package/src/kernel/state.ts +275 -0
  22. package/src/kernel/types.ts +366 -0
  23. package/src/log/errors.ts +77 -0
  24. package/src/log/facts.ts +50 -0
  25. package/src/log/index.ts +6 -0
  26. package/src/log/json-value.ts +67 -0
  27. package/src/log/open-log.ts +17 -0
  28. package/src/log/schema.ts +5 -0
  29. package/src/log/secret.ts +30 -0
  30. package/src/log/sqlite.ts +1011 -0
  31. package/src/log/types.ts +230 -0
  32. package/src/loop/code-watch.ts +486 -0
  33. package/src/loop/index.ts +3 -0
  34. package/src/loop/older-code.ts +58 -0
  35. package/src/loop/serve.ts +483 -0
  36. package/src/markdown.ts +451 -0
  37. package/src/notify/index.ts +10 -0
  38. package/src/notify/notify.ts +256 -0
  39. package/src/platform/file-lock.ts +385 -0
  40. package/src/platform/index.ts +13 -0
  41. package/src/platform/load.ts +18 -0
  42. package/src/platform/process-group.ts +675 -0
  43. package/src/platform/process-watch.ts +152 -0
  44. package/src/platform/sqlite-open.ts +104 -0
  45. package/src/platform/step-reap.ts +668 -0
  46. package/src/platform/watch.ts +158 -0
  47. package/src/platform/worker-reports.ts +34 -0
  48. package/src/plugin/action-schema.ts +550 -0
  49. package/src/plugin/declared-flows.ts +74 -0
  50. package/src/plugin/define-plugin.ts +12 -0
  51. package/src/plugin/errors.ts +73 -0
  52. package/src/plugin/filters.ts +46 -0
  53. package/src/plugin/harness.ts +50 -0
  54. package/src/plugin/home.ts +13 -0
  55. package/src/plugin/index.ts +65 -0
  56. package/src/plugin/install.ts +268 -0
  57. package/src/plugin/keys.ts +63 -0
  58. package/src/plugin/load.ts +256 -0
  59. package/src/plugin/logger.ts +30 -0
  60. package/src/plugin/object-facts.ts +132 -0
  61. package/src/plugin/open-store.ts +32 -0
  62. package/src/plugin/paging.ts +133 -0
  63. package/src/plugin/registry.ts +1786 -0
  64. package/src/plugin/secrets.ts +141 -0
  65. package/src/plugin/semver.ts +110 -0
  66. package/src/plugin/settings.ts +64 -0
  67. package/src/plugin/sqlite-store.ts +756 -0
  68. package/src/plugin/store.ts +318 -0
  69. package/src/plugin/types.ts +1243 -0
  70. package/src/plugin/usage.ts +157 -0
  71. package/src/plugin/validate.ts +1028 -0
  72. package/src/runner/answer.ts +156 -0
  73. package/src/runner/ask.ts +483 -0
  74. package/src/runner/cancel.ts +51 -0
  75. package/src/runner/errors.ts +20 -0
  76. package/src/runner/grants.ts +92 -0
  77. package/src/runner/index.ts +33 -0
  78. package/src/runner/limits.ts +403 -0
  79. package/src/runner/lock.ts +140 -0
  80. package/src/runner/runner.ts +1175 -0
  81. package/src/runner/service.ts +184 -0
  82. package/src/runner/step-worker.ts +303 -0
  83. package/src/testing/clock.ts +67 -0
  84. package/src/testing/index.ts +90 -0
  85. package/src/testing/types.ts +116 -0
  86. package/src/testing/world.ts +369 -0
  87. package/src/trigger/cron.ts +193 -0
  88. package/src/trigger/index.ts +32 -0
  89. package/src/trigger/kernel.ts +1221 -0
  90. package/src/trigger/rules.ts +300 -0
  91. package/src/trigger/store.ts +233 -0
  92. package/src/trigger/types.ts +156 -0
  93. package/src/util.ts +50 -0
  94. package/src/views/history.ts +634 -0
  95. package/src/views/index.ts +7 -0
  96. package/src/views/pending.ts +209 -0
  97. package/src/views/presentation.ts +2609 -0
  98. package/src/views/running.ts +255 -0
  99. package/src/views/settings.ts +452 -0
  100. package/src/views/types.ts +72 -0
  101. package/src/views/uploads.ts +228 -0
  102. package/triggers.schema.json +48 -0
@@ -0,0 +1,1011 @@
1
+ /**
2
+ * The sqlite log backend: one SQLite file holding runs, facts and inputs.
3
+ *
4
+ * Every append and every startRun is one `BEGIN IMMEDIATE` transaction, so a
5
+ * process killed mid-write leaves either the whole batch or none of it. WAL
6
+ * lets a reader keep a consistent snapshot of a run while another process
7
+ * appends to it.
8
+ */
9
+
10
+ import { Database } from "bun:sqlite";
11
+ import { randomUUID } from "node:crypto";
12
+ import { accessSync, constants, existsSync, mkdirSync } from "node:fs";
13
+ import { dirname, join } from "node:path";
14
+ import {
15
+ ActiveRunError,
16
+ CorruptLogError,
17
+ InvalidPayloadError,
18
+ LogBackendError,
19
+ RunEndedError,
20
+ RunNotFoundError,
21
+ SchemaVersionError,
22
+ SeqConflictError,
23
+ StoreClosedError,
24
+ } from "./errors.ts";
25
+ import {
26
+ assertExpectedSeq,
27
+ assertName,
28
+ assertRunId,
29
+ inputIdFor,
30
+ validateNewFact,
31
+ } from "./facts.ts";
32
+ import { assertJsonValue } from "./json-value.ts";
33
+ import { SCHEMA_VERSION } from "./schema.ts";
34
+ import {
35
+ enableWal,
36
+ resolveSubscriptionWatch,
37
+ setBusyTimeout,
38
+ type SubscriptionWatch,
39
+ } from "../platform/index.ts";
40
+ import type {
41
+ AppendResult,
42
+ Fact,
43
+ FactCause,
44
+ GlobalFact,
45
+ InputRecord,
46
+ InputOutcome,
47
+ InputsAfter,
48
+ JsonValue,
49
+ LogBackend,
50
+ LogBackendFactory,
51
+ LogBackendOptions,
52
+ LogChange,
53
+ NewFact,
54
+ RecordInputResult,
55
+ RecordOutcomeResult,
56
+ RunInfo,
57
+ RunsOptions,
58
+ } from "./types.ts";
59
+
60
+ /** The file the sqlite factory creates inside the store directory. */
61
+ export const SQLITE_FILE_NAME = "log.sqlite";
62
+
63
+ export { BUSY_TIMEOUT_MS } from "../platform/index.ts";
64
+
65
+ const SCHEMA = `
66
+ CREATE TABLE IF NOT EXISTS schema_version (
67
+ id INTEGER PRIMARY KEY CHECK (id = 1),
68
+ version INTEGER NOT NULL
69
+ );
70
+ CREATE TABLE IF NOT EXISTS runs (
71
+ run_id TEXT PRIMARY KEY,
72
+ flow TEXT NOT NULL,
73
+ object TEXT NOT NULL,
74
+ started_at INTEGER NOT NULL,
75
+ ended_at INTEGER,
76
+ start_input_id TEXT,
77
+ access TEXT
78
+ );
79
+ CREATE UNIQUE INDEX IF NOT EXISTS runs_one_active
80
+ ON runs (flow, object) WHERE ended_at IS NULL;
81
+ CREATE INDEX IF NOT EXISTS runs_object ON runs (object);
82
+ CREATE TABLE IF NOT EXISTS facts (
83
+ run_id TEXT NOT NULL REFERENCES runs (run_id),
84
+ seq INTEGER NOT NULL,
85
+ kind TEXT NOT NULL,
86
+ payload TEXT NOT NULL,
87
+ cause TEXT NOT NULL,
88
+ time INTEGER NOT NULL,
89
+ PRIMARY KEY (run_id, seq)
90
+ );
91
+ CREATE TABLE IF NOT EXISTS inputs (
92
+ input_id TEXT PRIMARY KEY,
93
+ run_id TEXT REFERENCES runs (run_id),
94
+ source TEXT NOT NULL,
95
+ source_key TEXT NOT NULL,
96
+ payload TEXT NOT NULL,
97
+ time INTEGER NOT NULL,
98
+ UNIQUE (source, source_key)
99
+ );
100
+ CREATE TABLE IF NOT EXISTS global_facts (
101
+ seq INTEGER PRIMARY KEY,
102
+ kind TEXT NOT NULL,
103
+ payload TEXT NOT NULL,
104
+ cause TEXT NOT NULL,
105
+ time INTEGER NOT NULL,
106
+ unique_key TEXT
107
+ );
108
+ CREATE TABLE IF NOT EXISTS outcomes (
109
+ input_id TEXT NOT NULL,
110
+ kind TEXT NOT NULL,
111
+ payload TEXT NOT NULL,
112
+ seq INTEGER NOT NULL UNIQUE,
113
+ time INTEGER NOT NULL,
114
+ PRIMARY KEY (input_id, kind)
115
+ );
116
+ `;
117
+
118
+ interface RunRow {
119
+ readonly run_id: string;
120
+ readonly flow: string;
121
+ readonly object: string;
122
+ readonly started_at: number;
123
+ readonly ended_at: number | null;
124
+ readonly last_seq: number;
125
+ readonly access: string | null;
126
+ readonly start_input_id: string | null;
127
+ }
128
+
129
+ interface InputRow {
130
+ readonly input_id: string;
131
+ readonly run_id: string | null;
132
+ readonly source: string;
133
+ readonly source_key: string;
134
+ readonly payload: string;
135
+ readonly time: number;
136
+ }
137
+
138
+ interface FactRow {
139
+ readonly seq: number;
140
+ readonly kind: string;
141
+ readonly payload: string;
142
+ readonly cause: string;
143
+ readonly time: number;
144
+ }
145
+
146
+ interface OutcomeRow {
147
+ readonly input_id: string;
148
+ readonly kind: string;
149
+ readonly payload: string;
150
+ readonly seq: number;
151
+ readonly time: number;
152
+ }
153
+
154
+ interface GlobalFactRow {
155
+ readonly seq: number;
156
+ readonly kind: string;
157
+ readonly payload: string;
158
+ readonly cause: string;
159
+ readonly time: number;
160
+ readonly unique_key: string | null;
161
+ }
162
+
163
+ function globalFactOfRow(row: GlobalFactRow): GlobalFact {
164
+ return {
165
+ seq: row.seq,
166
+ kind: row.kind,
167
+ payload: JSON.parse(row.payload) as JsonValue,
168
+ cause: JSON.parse(row.cause) as FactCause,
169
+ time: row.time,
170
+ ...(row.unique_key === null ? {} : { uniqueKey: row.unique_key }),
171
+ };
172
+ }
173
+
174
+ function inputOfRow(row: InputRow): InputRecord {
175
+ return {
176
+ inputId: row.input_id,
177
+ runId: row.run_id,
178
+ source: row.source,
179
+ sourceKey: row.source_key,
180
+ payload: JSON.parse(row.payload) as JsonValue,
181
+ time: row.time,
182
+ };
183
+ }
184
+
185
+ function outcomeOfRow(row: OutcomeRow): InputOutcome {
186
+ return {
187
+ inputId: row.input_id,
188
+ kind: row.kind,
189
+ payload: JSON.parse(row.payload) as JsonValue,
190
+ seq: row.seq,
191
+ time: row.time,
192
+ };
193
+ }
194
+
195
+ /** One run as a watcher last saw it, to tell a real change from a read. */
196
+ interface RunSnapshot {
197
+ readonly object: string;
198
+ readonly lastSeq: number;
199
+ readonly ended: boolean;
200
+ }
201
+
202
+ interface VersionRow {
203
+ readonly version: number;
204
+ }
205
+
206
+ interface TableColumn {
207
+ readonly name: string;
208
+ readonly notnull: number;
209
+ }
210
+
211
+ function tableColumns(database: Database, table: string): TableColumn[] {
212
+ try {
213
+ return database
214
+ .query<TableColumn, []>(`PRAGMA table_info(${table})`)
215
+ .all();
216
+ } catch {
217
+ return [];
218
+ }
219
+ }
220
+
221
+ function hasTable(database: Database, table: string): boolean {
222
+ return (
223
+ database
224
+ .query<{ name: string }, [string]>(
225
+ "SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?",
226
+ )
227
+ .get(table) !== null
228
+ );
229
+ }
230
+
231
+ function hasIndex(database: Database, index: string): boolean {
232
+ return (
233
+ database
234
+ .query<{ name: string }, [string]>(
235
+ "SELECT name FROM sqlite_master WHERE type = 'index' AND name = ?",
236
+ )
237
+ .get(index) !== null
238
+ );
239
+ }
240
+
241
+ /** True for a store written before trigger inputs could be global. */
242
+ function inputsNeedMigration(database: Database): boolean {
243
+ const column = tableColumns(database, "inputs").find((item) => item.name === "run_id");
244
+ return column !== undefined && column.notnull === 1;
245
+ }
246
+
247
+ /** Rebuild `inputs` so `run_id` may be null; the old table cannot be altered. */
248
+ function migrateInputs(database: Database): void {
249
+ database.exec(`
250
+ CREATE TABLE inputs_global (
251
+ input_id TEXT PRIMARY KEY,
252
+ run_id TEXT REFERENCES runs (run_id),
253
+ source TEXT NOT NULL,
254
+ source_key TEXT NOT NULL,
255
+ payload TEXT NOT NULL,
256
+ time INTEGER NOT NULL,
257
+ UNIQUE (source, source_key)
258
+ );
259
+ INSERT OR IGNORE INTO inputs_global (input_id, run_id, source, source_key, payload, time)
260
+ SELECT input_id, run_id, source, source_key, payload, time FROM inputs;
261
+ DROP TABLE inputs;
262
+ ALTER TABLE inputs_global RENAME TO inputs;
263
+ `);
264
+ }
265
+
266
+ interface DataVersionRow {
267
+ readonly data_version: number;
268
+ }
269
+
270
+ function openFailure(path: string, error: unknown): LogBackendError {
271
+ const detail = error instanceof Error ? error.message : String(error);
272
+ return new LogBackendError(`cannot open the sqlite log at ${path}: ${detail}`);
273
+ }
274
+
275
+ function ensureDirectory(path: string): void {
276
+ const directory = dirname(path);
277
+ try {
278
+ mkdirSync(directory, { recursive: true });
279
+ accessSync(directory, constants.W_OK);
280
+ if (existsSync(path)) accessSync(path, constants.W_OK);
281
+ } catch (error) {
282
+ throw openFailure(path, error);
283
+ }
284
+ }
285
+
286
+ function configure(database: Database): void {
287
+ setBusyTimeout(database);
288
+ database.run("PRAGMA synchronous = FULL");
289
+ database.run("PRAGMA foreign_keys = ON");
290
+ enableWal(database);
291
+ }
292
+
293
+ /** The recorded version, or undefined when the schema has not been created yet. */
294
+ function readSchemaVersion(database: Database): number | undefined {
295
+ try {
296
+ const row = database
297
+ .query<VersionRow, []>("SELECT version FROM schema_version WHERE id = 1")
298
+ .get();
299
+ return row && Number.isInteger(row.version) ? row.version : undefined;
300
+ } catch {
301
+ return undefined;
302
+ }
303
+ }
304
+
305
+ /**
306
+ * True when an open would have to change the schema. The checks are read-only,
307
+ * so opening an up-to-date store takes no write lock while another process is
308
+ * writing it.
309
+ */
310
+ function schemaNeedsWork(database: Database): boolean {
311
+ return (
312
+ !hasTable(database, "runs") ||
313
+ !hasTable(database, "facts") ||
314
+ !hasTable(database, "inputs") ||
315
+ !hasTable(database, "global_facts") ||
316
+ !hasTable(database, "outcomes") ||
317
+ !hasIndex(database, "runs_one_active") ||
318
+ !hasIndex(database, "runs_object") ||
319
+ inputsNeedMigration(database) ||
320
+ !tableColumns(database, "runs").some((item) => item.name === "start_input_id") ||
321
+ !tableColumns(database, "global_facts").some((item) => item.name === "unique_key") ||
322
+ !hasIndex(database, "global_facts_unique_key")
323
+ );
324
+ }
325
+
326
+ function ensureSchema(database: Database, path: string): void {
327
+ let version = readSchemaVersion(database);
328
+ if (version === undefined) {
329
+ // One immediate transaction for the whole schema: a second process opening
330
+ // the file at the same time waits in the busy handler, then finds it done.
331
+ database.transaction(() => {
332
+ database.exec(SCHEMA);
333
+ database.run("INSERT OR IGNORE INTO schema_version (id, version) VALUES (1, ?)", [
334
+ SCHEMA_VERSION,
335
+ ]);
336
+ }).immediate();
337
+ version = readSchemaVersion(database);
338
+ }
339
+
340
+ if (version === undefined) {
341
+ throw new SchemaVersionError(`store ${path} has no valid schema_version`);
342
+ }
343
+ if (version > SCHEMA_VERSION) {
344
+ throw new SchemaVersionError(
345
+ `store ${path} uses schema_version ${version}, but this build supports ${SCHEMA_VERSION}; ` +
346
+ "upgrade operad to open it",
347
+ );
348
+ }
349
+ if (version < SCHEMA_VERSION) {
350
+ version = migrateSchema(database, path, version);
351
+ }
352
+ if (version < SCHEMA_VERSION) {
353
+ throw new SchemaVersionError(
354
+ `store ${path} uses schema_version ${version}, but this build requires ${SCHEMA_VERSION}`,
355
+ );
356
+ }
357
+
358
+ // Tables added after a store was created are created here; the same
359
+ // transaction migrates an older inputs table whose run id could not be null
360
+ // and an older runs table that could not name the input that made the run.
361
+ // A current store needs none of it, so opening it stays read-only.
362
+ if (!schemaNeedsWork(database)) return;
363
+ database.transaction(() => {
364
+ // Recreate any base table or index a store lost; every statement is
365
+ // `IF NOT EXISTS`, so an existing object is left as it is.
366
+ database.exec(SCHEMA);
367
+ if (inputsNeedMigration(database)) migrateInputs(database);
368
+ const runsHaveStartInput = tableColumns(database, "runs").some(
369
+ (item) => item.name === "start_input_id",
370
+ );
371
+ if (!runsHaveStartInput) {
372
+ database.exec("ALTER TABLE runs ADD COLUMN start_input_id TEXT");
373
+ }
374
+ // A store written before global facts could be unique gains the column.
375
+ const globalHasUniqueKey = tableColumns(database, "global_facts").some(
376
+ (item) => item.name === "unique_key",
377
+ );
378
+ if (!globalHasUniqueKey) {
379
+ database.exec("ALTER TABLE global_facts ADD COLUMN unique_key TEXT");
380
+ }
381
+ database.exec(
382
+ "CREATE UNIQUE INDEX IF NOT EXISTS global_facts_unique_key " +
383
+ "ON global_facts (unique_key) WHERE unique_key IS NOT NULL",
384
+ );
385
+ }).immediate();
386
+ }
387
+
388
+ /**
389
+ * Upgrades an older store in place, one version at a time. Version 1 had no
390
+ * `runs.access` column; the column is additive, so the existing runs and
391
+ * history stay exactly as they were.
392
+ */
393
+ function migrateSchema(database: Database, path: string, from: number): number {
394
+ let version = from;
395
+ while (version < SCHEMA_VERSION) {
396
+ if (version === 1) {
397
+ database.transaction(() => {
398
+ const columns = database
399
+ .query<{ readonly name: string }, []>("PRAGMA table_info(runs)")
400
+ .all();
401
+ if (!columns.some((column) => column.name === "access")) {
402
+ database.run("ALTER TABLE runs ADD COLUMN access TEXT");
403
+ }
404
+ database.run("UPDATE schema_version SET version = ? WHERE id = 1", [2]);
405
+ }).immediate();
406
+ version = 2;
407
+ continue;
408
+ }
409
+ throw new SchemaVersionError(
410
+ `store ${path} uses schema_version ${version}, but this build requires ${SCHEMA_VERSION}`,
411
+ );
412
+ }
413
+ return version;
414
+ }
415
+
416
+ class SqliteLogBackend implements LogBackend {
417
+ readonly #database: Database;
418
+ readonly #clock: () => number;
419
+ readonly #newRunId: () => string;
420
+ readonly #path: string;
421
+ readonly #subscriptionWatch: SubscriptionWatch;
422
+ readonly #onSnapshot: (() => void) | undefined;
423
+ readonly #listeners = new Set<(change: LogChange) => void>();
424
+ #stopWatch: (() => void) | undefined;
425
+ #stopPoll: (() => void) | undefined;
426
+ #dataVersion: number | undefined;
427
+ #snapshot: Map<string, RunSnapshot> | undefined;
428
+ #closed = false;
429
+
430
+ constructor(
431
+ database: Database,
432
+ clock: () => number,
433
+ newRunId: () => string,
434
+ path: string,
435
+ subscriptionWatch: SubscriptionWatch,
436
+ onSnapshot?: () => void,
437
+ ) {
438
+ this.#onSnapshot = onSnapshot;
439
+ this.#database = database;
440
+ this.#clock = clock;
441
+ this.#newRunId = newRunId;
442
+ this.#path = path;
443
+ this.#subscriptionWatch = subscriptionWatch;
444
+ }
445
+
446
+ async startRun(
447
+ flow: string,
448
+ object: string,
449
+ startInputId: string | null = null,
450
+ access?: JsonValue,
451
+ ): Promise<RunInfo> {
452
+ assertName(flow, "flow");
453
+ assertName(object, "object");
454
+ if (access !== undefined) assertJsonValue(access, "run access");
455
+ this.#assertOpen();
456
+ return this.#database.transaction(() => {
457
+ const active = this.#database
458
+ .query<{ run_id: string }, [string, string]>(
459
+ "SELECT run_id FROM runs WHERE flow = ? AND object = ? AND ended_at IS NULL",
460
+ )
461
+ .get(flow, object);
462
+ if (active) throw new ActiveRunError(flow, object, active.run_id);
463
+
464
+ const runId = this.#newRunId();
465
+ assertRunId(runId);
466
+ const startedAt = this.#clock();
467
+ this.#database.run(
468
+ "INSERT INTO runs (run_id, flow, object, started_at, ended_at, start_input_id, access) " +
469
+ "VALUES (?, ?, ?, ?, NULL, ?, ?)",
470
+ [
471
+ runId,
472
+ flow,
473
+ object,
474
+ startedAt,
475
+ startInputId,
476
+ access === undefined ? null : JSON.stringify(access),
477
+ ],
478
+ );
479
+ this.#notify({ runId, object });
480
+ return {
481
+ runId,
482
+ flow,
483
+ object,
484
+ active: true,
485
+ startedAt,
486
+ endedAt: null,
487
+ lastSeq: 0,
488
+ ...(access === undefined ? {} : { access }),
489
+ startInputId,
490
+ };
491
+ }).immediate();
492
+ }
493
+
494
+ async endRun(runId: string): Promise<void> {
495
+ assertRunId(runId);
496
+ this.#assertOpen();
497
+ this.#database.transaction(() => {
498
+ const row = this.#runRow(runId);
499
+ if (!row) throw new RunNotFoundError(runId);
500
+ if (row.ended_at !== null) return;
501
+ this.#database.run("UPDATE runs SET ended_at = ? WHERE run_id = ? AND ended_at IS NULL", [
502
+ this.#clock(),
503
+ runId,
504
+ ]);
505
+ this.#notify({ runId, object: row.object });
506
+ }).immediate();
507
+ }
508
+
509
+ async recordInput(
510
+ runId: string | null,
511
+ source: string,
512
+ sourceKey: string,
513
+ payload: JsonValue,
514
+ ): Promise<RecordInputResult> {
515
+ if (runId !== null) assertRunId(runId);
516
+ assertName(source, "source");
517
+ assertName(sourceKey, "sourceKey");
518
+ assertJsonValue(payload, "input payload");
519
+ this.#assertOpen();
520
+ return this.#database.transaction(() => {
521
+ if (runId !== null) {
522
+ const row = this.#runRow(runId);
523
+ if (!row) throw new RunNotFoundError(runId);
524
+ if (row.ended_at !== null) throw new RunEndedError(runId);
525
+ }
526
+
527
+ const inputId = inputIdFor(source, sourceKey);
528
+ const result = this.#database.run(
529
+ "INSERT OR IGNORE INTO inputs (input_id, run_id, source, source_key, payload, time) " +
530
+ "VALUES (?, ?, ?, ?, ?, ?)",
531
+ [inputId, runId, source, sourceKey, JSON.stringify(payload), this.#clock()],
532
+ );
533
+ return { duplicate: result.changes === 0, inputId };
534
+ }).immediate();
535
+ }
536
+
537
+ async append(
538
+ runId: string,
539
+ expectedSeq: number,
540
+ facts: readonly NewFact[],
541
+ ): Promise<AppendResult> {
542
+ assertRunId(runId);
543
+ assertExpectedSeq(expectedSeq);
544
+ for (const fact of facts) validateNewFact(fact);
545
+ this.#assertOpen();
546
+
547
+ return this.#database.transaction(() => {
548
+ const row = this.#runRow(runId);
549
+ if (!row) throw new RunNotFoundError(runId);
550
+ if (row.ended_at !== null) throw new RunEndedError(runId);
551
+ if (row.last_seq !== expectedSeq) {
552
+ throw new SeqConflictError(runId, expectedSeq, row.last_seq);
553
+ }
554
+ if (facts.length === 0) {
555
+ return { lastSeq: row.last_seq, facts: [] };
556
+ }
557
+
558
+ const stored: Fact[] = facts.map((fact, index) => ({
559
+ runId,
560
+ seq: row.last_seq + index + 1,
561
+ kind: fact.kind,
562
+ payload: fact.payload,
563
+ cause: fact.cause,
564
+ time: this.#clock(),
565
+ }));
566
+ const insert = this.#database.prepare(
567
+ "INSERT INTO facts (run_id, seq, kind, payload, cause, time) VALUES (?, ?, ?, ?, ?, ?)",
568
+ );
569
+ try {
570
+ for (const fact of stored) {
571
+ insert.run(
572
+ fact.runId,
573
+ fact.seq,
574
+ fact.kind,
575
+ JSON.stringify(fact.payload),
576
+ JSON.stringify(fact.cause),
577
+ fact.time,
578
+ );
579
+ }
580
+ } finally {
581
+ insert.finalize();
582
+ }
583
+ this.#notify({ runId, object: row.object });
584
+ return { lastSeq: row.last_seq + stored.length, facts: stored };
585
+ }).immediate();
586
+ }
587
+
588
+ read(runId: string): AsyncIterable<Fact> {
589
+ assertRunId(runId);
590
+ return this.#read(runId);
591
+ }
592
+
593
+ async runs(options: RunsOptions = {}): Promise<RunInfo[]> {
594
+ this.#assertOpen();
595
+ const activeOnly = options.active === true ? 1 : 0;
596
+ const object = options.object ?? null;
597
+ const rows = this.#database
598
+ .query<RunRow, [number, string | null, string | null]>(
599
+ "SELECT r.run_id, r.flow, r.object, r.started_at, r.ended_at, r.start_input_id, r.access, " +
600
+ "COALESCE((SELECT MAX(seq) FROM facts WHERE run_id = r.run_id), 0) AS last_seq " +
601
+ "FROM runs r " +
602
+ "WHERE (? = 0 OR r.ended_at IS NULL) AND (? IS NULL OR r.object = ?) " +
603
+ "ORDER BY r.started_at, r.run_id",
604
+ )
605
+ .all(activeOnly, object, object);
606
+ return rows.map((row) => this.#toRunInfo(row));
607
+ }
608
+
609
+ async close(): Promise<void> {
610
+ if (this.#closed) return;
611
+ this.#closed = true;
612
+ this.#stopNotifications();
613
+ this.#listeners.clear();
614
+ this.#database.close();
615
+ }
616
+
617
+ async appendGlobal(fact: NewFact, uniqueKey?: string): Promise<GlobalFact> {
618
+ validateNewFact(fact);
619
+ if (uniqueKey !== undefined) assertName(uniqueKey, "uniqueKey");
620
+ this.#assertOpen();
621
+ return this.#database.transaction(() => {
622
+ if (uniqueKey !== undefined) {
623
+ const existing = this.#database
624
+ .query<GlobalFactRow, [string]>(
625
+ "SELECT seq, kind, payload, cause, time, unique_key FROM global_facts " +
626
+ "WHERE unique_key = ?",
627
+ )
628
+ .get(uniqueKey) ?? undefined;
629
+ if (existing !== undefined) return globalFactOfRow(existing);
630
+ }
631
+ const row = this.#database
632
+ .query<{ seq: number | null }, []>("SELECT MAX(seq) AS seq FROM global_facts")
633
+ .get();
634
+ const seq = (row?.seq ?? 0) + 1;
635
+ const time = this.#clock();
636
+ this.#database.run(
637
+ "INSERT INTO global_facts (seq, kind, payload, cause, time, unique_key) " +
638
+ "VALUES (?, ?, ?, ?, ?, ?)",
639
+ [
640
+ seq,
641
+ fact.kind,
642
+ JSON.stringify(fact.payload),
643
+ JSON.stringify(fact.cause),
644
+ time,
645
+ uniqueKey ?? null,
646
+ ],
647
+ );
648
+ return {
649
+ seq,
650
+ kind: fact.kind,
651
+ payload: fact.payload,
652
+ cause: fact.cause,
653
+ time,
654
+ ...(uniqueKey === undefined ? {} : { uniqueKey }),
655
+ };
656
+ }).immediate();
657
+ }
658
+
659
+ readGlobal(): AsyncIterable<GlobalFact> {
660
+ return this.#readGlobal();
661
+ }
662
+
663
+ async *readInputs(): AsyncGenerator<InputRecord> {
664
+ this.#assertOpen();
665
+ const statement = this.#database.prepare<InputRow, []>(
666
+ "SELECT input_id, run_id, source, source_key, payload, time " +
667
+ "FROM inputs ORDER BY time, input_id",
668
+ );
669
+ try {
670
+ for (const row of statement.iterate()) yield inputOfRow(row);
671
+ } finally {
672
+ statement.finalize();
673
+ }
674
+ }
675
+
676
+ async readInputsAfter(position: number): Promise<InputsAfter> {
677
+ this.#assertOpen();
678
+ const rows = this.#database
679
+ .query<InputRow & { pos: number }, [number]>(
680
+ "SELECT rowid AS pos, input_id, run_id, source, source_key, payload, time " +
681
+ "FROM inputs WHERE rowid > ? ORDER BY rowid",
682
+ )
683
+ .all(position);
684
+ const last = rows[rows.length - 1];
685
+ return {
686
+ inputs: rows.map(inputOfRow),
687
+ position: last === undefined ? position : last.pos,
688
+ };
689
+ }
690
+
691
+ async findInput(inputId: string): Promise<InputRecord | undefined> {
692
+ this.#assertOpen();
693
+ const row = this.#database
694
+ .query<InputRow, [string]>(
695
+ "SELECT input_id, run_id, source, source_key, payload, time " +
696
+ "FROM inputs WHERE input_id = ?",
697
+ )
698
+ .get(inputId);
699
+ return row === null || row === undefined ? undefined : inputOfRow(row);
700
+ }
701
+
702
+ async readOutcome(
703
+ inputId: string,
704
+ kind: string,
705
+ ): Promise<InputOutcome | undefined> {
706
+ this.#assertOpen();
707
+ const row = this.#outcomeRow(inputId, kind);
708
+ return row === undefined ? undefined : outcomeOfRow(row);
709
+ }
710
+
711
+ async readOutcomesAfter(seq: number): Promise<InputOutcome[]> {
712
+ this.#assertOpen();
713
+ return this.#database
714
+ .query<OutcomeRow, [number]>(
715
+ "SELECT input_id, kind, payload, seq, time FROM outcomes " +
716
+ "WHERE seq > ? ORDER BY seq",
717
+ )
718
+ .all(seq)
719
+ .map(outcomeOfRow);
720
+ }
721
+
722
+ async recordOutcome(
723
+ inputId: string,
724
+ kind: string,
725
+ payload: JsonValue,
726
+ ): Promise<RecordOutcomeResult> {
727
+ assertName(inputId, "inputId");
728
+ assertName(kind, "outcome kind");
729
+ assertJsonValue(payload, "outcome payload");
730
+ this.#assertOpen();
731
+ return this.#database.transaction(() => {
732
+ const existing = this.#outcomeRow(inputId, kind);
733
+ if (existing !== undefined) {
734
+ return { duplicate: true, outcome: outcomeOfRow(existing) };
735
+ }
736
+ const next = this.#database
737
+ .query<{ next: number }, []>(
738
+ "SELECT COALESCE(MAX(seq), 0) + 1 AS next FROM outcomes",
739
+ )
740
+ .get();
741
+ const seq = next?.next ?? 1;
742
+ const time = this.#clock();
743
+ this.#database.run(
744
+ "INSERT INTO outcomes (input_id, kind, payload, seq, time) VALUES (?, ?, ?, ?, ?)",
745
+ [inputId, kind, JSON.stringify(payload), seq, time],
746
+ );
747
+ return {
748
+ duplicate: false,
749
+ outcome: { inputId, kind, payload, seq, time },
750
+ };
751
+ }).immediate();
752
+ }
753
+
754
+ async *readOutcomes(): AsyncGenerator<InputOutcome> {
755
+ this.#assertOpen();
756
+ const statement = this.#database.prepare<OutcomeRow, []>(
757
+ "SELECT input_id, kind, payload, seq, time FROM outcomes ORDER BY seq",
758
+ );
759
+ try {
760
+ for (const row of statement.iterate()) {
761
+ yield outcomeOfRow(row);
762
+ }
763
+ } finally {
764
+ statement.finalize();
765
+ }
766
+ }
767
+
768
+ #outcomeRow(inputId: string, kind: string): OutcomeRow | undefined {
769
+ return this.#database
770
+ .query<OutcomeRow, [string, string]>(
771
+ "SELECT input_id, kind, payload, seq, time FROM outcomes " +
772
+ "WHERE input_id = ? AND kind = ?",
773
+ )
774
+ .get(inputId, kind) ?? undefined;
775
+ }
776
+
777
+ async *#readGlobal(): AsyncGenerator<GlobalFact> {
778
+ this.#assertOpen();
779
+ const statement = this.#database.prepare<GlobalFactRow, []>(
780
+ "SELECT seq, kind, payload, cause, time, unique_key FROM global_facts ORDER BY seq",
781
+ );
782
+ try {
783
+ for (const row of statement.iterate()) {
784
+ yield globalFactOfRow(row);
785
+ }
786
+ } finally {
787
+ statement.finalize();
788
+ }
789
+ }
790
+
791
+ /** Tells a listener in this process when a run changes. */
792
+ subscribe(listener: (change: LogChange) => void): () => void {
793
+ this.#listeners.add(listener);
794
+ if (this.#stopWatch === undefined) {
795
+ // Read the version before the snapshot: a write between the two is
796
+ // already in the snapshot and needs no event.
797
+ this.#dataVersion = this.#readDataVersion();
798
+ this.#snapshot = this.#takeSnapshot();
799
+ this.#stopWatch = this.#subscriptionWatch.watch(dirname(this.#path), () => {
800
+ // The plugin store shares this directory: its writes fire the watch
801
+ // too, so look at the data version before taking a snapshot.
802
+ this.#poll();
803
+ });
804
+ this.#stopPoll = this.#subscriptionWatch.repeat(this.#subscriptionWatch.pollMs, () => {
805
+ this.#poll();
806
+ });
807
+ }
808
+ return () => {
809
+ this.#listeners.delete(listener);
810
+ if (this.#listeners.size === 0) this.#stopNotifications();
811
+ };
812
+ }
813
+
814
+ #stopNotifications(): void {
815
+ this.#stopWatch?.();
816
+ this.#stopWatch = undefined;
817
+ this.#stopPoll?.();
818
+ this.#stopPoll = undefined;
819
+ this.#snapshot = undefined;
820
+ this.#dataVersion = undefined;
821
+ }
822
+
823
+ #notify(change: LogChange): void {
824
+ for (const listener of this.#listeners) listener(change);
825
+ }
826
+
827
+ /**
828
+ * The fallback check. `PRAGMA data_version` changes whenever another
829
+ * connection commits, including a commit the directory watch never reported.
830
+ */
831
+ #poll(): void {
832
+ if (this.#closed || this.#listeners.size === 0) return;
833
+ let version: number;
834
+ try {
835
+ version = this.#readDataVersion();
836
+ } catch {
837
+ return;
838
+ }
839
+ if (version === this.#dataVersion) return;
840
+ this.#dataVersion = version;
841
+ this.#notifyExternal();
842
+ }
843
+
844
+ #readDataVersion(): number {
845
+ return (
846
+ this.#database
847
+ .query<DataVersionRow, []>("PRAGMA data_version")
848
+ .get()?.data_version ?? 0
849
+ );
850
+ }
851
+
852
+ /** Reports runs another connection changed since the last event. */
853
+ #notifyExternal(): void {
854
+ if (this.#closed) return;
855
+ let next: Map<string, RunSnapshot>;
856
+ try {
857
+ next = this.#takeSnapshot();
858
+ } catch {
859
+ return;
860
+ }
861
+ const previous = this.#snapshot;
862
+ this.#snapshot = next;
863
+ if (previous === undefined) return;
864
+ for (const [runId, run] of next) {
865
+ const before = previous.get(runId);
866
+ if (
867
+ before !== undefined &&
868
+ before.object === run.object &&
869
+ before.lastSeq === run.lastSeq &&
870
+ before.ended === run.ended
871
+ ) {
872
+ continue;
873
+ }
874
+ this.#notify({ runId, object: run.object });
875
+ }
876
+ }
877
+
878
+ #takeSnapshot(): Map<string, RunSnapshot> {
879
+ this.#onSnapshot?.();
880
+ const rows = this.#database
881
+ .query<RunRow, []>(
882
+ "SELECT r.run_id, r.flow, r.object, r.started_at, r.ended_at, " +
883
+ "COALESCE((SELECT MAX(seq) FROM facts WHERE run_id = r.run_id), 0) AS last_seq " +
884
+ "FROM runs r",
885
+ )
886
+ .all();
887
+ const snapshot = new Map<string, RunSnapshot>();
888
+ for (const row of rows) {
889
+ snapshot.set(row.run_id, {
890
+ object: row.object,
891
+ lastSeq: row.last_seq,
892
+ ended: row.ended_at !== null,
893
+ });
894
+ }
895
+ return snapshot;
896
+ }
897
+
898
+ async *#read(runId: string): AsyncGenerator<Fact> {
899
+ this.#assertOpen();
900
+ if (!this.#runRow(runId)) throw new RunNotFoundError(runId);
901
+
902
+ const statement = this.#database.prepare<FactRow, [string]>(
903
+ "SELECT seq, kind, payload, cause, time FROM facts WHERE run_id = ? ORDER BY seq",
904
+ );
905
+ let expectedSeq = 1;
906
+ try {
907
+ for (const row of statement.iterate(runId)) {
908
+ if (row.seq !== expectedSeq) {
909
+ throw new CorruptLogError(runId, `sequence ${row.seq} follows ${expectedSeq - 1}`);
910
+ }
911
+ expectedSeq += 1;
912
+ yield {
913
+ runId,
914
+ seq: row.seq,
915
+ kind: row.kind,
916
+ payload: JSON.parse(row.payload) as JsonValue,
917
+ cause: JSON.parse(row.cause) as FactCause,
918
+ time: row.time,
919
+ };
920
+ }
921
+ } finally {
922
+ statement.finalize();
923
+ }
924
+ }
925
+
926
+ #assertOpen(): void {
927
+ if (this.#closed) throw new StoreClosedError();
928
+ }
929
+
930
+ #runRow(runId: string): RunRow | null {
931
+ return (
932
+ this.#database
933
+ .query<RunRow, [string]>(
934
+ "SELECT r.run_id, r.flow, r.object, r.started_at, r.ended_at, r.start_input_id, r.access, " +
935
+ "COALESCE((SELECT MAX(seq) FROM facts WHERE run_id = r.run_id), 0) AS last_seq " +
936
+ "FROM runs r WHERE r.run_id = ?",
937
+ )
938
+ .get(runId) ?? null
939
+ );
940
+ }
941
+
942
+ #toRunInfo(row: RunRow): RunInfo {
943
+ let access: JsonValue | undefined;
944
+ if (row.access !== null) {
945
+ try {
946
+ access = JSON.parse(row.access) as JsonValue;
947
+ } catch {
948
+ access = undefined;
949
+ }
950
+ }
951
+ return {
952
+ runId: row.run_id,
953
+ flow: row.flow,
954
+ object: row.object,
955
+ active: row.ended_at === null,
956
+ startedAt: row.started_at,
957
+ endedAt: row.ended_at,
958
+ lastSeq: row.last_seq,
959
+ ...(access === undefined ? {} : { access }),
960
+ startInputId: row.start_input_id,
961
+ };
962
+ }
963
+ }
964
+
965
+ /**
966
+ * Open the log at `path`, which is the database file itself. Parent
967
+ * directories are created. A directory the process cannot write is reported at
968
+ * open with the path in the message.
969
+ */
970
+ export function openSqliteLogBackend(
971
+ path: string,
972
+ options: LogBackendOptions = {},
973
+ ): LogBackend {
974
+ if (typeof path !== "string" || path.length === 0) {
975
+ throw new InvalidPayloadError("the sqlite log path must be a non-empty string");
976
+ }
977
+ ensureDirectory(path);
978
+
979
+ let database: Database;
980
+ try {
981
+ database = new Database(path, { create: true, readwrite: true });
982
+ } catch (error) {
983
+ throw openFailure(path, error);
984
+ }
985
+
986
+ try {
987
+ configure(database);
988
+ ensureSchema(database, path);
989
+ } catch (error) {
990
+ database.close();
991
+ if (error instanceof LogBackendError) throw error;
992
+ throw openFailure(path, error);
993
+ }
994
+
995
+ return new SqliteLogBackend(
996
+ database,
997
+ options.clock ?? Date.now,
998
+ options.runId ?? randomUUID,
999
+ path,
1000
+ resolveSubscriptionWatch(options),
1001
+ options.onSnapshot,
1002
+ );
1003
+ }
1004
+
1005
+ export const sqliteBackend: LogBackendFactory = {
1006
+ name: "sqlite",
1007
+ open: (directory, options) =>
1008
+ openSqliteLogBackend(join(directory, SQLITE_FILE_NAME), options),
1009
+ };
1010
+
1011
+ export default sqliteBackend;