@operad-io/cli 0.1.1 → 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.
@@ -0,0 +1,127 @@
1
+ /**
2
+ * What keeps `operad serve` up when a store is busy, and what it says when it
3
+ * ends on an error anyway. A busy store is another process holding the write
4
+ * lock past the busy timeout: it is never a reason to end the serve.
5
+ */
6
+
7
+ import { messageOf } from "@operad-io/engine";
8
+ import { appendFileSync } from "node:fs";
9
+ import { join } from "node:path";
10
+ import { isBusy } from "@operad-io/engine/platform";
11
+
12
+ /** Where the serve is, so an error says which operation it came from. */
13
+ let stage = "starting";
14
+
15
+ export function serveStage(next?: string): string {
16
+ if (next !== undefined) stage = next;
17
+ return stage;
18
+ }
19
+
20
+ /**
21
+ * A frame is operad's own when its path is in a source checkout (`/packages/`)
22
+ * or in an installed operad package (`node_modules/@operad-io/`); other
23
+ * dependencies and the runtime are not.
24
+ */
25
+ function isOwnFrame(frame: string): boolean {
26
+ // Windows paths use backslashes; the checks below read forward slashes.
27
+ const line = frame.replaceAll("\\", "/");
28
+ if (line.includes("node:") || line.includes("[native code]")) return false;
29
+ if (line.includes("/node_modules/@operad-io/")) return true;
30
+ if (line.includes("node_modules")) return false;
31
+ return /\/(packages|plugins)\/|operad/.test(line);
32
+ }
33
+
34
+ /** The first frames of the stack that are operad's own code (not node_modules, not the runtime). */
35
+ export function ownFrames(error: unknown, limit = 5): string[] {
36
+ if (!(error instanceof Error) || error.stack === undefined) return [];
37
+ return error.stack
38
+ .split("\n")
39
+ .map((line) => line.trim())
40
+ .filter((line) => line.startsWith("at ") && isOwnFrame(line))
41
+ .slice(0, limit);
42
+ }
43
+
44
+ /**
45
+ * Writes the operation and the stack's first frames to `<home>/serve.log`, and
46
+ * returns the one short line for the user.
47
+ */
48
+ export function recordServeFailure(
49
+ home: string,
50
+ operation: string,
51
+ error: unknown,
52
+ now: () => number = () => Date.now(),
53
+ ): string {
54
+ const lines = [
55
+ `${new Date(now()).toISOString()} serve: ${operation}: ${messageOf(error)}`,
56
+ ...ownFrames(error).map((frame) => ` ${frame}`),
57
+ ];
58
+ const cause = error instanceof Error ? error.cause : undefined;
59
+ if (cause !== undefined) {
60
+ lines.push(` caused by: ${messageOf(cause)}`, ...ownFrames(cause).map((frame) => ` ${frame}`));
61
+ }
62
+ try {
63
+ appendFileSync(join(home, "serve.log"), `${lines.join("\n")}\n`);
64
+ } catch {
65
+ // The user line below still says where it came from.
66
+ }
67
+ return `serve: ${operation}: ${messageOf(error)}`;
68
+ }
69
+
70
+ export interface BusyRetry {
71
+ readonly log: (message: string) => void;
72
+ /** Waits before the next try; the default waits one second. */
73
+ readonly wait?: (() => Promise<void>) | undefined;
74
+ }
75
+
76
+ /**
77
+ * Runs `operation`; a busy store is tried again, without end, because a serve
78
+ * that is not running is worse than one that waits for the store.
79
+ */
80
+ export async function retryWhileBusy<T>(
81
+ operation: string,
82
+ run: () => Promise<T>,
83
+ options: BusyRetry,
84
+ ): Promise<T> {
85
+ const wait =
86
+ options.wait ?? (() => new Promise<void>((resolve) => setTimeout(resolve, 1_000)));
87
+ for (;;) {
88
+ try {
89
+ return await run();
90
+ } catch (error) {
91
+ if (!isBusy(error)) throw error;
92
+ options.log(`serve: ${operation}: database is locked; trying again`);
93
+ }
94
+ await wait();
95
+ }
96
+ }
97
+
98
+ /**
99
+ * While the serve runs, a busy store that surfaces outside any pass (a
100
+ * plugin's own timer, a source, a client request) is logged and the serve goes
101
+ * on. Any other error ends the process as it did before, after it is recorded.
102
+ * Returns what removes the handlers.
103
+ */
104
+ export function guardBackgroundBusy(options: {
105
+ readonly home: string;
106
+ readonly log: (message: string) => void;
107
+ readonly exit?: (code: number) => void;
108
+ readonly target?: NodeJS.Process;
109
+ }): () => void {
110
+ const target = options.target ?? process;
111
+ const exit = options.exit ?? ((code: number) => process.exit(code));
112
+ const handle = (error: unknown): void => {
113
+ const operation = `${serveStage()} (background)`;
114
+ if (isBusy(error)) {
115
+ options.log(recordServeFailure(options.home, operation, error) + "; going on");
116
+ return;
117
+ }
118
+ options.log(recordServeFailure(options.home, operation, error));
119
+ exit(1);
120
+ };
121
+ target.on("unhandledRejection", handle);
122
+ target.on("uncaughtException", handle);
123
+ return () => {
124
+ target.off("unhandledRejection", handle);
125
+ target.off("uncaughtException", handle);
126
+ };
127
+ }
package/src/serve-stop.ts CHANGED
@@ -9,6 +9,7 @@
9
9
  */
10
10
 
11
11
  import { StateError, pidAlive, readLockPid, serveLockPath } from "@operad-io/engine";
12
+ import { stopAllKeptWorkers } from "@operad-io/engine/platform";
12
13
  import { existsSync } from "node:fs";
13
14
 
14
15
  export const DEFAULT_STOP_TIMEOUT_SECS = 30;
@@ -55,6 +56,9 @@ export function parseStopTimeout(value: string): number {
55
56
  }
56
57
 
57
58
  export async function serveStop(options: ServeStopOptions): Promise<void> {
59
+ // Kept workers are not children of serve: end them here too, even when no
60
+ // serve is left to do it.
61
+ await stopAllKeptWorkers({ home: options.home });
58
62
  const path = serveLockPath(options.home);
59
63
  const isAlive = options.isAlive ?? pidAlive;
60
64
  const pid = readLockPid(path);
package/src/markdown.ts DELETED
@@ -1,11 +0,0 @@
1
- /**
2
- * The CLI's terminal Markdown renderer now lives in the engine, so the TUI
3
- * draws the same lines. This module keeps the CLI's import path and names.
4
- */
5
-
6
- export {
7
- renderMarkdown,
8
- renderMarkdownLines,
9
- type MarkdownLine,
10
- type RenderOptions,
11
- } from "@operad-io/engine";