@operad-io/engine 0.1.0 → 0.2.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 (80) hide show
  1. package/config.schema.json +2 -1
  2. package/package.json +1 -1
  3. package/src/config/config.ts +74 -45
  4. package/src/flow/types.ts +4 -0
  5. package/src/flow/validate.ts +5 -0
  6. package/src/http/index.ts +2 -0
  7. package/src/http/plugins.ts +66 -0
  8. package/src/http/server.ts +342 -48
  9. package/src/kernel/decide.ts +115 -30
  10. package/src/kernel/state.ts +9 -0
  11. package/src/kernel/types.ts +25 -40
  12. package/src/log/open-log.ts +2 -5
  13. package/src/log/sqlite.ts +127 -85
  14. package/src/log/types.ts +35 -9
  15. package/src/loop/code-watch.ts +108 -2
  16. package/src/loop/older-code.ts +3 -4
  17. package/src/loop/serve.ts +122 -95
  18. package/src/notify/notify.ts +2 -6
  19. package/src/platform/atomic-write.ts +163 -0
  20. package/src/platform/file-lock.ts +43 -21
  21. package/src/platform/index.ts +2 -0
  22. package/src/platform/kept-workers.ts +290 -0
  23. package/src/platform/process-group.ts +11 -3
  24. package/src/platform/sqlite-open.ts +20 -6
  25. package/src/platform/sqlite-schema.ts +30 -0
  26. package/src/platform/step-reap.ts +33 -18
  27. package/src/platform/watch.ts +1 -11
  28. package/src/plugin/action-schema.ts +59 -1
  29. package/src/plugin/choice-info.ts +133 -0
  30. package/src/plugin/context.ts +279 -0
  31. package/src/plugin/declared-flows.ts +3 -10
  32. package/src/plugin/errors.ts +9 -0
  33. package/src/plugin/freeze.ts +12 -0
  34. package/src/plugin/harness.ts +28 -0
  35. package/src/plugin/index.ts +8 -7
  36. package/src/plugin/install.ts +265 -17
  37. package/src/plugin/keys.ts +2 -12
  38. package/src/plugin/load.ts +47 -23
  39. package/src/plugin/logger.ts +14 -0
  40. package/src/plugin/open-store.ts +0 -6
  41. package/src/plugin/question-form.ts +323 -0
  42. package/src/plugin/registry.ts +512 -76
  43. package/src/plugin/secrets.ts +14 -24
  44. package/src/plugin/semver.ts +52 -0
  45. package/src/plugin/settings.ts +1 -9
  46. package/src/plugin/sqlite-store.ts +94 -64
  47. package/src/plugin/store.ts +5 -0
  48. package/src/plugin/types.ts +566 -21
  49. package/src/plugin/validate.ts +396 -26
  50. package/src/runner/answer.ts +26 -68
  51. package/src/runner/ask.ts +227 -28
  52. package/src/runner/cancel.ts +10 -7
  53. package/src/runner/grants.ts +2 -2
  54. package/src/runner/index.ts +1 -3
  55. package/src/runner/limits.ts +2 -2
  56. package/src/runner/runner.ts +15 -14
  57. package/src/runner/service.ts +52 -19
  58. package/src/runner/step-worker.ts +9 -0
  59. package/src/testing/answer.ts +69 -0
  60. package/src/testing/clock-manual.ts +152 -0
  61. package/src/testing/config.ts +16 -0
  62. package/src/testing/fs.ts +172 -0
  63. package/src/testing/home.ts +43 -0
  64. package/src/testing/index.ts +19 -0
  65. package/src/testing/types.ts +2 -0
  66. package/src/testing/world.ts +9 -2
  67. package/src/trigger/kernel.ts +13 -46
  68. package/src/trigger/rules.ts +22 -12
  69. package/src/trigger/types.ts +2 -6
  70. package/src/util.ts +99 -0
  71. package/src/views/event-line.ts +22 -0
  72. package/src/views/history.ts +36 -19
  73. package/src/views/live-logs.ts +313 -0
  74. package/src/views/pending.ts +23 -5
  75. package/src/views/presentation.ts +629 -81
  76. package/src/views/running.ts +5 -5
  77. package/src/views/settings.ts +205 -66
  78. package/src/views/types.ts +3 -2
  79. package/src/views/uploads.ts +15 -7
  80. package/triggers.schema.json +4 -0
@@ -4,12 +4,12 @@
4
4
  * log's existing refusal still protects it.
5
5
  */
6
6
 
7
- import { randomUUID } from "node:crypto";
8
- import { chmod, mkdir, readFile, rename, unlink, writeFile } from "node:fs/promises";
7
+ import { chmod, mkdir, readFile, unlink } from "node:fs/promises";
9
8
  import { join } from "node:path";
9
+ import { writeJsonAtomic } from "../platform/index.ts";
10
10
  import { Secret } from "../log/secret.ts";
11
11
  import type { SecretStore } from "./types.ts";
12
- import { isRecord } from "../util.ts";
12
+ import { isMissingFile, isRecord } from "../util.ts";
13
13
 
14
14
  const NAME = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
15
15
 
@@ -70,18 +70,21 @@ export class FileSecretStore implements SecretStore {
70
70
  return Object.keys(await this.#read()).sort();
71
71
  }
72
72
 
73
+ async values(): Promise<readonly string[]> {
74
+ const values = await this.#read();
75
+ return Object.keys(values)
76
+ .sort()
77
+ .map((name) => values[name])
78
+ .filter((value): value is string => value !== undefined);
79
+ }
80
+
73
81
  async #read(): Promise<Record<string, string>> {
74
82
  const path = secretsPathFor(this.#home, this.#plugin);
75
83
  let text: string;
76
84
  try {
77
85
  text = await readFile(path, "utf8");
78
86
  } catch (error) {
79
- if (
80
- typeof error === "object" &&
81
- error !== null &&
82
- "code" in error &&
83
- error.code === "ENOENT"
84
- ) {
87
+ if (isMissingFile(error)) {
85
88
  return {};
86
89
  }
87
90
  throw new Error(`secrets for plugin "${this.#plugin}": cannot read: ${String(error)}`);
@@ -111,28 +114,15 @@ export class FileSecretStore implements SecretStore {
111
114
  try {
112
115
  await unlink(path);
113
116
  } catch (error) {
114
- if (
115
- !(
116
- typeof error === "object" &&
117
- error !== null &&
118
- "code" in error &&
119
- error.code === "ENOENT"
120
- )
121
- ) {
117
+ if (!isMissingFile(error)) {
122
118
  throw error;
123
119
  }
124
120
  }
125
121
  return;
126
122
  }
127
- const temporary = `${path}.${randomUUID()}.tmp`;
128
123
  try {
129
- await writeFile(temporary, `${JSON.stringify(values, null, 2)}\n`, {
130
- mode: 0o600,
131
- });
132
- await chmod(temporary, 0o600);
133
- await rename(temporary, path);
124
+ await writeJsonAtomic(path, values, { space: 2, mode: 0o600 });
134
125
  } catch (error) {
135
- await unlink(temporary).catch(() => undefined);
136
126
  throw new Error(
137
127
  `secrets for plugin "${this.#plugin}": cannot write: ${String(error)}`,
138
128
  );
@@ -26,6 +26,58 @@ function compare(left: Version, right: Version): number {
26
26
  return 0;
27
27
  }
28
28
 
29
+ /** A full version as text, with the prerelease parts a range does not read. */
30
+ export interface VersionText {
31
+ readonly major: number;
32
+ readonly minor: number;
33
+ readonly patch: number;
34
+ readonly prerelease: readonly string[];
35
+ }
36
+
37
+ /**
38
+ * Reads a full `x.y.z` version, with an optional leading `v`, a prerelease and
39
+ * a build suffix. Undefined for anything else, including a two-part version.
40
+ */
41
+ export function readVersionText(value: string): VersionText | undefined {
42
+ const match = /^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+.*)?$/.exec(value.trim());
43
+ if (match === null) return undefined;
44
+ return {
45
+ major: Number(match[1]),
46
+ minor: Number(match[2]),
47
+ patch: Number(match[3]),
48
+ prerelease: match[4] === undefined ? [] : match[4].split("."),
49
+ };
50
+ }
51
+
52
+ /**
53
+ * Negative, zero or positive as version `a` is below, equal to or above `b`.
54
+ * A prerelease is below its release, and its parts are compared as semver does.
55
+ */
56
+ export function compareVersionText(left: VersionText, right: VersionText): number {
57
+ const core = compare(left, right);
58
+ if (core !== 0) return core;
59
+ if (left.prerelease.length === 0 && right.prerelease.length === 0) return 0;
60
+ if (left.prerelease.length === 0) return 1;
61
+ if (right.prerelease.length === 0) return -1;
62
+ for (let at = 0; at < Math.max(left.prerelease.length, right.prerelease.length); at += 1) {
63
+ const l = left.prerelease[at];
64
+ const r = right.prerelease[at];
65
+ if (l === undefined) return -1;
66
+ if (r === undefined) return 1;
67
+ const ln = /^\d+$/.test(l);
68
+ const rn = /^\d+$/.test(r);
69
+ if (ln && rn) {
70
+ const diff = Number(l) - Number(r);
71
+ if (diff !== 0) return diff;
72
+ } else if (ln !== rn) {
73
+ return ln ? -1 : 1;
74
+ } else if (l !== r) {
75
+ return l < r ? -1 : 1;
76
+ }
77
+ }
78
+ return 0;
79
+ }
80
+
29
81
  function atLeast(value: Version, base: Version): boolean {
30
82
  return compare(value, base) >= 0;
31
83
  }
@@ -7,6 +7,7 @@ import type { JsonValue } from "../log/types.ts";
7
7
  import { ActionArgsError, validateSchemaValue } from "./action-schema.ts";
8
8
  import type { ActionArgSchema, ActionArgsSchema } from "./types.ts";
9
9
  import { isRecord } from "../util.ts";
10
+ import { deepFreeze } from "./freeze.ts";
10
11
 
11
12
  function cloneJson(value: unknown): unknown {
12
13
  if (Array.isArray(value)) return value.map((item) => cloneJson(item));
@@ -36,15 +37,6 @@ function applyDefaults(schema: ActionArgSchema, value: unknown): unknown {
36
37
  return result;
37
38
  }
38
39
 
39
- function deepFreeze<T>(value: T): T {
40
- if (typeof value !== "object" || value === null) return value;
41
- Object.freeze(value);
42
- for (const item of Object.values(value as Record<string, unknown>)) {
43
- deepFreeze(item);
44
- }
45
- return value;
46
- }
47
-
48
40
  /**
49
41
  * Validates one plugin's settings section and fills the defaults its schema
50
42
  * declares. The message names the plugin and the field, never a secret.
@@ -2,7 +2,7 @@
2
2
 
3
3
  import { Database } from "bun:sqlite";
4
4
  import { existsSync, mkdirSync } from "node:fs";
5
- import { enableWal, setBusyTimeout, writeImmediate } from "../platform/index.ts";
5
+ import { enableWal, isBusy, setBusyTimeout, writeImmediate } from "../platform/index.ts";
6
6
  import { dirname, join } from "node:path";
7
7
  import {
8
8
  followsChanges,
@@ -32,6 +32,8 @@ import type {
32
32
  } from "./types.ts";
33
33
  import { isRecord, requireName } from "../util.ts";
34
34
  import { repeatEvery } from "../util.ts";
35
+ import { hasTable, readSchemaVersion } from "../platform/sqlite-schema.ts";
36
+ import { deepFreeze } from "./freeze.ts";
35
37
  import {
36
38
  applyObjectChange,
37
39
  diffObject,
@@ -128,10 +130,6 @@ const SCHEMA_FILE = "plugins.sqlite";
128
130
  */
129
131
  export const PLUGIN_STORE_SCHEMA_VERSION = 2;
130
132
 
131
- interface VersionRow {
132
- readonly version: number;
133
- }
134
-
135
133
  interface ObjectKeyRow {
136
134
  readonly type: string;
137
135
  readonly id: string;
@@ -143,27 +141,6 @@ interface HistoryRow {
143
141
  readonly data: string;
144
142
  }
145
143
 
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
144
  /**
168
145
  * Rewrites every old full-snapshot put fact as a change, one transaction per
169
146
  * object, keeping its sequence, cause and time. It runs on every open: an
@@ -187,25 +164,32 @@ function migrateObjectFacts(database: Database): void {
187
164
  ORDER BY sequence`,
188
165
  );
189
166
  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;
167
+ try {
168
+ for (const object of objects) {
169
+ writeImmediate(database, () => {
170
+ const rows = history.all(object.type, object.id) as HistoryRow[];
171
+ let previous: ObjectData | undefined;
172
+ for (const row of rows) {
173
+ const data = parseData(row.data);
174
+ if (row.type === OBJECT_CHANGE_FACT) {
175
+ const change = objectChangeOf(data);
176
+ if (change !== undefined) previous = applyObjectChange(previous ?? {}, change);
177
+ } else if (row.type === object.type) {
178
+ const change: ObjectChange =
179
+ previous === undefined
180
+ ? { changed: data, removed: [] }
181
+ : (diffObject(previous, data) ?? { changed: {}, removed: [] });
182
+ update.run(OBJECT_CHANGE_FACT, JSON.stringify(change), row.sequence);
183
+ previous = data;
184
+ }
206
185
  }
207
- }
208
- });
186
+ });
187
+ }
188
+ } finally {
189
+ // Bun keeps a closed database's file handles until every statement made
190
+ // from it is finalized. These two would keep the store open past its close.
191
+ history.finalize();
192
+ update.finalize();
209
193
  }
210
194
  }
211
195
 
@@ -255,14 +239,6 @@ function ensureSchema(database: Database, file: string): void {
255
239
  }
256
240
  }
257
241
 
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
242
  function parseData(text: string): ObjectData {
267
243
  try {
268
244
  const value: unknown = JSON.parse(text);
@@ -523,6 +499,15 @@ export class SqlitePluginStore implements PluginStore {
523
499
  };
524
500
  }
525
501
 
502
+ latestFactSequence(object: ObjectRef): number {
503
+ const row = this.db
504
+ .query(
505
+ "SELECT COALESCE(MAX(sequence), 0) AS sequence FROM facts WHERE object_type = ? AND object_id = ?",
506
+ )
507
+ .get(object.type, object.id) as { sequence: number } | null;
508
+ return row?.sequence ?? 0;
509
+ }
510
+
526
511
  subscribe(listener: (object: ObjectRef) => void): () => void;
527
512
  subscribe(
528
513
  object: ObjectRef,
@@ -626,8 +611,7 @@ export class SqlitePluginStore implements PluginStore {
626
611
 
627
612
  /** Closes the database; tests open many homes. */
628
613
  close(): void {
629
- this.stopPoll?.();
630
- this.stopPoll = undefined;
614
+ this.stopPolling();
631
615
  this.db.close();
632
616
  }
633
617
 
@@ -644,10 +628,40 @@ export class SqlitePluginStore implements PluginStore {
644
628
 
645
629
  private releasePolling(): void {
646
630
  if (this.factListeners.size > 0 || this.listeners.size > 0) return;
631
+ this.stopPolling();
632
+ }
633
+
634
+ private stopPolling(): void {
647
635
  this.stopPoll?.();
648
636
  this.stopPoll = undefined;
649
637
  }
650
638
 
639
+ /**
640
+ * Whether the store's root or database file is gone. Before a query only
641
+ * these count: a live store can briefly lack its `-wal`, and it still
642
+ * delivers the facts checkpointed into the database.
643
+ */
644
+ private missing(): boolean {
645
+ if (!existsSync(this.root)) return true;
646
+ const file = this.location.file;
647
+ return file !== undefined && !existsSync(file);
648
+ }
649
+
650
+ /**
651
+ * Whether a store that met an I/O error went away. A WAL store keeps `-wal`
652
+ * and `-shm` beside the database while it is open, and a teardown can remove
653
+ * them before the database itself. Missing journals after a failed query mean
654
+ * the store went away, not that a live store met a disk error.
655
+ */
656
+ private gone(): boolean {
657
+ if (this.missing()) return true;
658
+ const file = this.location.file;
659
+ return (
660
+ file !== undefined &&
661
+ (!existsSync(`${file}-wal`) || !existsSync(`${file}-shm`))
662
+ );
663
+ }
664
+
651
665
  private maxSequence(): number {
652
666
  const row = this.db
653
667
  .query("SELECT COALESCE(MAX(sequence), 0) AS sequence FROM facts")
@@ -656,16 +670,32 @@ export class SqlitePluginStore implements PluginStore {
656
670
  }
657
671
 
658
672
  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[];
673
+ // A removed store has nothing left to deliver; stop the timer that outlived it.
674
+ if (this.missing()) {
675
+ this.stopPolling();
676
+ return;
677
+ }
678
+ let rows: FactRow[];
679
+ try {
680
+ rows = this.db
681
+ .query(
682
+ `SELECT sequence, type, object_type, object_id, cause, at, data
683
+ FROM facts
684
+ WHERE sequence > ?
685
+ ORDER BY sequence`,
686
+ )
687
+ .all(this.polledSequence) as FactRow[];
688
+ } catch (error) {
689
+ // A busy store is a poll that missed this turn, not a serve that ends:
690
+ // the next turn reads what was committed then.
691
+ if (isBusy(error)) return;
692
+ // The store can be removed between the check above and this query.
693
+ if (this.gone()) {
694
+ this.stopPolling();
695
+ return;
696
+ }
697
+ throw error;
698
+ }
669
699
  for (const row of rows) {
670
700
  const fact = this.factOf(row);
671
701
  this.polledSequence = Math.max(this.polledSequence, fact.sequence);
@@ -197,6 +197,11 @@ export class MemoryPluginStore implements PluginStore {
197
197
  };
198
198
  }
199
199
 
200
+ latestFactSequence(object: ObjectRef): number {
201
+ const all = this.byObject.get(this.key(object.type, object.id)) ?? [];
202
+ return all.at(-1)?.sequence ?? 0;
203
+ }
204
+
200
205
  subscribe(listener: (object: ObjectRef) => void): () => void;
201
206
  subscribe(
202
207
  object: ObjectRef,