@antelopejs/tooling-configs 0.2.18 → 0.2.19
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 +11 -6
- package/dist/bin/capture.mjs +1 -1
- package/dist/bin/checks.mjs +22 -4
- package/dist/bin/garden.mjs +228 -27
- package/dist/bin/lease.d.mts +1 -0
- package/dist/bin/lease.mjs +1053 -0
- package/dist/bin/sync.mjs +36 -8
- package/dist/{ci-workflow-ChW4He0r.mjs → ci-workflow-DVkpwauQ.mjs} +12 -0
- package/package.json +2 -1
|
@@ -0,0 +1,1053 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { c as object, f as parseJson, i as isObject, l as optNum, p as str, s as num, t as child } from "../json-CG2L7YFl.mjs";
|
|
3
|
+
import { n as runCliAsync } from "../cli-4Tv71vYk.mjs";
|
|
4
|
+
import { accessSync, closeSync, constants, mkdirSync, openSync, readFileSync, readSync, readdirSync, readlinkSync, realpathSync, renameSync, rmSync, statSync, utimesSync, writeFileSync } from "node:fs";
|
|
5
|
+
import { delimiter, isAbsolute, join } from "node:path";
|
|
6
|
+
import { execFileSync, spawn } from "node:child_process";
|
|
7
|
+
import { createHash } from "node:crypto";
|
|
8
|
+
import { homedir } from "node:os";
|
|
9
|
+
import { parseArgs } from "node:util";
|
|
10
|
+
import { setTimeout } from "node:timers/promises";
|
|
11
|
+
import { connect, createServer } from "node:net";
|
|
12
|
+
//#region src/lease/env.ts
|
|
13
|
+
function isServerRole(value) {
|
|
14
|
+
return value === "api" || value === "web";
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* The environment `run` hands its command: `parent` without `PORT`, plus the lease's variables.
|
|
18
|
+
* `PORT` comes back only for `as`, because one shell-wide `PORT` makes the backend and the
|
|
19
|
+
* dashboard bind the same port. `DMS_MONGO_URL` in `parent` replaces the lease's own mongod.
|
|
20
|
+
* `DMS_API_BASE_URL` stays unset. A backend whose config hard-codes its port falls back to a free
|
|
21
|
+
* one and records it in `.antelope/dev.json`, and `ajs dms dev` reads that file only without it.
|
|
22
|
+
*/
|
|
23
|
+
function leaseEnv(lease, parent, as) {
|
|
24
|
+
const { record, dir } = lease;
|
|
25
|
+
const { ports } = record;
|
|
26
|
+
const { PORT: _inherited, ...env } = parent;
|
|
27
|
+
Object.assign(env, {
|
|
28
|
+
ANTELOPEJS_LEASE: record.id,
|
|
29
|
+
ANTELOPEJS_LEASE_DIR: dir,
|
|
30
|
+
DMS_BACK_PORT: String(ports.api),
|
|
31
|
+
DMS_FRONT_PORT: String(ports.web),
|
|
32
|
+
DMS_INSPECT_PORT: String(ports.inspect),
|
|
33
|
+
DMS_SMTP_PORT: String(ports.smtp),
|
|
34
|
+
DMS_CLIENT_BASE_URL: `http://localhost:${ports.web}`,
|
|
35
|
+
MONGO_URL: parent.DMS_MONGO_URL || `mongodb://127.0.0.1:${ports.mongo}`,
|
|
36
|
+
MONGO_DATABASE: `dms_${record.id}`,
|
|
37
|
+
DMS_BACK_LOG: join(dir, "logs", "back.log"),
|
|
38
|
+
DMS_FRONT_LOG: join(dir, "logs", "front.log"),
|
|
39
|
+
TMPDIR: join(dir, "tmp")
|
|
40
|
+
});
|
|
41
|
+
if (as !== void 0) env.PORT = String(ports[as]);
|
|
42
|
+
return env;
|
|
43
|
+
}
|
|
44
|
+
//#endregion
|
|
45
|
+
//#region src/lease/exec.ts
|
|
46
|
+
const SHELL = "/bin/sh";
|
|
47
|
+
const DEFAULT_PATH = "/bin:/usr/bin";
|
|
48
|
+
const HEADER_BYTES = 256;
|
|
49
|
+
const SHEBANG = /^#![ \t]*([^ \t\n]*)/u;
|
|
50
|
+
const IGNORED_BY_NODE = ["SIGPIPE", "SIGXFSZ"];
|
|
51
|
+
function refusal(code, reason) {
|
|
52
|
+
return {
|
|
53
|
+
kind: "refuse",
|
|
54
|
+
code,
|
|
55
|
+
reason
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
const NOT_FOUND = refusal(127, "not found");
|
|
59
|
+
/**
|
|
60
|
+
* Why execve refuses `path` before it reads the file; `undefined` when it may start it. A path this
|
|
61
|
+
* user cannot stat counts as missing, as a shell's `PATH` search counts it.
|
|
62
|
+
*/
|
|
63
|
+
function problem(path) {
|
|
64
|
+
try {
|
|
65
|
+
if (statSync(path).isDirectory()) return refusal(126, "is a directory");
|
|
66
|
+
} catch {
|
|
67
|
+
return NOT_FOUND;
|
|
68
|
+
}
|
|
69
|
+
try {
|
|
70
|
+
accessSync(path, constants.X_OK);
|
|
71
|
+
return;
|
|
72
|
+
} catch {
|
|
73
|
+
return refusal(126, "is not executable");
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
/** The first bytes of `path` as text; `undefined` when this user may run it but not read it. */
|
|
77
|
+
function header(path) {
|
|
78
|
+
let fd;
|
|
79
|
+
try {
|
|
80
|
+
fd = openSync(path, "r");
|
|
81
|
+
} catch {
|
|
82
|
+
return;
|
|
83
|
+
}
|
|
84
|
+
try {
|
|
85
|
+
const buffer = Buffer.alloc(HEADER_BYTES);
|
|
86
|
+
return buffer.toString("utf8", 0, readSync(fd, buffer));
|
|
87
|
+
} catch {
|
|
88
|
+
return;
|
|
89
|
+
} finally {
|
|
90
|
+
closeSync(fd);
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* What execve does with `path`; `undefined` when no file is there. A `#!` line whose interpreter
|
|
95
|
+
* is missing, such as `/bin/sh\r` after a CRLF, refuses with 127. A text file without `#!` starts
|
|
96
|
+
* under `/bin/sh`, as execvp starts it. Anything else starts directly.
|
|
97
|
+
*/
|
|
98
|
+
function inspect(path) {
|
|
99
|
+
const own = problem(path);
|
|
100
|
+
if (own === NOT_FOUND) return void 0;
|
|
101
|
+
if (own !== void 0) return refusal(own.code, `${path} ${own.reason}`);
|
|
102
|
+
const head = header(path);
|
|
103
|
+
const interpreter = head === void 0 ? void 0 : SHEBANG.exec(head)?.[1];
|
|
104
|
+
if (interpreter !== void 0) {
|
|
105
|
+
const broken = problem(interpreter);
|
|
106
|
+
if (broken !== void 0) return refusal(broken.code, `interpreter ${JSON.stringify(interpreter)} ${broken.reason}`);
|
|
107
|
+
}
|
|
108
|
+
const text = head !== void 0 && !head.includes("\0");
|
|
109
|
+
return {
|
|
110
|
+
kind: "start",
|
|
111
|
+
file: path,
|
|
112
|
+
viaShell: interpreter === void 0 && text
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
116
|
+
* The file `name` names, found the way execvp finds it: as a path when it holds a `/`, else in
|
|
117
|
+
* each directory of the `PATH` in `env` in turn, an empty entry naming the working directory.
|
|
118
|
+
* A match execve refuses is skipped for a later one, and reported when no later one starts.
|
|
119
|
+
*/
|
|
120
|
+
function locate(name, env) {
|
|
121
|
+
if (name.includes("/")) return inspect(name) ?? NOT_FOUND;
|
|
122
|
+
if (name === "") return NOT_FOUND;
|
|
123
|
+
let refused;
|
|
124
|
+
for (const directory of (env.PATH ?? DEFAULT_PATH).split(delimiter)) {
|
|
125
|
+
const verdict = inspect(join(directory || ".", name));
|
|
126
|
+
if (verdict?.kind === "start") return verdict;
|
|
127
|
+
refused ??= verdict;
|
|
128
|
+
}
|
|
129
|
+
return refused ?? NOT_FOUND;
|
|
130
|
+
}
|
|
131
|
+
/**
|
|
132
|
+
* Replaces this process with `command` under exactly `env`. The command keeps this pid and is the
|
|
133
|
+
* only process, so a signal from a terminal, a process-group kill or `kill <pid>` reaches it once,
|
|
134
|
+
* and its exit status, 128 plus the signal included, is the caller's. Node ignores SIGPIPE and
|
|
135
|
+
* SIGXFSZ, and an ignored signal stays ignored across `execve`, so both get a handler first, which
|
|
136
|
+
* `execve` resets to the default. Returns only when the command cannot start: after printing why,
|
|
137
|
+
* with 127 when it is not found and 126 when it is found but cannot run, as a shell exits.
|
|
138
|
+
*/
|
|
139
|
+
function launch(command, env) {
|
|
140
|
+
if (process.execve === void 0) throw new Error("antelopejs-lease: run needs process.execve, from Node 22.15 on Linux or macOS");
|
|
141
|
+
const [name = "", ...args] = command;
|
|
142
|
+
const verdict = locate(name, env);
|
|
143
|
+
if (verdict.kind === "refuse") {
|
|
144
|
+
process.stderr.write(`antelopejs-lease: cannot run ${name}: ${verdict.reason}\n`);
|
|
145
|
+
return verdict.code;
|
|
146
|
+
}
|
|
147
|
+
for (const signal of IGNORED_BY_NODE) process.on(signal, () => void 0);
|
|
148
|
+
return verdict.viaShell ? process.execve(SHELL, [
|
|
149
|
+
SHELL,
|
|
150
|
+
verdict.file,
|
|
151
|
+
...args
|
|
152
|
+
], env) : process.execve(verdict.file, [name, ...args], env);
|
|
153
|
+
}
|
|
154
|
+
//#endregion
|
|
155
|
+
//#region src/lease/protocol.ts
|
|
156
|
+
/**
|
|
157
|
+
* The port every antelopejs-lease version listens on, on 127.0.0.1, while it holds the registry lock.
|
|
158
|
+
* Each repository pins its own tooling-configs version, so this port, {@link leaseHome} and the v1
|
|
159
|
+
* record are a protocol between versions: they may be extended, never changed.
|
|
160
|
+
*/
|
|
161
|
+
const LOCK_PORT = 2e4;
|
|
162
|
+
const RECORD_VERSION = 1;
|
|
163
|
+
/** The offset of each role's port in its block of ten. Offsets 6 to 9 stay spare for later roles. */
|
|
164
|
+
const PORT_ROLES = {
|
|
165
|
+
api: 0,
|
|
166
|
+
web: 1,
|
|
167
|
+
mongo: 2,
|
|
168
|
+
smtp: 3,
|
|
169
|
+
inspect: 4,
|
|
170
|
+
hmr: 5
|
|
171
|
+
};
|
|
172
|
+
function isRole(value) {
|
|
173
|
+
return Object.hasOwn(PORT_ROLES, value);
|
|
174
|
+
}
|
|
175
|
+
/**
|
|
176
|
+
* `ANTELOPEJS_LEASE_HOME`, else `~/.antelopejs/leases`: one registry for every repository of the
|
|
177
|
+
* user. A relative `ANTELOPEJS_LEASE_HOME` throws, since each working directory would resolve it to
|
|
178
|
+
* another registry.
|
|
179
|
+
*/
|
|
180
|
+
function leaseHome(env) {
|
|
181
|
+
const home = env.ANTELOPEJS_LEASE_HOME;
|
|
182
|
+
if (!home) return join(homedir(), ".antelopejs", "leases");
|
|
183
|
+
if (!isAbsolute(home)) throw new Error(`antelopejs-lease: ANTELOPEJS_LEASE_HOME must be an absolute path, not ${home}`);
|
|
184
|
+
return home;
|
|
185
|
+
}
|
|
186
|
+
function isLeaseId(value) {
|
|
187
|
+
return /^[0-9a-f]{10}$/u.test(value);
|
|
188
|
+
}
|
|
189
|
+
/** The lease id of the worktree whose real path is `worktree`. */
|
|
190
|
+
function leaseId(worktree) {
|
|
191
|
+
const id = createHash("sha256").update(worktree).digest("hex").slice(0, 10);
|
|
192
|
+
if (!isLeaseId(id)) throw new Error(`unexpected digest ${id}`);
|
|
193
|
+
return id;
|
|
194
|
+
}
|
|
195
|
+
/** Builds a value for every role, so a new role is a compile error until each table names it. */
|
|
196
|
+
function eachRole(value) {
|
|
197
|
+
return {
|
|
198
|
+
api: value("api"),
|
|
199
|
+
web: value("web"),
|
|
200
|
+
mongo: value("mongo"),
|
|
201
|
+
smtp: value("smtp"),
|
|
202
|
+
inspect: value("inspect"),
|
|
203
|
+
hmr: value("hmr")
|
|
204
|
+
};
|
|
205
|
+
}
|
|
206
|
+
function isMongoMode(value) {
|
|
207
|
+
return value === "owned" || value === "external";
|
|
208
|
+
}
|
|
209
|
+
function decodeRecord(value) {
|
|
210
|
+
const source = object(value, "lease.json");
|
|
211
|
+
if (num(source, "version") !== RECORD_VERSION) return void 0;
|
|
212
|
+
const id = str(source, "id");
|
|
213
|
+
const mongo = str(source, "mongo");
|
|
214
|
+
if (!isLeaseId(id) || !isMongoMode(mongo)) return void 0;
|
|
215
|
+
const ports = child(source, "ports");
|
|
216
|
+
return {
|
|
217
|
+
version: RECORD_VERSION,
|
|
218
|
+
id,
|
|
219
|
+
worktree: str(source, "worktree"),
|
|
220
|
+
gitInode: num(source, "gitInode"),
|
|
221
|
+
gitBirth: num(source, "gitBirth"),
|
|
222
|
+
ports: eachRole((role) => num(ports, role)),
|
|
223
|
+
createdAt: str(source, "createdAt"),
|
|
224
|
+
mongo
|
|
225
|
+
};
|
|
226
|
+
}
|
|
227
|
+
function reservedPorts(value) {
|
|
228
|
+
if (!isObject(value) || !Object.hasOwn(value, "ports")) return [];
|
|
229
|
+
const ports = value.ports;
|
|
230
|
+
if (!isObject(ports)) return [];
|
|
231
|
+
return Object.keys(ports).map((key) => optNum(ports, key)).filter((port) => port !== void 0);
|
|
232
|
+
}
|
|
233
|
+
function tryJson(text) {
|
|
234
|
+
try {
|
|
235
|
+
return parseJson(text);
|
|
236
|
+
} catch {
|
|
237
|
+
return;
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
function tryRecord(value) {
|
|
241
|
+
try {
|
|
242
|
+
return decodeRecord(value);
|
|
243
|
+
} catch {
|
|
244
|
+
return;
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
/** Reads a `lease.json` leniently: unknown fields are ignored, anything unreadable is `foreign`. */
|
|
248
|
+
function parseRecord(text) {
|
|
249
|
+
const value = tryJson(text);
|
|
250
|
+
if (value === void 0) return {
|
|
251
|
+
kind: "foreign",
|
|
252
|
+
reserved: []
|
|
253
|
+
};
|
|
254
|
+
const record = tryRecord(value);
|
|
255
|
+
if (record !== void 0) return {
|
|
256
|
+
kind: "current",
|
|
257
|
+
record
|
|
258
|
+
};
|
|
259
|
+
return {
|
|
260
|
+
kind: "foreign",
|
|
261
|
+
reserved: reservedPorts(value)
|
|
262
|
+
};
|
|
263
|
+
}
|
|
264
|
+
//#endregion
|
|
265
|
+
//#region src/lease/ports.ts
|
|
266
|
+
const BAND_START = 20010;
|
|
267
|
+
const BLOCK_SIZE = 10;
|
|
268
|
+
const BLOCK_COUNT = 9990 / BLOCK_SIZE;
|
|
269
|
+
const DENIED_PORTS = [
|
|
270
|
+
24678,
|
|
271
|
+
27017,
|
|
272
|
+
27018,
|
|
273
|
+
27019
|
|
274
|
+
];
|
|
275
|
+
const CONNECT_TIMEOUT_MS = 1e3;
|
|
276
|
+
const LISTEN_STATE = "0A";
|
|
277
|
+
/**
|
|
278
|
+
* The block bases a lease tries, in order: from a block picked by a hash of the id and `uid`
|
|
279
|
+
* together, forward and around the band. Each user keeps a registry of its own, so mixing in the
|
|
280
|
+
* uid usually starts two users' worktrees at one path on different blocks. The band [20010, 30000)
|
|
281
|
+
* sits below the kernel's ephemeral range (32768 and up on Linux, 49152 and up on macOS), so no
|
|
282
|
+
* `bind(:0)` caller races for these ports. Blocks holding the Vite HMR default (24678) or a system
|
|
283
|
+
* mongod (27017 to 27019) are skipped.
|
|
284
|
+
*/
|
|
285
|
+
function candidateBases(id, uid = process.getuid?.() ?? 0) {
|
|
286
|
+
const first = createHash("sha256").update(`${uid}:${id}`).digest().readUInt32BE(0) % BLOCK_COUNT;
|
|
287
|
+
return Array.from({ length: BLOCK_COUNT }, (_, step) => BAND_START + (first + step) % BLOCK_COUNT * BLOCK_SIZE).filter((base) => !DENIED_PORTS.some((port) => port >= base && port < base + BLOCK_SIZE));
|
|
288
|
+
}
|
|
289
|
+
function blockPorts(base) {
|
|
290
|
+
return Array.from({ length: BLOCK_SIZE }, (_, offset) => base + offset);
|
|
291
|
+
}
|
|
292
|
+
async function everyBindable(ports, bindable) {
|
|
293
|
+
for (const port of ports) if (!await bindable(port)) return false;
|
|
294
|
+
return true;
|
|
295
|
+
}
|
|
296
|
+
/**
|
|
297
|
+
* The first candidate block none of whose ten ports is in `taken` and all of whose ports bind.
|
|
298
|
+
* Throws when the band has no such block.
|
|
299
|
+
*/
|
|
300
|
+
async function chooseBlock(id, taken, bindable) {
|
|
301
|
+
for (const base of candidateBases(id)) {
|
|
302
|
+
const ports = blockPorts(base);
|
|
303
|
+
if (ports.some((port) => taken.has(port))) continue;
|
|
304
|
+
if (await everyBindable(ports, bindable)) return eachRole((role) => base + PORT_ROLES[role]);
|
|
305
|
+
}
|
|
306
|
+
throw new Error(`antelopejs-lease: no free port block in ${BAND_START}-29999; run antelopejs-lease gc, then retry`);
|
|
307
|
+
}
|
|
308
|
+
/** Listens on `host:port`, Node's dual-stack default without `host`. `undefined` when the address is in use. */
|
|
309
|
+
function claimPort(port, host) {
|
|
310
|
+
return new Promise((resolve, reject) => {
|
|
311
|
+
const server = createServer();
|
|
312
|
+
server.once("error", (error) => {
|
|
313
|
+
if (error.code === "EADDRINUSE") resolve(void 0);
|
|
314
|
+
else reject(error);
|
|
315
|
+
});
|
|
316
|
+
server.listen({
|
|
317
|
+
port,
|
|
318
|
+
host
|
|
319
|
+
}, () => resolve(server));
|
|
320
|
+
});
|
|
321
|
+
}
|
|
322
|
+
function closeServer(server) {
|
|
323
|
+
return new Promise((resolve) => server.close(() => resolve()));
|
|
324
|
+
}
|
|
325
|
+
async function bindsOn(port, host) {
|
|
326
|
+
try {
|
|
327
|
+
const server = await claimPort(port, host);
|
|
328
|
+
if (server === void 0) return false;
|
|
329
|
+
await closeServer(server);
|
|
330
|
+
return true;
|
|
331
|
+
} catch {
|
|
332
|
+
return false;
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
/**
|
|
336
|
+
* True when nothing holds `port`. The dual-stack wildcard bind fails on Linux for a listener on any
|
|
337
|
+
* local address; the 127.0.0.1 bind covers systems that let a wildcard sit beside a specific address.
|
|
338
|
+
*/
|
|
339
|
+
async function bindable(port) {
|
|
340
|
+
return await bindsOn(port, "127.0.0.1") && bindsOn(port);
|
|
341
|
+
}
|
|
342
|
+
function acceptsOn(port, host) {
|
|
343
|
+
return new Promise((resolve) => {
|
|
344
|
+
const socket = connect({
|
|
345
|
+
port,
|
|
346
|
+
host,
|
|
347
|
+
timeout: CONNECT_TIMEOUT_MS
|
|
348
|
+
});
|
|
349
|
+
const settle = (answer) => {
|
|
350
|
+
socket.destroy();
|
|
351
|
+
resolve(answer);
|
|
352
|
+
};
|
|
353
|
+
socket.once("connect", () => settle(true));
|
|
354
|
+
socket.once("timeout", () => settle(false));
|
|
355
|
+
socket.once("error", () => settle(false));
|
|
356
|
+
});
|
|
357
|
+
}
|
|
358
|
+
/** True when a server accepts connections on `port` on the IPv4 or the IPv6 loopback. */
|
|
359
|
+
async function accepting(port) {
|
|
360
|
+
return await acceptsOn(port, "127.0.0.1") || acceptsOn(port, "::1");
|
|
361
|
+
}
|
|
362
|
+
function listenInodes(table, port) {
|
|
363
|
+
let text;
|
|
364
|
+
try {
|
|
365
|
+
text = readFileSync(table, "utf8");
|
|
366
|
+
} catch {
|
|
367
|
+
return [];
|
|
368
|
+
}
|
|
369
|
+
return text.split("\n").slice(1).map((line) => line.trim().split(/\s+/u)).filter((columns) => columns[3] === LISTEN_STATE && Number.parseInt(columns[1]?.split(":")[1] ?? "", 16) === port).map((columns) => `socket:[${columns[9]}]`);
|
|
370
|
+
}
|
|
371
|
+
function holdsSocket(pid, sockets) {
|
|
372
|
+
let fds;
|
|
373
|
+
try {
|
|
374
|
+
fds = readdirSync(`/proc/${pid}/fd`);
|
|
375
|
+
} catch {
|
|
376
|
+
return false;
|
|
377
|
+
}
|
|
378
|
+
return fds.some((fd) => {
|
|
379
|
+
try {
|
|
380
|
+
return sockets.has(readlinkSync(`/proc/${pid}/fd/${fd}`));
|
|
381
|
+
} catch {
|
|
382
|
+
return false;
|
|
383
|
+
}
|
|
384
|
+
});
|
|
385
|
+
}
|
|
386
|
+
function listenSockets(port) {
|
|
387
|
+
return /* @__PURE__ */ new Set([...listenInodes("/proc/net/tcp", port), ...listenInodes("/proc/net/tcp6", port)]);
|
|
388
|
+
}
|
|
389
|
+
function linuxListenerPids(port) {
|
|
390
|
+
const sockets = listenSockets(port);
|
|
391
|
+
if (sockets.size === 0) return [];
|
|
392
|
+
return readdirSync("/proc").filter((name) => /^\d+$/u.test(name) && holdsSocket(name, sockets)).map(Number);
|
|
393
|
+
}
|
|
394
|
+
function lsofListenerPids(port) {
|
|
395
|
+
try {
|
|
396
|
+
return execFileSync("lsof", [
|
|
397
|
+
"-nP",
|
|
398
|
+
"-t",
|
|
399
|
+
`-iTCP:${port}`,
|
|
400
|
+
"-sTCP:LISTEN"
|
|
401
|
+
], {
|
|
402
|
+
encoding: "utf8",
|
|
403
|
+
stdio: [
|
|
404
|
+
"ignore",
|
|
405
|
+
"pipe",
|
|
406
|
+
"ignore"
|
|
407
|
+
]
|
|
408
|
+
}).split("\n").filter((line) => /^\d+$/u.test(line)).map(Number);
|
|
409
|
+
} catch {
|
|
410
|
+
return [];
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
/** The pids listening on `port` that this user may inspect; empty when none can be read. */
|
|
414
|
+
function listenerPids(port) {
|
|
415
|
+
if (process.platform === "linux") return linuxListenerPids(port);
|
|
416
|
+
if (process.platform === "darwin") return lsofListenerPids(port);
|
|
417
|
+
return [];
|
|
418
|
+
}
|
|
419
|
+
/**
|
|
420
|
+
* True when process `pid` listens on `port`. Where the platform gives no way to tell, true when
|
|
421
|
+
* anything accepts on `port`.
|
|
422
|
+
*/
|
|
423
|
+
async function listensOn(pid, port) {
|
|
424
|
+
if (process.platform === "linux") return holdsSocket(String(pid), listenSockets(port));
|
|
425
|
+
if (process.platform === "darwin") return lsofListenerPids(port).includes(pid);
|
|
426
|
+
return accepting(port);
|
|
427
|
+
}
|
|
428
|
+
//#endregion
|
|
429
|
+
//#region src/lease/mongo.ts
|
|
430
|
+
const READY_TIMEOUT_MS = 3e4;
|
|
431
|
+
const KILL_WAIT_MS = 2e3;
|
|
432
|
+
const POLL_MS = 50;
|
|
433
|
+
const CACHED_BINARY = /^mongod-.+-(\d+)\.(\d+)\.(\d+)$/u;
|
|
434
|
+
function executable(path) {
|
|
435
|
+
try {
|
|
436
|
+
accessSync(path, constants.X_OK);
|
|
437
|
+
return true;
|
|
438
|
+
} catch {
|
|
439
|
+
return false;
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
function versionOf(name) {
|
|
443
|
+
return (CACHED_BINARY.exec(name) ?? []).slice(1).map(Number);
|
|
444
|
+
}
|
|
445
|
+
function byNewestVersion(left, right) {
|
|
446
|
+
const a = versionOf(left);
|
|
447
|
+
const b = versionOf(right);
|
|
448
|
+
const index = a.findIndex((part, at) => part !== b[at]);
|
|
449
|
+
return index === -1 ? 0 : (b[index] ?? 0) - (a[index] ?? 0);
|
|
450
|
+
}
|
|
451
|
+
function newestCached(directory) {
|
|
452
|
+
let names;
|
|
453
|
+
try {
|
|
454
|
+
names = readdirSync(directory);
|
|
455
|
+
} catch {
|
|
456
|
+
return;
|
|
457
|
+
}
|
|
458
|
+
return names.filter((name) => CACHED_BINARY.test(name)).sort(byNewestVersion).map((name) => join(directory, name)).find(executable);
|
|
459
|
+
}
|
|
460
|
+
/**
|
|
461
|
+
* The mongod a lease runs: `MONGOMS_SYSTEM_BINARY`, else `mongod` on `PATH`, else the newest
|
|
462
|
+
* mongodb-memory-server download in `MONGOMS_DOWNLOAD_DIR` or `~/.cache/mongodb-binaries`.
|
|
463
|
+
*/
|
|
464
|
+
function findMongod(env) {
|
|
465
|
+
const system = env.MONGOMS_SYSTEM_BINARY;
|
|
466
|
+
if (system && executable(system)) return system;
|
|
467
|
+
return (env.PATH ?? "").split(delimiter).filter(Boolean).map((directory) => join(directory, "mongod")).find(executable) ?? newestCached(env.MONGOMS_DOWNLOAD_DIR || join(homedir(), ".cache", "mongodb-binaries"));
|
|
468
|
+
}
|
|
469
|
+
/** The command line of `pid`, empty once the process has exited, a zombie included. */
|
|
470
|
+
function commandLine(pid) {
|
|
471
|
+
try {
|
|
472
|
+
if (process.platform === "linux") return readFileSync(`/proc/${pid}/cmdline`, "utf8").replaceAll("\0", " ");
|
|
473
|
+
return execFileSync("ps", [
|
|
474
|
+
"-o",
|
|
475
|
+
"command=",
|
|
476
|
+
"-p",
|
|
477
|
+
String(pid)
|
|
478
|
+
], {
|
|
479
|
+
encoding: "utf8",
|
|
480
|
+
stdio: [
|
|
481
|
+
"ignore",
|
|
482
|
+
"pipe",
|
|
483
|
+
"ignore"
|
|
484
|
+
]
|
|
485
|
+
});
|
|
486
|
+
} catch {
|
|
487
|
+
return "";
|
|
488
|
+
}
|
|
489
|
+
}
|
|
490
|
+
/**
|
|
491
|
+
* The pid of the mongod serving `dbpath`, read from the `mongod.lock` mongod writes there. A pid is
|
|
492
|
+
* trusted only while its command line names `dbpath`, so a reused pid never counts.
|
|
493
|
+
*/
|
|
494
|
+
function mongodPid(dbpath) {
|
|
495
|
+
let text;
|
|
496
|
+
try {
|
|
497
|
+
text = readFileSync(join(dbpath, "mongod.lock"), "utf8").trim();
|
|
498
|
+
} catch {
|
|
499
|
+
return;
|
|
500
|
+
}
|
|
501
|
+
const pid = Number(text);
|
|
502
|
+
if (!Number.isInteger(pid) || pid <= 0) return void 0;
|
|
503
|
+
return serves(pid, dbpath) ? pid : void 0;
|
|
504
|
+
}
|
|
505
|
+
function serves(pid, dbpath) {
|
|
506
|
+
return commandLine(pid).includes(dbpath);
|
|
507
|
+
}
|
|
508
|
+
/** Waits for the process itself: mongod empties `mongod.lock` before it exits. */
|
|
509
|
+
async function untilGone(pid, dbpath, ms) {
|
|
510
|
+
const deadline = Date.now() + ms;
|
|
511
|
+
while (serves(pid, dbpath) && Date.now() < deadline) await setTimeout(POLL_MS);
|
|
512
|
+
return !serves(pid, dbpath);
|
|
513
|
+
}
|
|
514
|
+
function signal(pid, name) {
|
|
515
|
+
try {
|
|
516
|
+
process.kill(pid, name);
|
|
517
|
+
} catch {
|
|
518
|
+
return;
|
|
519
|
+
}
|
|
520
|
+
}
|
|
521
|
+
/**
|
|
522
|
+
* Stops the mongod serving `dbpath`, if any: SIGTERM and `graceMs` to shut down, then SIGKILL.
|
|
523
|
+
* With `graceMs` 0 it kills at once. Throws when the process outlives the kill.
|
|
524
|
+
*/
|
|
525
|
+
async function stopMongod(dbpath, graceMs) {
|
|
526
|
+
const pid = mongodPid(dbpath);
|
|
527
|
+
if (pid === void 0) return;
|
|
528
|
+
if (graceMs > 0) {
|
|
529
|
+
signal(pid, "SIGTERM");
|
|
530
|
+
if (await untilGone(pid, dbpath, graceMs)) return;
|
|
531
|
+
}
|
|
532
|
+
signal(pid, "SIGKILL");
|
|
533
|
+
if (await untilGone(pid, dbpath, KILL_WAIT_MS)) return;
|
|
534
|
+
throw new Error(`antelopejs-lease: mongod ${pid} was still running ${KILL_WAIT_MS / 1e3} s after SIGKILL`);
|
|
535
|
+
}
|
|
536
|
+
async function holder(port) {
|
|
537
|
+
const pids = listenerPids(port);
|
|
538
|
+
if (pids.length > 0) return `, held by pid ${pids.join(", ")}`;
|
|
539
|
+
return await accepting(port) ? ", held by another process" : "";
|
|
540
|
+
}
|
|
541
|
+
/** The command lines of the processes this user may read. */
|
|
542
|
+
function commandLines() {
|
|
543
|
+
if (process.platform === "linux") return readdirSync("/proc").filter((name) => /^\d+$/u.test(name)).map((name) => commandLine(Number(name)));
|
|
544
|
+
try {
|
|
545
|
+
return execFileSync("ps", ["-axo", "command="], {
|
|
546
|
+
encoding: "utf8",
|
|
547
|
+
stdio: [
|
|
548
|
+
"ignore",
|
|
549
|
+
"pipe",
|
|
550
|
+
"ignore"
|
|
551
|
+
]
|
|
552
|
+
}).split("\n");
|
|
553
|
+
} catch {
|
|
554
|
+
return [];
|
|
555
|
+
}
|
|
556
|
+
}
|
|
557
|
+
function starting(dbpath) {
|
|
558
|
+
const argument = `--dbpath ${dbpath} `;
|
|
559
|
+
return commandLines().some((line) => line.includes(argument));
|
|
560
|
+
}
|
|
561
|
+
/**
|
|
562
|
+
* Waits until the mongod this call started with `--fork` has exited and the lease's own mongod
|
|
563
|
+
* serves: the pid in `mongod.lock`, whose command line names the dbpath, listens on `port`. A
|
|
564
|
+
* foreign listener on `port` never counts. Gives up once no process runs mongod on the dbpath: a
|
|
565
|
+
* second mongod on the same dbpath can exit before the first has written its pid, so two runs at
|
|
566
|
+
* once wait for the first.
|
|
567
|
+
*/
|
|
568
|
+
async function ready(port, paths, exited) {
|
|
569
|
+
const deadline = Date.now() + READY_TIMEOUT_MS;
|
|
570
|
+
while (Date.now() < deadline) {
|
|
571
|
+
if (exited()) {
|
|
572
|
+
const pid = mongodPid(paths.dbpath);
|
|
573
|
+
if (pid !== void 0 && await listensOn(pid, port)) return;
|
|
574
|
+
if (pid === void 0 && !starting(paths.dbpath)) break;
|
|
575
|
+
}
|
|
576
|
+
await setTimeout(POLL_MS);
|
|
577
|
+
}
|
|
578
|
+
throw new Error(`antelopejs-lease: mongod did not answer on port ${port}${await holder(port)}; see ${paths.log}`);
|
|
579
|
+
}
|
|
580
|
+
/**
|
|
581
|
+
* Makes sure the lease's own mongod serves `paths.dbpath` on `port`, starting one when none does.
|
|
582
|
+
* With `--fork`, mongod daemonizes itself, and the process this call starts exits once the server
|
|
583
|
+
* accepts connections. The server is never a child of this process, nor of the command `run`
|
|
584
|
+
* becomes, which would keep it as a zombie after `down`. Two callers at once are safe: mongod locks its dbpath, so the second exits and both wait
|
|
585
|
+
* for the first.
|
|
586
|
+
*/
|
|
587
|
+
async function ensureMongod(port, paths, env) {
|
|
588
|
+
if (mongodPid(paths.dbpath) !== void 0) return ready(port, paths, () => true);
|
|
589
|
+
const binary = findMongod(env);
|
|
590
|
+
if (binary === void 0) throw new Error("antelopejs-lease: no mongod on PATH or in ~/.cache/mongodb-binaries; install MongoDB, or set DMS_MONGO_URL to a server you run");
|
|
591
|
+
const started = spawn(binary, [
|
|
592
|
+
"--dbpath",
|
|
593
|
+
paths.dbpath,
|
|
594
|
+
"--port",
|
|
595
|
+
String(port),
|
|
596
|
+
"--bind_ip",
|
|
597
|
+
"127.0.0.1",
|
|
598
|
+
"--logpath",
|
|
599
|
+
paths.log,
|
|
600
|
+
"--logappend",
|
|
601
|
+
"--wiredTigerCacheSizeGB",
|
|
602
|
+
"0.25",
|
|
603
|
+
"--fork"
|
|
604
|
+
], {
|
|
605
|
+
detached: true,
|
|
606
|
+
stdio: "ignore"
|
|
607
|
+
});
|
|
608
|
+
let exited = false;
|
|
609
|
+
started.once("exit", () => exited = true);
|
|
610
|
+
started.once("error", () => exited = true);
|
|
611
|
+
started.unref();
|
|
612
|
+
return ready(port, paths, () => exited);
|
|
613
|
+
}
|
|
614
|
+
//#endregion
|
|
615
|
+
//#region src/lease/registry.ts
|
|
616
|
+
const LOCK_WAIT_MS = 15e3;
|
|
617
|
+
const RECORD_FILE = "lease.json";
|
|
618
|
+
const RUNS_DIR = "runs";
|
|
619
|
+
function staleReason(record, git) {
|
|
620
|
+
if (git === void 0) return "missing";
|
|
621
|
+
if (git.inode !== record.gitInode) return "recreated";
|
|
622
|
+
return git.birth !== 0 && record.gitBirth !== 0 && git.birth !== record.gitBirth ? "recreated" : void 0;
|
|
623
|
+
}
|
|
624
|
+
/** The state of a lease from its parsed record and the facts observed about it. */
|
|
625
|
+
function leaseState(parsed, facts) {
|
|
626
|
+
if (parsed === void 0) return { kind: "claiming" };
|
|
627
|
+
if (parsed.kind === "foreign") return { kind: "foreign" };
|
|
628
|
+
if (facts.git.kind === "unreadable") return {
|
|
629
|
+
kind: "unreadable",
|
|
630
|
+
code: facts.git.code
|
|
631
|
+
};
|
|
632
|
+
const git = facts.git.kind === "present" ? facts.git.identity : void 0;
|
|
633
|
+
const reason = staleReason(parsed.record, git);
|
|
634
|
+
if (reason === void 0) return { kind: "live" };
|
|
635
|
+
return {
|
|
636
|
+
kind: facts.serving ? "orphaned" : "stale",
|
|
637
|
+
reason
|
|
638
|
+
};
|
|
639
|
+
}
|
|
640
|
+
function probeGit(worktree) {
|
|
641
|
+
try {
|
|
642
|
+
const stat = statSync(join(worktree, ".git"), { throwIfNoEntry: false });
|
|
643
|
+
if (stat === void 0) return { kind: "gone" };
|
|
644
|
+
return {
|
|
645
|
+
kind: "present",
|
|
646
|
+
identity: {
|
|
647
|
+
inode: stat.ino,
|
|
648
|
+
birth: stat.birthtimeMs
|
|
649
|
+
}
|
|
650
|
+
};
|
|
651
|
+
} catch (error) {
|
|
652
|
+
return {
|
|
653
|
+
kind: "unreadable",
|
|
654
|
+
code: (error instanceof Error && "code" in error ? String(error.code) : "") || "unknown"
|
|
655
|
+
};
|
|
656
|
+
}
|
|
657
|
+
}
|
|
658
|
+
/** The worktree containing `cwd`, by the real path of `git rev-parse --show-toplevel`. */
|
|
659
|
+
function locateWorktree(cwd) {
|
|
660
|
+
let top;
|
|
661
|
+
try {
|
|
662
|
+
top = execFileSync("git", ["rev-parse", "--show-toplevel"], {
|
|
663
|
+
cwd,
|
|
664
|
+
encoding: "utf8",
|
|
665
|
+
stdio: [
|
|
666
|
+
"ignore",
|
|
667
|
+
"pipe",
|
|
668
|
+
"ignore"
|
|
669
|
+
]
|
|
670
|
+
}).trim();
|
|
671
|
+
} catch {
|
|
672
|
+
throw new Error(`antelopejs-lease: ${cwd} is not inside a git worktree`);
|
|
673
|
+
}
|
|
674
|
+
const path = realpathSync(top);
|
|
675
|
+
const git = probeGit(path);
|
|
676
|
+
if (git.kind !== "present") throw new Error(`antelopejs-lease: ${path} has no .git entry`);
|
|
677
|
+
return {
|
|
678
|
+
path,
|
|
679
|
+
id: leaseId(path),
|
|
680
|
+
git: git.identity
|
|
681
|
+
};
|
|
682
|
+
}
|
|
683
|
+
function mongodPaths(dir) {
|
|
684
|
+
return {
|
|
685
|
+
dbpath: join(dir, "mongo"),
|
|
686
|
+
log: join(dir, "logs", "mongod.log")
|
|
687
|
+
};
|
|
688
|
+
}
|
|
689
|
+
/**
|
|
690
|
+
* Runs `body` holding the registry lock: a listener on 127.0.0.1:{@link LOCK_PORT}. The kernel
|
|
691
|
+
* frees it when its holder exits, crash included, so the lock never goes stale. Waits up to 15 s.
|
|
692
|
+
*/
|
|
693
|
+
async function withRegistryLock(body) {
|
|
694
|
+
const deadline = Date.now() + LOCK_WAIT_MS;
|
|
695
|
+
let server = await claimPort(LOCK_PORT, "127.0.0.1");
|
|
696
|
+
while (server === void 0) {
|
|
697
|
+
if (Date.now() > deadline) throw new Error(`antelopejs-lease: registry lock 127.0.0.1:${LOCK_PORT} held for ${LOCK_WAIT_MS / 1e3} s; find its holder with: ss -ltnp 'sport = :${LOCK_PORT}' or lsof -iTCP:${LOCK_PORT} -sTCP:LISTEN`);
|
|
698
|
+
await setTimeout(20 + Math.random() * 20);
|
|
699
|
+
server = await claimPort(LOCK_PORT, "127.0.0.1");
|
|
700
|
+
}
|
|
701
|
+
try {
|
|
702
|
+
return await body();
|
|
703
|
+
} finally {
|
|
704
|
+
await closeServer(server);
|
|
705
|
+
}
|
|
706
|
+
}
|
|
707
|
+
function readParsed(dir) {
|
|
708
|
+
let text;
|
|
709
|
+
try {
|
|
710
|
+
text = readFileSync(join(dir, RECORD_FILE), "utf8");
|
|
711
|
+
} catch {
|
|
712
|
+
return;
|
|
713
|
+
}
|
|
714
|
+
return parseRecord(text);
|
|
715
|
+
}
|
|
716
|
+
/** Every lease directory under `home`. */
|
|
717
|
+
function readEntries(home) {
|
|
718
|
+
let names;
|
|
719
|
+
try {
|
|
720
|
+
names = readdirSync(home);
|
|
721
|
+
} catch {
|
|
722
|
+
return [];
|
|
723
|
+
}
|
|
724
|
+
return names.filter(isLeaseId).map((id) => {
|
|
725
|
+
const dir = join(home, id);
|
|
726
|
+
return {
|
|
727
|
+
id,
|
|
728
|
+
dir,
|
|
729
|
+
parsed: readParsed(dir)
|
|
730
|
+
};
|
|
731
|
+
});
|
|
732
|
+
}
|
|
733
|
+
/** The ports an entry keeps from every other lease. */
|
|
734
|
+
function reservedBy(entry) {
|
|
735
|
+
if (entry.parsed === void 0) return [];
|
|
736
|
+
if (entry.parsed.kind === "foreign") return entry.parsed.reserved;
|
|
737
|
+
return Object.values(entry.parsed.record.ports);
|
|
738
|
+
}
|
|
739
|
+
async function serving(record) {
|
|
740
|
+
return await accepting(record.ports.api) || accepting(record.ports.web);
|
|
741
|
+
}
|
|
742
|
+
async function observe(entry) {
|
|
743
|
+
const record = entry.parsed?.kind === "current" ? entry.parsed.record : void 0;
|
|
744
|
+
const facts = record === void 0 ? {
|
|
745
|
+
git: { kind: "gone" },
|
|
746
|
+
serving: false
|
|
747
|
+
} : {
|
|
748
|
+
git: probeGit(record.worktree),
|
|
749
|
+
serving: await serving(record)
|
|
750
|
+
};
|
|
751
|
+
return {
|
|
752
|
+
entry,
|
|
753
|
+
state: leaseState(entry.parsed, facts)
|
|
754
|
+
};
|
|
755
|
+
}
|
|
756
|
+
/** Kills the lease's mongod, then deletes its directory. Call under the lock. */
|
|
757
|
+
async function removeLease(dir) {
|
|
758
|
+
await stopMongod(mongodPaths(dir).dbpath, 0);
|
|
759
|
+
rmSync(dir, {
|
|
760
|
+
recursive: true,
|
|
761
|
+
force: true
|
|
762
|
+
});
|
|
763
|
+
}
|
|
764
|
+
function running(pid) {
|
|
765
|
+
if (!Number.isInteger(pid) || pid <= 0) return false;
|
|
766
|
+
try {
|
|
767
|
+
process.kill(pid, 0);
|
|
768
|
+
return true;
|
|
769
|
+
} catch {
|
|
770
|
+
return false;
|
|
771
|
+
}
|
|
772
|
+
}
|
|
773
|
+
function runPids(dir) {
|
|
774
|
+
try {
|
|
775
|
+
return readdirSync(join(dir, RUNS_DIR)).map(Number);
|
|
776
|
+
} catch {
|
|
777
|
+
return [];
|
|
778
|
+
}
|
|
779
|
+
}
|
|
780
|
+
/**
|
|
781
|
+
* Records that process `pid` runs a command under the lease in `dir`, and forgets the runs that
|
|
782
|
+
* have exited. `gc` never removes a lease while one of its runs is alive. A pid the system reused
|
|
783
|
+
* keeps the lease until that process exits too, which only delays `gc`.
|
|
784
|
+
*/
|
|
785
|
+
function markRun(dir, pid) {
|
|
786
|
+
const runs = join(dir, RUNS_DIR);
|
|
787
|
+
mkdirSync(runs, { recursive: true });
|
|
788
|
+
for (const gone of runPids(dir).filter((other) => !running(other))) rmSync(join(runs, String(gone)), { force: true });
|
|
789
|
+
writeFileSync(join(runs, String(pid)), "");
|
|
790
|
+
}
|
|
791
|
+
async function quiet(record, dir) {
|
|
792
|
+
if (runPids(dir).some(running)) return false;
|
|
793
|
+
if (mongodPid(mongodPaths(dir).dbpath) !== void 0) return false;
|
|
794
|
+
for (const port of Object.values(record.ports)) if (await accepting(port)) return false;
|
|
795
|
+
return true;
|
|
796
|
+
}
|
|
797
|
+
async function removable(observed, policy) {
|
|
798
|
+
const { entry, state } = observed;
|
|
799
|
+
if (state.kind === "stale") return true;
|
|
800
|
+
if (state.kind === "claiming") return policy.leftovers;
|
|
801
|
+
if (state.kind !== "live" || policy.idleBefore === void 0) return false;
|
|
802
|
+
if (entry.parsed?.kind !== "current") return false;
|
|
803
|
+
if (statSync(entry.dir).mtimeMs >= policy.idleBefore) return false;
|
|
804
|
+
return quiet(entry.parsed.record, entry.dir);
|
|
805
|
+
}
|
|
806
|
+
/** Removes the leases `policy` allows and returns the others, observed. Call under the lock. */
|
|
807
|
+
async function sweep(home, policy) {
|
|
808
|
+
const kept = [];
|
|
809
|
+
for (const entry of readEntries(home)) {
|
|
810
|
+
const observed = await observe(entry);
|
|
811
|
+
if (await removable(observed, policy)) await removeLease(entry.dir);
|
|
812
|
+
else kept.push(observed);
|
|
813
|
+
}
|
|
814
|
+
return kept;
|
|
815
|
+
}
|
|
816
|
+
function writeRecord(dir, record) {
|
|
817
|
+
const file = join(dir, RECORD_FILE);
|
|
818
|
+
const partial = `${file}.${process.pid}.tmp`;
|
|
819
|
+
writeFileSync(partial, `${JSON.stringify(record, null, 2)}\n`);
|
|
820
|
+
renameSync(partial, file);
|
|
821
|
+
}
|
|
822
|
+
/** The error for a lease directory whose record this version cannot read. */
|
|
823
|
+
function foreignRecord(dir) {
|
|
824
|
+
return /* @__PURE__ */ new Error(`antelopejs-lease: ${join(dir, RECORD_FILE)} was written by another antelopejs-lease version; run that version, or remove the directory once nothing uses it`);
|
|
825
|
+
}
|
|
826
|
+
function orphanedOwn(observed, worktree) {
|
|
827
|
+
if (observed.entry.parsed?.kind !== "current") return foreignRecord(observed.entry.dir);
|
|
828
|
+
const { ports } = observed.entry.parsed.record;
|
|
829
|
+
const pids = [ports.api, ports.web].flatMap(listenerPids);
|
|
830
|
+
return /* @__PURE__ */ new Error(`antelopejs-lease: the lease of ${worktree.path} belongs to an earlier checkout at this path, whose servers still listen on api port ${ports.api} or web port ${ports.web}${pids.length ? ` (pids ${pids.join(", ")})` : ""}; stop them, then rerun`);
|
|
831
|
+
}
|
|
832
|
+
function reuse(observed, worktree, mongo) {
|
|
833
|
+
if (observed.state.kind !== "live" || observed.entry.parsed?.kind !== "current") throw orphanedOwn(observed, worktree);
|
|
834
|
+
const { dir } = observed.entry;
|
|
835
|
+
const current = observed.entry.parsed.record;
|
|
836
|
+
const record = current.mongo === mongo ? current : {
|
|
837
|
+
...current,
|
|
838
|
+
mongo
|
|
839
|
+
};
|
|
840
|
+
if (record !== current) writeRecord(dir, record);
|
|
841
|
+
const now = /* @__PURE__ */ new Date();
|
|
842
|
+
utimesSync(dir, now, now);
|
|
843
|
+
return {
|
|
844
|
+
record,
|
|
845
|
+
dir
|
|
846
|
+
};
|
|
847
|
+
}
|
|
848
|
+
/**
|
|
849
|
+
* The lease of `worktree`, created on first use: the same record, ports and directory on every
|
|
850
|
+
* later call from the same checkout. Sweeps stale leases on the way.
|
|
851
|
+
*/
|
|
852
|
+
function openLease(home, worktree, mongo) {
|
|
853
|
+
return withRegistryLock(async () => {
|
|
854
|
+
const kept = await sweep(home, { leftovers: false });
|
|
855
|
+
const own = kept.find((observed) => observed.entry.id === worktree.id && observed.state.kind !== "claiming");
|
|
856
|
+
if (own !== void 0) return reuse(own, worktree, mongo);
|
|
857
|
+
const taken = new Set(kept.flatMap((observed) => reservedBy(observed.entry)));
|
|
858
|
+
const ports = await chooseBlock(worktree.id, taken, bindable);
|
|
859
|
+
const dir = join(home, worktree.id);
|
|
860
|
+
for (const sub of [
|
|
861
|
+
"mongo",
|
|
862
|
+
"logs",
|
|
863
|
+
"tmp"
|
|
864
|
+
]) mkdirSync(join(dir, sub), { recursive: true });
|
|
865
|
+
const record = {
|
|
866
|
+
version: 1,
|
|
867
|
+
id: worktree.id,
|
|
868
|
+
worktree: worktree.path,
|
|
869
|
+
gitInode: worktree.git.inode,
|
|
870
|
+
gitBirth: worktree.git.birth,
|
|
871
|
+
ports,
|
|
872
|
+
createdAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
873
|
+
mongo
|
|
874
|
+
};
|
|
875
|
+
writeRecord(dir, record);
|
|
876
|
+
return {
|
|
877
|
+
record,
|
|
878
|
+
dir
|
|
879
|
+
};
|
|
880
|
+
});
|
|
881
|
+
}
|
|
882
|
+
//#endregion
|
|
883
|
+
//#region src/lease/commands.ts
|
|
884
|
+
const DOWN_GRACE_MS = 1e4;
|
|
885
|
+
const DAY_MS = 864e5;
|
|
886
|
+
const ROLES = Object.keys(PORT_ROLES).filter(isRole);
|
|
887
|
+
/**
|
|
888
|
+
* Opens this worktree's lease, makes sure its mongod runs unless `DMS_MONGO_URL` names another
|
|
889
|
+
* server, and replaces this process with `command` under the lease's environment. Answers 127 or
|
|
890
|
+
* 126, as a shell does, only when the command is not found or cannot run.
|
|
891
|
+
*/
|
|
892
|
+
async function run(command, as, env) {
|
|
893
|
+
const worktree = locateWorktree(process.cwd());
|
|
894
|
+
const lease = await openLease(leaseHome(env), worktree, env.DMS_MONGO_URL ? "external" : "owned");
|
|
895
|
+
markRun(lease.dir, process.pid);
|
|
896
|
+
if (lease.record.mongo === "owned") await ensureMongod(lease.record.ports.mongo, mongodPaths(lease.dir), env);
|
|
897
|
+
return launch(command, leaseEnv(lease, env, as));
|
|
898
|
+
}
|
|
899
|
+
function stateLabel(state) {
|
|
900
|
+
if (state.kind === "unreadable") return `${state.kind}:${state.code}`;
|
|
901
|
+
return state.kind === "stale" || state.kind === "orphaned" ? `${state.kind}:${state.reason}` : state.kind;
|
|
902
|
+
}
|
|
903
|
+
async function listeningRoles(record) {
|
|
904
|
+
const roles = [];
|
|
905
|
+
for (const role of ROLES) if (await accepting(record.ports[role])) roles.push(role);
|
|
906
|
+
return roles;
|
|
907
|
+
}
|
|
908
|
+
async function report(observed) {
|
|
909
|
+
const { entry, state } = observed;
|
|
910
|
+
const record = entry.parsed?.kind === "current" ? entry.parsed.record : null;
|
|
911
|
+
const base = {
|
|
912
|
+
id: entry.id,
|
|
913
|
+
state: stateLabel(state),
|
|
914
|
+
dir: entry.dir
|
|
915
|
+
};
|
|
916
|
+
if (record === null) return {
|
|
917
|
+
...base,
|
|
918
|
+
record,
|
|
919
|
+
mongod: null,
|
|
920
|
+
listening: [],
|
|
921
|
+
pids: []
|
|
922
|
+
};
|
|
923
|
+
const pids = state.kind === "orphaned" ? [record.ports.api, record.ports.web].flatMap(listenerPids) : [];
|
|
924
|
+
return {
|
|
925
|
+
...base,
|
|
926
|
+
record,
|
|
927
|
+
mongod: mongodPid(mongodPaths(entry.dir).dbpath) ?? null,
|
|
928
|
+
listening: await listeningRoles(record),
|
|
929
|
+
pids
|
|
930
|
+
};
|
|
931
|
+
}
|
|
932
|
+
/** Every lease on the machine after sweeping stale ones. */
|
|
933
|
+
async function status(env) {
|
|
934
|
+
const home = leaseHome(env);
|
|
935
|
+
const kept = await withRegistryLock(() => sweep(home, { leftovers: false }));
|
|
936
|
+
return Promise.all(kept.map(report));
|
|
937
|
+
}
|
|
938
|
+
/** A running mongod shows its pid in every mode, so a lease switched to `DMS_MONGO_URL` hides none. */
|
|
939
|
+
function mongodCell(row) {
|
|
940
|
+
if (row.mongod !== null) return String(row.mongod);
|
|
941
|
+
return row.record?.mongo === "external" ? "external" : "-";
|
|
942
|
+
}
|
|
943
|
+
/** `status` as an aligned table, one lease per line; empty when there is no lease. */
|
|
944
|
+
function statusTable(rows) {
|
|
945
|
+
if (rows.length === 0) return "";
|
|
946
|
+
const cells = [[
|
|
947
|
+
"ID",
|
|
948
|
+
"STATE",
|
|
949
|
+
"API",
|
|
950
|
+
"WEB",
|
|
951
|
+
"MONGO",
|
|
952
|
+
"MONGOD",
|
|
953
|
+
"WORKTREE"
|
|
954
|
+
], ...rows.map((row) => [
|
|
955
|
+
row.id,
|
|
956
|
+
row.state,
|
|
957
|
+
String(row.record?.ports.api ?? "-"),
|
|
958
|
+
String(row.record?.ports.web ?? "-"),
|
|
959
|
+
String(row.record?.ports.mongo ?? "-"),
|
|
960
|
+
mongodCell(row),
|
|
961
|
+
`${row.record?.worktree ?? row.dir}${row.pids.length ? ` (pids ${row.pids.join(", ")})` : ""}`
|
|
962
|
+
])];
|
|
963
|
+
const widths = cells[0]?.map((_, column) => Math.max(...cells.map((line) => line[column]?.length ?? 0)));
|
|
964
|
+
return cells.map((line) => line.map((cell, column) => cell.padEnd(widths?.[column] ?? 0)).join(" ").trimEnd()).map((line) => `${line}\n`).join("");
|
|
965
|
+
}
|
|
966
|
+
/**
|
|
967
|
+
* Tears down this worktree's lease: stops its mongod and deletes its data, logs and tmp. Refuses
|
|
968
|
+
* while its api or web port accepts, unless `force`. Does nothing when there is no lease.
|
|
969
|
+
*/
|
|
970
|
+
async function down(env, force) {
|
|
971
|
+
const worktree = locateWorktree(process.cwd());
|
|
972
|
+
const entry = readEntries(leaseHome(env)).find((candidate) => candidate.id === worktree.id);
|
|
973
|
+
if (entry === void 0) return;
|
|
974
|
+
if (entry.parsed?.kind === "foreign") throw foreignRecord(entry.dir);
|
|
975
|
+
const ports = entry.parsed?.kind === "current" ? entry.parsed.record.ports : void 0;
|
|
976
|
+
if (ports !== void 0 && !force) {
|
|
977
|
+
const busy = [];
|
|
978
|
+
for (const port of [ports.api, ports.web]) if (await accepting(port)) busy.push(port);
|
|
979
|
+
if (busy.length > 0) throw new Error(`antelopejs-lease: port ${busy.join(" and ")} of this lease still listens; stop the servers first (for dms-dev.sh: antelopejs-lease run -- bash <path to dms-dev.sh> stop), or pass --force`);
|
|
980
|
+
}
|
|
981
|
+
await stopMongod(mongodPaths(entry.dir).dbpath, DOWN_GRACE_MS);
|
|
982
|
+
await withRegistryLock(() => removeLease(entry.dir));
|
|
983
|
+
}
|
|
984
|
+
/**
|
|
985
|
+
* Removes every lease left behind machine-wide: stale leases, directories with no record, and
|
|
986
|
+
* leases with no running `run`, no mongod and no listening port that no `run` opened for
|
|
987
|
+
* `idleDays`.
|
|
988
|
+
*/
|
|
989
|
+
async function gc(env, idleDays) {
|
|
990
|
+
const idleBefore = Date.now() - idleDays * DAY_MS;
|
|
991
|
+
await withRegistryLock(() => sweep(leaseHome(env), {
|
|
992
|
+
leftovers: true,
|
|
993
|
+
idleBefore
|
|
994
|
+
}));
|
|
995
|
+
}
|
|
996
|
+
//#endregion
|
|
997
|
+
//#region src/bin/lease.ts
|
|
998
|
+
const USAGE = "usage: antelopejs-lease run [--as api|web] -- <command...> | status [--json] | down [--force] | gc [--idle <days>]";
|
|
999
|
+
const DEFAULT_IDLE_DAYS = 14;
|
|
1000
|
+
const MIN_IDLE_DAYS = 1;
|
|
1001
|
+
function usage(problem) {
|
|
1002
|
+
return /* @__PURE__ */ new Error(`antelopejs-lease: ${problem}\n${USAGE}`);
|
|
1003
|
+
}
|
|
1004
|
+
async function runVerb(args, command) {
|
|
1005
|
+
const { values } = parseArgs({
|
|
1006
|
+
args,
|
|
1007
|
+
options: { as: { type: "string" } }
|
|
1008
|
+
});
|
|
1009
|
+
if (values.as !== void 0 && !isServerRole(values.as)) throw usage(`--as takes api or web, not ${values.as}`);
|
|
1010
|
+
if (command.length === 0) throw usage("run needs a command after --");
|
|
1011
|
+
return run(command, values.as, process.env);
|
|
1012
|
+
}
|
|
1013
|
+
async function statusVerb(args) {
|
|
1014
|
+
const { values } = parseArgs({
|
|
1015
|
+
args,
|
|
1016
|
+
options: { json: { type: "boolean" } }
|
|
1017
|
+
});
|
|
1018
|
+
const rows = await status(process.env);
|
|
1019
|
+
process.stdout.write(values.json ? `${JSON.stringify(rows, null, 2)}\n` : statusTable(rows));
|
|
1020
|
+
return 0;
|
|
1021
|
+
}
|
|
1022
|
+
async function downVerb(args) {
|
|
1023
|
+
const { values } = parseArgs({
|
|
1024
|
+
args,
|
|
1025
|
+
options: { force: { type: "boolean" } }
|
|
1026
|
+
});
|
|
1027
|
+
await down(process.env, values.force === true);
|
|
1028
|
+
return 0;
|
|
1029
|
+
}
|
|
1030
|
+
async function gcVerb(args) {
|
|
1031
|
+
const { values } = parseArgs({
|
|
1032
|
+
args,
|
|
1033
|
+
options: { idle: { type: "string" } }
|
|
1034
|
+
});
|
|
1035
|
+
const days = values.idle === void 0 ? DEFAULT_IDLE_DAYS : Number(values.idle);
|
|
1036
|
+
if (!Number.isFinite(days) || days < MIN_IDLE_DAYS) throw usage(`--idle takes ${MIN_IDLE_DAYS} or more days, not ${values.idle}; a lease a run opened within the last day is never idle`);
|
|
1037
|
+
await gc(process.env, days);
|
|
1038
|
+
return 0;
|
|
1039
|
+
}
|
|
1040
|
+
await runCliAsync(async () => {
|
|
1041
|
+
const argv = process.argv.slice(2);
|
|
1042
|
+
const split = argv.indexOf("--");
|
|
1043
|
+
const [verb, ...args] = split === -1 ? argv : argv.slice(0, split);
|
|
1044
|
+
const command = split === -1 ? [] : argv.slice(split + 1);
|
|
1045
|
+
if (verb === "run") return runVerb(args, command);
|
|
1046
|
+
if (command.length > 0) throw usage(`${verb} takes no command`);
|
|
1047
|
+
if (verb === "status") return statusVerb(args);
|
|
1048
|
+
if (verb === "down") return downVerb(args);
|
|
1049
|
+
if (verb === "gc") return gcVerb(args);
|
|
1050
|
+
throw usage(verb === void 0 ? "missing command" : `unknown command ${verb}`);
|
|
1051
|
+
});
|
|
1052
|
+
//#endregion
|
|
1053
|
+
export {};
|