@operad-io/engine 0.0.0-stage → 0.0.1

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/config.schema.json +188 -0
  3. package/keys.schema.json +12 -0
  4. package/package.json +22 -4
  5. package/src/config/config.ts +627 -0
  6. package/src/config/index.ts +1 -0
  7. package/src/flow/define-flow.ts +57 -0
  8. package/src/flow/index.ts +5 -0
  9. package/src/flow/load.ts +41 -0
  10. package/src/flow/types.ts +107 -0
  11. package/src/flow/validate.ts +296 -0
  12. package/src/http/address.ts +142 -0
  13. package/src/http/index.ts +25 -0
  14. package/src/http/link.ts +20 -0
  15. package/src/http/server.ts +920 -0
  16. package/src/http/token.ts +85 -0
  17. package/src/index.ts +16 -0
  18. package/src/kernel/decide.ts +689 -0
  19. package/src/kernel/index.ts +3 -0
  20. package/src/kernel/state.ts +275 -0
  21. package/src/kernel/types.ts +366 -0
  22. package/src/log/errors.ts +77 -0
  23. package/src/log/facts.ts +50 -0
  24. package/src/log/index.ts +6 -0
  25. package/src/log/json-value.ts +67 -0
  26. package/src/log/open-log.ts +17 -0
  27. package/src/log/schema.ts +5 -0
  28. package/src/log/secret.ts +30 -0
  29. package/src/log/sqlite.ts +1011 -0
  30. package/src/log/types.ts +230 -0
  31. package/src/loop/code-watch.ts +486 -0
  32. package/src/loop/index.ts +3 -0
  33. package/src/loop/older-code.ts +58 -0
  34. package/src/loop/serve.ts +483 -0
  35. package/src/markdown.ts +451 -0
  36. package/src/notify/index.ts +10 -0
  37. package/src/notify/notify.ts +256 -0
  38. package/src/platform/file-lock.ts +385 -0
  39. package/src/platform/index.ts +13 -0
  40. package/src/platform/load.ts +18 -0
  41. package/src/platform/process-group.ts +635 -0
  42. package/src/platform/process-watch.ts +152 -0
  43. package/src/platform/sqlite-open.ts +104 -0
  44. package/src/platform/step-reap.ts +668 -0
  45. package/src/platform/watch.ts +158 -0
  46. package/src/platform/worker-reports.ts +34 -0
  47. package/src/plugin/action-schema.ts +550 -0
  48. package/src/plugin/declared-flows.ts +74 -0
  49. package/src/plugin/define-plugin.ts +12 -0
  50. package/src/plugin/errors.ts +73 -0
  51. package/src/plugin/filters.ts +46 -0
  52. package/src/plugin/harness.ts +50 -0
  53. package/src/plugin/home.ts +13 -0
  54. package/src/plugin/index.ts +65 -0
  55. package/src/plugin/install.ts +268 -0
  56. package/src/plugin/keys.ts +63 -0
  57. package/src/plugin/load.ts +256 -0
  58. package/src/plugin/logger.ts +30 -0
  59. package/src/plugin/object-facts.ts +132 -0
  60. package/src/plugin/open-store.ts +32 -0
  61. package/src/plugin/paging.ts +133 -0
  62. package/src/plugin/registry.ts +1783 -0
  63. package/src/plugin/secrets.ts +141 -0
  64. package/src/plugin/semver.ts +110 -0
  65. package/src/plugin/settings.ts +64 -0
  66. package/src/plugin/sqlite-store.ts +756 -0
  67. package/src/plugin/store.ts +318 -0
  68. package/src/plugin/types.ts +1236 -0
  69. package/src/plugin/usage.ts +157 -0
  70. package/src/plugin/validate.ts +1028 -0
  71. package/src/runner/answer.ts +156 -0
  72. package/src/runner/ask.ts +483 -0
  73. package/src/runner/cancel.ts +51 -0
  74. package/src/runner/errors.ts +20 -0
  75. package/src/runner/grants.ts +92 -0
  76. package/src/runner/index.ts +33 -0
  77. package/src/runner/limits.ts +403 -0
  78. package/src/runner/lock.ts +140 -0
  79. package/src/runner/runner.ts +1175 -0
  80. package/src/runner/service.ts +184 -0
  81. package/src/runner/step-worker.ts +303 -0
  82. package/src/testing/clock.ts +67 -0
  83. package/src/testing/index.ts +90 -0
  84. package/src/testing/types.ts +116 -0
  85. package/src/testing/world.ts +369 -0
  86. package/src/trigger/cron.ts +193 -0
  87. package/src/trigger/index.ts +32 -0
  88. package/src/trigger/kernel.ts +1212 -0
  89. package/src/trigger/rules.ts +300 -0
  90. package/src/trigger/store.ts +233 -0
  91. package/src/trigger/types.ts +156 -0
  92. package/src/util.ts +50 -0
  93. package/src/views/history.ts +634 -0
  94. package/src/views/index.ts +7 -0
  95. package/src/views/pending.ts +209 -0
  96. package/src/views/presentation.ts +2551 -0
  97. package/src/views/running.ts +255 -0
  98. package/src/views/settings.ts +452 -0
  99. package/src/views/types.ts +72 -0
  100. package/src/views/uploads.ts +228 -0
  101. package/triggers.schema.json +48 -0
  102. package/README.md +0 -3
@@ -0,0 +1,756 @@
1
+ /** A plugin store backed by one SQLite file, in the same home as the log. */
2
+
3
+ import { Database } from "bun:sqlite";
4
+ import { existsSync, mkdirSync } from "node:fs";
5
+ import { enableWal, setBusyTimeout, writeImmediate } from "../platform/index.ts";
6
+ import { dirname, join } from "node:path";
7
+ import {
8
+ followsChanges,
9
+ type FollowOptions,
10
+ } from "../platform/index.ts";
11
+ import {
12
+ assertWhere,
13
+ CursorError,
14
+ decodeCursor,
15
+ encodeCursor,
16
+ matchesWhere,
17
+ pageLimit,
18
+ whereFingerprint,
19
+ } from "./paging.ts";
20
+ import type {
21
+ StoreFactInput,
22
+ FactsOptions,
23
+ FactsPage,
24
+ ListOptions,
25
+ ListPage,
26
+ ObjectData,
27
+ ObjectRef,
28
+ PluginFact,
29
+ PluginStore,
30
+ PluginStoreLocation,
31
+ StoredObject,
32
+ } from "./types.ts";
33
+ import { isRecord, requireName } from "../util.ts";
34
+ import { repeatEvery } from "../util.ts";
35
+ import {
36
+ applyObjectChange,
37
+ diffObject,
38
+ isObjectFact,
39
+ OBJECT_CHANGE_FACT,
40
+ type ObjectChange,
41
+ objectChangeOf,
42
+ } from "./object-facts.ts";
43
+
44
+ export interface SqlitePluginStoreOptions extends FollowOptions {
45
+ readonly root: string;
46
+ /** The database file; defaults to `<root>/plugins.sqlite`. */
47
+ readonly file?: string | undefined;
48
+ readonly clock?: (() => number) | undefined;
49
+ /**
50
+ * Starts a repeating timer that calls `callback` every `ms` and returns a
51
+ * stop function. Defaults to `setInterval`. A test passes a stub it fires by
52
+ * hand, so no test waits on wall time.
53
+ */
54
+ readonly repeat?:
55
+ | ((ms: number, callback: () => void) => () => void)
56
+ | undefined;
57
+ }
58
+
59
+ interface ObjectRow {
60
+ readonly type: string;
61
+ readonly id: string;
62
+ readonly data: string;
63
+ readonly version: number;
64
+ readonly cause: string;
65
+ readonly at: number;
66
+ }
67
+
68
+ interface FactRow {
69
+ readonly sequence: number;
70
+ readonly type: string;
71
+ readonly object_type: string | null;
72
+ readonly object_id: string | null;
73
+ readonly cause: string;
74
+ readonly at: number;
75
+ readonly data: string;
76
+ }
77
+
78
+ interface Subscription {
79
+ readonly key: string;
80
+ readonly after: number;
81
+ readonly listener: (fact: PluginFact) => void;
82
+ }
83
+
84
+ const SCHEMA = `
85
+ CREATE TABLE IF NOT EXISTS schema_version (
86
+ id INTEGER PRIMARY KEY CHECK (id = 1),
87
+ version INTEGER NOT NULL
88
+ );
89
+ CREATE TABLE IF NOT EXISTS objects (
90
+ type TEXT NOT NULL,
91
+ id TEXT NOT NULL,
92
+ data TEXT NOT NULL,
93
+ version INTEGER NOT NULL,
94
+ cause TEXT NOT NULL,
95
+ at INTEGER NOT NULL,
96
+ PRIMARY KEY (type, id)
97
+ );
98
+ CREATE TABLE IF NOT EXISTS facts (
99
+ sequence INTEGER PRIMARY KEY AUTOINCREMENT,
100
+ type TEXT NOT NULL,
101
+ object_type TEXT,
102
+ object_id TEXT,
103
+ cause TEXT NOT NULL,
104
+ at INTEGER NOT NULL,
105
+ data TEXT NOT NULL
106
+ );
107
+ CREATE INDEX IF NOT EXISTS facts_by_object
108
+ ON facts (object_type, object_id, sequence);
109
+ CREATE INDEX IF NOT EXISTS facts_old_shape
110
+ ON facts (object_type, object_id) WHERE type = object_type;
111
+ CREATE INDEX IF NOT EXISTS facts_by_object_id
112
+ ON facts (object_id, object_type);
113
+ CREATE TABLE IF NOT EXISTS declared_index (
114
+ type TEXT NOT NULL,
115
+ field TEXT NOT NULL,
116
+ PRIMARY KEY (type, field)
117
+ );
118
+ CREATE TABLE IF NOT EXISTS declared_types (
119
+ type TEXT PRIMARY KEY
120
+ );
121
+ `;
122
+
123
+ const SCHEMA_FILE = "plugins.sqlite";
124
+
125
+ /**
126
+ * The plugin store's schema version. Version 1 wrote a whole object snapshot
127
+ * on every put; version 2 writes the changed fields and the removed names.
128
+ */
129
+ export const PLUGIN_STORE_SCHEMA_VERSION = 2;
130
+
131
+ interface VersionRow {
132
+ readonly version: number;
133
+ }
134
+
135
+ interface ObjectKeyRow {
136
+ readonly type: string;
137
+ readonly id: string;
138
+ }
139
+
140
+ interface HistoryRow {
141
+ readonly sequence: number;
142
+ readonly type: string;
143
+ readonly data: string;
144
+ }
145
+
146
+ function readSchemaVersion(database: Database): number | undefined {
147
+ try {
148
+ const row = database
149
+ .query<VersionRow, []>("SELECT version FROM schema_version WHERE id = 1")
150
+ .get();
151
+ return row !== null && Number.isInteger(row.version) ? row.version : undefined;
152
+ } catch {
153
+ return undefined;
154
+ }
155
+ }
156
+
157
+ function hasTable(database: Database, name: string): boolean {
158
+ return (
159
+ database
160
+ .query<{ name: string }, [string]>(
161
+ "SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?",
162
+ )
163
+ .get(name) !== null
164
+ );
165
+ }
166
+
167
+ /**
168
+ * Rewrites every old full-snapshot put fact as a change, one transaction per
169
+ * object, keeping its sequence, cause and time. It runs on every open: an
170
+ * older process still writing to the same file keeps appending snapshots. The
171
+ * partial index `facts_old_shape` finds them without a scan, and an object
172
+ * already rewritten is not listed, so a repeat changes nothing.
173
+ */
174
+ function migrateObjectFacts(database: Database): void {
175
+ const objects = database
176
+ .query<ObjectKeyRow, []>(
177
+ `SELECT DISTINCT object_type AS type, object_id AS id
178
+ FROM facts
179
+ WHERE object_type IS NOT NULL AND object_id IS NOT NULL
180
+ AND type = object_type
181
+ ORDER BY object_type, object_id`,
182
+ )
183
+ .all();
184
+ const history = database.prepare(
185
+ `SELECT sequence, type, data FROM facts
186
+ WHERE object_type = ? AND object_id = ?
187
+ ORDER BY sequence`,
188
+ );
189
+ const update = database.prepare("UPDATE facts SET type = ?, data = ? WHERE sequence = ?");
190
+ for (const object of objects) {
191
+ writeImmediate(database, () => {
192
+ const rows = history.all(object.type, object.id) as HistoryRow[];
193
+ let previous: ObjectData | undefined;
194
+ for (const row of rows) {
195
+ const data = parseData(row.data);
196
+ if (row.type === OBJECT_CHANGE_FACT) {
197
+ const change = objectChangeOf(data);
198
+ if (change !== undefined) previous = applyObjectChange(previous ?? {}, change);
199
+ } else if (row.type === object.type) {
200
+ const change: ObjectChange =
201
+ previous === undefined
202
+ ? { changed: data, removed: [] }
203
+ : (diffObject(previous, data) ?? { changed: {}, removed: [] });
204
+ update.run(OBJECT_CHANGE_FACT, JSON.stringify(change), row.sequence);
205
+ previous = data;
206
+ }
207
+ }
208
+ });
209
+ }
210
+ }
211
+
212
+ function ensureSchema(database: Database, file: string): void {
213
+ let version = readSchemaVersion(database);
214
+ if (version === undefined) {
215
+ // A store with tables but no version was written before this version
216
+ // existed: its full-snapshot facts are version 1. A fresh store starts at
217
+ // the current version. The immediate transaction makes two processes
218
+ // opening the file at once wait, then find it done.
219
+ const old = hasTable(database, "facts") || hasTable(database, "objects");
220
+ database
221
+ .transaction(() => {
222
+ database.exec(SCHEMA);
223
+ database.run("INSERT OR IGNORE INTO schema_version (id, version) VALUES (1, ?)", [
224
+ old ? 1 : PLUGIN_STORE_SCHEMA_VERSION,
225
+ ]);
226
+ })
227
+ .immediate();
228
+ version = readSchemaVersion(database);
229
+ }
230
+ if (version === undefined) {
231
+ throw new Error(`plugin store ${file} has no valid schema_version`);
232
+ }
233
+ if (version > PLUGIN_STORE_SCHEMA_VERSION) {
234
+ throw new Error(
235
+ `plugin store ${file} uses schema_version ${version}, but this build supports ` +
236
+ `${PLUGIN_STORE_SCHEMA_VERSION}; upgrade operad to open it`,
237
+ );
238
+ }
239
+ // Repair a base table or index a store lost; every statement is IF NOT EXISTS.
240
+ database.exec(SCHEMA);
241
+ migrateObjectFacts(database);
242
+ if (version < PLUGIN_STORE_SCHEMA_VERSION) {
243
+ writeImmediate(database, () => {
244
+ database.run("UPDATE schema_version SET version = ? WHERE id = 1", [
245
+ PLUGIN_STORE_SCHEMA_VERSION,
246
+ ]);
247
+ });
248
+ version = readSchemaVersion(database);
249
+ }
250
+ if (version !== PLUGIN_STORE_SCHEMA_VERSION) {
251
+ throw new Error(
252
+ `plugin store ${file} uses schema_version ${String(version)}, but this build ` +
253
+ `requires ${PLUGIN_STORE_SCHEMA_VERSION}`,
254
+ );
255
+ }
256
+ }
257
+
258
+ function deepFreeze<T>(value: T): T {
259
+ if (typeof value === "object" && value !== null && !Object.isFrozen(value)) {
260
+ Object.freeze(value);
261
+ for (const inner of Object.values(value)) deepFreeze(inner);
262
+ }
263
+ return value;
264
+ }
265
+
266
+ function parseData(text: string): ObjectData {
267
+ try {
268
+ const value: unknown = JSON.parse(text);
269
+ return isRecord(value) ? value : {};
270
+ } catch {
271
+ return {};
272
+ }
273
+ }
274
+
275
+ /** A durable object store for a home configured with the sqlite backend. */
276
+ export class SqlitePluginStore implements PluginStore {
277
+ readonly kind = "file" as const;
278
+ readonly root: string;
279
+ readonly location: PluginStoreLocation;
280
+ private readonly db: Database;
281
+ private readonly clock: () => number;
282
+ private readonly follow: boolean;
283
+ private readonly repeat: (ms: number, callback: () => void) => () => void;
284
+ private readonly listeners = new Set<(object: ObjectRef) => void>();
285
+ private readonly factListeners = new Set<Subscription>();
286
+ /** The last sequence any subscription has been told about. */
287
+ private polledSequence = 0;
288
+ private stopPoll: (() => void) | undefined;
289
+ /** The objects `list` last read, by type and id; frozen, so sharing is safe. */
290
+ private readonly listed = new Map<string, Map<string, StoredObject>>();
291
+
292
+ constructor(options: SqlitePluginStoreOptions) {
293
+ this.root = options.root;
294
+ this.clock = options.clock ?? (() => Date.now());
295
+ this.follow = followsChanges(options);
296
+ this.repeat = options.repeat ?? repeatEvery;
297
+ const file = options.file ?? join(options.root, SCHEMA_FILE);
298
+ this.location = { backend: "sqlite", root: options.root, file };
299
+ mkdirSync(dirname(file), { recursive: true });
300
+ this.db = new Database(file);
301
+ try {
302
+ setBusyTimeout(this.db);
303
+ enableWal(this.db);
304
+ ensureSchema(this.db, file);
305
+ } catch (error) {
306
+ this.db.close();
307
+ throw error;
308
+ }
309
+ }
310
+
311
+ /**
312
+ * Record the type and its index fields. Every command loads the plugins and
313
+ * so calls this, `list` among them: it writes only when the stored
314
+ * declaration differs, so a command that only reads never waits for the
315
+ * write lock a running `serve` keeps taking (and never fails with "database
316
+ * is locked" when serve holds it past the busy timeout). A change is one
317
+ * transaction, so a reader never sees the index half replaced.
318
+ */
319
+ declare(type: string, index: readonly string[]): void {
320
+ const fields = [...new Set(index)].sort();
321
+ const stored = this.declaredIndex(type);
322
+ if (
323
+ stored !== undefined &&
324
+ stored.length === fields.length &&
325
+ stored.every((field, position) => field === fields[position])
326
+ ) {
327
+ return;
328
+ }
329
+ writeImmediate(this.db, () => {
330
+ this.db
331
+ .query("INSERT OR IGNORE INTO declared_types (type) VALUES (?)")
332
+ .run(type);
333
+ this.db.query("DELETE FROM declared_index WHERE type = ?").run(type);
334
+ const insert = this.db.query(
335
+ "INSERT OR IGNORE INTO declared_index (type, field) VALUES (?, ?)",
336
+ );
337
+ for (const field of fields) insert.run(type, field);
338
+ });
339
+ }
340
+
341
+ put(type: string, id: string, data: ObjectData, cause: string): StoredObject {
342
+ requireName(type, "object type");
343
+ requireName(id, "object id");
344
+ requireName(cause, "cause");
345
+ const at = this.clock();
346
+ return writeImmediate(this.db, () => {
347
+ // Read the previous version under the write lock, so a put another
348
+ // process committed since this call began is the base of this change.
349
+ const previous = this.get(type, id);
350
+ let change: ObjectChange;
351
+ if (previous === undefined) {
352
+ change = { changed: { ...data }, removed: [] };
353
+ } else {
354
+ // An unchanged put still records its cause: dev's attempts table reads
355
+ // the cause of a step's put even when the step changed no field.
356
+ change = diffObject(previous.data, data) ?? { changed: {}, removed: [] };
357
+ }
358
+ const object: StoredObject = {
359
+ type,
360
+ id,
361
+ data: { ...data },
362
+ version: (previous?.version ?? 0) + 1,
363
+ cause,
364
+ at,
365
+ };
366
+ this.db
367
+ .query(
368
+ `INSERT INTO objects (type, id, data, version, cause, at)
369
+ VALUES (?, ?, ?, ?, ?, ?)
370
+ ON CONFLICT (type, id) DO UPDATE SET
371
+ data = excluded.data,
372
+ version = excluded.version,
373
+ cause = excluded.cause,
374
+ at = excluded.at`,
375
+ )
376
+ .run(
377
+ type,
378
+ id,
379
+ JSON.stringify(object.data),
380
+ object.version,
381
+ cause,
382
+ object.at,
383
+ );
384
+ this.insertFact({ type: OBJECT_CHANGE_FACT, object: { type, id }, data: change, cause });
385
+ return object;
386
+ });
387
+ }
388
+
389
+ get(type: string, id: string): StoredObject | undefined {
390
+ const row = this.db
391
+ .query("SELECT type, id, data, version, cause, at FROM objects WHERE type = ? AND id = ?")
392
+ .get(type, id) as ObjectRow | null;
393
+ return row === null ? undefined : this.objectOf(row);
394
+ }
395
+
396
+ list(type: string, options: ListOptions = {}): ListPage {
397
+ this.assertWhere(type, options);
398
+ const fingerprint = whereFingerprint(options.where ?? {});
399
+ let after: string | undefined;
400
+ if (options.cursor !== undefined) {
401
+ const cursor = decodeCursor(options.cursor, `list "${type}"`);
402
+ if (cursor.kind !== "list") {
403
+ throw new CursorError(`list "${type}": invalid cursor`);
404
+ }
405
+ if (cursor.type !== type) {
406
+ throw new CursorError(
407
+ `list "${type}": the cursor belongs to object type "${String(cursor.type)}"`,
408
+ );
409
+ }
410
+ if (cursor.where !== fingerprint) {
411
+ throw new CursorError(
412
+ `list "${type}": the cursor was made for a different filter`,
413
+ );
414
+ }
415
+ if (typeof cursor.after !== "string") {
416
+ throw new CursorError(`list "${type}": invalid cursor`);
417
+ }
418
+ after = cursor.after;
419
+ }
420
+
421
+ // Read from the cursor on and stop once a page and one more are found. The
422
+ // scan reads each row's version, not its data: an object whose version,
423
+ // time and cause match the remembered copy is not read or parsed again, so
424
+ // a page costs what changed in it, not what it holds.
425
+ const statement = this.db.prepare(
426
+ "SELECT type, id, version, cause, at FROM objects WHERE type = ? AND id > ? ORDER BY id",
427
+ );
428
+ const limit = pageLimit(options.limit);
429
+ const objects: StoredObject[] = [];
430
+ const remembered = this.listed.get(type) ?? new Map<string, StoredObject>();
431
+ this.listed.set(type, remembered);
432
+ try {
433
+ for (const row of statement.iterate(type, after ?? "") as IterableIterator<
434
+ Omit<ObjectRow, "data">
435
+ >) {
436
+ let object = remembered.get(row.id);
437
+ if (
438
+ object === undefined ||
439
+ object.version !== row.version ||
440
+ object.at !== row.at ||
441
+ object.cause !== row.cause
442
+ ) {
443
+ const full = this.get(type, row.id);
444
+ if (full === undefined) continue;
445
+ object = deepFreeze(full);
446
+ remembered.set(row.id, object);
447
+ }
448
+ if (!matchesWhere(object.data, options.where)) continue;
449
+ objects.push(object);
450
+ if (objects.length > limit) break;
451
+ }
452
+ } finally {
453
+ statement.finalize();
454
+ }
455
+ const more = objects.length > limit;
456
+ if (more) objects.length = limit;
457
+ const last = objects.at(-1);
458
+ return {
459
+ objects,
460
+ ...(more && last !== undefined
461
+ ? {
462
+ next: encodeCursor({
463
+ kind: "list",
464
+ type,
465
+ after: last.id,
466
+ where: fingerprint,
467
+ }),
468
+ }
469
+ : {}),
470
+ };
471
+ }
472
+
473
+ objectTypesOf(id: string): readonly string[] {
474
+ const rows = this.db
475
+ .query(
476
+ "SELECT DISTINCT object_type FROM facts WHERE object_id = ? AND object_type IS NOT NULL ORDER BY object_type",
477
+ )
478
+ .all(id) as { object_type: string }[];
479
+ return rows.map((row) => row.object_type);
480
+ }
481
+
482
+ facts(): readonly PluginFact[];
483
+ facts(object: ObjectRef, options?: FactsOptions): FactsPage;
484
+ facts(
485
+ object?: ObjectRef,
486
+ options: FactsOptions = {},
487
+ ): readonly PluginFact[] | FactsPage {
488
+ if (object === undefined) {
489
+ const rows = this.db
490
+ .query(
491
+ "SELECT sequence, type, object_type, object_id, cause, at, data FROM facts ORDER BY sequence",
492
+ )
493
+ .all() as FactRow[];
494
+ return rows.map((row) => this.factOf(row));
495
+ }
496
+
497
+ const after = this.factCursor(object, options.cursor);
498
+ const limit = pageLimit(options.limit);
499
+ const rows = this.db
500
+ .query(
501
+ `SELECT sequence, type, object_type, object_id, cause, at, data
502
+ FROM facts
503
+ WHERE object_type = ? AND object_id = ? AND sequence > ?
504
+ ORDER BY sequence
505
+ LIMIT ?`,
506
+ )
507
+ .all(object.type, object.id, after, limit + 1) as FactRow[];
508
+ const more = rows.length > limit;
509
+ const page = rows.slice(0, limit).map((row) => this.factOf(row));
510
+ const last = page.at(-1);
511
+ return {
512
+ facts: page,
513
+ ...(more && last !== undefined
514
+ ? {
515
+ next: encodeCursor({
516
+ kind: "facts",
517
+ type: object.type,
518
+ id: object.id,
519
+ after: last.sequence,
520
+ }),
521
+ }
522
+ : {}),
523
+ };
524
+ }
525
+
526
+ subscribe(listener: (object: ObjectRef) => void): () => void;
527
+ subscribe(
528
+ object: ObjectRef,
529
+ options: FactsOptions,
530
+ listener: (fact: PluginFact) => void,
531
+ ): () => void;
532
+ subscribe(
533
+ objectOrListener: ObjectRef | ((object: ObjectRef) => void),
534
+ options: FactsOptions = {},
535
+ factListener?: (fact: PluginFact) => void,
536
+ ): () => void {
537
+ if (typeof objectOrListener !== "function") {
538
+ if (factListener === undefined) {
539
+ throw new Error("subscribe: a fact listener is required");
540
+ }
541
+ return this.subscribeFacts(objectOrListener, options, factListener);
542
+ }
543
+ this.listeners.add(objectOrListener);
544
+ this.ensurePolling();
545
+ return () => {
546
+ this.listeners.delete(objectOrListener);
547
+ this.releasePolling();
548
+ };
549
+ }
550
+
551
+ subscribeFacts(
552
+ object: ObjectRef,
553
+ options: FactsOptions,
554
+ listener: (fact: PluginFact) => void,
555
+ ): () => void {
556
+ const key = this.key(object.type, object.id);
557
+ let after = this.factCursor(object, options.cursor);
558
+ if (options.cursor === undefined) {
559
+ const last = this.db
560
+ .query(
561
+ "SELECT sequence FROM facts WHERE object_type = ? AND object_id = ? ORDER BY sequence DESC LIMIT 1",
562
+ )
563
+ .get(object.type, object.id) as { sequence: number } | null;
564
+ after = last?.sequence ?? 0;
565
+ }
566
+ const existing = this.db
567
+ .query(
568
+ `SELECT sequence, type, object_type, object_id, cause, at, data
569
+ FROM facts
570
+ WHERE object_type = ? AND object_id = ? AND sequence > ?
571
+ ORDER BY sequence`,
572
+ )
573
+ .all(object.type, object.id, after) as FactRow[];
574
+ let replayed = 0;
575
+ for (const row of existing) {
576
+ const fact = this.factOf(row);
577
+ listener(fact);
578
+ replayed = Math.max(replayed, fact.sequence);
579
+ }
580
+ this.polledSequence = Math.max(this.polledSequence, replayed);
581
+ const subscription: Subscription = { key, after, listener };
582
+ this.factListeners.add(subscription);
583
+ this.ensurePolling();
584
+ return () => {
585
+ this.factListeners.delete(subscription);
586
+ this.releasePolling();
587
+ };
588
+ }
589
+
590
+ append(input: StoreFactInput): PluginFact {
591
+ return writeImmediate(this.db, () => this.insertFact(input));
592
+ }
593
+
594
+ private insertFact(input: StoreFactInput): PluginFact {
595
+ requireName(input.type, "fact type");
596
+ const cause = input.cause;
597
+ requireName(cause, "cause");
598
+ const at = this.clock();
599
+ const result = this.db
600
+ .query(
601
+ "INSERT INTO facts (type, object_type, object_id, cause, at, data) VALUES (?, ?, ?, ?, ?, ?)",
602
+ )
603
+ .run(
604
+ input.type,
605
+ input.object?.type ?? null,
606
+ input.object?.id ?? null,
607
+ cause,
608
+ at,
609
+ JSON.stringify(input.data),
610
+ );
611
+ const fact: PluginFact = {
612
+ sequence: Number(result.lastInsertRowid),
613
+ type: input.type,
614
+ object: input.object,
615
+ cause,
616
+ at,
617
+ data: { ...input.data },
618
+ };
619
+ if (fact.object !== undefined) {
620
+ for (const listener of this.listeners) listener(fact.object);
621
+ }
622
+ this.polledSequence = Math.max(this.polledSequence, fact.sequence);
623
+ this.notifyFacts(fact);
624
+ return fact;
625
+ }
626
+
627
+ /** Closes the database; tests open many homes. */
628
+ close(): void {
629
+ this.stopPoll?.();
630
+ this.stopPoll = undefined;
631
+ this.db.close();
632
+ }
633
+
634
+ /** Polls for facts another connection committed; SQLite has no notification. */
635
+ private ensurePolling(): void {
636
+ if (!this.follow) return;
637
+ if (this.factListeners.size === 0 && this.listeners.size === 0) return;
638
+ if (this.stopPoll !== undefined) return;
639
+ if (this.factListeners.size === 0) {
640
+ this.polledSequence = Math.max(this.polledSequence, this.maxSequence());
641
+ }
642
+ this.stopPoll = this.repeat(25, () => this.pollFacts());
643
+ }
644
+
645
+ private releasePolling(): void {
646
+ if (this.factListeners.size > 0 || this.listeners.size > 0) return;
647
+ this.stopPoll?.();
648
+ this.stopPoll = undefined;
649
+ }
650
+
651
+ private maxSequence(): number {
652
+ const row = this.db
653
+ .query("SELECT COALESCE(MAX(sequence), 0) AS sequence FROM facts")
654
+ .get() as { sequence: number };
655
+ return row.sequence;
656
+ }
657
+
658
+ private pollFacts(): void {
659
+ // A removed database has nothing left to deliver; its timer outlives it.
660
+ if (!existsSync(this.location.file ?? this.root)) return;
661
+ const rows = this.db
662
+ .query(
663
+ `SELECT sequence, type, object_type, object_id, cause, at, data
664
+ FROM facts
665
+ WHERE sequence > ?
666
+ ORDER BY sequence`,
667
+ )
668
+ .all(this.polledSequence) as FactRow[];
669
+ for (const row of rows) {
670
+ const fact = this.factOf(row);
671
+ this.polledSequence = Math.max(this.polledSequence, fact.sequence);
672
+ if (isObjectFact(fact)) {
673
+ for (const listener of this.listeners) listener(fact.object);
674
+ }
675
+ this.notifyFacts(fact);
676
+ }
677
+ }
678
+
679
+ private notifyFacts(fact: PluginFact): void {
680
+ if (fact.object === undefined) return;
681
+ const key = this.key(fact.object.type, fact.object.id);
682
+ for (const subscription of this.factListeners) {
683
+ if (subscription.key !== key) continue;
684
+ if (fact.sequence <= subscription.after) continue;
685
+ subscription.listener(fact);
686
+ }
687
+ }
688
+
689
+ private objectOf(row: ObjectRow): StoredObject {
690
+ return {
691
+ type: row.type,
692
+ id: row.id,
693
+ data: parseData(row.data),
694
+ version: row.version,
695
+ cause: row.cause,
696
+ at: row.at,
697
+ };
698
+ }
699
+
700
+ private factOf(row: FactRow): PluginFact {
701
+ return {
702
+ sequence: row.sequence,
703
+ type: row.type,
704
+ object:
705
+ row.object_type === null || row.object_id === null
706
+ ? undefined
707
+ : { type: row.object_type, id: row.object_id },
708
+ cause: row.cause,
709
+ at: row.at,
710
+ data: parseData(row.data),
711
+ };
712
+ }
713
+
714
+ private assertWhere(type: string, options: ListOptions): void {
715
+ if (options.where === undefined) return;
716
+ const declared = options.index ?? this.declaredIndex(type);
717
+ if (declared === undefined) {
718
+ assertWhere(Object.keys(options.where), options.where, `list "${type}"`);
719
+ return;
720
+ }
721
+ assertWhere(declared, options.where, `list "${type}"`);
722
+ }
723
+
724
+ private declaredIndex(type: string): readonly string[] | undefined {
725
+ const declared = this.db
726
+ .query("SELECT 1 AS present FROM declared_types WHERE type = ?")
727
+ .get(type);
728
+ if (declared === null) return undefined;
729
+ const rows = this.db
730
+ .query("SELECT field FROM declared_index WHERE type = ? ORDER BY field")
731
+ .all(type) as { field: string }[];
732
+ return rows.map((row) => row.field);
733
+ }
734
+
735
+ private factCursor(object: ObjectRef, cursor: string | undefined): number {
736
+ if (cursor === undefined) return 0;
737
+ const label = `facts "${object.type}:${object.id}"`;
738
+ const value = decodeCursor(cursor, label);
739
+ if (value.kind !== "facts") {
740
+ throw new CursorError(`${label}: invalid cursor`);
741
+ }
742
+ if (value.type !== object.type || value.id !== object.id) {
743
+ throw new CursorError(
744
+ `${label}: the cursor belongs to "${String(value.type)}:${String(value.id)}"`,
745
+ );
746
+ }
747
+ if (typeof value.after !== "number" || !Number.isInteger(value.after)) {
748
+ throw new CursorError(`${label}: invalid cursor`);
749
+ }
750
+ return value.after;
751
+ }
752
+
753
+ private key(type: string, id: string): string {
754
+ return `${type}\u0000${id}`;
755
+ }
756
+ }