@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,486 @@
1
+ /**
2
+ * The code a process loaded, as a fingerprint, and a watch on it.
3
+ *
4
+ * A process keeps running the code it loaded. `serve` and every run's process
5
+ * record a fingerprint of the files they loaded (the engine and cli sources, each
6
+ * loaded plugin's package and the workspace packages it depends on, their
7
+ * schemas) and compare it later: `serve` watches and restarts itself, a run's
8
+ * process compares between steps and hands over.
9
+ */
10
+
11
+ import { readFileSync, readdirSync, realpathSync, statSync } from "node:fs";
12
+ import { homedir } from "node:os";
13
+ import { dirname, join, resolve, sep } from "node:path";
14
+ import { fileURLToPath } from "node:url";
15
+ import { systemClock, watchDirectory } from "../platform/index.ts";
16
+ import type { Clock } from "../platform/index.ts";
17
+
18
+ /** A file or directory whose files count as code, under the name a log line uses. */
19
+ export interface CodeRoot {
20
+ readonly label: string;
21
+ readonly path: string;
22
+ }
23
+
24
+ /** The files of the code roots and a hash of each file's content. */
25
+ export interface CodeFingerprint {
26
+ readonly hashes: ReadonlyMap<string, string>;
27
+ readonly labels: ReadonlyMap<string, string>;
28
+ /** The directories that hold the files, for watching. */
29
+ readonly directories: ReadonlySet<string>;
30
+ }
31
+
32
+ /** The files that differ between two fingerprints, by root label. */
33
+ export interface CodeChange {
34
+ readonly labels: readonly string[];
35
+ readonly files: readonly string[];
36
+ }
37
+
38
+ const SKIPPED_DIRECTORIES: ReadonlySet<string> = new Set([
39
+ "node_modules",
40
+ ".git",
41
+ "test",
42
+ "tests",
43
+ "fixtures",
44
+ ]);
45
+
46
+ /** Docs and tests are not code a process loads. */
47
+ function isCodeFile(name: string): boolean {
48
+ return !name.endsWith(".md") && !name.endsWith(".test.ts");
49
+ }
50
+
51
+ /**
52
+ * Remembers a file's hash under its size and timestamps. A hash read while
53
+ * the stamps were still fresh stays untrusted: Linux rounds a newly written
54
+ * file's timestamps to the millisecond, so a same-size rewrite can keep the
55
+ * key, and a later poll must read the file again before it believes the hash.
56
+ */
57
+ export interface HashCache {
58
+ readonly entries: Map<
59
+ string,
60
+ { readonly key: string; readonly hash: string; readonly trusted: boolean }
61
+ >;
62
+ readonly now: () => number;
63
+ }
64
+
65
+ export function newHashCache(now: () => number = Date.now): HashCache {
66
+ return { entries: new Map(), now };
67
+ }
68
+
69
+ /** How close a stamp may be to now before a cached hash stops being trusted. */
70
+ const RACY_MS = 2_000;
71
+
72
+ function hashFile(path: string, cache: HashCache): string | undefined {
73
+ try {
74
+ const info = statSync(path);
75
+ const key = `${info.size}:${info.mtimeMs}:${info.ctimeMs}`;
76
+ const cached = cache.entries.get(path);
77
+ if (cached?.key === key && cached.trusted) return cached.hash;
78
+ const hash = Bun.hash(readFileSync(path)).toString(16);
79
+ const trusted = cache.now() - Math.max(info.mtimeMs, info.ctimeMs) > RACY_MS;
80
+ cache.entries.set(path, { key, hash, trusted });
81
+ return hash;
82
+ } catch {
83
+ return undefined;
84
+ }
85
+ }
86
+
87
+ /** Reads the files of every root. A missing file or directory counts as empty. */
88
+ export function fingerprintCode(
89
+ roots: readonly CodeRoot[],
90
+ cache: HashCache = newHashCache(),
91
+ ): CodeFingerprint {
92
+ const hashes = new Map<string, string>();
93
+ const labels = new Map<string, string>();
94
+ const directories = new Set<string>();
95
+
96
+ const visit = (label: string, path: string, top: boolean): void => {
97
+ let info;
98
+ try {
99
+ info = statSync(path);
100
+ } catch {
101
+ directories.add(dirname(path));
102
+ return;
103
+ }
104
+ if (info.isDirectory()) {
105
+ directories.add(path);
106
+ let names: string[];
107
+ try {
108
+ names = readdirSync(path).sort();
109
+ } catch {
110
+ return;
111
+ }
112
+ for (const name of names) {
113
+ const child = join(path, name);
114
+ let childInfo;
115
+ try {
116
+ childInfo = statSync(child);
117
+ } catch {
118
+ continue;
119
+ }
120
+ if (childInfo.isDirectory()) {
121
+ if (!SKIPPED_DIRECTORIES.has(name) && !name.startsWith(".")) {
122
+ visit(label, child, false);
123
+ }
124
+ } else if (isCodeFile(name)) {
125
+ visit(label, child, false);
126
+ }
127
+ }
128
+ return;
129
+ }
130
+ if (!top && !isCodeFile(path)) return;
131
+ directories.add(dirname(path));
132
+ const hash = hashFile(path, cache);
133
+ if (hash === undefined || hashes.has(path)) return;
134
+ hashes.set(path, hash);
135
+ labels.set(path, label);
136
+ };
137
+
138
+ for (const root of roots) visit(root.label, root.path, true);
139
+ return { hashes, labels, directories };
140
+ }
141
+
142
+ /** What differs between two fingerprints; undefined when nothing does. */
143
+ export function diffFingerprints(
144
+ before: CodeFingerprint,
145
+ after: CodeFingerprint,
146
+ ): CodeChange | undefined {
147
+ const files: string[] = [];
148
+ const labels = new Set<string>();
149
+ for (const [file, hash] of after.hashes) {
150
+ if (before.hashes.get(file) !== hash) {
151
+ files.push(file);
152
+ labels.add(after.labels.get(file) ?? file);
153
+ }
154
+ }
155
+ for (const file of before.hashes.keys()) {
156
+ if (!after.hashes.has(file)) {
157
+ files.push(file);
158
+ labels.add(before.labels.get(file) ?? file);
159
+ }
160
+ }
161
+ if (files.length === 0) return undefined;
162
+ return { labels: [...labels].sort(), files: files.sort() };
163
+ }
164
+
165
+ /** One line for a log or for history: what changed, by name. */
166
+ export function describeChange(change: CodeChange): string {
167
+ const shown = change.files.slice(0, 3).map((file) => file.split("/").slice(-2).join("/"));
168
+ const more = change.files.length > shown.length ? ` and ${change.files.length - shown.length} more` : "";
169
+ return `${change.labels.join(", ")}: ${shown.join(", ")}${more}`;
170
+ }
171
+
172
+ function packageDirectoryOf(file: string): string | undefined {
173
+ let directory = dirname(file);
174
+ for (;;) {
175
+ try {
176
+ statSync(join(directory, "package.json"));
177
+ return directory;
178
+ } catch {
179
+ const parent = dirname(directory);
180
+ if (parent === directory) return undefined;
181
+ directory = parent;
182
+ }
183
+ }
184
+ }
185
+
186
+ /** The directory of the engine package, which every process loads. */
187
+ export const ENGINE_CODE_ROOT: CodeRoot = {
188
+ label: "engine",
189
+ path: fileURLToPath(new URL("../../", import.meta.url)),
190
+ };
191
+
192
+ /** The file a plugin specifier names, resolved the way the loader does. */
193
+ export function pluginFile(specifier: string, home: string): string | undefined {
194
+ try {
195
+ if (specifier.startsWith("file:")) return realpathSync(fileURLToPath(specifier));
196
+ if (specifier.startsWith("~")) {
197
+ return realpathSync(join(homedir(), specifier.slice(1)));
198
+ }
199
+ if (specifier.startsWith(".") || specifier.startsWith("/")) {
200
+ return realpathSync(resolve(home, specifier));
201
+ }
202
+ // The loader imports a bare module name from inside the engine package,
203
+ // not from the operad home: resolve it from there.
204
+ return realpathSync(Bun.resolveSync(specifier, ENGINE_CODE_ROOT.path));
205
+ } catch {
206
+ return undefined;
207
+ }
208
+ }
209
+
210
+ /** The workspace packages a package directory lists as dependencies. */
211
+ function workspaceDependencies(directory: string): string[] {
212
+ const found: string[] = [];
213
+ try {
214
+ const raw: unknown = JSON.parse(readFileSync(join(directory, "package.json"), "utf8"));
215
+ const dependencies =
216
+ typeof raw === "object" && raw !== null && "dependencies" in raw
217
+ ? (raw as { dependencies?: unknown }).dependencies
218
+ : undefined;
219
+ if (typeof dependencies !== "object" || dependencies === null) return found;
220
+ for (const name of Object.keys(dependencies)) {
221
+ if (!name.startsWith("@operad-io/")) continue;
222
+ try {
223
+ found.push(dirname(realpathSync(Bun.resolveSync(`${name}/package.json`, directory))));
224
+ } catch {
225
+ // A dependency that does not resolve adds nothing.
226
+ }
227
+ }
228
+ } catch {
229
+ // A package without a readable manifest adds nothing.
230
+ }
231
+ return found;
232
+ }
233
+
234
+ /**
235
+ * The code roots of a process: the engine, the extra roots the caller names (the
236
+ * cli), and for each plugin module its package (or the single file when it has
237
+ * none) with the workspace packages that package depends on.
238
+ */
239
+ export function codeRoots(options: {
240
+ readonly home: string;
241
+ readonly extra?: readonly CodeRoot[] | undefined;
242
+ readonly plugins: readonly { readonly name: string; readonly module: string }[];
243
+ }): CodeRoot[] {
244
+ const roots: CodeRoot[] = [ENGINE_CODE_ROOT, ...(options.extra ?? [])];
245
+ const seen = new Set(roots.map((root) => root.path));
246
+ const add = (label: string, path: string): void => {
247
+ if (seen.has(path)) return;
248
+ seen.add(path);
249
+ roots.push({ label, path });
250
+ };
251
+ for (const plugin of options.plugins) {
252
+ const file = pluginFile(plugin.module, options.home);
253
+ if (file === undefined) {
254
+ add(`plugin ${plugin.name}`, resolve(options.home, plugin.module));
255
+ continue;
256
+ }
257
+ const found = packageDirectoryOf(file);
258
+ // A package that holds the operad home is a project, not a plugin's code:
259
+ // watching it would restart on every edit of the project.
260
+ const directory =
261
+ found !== undefined && !(options.home + sep).startsWith(found + sep) ? found : undefined;
262
+ if (directory === undefined) {
263
+ add(`plugin ${plugin.name}`, file);
264
+ continue;
265
+ }
266
+ add(`plugin ${plugin.name}`, directory);
267
+ const queue = workspaceDependencies(directory);
268
+ while (queue.length > 0) {
269
+ const dependency = queue.pop();
270
+ if (dependency === undefined || seen.has(dependency)) continue;
271
+ add(`plugin ${plugin.name}`, dependency);
272
+ queue.push(...workspaceDependencies(dependency));
273
+ }
274
+ }
275
+ return roots;
276
+ }
277
+
278
+ /**
279
+ * Resolves once the files of `roots` differ from `since`. Directory events wake
280
+ * it; a timer reads the files again in case no event came.
281
+ */
282
+ export function waitForCodeChange(options: {
283
+ readonly roots: readonly CodeRoot[];
284
+ readonly since: CodeFingerprint;
285
+ readonly cache?: HashCache | undefined;
286
+ readonly pollMs: number;
287
+ readonly clock?: Clock | undefined;
288
+ readonly watch?:
289
+ | ((directory: string, onChange: (filename: string | null) => void) => () => void)
290
+ | undefined;
291
+ }): Promise<CodeFingerprint> {
292
+ const clock = options.clock ?? systemClock;
293
+ const watch = options.watch ?? watchDirectory;
294
+ const cache = options.cache ?? newHashCache();
295
+ return new Promise((resolve) => {
296
+ const closers: (() => void)[] = [];
297
+ let timer: unknown;
298
+ let done = false;
299
+ const look = (): void => {
300
+ if (done) return;
301
+ const current = fingerprintCode(options.roots, cache);
302
+ if (diffFingerprints(options.since, current) === undefined) return;
303
+ done = true;
304
+ for (const close of closers) close();
305
+ clock.clearTimeout(timer);
306
+ resolve(current);
307
+ };
308
+ for (const directory of fingerprintCode(options.roots, cache).directories) {
309
+ closers.push(watch(directory, look));
310
+ }
311
+ const tick = (): void => {
312
+ look();
313
+ if (!done) timer = clock.setTimeout(tick, options.pollMs);
314
+ };
315
+ timer = clock.setTimeout(tick, options.pollMs);
316
+ look();
317
+ });
318
+ }
319
+
320
+ /** What `CodeWatch` calls when the code on disk differs from what it loaded. */
321
+ export type CodeChangeHandler = (change: CodeChange) => Promise<"reload" | "keep">;
322
+
323
+ export interface CodeWatchOptions {
324
+ readonly roots: readonly CodeRoot[];
325
+ /**
326
+ * Files that are not code but whose change is worth another try after a
327
+ * change was kept: a settings file that failed to read may be fixed now.
328
+ */
329
+ readonly alsoWatch?: readonly CodeRoot[] | undefined;
330
+ /** What the process loaded; the watch takes its own when omitted. */
331
+ readonly baseline?: CodeFingerprint | undefined;
332
+ /**
333
+ * The files as they were when a change was already tried and kept before this
334
+ * watch started (a serve that fell back to its old code). They count as
335
+ * declined: the handler is offered only what differs from them.
336
+ */
337
+ readonly declined?: CodeFingerprint | undefined;
338
+ /** How long files stay unchanged before the watch acts. */
339
+ readonly quietMs: number;
340
+ /** The timers of the quiet period and the fallback check; tests inject theirs. */
341
+ readonly clock?: Clock | undefined;
342
+ /** How often the files are read again when no event came. */
343
+ readonly pollMs?: number | undefined;
344
+ readonly watch?:
345
+ | ((directory: string, onChange: (filename: string | null) => void) => () => void)
346
+ | undefined;
347
+ /**
348
+ * Called with what changed once files are quiet. "reload" ends the watch;
349
+ * "keep" leaves the process on its old code until the files change again.
350
+ */
351
+ readonly onChange: CodeChangeHandler;
352
+ /**
353
+ * Called when the process starts or stops running older code than the files
354
+ * on disk: true once a change is on disk and the process has not taken it up.
355
+ */
356
+ readonly onOlder?: ((older: boolean) => void) | undefined;
357
+ }
358
+
359
+ /** Watches code files and reports a change once, after a quiet period. */
360
+ export class CodeWatch {
361
+ private readonly options: CodeWatchOptions;
362
+ private readonly clock: Clock;
363
+ private readonly cache = newHashCache();
364
+ private baseline: CodeFingerprint | undefined;
365
+ private readonly watchers = new Map<string, () => void>();
366
+ private quiet: unknown;
367
+ private poll: unknown;
368
+ private busy = false;
369
+ private closed = false;
370
+ private older = false;
371
+ /** The change the handler last kept, so the same files are not offered twice. */
372
+ private declined:
373
+ | { readonly code: CodeFingerprint; readonly settings: CodeFingerprint }
374
+ | undefined;
375
+
376
+ constructor(options: CodeWatchOptions) {
377
+ this.options = options;
378
+ this.clock = options.clock ?? systemClock;
379
+ this.baseline = options.baseline;
380
+ }
381
+
382
+ /** Takes the baseline when none was given and starts watching. */
383
+ start(): void {
384
+ const current = fingerprintCode(this.options.roots, this.cache);
385
+ this.baseline ??= current;
386
+ const settings = this.settings();
387
+ if (this.options.declined !== undefined) {
388
+ this.declined = { code: this.options.declined, settings };
389
+ }
390
+ // Code that already differs from the baseline at the start is older now.
391
+ this.setOlder(diffFingerprints(this.baseline, current) !== undefined);
392
+ this.sync(current, settings);
393
+ const pollMs = this.options.pollMs ?? 5_000;
394
+ const tick = (): void => {
395
+ if (this.closed) return;
396
+ this.schedule();
397
+ this.poll = this.clock.setTimeout(tick, pollMs);
398
+ };
399
+ this.poll = this.clock.setTimeout(tick, pollMs);
400
+ }
401
+
402
+ stop(): void {
403
+ this.closed = true;
404
+ if (this.quiet !== undefined) this.clock.clearTimeout(this.quiet);
405
+ if (this.poll !== undefined) this.clock.clearTimeout(this.poll);
406
+ for (const close of this.watchers.values()) close();
407
+ this.watchers.clear();
408
+ }
409
+
410
+ private setOlder(older: boolean): void {
411
+ if (this.older === older) return;
412
+ this.older = older;
413
+ this.options.onOlder?.(older);
414
+ }
415
+
416
+ private settings(): CodeFingerprint {
417
+ return fingerprintCode(this.options.alsoWatch ?? [], this.cache);
418
+ }
419
+
420
+ private sync(code: CodeFingerprint, settings: CodeFingerprint): void {
421
+ const watch = this.options.watch ?? watchDirectory;
422
+ const directories = new Set([...code.directories, ...settings.directories]);
423
+ const fingerprint = { directories };
424
+ for (const [directory, close] of [...this.watchers]) {
425
+ if (!fingerprint.directories.has(directory)) {
426
+ close();
427
+ this.watchers.delete(directory);
428
+ }
429
+ }
430
+ for (const directory of fingerprint.directories) {
431
+ if (this.watchers.has(directory)) continue;
432
+ this.watchers.set(
433
+ directory,
434
+ watch(directory, () => {
435
+ this.schedule();
436
+ }),
437
+ );
438
+ }
439
+ }
440
+
441
+ /** Every event restarts the quiet period; a stop in progress ignores it. */
442
+ private schedule(): void {
443
+ if (this.closed || this.busy) return;
444
+ if (this.quiet !== undefined) this.clock.clearTimeout(this.quiet);
445
+ this.quiet = this.clock.setTimeout(() => {
446
+ this.quiet = undefined;
447
+ this.check().catch(() => {
448
+ // A handler that fails keeps the old code; the next change tries again.
449
+ this.busy = false;
450
+ });
451
+ }, this.options.quietMs);
452
+ }
453
+
454
+ private async check(): Promise<void> {
455
+ if (this.closed || this.busy || this.baseline === undefined) return;
456
+ const current = fingerprintCode(this.options.roots, this.cache);
457
+ const settings = this.settings();
458
+ this.sync(current, settings);
459
+ const change = diffFingerprints(this.baseline, current);
460
+ if (change === undefined) {
461
+ this.setOlder(false);
462
+ return;
463
+ }
464
+ if (
465
+ this.declined !== undefined &&
466
+ diffFingerprints(this.declined.code, current) === undefined &&
467
+ diffFingerprints(this.declined.settings, settings) === undefined
468
+ ) {
469
+ this.setOlder(true);
470
+ return;
471
+ }
472
+ this.busy = true;
473
+ let answer: "reload" | "keep" = "keep";
474
+ try {
475
+ answer = await this.options.onChange(change);
476
+ } finally {
477
+ if (answer === "reload") {
478
+ this.stop();
479
+ } else {
480
+ this.declined = { code: current, settings };
481
+ this.busy = false;
482
+ this.setOlder(true);
483
+ }
484
+ }
485
+ }
486
+ }
@@ -0,0 +1,3 @@
1
+ export * from "./serve.ts";
2
+ export * from "./code-watch.ts";
3
+ export * from "./older-code.ts";
@@ -0,0 +1,58 @@
1
+ /**
2
+ * The notice that serve runs older code than the files on disk.
3
+ *
4
+ * The code watch knows when the files differ from what serve loaded. When it
5
+ * keeps the old code (the new files do not load, or serve could not hand over),
6
+ * serve leaves a small file in the home naming its process; the pending view
7
+ * shows one item while that process still holds the serve lock. A restarted
8
+ * serve is another process, so the item leaves with it.
9
+ */
10
+
11
+ import { readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
12
+ import { join } from "node:path";
13
+ import { pidAlive, readLockPid, serveLockPath } from "../runner/lock.ts";
14
+
15
+ function noticePath(home: string): string {
16
+ return join(home, "serve-older.json");
17
+ }
18
+
19
+ /** What the pending view shows; the id is the same item each time. */
20
+ export const OLDER_CODE_ITEM_ID = "serve-older";
21
+
22
+ export const OLDER_CODE_PROMPT =
23
+ "serve runs older code than the files on disk: restart serve to load them (operad serve stop, then operad serve)";
24
+
25
+ /** Records, for the serve of this process, whether its code is older than the disk. */
26
+ export function olderCodeNotice(home: string, pid: number = process.pid): {
27
+ readonly report: (older: boolean) => void;
28
+ readonly clear: () => void;
29
+ } {
30
+ const clear = (): void => rmSync(noticePath(home), { force: true });
31
+ return {
32
+ report: (older) => {
33
+ if (!older) {
34
+ clear();
35
+ return;
36
+ }
37
+ const temporary = `${noticePath(home)}.${pid}.tmp`;
38
+ writeFileSync(temporary, `${JSON.stringify({ pid })}\n`);
39
+ renameSync(temporary, noticePath(home));
40
+ },
41
+ clear,
42
+ };
43
+ }
44
+
45
+ /** True when the serve that holds the home's lock reported older code. */
46
+ export function servesOlderCode(home: string): boolean {
47
+ try {
48
+ const raw: unknown = JSON.parse(readFileSync(noticePath(home), "utf8"));
49
+ const pid =
50
+ typeof raw === "object" && raw !== null && "pid" in raw
51
+ ? (raw as { pid?: unknown }).pid
52
+ : undefined;
53
+ if (typeof pid !== "number") return false;
54
+ return readLockPid(serveLockPath(home)) === pid && pidAlive(pid);
55
+ } catch {
56
+ return false;
57
+ }
58
+ }