@operad-io/cli 0.1.1 → 0.3.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.
- package/README.md +4 -2
- package/package.json +16 -12
- package/src/code-reload.ts +81 -13
- package/src/defaults.ts +35 -19
- package/src/doctor.ts +211 -0
- package/src/http-bind.ts +2 -1
- package/src/main.ts +1176 -248
- package/src/serve-guard.ts +127 -0
- package/src/serve-stop.ts +71 -4
- package/src/markdown.ts +0 -11
|
@@ -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,12 +9,50 @@
|
|
|
9
9
|
*/
|
|
10
10
|
|
|
11
11
|
import { StateError, pidAlive, readLockPid, serveLockPath } from "@operad-io/engine";
|
|
12
|
-
import {
|
|
12
|
+
import { stopAllKeptWorkers, writeJsonAtomicSync } from "@operad-io/engine/platform";
|
|
13
|
+
import { existsSync, readFileSync, rmSync } from "node:fs";
|
|
14
|
+
import { join } from "node:path";
|
|
13
15
|
|
|
14
16
|
export const DEFAULT_STOP_TIMEOUT_SECS = 30;
|
|
15
17
|
const COMMAND_ASKS = 20;
|
|
16
18
|
const COMMAND_ASK_WAIT_MS = 50;
|
|
17
19
|
|
|
20
|
+
function supervisorPath(home: string): string {
|
|
21
|
+
return join(home, "serve-supervisor.json");
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* A serve that runs under a supervisor names it in the home: the supervisor
|
|
26
|
+
* outlives each serve it starts and starts the next one after a reload, so
|
|
27
|
+
* `serve stop` must reach it, not only the serve that holds the lock.
|
|
28
|
+
*/
|
|
29
|
+
export function recordSupervisor(home: string, pid: number = process.ppid): void {
|
|
30
|
+
writeJsonAtomicSync(supervisorPath(home), { pid });
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function readSupervisor(home: string): number | undefined {
|
|
34
|
+
try {
|
|
35
|
+
const raw: unknown = JSON.parse(readFileSync(supervisorPath(home), "utf8"));
|
|
36
|
+
const pid =
|
|
37
|
+
typeof raw === "object" && raw !== null ? (raw as { pid?: unknown }).pid : undefined;
|
|
38
|
+
return typeof pid === "number" ? pid : undefined;
|
|
39
|
+
} catch {
|
|
40
|
+
return undefined;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** The parent of a process, or undefined when `ps` cannot say. */
|
|
45
|
+
export function parentOf(pid: number): number | undefined {
|
|
46
|
+
const result = Bun.spawnSync({
|
|
47
|
+
cmd: ["ps", "-p", String(pid), "-o", "ppid="],
|
|
48
|
+
stdout: "pipe",
|
|
49
|
+
stderr: "ignore",
|
|
50
|
+
});
|
|
51
|
+
if (result.exitCode !== 0) return undefined;
|
|
52
|
+
const value = Number(result.stdout.toString().trim());
|
|
53
|
+
return Number.isInteger(value) && value > 0 ? value : undefined;
|
|
54
|
+
}
|
|
55
|
+
|
|
18
56
|
export interface ServeStopOptions {
|
|
19
57
|
readonly home: string;
|
|
20
58
|
readonly timeoutSecs: number;
|
|
@@ -23,6 +61,7 @@ export interface ServeStopOptions {
|
|
|
23
61
|
readonly isAlive?: ((pid: number) => boolean) | undefined;
|
|
24
62
|
readonly commandOf?: ((pid: number) => string | undefined) | undefined;
|
|
25
63
|
readonly signal?: ((pid: number) => void) | undefined;
|
|
64
|
+
readonly parentOf?: ((pid: number) => number | undefined) | undefined;
|
|
26
65
|
readonly sleep?: ((ms: number) => Promise<void>) | undefined;
|
|
27
66
|
readonly clock?: (() => number) | undefined;
|
|
28
67
|
}
|
|
@@ -55,10 +94,32 @@ export function parseStopTimeout(value: string): number {
|
|
|
55
94
|
}
|
|
56
95
|
|
|
57
96
|
export async function serveStop(options: ServeStopOptions): Promise<void> {
|
|
97
|
+
// Kept workers are not children of serve: end them here too, even when no
|
|
98
|
+
// serve is left to do it.
|
|
99
|
+
await stopAllKeptWorkers({ home: options.home });
|
|
58
100
|
const path = serveLockPath(options.home);
|
|
59
101
|
const isAlive = options.isAlive ?? pidAlive;
|
|
60
|
-
const
|
|
61
|
-
|
|
102
|
+
const lockPid = readLockPid(path);
|
|
103
|
+
const holder = lockPid !== undefined && isAlive(lockPid) ? lockPid : undefined;
|
|
104
|
+
// The supervisor of the serve, when there is one that is really its parent.
|
|
105
|
+
// Between two serves of a reload nothing holds the lock, and the supervisor
|
|
106
|
+
// is the only process that will start the next one.
|
|
107
|
+
let supervisor = readSupervisor(options.home);
|
|
108
|
+
if (supervisor !== undefined && !isAlive(supervisor)) supervisor = undefined;
|
|
109
|
+
// A record whose pid was reused by another process names no supervisor.
|
|
110
|
+
if (supervisor !== undefined) {
|
|
111
|
+
const supervisorCommand = (options.commandOf ?? processCommand)(supervisor);
|
|
112
|
+
if (supervisorCommand !== undefined && !isServeCommand(supervisorCommand)) {
|
|
113
|
+
rmSync(supervisorPath(options.home), { force: true });
|
|
114
|
+
supervisor = undefined;
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
if (supervisor !== undefined && holder !== undefined && holder !== supervisor) {
|
|
118
|
+
const parent = (options.parentOf ?? parentOf)(holder);
|
|
119
|
+
if (parent !== undefined && parent !== supervisor) supervisor = undefined;
|
|
120
|
+
}
|
|
121
|
+
const pid = supervisor ?? holder;
|
|
122
|
+
if (pid === undefined) {
|
|
62
123
|
options.write(`no operad serve runs for ${options.home}\n`);
|
|
63
124
|
return;
|
|
64
125
|
}
|
|
@@ -95,7 +156,13 @@ export async function serveStop(options: ServeStopOptions): Promise<void> {
|
|
|
95
156
|
const clock = options.clock ?? (() => Date.now());
|
|
96
157
|
const deadline = clock() + options.timeoutSecs * 1_000;
|
|
97
158
|
for (;;) {
|
|
98
|
-
|
|
159
|
+
// The supervisor is gone, and so is every serve it started: the lock
|
|
160
|
+
// names no live process, or the file is gone.
|
|
161
|
+
const current = readLockPid(path);
|
|
162
|
+
const served = current !== undefined && isAlive(current) && existsSync(path);
|
|
163
|
+
const supervised = supervisor !== undefined && isAlive(supervisor);
|
|
164
|
+
if (supervisor === undefined ? !isAlive(pid) || !existsSync(path) : !supervised && !served) {
|
|
165
|
+
if (supervisor !== undefined) rmSync(supervisorPath(options.home), { force: true });
|
|
99
166
|
options.write("stopped\n");
|
|
100
167
|
return;
|
|
101
168
|
}
|
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";
|