@mostra/runtime 0.2.0 → 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/dist/bin.js +7 -7
- package/dist/bin.js.map +1 -1
- package/dist/builder/child/main.js +18 -17
- package/dist/builder/child/main.js.map +1 -1
- package/dist/{child-xrHmytks.js → child-BQc3arf7.js} +5 -2
- package/dist/{child-xrHmytks.js.map → child-BQc3arf7.js.map} +1 -1
- package/dist/deps/child/install.js +9 -6
- package/dist/deps/child/install.js.map +1 -1
- package/dist/files-KxzOxckl.js +674 -0
- package/dist/files-KxzOxckl.js.map +1 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -2
- package/dist/{instance-CzBkUyHu.js → instance-DiKSe7s6.js} +1148 -737
- package/dist/instance-DiKSe7s6.js.map +1 -0
- package/package.json +5 -5
- package/src/bin.ts +4 -10
- package/src/builder/child/dev.ts +4 -3
- package/src/builder/child/plugins.ts +12 -7
- package/src/builder/child/spa.ts +15 -9
- package/src/builder/index.ts +3 -6
- package/src/deps/child/install.ts +3 -2
- package/src/deps/index.ts +21 -16
- package/src/deps/warm.ts +3 -16
- package/src/faults.ts +9 -2
- package/src/gateway/capabilities.ts +2 -2
- package/src/home/acquire.ts +27 -11
- package/src/home/paths.ts +45 -135
- package/src/home/platform.ts +17 -9
- package/src/home/record.ts +3 -3
- package/src/home/settings.ts +5 -16
- package/src/instance/index.ts +31 -7
- package/src/ledger/index.ts +5 -27
- package/src/platform/control.ts +409 -0
- package/src/platform/directories.ts +212 -0
- package/src/platform/environment.ts +64 -0
- package/src/platform/files.ts +368 -0
- package/src/platform/helper.ts +152 -0
- package/src/{processes → platform}/identity.ts +40 -8
- package/src/platform/index.ts +46 -0
- package/src/platform/launch.ts +373 -0
- package/src/processes/child.ts +4 -1
- package/src/processes/environment.ts +22 -3
- package/src/processes/index.ts +2 -1
- package/src/processes/manager.ts +76 -179
- package/src/protocol-server/client.ts +19 -18
- package/src/protocol-server/server.ts +75 -54
- package/src/publish/publisher.ts +16 -9
- package/src/publish/source.ts +7 -4
- package/src/registry/store.ts +7 -65
- package/src/secrets/index.ts +2 -2
- package/src/service/unit.ts +3 -2
- package/src/verify/index.ts +5 -3
- package/src/verify/typecheck.ts +3 -2
- package/src/workers/launcher.ts +3 -1
- package/dist/instance-CzBkUyHu.js.map +0 -1
- package/dist/types-NjNy7gXX.js +0 -57
- package/dist/types-NjNy7gXX.js.map +0 -1
|
@@ -1,19 +1,19 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { C as runtimeRoot$1, D as DEV_RELOAD_METHOD, E as DEV_METHOD, M as STAGING_FILES, O as DEV_SECRET_HEADER, S as runHelperAsync, T as DEV_CHANGED_METHOD, _ as ownedDirectory, a as nameKey, b as socketPathLimit, c as renamePath, d as samePath, f as sealPlaced, g as defaultHome, h as WINDOWS, i as linkTarget, j as LIVE_DECLARATION, l as renamePathSync, m as OS, o as pathKey, p as sealTree, r as linkDirectory, s as removeTree, t as fsyncPath, u as replaceDirectoryLink, v as pathsOf, w as BUILD_METHOD, x as helperPath, y as runtimeDirFor } from "./files-KxzOxckl.js";
|
|
2
2
|
import { builtinModules, createRequire } from "node:module";
|
|
3
|
-
import { appendFileSync, chmodSync, closeSync, constants, createReadStream, createWriteStream, existsSync, fsyncSync, linkSync, mkdirSync, openSync, readFileSync, readdirSync,
|
|
4
|
-
import { basename, delimiter, dirname, extname,
|
|
3
|
+
import { appendFileSync, chmodSync, closeSync, constants, createReadStream, createWriteStream, existsSync, fsyncSync, linkSync, mkdirSync, openSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, statSync, unlinkSync, watch, writeFileSync, writeSync } from "node:fs";
|
|
4
|
+
import { basename, delimiter, dirname, extname, join, relative, resolve, sep } from "node:path";
|
|
5
5
|
import { fileURLToPath } from "node:url";
|
|
6
6
|
import { ACTION_ARGS_MAX, ACTION_RESULT_MAX, ALL_SCOPES, ARTIFACT_MANIFEST_KEYS, ARTIFACT_PROGRESS, ArtifactId, ArtifactManifest, BROWSER_PROTOCOL_REVISION, BROWSER_PROTOCOL_REVISIONS, BUNDLE_NAME, CLI_CLIENT_NAME, CallRequest, ChooseRequest, DEFAULT_WORKER_LIMITS, DEV_NOTIFY, DeliveryId, EVENTS_NOTIFY, FieldsRequest, FollowRequest, HOST_PROTOCOL_REVISIONS, LIVE_RING_DEFAULT, LIVE_RING_MAX, LIVE_VALUE_MAX, LineSplitter, LiveRequest, MAX_LINE_LENGTH, MutationId, RUN_LOG_MAX, RUN_LOG_TRUNCATED, RpcError, RpcPeer, RunAttachRequest, RunCancelRequest, RunId, RunRequest, SECRET_NAME_PATTERN, SECRET_VALUE_MAX, SIGNAL_NAME_PATTERN, SIGNAL_PAYLOAD_MAX_BYTES, ServerEmitParams, ServerLiveValueParams, ServerSecretParams, ServerSignalParams, ServerStateGetParams, ServerStatePatchParams, ShellSubmitRequest, SignalRequest, SubmissionId, SubmissionPolicy, SubmitRequest, TokenId, VERIFY_RUNNER_METHODS, VerifyVerdict, VersionId, ViewId, ViewerId, WORKER_METHODS, WorkerBatchParams, WorkerCallOutcome, WorkerPingResult, WorkerStartResult, ariaSummary, artifactCreateMethod, artifactGetMethod, artifactListMethod, artifactPublishMethod, artifactVerifyMethod, canonicalJson, checkArgumentFrames, checkRequest, createDiagnostic, depsAddMethod, devStartMethod, devStopMethod, durationMs, encodeLine, estimateImageTokens, eventsAckMethod, eventsReadMethod, eventsSubscribeMethod, eventsUnsubscribeMethod, fromBase64, gcRunMethod, instanceCheckMethod, instanceStatusMethod, isFieldId, isFinalRunStatus, livePushMethod, mostraInitializeMethod, mostraShutdownMethod, negotiateRevision, normalizeScopes, parseParams, portDraftsMirrorMethod, portIdentityResolveMethod, portSecretsGetMethod, portSubmissionsDeliverMethod, portTrustedControlsActivatedMethod, portTrustedControlsPolicyMethod, refusal, resultsGetMethod, safeEqual, safePath, scopeAllows, secretDeleteMethod, secretListMethod, secretSetMethod, serializeAll, stateGetMethod, statePatchMethod, toBase64, viewDefaultMethod, viewLaunchMethod, viewRevokeMethod, viewRotateMethod, viewUrlMethod, viewportsFor, waitMethod } from "@mostra/protocol";
|
|
7
7
|
import { createHash, createHmac, randomBytes, randomInt, randomUUID } from "node:crypto";
|
|
8
8
|
import { connect, createConnection, createServer, isIP } from "node:net";
|
|
9
|
-
import {
|
|
9
|
+
import { execFile, execFileSync, spawn } from "node:child_process";
|
|
10
|
+
import { Duplex, Readable } from "node:stream";
|
|
11
|
+
import { access, chmod, copyFile, cp, lstat, mkdir, mkdtemp, readFile, readdir, realpath, rm, stat, unlink, utimes, writeFile } from "node:fs/promises";
|
|
10
12
|
import { homedir, networkInterfaces } from "node:os";
|
|
11
13
|
import semver from "semver";
|
|
12
|
-
import { execFile, execFileSync, spawn } from "node:child_process";
|
|
13
14
|
import { createInterface } from "node:readline";
|
|
14
15
|
import * as z from "zod";
|
|
15
16
|
import { parse, parseDocument } from "yaml";
|
|
16
|
-
import { Readable } from "node:stream";
|
|
17
17
|
import { pipeline } from "node:stream/promises";
|
|
18
18
|
import { createZstdCompress } from "node:zlib";
|
|
19
19
|
import { createServer as createServer$1, request } from "node:http";
|
|
@@ -844,20 +844,846 @@ function escapeRegExp(text) {
|
|
|
844
844
|
return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
845
845
|
}
|
|
846
846
|
/**
|
|
847
|
-
* Whether a version with this coverage covers a draft field ID (D109). A version without
|
|
848
|
-
* coverage (built before WP-07) covers everything, as does an open one. Only entries that may be
|
|
849
|
-
* viewer-scoped count: an artifact-scoped field never lives in a draft.
|
|
847
|
+
* Whether a version with this coverage covers a draft field ID (D109). A version without
|
|
848
|
+
* coverage (built before WP-07) covers everything, as does an open one. Only entries that may be
|
|
849
|
+
* viewer-scoped count: an artifact-scoped field never lives in a draft.
|
|
850
|
+
*/
|
|
851
|
+
function coverageMatcher(coverage) {
|
|
852
|
+
if (coverage === void 0 || coverage.open) return () => true;
|
|
853
|
+
const ids = /* @__PURE__ */ new Set();
|
|
854
|
+
const templates = [];
|
|
855
|
+
for (const entry of coverage.entries) {
|
|
856
|
+
if (entry.scope === "artifact") continue;
|
|
857
|
+
if (entry.id !== void 0) ids.add(entry.id);
|
|
858
|
+
else if (entry.template !== void 0) templates.push(new RegExp(`^${entry.template.map(escapeRegExp).join("[\\s\\S]*")}$`));
|
|
859
|
+
}
|
|
860
|
+
return (fieldId) => ids.has(fieldId) || templates.some((pattern) => pattern.test(fieldId));
|
|
861
|
+
}
|
|
862
|
+
//#endregion
|
|
863
|
+
//#region src/platform/identity.ts
|
|
864
|
+
/**
|
|
865
|
+
* Process identity (DATA_MODEL §3 `child.start_time`, FAILURE_MODEL §2). A PID alone can be
|
|
866
|
+
* reused, so a process is identified by its PID plus an opaque start time: the boot it started in
|
|
867
|
+
* and when it started within that boot. Linux reads `/proc/<pid>/stat` (start ticks since boot)
|
|
868
|
+
* and the boot ID; macOS reads `ps -o lstart` (seconds) and `kern.boottime` (VERIFIED_FACTS,
|
|
869
|
+
* WP-02); Windows asks the helper for the creation time (`GetProcessTimes`, 100 ns units since
|
|
870
|
+
* 1601, so absolute across boots), written `win/<creation time>` (VERIFIED_FACTS, WP-W1). Zombies,
|
|
871
|
+
* and Windows processes that exited but whose object a handle still keeps, count as gone.
|
|
872
|
+
*
|
|
873
|
+
* Seconds are enough on macOS (issue #8): XNU hands out PIDs in order from the last one, up to
|
|
874
|
+
* 99,999, then from 100, skipping any PID still used as a process, process group or session
|
|
875
|
+
* (`forkproc` in `bsd/kern/kern_fork.c`). A PID comes back only after the whole range has been
|
|
876
|
+
* handed out, about 99,900 forks, which takes this machine about 100 s at its measured 1,000
|
|
877
|
+
* spawns a second, and never while its process group lives (VERIFIED_FACTS, WP-08).
|
|
878
|
+
*/
|
|
879
|
+
/** The boot part of every Windows start time: creation times are absolute. */
|
|
880
|
+
const WINDOWS_BOOT = "win";
|
|
881
|
+
/** Splits a start time into its boot and its position within the boot. */
|
|
882
|
+
function parts(startTime) {
|
|
883
|
+
const slash = startTime.lastIndexOf("/");
|
|
884
|
+
if (slash <= 0) return void 0;
|
|
885
|
+
const text = startTime.slice(slash + 1);
|
|
886
|
+
if (!/^\d+$/.test(text)) return void 0;
|
|
887
|
+
return {
|
|
888
|
+
boot: startTime.slice(0, slash),
|
|
889
|
+
at: BigInt(text)
|
|
890
|
+
};
|
|
891
|
+
}
|
|
892
|
+
/** Whether two start times belong to the same boot of the machine. */
|
|
893
|
+
function sameBoot(a, b) {
|
|
894
|
+
const left = parts(a);
|
|
895
|
+
const right = parts(b);
|
|
896
|
+
return left !== void 0 && right !== void 0 && left.boot === right.boot;
|
|
897
|
+
}
|
|
898
|
+
/**
|
|
899
|
+
* Whether `candidate` started in the same boot as `reference` and no earlier. On macOS the
|
|
900
|
+
* resolution is one second, so a process started in the same second counts as no earlier.
|
|
901
|
+
*/
|
|
902
|
+
function startedNoEarlier(candidate, reference) {
|
|
903
|
+
const c = parts(candidate);
|
|
904
|
+
const r = parts(reference);
|
|
905
|
+
return c !== void 0 && r !== void 0 && c.boot === r.boot && c.at >= r.at;
|
|
906
|
+
}
|
|
907
|
+
/** Parses one `/proc/<pid>/stat` line. `comm` may contain spaces and parentheses. */
|
|
908
|
+
function parseProcStat(line, boot) {
|
|
909
|
+
const open = line.indexOf("(");
|
|
910
|
+
const close = line.lastIndexOf(")");
|
|
911
|
+
if (open < 0 || close < open) return void 0;
|
|
912
|
+
const pid = Number(line.slice(0, open).trim());
|
|
913
|
+
const rest = line.slice(close + 1).trim().split(/\s+/);
|
|
914
|
+
if (rest[0] === "Z") return void 0;
|
|
915
|
+
const pgid = Number(rest[2]);
|
|
916
|
+
const start = rest[19];
|
|
917
|
+
if (!Number.isSafeInteger(pid) || !Number.isSafeInteger(pgid) || start === void 0) return;
|
|
918
|
+
if (!/^\d+$/.test(start)) return void 0;
|
|
919
|
+
return {
|
|
920
|
+
pid,
|
|
921
|
+
pgid,
|
|
922
|
+
startTime: `${boot}/${start}`
|
|
923
|
+
};
|
|
924
|
+
}
|
|
925
|
+
const MONTHS = [
|
|
926
|
+
"Jan",
|
|
927
|
+
"Feb",
|
|
928
|
+
"Mar",
|
|
929
|
+
"Apr",
|
|
930
|
+
"May",
|
|
931
|
+
"Jun",
|
|
932
|
+
"Jul",
|
|
933
|
+
"Aug",
|
|
934
|
+
"Sep",
|
|
935
|
+
"Oct",
|
|
936
|
+
"Nov",
|
|
937
|
+
"Dec"
|
|
938
|
+
];
|
|
939
|
+
/**
|
|
940
|
+
* Parses one line of `LC_ALL=C TZ=UTC ps -o pid=,pgid=,stat=,lstart=`, such as
|
|
941
|
+
* ` 214 99444 Ss Tue Oct 6 13:53:19 2026`. Zombies (`stat` starting with `Z`) are skipped.
|
|
942
|
+
*/
|
|
943
|
+
function parsePsLine(line, boot) {
|
|
944
|
+
const fields = line.trim().split(/\s+/);
|
|
945
|
+
if (fields.length < 8) return void 0;
|
|
946
|
+
const [pidText, pgidText, stat, , monthText, dayText, timeText, yearText] = fields;
|
|
947
|
+
if (stat?.startsWith("Z")) return void 0;
|
|
948
|
+
const pid = Number(pidText);
|
|
949
|
+
const pgid = Number(pgidText);
|
|
950
|
+
const month = MONTHS.indexOf(monthText ?? "");
|
|
951
|
+
const [hours, minutes, seconds] = (timeText ?? "").split(":").map(Number);
|
|
952
|
+
const millis = Date.UTC(Number(yearText), month, Number(dayText), hours ?? NaN, minutes ?? NaN, seconds ?? NaN);
|
|
953
|
+
if (!Number.isSafeInteger(pid) || !Number.isSafeInteger(pgid) || month < 0 || Number.isNaN(millis)) return;
|
|
954
|
+
return {
|
|
955
|
+
pid,
|
|
956
|
+
pgid,
|
|
957
|
+
startTime: `${boot}/${millis / 1e3}`
|
|
958
|
+
};
|
|
959
|
+
}
|
|
960
|
+
function run$1(file, args) {
|
|
961
|
+
return new Promise((resolve, reject) => {
|
|
962
|
+
execFile(file, args, {
|
|
963
|
+
env: {
|
|
964
|
+
LC_ALL: "C",
|
|
965
|
+
TZ: "UTC",
|
|
966
|
+
PATH: "/usr/bin:/bin:/usr/sbin:/sbin"
|
|
967
|
+
},
|
|
968
|
+
maxBuffer: 67108864
|
|
969
|
+
}, (error, stdout) => {
|
|
970
|
+
if (error && typeof error.code !== "number") {
|
|
971
|
+
reject(error);
|
|
972
|
+
return;
|
|
973
|
+
}
|
|
974
|
+
resolve({
|
|
975
|
+
code: typeof error?.code === "number" ? error.code : 0,
|
|
976
|
+
stdout
|
|
977
|
+
});
|
|
978
|
+
});
|
|
979
|
+
});
|
|
980
|
+
}
|
|
981
|
+
let cachedBoot;
|
|
982
|
+
/** The identity of the current boot of this machine (on Windows a constant: times are absolute). */
|
|
983
|
+
function bootId() {
|
|
984
|
+
cachedBoot ??= (async () => {
|
|
985
|
+
if (process.platform === "win32") return WINDOWS_BOOT;
|
|
986
|
+
if (process.platform === "linux") return (await readFile("/proc/sys/kernel/random/boot_id", "utf8")).trim();
|
|
987
|
+
const { stdout } = await run$1("/usr/sbin/sysctl", ["-n", "kern.boottime"]);
|
|
988
|
+
const match = /sec = (\d+), usec = (\d+)/.exec(stdout);
|
|
989
|
+
if (!match) throw new Error("Couldn't read kern.boottime.");
|
|
990
|
+
return `${match[1]}.${match[2]}`;
|
|
991
|
+
})();
|
|
992
|
+
return cachedBoot;
|
|
993
|
+
}
|
|
994
|
+
/** Reads one process, or `undefined` when no process has that PID. */
|
|
995
|
+
async function readProcess(pid) {
|
|
996
|
+
if (process.platform === "win32") {
|
|
997
|
+
const [entry] = await runHelperAsync(["identity", String(pid)]);
|
|
998
|
+
return entry?.startTime === void 0 ? void 0 : {
|
|
999
|
+
pid,
|
|
1000
|
+
pgid: pid,
|
|
1001
|
+
startTime: entry.startTime
|
|
1002
|
+
};
|
|
1003
|
+
}
|
|
1004
|
+
const boot = await bootId();
|
|
1005
|
+
if (process.platform === "linux") try {
|
|
1006
|
+
return parseProcStat(await readFile(`/proc/${pid}/stat`, "utf8"), boot);
|
|
1007
|
+
} catch {
|
|
1008
|
+
return;
|
|
1009
|
+
}
|
|
1010
|
+
const { code, stdout } = await run$1("/bin/ps", [
|
|
1011
|
+
"-o",
|
|
1012
|
+
"pid=,pgid=,stat=,lstart=",
|
|
1013
|
+
"-p",
|
|
1014
|
+
String(pid)
|
|
1015
|
+
]);
|
|
1016
|
+
if (code !== 0) return void 0;
|
|
1017
|
+
const [line] = stdout.split("\n").filter((text) => text.trim() !== "");
|
|
1018
|
+
return line === void 0 ? void 0 : parsePsLine(line, boot);
|
|
1019
|
+
}
|
|
1020
|
+
/**
|
|
1021
|
+
* Lists every process the user can see. On Windows each carries its parent's PID (`ppid`), which
|
|
1022
|
+
* may name a process that has since exited and whose PID was reused.
|
|
1023
|
+
*/
|
|
1024
|
+
async function listProcesses() {
|
|
1025
|
+
if (process.platform === "win32") return (await runHelperAsync(["processes"])).flatMap((entry) => entry.startTime === void 0 ? [] : [{
|
|
1026
|
+
pid: entry.pid,
|
|
1027
|
+
pgid: entry.pid,
|
|
1028
|
+
startTime: entry.startTime,
|
|
1029
|
+
ppid: entry.ppid ?? 0
|
|
1030
|
+
}]);
|
|
1031
|
+
const boot = await bootId();
|
|
1032
|
+
if (process.platform === "linux") {
|
|
1033
|
+
const entries = (await readdir("/proc")).filter((name) => /^\d+$/.test(name));
|
|
1034
|
+
return (await Promise.all(entries.map(async (name) => {
|
|
1035
|
+
try {
|
|
1036
|
+
return parseProcStat(await readFile(`/proc/${name}/stat`, "utf8"), boot);
|
|
1037
|
+
} catch {
|
|
1038
|
+
return;
|
|
1039
|
+
}
|
|
1040
|
+
}))).filter((info) => info !== void 0);
|
|
1041
|
+
}
|
|
1042
|
+
const { stdout } = await run$1("/bin/ps", [
|
|
1043
|
+
"-A",
|
|
1044
|
+
"-o",
|
|
1045
|
+
"pid=,pgid=,stat=,lstart="
|
|
1046
|
+
]);
|
|
1047
|
+
return stdout.split("\n").map((line) => parsePsLine(line, boot)).filter((info) => info !== void 0);
|
|
1048
|
+
}
|
|
1049
|
+
/** Whether the process recorded as `pid` and `startTime` is still the one running. */
|
|
1050
|
+
async function isSameProcess(pid, startTime) {
|
|
1051
|
+
const info = await readProcess(pid);
|
|
1052
|
+
return info !== void 0 && info.startTime === startTime;
|
|
1053
|
+
}
|
|
1054
|
+
//#endregion
|
|
1055
|
+
//#region src/platform/launch.ts
|
|
1056
|
+
/**
|
|
1057
|
+
* Starting, ending and reaping children on each operating system (RT-09, RT-10, issue #7, D93,
|
|
1058
|
+
* FAILURE_MODEL §2). The process manager keeps the policy (record a child before it runs, end its
|
|
1059
|
+
* descendants with it, reap what a crashed supervisor left); this module is how each system does
|
|
1060
|
+
* it.
|
|
1061
|
+
*
|
|
1062
|
+
* - **POSIX.** A child is started detached, as the leader of its own process group, behind a
|
|
1063
|
+
* `/bin/sh` gate that waits for "go" on descriptor 3 and then `exec`s the command, keeping its
|
|
1064
|
+
* PID, group and start time. It is ended by signalling its group (SIGTERM, then SIGKILL), and
|
|
1065
|
+
* the reaper signals a recorded group's members that started no earlier than its leader.
|
|
1066
|
+
* - **Windows.** A child is started behind `mostra-win gate`, which creates it suspended in a Job
|
|
1067
|
+
* Object of its own that ends every member when its last handle closes, reports its PID and
|
|
1068
|
+
* creation time on descriptor 3, and lets it run on "go". Descriptor 3 stays open as the
|
|
1069
|
+
* child's lifeline: closing it (a stop, or the supervisor's exit or crash) ends the job, child
|
|
1070
|
+
* and descendants at once. Windows has no signals to ask a process to stop, so a stop is that:
|
|
1071
|
+
* graceful work goes over the child's own channel first (D87). The reaper ends a recorded
|
|
1072
|
+
* child's job, which it opens by the name the gate gave it (`Local\mostra-job-<pid>-<creation>`),
|
|
1073
|
+
* and the child itself if it still runs as the recorded process.
|
|
1074
|
+
*/
|
|
1075
|
+
/**
|
|
1076
|
+
* The POSIX gate (issue #7): `/bin/sh` waits for "go" on file descriptor 3 and only then replaces
|
|
1077
|
+
* itself with the real command. A supervisor killed in between leaves a gate that reads
|
|
1078
|
+
* end-of-file and exits 125 without running anything.
|
|
1079
|
+
*/
|
|
1080
|
+
const GATE_SCRIPT = "IFS= read -r go <&3 && [ \"$go\" = go ] || exit 125; exec 3<&-; exec \"$@\"";
|
|
1081
|
+
/** How long reaping waits between SIGTERM and SIGKILL. */
|
|
1082
|
+
const REAP_GRACE_MS = 2e3;
|
|
1083
|
+
/** How long to wait for SIGKILLed processes to disappear before reporting them. */
|
|
1084
|
+
const KILL_WAIT_MS = 5e3;
|
|
1085
|
+
const delay$1 = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
1086
|
+
function signalGroup(pgid, signal) {
|
|
1087
|
+
try {
|
|
1088
|
+
process.kill(-pgid, signal);
|
|
1089
|
+
return true;
|
|
1090
|
+
} catch {
|
|
1091
|
+
return false;
|
|
1092
|
+
}
|
|
1093
|
+
}
|
|
1094
|
+
const groupAlive = (pgid) => signalGroup(pgid, 0);
|
|
1095
|
+
/** Starts `spec` behind its gate. */
|
|
1096
|
+
function launch(spec, warn) {
|
|
1097
|
+
return WINDOWS ? launchWindows(spec) : launchPosix(spec, warn);
|
|
1098
|
+
}
|
|
1099
|
+
function stdioFor(extra) {
|
|
1100
|
+
const base = [
|
|
1101
|
+
"ignore",
|
|
1102
|
+
"pipe",
|
|
1103
|
+
"pipe",
|
|
1104
|
+
"pipe"
|
|
1105
|
+
];
|
|
1106
|
+
if (extra === "ipc") return [...base, "ipc"];
|
|
1107
|
+
if (extra === "channel") return [...base, "overlapped"];
|
|
1108
|
+
return base;
|
|
1109
|
+
}
|
|
1110
|
+
function launchPosix(spec, warn) {
|
|
1111
|
+
const child = spawn("/bin/sh", [
|
|
1112
|
+
"-c",
|
|
1113
|
+
GATE_SCRIPT,
|
|
1114
|
+
`mostra-${spec.kind}`,
|
|
1115
|
+
spec.command,
|
|
1116
|
+
...spec.args
|
|
1117
|
+
], {
|
|
1118
|
+
cwd: spec.cwd,
|
|
1119
|
+
env: spec.env,
|
|
1120
|
+
detached: true,
|
|
1121
|
+
stdio: stdioFor(spec.extra),
|
|
1122
|
+
serialization: "json"
|
|
1123
|
+
});
|
|
1124
|
+
const gate = child.stdio[3];
|
|
1125
|
+
gate?.on("error", () => {});
|
|
1126
|
+
const pid = () => child.pid ?? 0;
|
|
1127
|
+
const end = async (pgids, graceMs) => {
|
|
1128
|
+
for (const pgid of pgids) signalGroup(pgid, "SIGTERM");
|
|
1129
|
+
const deadline = Date.now() + graceMs;
|
|
1130
|
+
while (Date.now() < deadline && pgids.some(groupAlive)) await delay$1(25);
|
|
1131
|
+
for (const pgid of pgids) if (groupAlive(pgid)) signalGroup(pgid, "SIGKILL");
|
|
1132
|
+
const killDeadline = Date.now() + KILL_WAIT_MS;
|
|
1133
|
+
while (Date.now() < killDeadline && pgids.some(groupAlive)) await delay$1(10);
|
|
1134
|
+
const left = pgids.filter(groupAlive);
|
|
1135
|
+
if (left.length > 0) warn("process.group_survived_sigkill", { pgids: left });
|
|
1136
|
+
};
|
|
1137
|
+
return {
|
|
1138
|
+
process: child,
|
|
1139
|
+
async identify() {
|
|
1140
|
+
const info = await readProcess(pid());
|
|
1141
|
+
if (info) return {
|
|
1142
|
+
pid: info.pid,
|
|
1143
|
+
startTime: info.startTime
|
|
1144
|
+
};
|
|
1145
|
+
if (child.exitCode !== null || child.signalCode !== null) return void 0;
|
|
1146
|
+
throw new Error(`Couldn't read the process identity of ${spec.kind} ${pid()}.`);
|
|
1147
|
+
},
|
|
1148
|
+
release() {
|
|
1149
|
+
gate?.end("go\n");
|
|
1150
|
+
},
|
|
1151
|
+
running: () => child.exitCode === null && child.signalCode === null,
|
|
1152
|
+
end: (graceMs, extraGroups) => end([pid(), ...extraGroups], graceMs),
|
|
1153
|
+
sweep: (extraGroups) => end([pid(), ...extraGroups], 2e3),
|
|
1154
|
+
kill() {
|
|
1155
|
+
signalGroup(pid(), "SIGKILL");
|
|
1156
|
+
}
|
|
1157
|
+
};
|
|
1158
|
+
}
|
|
1159
|
+
function launchWindows(spec) {
|
|
1160
|
+
const hung = (spec.env["MOSTRA_TEST_GATE"] ?? "").split(",").includes("ignore-lifeline");
|
|
1161
|
+
const child = spawn(helperPath(), [
|
|
1162
|
+
"gate",
|
|
1163
|
+
"--",
|
|
1164
|
+
spec.command,
|
|
1165
|
+
...spec.args
|
|
1166
|
+
], {
|
|
1167
|
+
cwd: spec.cwd,
|
|
1168
|
+
env: spec.env,
|
|
1169
|
+
windowsHide: true,
|
|
1170
|
+
detached: hung,
|
|
1171
|
+
stdio: stdioFor(spec.extra),
|
|
1172
|
+
serialization: "json"
|
|
1173
|
+
});
|
|
1174
|
+
const lifeline = child.stdio[3];
|
|
1175
|
+
lifeline?.on("error", () => {});
|
|
1176
|
+
const report = new Promise((resolve, reject) => {
|
|
1177
|
+
let text = "";
|
|
1178
|
+
const onData = (chunk) => {
|
|
1179
|
+
text += chunk.toString("utf8");
|
|
1180
|
+
const end = text.indexOf("\n");
|
|
1181
|
+
if (end < 0) return;
|
|
1182
|
+
lifeline?.off("data", onData);
|
|
1183
|
+
try {
|
|
1184
|
+
const line = JSON.parse(text.slice(0, end));
|
|
1185
|
+
if (line.pid !== void 0 && line.startTime !== void 0) resolve({
|
|
1186
|
+
pid: line.pid,
|
|
1187
|
+
startTime: line.startTime
|
|
1188
|
+
});
|
|
1189
|
+
else reject(/* @__PURE__ */ new Error(`The gate couldn't start ${spec.kind}: ${line.error ?? text.slice(0, end)}`));
|
|
1190
|
+
} catch {
|
|
1191
|
+
reject(/* @__PURE__ */ new Error(`The gate of ${spec.kind} reported ${text.slice(0, 200)}`));
|
|
1192
|
+
}
|
|
1193
|
+
};
|
|
1194
|
+
lifeline?.on("data", onData);
|
|
1195
|
+
child.once("exit", () => resolve(void 0));
|
|
1196
|
+
child.once("error", reject);
|
|
1197
|
+
});
|
|
1198
|
+
const exited = new Promise((resolve) => {
|
|
1199
|
+
if (child.exitCode !== null) resolve();
|
|
1200
|
+
child.once("exit", () => resolve());
|
|
1201
|
+
});
|
|
1202
|
+
const running = () => child.exitCode === null && child.signalCode === null;
|
|
1203
|
+
return {
|
|
1204
|
+
process: child,
|
|
1205
|
+
identify: () => report,
|
|
1206
|
+
release() {
|
|
1207
|
+
lifeline?.write("go\n");
|
|
1208
|
+
},
|
|
1209
|
+
running,
|
|
1210
|
+
async end(graceMs) {
|
|
1211
|
+
lifeline?.end();
|
|
1212
|
+
if (!running()) return;
|
|
1213
|
+
let timer;
|
|
1214
|
+
await Promise.race([exited, new Promise((resolve) => timer = setTimeout(resolve, graceMs))]);
|
|
1215
|
+
clearTimeout(timer);
|
|
1216
|
+
if (running()) child.kill();
|
|
1217
|
+
await Promise.race([exited, delay$1(KILL_WAIT_MS)]);
|
|
1218
|
+
},
|
|
1219
|
+
async sweep() {},
|
|
1220
|
+
kill() {
|
|
1221
|
+
lifeline?.destroy();
|
|
1222
|
+
child.kill();
|
|
1223
|
+
}
|
|
1224
|
+
};
|
|
1225
|
+
}
|
|
1226
|
+
/**
|
|
1227
|
+
* Ends what a previous supervisor's children left running, by their recorded identities, and
|
|
1228
|
+
* leaves alone processes that only look like them (FAILURE_MODEL §2). Call it only while holding
|
|
1229
|
+
* the home's ledger lock.
|
|
1230
|
+
*/
|
|
1231
|
+
function reapRecorded(rows, warn) {
|
|
1232
|
+
return WINDOWS ? reapWindows(rows, warn) : reapPosix(rows, warn);
|
|
1233
|
+
}
|
|
1234
|
+
async function reapWindows(rows, warn) {
|
|
1235
|
+
if (rows.length === 0) return [];
|
|
1236
|
+
const answers = await runHelperAsync(["reap", ...rows.map((row) => `${row.pid}:${row.start_time}`)]);
|
|
1237
|
+
return rows.map((row, index) => {
|
|
1238
|
+
const answer = answers[index];
|
|
1239
|
+
if (answer?.error !== void 0) warn("process.reap_incomplete", {
|
|
1240
|
+
pid: row.pid,
|
|
1241
|
+
error: answer.error
|
|
1242
|
+
});
|
|
1243
|
+
const ended = answer?.ended ?? [];
|
|
1244
|
+
if (ended.length > 0) return { ended };
|
|
1245
|
+
return {
|
|
1246
|
+
ended: [],
|
|
1247
|
+
skipped: answer?.reused ? "pid reused" : "gone"
|
|
1248
|
+
};
|
|
1249
|
+
});
|
|
1250
|
+
}
|
|
1251
|
+
/** The processes of a recorded group that are provably the recorded child's. */
|
|
1252
|
+
function targetsFor(row, processes) {
|
|
1253
|
+
const leader = processes.find((info) => info.pid === row.pid);
|
|
1254
|
+
if (leader && leader.startTime !== row.start_time) return "pid reused";
|
|
1255
|
+
if (!leader) {
|
|
1256
|
+
const boot = processes.find((info) => info.pid === process.pid)?.startTime;
|
|
1257
|
+
if (boot === void 0 || !sameBoot(boot, row.start_time)) return "other boot";
|
|
1258
|
+
}
|
|
1259
|
+
const members = processes.filter((info) => info.pgid === row.pgid && info.pid !== process.pid).filter((info) => startedNoEarlier(info.startTime, row.start_time)).map((info) => info.pid);
|
|
1260
|
+
return members.length > 0 ? members : "gone";
|
|
1261
|
+
}
|
|
1262
|
+
function signalAll(pids, signal) {
|
|
1263
|
+
for (const pid of pids) try {
|
|
1264
|
+
process.kill(pid, signal);
|
|
1265
|
+
} catch {}
|
|
1266
|
+
}
|
|
1267
|
+
async function reapPosix(rows, warn) {
|
|
1268
|
+
if (rows.length === 0) return [];
|
|
1269
|
+
const before = await listProcesses();
|
|
1270
|
+
const plan = rows.map((row) => ({
|
|
1271
|
+
row,
|
|
1272
|
+
targets: targetsFor(row, before)
|
|
1273
|
+
}));
|
|
1274
|
+
const owned = plan.filter((entry) => Array.isArray(entry.targets)).map((entry) => entry.row);
|
|
1275
|
+
const members = (processes) => [...new Set(owned.flatMap((row) => {
|
|
1276
|
+
const targets = targetsFor(row, processes);
|
|
1277
|
+
return Array.isArray(targets) ? targets : [];
|
|
1278
|
+
}))];
|
|
1279
|
+
const groupsLeft = () => owned.some((row) => groupAlive(row.pgid));
|
|
1280
|
+
signalAll(members(before), "SIGTERM");
|
|
1281
|
+
const deadline = Date.now() + REAP_GRACE_MS;
|
|
1282
|
+
let remaining = members(await listProcesses());
|
|
1283
|
+
while ((remaining.length > 0 || groupsLeft()) && Date.now() < deadline) {
|
|
1284
|
+
await delay$1(100);
|
|
1285
|
+
remaining = members(await listProcesses());
|
|
1286
|
+
}
|
|
1287
|
+
const killDeadline = Date.now() + KILL_WAIT_MS;
|
|
1288
|
+
while ((remaining.length > 0 || groupsLeft()) && Date.now() < killDeadline) {
|
|
1289
|
+
signalAll(remaining, "SIGKILL");
|
|
1290
|
+
await delay$1(50);
|
|
1291
|
+
remaining = members(await listProcesses());
|
|
1292
|
+
}
|
|
1293
|
+
if (remaining.length > 0 || groupsLeft()) warn("process.reap_incomplete", {
|
|
1294
|
+
pids: remaining,
|
|
1295
|
+
pgids: owned.map((row) => row.pgid)
|
|
1296
|
+
});
|
|
1297
|
+
return plan.map(({ targets }) => Array.isArray(targets) ? { ended: targets } : {
|
|
1298
|
+
ended: [],
|
|
1299
|
+
skipped: targets
|
|
1300
|
+
});
|
|
1301
|
+
}
|
|
1302
|
+
/**
|
|
1303
|
+
* Whether `pid` can be adopted by a child whose own group is `childPgid`: on POSIX a program the
|
|
1304
|
+
* child started in its own session (a PTY program), which only a group leader is; on Windows every
|
|
1305
|
+
* descendant is already in the child's job and ends with it, so a running process needs nothing
|
|
1306
|
+
* more (it isn't recorded again).
|
|
1307
|
+
*/
|
|
1308
|
+
async function adoptable(pid) {
|
|
1309
|
+
const info = await readProcess(pid);
|
|
1310
|
+
if (!info) return void 0;
|
|
1311
|
+
if (WINDOWS) return {
|
|
1312
|
+
info,
|
|
1313
|
+
record: false
|
|
1314
|
+
};
|
|
1315
|
+
return info.pgid === info.pid ? {
|
|
1316
|
+
info,
|
|
1317
|
+
record: true
|
|
1318
|
+
} : void 0;
|
|
1319
|
+
}
|
|
1320
|
+
//#endregion
|
|
1321
|
+
//#region src/platform/control.ts
|
|
1322
|
+
/**
|
|
1323
|
+
* The home's control endpoint (D81, D82; RT-06, RT-10): how attached clients reach the
|
|
1324
|
+
* supervisor. On POSIX it is a Unix socket in the owner-only runtime directory; on Windows a named
|
|
1325
|
+
* pipe that only the user can open and that refuses remote clients, which the helper creates and
|
|
1326
|
+
* forwards to the supervisor over its descriptor 4 (`crates/mostra-win/src/win/pipe.rs`), because
|
|
1327
|
+
* Node.js's own pipes let any local user open them for reading (VERIFIED_FACTS, WP-W1).
|
|
1328
|
+
*
|
|
1329
|
+
* Either way the caller gets one stream per client and a listener it can check and replace: a
|
|
1330
|
+
* socket file that disappeared, or a pipe whose helper stopped, is bound again (D81 item 4).
|
|
1331
|
+
*/
|
|
1332
|
+
/**
|
|
1333
|
+
* The endpoint for a home. POSIX: `<runtime dir>/<home hash>.sock`, refused with
|
|
1334
|
+
* `MOSTRA_HOME_SOCKET_TOO_LONG` past the system's limit. Windows: `\\.\pipe\mostra-<home hash>`,
|
|
1335
|
+
* to which each bind adds a random part, so no other program can create the name before the
|
|
1336
|
+
* supervisor does; clients learn the full name from `instance.json`.
|
|
1337
|
+
*/
|
|
1338
|
+
function controlEndpoint(runtimeDir, hash, os = OS) {
|
|
1339
|
+
if (os === "win32" || runtimeDir === void 0) return `\\\\.\\pipe\\mostra-${hash}`;
|
|
1340
|
+
const path = pathsOf(os).join(runtimeDir, `${hash}.sock`);
|
|
1341
|
+
const limit = socketPathLimit(os);
|
|
1342
|
+
const length = Buffer.byteLength(path);
|
|
1343
|
+
if (length > limit) throw new RpcError(createDiagnostic("MOSTRA_HOME_SOCKET_TOO_LONG", {
|
|
1344
|
+
message: `The control socket path ${path} is ${length} bytes; this system allows ${limit}.`,
|
|
1345
|
+
fix: {
|
|
1346
|
+
kind: "command",
|
|
1347
|
+
command: "export MOSTRA_RUNTIME_DIR=/tmp/mostra-$USER"
|
|
1348
|
+
}
|
|
1349
|
+
}));
|
|
1350
|
+
return path;
|
|
1351
|
+
}
|
|
1352
|
+
/** Binds `endpoint` and calls `onConnection` for every client. */
|
|
1353
|
+
function listenControl(endpoint, onConnection, options = {}) {
|
|
1354
|
+
if (WINDOWS) return listenPipe(endpoint, onConnection, options.launchPipe ?? launchPipeDirectly);
|
|
1355
|
+
return listenSocket(endpoint, onConnection, options.onError ?? (() => {}));
|
|
1356
|
+
}
|
|
1357
|
+
const PIPE_PREFIX = "\\\\.\\pipe\\";
|
|
1358
|
+
/**
|
|
1359
|
+
* Starts the pipe's helper behind its gate without a process manager to record it: for a
|
|
1360
|
+
* protocol server outside an instance (the instance always records its helper).
|
|
1361
|
+
*/
|
|
1362
|
+
const launchPipeDirectly = async (name) => {
|
|
1363
|
+
const launched = launch({
|
|
1364
|
+
kind: "control-pipe",
|
|
1365
|
+
command: helperPath(),
|
|
1366
|
+
args: ["pipe", name],
|
|
1367
|
+
env: process.env,
|
|
1368
|
+
extra: "channel"
|
|
1369
|
+
}, () => {});
|
|
1370
|
+
const exited = new Promise((resolve) => launched.process.once("exit", resolve));
|
|
1371
|
+
await launched.identify();
|
|
1372
|
+
launched.release();
|
|
1373
|
+
const channel = launched.process.stdio[4];
|
|
1374
|
+
if (!channel) throw new Error("The control pipe's helper has no channel.");
|
|
1375
|
+
return {
|
|
1376
|
+
channel,
|
|
1377
|
+
exited,
|
|
1378
|
+
stop: () => launched.end(2e3, [])
|
|
1379
|
+
};
|
|
1380
|
+
};
|
|
1381
|
+
async function listenSocket(path, onConnection, onError) {
|
|
1382
|
+
mkdirSync(dirname(path), {
|
|
1383
|
+
recursive: true,
|
|
1384
|
+
mode: 448
|
|
1385
|
+
});
|
|
1386
|
+
try {
|
|
1387
|
+
unlinkSync(path);
|
|
1388
|
+
} catch (error) {
|
|
1389
|
+
if (error.code !== "ENOENT") throw error;
|
|
1390
|
+
}
|
|
1391
|
+
const server = createServer((socket) => onConnection(socket));
|
|
1392
|
+
await new Promise((resolve, reject) => {
|
|
1393
|
+
server.once("error", reject);
|
|
1394
|
+
server.listen(path, () => {
|
|
1395
|
+
server.off("error", reject);
|
|
1396
|
+
resolve();
|
|
1397
|
+
});
|
|
1398
|
+
});
|
|
1399
|
+
chmodSync(path, 384);
|
|
1400
|
+
server.on("error", onError);
|
|
1401
|
+
const stats = statSync(path);
|
|
1402
|
+
const same = () => {
|
|
1403
|
+
try {
|
|
1404
|
+
const current = statSync(path);
|
|
1405
|
+
return current.ino === stats.ino && current.dev === stats.dev;
|
|
1406
|
+
} catch {
|
|
1407
|
+
return false;
|
|
1408
|
+
}
|
|
1409
|
+
};
|
|
1410
|
+
return {
|
|
1411
|
+
path,
|
|
1412
|
+
intact: same,
|
|
1413
|
+
async close() {
|
|
1414
|
+
const ours = same();
|
|
1415
|
+
server.close();
|
|
1416
|
+
if (ours) try {
|
|
1417
|
+
unlinkSync(path);
|
|
1418
|
+
} catch {}
|
|
1419
|
+
}
|
|
1420
|
+
};
|
|
1421
|
+
}
|
|
1422
|
+
const OPEN = 1;
|
|
1423
|
+
const DATA = 2;
|
|
1424
|
+
const CLOSE = 3;
|
|
1425
|
+
const READY = 4;
|
|
1426
|
+
const FATAL = 5;
|
|
1427
|
+
/** The largest payload the supervisor sends in one frame. */
|
|
1428
|
+
const MAX_FRAME = 1 << 20;
|
|
1429
|
+
/** How long the helper may take to create the pipe. */
|
|
1430
|
+
const READY_MS = 1e4;
|
|
1431
|
+
/** How long a closing listener waits for its helper to hand clients their bytes (its own 5 s). */
|
|
1432
|
+
const DRAIN_MS = 6e3;
|
|
1433
|
+
function frame(connection, kind, payload) {
|
|
1434
|
+
const header = Buffer.alloc(9);
|
|
1435
|
+
header.writeUInt32LE(connection, 0);
|
|
1436
|
+
header[4] = kind;
|
|
1437
|
+
header.writeUInt32LE(payload?.length ?? 0, 5);
|
|
1438
|
+
return payload ? Buffer.concat([header, payload]) : header;
|
|
1439
|
+
}
|
|
1440
|
+
async function listenPipe(base, onConnection, launchPipe) {
|
|
1441
|
+
const helper = await launchPipe(`${base.startsWith(PIPE_PREFIX) ? base.slice(9) : `mostra-${createHash("sha256").update(base).digest("hex").slice(0, 16)}`}-${randomBytes(8).toString("hex")}`);
|
|
1442
|
+
const streams = /* @__PURE__ */ new Map();
|
|
1443
|
+
let exited = false;
|
|
1444
|
+
let failed = false;
|
|
1445
|
+
let path;
|
|
1446
|
+
helper.exited.then(() => {
|
|
1447
|
+
exited = true;
|
|
1448
|
+
for (const stream of streams.values()) stream.destroy();
|
|
1449
|
+
streams.clear();
|
|
1450
|
+
});
|
|
1451
|
+
const send = (bytes) => {
|
|
1452
|
+
if (!exited && !helper.channel.destroyed) helper.channel.write(bytes);
|
|
1453
|
+
};
|
|
1454
|
+
const ready = new Promise((resolve, reject) => {
|
|
1455
|
+
const timer = setTimeout(() => reject(/* @__PURE__ */ new Error("The control pipe's helper didn't create the pipe in time.")), READY_MS);
|
|
1456
|
+
let pending = Buffer.alloc(0);
|
|
1457
|
+
helper.channel.on("data", (chunk) => {
|
|
1458
|
+
pending = pending.length === 0 ? chunk : Buffer.concat([pending, chunk]);
|
|
1459
|
+
while (pending.length >= 9) {
|
|
1460
|
+
const length = pending.readUInt32LE(5);
|
|
1461
|
+
if (pending.length < 9 + length) break;
|
|
1462
|
+
const id = pending.readUInt32LE(0);
|
|
1463
|
+
const kind = pending[4];
|
|
1464
|
+
const payload = pending.subarray(9, 9 + length);
|
|
1465
|
+
pending = pending.subarray(9 + length);
|
|
1466
|
+
if (kind === READY) {
|
|
1467
|
+
clearTimeout(timer);
|
|
1468
|
+
path = payload.toString("utf8");
|
|
1469
|
+
resolve(path);
|
|
1470
|
+
} else if (kind === FATAL) {
|
|
1471
|
+
clearTimeout(timer);
|
|
1472
|
+
const why = `The control pipe can't be served: ${payload.toString("utf8")}`;
|
|
1473
|
+
if (path === void 0) reject(new Error(why));
|
|
1474
|
+
else {
|
|
1475
|
+
failed = true;
|
|
1476
|
+
helper.stop();
|
|
1477
|
+
}
|
|
1478
|
+
} else if (kind === OPEN) {
|
|
1479
|
+
const stream = clientStream(id, send, () => streams.delete(id));
|
|
1480
|
+
streams.set(id, stream);
|
|
1481
|
+
onConnection(stream);
|
|
1482
|
+
} else if (kind === DATA) streams.get(id)?.push(Buffer.from(payload));
|
|
1483
|
+
else if (kind === CLOSE) {
|
|
1484
|
+
const stream = streams.get(id);
|
|
1485
|
+
streams.delete(id);
|
|
1486
|
+
if (stream) {
|
|
1487
|
+
stream.push(null);
|
|
1488
|
+
stream.end();
|
|
1489
|
+
}
|
|
1490
|
+
}
|
|
1491
|
+
}
|
|
1492
|
+
});
|
|
1493
|
+
helper.exited.then(() => {
|
|
1494
|
+
clearTimeout(timer);
|
|
1495
|
+
reject(/* @__PURE__ */ new Error("The control pipe's helper exited."));
|
|
1496
|
+
});
|
|
1497
|
+
});
|
|
1498
|
+
helper.channel.on("error", () => {});
|
|
1499
|
+
let bound;
|
|
1500
|
+
try {
|
|
1501
|
+
bound = await ready;
|
|
1502
|
+
} catch (error) {
|
|
1503
|
+
await helper.stop();
|
|
1504
|
+
throw error;
|
|
1505
|
+
}
|
|
1506
|
+
return {
|
|
1507
|
+
path: bound,
|
|
1508
|
+
intact: () => !exited && !failed,
|
|
1509
|
+
async close() {
|
|
1510
|
+
for (const stream of streams.values()) stream.end();
|
|
1511
|
+
if (!exited) send(frame(0, CLOSE));
|
|
1512
|
+
let timer;
|
|
1513
|
+
await Promise.race([helper.exited, new Promise((resolve) => {
|
|
1514
|
+
timer = setTimeout(resolve, DRAIN_MS);
|
|
1515
|
+
})]);
|
|
1516
|
+
clearTimeout(timer);
|
|
1517
|
+
for (const stream of streams.values()) stream.destroy();
|
|
1518
|
+
streams.clear();
|
|
1519
|
+
await helper.stop();
|
|
1520
|
+
}
|
|
1521
|
+
};
|
|
1522
|
+
}
|
|
1523
|
+
/** One client's stream over the helper's channel. */
|
|
1524
|
+
function clientStream(id, send, forget) {
|
|
1525
|
+
let closed = false;
|
|
1526
|
+
const close = () => {
|
|
1527
|
+
if (closed) return;
|
|
1528
|
+
closed = true;
|
|
1529
|
+
forget();
|
|
1530
|
+
send(frame(id, CLOSE));
|
|
1531
|
+
};
|
|
1532
|
+
return new Duplex({
|
|
1533
|
+
read() {},
|
|
1534
|
+
write(chunk, _encoding, callback) {
|
|
1535
|
+
for (let offset = 0; offset < chunk.length; offset += MAX_FRAME) send(frame(id, DATA, chunk.subarray(offset, offset + MAX_FRAME)));
|
|
1536
|
+
callback();
|
|
1537
|
+
},
|
|
1538
|
+
final(callback) {
|
|
1539
|
+
close();
|
|
1540
|
+
callback();
|
|
1541
|
+
},
|
|
1542
|
+
destroy(error, callback) {
|
|
1543
|
+
close();
|
|
1544
|
+
callback(error);
|
|
1545
|
+
}
|
|
1546
|
+
});
|
|
1547
|
+
}
|
|
1548
|
+
/** Why a client couldn't open a control endpoint. */
|
|
1549
|
+
var ControlConnectError = class extends Error {
|
|
1550
|
+
/** `unreachable` (nothing serves it, or it timed out) or `not-owned` (another user's pipe). */
|
|
1551
|
+
reason;
|
|
1552
|
+
constructor(reason, message) {
|
|
1553
|
+
super(message);
|
|
1554
|
+
this.name = "ControlConnectError";
|
|
1555
|
+
this.reason = reason;
|
|
1556
|
+
}
|
|
1557
|
+
};
|
|
1558
|
+
/**
|
|
1559
|
+
* Connects to a home's control endpoint as a client. On Windows through `mostra-win connect`,
|
|
1560
|
+
* which refuses a pipe another user created under the name (an old name `instance.json` still
|
|
1561
|
+
* names may be free for anyone to take), and never lets the server act as this process: Node.js
|
|
1562
|
+
* can check neither (Opus review of WP-W1). Rejects with a {@link ControlConnectError}.
|
|
850
1563
|
*/
|
|
851
|
-
function
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
|
|
1564
|
+
function connectControl(endpoint, timeoutMs = 5e3) {
|
|
1565
|
+
return WINDOWS ? connectPipe(endpoint, timeoutMs) : connectSocket$1(endpoint, timeoutMs);
|
|
1566
|
+
}
|
|
1567
|
+
function connectSocket$1(path, timeoutMs) {
|
|
1568
|
+
return new Promise((resolve, reject) => {
|
|
1569
|
+
const socket = createConnection(path);
|
|
1570
|
+
const timer = setTimeout(() => {
|
|
1571
|
+
socket.destroy();
|
|
1572
|
+
reject(new ControlConnectError("unreachable", "timed out"));
|
|
1573
|
+
}, timeoutMs);
|
|
1574
|
+
socket.once("error", (error) => {
|
|
1575
|
+
clearTimeout(timer);
|
|
1576
|
+
reject(new ControlConnectError("unreachable", error.code ?? "failed"));
|
|
1577
|
+
});
|
|
1578
|
+
socket.once("connect", () => {
|
|
1579
|
+
clearTimeout(timer);
|
|
1580
|
+
resolve(socket);
|
|
1581
|
+
});
|
|
1582
|
+
});
|
|
1583
|
+
}
|
|
1584
|
+
function connectPipe(endpoint, timeoutMs) {
|
|
1585
|
+
const name = endpoint.startsWith(PIPE_PREFIX) ? endpoint.slice(9) : endpoint;
|
|
1586
|
+
return new Promise((resolve, reject) => {
|
|
1587
|
+
const child = spawn(helperPath(), ["connect", name], {
|
|
1588
|
+
stdio: [
|
|
1589
|
+
"pipe",
|
|
1590
|
+
"pipe",
|
|
1591
|
+
"pipe"
|
|
1592
|
+
],
|
|
1593
|
+
windowsHide: true
|
|
1594
|
+
});
|
|
1595
|
+
let settled = false;
|
|
1596
|
+
const fail = (reason, message) => {
|
|
1597
|
+
if (settled) return;
|
|
1598
|
+
settled = true;
|
|
1599
|
+
clearTimeout(timer);
|
|
1600
|
+
child.kill();
|
|
1601
|
+
reject(new ControlConnectError(reason, message));
|
|
1602
|
+
};
|
|
1603
|
+
const timer = setTimeout(() => fail("unreachable", "timed out"), timeoutMs);
|
|
1604
|
+
child.once("error", (error) => fail("unreachable", error.message));
|
|
1605
|
+
child.once("exit", (code) => fail(code === 3 ? "not-owned" : "unreachable", `exit ${code}`));
|
|
1606
|
+
let text = "";
|
|
1607
|
+
child.stderr.setEncoding("utf8");
|
|
1608
|
+
child.stderr.on("data", (chunk) => {
|
|
1609
|
+
if (settled) return;
|
|
1610
|
+
text += chunk;
|
|
1611
|
+
const end = text.indexOf("\n");
|
|
1612
|
+
if (end < 0) return;
|
|
1613
|
+
let line = {};
|
|
1614
|
+
try {
|
|
1615
|
+
line = JSON.parse(text.slice(0, end));
|
|
1616
|
+
} catch {}
|
|
1617
|
+
if (line.connected !== true) {
|
|
1618
|
+
fail(line.code === "not-owned" ? "not-owned" : "unreachable", line.error ?? text.slice(0, end));
|
|
1619
|
+
return;
|
|
1620
|
+
}
|
|
1621
|
+
settled = true;
|
|
1622
|
+
clearTimeout(timer);
|
|
1623
|
+
resolve(Duplex.from({
|
|
1624
|
+
readable: child.stdout,
|
|
1625
|
+
writable: child.stdin
|
|
1626
|
+
}));
|
|
1627
|
+
});
|
|
1628
|
+
});
|
|
1629
|
+
}
|
|
1630
|
+
//#endregion
|
|
1631
|
+
//#region src/platform/environment.ts
|
|
1632
|
+
/**
|
|
1633
|
+
* The smallest environment a child can run in (the builder's): `PATH`, `HOME` and `TMPDIR` on
|
|
1634
|
+
* POSIX. Windows programs need more of what Windows itself gives every program (without
|
|
1635
|
+
* `SystemRoot` Node.js can't load its cryptography, without `TEMP` it has no temporary folder),
|
|
1636
|
+
* and Windows compares variable names without case, so they are found that way.
|
|
1637
|
+
*/
|
|
1638
|
+
/**
|
|
1639
|
+
* What Windows itself gives every program and programs rely on, besides `Path`: the system's
|
|
1640
|
+
* directories, the user's profile folders, the shell and how it finds programs, who the user is
|
|
1641
|
+
* and the processor. None names a secret. The one list both the base and the artifact environment
|
|
1642
|
+
* pass on Windows (`processes/environment.ts`).
|
|
1643
|
+
*/
|
|
1644
|
+
const WINDOWS_SYSTEM_VARIABLES = [
|
|
1645
|
+
"SystemRoot",
|
|
1646
|
+
"SystemDrive",
|
|
1647
|
+
"windir",
|
|
1648
|
+
"ComSpec",
|
|
1649
|
+
"PATHEXT",
|
|
1650
|
+
"TEMP",
|
|
1651
|
+
"TMP",
|
|
1652
|
+
"USERPROFILE",
|
|
1653
|
+
"HOMEDRIVE",
|
|
1654
|
+
"HOMEPATH",
|
|
1655
|
+
"APPDATA",
|
|
1656
|
+
"LOCALAPPDATA",
|
|
1657
|
+
"ProgramData",
|
|
1658
|
+
"ProgramFiles",
|
|
1659
|
+
"ProgramFiles(x86)",
|
|
1660
|
+
"ProgramW6432",
|
|
1661
|
+
"CommonProgramFiles",
|
|
1662
|
+
"CommonProgramFiles(x86)",
|
|
1663
|
+
"CommonProgramW6432",
|
|
1664
|
+
"USERNAME",
|
|
1665
|
+
"USERDOMAIN",
|
|
1666
|
+
"COMPUTERNAME",
|
|
1667
|
+
"OS",
|
|
1668
|
+
"NUMBER_OF_PROCESSORS",
|
|
1669
|
+
"PROCESSOR_ARCHITECTURE",
|
|
1670
|
+
"PROCESSOR_IDENTIFIER"
|
|
1671
|
+
];
|
|
1672
|
+
const WINDOWS_BASE = ["Path", ...WINDOWS_SYSTEM_VARIABLES];
|
|
1673
|
+
/** The base environment of a child, from the supervisor's `env`. */
|
|
1674
|
+
function baseEnvironment(env) {
|
|
1675
|
+
if (!WINDOWS) return {
|
|
1676
|
+
PATH: env["PATH"] ?? "/usr/bin:/bin",
|
|
1677
|
+
HOME: env["HOME"] ?? "/",
|
|
1678
|
+
...env["TMPDIR"] ? { TMPDIR: env["TMPDIR"] } : {}
|
|
1679
|
+
};
|
|
1680
|
+
const byName = new Map(Object.entries(env).map(([name, value]) => [name.toUpperCase(), value]));
|
|
1681
|
+
const result = {};
|
|
1682
|
+
for (const name of WINDOWS_BASE) {
|
|
1683
|
+
const value = byName.get(name.toUpperCase());
|
|
1684
|
+
if (value !== void 0) result[name] = value;
|
|
859
1685
|
}
|
|
860
|
-
return
|
|
1686
|
+
return result;
|
|
861
1687
|
}
|
|
862
1688
|
/** Packages whose versions define the SPA build; they are part of `buildConfigDigest` (VR-01). */
|
|
863
1689
|
const BUILD_PACKAGES = [
|
|
@@ -872,7 +1698,7 @@ const BUILD_PACKAGES = [
|
|
|
872
1698
|
/** Bumped whenever the SPA build's settings change, so older versions aren't reused. */
|
|
873
1699
|
const SPA_CONFIG_REVISION = 7;
|
|
874
1700
|
/** The directory of `@mostra/runtime`'s package.json. */
|
|
875
|
-
function runtimeRoot
|
|
1701
|
+
function runtimeRoot() {
|
|
876
1702
|
let dir = dirname(fileURLToPath(import.meta.url));
|
|
877
1703
|
for (;;) {
|
|
878
1704
|
const manifest = join(dir, "package.json");
|
|
@@ -905,7 +1731,7 @@ function childEntry$1(root) {
|
|
|
905
1731
|
}
|
|
906
1732
|
/** The SPA render mode (D19): every build in its own builder child. */
|
|
907
1733
|
function createSpaRenderMode(options) {
|
|
908
|
-
const root = runtimeRoot
|
|
1734
|
+
const root = runtimeRoot();
|
|
909
1735
|
const buildPackages = {};
|
|
910
1736
|
for (const name of BUILD_PACKAGES) {
|
|
911
1737
|
const dir = packageDir(name, root);
|
|
@@ -921,12 +1747,9 @@ function createSpaRenderMode(options) {
|
|
|
921
1747
|
stagingFiles: STAGING_FILES
|
|
922
1748
|
};
|
|
923
1749
|
const timeoutMs = options.timeoutMs ?? 18e4;
|
|
924
|
-
const env = options.env ?? process.env;
|
|
925
1750
|
const childEnv = {
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
NODE_ENV: "production",
|
|
929
|
-
...env["TMPDIR"] ? { TMPDIR: env["TMPDIR"] } : {}
|
|
1751
|
+
...baseEnvironment(options.env ?? process.env),
|
|
1752
|
+
NODE_ENV: "production"
|
|
930
1753
|
};
|
|
931
1754
|
return {
|
|
932
1755
|
id: "spa",
|
|
@@ -1114,13 +1937,17 @@ function faultsFrom(env) {
|
|
|
1114
1937
|
const separator = entry.lastIndexOf(":");
|
|
1115
1938
|
const point = entry.slice(0, separator).trim();
|
|
1116
1939
|
const action = entry.slice(separator + 1).trim();
|
|
1117
|
-
if (point && (action === "throw" || action === "crash" || action === "hang")) configured.set(point, action);
|
|
1940
|
+
if (point && (action === "throw" || action === "throw-once" || action === "crash" || action === "hang")) configured.set(point, action);
|
|
1118
1941
|
}
|
|
1119
1942
|
return {
|
|
1120
1943
|
hangs: (point) => configured.get(point) === "hang",
|
|
1121
1944
|
at(point) {
|
|
1122
1945
|
const action = configured.get(point);
|
|
1123
1946
|
if (action === "throw") throw new InjectedFault(point);
|
|
1947
|
+
if (action === "throw-once") {
|
|
1948
|
+
configured.delete(point);
|
|
1949
|
+
throw new InjectedFault(point);
|
|
1950
|
+
}
|
|
1124
1951
|
if (action === "crash") {
|
|
1125
1952
|
process.kill(process.pid, "SIGKILL");
|
|
1126
1953
|
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 1e4);
|
|
@@ -1755,12 +2582,7 @@ function createLedgerFile(storeDir, file, log) {
|
|
|
1755
2582
|
} finally {
|
|
1756
2583
|
db.close();
|
|
1757
2584
|
}
|
|
1758
|
-
|
|
1759
|
-
try {
|
|
1760
|
-
fsyncSync(fd);
|
|
1761
|
-
} finally {
|
|
1762
|
-
closeSync(fd);
|
|
1763
|
-
}
|
|
2585
|
+
fsyncPath(temp);
|
|
1764
2586
|
try {
|
|
1765
2587
|
linkSync(temp, file);
|
|
1766
2588
|
log.info("ledger.created", { file });
|
|
@@ -1772,14 +2594,7 @@ function createLedgerFile(storeDir, file, log) {
|
|
|
1772
2594
|
syncDirectory(storeDir);
|
|
1773
2595
|
}
|
|
1774
2596
|
function syncDirectory(dir) {
|
|
1775
|
-
|
|
1776
|
-
const fd = openSync(dir, "r");
|
|
1777
|
-
try {
|
|
1778
|
-
fsyncSync(fd);
|
|
1779
|
-
} finally {
|
|
1780
|
-
closeSync(fd);
|
|
1781
|
-
}
|
|
1782
|
-
} catch {}
|
|
2597
|
+
fsyncPath(dir, true);
|
|
1783
2598
|
}
|
|
1784
2599
|
/**
|
|
1785
2600
|
* Removes `*.creating` files left by starters that died while building a ledger. A file whose
|
|
@@ -2032,6 +2847,9 @@ const PASSED = /* @__PURE__ */ new Set([
|
|
|
2032
2847
|
"SSL_CERT_FILE",
|
|
2033
2848
|
"SSL_CERT_DIR"
|
|
2034
2849
|
]);
|
|
2850
|
+
/** What Windows programs need besides the variables above (`platform`'s one list). */
|
|
2851
|
+
const PASSED_WINDOWS = new Set(WINDOWS_SYSTEM_VARIABLES.map((name) => name.toUpperCase()));
|
|
2852
|
+
const PASSED_UPPER = new Set([...PASSED].map((name) => name.toUpperCase()));
|
|
2035
2853
|
/** npm's own configuration channel: the user's registry, scopes and proxies for installs. */
|
|
2036
2854
|
const NPM_CONFIG = /^npm_config_/i;
|
|
2037
2855
|
/**
|
|
@@ -2041,207 +2859,35 @@ const NPM_CONFIG = /^npm_config_/i;
|
|
|
2041
2859
|
*/
|
|
2042
2860
|
function artifactEnvironment(env) {
|
|
2043
2861
|
const result = {};
|
|
2862
|
+
let pathName = "PATH";
|
|
2044
2863
|
for (const [name, value] of Object.entries(env)) {
|
|
2045
2864
|
if (value === void 0) continue;
|
|
2046
|
-
if (
|
|
2865
|
+
if (WINDOWS) {
|
|
2866
|
+
const upper = name.toUpperCase();
|
|
2867
|
+
if (upper === "PATH") pathName = name;
|
|
2868
|
+
if (PASSED_UPPER.has(upper) || PASSED_WINDOWS.has(upper) || NPM_CONFIG.test(name)) result[name] = value;
|
|
2869
|
+
} else if (PASSED.has(name) || NPM_CONFIG.test(name)) result[name] = value;
|
|
2047
2870
|
}
|
|
2048
2871
|
const own = dirname(process.execPath);
|
|
2049
|
-
const path = result[
|
|
2050
|
-
|
|
2872
|
+
const path = result[pathName] ?? (WINDOWS ? "" : "/usr/bin:/bin");
|
|
2873
|
+
const first = path.split(delimiter)[0] ?? "";
|
|
2874
|
+
const already = WINDOWS ? first.toLowerCase() === own.toLowerCase() : first === own;
|
|
2875
|
+
result[pathName] = already ? path : path === "" ? own : `${own}${delimiter}${path}`;
|
|
2051
2876
|
return result;
|
|
2052
2877
|
}
|
|
2053
2878
|
//#endregion
|
|
2054
|
-
//#region src/processes/identity.ts
|
|
2055
|
-
/**
|
|
2056
|
-
* Process identity (DATA_MODEL §3 `child.start_time`, FAILURE_MODEL §2). A PID alone can be
|
|
2057
|
-
* reused, so a process is identified by its PID plus an opaque start time: the boot it started in
|
|
2058
|
-
* and when it started within that boot. Linux reads `/proc/<pid>/stat` (start ticks since boot)
|
|
2059
|
-
* and the boot ID; macOS reads `ps -o lstart` (seconds) and `kern.boottime` (VERIFIED_FACTS,
|
|
2060
|
-
* WP-02). Zombies count as gone: they have exited and only wait for their parent.
|
|
2061
|
-
*
|
|
2062
|
-
* Seconds are enough on macOS (issue #8): XNU hands out PIDs in order from the last one, up to
|
|
2063
|
-
* 99,999, then from 100, skipping any PID still used as a process, process group or session
|
|
2064
|
-
* (`forkproc` in `bsd/kern/kern_fork.c`). A PID comes back only after the whole range has been
|
|
2065
|
-
* handed out, about 99,900 forks, which takes this machine about 100 s at its measured 1,000
|
|
2066
|
-
* spawns a second, and never while its process group lives (VERIFIED_FACTS, WP-08).
|
|
2067
|
-
*/
|
|
2068
|
-
/** Splits a start time into its boot and its position within the boot. */
|
|
2069
|
-
function parts(startTime) {
|
|
2070
|
-
const slash = startTime.lastIndexOf("/");
|
|
2071
|
-
if (slash <= 0) return void 0;
|
|
2072
|
-
const at = Number(startTime.slice(slash + 1));
|
|
2073
|
-
return Number.isSafeInteger(at) ? {
|
|
2074
|
-
boot: startTime.slice(0, slash),
|
|
2075
|
-
at
|
|
2076
|
-
} : void 0;
|
|
2077
|
-
}
|
|
2078
|
-
/** Whether two start times belong to the same boot of the machine. */
|
|
2079
|
-
function sameBoot(a, b) {
|
|
2080
|
-
const left = parts(a);
|
|
2081
|
-
const right = parts(b);
|
|
2082
|
-
return left !== void 0 && right !== void 0 && left.boot === right.boot;
|
|
2083
|
-
}
|
|
2084
|
-
/**
|
|
2085
|
-
* Whether `candidate` started in the same boot as `reference` and no earlier. On macOS the
|
|
2086
|
-
* resolution is one second, so a process started in the same second counts as no earlier.
|
|
2087
|
-
*/
|
|
2088
|
-
function startedNoEarlier(candidate, reference) {
|
|
2089
|
-
const c = parts(candidate);
|
|
2090
|
-
const r = parts(reference);
|
|
2091
|
-
return c !== void 0 && r !== void 0 && c.boot === r.boot && c.at >= r.at;
|
|
2092
|
-
}
|
|
2093
|
-
/** Parses one `/proc/<pid>/stat` line. `comm` may contain spaces and parentheses. */
|
|
2094
|
-
function parseProcStat(line, boot) {
|
|
2095
|
-
const open = line.indexOf("(");
|
|
2096
|
-
const close = line.lastIndexOf(")");
|
|
2097
|
-
if (open < 0 || close < open) return void 0;
|
|
2098
|
-
const pid = Number(line.slice(0, open).trim());
|
|
2099
|
-
const rest = line.slice(close + 1).trim().split(/\s+/);
|
|
2100
|
-
if (rest[0] === "Z") return void 0;
|
|
2101
|
-
const pgid = Number(rest[2]);
|
|
2102
|
-
const start = rest[19];
|
|
2103
|
-
if (!Number.isSafeInteger(pid) || !Number.isSafeInteger(pgid) || start === void 0) return;
|
|
2104
|
-
if (!/^\d+$/.test(start)) return void 0;
|
|
2105
|
-
return {
|
|
2106
|
-
pid,
|
|
2107
|
-
pgid,
|
|
2108
|
-
startTime: `${boot}/${start}`
|
|
2109
|
-
};
|
|
2110
|
-
}
|
|
2111
|
-
const MONTHS = [
|
|
2112
|
-
"Jan",
|
|
2113
|
-
"Feb",
|
|
2114
|
-
"Mar",
|
|
2115
|
-
"Apr",
|
|
2116
|
-
"May",
|
|
2117
|
-
"Jun",
|
|
2118
|
-
"Jul",
|
|
2119
|
-
"Aug",
|
|
2120
|
-
"Sep",
|
|
2121
|
-
"Oct",
|
|
2122
|
-
"Nov",
|
|
2123
|
-
"Dec"
|
|
2124
|
-
];
|
|
2125
|
-
/**
|
|
2126
|
-
* Parses one line of `LC_ALL=C TZ=UTC ps -o pid=,pgid=,stat=,lstart=`, such as
|
|
2127
|
-
* ` 214 99444 Ss Tue Oct 6 13:53:19 2026`. Zombies (`stat` starting with `Z`) are skipped.
|
|
2128
|
-
*/
|
|
2129
|
-
function parsePsLine(line, boot) {
|
|
2130
|
-
const fields = line.trim().split(/\s+/);
|
|
2131
|
-
if (fields.length < 8) return void 0;
|
|
2132
|
-
const [pidText, pgidText, stat, , monthText, dayText, timeText, yearText] = fields;
|
|
2133
|
-
if (stat?.startsWith("Z")) return void 0;
|
|
2134
|
-
const pid = Number(pidText);
|
|
2135
|
-
const pgid = Number(pgidText);
|
|
2136
|
-
const month = MONTHS.indexOf(monthText ?? "");
|
|
2137
|
-
const [hours, minutes, seconds] = (timeText ?? "").split(":").map(Number);
|
|
2138
|
-
const millis = Date.UTC(Number(yearText), month, Number(dayText), hours ?? NaN, minutes ?? NaN, seconds ?? NaN);
|
|
2139
|
-
if (!Number.isSafeInteger(pid) || !Number.isSafeInteger(pgid) || month < 0 || Number.isNaN(millis)) return;
|
|
2140
|
-
return {
|
|
2141
|
-
pid,
|
|
2142
|
-
pgid,
|
|
2143
|
-
startTime: `${boot}/${millis / 1e3}`
|
|
2144
|
-
};
|
|
2145
|
-
}
|
|
2146
|
-
function run$1(file, args) {
|
|
2147
|
-
return new Promise((resolve, reject) => {
|
|
2148
|
-
execFile(file, args, {
|
|
2149
|
-
env: {
|
|
2150
|
-
LC_ALL: "C",
|
|
2151
|
-
TZ: "UTC",
|
|
2152
|
-
PATH: "/usr/bin:/bin:/usr/sbin:/sbin"
|
|
2153
|
-
},
|
|
2154
|
-
maxBuffer: 67108864
|
|
2155
|
-
}, (error, stdout) => {
|
|
2156
|
-
if (error && typeof error.code !== "number") {
|
|
2157
|
-
reject(error);
|
|
2158
|
-
return;
|
|
2159
|
-
}
|
|
2160
|
-
resolve({
|
|
2161
|
-
code: typeof error?.code === "number" ? error.code : 0,
|
|
2162
|
-
stdout
|
|
2163
|
-
});
|
|
2164
|
-
});
|
|
2165
|
-
});
|
|
2166
|
-
}
|
|
2167
|
-
let cachedBoot;
|
|
2168
|
-
/** The identity of the current boot of this machine. */
|
|
2169
|
-
function bootId() {
|
|
2170
|
-
cachedBoot ??= (async () => {
|
|
2171
|
-
if (process.platform === "linux") return (await readFile("/proc/sys/kernel/random/boot_id", "utf8")).trim();
|
|
2172
|
-
const { stdout } = await run$1("/usr/sbin/sysctl", ["-n", "kern.boottime"]);
|
|
2173
|
-
const match = /sec = (\d+), usec = (\d+)/.exec(stdout);
|
|
2174
|
-
if (!match) throw new Error("Couldn't read kern.boottime.");
|
|
2175
|
-
return `${match[1]}.${match[2]}`;
|
|
2176
|
-
})();
|
|
2177
|
-
return cachedBoot;
|
|
2178
|
-
}
|
|
2179
|
-
/** Reads one process, or `undefined` when no process has that PID. */
|
|
2180
|
-
async function readProcess(pid) {
|
|
2181
|
-
const boot = await bootId();
|
|
2182
|
-
if (process.platform === "linux") try {
|
|
2183
|
-
return parseProcStat(await readFile(`/proc/${pid}/stat`, "utf8"), boot);
|
|
2184
|
-
} catch {
|
|
2185
|
-
return;
|
|
2186
|
-
}
|
|
2187
|
-
const { code, stdout } = await run$1("/bin/ps", [
|
|
2188
|
-
"-o",
|
|
2189
|
-
"pid=,pgid=,stat=,lstart=",
|
|
2190
|
-
"-p",
|
|
2191
|
-
String(pid)
|
|
2192
|
-
]);
|
|
2193
|
-
if (code !== 0) return void 0;
|
|
2194
|
-
const [line] = stdout.split("\n").filter((text) => text.trim() !== "");
|
|
2195
|
-
return line === void 0 ? void 0 : parsePsLine(line, boot);
|
|
2196
|
-
}
|
|
2197
|
-
/** Lists every process the user can see. */
|
|
2198
|
-
async function listProcesses() {
|
|
2199
|
-
const boot = await bootId();
|
|
2200
|
-
if (process.platform === "linux") {
|
|
2201
|
-
const entries = (await readdir("/proc")).filter((name) => /^\d+$/.test(name));
|
|
2202
|
-
return (await Promise.all(entries.map(async (name) => {
|
|
2203
|
-
try {
|
|
2204
|
-
return parseProcStat(await readFile(`/proc/${name}/stat`, "utf8"), boot);
|
|
2205
|
-
} catch {
|
|
2206
|
-
return;
|
|
2207
|
-
}
|
|
2208
|
-
}))).filter((info) => info !== void 0);
|
|
2209
|
-
}
|
|
2210
|
-
const { stdout } = await run$1("/bin/ps", [
|
|
2211
|
-
"-A",
|
|
2212
|
-
"-o",
|
|
2213
|
-
"pid=,pgid=,stat=,lstart="
|
|
2214
|
-
]);
|
|
2215
|
-
return stdout.split("\n").map((line) => parsePsLine(line, boot)).filter((info) => info !== void 0);
|
|
2216
|
-
}
|
|
2217
|
-
/** Whether the process recorded as `pid` and `startTime` is still the one running. */
|
|
2218
|
-
async function isSameProcess(pid, startTime) {
|
|
2219
|
-
const info = await readProcess(pid);
|
|
2220
|
-
return info !== void 0 && info.startTime === startTime;
|
|
2221
|
-
}
|
|
2222
|
-
//#endregion
|
|
2223
2879
|
//#region src/processes/manager.ts
|
|
2224
2880
|
/**
|
|
2225
|
-
* The process manager (RT-09, ARCHITECTURE §4, FAILURE_MODEL §2). Every child
|
|
2226
|
-
*
|
|
2227
|
-
*
|
|
2228
|
-
*
|
|
2229
|
-
|
|
2230
|
-
/** How long a stopping child gets between SIGTERM and SIGKILL, by default. */
|
|
2231
|
-
const DEFAULT_GRACE_MS = 5e3;
|
|
2232
|
-
/** How long reaping waits between SIGTERM and SIGKILL. */
|
|
2233
|
-
const REAP_GRACE_MS = 2e3;
|
|
2234
|
-
/** How long to wait for SIGKILLed processes to disappear before reporting them. */
|
|
2235
|
-
const KILL_WAIT_MS = 5e3;
|
|
2236
|
-
/** How many stderr lines a child's exit report keeps. */
|
|
2237
|
-
const STDERR_TAIL = 50;
|
|
2238
|
-
/**
|
|
2239
|
-
* The gate every child starts behind (issue #7): `/bin/sh` waits for "go" on file descriptor 3 and
|
|
2240
|
-
* only then replaces itself with the real command, keeping its PID, process group and start time.
|
|
2241
|
-
* The supervisor writes "go" after it has recorded the child, so a supervisor killed in between
|
|
2242
|
-
* leaves a gate that reads end-of-file and exits 125 without running anything.
|
|
2881
|
+
* The process manager (RT-09, RT-10, ARCHITECTURE §4, FAILURE_MODEL §2). Every child starts
|
|
2882
|
+
* behind a gate in a group of its own (a process group on POSIX, a Job Object on Windows,
|
|
2883
|
+
* `platform/launch.ts`) and is recorded in the ledger's `child` table with its PID and start
|
|
2884
|
+
* time before it may run. A child's group dies with it, and a supervisor that starts after a
|
|
2885
|
+
* crash reaps every recorded group that is still running.
|
|
2243
2886
|
*/
|
|
2244
|
-
|
|
2887
|
+
/** How long a stopping child gets between SIGTERM and SIGKILL, by default. */
|
|
2888
|
+
const DEFAULT_GRACE_MS = 5e3;
|
|
2889
|
+
/** How many stderr lines a child's exit report keeps. */
|
|
2890
|
+
const STDERR_TAIL = 50;
|
|
2245
2891
|
const AdoptParams = z.object({ pid: z.int().min(2) });
|
|
2246
2892
|
/**
|
|
2247
2893
|
* Opens the process manager: first reaps every child a previous supervisor of this home left
|
|
@@ -2249,28 +2895,12 @@ const AdoptParams = z.object({ pid: z.int().min(2) });
|
|
|
2249
2895
|
* ledger lock, so no live supervisor's children are touched.
|
|
2250
2896
|
*/
|
|
2251
2897
|
async function openProcessManager(options) {
|
|
2252
|
-
const reaped = await
|
|
2898
|
+
const reaped = await reap(options.ledger, options.log);
|
|
2253
2899
|
return {
|
|
2254
2900
|
manager: createManager(options),
|
|
2255
2901
|
reaped
|
|
2256
2902
|
};
|
|
2257
2903
|
}
|
|
2258
|
-
/** Signals `pids`, ignoring ones already gone. */
|
|
2259
|
-
function signalAll(pids, signal) {
|
|
2260
|
-
for (const pid of pids) try {
|
|
2261
|
-
process.kill(pid, signal);
|
|
2262
|
-
} catch {}
|
|
2263
|
-
}
|
|
2264
|
-
function signalGroup(pgid, signal) {
|
|
2265
|
-
try {
|
|
2266
|
-
process.kill(-pgid, signal);
|
|
2267
|
-
return true;
|
|
2268
|
-
} catch {
|
|
2269
|
-
return false;
|
|
2270
|
-
}
|
|
2271
|
-
}
|
|
2272
|
-
const groupAlive = (pgid) => signalGroup(pgid, 0);
|
|
2273
|
-
const delay$1 = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
2274
2904
|
/** Waits for `promise` to settle, or `ms` at most, leaving no timer behind. */
|
|
2275
2905
|
async function settleWithin(promise, ms) {
|
|
2276
2906
|
let timer;
|
|
@@ -2282,64 +2912,27 @@ async function settleWithin(promise, ms) {
|
|
|
2282
2912
|
clearTimeout(timer);
|
|
2283
2913
|
}
|
|
2284
2914
|
}
|
|
2285
|
-
|
|
2286
|
-
function targetsFor(row, processes) {
|
|
2287
|
-
const leader = processes.find((info) => info.pid === row.pid);
|
|
2288
|
-
if (leader && leader.startTime !== row.start_time) return "pid reused";
|
|
2289
|
-
if (!leader) {
|
|
2290
|
-
const boot = processes.find((info) => info.pid === process.pid)?.startTime;
|
|
2291
|
-
if (boot === void 0 || !sameBoot(boot, row.start_time)) return "other boot";
|
|
2292
|
-
}
|
|
2293
|
-
const members = processes.filter((info) => info.pgid === row.pgid && info.pid !== process.pid).filter((info) => startedNoEarlier(info.startTime, row.start_time)).map((info) => info.pid);
|
|
2294
|
-
return members.length > 0 ? members : "gone";
|
|
2295
|
-
}
|
|
2296
|
-
async function reapRecorded(ledger, log) {
|
|
2915
|
+
async function reap(ledger, log) {
|
|
2297
2916
|
const rows = ledger.read((db) => db.all("SELECT * FROM child ORDER BY started_at"));
|
|
2298
2917
|
if (rows.length === 0) return [];
|
|
2299
|
-
const
|
|
2300
|
-
const plan = rows.map((row) => ({
|
|
2301
|
-
row,
|
|
2302
|
-
targets: targetsFor(row, before)
|
|
2303
|
-
}));
|
|
2304
|
-
const owned = plan.filter((entry) => Array.isArray(entry.targets)).map((entry) => entry.row);
|
|
2305
|
-
const members = (processes) => [...new Set(owned.flatMap((row) => {
|
|
2306
|
-
const targets = targetsFor(row, processes);
|
|
2307
|
-
return Array.isArray(targets) ? targets : [];
|
|
2308
|
-
}))];
|
|
2309
|
-
const groupsLeft = () => owned.some((row) => groupAlive(row.pgid));
|
|
2310
|
-
signalAll(members(before), "SIGTERM");
|
|
2311
|
-
const deadline = Date.now() + REAP_GRACE_MS;
|
|
2312
|
-
let remaining = members(await listProcesses());
|
|
2313
|
-
while ((remaining.length > 0 || groupsLeft()) && Date.now() < deadline) {
|
|
2314
|
-
await delay$1(100);
|
|
2315
|
-
remaining = members(await listProcesses());
|
|
2316
|
-
}
|
|
2317
|
-
const killDeadline = Date.now() + KILL_WAIT_MS;
|
|
2318
|
-
while ((remaining.length > 0 || groupsLeft()) && Date.now() < killDeadline) {
|
|
2319
|
-
signalAll(remaining, "SIGKILL");
|
|
2320
|
-
await delay$1(50);
|
|
2321
|
-
remaining = members(await listProcesses());
|
|
2322
|
-
}
|
|
2323
|
-
if (remaining.length > 0 || groupsLeft()) log.warn("process.reap_incomplete", {
|
|
2324
|
-
pids: remaining,
|
|
2325
|
-
pgids: owned.map((row) => row.pgid)
|
|
2326
|
-
});
|
|
2918
|
+
const outcomes = await reapRecorded(rows, (event, fields) => log.warn(event, fields));
|
|
2327
2919
|
ledger.write((db) => {
|
|
2328
|
-
for (const
|
|
2920
|
+
for (const row of rows) db.run("DELETE FROM child WHERE pid = ? AND start_time = ?", row.pid, row.start_time);
|
|
2329
2921
|
});
|
|
2330
|
-
const report =
|
|
2922
|
+
const report = rows.map((row, index) => {
|
|
2331
2923
|
const base = {
|
|
2332
2924
|
pid: row.pid,
|
|
2333
2925
|
kind: row.kind,
|
|
2334
2926
|
ownerRef: row.owner_ref
|
|
2335
2927
|
};
|
|
2336
|
-
|
|
2928
|
+
const outcome = outcomes[index];
|
|
2929
|
+
return outcome?.skipped === void 0 ? {
|
|
2337
2930
|
...base,
|
|
2338
|
-
signalled:
|
|
2931
|
+
signalled: outcome?.ended ?? []
|
|
2339
2932
|
} : {
|
|
2340
2933
|
...base,
|
|
2341
2934
|
signalled: [],
|
|
2342
|
-
skipped:
|
|
2935
|
+
skipped: outcome.skipped
|
|
2343
2936
|
};
|
|
2344
2937
|
});
|
|
2345
2938
|
for (const entry of report) log.info("process.reaped", { ...entry });
|
|
@@ -2354,62 +2947,27 @@ function createManager({ ledger, log, redactor, faults = noFaults }) {
|
|
|
2354
2947
|
const forget = (pid) => {
|
|
2355
2948
|
ledger.write((db) => db.run("DELETE FROM child WHERE pid = ? OR parent_pid = ?", pid, pid));
|
|
2356
2949
|
};
|
|
2357
|
-
|
|
2358
|
-
* Terminates groups: SIGTERM, then SIGKILL after `graceMs` to those still present, then waits
|
|
2359
|
-
* (boundedly) until they are gone.
|
|
2360
|
-
*/
|
|
2361
|
-
const endGroups = async (pgids, graceMs) => {
|
|
2362
|
-
for (const pgid of pgids) signalGroup(pgid, "SIGTERM");
|
|
2363
|
-
const deadline = Date.now() + graceMs;
|
|
2364
|
-
while (Date.now() < deadline && pgids.some(groupAlive)) await delay$1(25);
|
|
2365
|
-
for (const pgid of pgids) if (groupAlive(pgid)) signalGroup(pgid, "SIGKILL");
|
|
2366
|
-
const killDeadline = Date.now() + KILL_WAIT_MS;
|
|
2367
|
-
while (Date.now() < killDeadline && pgids.some(groupAlive)) await delay$1(10);
|
|
2368
|
-
const left = pgids.filter(groupAlive);
|
|
2369
|
-
if (left.length > 0) log.warn("process.group_survived_sigkill", { pgids: left });
|
|
2370
|
-
};
|
|
2950
|
+
const warn = (event, fields) => log.warn(event, fields);
|
|
2371
2951
|
const spawnChild = async (spec) => {
|
|
2372
2952
|
if (stopping) throw new Error("The process manager is stopping.");
|
|
2373
2953
|
if (spec.ipc && spec.channel) throw new Error("A child takes ipc or a channel, not both.");
|
|
2374
2954
|
for (const value of spec.redact ?? []) redactor.protect(value);
|
|
2375
2955
|
redactor.protectEnvironment(spec.env ?? process.env);
|
|
2376
|
-
const
|
|
2377
|
-
|
|
2378
|
-
|
|
2379
|
-
|
|
2380
|
-
spec.command,
|
|
2381
|
-
...spec.args ?? []
|
|
2382
|
-
], {
|
|
2956
|
+
const launched = launch({
|
|
2957
|
+
kind: spec.kind,
|
|
2958
|
+
command: spec.command,
|
|
2959
|
+
args: spec.args ?? [],
|
|
2383
2960
|
cwd: spec.cwd,
|
|
2384
2961
|
env: spec.env ?? process.env,
|
|
2385
|
-
|
|
2386
|
-
|
|
2387
|
-
|
|
2388
|
-
"pipe",
|
|
2389
|
-
"pipe",
|
|
2390
|
-
"pipe",
|
|
2391
|
-
"ipc"
|
|
2392
|
-
] : spec.channel ? [
|
|
2393
|
-
"ignore",
|
|
2394
|
-
"pipe",
|
|
2395
|
-
"pipe",
|
|
2396
|
-
"pipe",
|
|
2397
|
-
"pipe"
|
|
2398
|
-
] : [
|
|
2399
|
-
"ignore",
|
|
2400
|
-
"pipe",
|
|
2401
|
-
"pipe",
|
|
2402
|
-
"pipe"
|
|
2403
|
-
],
|
|
2404
|
-
serialization: "json"
|
|
2405
|
-
});
|
|
2406
|
-
const gate = child.stdio[3];
|
|
2407
|
-
gate?.on("error", () => {});
|
|
2962
|
+
extra: spec.ipc ? "ipc" : spec.channel ? "channel" : void 0
|
|
2963
|
+
}, warn);
|
|
2964
|
+
const child = launched.process;
|
|
2408
2965
|
const startedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
2409
|
-
|
|
2410
|
-
child.once("spawn", () => resolve(
|
|
2966
|
+
await new Promise((resolve, reject) => {
|
|
2967
|
+
child.once("spawn", () => resolve());
|
|
2411
2968
|
child.once("error", reject);
|
|
2412
2969
|
});
|
|
2970
|
+
let pid = child.pid ?? 0;
|
|
2413
2971
|
child.on("error", (error) => log.warn("process.error", {
|
|
2414
2972
|
kind: spec.kind,
|
|
2415
2973
|
pid,
|
|
@@ -2466,15 +3024,16 @@ function createManager({ ledger, log, redactor, faults = noFaults }) {
|
|
|
2466
3024
|
ledger.write((db) => db.run("DELETE FROM child WHERE pid = ? AND parent_pid = ?", parsed.data.pid, pid));
|
|
2467
3025
|
return {};
|
|
2468
3026
|
}
|
|
2469
|
-
const
|
|
2470
|
-
if (!
|
|
2471
|
-
|
|
3027
|
+
const found = await adoptable(parsed.data.pid);
|
|
3028
|
+
if (!found) return { adopted: false };
|
|
3029
|
+
if (!found.record) return { adopted: true };
|
|
3030
|
+
adopted.set(found.info.pid, found.info.pgid);
|
|
2472
3031
|
record({
|
|
2473
|
-
pid: info.pid,
|
|
2474
|
-
start_time: info.startTime,
|
|
3032
|
+
pid: found.info.pid,
|
|
3033
|
+
start_time: found.info.startTime,
|
|
2475
3034
|
kind: `${spec.kind}/adopted`,
|
|
2476
3035
|
owner_ref: spec.ownerRef,
|
|
2477
|
-
pgid: info.pgid,
|
|
3036
|
+
pgid: found.info.pgid,
|
|
2478
3037
|
started_at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2479
3038
|
parent_pid: pid
|
|
2480
3039
|
});
|
|
@@ -2496,28 +3055,28 @@ function createManager({ ledger, log, redactor, faults = noFaults }) {
|
|
|
2496
3055
|
child.on("disconnect", () => connected.close());
|
|
2497
3056
|
}
|
|
2498
3057
|
const registered = (async () => {
|
|
2499
|
-
const info = await
|
|
3058
|
+
const info = await launched.identify();
|
|
2500
3059
|
faults.at("spawn:before-record");
|
|
2501
|
-
|
|
2502
|
-
|
|
2503
|
-
|
|
2504
|
-
|
|
3060
|
+
faults.at(`spawn:before-record:${spec.kind}`);
|
|
3061
|
+
if (faults.hangs(`spawn:before-record:${spec.kind}`)) await new Promise(() => {});
|
|
3062
|
+
if (!info) return;
|
|
3063
|
+
pid = info.pid;
|
|
2505
3064
|
record({
|
|
2506
|
-
pid,
|
|
3065
|
+
pid: info.pid,
|
|
2507
3066
|
start_time: info.startTime,
|
|
2508
3067
|
kind: spec.kind,
|
|
2509
3068
|
owner_ref: spec.ownerRef,
|
|
2510
|
-
pgid: pid,
|
|
3069
|
+
pgid: info.pid,
|
|
2511
3070
|
started_at: startedAt,
|
|
2512
3071
|
parent_pid: null
|
|
2513
3072
|
});
|
|
2514
|
-
|
|
3073
|
+
launched.release();
|
|
2515
3074
|
})();
|
|
2516
3075
|
const exited = exit.then(async ({ code, signal }) => {
|
|
2517
|
-
await
|
|
3076
|
+
await launched.sweep([...adopted.values()]);
|
|
2518
3077
|
await settleWithin(Promise.all(drained), 2e3);
|
|
2519
3078
|
await registered.catch(() => {});
|
|
2520
|
-
running.delete(pid);
|
|
3079
|
+
running.delete(child.pid ?? 0);
|
|
2521
3080
|
try {
|
|
2522
3081
|
forget(pid);
|
|
2523
3082
|
} catch (error) {
|
|
@@ -2544,8 +3103,14 @@ function createManager({ ledger, log, redactor, faults = noFaults }) {
|
|
|
2544
3103
|
pid,
|
|
2545
3104
|
error
|
|
2546
3105
|
}));
|
|
3106
|
+
const stop = async (graceMs = DEFAULT_GRACE_MS) => {
|
|
3107
|
+
if (launched.running()) await launched.end(graceMs, [...adopted.values()]);
|
|
3108
|
+
return exited;
|
|
3109
|
+
};
|
|
2547
3110
|
const handle = {
|
|
2548
|
-
pid
|
|
3111
|
+
get pid() {
|
|
3112
|
+
return pid;
|
|
3113
|
+
},
|
|
2549
3114
|
kind: spec.kind,
|
|
2550
3115
|
ownerRef: spec.ownerRef,
|
|
2551
3116
|
startedAt,
|
|
@@ -2555,12 +3120,12 @@ function createManager({ ledger, log, redactor, faults = noFaults }) {
|
|
|
2555
3120
|
if (!peer) return Promise.reject(/* @__PURE__ */ new Error(`${spec.kind} was started without IPC.`));
|
|
2556
3121
|
return peer.request(method, params, options);
|
|
2557
3122
|
},
|
|
2558
|
-
|
|
2559
|
-
if (child.exitCode === null && child.signalCode === null) await endGroups([pid, ...adopted.values()], graceMs);
|
|
2560
|
-
return exited;
|
|
2561
|
-
}
|
|
3123
|
+
stop
|
|
2562
3124
|
};
|
|
2563
|
-
running.set(pid,
|
|
3125
|
+
running.set(child.pid ?? 0, {
|
|
3126
|
+
handle,
|
|
3127
|
+
kill: () => launched.kill()
|
|
3128
|
+
});
|
|
2564
3129
|
try {
|
|
2565
3130
|
await registered;
|
|
2566
3131
|
} catch (error) {
|
|
@@ -2590,16 +3155,19 @@ function createManager({ ledger, log, redactor, faults = noFaults }) {
|
|
|
2590
3155
|
};
|
|
2591
3156
|
return {
|
|
2592
3157
|
spawn: trackedSpawn,
|
|
2593
|
-
list: () => [...running.values()].map((
|
|
2594
|
-
pid:
|
|
2595
|
-
kind:
|
|
2596
|
-
ownerRef:
|
|
2597
|
-
startedAt:
|
|
3158
|
+
list: () => [...running.values()].map(({ handle }) => ({
|
|
3159
|
+
pid: handle.pid,
|
|
3160
|
+
kind: handle.kind,
|
|
3161
|
+
ownerRef: handle.ownerRef,
|
|
3162
|
+
startedAt: handle.startedAt
|
|
2598
3163
|
})),
|
|
2599
3164
|
async stopAll(graceMs = DEFAULT_GRACE_MS) {
|
|
2600
3165
|
stopping = true;
|
|
2601
3166
|
await Promise.all(inflight);
|
|
2602
|
-
await Promise.all([...running.values()].map((
|
|
3167
|
+
await Promise.all([...running.values()].map(({ handle }) => handle.stop(graceMs)));
|
|
3168
|
+
},
|
|
3169
|
+
killAll() {
|
|
3170
|
+
for (const { kill } of running.values()) kill();
|
|
2603
3171
|
}
|
|
2604
3172
|
};
|
|
2605
3173
|
}
|
|
@@ -2609,20 +3177,6 @@ function createManager({ ledger, log, redactor, faults = noFaults }) {
|
|
|
2609
3177
|
* The warm set (D91, D95): the pre-built, read-only layout every artifact resolves without an
|
|
2610
3178
|
* install. `@mostra/warm`'s `dependencies` are the warm packages; its `node_modules` is the layout.
|
|
2611
3179
|
*/
|
|
2612
|
-
/** The directory of `@mostra/runtime`'s package.json. */
|
|
2613
|
-
function runtimeRoot() {
|
|
2614
|
-
let dir = dirname(fileURLToPath(import.meta.url));
|
|
2615
|
-
for (;;) {
|
|
2616
|
-
const manifest = join(dir, "package.json");
|
|
2617
|
-
if (existsSync(manifest)) {
|
|
2618
|
-
const { name } = JSON.parse(readFileSync(manifest, "utf8"));
|
|
2619
|
-
if (name === "@mostra/runtime") return dir;
|
|
2620
|
-
}
|
|
2621
|
-
const parent = dirname(dir);
|
|
2622
|
-
if (parent === dir) throw new Error("Couldn't find @mostra/runtime's package.json.");
|
|
2623
|
-
dir = parent;
|
|
2624
|
-
}
|
|
2625
|
-
}
|
|
2626
3180
|
function warmMissing(message) {
|
|
2627
3181
|
return new RpcError(createDiagnostic("MOSTRA_ENV_WARM_MISSING", { message }));
|
|
2628
3182
|
}
|
|
@@ -2631,7 +3185,7 @@ function warmMissing(message) {
|
|
|
2631
3185
|
* the runtime bundle and this repository lay it out. Every listed package must be installed.
|
|
2632
3186
|
*/
|
|
2633
3187
|
function locateWarmSet(env) {
|
|
2634
|
-
const dir = env["MOSTRA_WARM_DIR"] ?? resolve(runtimeRoot(), "..", "warm");
|
|
3188
|
+
const dir = env["MOSTRA_WARM_DIR"] ?? resolve(runtimeRoot$1(), "..", "warm");
|
|
2635
3189
|
const manifestFile = join(dir, "package.json");
|
|
2636
3190
|
if (!existsSync(manifestFile)) throw warmMissing(`No warm package set at ${dir}.`);
|
|
2637
3191
|
const { dependencies = {} } = JSON.parse(readFileSync(manifestFile, "utf8"));
|
|
@@ -2661,11 +3215,11 @@ function packageNamed(record, message) {
|
|
|
2661
3215
|
}
|
|
2662
3216
|
/** The install child's entry: the compiled one beside the compiled supervisor, else the source. */
|
|
2663
3217
|
function childEntry() {
|
|
2664
|
-
return fileURLToPath(import.meta.url).endsWith(".ts") ? join(runtimeRoot(), "src/deps/child/install.ts") : join(runtimeRoot(), "dist/deps/child/install.js");
|
|
3218
|
+
return fileURLToPath(import.meta.url).endsWith(".ts") ? join(runtimeRoot$1(), "src/deps/child/install.ts") : join(runtimeRoot$1(), "dist/deps/child/install.js");
|
|
2665
3219
|
}
|
|
2666
3220
|
/** Finds pnpm 10 beside the runtime; anything else is refused (D94). */
|
|
2667
3221
|
function locatePnpm() {
|
|
2668
|
-
let dir = runtimeRoot();
|
|
3222
|
+
let dir = runtimeRoot$1();
|
|
2669
3223
|
for (;;) {
|
|
2670
3224
|
const candidate = join(dir, "node_modules", "pnpm");
|
|
2671
3225
|
if (existsSync(join(candidate, "package.json"))) {
|
|
@@ -3239,8 +3793,13 @@ function isOffline(env) {
|
|
|
3239
3793
|
if (flag !== void 0 && flag !== "" && !/^(?:0|false|no)$/i.test(flag)) return true;
|
|
3240
3794
|
return !Object.values(networkInterfaces()).some((addresses) => (addresses ?? []).some((address) => !address.internal && !address.address.startsWith("169.254.") && !/^fe[89ab]/i.test(address.address)));
|
|
3241
3795
|
}
|
|
3242
|
-
/**
|
|
3796
|
+
/**
|
|
3797
|
+
* A shell-safe rendering of `value`, for the commands in diagnostics: POSIX shell quoting, or on
|
|
3798
|
+
* Windows the double quotes PowerShell and `cmd` both read (a Windows path holds no `"`), and a
|
|
3799
|
+
* plain path with backslashes as it is.
|
|
3800
|
+
*/
|
|
3243
3801
|
function shellQuote(value) {
|
|
3802
|
+
if (WINDOWS) return /^[\w@%+=:,./\\-]+$/.test(value) ? value : `"${value}"`;
|
|
3244
3803
|
return /^[\w@%+=:,./-]+$/.test(value) ? value : `'${value.replaceAll("'", `'\\''`)}'`;
|
|
3245
3804
|
}
|
|
3246
3805
|
/** Serializes work per key; one supervisor, so in-process order is the order. */
|
|
@@ -3321,7 +3880,7 @@ function createDependencies(options) {
|
|
|
3321
3880
|
const work = join(dirs.tmp, `resolve-${randomBytes(6).toString("hex")}`);
|
|
3322
3881
|
await mkdir(work);
|
|
3323
3882
|
try {
|
|
3324
|
-
await
|
|
3883
|
+
await linkDirectory(warm.nodeModules, join(work, "warm"));
|
|
3325
3884
|
await writeFile(join(work, "package.json"), manifestOf(input.pins));
|
|
3326
3885
|
if (input.previous !== void 0) await writeFile(join(work, "pnpm-lock.yaml"), input.previous);
|
|
3327
3886
|
const outcome = await install().run({
|
|
@@ -3363,16 +3922,9 @@ function createDependencies(options) {
|
|
|
3363
3922
|
/** Points a layout's `warm` symlink at the current warm set (the runtime may have moved). */
|
|
3364
3923
|
const relinkWarm = async (dir) => {
|
|
3365
3924
|
const link = join(dir, "warm");
|
|
3366
|
-
|
|
3367
|
-
|
|
3368
|
-
|
|
3369
|
-
} catch {
|
|
3370
|
-
target = void 0;
|
|
3371
|
-
}
|
|
3372
|
-
if (target === warm.nodeModules) return;
|
|
3373
|
-
const fresh = `${link}.${randomBytes(4).toString("hex")}`;
|
|
3374
|
-
await symlink(warm.nodeModules, fresh, "dir");
|
|
3375
|
-
await rename(fresh, link);
|
|
3925
|
+
const target = await linkTarget(link);
|
|
3926
|
+
if (target !== void 0 && samePath(target, warm.nodeModules)) return;
|
|
3927
|
+
await replaceDirectoryLink(warm.nodeModules, link);
|
|
3376
3928
|
};
|
|
3377
3929
|
/**
|
|
3378
3930
|
* The layout of `lock`, installed from the store (and the registry for what the store lacks)
|
|
@@ -3397,7 +3949,7 @@ function createDependencies(options) {
|
|
|
3397
3949
|
});
|
|
3398
3950
|
await mkdir(dir, { recursive: true });
|
|
3399
3951
|
try {
|
|
3400
|
-
await
|
|
3952
|
+
await linkDirectory(warm.nodeModules, join(dir, "warm"));
|
|
3401
3953
|
await writeFile(join(dir, "package.json"), manifestOf(lock.packages));
|
|
3402
3954
|
await writeFile(join(dir, "pnpm-lock.yaml"), pnpm);
|
|
3403
3955
|
const outcome = await install().run({
|
|
@@ -3457,7 +4009,7 @@ function createDependencies(options) {
|
|
|
3457
4009
|
});
|
|
3458
4010
|
await mkdir(dir, { recursive: true });
|
|
3459
4011
|
try {
|
|
3460
|
-
await
|
|
4012
|
+
await linkDirectory(warm.nodeModules, join(dir, "warm"));
|
|
3461
4013
|
await writeFile(join(dir, "package.json"), `${JSON.stringify({
|
|
3462
4014
|
name: "mostra-artifact-dependencies",
|
|
3463
4015
|
private: true,
|
|
@@ -3808,12 +4360,6 @@ function writeLine(output, message) {
|
|
|
3808
4360
|
}
|
|
3809
4361
|
//#endregion
|
|
3810
4362
|
//#region src/protocol-server/server.ts
|
|
3811
|
-
/**
|
|
3812
|
-
* The host protocol server (D59, INTERFACES §6, HO-02): one dispatcher for every connection,
|
|
3813
|
-
* whether `mostra-runtime host`'s stdio or an attached client's Unix socket. It owns the session
|
|
3814
|
-
* rules (initialize first and once, revision negotiation, the home check, port registration on
|
|
3815
|
-
* the registering connection) and routes every other method to the handler a module registered.
|
|
3816
|
-
*/
|
|
3817
4363
|
/** Builds a handler with its types checked against the method definition. */
|
|
3818
4364
|
function handler(definition, handle) {
|
|
3819
4365
|
return {
|
|
@@ -3829,7 +4375,14 @@ var ProtocolServer = class {
|
|
|
3829
4375
|
#nextId = 1;
|
|
3830
4376
|
#refusal;
|
|
3831
4377
|
#listener;
|
|
4378
|
+
#endpoint;
|
|
4379
|
+
#listenOptions = {};
|
|
3832
4380
|
#healTimer;
|
|
4381
|
+
/** A heal under way: one at a time, and `close` waits for it (Opus review of WP-W1). */
|
|
4382
|
+
#healing;
|
|
4383
|
+
/** An endpoint that moved but whose `onMoved` failed: announced again by every heal until it holds. */
|
|
4384
|
+
#unannounced;
|
|
4385
|
+
#closed = false;
|
|
3833
4386
|
constructor(options) {
|
|
3834
4387
|
this.#options = options;
|
|
3835
4388
|
this.#handlers = new Map(options.handlers.map((entry) => [entry.definition.method, entry]));
|
|
@@ -3907,62 +4460,52 @@ var ProtocolServer = class {
|
|
|
3907
4460
|
return session;
|
|
3908
4461
|
}
|
|
3909
4462
|
/**
|
|
3910
|
-
* Listens on the home's control
|
|
3911
|
-
* lock holder calls this)
|
|
3912
|
-
* 10 s) that the
|
|
4463
|
+
* Listens on the home's control endpoint (D81, D82): a Unix socket, replacing any leftover file
|
|
4464
|
+
* (only the lock holder calls this) and owner-only; on Windows the helper's owner-only pipe
|
|
4465
|
+
* (`launchPipe`). Every `healMs` (at most 10 s) it checks that the endpoint still serves and
|
|
4466
|
+
* binds it again when it doesn't, calling `onMoved` when the new endpoint has another name.
|
|
3913
4467
|
*/
|
|
3914
|
-
async listen(path, healMs = 5e3) {
|
|
3915
|
-
this.#
|
|
4468
|
+
async listen(path, healMs = 5e3, options = {}) {
|
|
4469
|
+
this.#endpoint = path;
|
|
4470
|
+
this.#listenOptions = options;
|
|
4471
|
+
this.#listener = await this.#bind();
|
|
3916
4472
|
this.#healTimer = setInterval(() => void this.#heal(), Math.min(healMs, 1e4));
|
|
3917
4473
|
this.#healTimer.unref();
|
|
3918
4474
|
}
|
|
3919
|
-
/** The
|
|
4475
|
+
/** The endpoint the server listens on, as clients connect to it. */
|
|
3920
4476
|
get socketPath() {
|
|
3921
4477
|
return this.#listener?.path;
|
|
3922
4478
|
}
|
|
3923
|
-
|
|
3924
|
-
|
|
3925
|
-
|
|
3926
|
-
|
|
3927
|
-
|
|
3928
|
-
|
|
3929
|
-
unlinkSync(path);
|
|
3930
|
-
} catch (error) {
|
|
3931
|
-
if (error.code !== "ENOENT") throw error;
|
|
3932
|
-
}
|
|
3933
|
-
const server = createServer((socket) => {
|
|
3934
|
-
this.serve("socket", socket, socket);
|
|
4479
|
+
#bind() {
|
|
4480
|
+
return listenControl(this.#endpoint ?? "", (stream) => {
|
|
4481
|
+
this.serve("socket", stream, stream);
|
|
4482
|
+
}, {
|
|
4483
|
+
...this.#listenOptions.launchPipe ? { launchPipe: this.#listenOptions.launchPipe } : {},
|
|
4484
|
+
onError: (error) => this.#options.log.error("protocol.listener_error", { error })
|
|
3935
4485
|
});
|
|
3936
|
-
|
|
3937
|
-
|
|
3938
|
-
|
|
3939
|
-
|
|
3940
|
-
|
|
3941
|
-
});
|
|
4486
|
+
}
|
|
4487
|
+
#heal() {
|
|
4488
|
+
if (this.#closed) return Promise.resolve();
|
|
4489
|
+
this.#healing ??= this.#healOnce().finally(() => {
|
|
4490
|
+
this.#healing = void 0;
|
|
3942
4491
|
});
|
|
3943
|
-
|
|
3944
|
-
server.on("error", (error) => this.#options.log.error("protocol.listener_error", { error }));
|
|
3945
|
-
return {
|
|
3946
|
-
server,
|
|
3947
|
-
path,
|
|
3948
|
-
stats: statSync(path)
|
|
3949
|
-
};
|
|
4492
|
+
return this.#healing;
|
|
3950
4493
|
}
|
|
3951
|
-
async #
|
|
4494
|
+
async #healOnce() {
|
|
4495
|
+
if (this.#unannounced !== void 0) this.#announce(this.#unannounced);
|
|
3952
4496
|
const listener = this.#listener;
|
|
3953
|
-
if (!listener) return;
|
|
3954
|
-
|
|
3955
|
-
|
|
3956
|
-
current = statSync(listener.path);
|
|
3957
|
-
} catch {
|
|
3958
|
-
current = void 0;
|
|
3959
|
-
}
|
|
3960
|
-
if (current && current.ino === listener.stats.ino && current.dev === listener.stats.dev) return;
|
|
3961
|
-
listener.server.close();
|
|
4497
|
+
if (!listener || listener.intact()) return;
|
|
4498
|
+
await listener.close();
|
|
4499
|
+
if (this.#closed) return;
|
|
3962
4500
|
try {
|
|
3963
|
-
const replacement = await this.#bind(
|
|
4501
|
+
const replacement = await this.#bind();
|
|
4502
|
+
if (this.#closed) {
|
|
4503
|
+
await replacement.close();
|
|
4504
|
+
return;
|
|
4505
|
+
}
|
|
3964
4506
|
this.#listener = replacement;
|
|
3965
|
-
this.#options.log.warn("protocol.socket_recreated", { path:
|
|
4507
|
+
this.#options.log.warn("protocol.socket_recreated", { path: replacement.path });
|
|
4508
|
+
if (replacement.path !== listener.path) this.#announce(replacement.path);
|
|
3966
4509
|
} catch (error) {
|
|
3967
4510
|
this.#options.log.warn("protocol.socket_recreate_failed", {
|
|
3968
4511
|
path: listener.path,
|
|
@@ -3971,6 +4514,22 @@ var ProtocolServer = class {
|
|
|
3971
4514
|
}
|
|
3972
4515
|
}
|
|
3973
4516
|
/**
|
|
4517
|
+
* Tells the instance the endpoint moved (it rewrites `instance.json`); when that fails, every
|
|
4518
|
+
* later heal tries again, so starters are never left with a record naming a dead pipe.
|
|
4519
|
+
*/
|
|
4520
|
+
#announce(path) {
|
|
4521
|
+
try {
|
|
4522
|
+
this.#listenOptions.onMoved?.(path);
|
|
4523
|
+
this.#unannounced = void 0;
|
|
4524
|
+
} catch (error) {
|
|
4525
|
+
this.#unannounced = path;
|
|
4526
|
+
this.#options.log.warn("protocol.endpoint_announce_failed", {
|
|
4527
|
+
path,
|
|
4528
|
+
error
|
|
4529
|
+
});
|
|
4530
|
+
}
|
|
4531
|
+
}
|
|
4532
|
+
/**
|
|
3974
4533
|
* Answers every request from now on with `diagnostic`, for an instance that can no longer serve
|
|
3975
4534
|
* (`MOSTRA_HOME_GONE`).
|
|
3976
4535
|
*/
|
|
@@ -4040,20 +4599,17 @@ var ProtocolServer = class {
|
|
|
4040
4599
|
}
|
|
4041
4600
|
/**
|
|
4042
4601
|
* Stops listening, removes the socket file if it is still this server's, and closes every
|
|
4043
|
-
* connection. Responses already sent are flushed first
|
|
4602
|
+
* connection. Responses already sent are flushed first: the connections end before the
|
|
4603
|
+
* listener, which on Windows lets the pipe's helper hand them over before it exits.
|
|
4044
4604
|
*/
|
|
4045
|
-
close() {
|
|
4605
|
+
async close() {
|
|
4606
|
+
this.#closed = true;
|
|
4046
4607
|
if (this.#healTimer) clearInterval(this.#healTimer);
|
|
4608
|
+
await this.#healing;
|
|
4609
|
+
for (const connection of this.#connections) connection.close();
|
|
4047
4610
|
const listener = this.#listener;
|
|
4048
4611
|
this.#listener = void 0;
|
|
4049
|
-
|
|
4050
|
-
listener.server.close();
|
|
4051
|
-
try {
|
|
4052
|
-
const current = statSync(listener.path);
|
|
4053
|
-
if (current.ino === listener.stats.ino && current.dev === listener.stats.dev) unlinkSync(listener.path);
|
|
4054
|
-
} catch {}
|
|
4055
|
-
}
|
|
4056
|
-
for (const connection of this.#connections) connection.close();
|
|
4612
|
+
await listener?.close();
|
|
4057
4613
|
}
|
|
4058
4614
|
async #dispatch(session, method, params) {
|
|
4059
4615
|
try {
|
|
@@ -4146,43 +4702,34 @@ var ProtocolServer = class {
|
|
|
4146
4702
|
*/
|
|
4147
4703
|
/**
|
|
4148
4704
|
* Connects to a control socket. Rejects with `MOSTRA_HOST_CONNECTION_CLOSED` when nothing
|
|
4149
|
-
* listens there (the file is missing or stale)
|
|
4705
|
+
* listens there (the file is missing or stale), the connection doesn't open within `timeoutMs`,
|
|
4706
|
+
* or, on Windows, the pipe under that name is another user's.
|
|
4150
4707
|
*/
|
|
4151
4708
|
function connectSocket(path, timeoutMs = 5e3) {
|
|
4152
|
-
return
|
|
4153
|
-
const
|
|
4154
|
-
|
|
4155
|
-
|
|
4156
|
-
|
|
4157
|
-
}, timeoutMs);
|
|
4158
|
-
socket.once("error", (error) => {
|
|
4159
|
-
clearTimeout(timer);
|
|
4160
|
-
reject(refused(path, error.code ?? "failed"));
|
|
4709
|
+
return connectControl(path, timeoutMs).then((socket) => {
|
|
4710
|
+
const peer = new RpcPeer({ send: (message) => void writeLine(socket, message) });
|
|
4711
|
+
let markClosed = () => {};
|
|
4712
|
+
const closed = new Promise((done) => {
|
|
4713
|
+
markClosed = done;
|
|
4161
4714
|
});
|
|
4162
|
-
socket.
|
|
4163
|
-
|
|
4164
|
-
|
|
4165
|
-
|
|
4166
|
-
|
|
4167
|
-
|
|
4168
|
-
|
|
4169
|
-
socket.on("error", () => socket.destroy());
|
|
4170
|
-
pump({
|
|
4171
|
-
input: socket,
|
|
4172
|
-
output: socket
|
|
4173
|
-
}, () => peer, () => {
|
|
4174
|
-
peer.close();
|
|
4175
|
-
markClosed();
|
|
4176
|
-
});
|
|
4177
|
-
resolve({
|
|
4178
|
-
peer,
|
|
4179
|
-
closed,
|
|
4180
|
-
close: () => {
|
|
4181
|
-
peer.close();
|
|
4182
|
-
socket.end();
|
|
4183
|
-
}
|
|
4184
|
-
});
|
|
4715
|
+
socket.on("error", () => socket.destroy());
|
|
4716
|
+
pump({
|
|
4717
|
+
input: socket,
|
|
4718
|
+
output: socket
|
|
4719
|
+
}, () => peer, () => {
|
|
4720
|
+
peer.close();
|
|
4721
|
+
markClosed();
|
|
4185
4722
|
});
|
|
4723
|
+
return {
|
|
4724
|
+
peer,
|
|
4725
|
+
closed,
|
|
4726
|
+
close: () => {
|
|
4727
|
+
peer.close();
|
|
4728
|
+
socket.end();
|
|
4729
|
+
}
|
|
4730
|
+
};
|
|
4731
|
+
}, (error) => {
|
|
4732
|
+
throw refused(path, error instanceof ControlConnectError && error.reason === "not-owned" ? "it belongs to another user" : error instanceof Error ? error.message : "failed");
|
|
4186
4733
|
});
|
|
4187
4734
|
}
|
|
4188
4735
|
function refused(path, why) {
|
|
@@ -6785,69 +7332,10 @@ function createInteraction(options) {
|
|
|
6785
7332
|
/**
|
|
6786
7333
|
* The content-addressed version store on disk (DATA_MODEL §1, FAILURE_MODEL §3): `versions/<id>/`
|
|
6787
7334
|
* and `sources/<artifactId>/<sourceDigest>.tar.zst`. A version directory is assembled in staging,
|
|
6788
|
-
* made read-only
|
|
7335
|
+
* synced and made read-only (`platform`: modes on POSIX, an access list on Windows), then renamed
|
|
7336
|
+
* into place; it becomes visible only when its ledger row
|
|
6789
7337
|
* commits, and anything without a row is removed at the next start.
|
|
6790
7338
|
*/
|
|
6791
|
-
/** Calls `visit` for every entry under `dir`, children before their directory. */
|
|
6792
|
-
async function walk(dir, visit) {
|
|
6793
|
-
for (const entry of await readdir(dir, { withFileTypes: true })) {
|
|
6794
|
-
const path = join(dir, entry.name);
|
|
6795
|
-
if (entry.isDirectory()) await walk(path, visit);
|
|
6796
|
-
await visit(path, entry.isDirectory());
|
|
6797
|
-
}
|
|
6798
|
-
}
|
|
6799
|
-
/**
|
|
6800
|
-
* Syncs a file or a directory to disk. A file that can't be synced fails the caller (its bytes
|
|
6801
|
-
* would not be durable); a directory may not support it on some file systems, and only that
|
|
6802
|
-
* case is tolerated (EINVAL, ENOTSUP, EISDIR, EPERM, EACCES on `open`).
|
|
6803
|
-
*/
|
|
6804
|
-
function fsyncPath(path, directory = false) {
|
|
6805
|
-
let fd;
|
|
6806
|
-
try {
|
|
6807
|
-
fd = openSync(path, "r");
|
|
6808
|
-
fsyncSync(fd);
|
|
6809
|
-
} catch (error) {
|
|
6810
|
-
const code = error.code;
|
|
6811
|
-
if (!directory || ![
|
|
6812
|
-
"EINVAL",
|
|
6813
|
-
"ENOTSUP",
|
|
6814
|
-
"EISDIR",
|
|
6815
|
-
"EPERM",
|
|
6816
|
-
"EACCES"
|
|
6817
|
-
].includes(code ?? "")) throw error;
|
|
6818
|
-
} finally {
|
|
6819
|
-
if (fd !== void 0) closeSync(fd);
|
|
6820
|
-
}
|
|
6821
|
-
}
|
|
6822
|
-
/**
|
|
6823
|
-
* Makes a tree read-only (files 0444, directories 0555) and syncs it to disk. The top directory is
|
|
6824
|
-
* left writable when `keepTop` is set: renaming a directory needs write access to it, to update `..`.
|
|
6825
|
-
*/
|
|
6826
|
-
async function sealTree(dir, keepTop = false) {
|
|
6827
|
-
await walk(dir, async (path, isDirectory) => {
|
|
6828
|
-
await chmod(path, isDirectory ? 365 : 292);
|
|
6829
|
-
fsyncPath(path, isDirectory);
|
|
6830
|
-
});
|
|
6831
|
-
if (!keepTop) await chmod(dir, 365);
|
|
6832
|
-
fsyncPath(dir, true);
|
|
6833
|
-
}
|
|
6834
|
-
/** Removes a tree, sealed or not. Missing trees are fine. */
|
|
6835
|
-
async function removeTree(dir) {
|
|
6836
|
-
try {
|
|
6837
|
-
if ((await lstat(dir)).isDirectory()) {
|
|
6838
|
-
await chmod(dir, 493);
|
|
6839
|
-
await walk(dir, async (path, isDirectory) => {
|
|
6840
|
-
if (isDirectory) await chmod(path, 493);
|
|
6841
|
-
}).catch(() => {});
|
|
6842
|
-
}
|
|
6843
|
-
} catch {
|
|
6844
|
-
return;
|
|
6845
|
-
}
|
|
6846
|
-
await rm(dir, {
|
|
6847
|
-
recursive: true,
|
|
6848
|
-
force: true
|
|
6849
|
-
});
|
|
6850
|
-
}
|
|
6851
7339
|
/** Opens the version store of the home at `home`, creating its directories. */
|
|
6852
7340
|
async function openVersionStore(home) {
|
|
6853
7341
|
const versionsDir = join(home, "versions");
|
|
@@ -6872,9 +7360,8 @@ async function openVersionStore(home) {
|
|
|
6872
7360
|
await sealTree(built, true);
|
|
6873
7361
|
const target = versionDir(versionId);
|
|
6874
7362
|
await removeTree(target);
|
|
6875
|
-
await
|
|
6876
|
-
await
|
|
6877
|
-
fsyncPath(target, true);
|
|
7363
|
+
await renamePath(built, target);
|
|
7364
|
+
await sealPlaced(target);
|
|
6878
7365
|
fsyncPath(versionsDir, true);
|
|
6879
7366
|
},
|
|
6880
7367
|
async sweep(known) {
|
|
@@ -8167,7 +8654,7 @@ function capabilityKey(home, log) {
|
|
|
8167
8654
|
} finally {
|
|
8168
8655
|
closeSync(fd);
|
|
8169
8656
|
}
|
|
8170
|
-
|
|
8657
|
+
renamePathSync(aside, file);
|
|
8171
8658
|
chmodSync(file, 384);
|
|
8172
8659
|
return key;
|
|
8173
8660
|
}
|
|
@@ -10107,7 +10594,7 @@ async function verifyDocument(path, request, headers) {
|
|
|
10107
10594
|
* `MOSTRA_ENV_SHELL_MISSING`.
|
|
10108
10595
|
*/
|
|
10109
10596
|
function locateShell(env) {
|
|
10110
|
-
const dir = env["MOSTRA_SHELL_DIR"] ?? resolve(runtimeRoot(), "..", "shell", "dist");
|
|
10597
|
+
const dir = env["MOSTRA_SHELL_DIR"] ?? resolve(runtimeRoot$1(), "..", "shell", "dist");
|
|
10111
10598
|
return existsSync(join(dir, "index.html")) ? dir : void 0;
|
|
10112
10599
|
}
|
|
10113
10600
|
//#endregion
|
|
@@ -10497,7 +10984,7 @@ function localLauncher(options) {
|
|
|
10497
10984
|
resolve(options.home, "versions"),
|
|
10498
10985
|
resolve(options.home, "cache", "builds"),
|
|
10499
10986
|
resolve(options.home, "cache", "dev")
|
|
10500
|
-
].some((root) => versionDir.startsWith(`${root}/`))) throw new Error("A home: locator names a version directory, a verify build or a dev session of the home.");
|
|
10987
|
+
].some((root) => pathKey(versionDir).startsWith(`${pathKey(root)}/`))) throw new Error("A home: locator names a version directory, a verify build or a dev session of the home.");
|
|
10501
10988
|
const modules = await options.modules?.({
|
|
10502
10989
|
artifactId: spec.artifactId,
|
|
10503
10990
|
versionDir,
|
|
@@ -11491,7 +11978,7 @@ function parseTscOutput(lines, alreadyReported, ownConfig = false) {
|
|
|
11491
11978
|
}
|
|
11492
11979
|
/** Where `@mostra/server`'s declarations are: the worker provides the package, so no layout has it (D129). */
|
|
11493
11980
|
function serverTypes() {
|
|
11494
|
-
const root = runtimeRoot();
|
|
11981
|
+
const root = runtimeRoot$1();
|
|
11495
11982
|
for (const candidate of [join(root, "..", "server", "dist", "index.d.ts"), join(root, "..", "server", "src", "index.ts")]) if (existsSync(candidate)) return candidate;
|
|
11496
11983
|
}
|
|
11497
11984
|
/** Runs the type check of the snapshot in `sourceDir` against `nodeModules`. */
|
|
@@ -11504,7 +11991,7 @@ async function typecheck(options) {
|
|
|
11504
11991
|
await mkdir(join(workDir, ".mostra-check"), { recursive: true });
|
|
11505
11992
|
try {
|
|
11506
11993
|
await cp(options.sourceDir, join(workDir, "source"), { recursive: true });
|
|
11507
|
-
await
|
|
11994
|
+
await linkDirectory(options.nodeModules, join(workDir, "node_modules"));
|
|
11508
11995
|
await writeFile(join(workDir, ".mostra-check", "assets.d.ts"), AMBIENT);
|
|
11509
11996
|
if (options.hasLive) await writeFile(join(workDir, ".mostra-check", "mostra-env.d.ts"), LIVE_DECLARATION);
|
|
11510
11997
|
const own = existsSync(join(workDir, "source", "tsconfig.json"));
|
|
@@ -11927,7 +12414,7 @@ function createVerifier(options) {
|
|
|
11927
12414
|
recursive: true,
|
|
11928
12415
|
force: true
|
|
11929
12416
|
});
|
|
11930
|
-
await
|
|
12417
|
+
await renamePath(temporary, join(buildsDir, prepared.versionId));
|
|
11931
12418
|
await pruneBuilds(prepared.versionId);
|
|
11932
12419
|
return outcome;
|
|
11933
12420
|
} finally {
|
|
@@ -12237,7 +12724,7 @@ function createVerifier(options) {
|
|
|
12237
12724
|
verdict: checkedVerdict,
|
|
12238
12725
|
built: built.ok
|
|
12239
12726
|
}, null, 2)}\n`);
|
|
12240
|
-
await
|
|
12727
|
+
await renamePath(temporary, target);
|
|
12241
12728
|
await pruneVerdicts();
|
|
12242
12729
|
} else {
|
|
12243
12730
|
await rm(join(cacheDir, `${key}.json`), { force: true });
|
|
@@ -12776,7 +13263,7 @@ async function listSource(source) {
|
|
|
12776
13263
|
continue;
|
|
12777
13264
|
}
|
|
12778
13265
|
if (kind === "dir") {
|
|
12779
|
-
if (IGNORED_DIRS.has(entry.name) || rules.ignores(`${path}/`)) continue;
|
|
13266
|
+
if (IGNORED_DIRS.has(nameKey(entry.name)) || rules.ignores(`${path}/`)) continue;
|
|
12780
13267
|
let real;
|
|
12781
13268
|
try {
|
|
12782
13269
|
real = await realpath(absolute);
|
|
@@ -12787,9 +13274,9 @@ async function listSource(source) {
|
|
|
12787
13274
|
await walk(absolute, path, /* @__PURE__ */ new Set([...ancestors, real]));
|
|
12788
13275
|
} else if (kind === "file") {
|
|
12789
13276
|
if (IGNORED_FILE.test(entry.name) || rules.ignores(path)) continue;
|
|
12790
|
-
const clash = seen.get(path);
|
|
12791
|
-
if (clash !== void 0) throw artifactError("MOSTRA_ARTIFACT_SOURCE_UNREADABLE", `${clash} and ${absolute} have the same name after Unicode normalization (NFC).`);
|
|
12792
|
-
seen.set(path, absolute);
|
|
13277
|
+
const clash = seen.get(nameKey(path));
|
|
13278
|
+
if (clash !== void 0) throw artifactError("MOSTRA_ARTIFACT_SOURCE_UNREADABLE", `${clash} and ${absolute} have the same name after Unicode normalization (NFC)${WINDOWS ? " and ignoring case, as Windows compares names" : ""}.`);
|
|
13279
|
+
seen.set(nameKey(path), absolute);
|
|
12793
13280
|
files.push({
|
|
12794
13281
|
path,
|
|
12795
13282
|
absolute
|
|
@@ -13037,15 +13524,15 @@ async function archiveSnapshot(source, files, target) {
|
|
|
13037
13524
|
}
|
|
13038
13525
|
yield TAR_END;
|
|
13039
13526
|
}
|
|
13040
|
-
const output = createWriteStream(temporary, { mode: 256 });
|
|
13041
|
-
await pipeline(Readable.from(blocks()), createZstdCompress(), output);
|
|
13042
|
-
const handle = await import("node:fs/promises").then((fs) => fs.open(temporary, "r"));
|
|
13043
13527
|
try {
|
|
13044
|
-
await
|
|
13045
|
-
|
|
13046
|
-
await
|
|
13528
|
+
await pipeline(Readable.from(blocks()), createZstdCompress(), createWriteStream(temporary, { mode: 384 }));
|
|
13529
|
+
fsyncPath(temporary);
|
|
13530
|
+
await chmod(temporary, 256);
|
|
13531
|
+
} catch (error) {
|
|
13532
|
+
await removeTree(temporary).catch(() => {});
|
|
13533
|
+
throw error;
|
|
13047
13534
|
}
|
|
13048
|
-
await
|
|
13535
|
+
await renamePath(temporary, target);
|
|
13049
13536
|
fsyncPath(dirname(target), true);
|
|
13050
13537
|
return true;
|
|
13051
13538
|
}
|
|
@@ -13404,7 +13891,7 @@ function createPublisher(options) {
|
|
|
13404
13891
|
};
|
|
13405
13892
|
const cachedBuild = verifier().builtVersion(versionId);
|
|
13406
13893
|
if (cachedBuild && await versionDamage(cachedBuild) === void 0) {
|
|
13407
|
-
await
|
|
13894
|
+
await renamePath(cachedBuild, out);
|
|
13408
13895
|
outputDigest = JSON.parse(await readFile(join(out, "manifest.json"), "utf8")).outputDigest;
|
|
13409
13896
|
} else {
|
|
13410
13897
|
log.info("publish.rebuild", {
|
|
@@ -14324,82 +14811,35 @@ function gcMethods(gc) {
|
|
|
14324
14811
|
//#endregion
|
|
14325
14812
|
//#region src/home/paths.ts
|
|
14326
14813
|
/**
|
|
14327
|
-
* Where a home and its control
|
|
14328
|
-
* touches the file system; preparing a directory creates it
|
|
14329
|
-
* owns, and refuses one owned by someone else.
|
|
14814
|
+
* Where a home and its control endpoint live (DATA_MODEL §1, D82, D84, D85). Resolving a path never
|
|
14815
|
+
* touches the file system; preparing a directory creates it owner-only, tightens one the user
|
|
14816
|
+
* owns, and refuses one owned by someone else. The per-system details are the platform layer's.
|
|
14330
14817
|
*/
|
|
14331
14818
|
const nonEmpty = (value) => value === void 0 || value === "" ? void 0 : value;
|
|
14332
14819
|
/**
|
|
14333
14820
|
* The home path, resolved in D84's order: `--home`, then `MOSTRA_HOME`, then the platform default
|
|
14334
|
-
* (`~/.mostra` on macOS, `${XDG_DATA_HOME:-~/.local/share}/mostra` on Linux
|
|
14335
|
-
* `home` option as `--home`.
|
|
14821
|
+
* (`~/.mostra` on macOS, `${XDG_DATA_HOME:-~/.local/share}/mostra` on Linux,
|
|
14822
|
+
* `%LOCALAPPDATA%\mostra` on Windows). An SDK passes its `home` option as `--home`.
|
|
14336
14823
|
*/
|
|
14337
14824
|
function resolveHomePath(inputs) {
|
|
14338
14825
|
const cwd = inputs.cwd ?? process.cwd();
|
|
14339
14826
|
const chosen = nonEmpty(inputs.home) ?? nonEmpty(inputs.env["MOSTRA_HOME"]);
|
|
14340
|
-
if (chosen !== void 0) return resolve(cwd, chosen);
|
|
14341
|
-
|
|
14342
|
-
if ((inputs.platform ?? process.platform) === "darwin") return join(user, ".mostra");
|
|
14343
|
-
const data = nonEmpty(inputs.env["XDG_DATA_HOME"]);
|
|
14344
|
-
return join(data !== void 0 && isAbsolute(data) ? data : join(user, ".local", "share"), "mostra");
|
|
14345
|
-
}
|
|
14346
|
-
/** The current user's ID. */
|
|
14347
|
-
function uid$1() {
|
|
14348
|
-
return process.getuid?.() ?? -1;
|
|
14827
|
+
if (chosen !== void 0) return pathsOf(inputs.platform ?? OS).resolve(cwd, chosen);
|
|
14828
|
+
return defaultHome(inputs.platform ?? OS, inputs.env, inputs.userHome ?? homedir());
|
|
14349
14829
|
}
|
|
14350
14830
|
/**
|
|
14351
14831
|
* The runtime directory for control sockets (D82): `MOSTRA_RUNTIME_DIR`; else `~/.mostra/run` on
|
|
14352
14832
|
* macOS; on Linux `$XDG_RUNTIME_DIR/mostra` when `$XDG_RUNTIME_DIR` is a directory the user owns
|
|
14353
|
-
* that nobody else can read or write, else `${XDG_STATE_HOME:-~/.local/state}/mostra/run`.
|
|
14833
|
+
* that nobody else can read or write, else `${XDG_STATE_HOME:-~/.local/state}/mostra/run`. On
|
|
14834
|
+
* Windows `undefined`: the control pipe lives in the system's pipe namespace.
|
|
14354
14835
|
*/
|
|
14355
14836
|
function resolveRuntimeDir(inputs) {
|
|
14356
|
-
|
|
14357
|
-
|
|
14358
|
-
|
|
14359
|
-
|
|
14360
|
-
|
|
14361
|
-
|
|
14362
|
-
if ((inputs.platform ?? process.platform) === "darwin") return {
|
|
14363
|
-
dir: join(user, ".mostra", "run"),
|
|
14364
|
-
source: "fallback"
|
|
14365
|
-
};
|
|
14366
|
-
const xdg = nonEmpty(inputs.env["XDG_RUNTIME_DIR"]);
|
|
14367
|
-
let rejected;
|
|
14368
|
-
if (xdg !== void 0) {
|
|
14369
|
-
rejected = unsafeXdgRuntimeDir(xdg);
|
|
14370
|
-
if (rejected === void 0) return {
|
|
14371
|
-
dir: join(xdg, "mostra"),
|
|
14372
|
-
source: "xdg"
|
|
14373
|
-
};
|
|
14374
|
-
}
|
|
14375
|
-
const state = nonEmpty(inputs.env["XDG_STATE_HOME"]);
|
|
14376
|
-
const base = state !== void 0 && isAbsolute(state) ? state : join(user, ".local", "state");
|
|
14377
|
-
const dir = join(base, "mostra", "run");
|
|
14378
|
-
return rejected === void 0 ? {
|
|
14379
|
-
dir,
|
|
14380
|
-
source: "fallback"
|
|
14381
|
-
} : {
|
|
14382
|
-
dir,
|
|
14383
|
-
source: "fallback",
|
|
14384
|
-
rejected
|
|
14385
|
-
};
|
|
14386
|
-
}
|
|
14387
|
-
/** Why `$XDG_RUNTIME_DIR` can't be used, or `undefined` when it can (XDG Base Directory spec). */
|
|
14388
|
-
function unsafeXdgRuntimeDir(dir) {
|
|
14389
|
-
if (!isAbsolute(dir)) return "it isn't an absolute path";
|
|
14390
|
-
let stats;
|
|
14391
|
-
try {
|
|
14392
|
-
stats = statSync(dir);
|
|
14393
|
-
} catch {
|
|
14394
|
-
return "it doesn't exist";
|
|
14395
|
-
}
|
|
14396
|
-
if (!stats.isDirectory()) return "it isn't a directory";
|
|
14397
|
-
if (stats.uid !== uid$1()) return "another user owns it";
|
|
14398
|
-
if ((stats.mode & 63) !== 0) return "other users can access it";
|
|
14399
|
-
}
|
|
14400
|
-
/** The longest control socket path the operating system accepts, in bytes (VERIFIED_FACTS). */
|
|
14401
|
-
function socketPathLimit(platform = process.platform) {
|
|
14402
|
-
return platform === "darwin" ? 103 : 107;
|
|
14837
|
+
return runtimeDirFor({
|
|
14838
|
+
os: inputs.platform ?? OS,
|
|
14839
|
+
env: inputs.env,
|
|
14840
|
+
userHome: inputs.userHome ?? homedir(),
|
|
14841
|
+
cwd: inputs.cwd ?? process.cwd()
|
|
14842
|
+
});
|
|
14403
14843
|
}
|
|
14404
14844
|
/**
|
|
14405
14845
|
* A home's hash (D82): 16 Crockford base32 characters of the SHA-256 of its real path, which
|
|
@@ -14410,73 +14850,20 @@ function homeHash(realHome) {
|
|
|
14410
14850
|
return VersionId.fromSha256(new Uint8Array(digest)).slice(4, 20);
|
|
14411
14851
|
}
|
|
14412
14852
|
/**
|
|
14413
|
-
* The control
|
|
14414
|
-
* `MOSTRA_HOME_SOCKET_TOO_LONG`
|
|
14853
|
+
* The control endpoint for a home (D82), named by its {@link homeHash}: the socket in `runtimeDir`
|
|
14854
|
+
* on POSIX, throwing `MOSTRA_HOME_SOCKET_TOO_LONG` past the system's limit; on Windows the pipe
|
|
14855
|
+
* name that each bind completes with a random part.
|
|
14415
14856
|
*/
|
|
14416
|
-
function socketPathFor(runtimeDir, realHome, platform) {
|
|
14417
|
-
|
|
14418
|
-
const path = join(runtimeDir, `${hash}.sock`);
|
|
14419
|
-
const limit = socketPathLimit(platform);
|
|
14420
|
-
const length = Buffer.byteLength(path);
|
|
14421
|
-
if (length > limit) throw new RpcError(createDiagnostic("MOSTRA_HOME_SOCKET_TOO_LONG", {
|
|
14422
|
-
message: `The control socket path ${path} is ${length} bytes; this system allows ${limit}.`,
|
|
14423
|
-
fix: {
|
|
14424
|
-
kind: "command",
|
|
14425
|
-
command: "export MOSTRA_RUNTIME_DIR=/tmp/mostra-$USER"
|
|
14426
|
-
}
|
|
14427
|
-
}));
|
|
14428
|
-
return path;
|
|
14429
|
-
}
|
|
14430
|
-
function notOwned(path, why) {
|
|
14431
|
-
return new RpcError(createDiagnostic("MOSTRA_HOME_NOT_OWNED", { message: `Mostra can't use ${path}: ${why}.` }));
|
|
14857
|
+
function socketPathFor(runtimeDir, realHome, platform = OS) {
|
|
14858
|
+
return controlEndpoint(runtimeDir, homeHash(realHome), platform);
|
|
14432
14859
|
}
|
|
14433
14860
|
/**
|
|
14434
|
-
* Makes `path` a directory only its owner can use (D85): creates it
|
|
14435
|
-
* tightens one the user owns
|
|
14436
|
-
* another user or a path that isn't a directory.
|
|
14861
|
+
* Makes `path` a directory only its owner can use (D85): creates it owner-only when missing,
|
|
14862
|
+
* tightens one the user owns (mode 0700, or an owner-only access list on Windows), and throws
|
|
14863
|
+
* `MOSTRA_HOME_NOT_OWNED` for one owned by another user or a path that isn't a directory.
|
|
14437
14864
|
*/
|
|
14438
14865
|
function prepareOwnedDirectory(path) {
|
|
14439
|
-
|
|
14440
|
-
return prepare(path);
|
|
14441
|
-
} catch (error) {
|
|
14442
|
-
const code = error.code;
|
|
14443
|
-
if (code === "ENOTDIR" || code === "EEXIST") throw notOwned(path, "a part of the path isn't a directory");
|
|
14444
|
-
if (code === "EACCES" || code === "EPERM") throw notOwned(path, "you have no permission to use it");
|
|
14445
|
-
throw error;
|
|
14446
|
-
}
|
|
14447
|
-
}
|
|
14448
|
-
function prepare(path) {
|
|
14449
|
-
let created = false;
|
|
14450
|
-
try {
|
|
14451
|
-
statSync(path);
|
|
14452
|
-
} catch (error) {
|
|
14453
|
-
if (error.code !== "ENOENT") throw error;
|
|
14454
|
-
mkdirSync(path, {
|
|
14455
|
-
recursive: true,
|
|
14456
|
-
mode: 448
|
|
14457
|
-
});
|
|
14458
|
-
created = true;
|
|
14459
|
-
}
|
|
14460
|
-
const realPath = realpathSync(path);
|
|
14461
|
-
const stats = statSync(realPath);
|
|
14462
|
-
if (!stats.isDirectory()) throw notOwned(path, "it isn't a directory");
|
|
14463
|
-
if (stats.uid !== uid$1()) throw notOwned(path, `it belongs to user ${stats.uid}, not to you`);
|
|
14464
|
-
const mode = stats.mode & 511;
|
|
14465
|
-
if (mode !== 448) {
|
|
14466
|
-
chmodSync(realPath, 448);
|
|
14467
|
-
return created ? {
|
|
14468
|
-
realPath,
|
|
14469
|
-
created
|
|
14470
|
-
} : {
|
|
14471
|
-
realPath,
|
|
14472
|
-
created,
|
|
14473
|
-
tightenedFrom: mode
|
|
14474
|
-
};
|
|
14475
|
-
}
|
|
14476
|
-
return {
|
|
14477
|
-
realPath,
|
|
14478
|
-
created
|
|
14479
|
-
};
|
|
14866
|
+
return ownedDirectory(path);
|
|
14480
14867
|
}
|
|
14481
14868
|
//#endregion
|
|
14482
14869
|
//#region src/home/record.ts
|
|
@@ -14517,7 +14904,7 @@ function writeInstanceRecord(home, record) {
|
|
|
14517
14904
|
const file = join(home, INSTANCE_FILE);
|
|
14518
14905
|
const temp = `${file}.${process.pid}.tmp`;
|
|
14519
14906
|
writeFileSync(temp, `${JSON.stringify(record, null, 2)}\n`, { mode: 384 });
|
|
14520
|
-
|
|
14907
|
+
renamePathSync(temp, file);
|
|
14521
14908
|
}
|
|
14522
14909
|
/** Removes the record when it is still this process's (a clean exit). */
|
|
14523
14910
|
function removeInstanceRecord(home, pid, startTime) {
|
|
@@ -14550,8 +14937,12 @@ async function acquireHome(options) {
|
|
|
14550
14937
|
const prepared = prepareOwnedDirectory(options.home);
|
|
14551
14938
|
const home = prepared.realPath;
|
|
14552
14939
|
const runtimeDir = resolveRuntimeDir({ env: options.env });
|
|
14553
|
-
|
|
14554
|
-
|
|
14940
|
+
let socketPath;
|
|
14941
|
+
if (runtimeDir === void 0) socketPath = socketPathFor(void 0, home);
|
|
14942
|
+
else {
|
|
14943
|
+
socketPathFor(runtimeDir.dir, home);
|
|
14944
|
+
socketPath = socketPathFor(prepareOwnedDirectory(runtimeDir.dir).realPath, home);
|
|
14945
|
+
}
|
|
14555
14946
|
const redactor = new Redactor();
|
|
14556
14947
|
redactor.protectEnvironment(options.env);
|
|
14557
14948
|
const log = openFileLog({
|
|
@@ -14561,10 +14952,10 @@ async function acquireHome(options) {
|
|
|
14561
14952
|
});
|
|
14562
14953
|
if (prepared.tightenedFrom !== void 0) log.warn("home.tightened", {
|
|
14563
14954
|
home,
|
|
14564
|
-
from: prepared.tightenedFrom
|
|
14565
|
-
to: "
|
|
14955
|
+
from: prepared.tightenedFrom,
|
|
14956
|
+
to: "owner only"
|
|
14566
14957
|
});
|
|
14567
|
-
if (runtimeDir
|
|
14958
|
+
if (runtimeDir?.rejected !== void 0) log.warn("home.xdg_runtime_dir_rejected", {
|
|
14568
14959
|
reason: runtimeDir.rejected,
|
|
14569
14960
|
using: runtimeDir.dir
|
|
14570
14961
|
});
|
|
@@ -14655,11 +15046,11 @@ function own(inputs) {
|
|
|
14655
15046
|
redactor,
|
|
14656
15047
|
self,
|
|
14657
15048
|
startedAt,
|
|
14658
|
-
publish(mode) {
|
|
15049
|
+
publish(mode, socket) {
|
|
14659
15050
|
writeInstanceRecord(home, {
|
|
14660
15051
|
pid: self.pid,
|
|
14661
15052
|
startTime: self.startTime,
|
|
14662
|
-
socket
|
|
15053
|
+
socket,
|
|
14663
15054
|
runtimeVersion: inputs.options.runtimeVersion,
|
|
14664
15055
|
revisions: [...HOST_PROTOCOL_REVISIONS],
|
|
14665
15056
|
mode,
|
|
@@ -14694,21 +15085,27 @@ function own(inputs) {
|
|
|
14694
15085
|
//#endregion
|
|
14695
15086
|
//#region src/home/platform.ts
|
|
14696
15087
|
/**
|
|
14697
|
-
* The unsupported-platform gate (D35, RT-07). Every entry point calls it before it touches
|
|
14698
|
-
* home: Mostra
|
|
15088
|
+
* The unsupported-platform gate (D35, D146, RT-07). Every entry point calls it before it touches
|
|
15089
|
+
* the home: Mostra runs on macOS and Linux, on x64 and arm64, and fails closed elsewhere. Windows
|
|
15090
|
+
* (x64 and arm64) is being built (WP-W1 to WP-W3) and runs only behind the development switch
|
|
15091
|
+
* `MOSTRA_DEV_WINDOWS=1`, which only Mostra's own CI sets, so no release exposes a partial port.
|
|
15092
|
+
* WP-W3 removes the switch.
|
|
14699
15093
|
*/
|
|
14700
15094
|
const OPERATING_SYSTEMS = ["darwin", "linux"];
|
|
14701
15095
|
const ARCHITECTURES = ["x64", "arm64"];
|
|
14702
15096
|
/** The platform as `<os>-<arch>`, as `InstanceInfo.platform` reports it. */
|
|
14703
|
-
function platformName(platform =
|
|
15097
|
+
function platformName(platform = OS, arch = process.arch) {
|
|
14704
15098
|
return `${platform}-${arch}`;
|
|
14705
15099
|
}
|
|
14706
15100
|
/**
|
|
14707
15101
|
* Returns `MOSTRA_PLATFORM_UNSUPPORTED` for a platform Mostra doesn't run on, or `undefined` for
|
|
14708
|
-
* a supported one.
|
|
15102
|
+
* a supported one. Windows is supported only while `env` sets the development switch to `1`.
|
|
14709
15103
|
*/
|
|
14710
|
-
function checkPlatform(platform = process.
|
|
14711
|
-
if (
|
|
15104
|
+
function checkPlatform(platform = OS, arch = process.arch, env = process.env) {
|
|
15105
|
+
if (ARCHITECTURES.includes(arch)) {
|
|
15106
|
+
if (OPERATING_SYSTEMS.includes(platform)) return void 0;
|
|
15107
|
+
if (platform === "win32" && env["MOSTRA_DEV_WINDOWS"] === "1") return void 0;
|
|
15108
|
+
}
|
|
14712
15109
|
const name = platform === "win32" ? `Windows (${platformName(platform, arch)})` : platformName(platform, arch);
|
|
14713
15110
|
return createDiagnostic("MOSTRA_PLATFORM_UNSUPPORTED", { message: `Mostra doesn't run on ${name}; it supports macOS and Linux on x64 and arm64.` });
|
|
14714
15111
|
}
|
|
@@ -14771,19 +15168,9 @@ function writeHomeSettings(home, change) {
|
|
|
14771
15168
|
const file = join(home, SETTINGS_FILE);
|
|
14772
15169
|
const temporary = `${file}.${process.pid}.tmp`;
|
|
14773
15170
|
writeFileSync(temporary, `${JSON.stringify(next, null, 2)}\n`, { mode: 384 });
|
|
14774
|
-
|
|
14775
|
-
|
|
14776
|
-
|
|
14777
|
-
} finally {
|
|
14778
|
-
closeSync(handle);
|
|
14779
|
-
}
|
|
14780
|
-
renameSync(temporary, file);
|
|
14781
|
-
const dir = openSync(home, "r");
|
|
14782
|
-
try {
|
|
14783
|
-
fsyncSync(dir);
|
|
14784
|
-
} catch {} finally {
|
|
14785
|
-
closeSync(dir);
|
|
14786
|
-
}
|
|
15171
|
+
fsyncPath(temporary);
|
|
15172
|
+
renamePathSync(temporary, file);
|
|
15173
|
+
fsyncPath(home, true);
|
|
14787
15174
|
}
|
|
14788
15175
|
/**
|
|
14789
15176
|
* Marks the home as configured by a host (D140 item 4), once: the first host's client name and
|
|
@@ -14873,7 +15260,7 @@ function openSecrets(options) {
|
|
|
14873
15260
|
flag: "w"
|
|
14874
15261
|
});
|
|
14875
15262
|
chmodSync(temporary, 384);
|
|
14876
|
-
|
|
15263
|
+
renamePathSync(temporary, join(dir, name));
|
|
14877
15264
|
options.log.info("secret.set", {
|
|
14878
15265
|
name,
|
|
14879
15266
|
scope: scope.kind
|
|
@@ -14989,7 +15376,7 @@ function userHome(env) {
|
|
|
14989
15376
|
/** The service a home's daemon would be, installed or not. */
|
|
14990
15377
|
function serviceFor(spec) {
|
|
14991
15378
|
const env = spec.env ?? process.env;
|
|
14992
|
-
const platform = spec.platform ??
|
|
15379
|
+
const platform = spec.platform ?? OS;
|
|
14993
15380
|
const hash = homeHash(spec.home);
|
|
14994
15381
|
const command = [
|
|
14995
15382
|
spec.node,
|
|
@@ -15372,7 +15759,7 @@ async function assemble(home, options) {
|
|
|
15372
15759
|
let runner;
|
|
15373
15760
|
let verifier;
|
|
15374
15761
|
const sandboxOptions = () => {
|
|
15375
|
-
const workerLocation = locateWorker(environment, runtimeRoot());
|
|
15762
|
+
const workerLocation = locateWorker(environment, runtimeRoot$1());
|
|
15376
15763
|
return {
|
|
15377
15764
|
home: home.path,
|
|
15378
15765
|
log,
|
|
@@ -15394,7 +15781,7 @@ async function assemble(home, options) {
|
|
|
15394
15781
|
};
|
|
15395
15782
|
const getVerifier = () => {
|
|
15396
15783
|
if (verifier) return verifier;
|
|
15397
|
-
const located = locateRunner(environment, runtimeRoot());
|
|
15784
|
+
const located = locateRunner(environment, runtimeRoot$1());
|
|
15398
15785
|
runner = createRunnerClient({
|
|
15399
15786
|
processes: manager,
|
|
15400
15787
|
log,
|
|
@@ -15482,7 +15869,7 @@ async function assemble(home, options) {
|
|
|
15482
15869
|
const testLease = Number(environment["MOSTRA_TEST_INTEREST_LEASE_MS"]);
|
|
15483
15870
|
const bus = createEphemeralBus(testLease > 0 ? { leaseMs: testLease } : {});
|
|
15484
15871
|
const workerSocket = environment["MOSTRA_TEST_WORKER_HOST"];
|
|
15485
|
-
const located = locateWorker(environment, runtimeRoot());
|
|
15872
|
+
const located = locateWorker(environment, runtimeRoot$1());
|
|
15486
15873
|
const launcher = workerSocket ? socketLauncher(workerSocket) : localLauncher({
|
|
15487
15874
|
processes: manager,
|
|
15488
15875
|
home: home.path,
|
|
@@ -15742,7 +16129,7 @@ async function assemble(home, options) {
|
|
|
15742
16129
|
...sessionMethods({
|
|
15743
16130
|
describe: () => info,
|
|
15744
16131
|
startedAt: home.startedAt,
|
|
15745
|
-
socketPath: () => home.socketPath,
|
|
16132
|
+
socketPath: () => server.socketPath ?? home.socketPath,
|
|
15746
16133
|
connections: () => server.connections,
|
|
15747
16134
|
processes: () => manager.list(),
|
|
15748
16135
|
gateway: () => gatewayStarted ? {
|
|
@@ -15769,7 +16156,9 @@ async function assemble(home, options) {
|
|
|
15769
16156
|
});
|
|
15770
16157
|
const instance = {
|
|
15771
16158
|
info,
|
|
15772
|
-
socketPath
|
|
16159
|
+
get socketPath() {
|
|
16160
|
+
return server.socketPath ?? home.socketPath;
|
|
16161
|
+
},
|
|
15773
16162
|
processes: manager,
|
|
15774
16163
|
reaped,
|
|
15775
16164
|
stopped,
|
|
@@ -15783,7 +16172,7 @@ async function assemble(home, options) {
|
|
|
15783
16172
|
stopWatchingPublishes();
|
|
15784
16173
|
live.stop();
|
|
15785
16174
|
interaction.stop();
|
|
15786
|
-
server.close();
|
|
16175
|
+
await server.close();
|
|
15787
16176
|
await dev.stopAll();
|
|
15788
16177
|
await gateway.close();
|
|
15789
16178
|
await pool.stopAll();
|
|
@@ -15817,15 +16206,37 @@ async function assemble(home, options) {
|
|
|
15817
16206
|
try {
|
|
15818
16207
|
await gateway.start();
|
|
15819
16208
|
gatewayStarted = true;
|
|
15820
|
-
|
|
16209
|
+
const launchPipe = async (name) => {
|
|
16210
|
+
const child = await manager.spawn({
|
|
16211
|
+
kind: "control-pipe",
|
|
16212
|
+
ownerRef: home.path,
|
|
16213
|
+
command: helperPath(),
|
|
16214
|
+
args: ["pipe", name],
|
|
16215
|
+
channel: true
|
|
16216
|
+
});
|
|
16217
|
+
if (!child.channel) throw new Error("The control pipe's helper has no channel.");
|
|
16218
|
+
return {
|
|
16219
|
+
channel: child.channel,
|
|
16220
|
+
exited: child.exited,
|
|
16221
|
+
stop: () => child.stop(2e3)
|
|
16222
|
+
};
|
|
16223
|
+
};
|
|
16224
|
+
await server.listen(home.socketPath, options.checkIntervalMs, {
|
|
16225
|
+
launchPipe,
|
|
16226
|
+
onMoved: (path) => {
|
|
16227
|
+
faults.at("endpoint:moved");
|
|
16228
|
+
home.publish(options.mode, path);
|
|
16229
|
+
log.warn("home.endpoint_moved", { socket: path });
|
|
16230
|
+
}
|
|
16231
|
+
});
|
|
15821
16232
|
interaction.start();
|
|
15822
16233
|
live.start();
|
|
15823
|
-
home.publish(options.mode);
|
|
16234
|
+
home.publish(options.mode, server.socketPath ?? home.socketPath);
|
|
15824
16235
|
if (options.mode === "host" && markHostConfigured(home.path, "mostra-runtime host")) log.info("home.host_configured", { client: "mostra-runtime host" });
|
|
15825
16236
|
} catch (error) {
|
|
15826
16237
|
live.stop();
|
|
15827
16238
|
interaction.stop();
|
|
15828
|
-
server.close();
|
|
16239
|
+
await server.close();
|
|
15829
16240
|
await gateway.close();
|
|
15830
16241
|
await pool.stopAll();
|
|
15831
16242
|
await manager.stopAll();
|
|
@@ -15864,7 +16275,7 @@ async function assemble(home, options) {
|
|
|
15864
16275
|
log.info("instance.started", {
|
|
15865
16276
|
mode: options.mode,
|
|
15866
16277
|
pid: process.pid,
|
|
15867
|
-
socket: home.socketPath,
|
|
16278
|
+
socket: server.socketPath ?? home.socketPath,
|
|
15868
16279
|
shell: gateway.shellOrigin()
|
|
15869
16280
|
});
|
|
15870
16281
|
return instance;
|
|
@@ -15917,4 +16328,4 @@ function sourceDirectory(path) {
|
|
|
15917
16328
|
//#endregion
|
|
15918
16329
|
export { uninstallService as a, serviceStatus as i, startInstance as n, checkPlatform as o, installService as r, resolveHomePath as s, runtimeVersion as t };
|
|
15919
16330
|
|
|
15920
|
-
//# sourceMappingURL=instance-
|
|
16331
|
+
//# sourceMappingURL=instance-DiKSe7s6.js.map
|