@mostra/runtime 0.1.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-D7_UVdoN.js → instance-DiKSe7s6.js} +1331 -752
- 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/actions.ts +1 -1
- package/src/gateway/browser.ts +1 -1
- package/src/gateway/capabilities.ts +28 -7
- package/src/gateway/identity.ts +101 -0
- package/src/gateway/index.ts +96 -6
- 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 +73 -12
- package/src/interaction/index.ts +4 -0
- package/src/interaction/viewers.ts +16 -2
- package/src/ledger/index.ts +5 -27
- package/src/ledger/migrations.ts +13 -0
- 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 +84 -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 +3 -3
- 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-D7_UVdoN.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
|
-
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, 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";
|
|
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";
|
|
@@ -857,7 +857,833 @@ function coverageMatcher(coverage) {
|
|
|
857
857
|
if (entry.id !== void 0) ids.add(entry.id);
|
|
858
858
|
else if (entry.template !== void 0) templates.push(new RegExp(`^${entry.template.map(escapeRegExp).join("[\\s\\S]*")}$`));
|
|
859
859
|
}
|
|
860
|
-
return (fieldId) => ids.has(fieldId) || templates.some((pattern) => pattern.test(fieldId));
|
|
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}.
|
|
1563
|
+
*/
|
|
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;
|
|
1685
|
+
}
|
|
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);
|
|
@@ -1620,6 +2447,15 @@ const MIGRATIONS = [
|
|
|
1620
2447
|
BEGIN
|
|
1621
2448
|
SELECT RAISE(ABORT, 'a version row is kept forever, collected or not');
|
|
1622
2449
|
END;
|
|
2450
|
+
`);
|
|
2451
|
+
}
|
|
2452
|
+
},
|
|
2453
|
+
{
|
|
2454
|
+
version: 10,
|
|
2455
|
+
name: "session viewers",
|
|
2456
|
+
up(db) {
|
|
2457
|
+
db.exec(`
|
|
2458
|
+
ALTER TABLE session ADD COLUMN viewer_id TEXT REFERENCES viewer(id);
|
|
1623
2459
|
`);
|
|
1624
2460
|
}
|
|
1625
2461
|
}
|
|
@@ -1746,12 +2582,7 @@ function createLedgerFile(storeDir, file, log) {
|
|
|
1746
2582
|
} finally {
|
|
1747
2583
|
db.close();
|
|
1748
2584
|
}
|
|
1749
|
-
|
|
1750
|
-
try {
|
|
1751
|
-
fsyncSync(fd);
|
|
1752
|
-
} finally {
|
|
1753
|
-
closeSync(fd);
|
|
1754
|
-
}
|
|
2585
|
+
fsyncPath(temp);
|
|
1755
2586
|
try {
|
|
1756
2587
|
linkSync(temp, file);
|
|
1757
2588
|
log.info("ledger.created", { file });
|
|
@@ -1763,14 +2594,7 @@ function createLedgerFile(storeDir, file, log) {
|
|
|
1763
2594
|
syncDirectory(storeDir);
|
|
1764
2595
|
}
|
|
1765
2596
|
function syncDirectory(dir) {
|
|
1766
|
-
|
|
1767
|
-
const fd = openSync(dir, "r");
|
|
1768
|
-
try {
|
|
1769
|
-
fsyncSync(fd);
|
|
1770
|
-
} finally {
|
|
1771
|
-
closeSync(fd);
|
|
1772
|
-
}
|
|
1773
|
-
} catch {}
|
|
2597
|
+
fsyncPath(dir, true);
|
|
1774
2598
|
}
|
|
1775
2599
|
/**
|
|
1776
2600
|
* Removes `*.creating` files left by starters that died while building a ledger. A file whose
|
|
@@ -2023,6 +2847,9 @@ const PASSED = /* @__PURE__ */ new Set([
|
|
|
2023
2847
|
"SSL_CERT_FILE",
|
|
2024
2848
|
"SSL_CERT_DIR"
|
|
2025
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()));
|
|
2026
2853
|
/** npm's own configuration channel: the user's registry, scopes and proxies for installs. */
|
|
2027
2854
|
const NPM_CONFIG = /^npm_config_/i;
|
|
2028
2855
|
/**
|
|
@@ -2032,207 +2859,35 @@ const NPM_CONFIG = /^npm_config_/i;
|
|
|
2032
2859
|
*/
|
|
2033
2860
|
function artifactEnvironment(env) {
|
|
2034
2861
|
const result = {};
|
|
2862
|
+
let pathName = "PATH";
|
|
2035
2863
|
for (const [name, value] of Object.entries(env)) {
|
|
2036
2864
|
if (value === void 0) continue;
|
|
2037
|
-
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;
|
|
2038
2870
|
}
|
|
2039
2871
|
const own = dirname(process.execPath);
|
|
2040
|
-
const path = result[
|
|
2041
|
-
|
|
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}`;
|
|
2042
2876
|
return result;
|
|
2043
2877
|
}
|
|
2044
2878
|
//#endregion
|
|
2045
|
-
//#region src/processes/identity.ts
|
|
2046
|
-
/**
|
|
2047
|
-
* Process identity (DATA_MODEL §3 `child.start_time`, FAILURE_MODEL §2). A PID alone can be
|
|
2048
|
-
* reused, so a process is identified by its PID plus an opaque start time: the boot it started in
|
|
2049
|
-
* and when it started within that boot. Linux reads `/proc/<pid>/stat` (start ticks since boot)
|
|
2050
|
-
* and the boot ID; macOS reads `ps -o lstart` (seconds) and `kern.boottime` (VERIFIED_FACTS,
|
|
2051
|
-
* WP-02). Zombies count as gone: they have exited and only wait for their parent.
|
|
2052
|
-
*
|
|
2053
|
-
* Seconds are enough on macOS (issue #8): XNU hands out PIDs in order from the last one, up to
|
|
2054
|
-
* 99,999, then from 100, skipping any PID still used as a process, process group or session
|
|
2055
|
-
* (`forkproc` in `bsd/kern/kern_fork.c`). A PID comes back only after the whole range has been
|
|
2056
|
-
* handed out, about 99,900 forks, which takes this machine about 100 s at its measured 1,000
|
|
2057
|
-
* spawns a second, and never while its process group lives (VERIFIED_FACTS, WP-08).
|
|
2058
|
-
*/
|
|
2059
|
-
/** Splits a start time into its boot and its position within the boot. */
|
|
2060
|
-
function parts(startTime) {
|
|
2061
|
-
const slash = startTime.lastIndexOf("/");
|
|
2062
|
-
if (slash <= 0) return void 0;
|
|
2063
|
-
const at = Number(startTime.slice(slash + 1));
|
|
2064
|
-
return Number.isSafeInteger(at) ? {
|
|
2065
|
-
boot: startTime.slice(0, slash),
|
|
2066
|
-
at
|
|
2067
|
-
} : void 0;
|
|
2068
|
-
}
|
|
2069
|
-
/** Whether two start times belong to the same boot of the machine. */
|
|
2070
|
-
function sameBoot(a, b) {
|
|
2071
|
-
const left = parts(a);
|
|
2072
|
-
const right = parts(b);
|
|
2073
|
-
return left !== void 0 && right !== void 0 && left.boot === right.boot;
|
|
2074
|
-
}
|
|
2075
|
-
/**
|
|
2076
|
-
* Whether `candidate` started in the same boot as `reference` and no earlier. On macOS the
|
|
2077
|
-
* resolution is one second, so a process started in the same second counts as no earlier.
|
|
2078
|
-
*/
|
|
2079
|
-
function startedNoEarlier(candidate, reference) {
|
|
2080
|
-
const c = parts(candidate);
|
|
2081
|
-
const r = parts(reference);
|
|
2082
|
-
return c !== void 0 && r !== void 0 && c.boot === r.boot && c.at >= r.at;
|
|
2083
|
-
}
|
|
2084
|
-
/** Parses one `/proc/<pid>/stat` line. `comm` may contain spaces and parentheses. */
|
|
2085
|
-
function parseProcStat(line, boot) {
|
|
2086
|
-
const open = line.indexOf("(");
|
|
2087
|
-
const close = line.lastIndexOf(")");
|
|
2088
|
-
if (open < 0 || close < open) return void 0;
|
|
2089
|
-
const pid = Number(line.slice(0, open).trim());
|
|
2090
|
-
const rest = line.slice(close + 1).trim().split(/\s+/);
|
|
2091
|
-
if (rest[0] === "Z") return void 0;
|
|
2092
|
-
const pgid = Number(rest[2]);
|
|
2093
|
-
const start = rest[19];
|
|
2094
|
-
if (!Number.isSafeInteger(pid) || !Number.isSafeInteger(pgid) || start === void 0) return;
|
|
2095
|
-
if (!/^\d+$/.test(start)) return void 0;
|
|
2096
|
-
return {
|
|
2097
|
-
pid,
|
|
2098
|
-
pgid,
|
|
2099
|
-
startTime: `${boot}/${start}`
|
|
2100
|
-
};
|
|
2101
|
-
}
|
|
2102
|
-
const MONTHS = [
|
|
2103
|
-
"Jan",
|
|
2104
|
-
"Feb",
|
|
2105
|
-
"Mar",
|
|
2106
|
-
"Apr",
|
|
2107
|
-
"May",
|
|
2108
|
-
"Jun",
|
|
2109
|
-
"Jul",
|
|
2110
|
-
"Aug",
|
|
2111
|
-
"Sep",
|
|
2112
|
-
"Oct",
|
|
2113
|
-
"Nov",
|
|
2114
|
-
"Dec"
|
|
2115
|
-
];
|
|
2116
|
-
/**
|
|
2117
|
-
* Parses one line of `LC_ALL=C TZ=UTC ps -o pid=,pgid=,stat=,lstart=`, such as
|
|
2118
|
-
* ` 214 99444 Ss Tue Oct 6 13:53:19 2026`. Zombies (`stat` starting with `Z`) are skipped.
|
|
2119
|
-
*/
|
|
2120
|
-
function parsePsLine(line, boot) {
|
|
2121
|
-
const fields = line.trim().split(/\s+/);
|
|
2122
|
-
if (fields.length < 8) return void 0;
|
|
2123
|
-
const [pidText, pgidText, stat, , monthText, dayText, timeText, yearText] = fields;
|
|
2124
|
-
if (stat?.startsWith("Z")) return void 0;
|
|
2125
|
-
const pid = Number(pidText);
|
|
2126
|
-
const pgid = Number(pgidText);
|
|
2127
|
-
const month = MONTHS.indexOf(monthText ?? "");
|
|
2128
|
-
const [hours, minutes, seconds] = (timeText ?? "").split(":").map(Number);
|
|
2129
|
-
const millis = Date.UTC(Number(yearText), month, Number(dayText), hours ?? NaN, minutes ?? NaN, seconds ?? NaN);
|
|
2130
|
-
if (!Number.isSafeInteger(pid) || !Number.isSafeInteger(pgid) || month < 0 || Number.isNaN(millis)) return;
|
|
2131
|
-
return {
|
|
2132
|
-
pid,
|
|
2133
|
-
pgid,
|
|
2134
|
-
startTime: `${boot}/${millis / 1e3}`
|
|
2135
|
-
};
|
|
2136
|
-
}
|
|
2137
|
-
function run$1(file, args) {
|
|
2138
|
-
return new Promise((resolve, reject) => {
|
|
2139
|
-
execFile(file, args, {
|
|
2140
|
-
env: {
|
|
2141
|
-
LC_ALL: "C",
|
|
2142
|
-
TZ: "UTC",
|
|
2143
|
-
PATH: "/usr/bin:/bin:/usr/sbin:/sbin"
|
|
2144
|
-
},
|
|
2145
|
-
maxBuffer: 67108864
|
|
2146
|
-
}, (error, stdout) => {
|
|
2147
|
-
if (error && typeof error.code !== "number") {
|
|
2148
|
-
reject(error);
|
|
2149
|
-
return;
|
|
2150
|
-
}
|
|
2151
|
-
resolve({
|
|
2152
|
-
code: typeof error?.code === "number" ? error.code : 0,
|
|
2153
|
-
stdout
|
|
2154
|
-
});
|
|
2155
|
-
});
|
|
2156
|
-
});
|
|
2157
|
-
}
|
|
2158
|
-
let cachedBoot;
|
|
2159
|
-
/** The identity of the current boot of this machine. */
|
|
2160
|
-
function bootId() {
|
|
2161
|
-
cachedBoot ??= (async () => {
|
|
2162
|
-
if (process.platform === "linux") return (await readFile("/proc/sys/kernel/random/boot_id", "utf8")).trim();
|
|
2163
|
-
const { stdout } = await run$1("/usr/sbin/sysctl", ["-n", "kern.boottime"]);
|
|
2164
|
-
const match = /sec = (\d+), usec = (\d+)/.exec(stdout);
|
|
2165
|
-
if (!match) throw new Error("Couldn't read kern.boottime.");
|
|
2166
|
-
return `${match[1]}.${match[2]}`;
|
|
2167
|
-
})();
|
|
2168
|
-
return cachedBoot;
|
|
2169
|
-
}
|
|
2170
|
-
/** Reads one process, or `undefined` when no process has that PID. */
|
|
2171
|
-
async function readProcess(pid) {
|
|
2172
|
-
const boot = await bootId();
|
|
2173
|
-
if (process.platform === "linux") try {
|
|
2174
|
-
return parseProcStat(await readFile(`/proc/${pid}/stat`, "utf8"), boot);
|
|
2175
|
-
} catch {
|
|
2176
|
-
return;
|
|
2177
|
-
}
|
|
2178
|
-
const { code, stdout } = await run$1("/bin/ps", [
|
|
2179
|
-
"-o",
|
|
2180
|
-
"pid=,pgid=,stat=,lstart=",
|
|
2181
|
-
"-p",
|
|
2182
|
-
String(pid)
|
|
2183
|
-
]);
|
|
2184
|
-
if (code !== 0) return void 0;
|
|
2185
|
-
const [line] = stdout.split("\n").filter((text) => text.trim() !== "");
|
|
2186
|
-
return line === void 0 ? void 0 : parsePsLine(line, boot);
|
|
2187
|
-
}
|
|
2188
|
-
/** Lists every process the user can see. */
|
|
2189
|
-
async function listProcesses() {
|
|
2190
|
-
const boot = await bootId();
|
|
2191
|
-
if (process.platform === "linux") {
|
|
2192
|
-
const entries = (await readdir("/proc")).filter((name) => /^\d+$/.test(name));
|
|
2193
|
-
return (await Promise.all(entries.map(async (name) => {
|
|
2194
|
-
try {
|
|
2195
|
-
return parseProcStat(await readFile(`/proc/${name}/stat`, "utf8"), boot);
|
|
2196
|
-
} catch {
|
|
2197
|
-
return;
|
|
2198
|
-
}
|
|
2199
|
-
}))).filter((info) => info !== void 0);
|
|
2200
|
-
}
|
|
2201
|
-
const { stdout } = await run$1("/bin/ps", [
|
|
2202
|
-
"-A",
|
|
2203
|
-
"-o",
|
|
2204
|
-
"pid=,pgid=,stat=,lstart="
|
|
2205
|
-
]);
|
|
2206
|
-
return stdout.split("\n").map((line) => parsePsLine(line, boot)).filter((info) => info !== void 0);
|
|
2207
|
-
}
|
|
2208
|
-
/** Whether the process recorded as `pid` and `startTime` is still the one running. */
|
|
2209
|
-
async function isSameProcess(pid, startTime) {
|
|
2210
|
-
const info = await readProcess(pid);
|
|
2211
|
-
return info !== void 0 && info.startTime === startTime;
|
|
2212
|
-
}
|
|
2213
|
-
//#endregion
|
|
2214
2879
|
//#region src/processes/manager.ts
|
|
2215
2880
|
/**
|
|
2216
|
-
* The process manager (RT-09, ARCHITECTURE §4, FAILURE_MODEL §2). Every child
|
|
2217
|
-
*
|
|
2218
|
-
*
|
|
2219
|
-
*
|
|
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.
|
|
2220
2886
|
*/
|
|
2221
2887
|
/** How long a stopping child gets between SIGTERM and SIGKILL, by default. */
|
|
2222
2888
|
const DEFAULT_GRACE_MS = 5e3;
|
|
2223
|
-
/** How long reaping waits between SIGTERM and SIGKILL. */
|
|
2224
|
-
const REAP_GRACE_MS = 2e3;
|
|
2225
|
-
/** How long to wait for SIGKILLed processes to disappear before reporting them. */
|
|
2226
|
-
const KILL_WAIT_MS = 5e3;
|
|
2227
2889
|
/** How many stderr lines a child's exit report keeps. */
|
|
2228
2890
|
const STDERR_TAIL = 50;
|
|
2229
|
-
/**
|
|
2230
|
-
* The gate every child starts behind (issue #7): `/bin/sh` waits for "go" on file descriptor 3 and
|
|
2231
|
-
* only then replaces itself with the real command, keeping its PID, process group and start time.
|
|
2232
|
-
* The supervisor writes "go" after it has recorded the child, so a supervisor killed in between
|
|
2233
|
-
* leaves a gate that reads end-of-file and exits 125 without running anything.
|
|
2234
|
-
*/
|
|
2235
|
-
const GATE_SCRIPT = "IFS= read -r go <&3 && [ \"$go\" = go ] || exit 125; exec 3<&-; exec \"$@\"";
|
|
2236
2891
|
const AdoptParams = z.object({ pid: z.int().min(2) });
|
|
2237
2892
|
/**
|
|
2238
2893
|
* Opens the process manager: first reaps every child a previous supervisor of this home left
|
|
@@ -2240,28 +2895,12 @@ const AdoptParams = z.object({ pid: z.int().min(2) });
|
|
|
2240
2895
|
* ledger lock, so no live supervisor's children are touched.
|
|
2241
2896
|
*/
|
|
2242
2897
|
async function openProcessManager(options) {
|
|
2243
|
-
const reaped = await
|
|
2898
|
+
const reaped = await reap(options.ledger, options.log);
|
|
2244
2899
|
return {
|
|
2245
2900
|
manager: createManager(options),
|
|
2246
2901
|
reaped
|
|
2247
2902
|
};
|
|
2248
2903
|
}
|
|
2249
|
-
/** Signals `pids`, ignoring ones already gone. */
|
|
2250
|
-
function signalAll(pids, signal) {
|
|
2251
|
-
for (const pid of pids) try {
|
|
2252
|
-
process.kill(pid, signal);
|
|
2253
|
-
} catch {}
|
|
2254
|
-
}
|
|
2255
|
-
function signalGroup(pgid, signal) {
|
|
2256
|
-
try {
|
|
2257
|
-
process.kill(-pgid, signal);
|
|
2258
|
-
return true;
|
|
2259
|
-
} catch {
|
|
2260
|
-
return false;
|
|
2261
|
-
}
|
|
2262
|
-
}
|
|
2263
|
-
const groupAlive = (pgid) => signalGroup(pgid, 0);
|
|
2264
|
-
const delay$1 = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
2265
2904
|
/** Waits for `promise` to settle, or `ms` at most, leaving no timer behind. */
|
|
2266
2905
|
async function settleWithin(promise, ms) {
|
|
2267
2906
|
let timer;
|
|
@@ -2270,67 +2909,30 @@ async function settleWithin(promise, ms) {
|
|
|
2270
2909
|
timer = setTimeout(resolve, ms);
|
|
2271
2910
|
})]);
|
|
2272
2911
|
} finally {
|
|
2273
|
-
clearTimeout(timer);
|
|
2274
|
-
}
|
|
2275
|
-
}
|
|
2276
|
-
|
|
2277
|
-
|
|
2278
|
-
|
|
2279
|
-
|
|
2280
|
-
if (!leader) {
|
|
2281
|
-
const boot = processes.find((info) => info.pid === process.pid)?.startTime;
|
|
2282
|
-
if (boot === void 0 || !sameBoot(boot, row.start_time)) return "other boot";
|
|
2283
|
-
}
|
|
2284
|
-
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);
|
|
2285
|
-
return members.length > 0 ? members : "gone";
|
|
2286
|
-
}
|
|
2287
|
-
async function reapRecorded(ledger, log) {
|
|
2288
|
-
const rows = ledger.read((db) => db.all("SELECT * FROM child ORDER BY started_at"));
|
|
2289
|
-
if (rows.length === 0) return [];
|
|
2290
|
-
const before = await listProcesses();
|
|
2291
|
-
const plan = rows.map((row) => ({
|
|
2292
|
-
row,
|
|
2293
|
-
targets: targetsFor(row, before)
|
|
2294
|
-
}));
|
|
2295
|
-
const owned = plan.filter((entry) => Array.isArray(entry.targets)).map((entry) => entry.row);
|
|
2296
|
-
const members = (processes) => [...new Set(owned.flatMap((row) => {
|
|
2297
|
-
const targets = targetsFor(row, processes);
|
|
2298
|
-
return Array.isArray(targets) ? targets : [];
|
|
2299
|
-
}))];
|
|
2300
|
-
const groupsLeft = () => owned.some((row) => groupAlive(row.pgid));
|
|
2301
|
-
signalAll(members(before), "SIGTERM");
|
|
2302
|
-
const deadline = Date.now() + REAP_GRACE_MS;
|
|
2303
|
-
let remaining = members(await listProcesses());
|
|
2304
|
-
while ((remaining.length > 0 || groupsLeft()) && Date.now() < deadline) {
|
|
2305
|
-
await delay$1(100);
|
|
2306
|
-
remaining = members(await listProcesses());
|
|
2307
|
-
}
|
|
2308
|
-
const killDeadline = Date.now() + KILL_WAIT_MS;
|
|
2309
|
-
while ((remaining.length > 0 || groupsLeft()) && Date.now() < killDeadline) {
|
|
2310
|
-
signalAll(remaining, "SIGKILL");
|
|
2311
|
-
await delay$1(50);
|
|
2312
|
-
remaining = members(await listProcesses());
|
|
2313
|
-
}
|
|
2314
|
-
if (remaining.length > 0 || groupsLeft()) log.warn("process.reap_incomplete", {
|
|
2315
|
-
pids: remaining,
|
|
2316
|
-
pgids: owned.map((row) => row.pgid)
|
|
2317
|
-
});
|
|
2912
|
+
clearTimeout(timer);
|
|
2913
|
+
}
|
|
2914
|
+
}
|
|
2915
|
+
async function reap(ledger, log) {
|
|
2916
|
+
const rows = ledger.read((db) => db.all("SELECT * FROM child ORDER BY started_at"));
|
|
2917
|
+
if (rows.length === 0) return [];
|
|
2918
|
+
const outcomes = await reapRecorded(rows, (event, fields) => log.warn(event, fields));
|
|
2318
2919
|
ledger.write((db) => {
|
|
2319
|
-
for (const
|
|
2920
|
+
for (const row of rows) db.run("DELETE FROM child WHERE pid = ? AND start_time = ?", row.pid, row.start_time);
|
|
2320
2921
|
});
|
|
2321
|
-
const report =
|
|
2922
|
+
const report = rows.map((row, index) => {
|
|
2322
2923
|
const base = {
|
|
2323
2924
|
pid: row.pid,
|
|
2324
2925
|
kind: row.kind,
|
|
2325
2926
|
ownerRef: row.owner_ref
|
|
2326
2927
|
};
|
|
2327
|
-
|
|
2928
|
+
const outcome = outcomes[index];
|
|
2929
|
+
return outcome?.skipped === void 0 ? {
|
|
2328
2930
|
...base,
|
|
2329
|
-
signalled:
|
|
2931
|
+
signalled: outcome?.ended ?? []
|
|
2330
2932
|
} : {
|
|
2331
2933
|
...base,
|
|
2332
2934
|
signalled: [],
|
|
2333
|
-
skipped:
|
|
2935
|
+
skipped: outcome.skipped
|
|
2334
2936
|
};
|
|
2335
2937
|
});
|
|
2336
2938
|
for (const entry of report) log.info("process.reaped", { ...entry });
|
|
@@ -2345,62 +2947,27 @@ function createManager({ ledger, log, redactor, faults = noFaults }) {
|
|
|
2345
2947
|
const forget = (pid) => {
|
|
2346
2948
|
ledger.write((db) => db.run("DELETE FROM child WHERE pid = ? OR parent_pid = ?", pid, pid));
|
|
2347
2949
|
};
|
|
2348
|
-
|
|
2349
|
-
* Terminates groups: SIGTERM, then SIGKILL after `graceMs` to those still present, then waits
|
|
2350
|
-
* (boundedly) until they are gone.
|
|
2351
|
-
*/
|
|
2352
|
-
const endGroups = async (pgids, graceMs) => {
|
|
2353
|
-
for (const pgid of pgids) signalGroup(pgid, "SIGTERM");
|
|
2354
|
-
const deadline = Date.now() + graceMs;
|
|
2355
|
-
while (Date.now() < deadline && pgids.some(groupAlive)) await delay$1(25);
|
|
2356
|
-
for (const pgid of pgids) if (groupAlive(pgid)) signalGroup(pgid, "SIGKILL");
|
|
2357
|
-
const killDeadline = Date.now() + KILL_WAIT_MS;
|
|
2358
|
-
while (Date.now() < killDeadline && pgids.some(groupAlive)) await delay$1(10);
|
|
2359
|
-
const left = pgids.filter(groupAlive);
|
|
2360
|
-
if (left.length > 0) log.warn("process.group_survived_sigkill", { pgids: left });
|
|
2361
|
-
};
|
|
2950
|
+
const warn = (event, fields) => log.warn(event, fields);
|
|
2362
2951
|
const spawnChild = async (spec) => {
|
|
2363
2952
|
if (stopping) throw new Error("The process manager is stopping.");
|
|
2364
2953
|
if (spec.ipc && spec.channel) throw new Error("A child takes ipc or a channel, not both.");
|
|
2365
2954
|
for (const value of spec.redact ?? []) redactor.protect(value);
|
|
2366
2955
|
redactor.protectEnvironment(spec.env ?? process.env);
|
|
2367
|
-
const
|
|
2368
|
-
|
|
2369
|
-
|
|
2370
|
-
|
|
2371
|
-
spec.command,
|
|
2372
|
-
...spec.args ?? []
|
|
2373
|
-
], {
|
|
2956
|
+
const launched = launch({
|
|
2957
|
+
kind: spec.kind,
|
|
2958
|
+
command: spec.command,
|
|
2959
|
+
args: spec.args ?? [],
|
|
2374
2960
|
cwd: spec.cwd,
|
|
2375
2961
|
env: spec.env ?? process.env,
|
|
2376
|
-
|
|
2377
|
-
|
|
2378
|
-
|
|
2379
|
-
"pipe",
|
|
2380
|
-
"pipe",
|
|
2381
|
-
"pipe",
|
|
2382
|
-
"ipc"
|
|
2383
|
-
] : spec.channel ? [
|
|
2384
|
-
"ignore",
|
|
2385
|
-
"pipe",
|
|
2386
|
-
"pipe",
|
|
2387
|
-
"pipe",
|
|
2388
|
-
"pipe"
|
|
2389
|
-
] : [
|
|
2390
|
-
"ignore",
|
|
2391
|
-
"pipe",
|
|
2392
|
-
"pipe",
|
|
2393
|
-
"pipe"
|
|
2394
|
-
],
|
|
2395
|
-
serialization: "json"
|
|
2396
|
-
});
|
|
2397
|
-
const gate = child.stdio[3];
|
|
2398
|
-
gate?.on("error", () => {});
|
|
2962
|
+
extra: spec.ipc ? "ipc" : spec.channel ? "channel" : void 0
|
|
2963
|
+
}, warn);
|
|
2964
|
+
const child = launched.process;
|
|
2399
2965
|
const startedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
2400
|
-
|
|
2401
|
-
child.once("spawn", () => resolve(
|
|
2966
|
+
await new Promise((resolve, reject) => {
|
|
2967
|
+
child.once("spawn", () => resolve());
|
|
2402
2968
|
child.once("error", reject);
|
|
2403
2969
|
});
|
|
2970
|
+
let pid = child.pid ?? 0;
|
|
2404
2971
|
child.on("error", (error) => log.warn("process.error", {
|
|
2405
2972
|
kind: spec.kind,
|
|
2406
2973
|
pid,
|
|
@@ -2457,15 +3024,16 @@ function createManager({ ledger, log, redactor, faults = noFaults }) {
|
|
|
2457
3024
|
ledger.write((db) => db.run("DELETE FROM child WHERE pid = ? AND parent_pid = ?", parsed.data.pid, pid));
|
|
2458
3025
|
return {};
|
|
2459
3026
|
}
|
|
2460
|
-
const
|
|
2461
|
-
if (!
|
|
2462
|
-
|
|
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);
|
|
2463
3031
|
record({
|
|
2464
|
-
pid: info.pid,
|
|
2465
|
-
start_time: info.startTime,
|
|
3032
|
+
pid: found.info.pid,
|
|
3033
|
+
start_time: found.info.startTime,
|
|
2466
3034
|
kind: `${spec.kind}/adopted`,
|
|
2467
3035
|
owner_ref: spec.ownerRef,
|
|
2468
|
-
pgid: info.pgid,
|
|
3036
|
+
pgid: found.info.pgid,
|
|
2469
3037
|
started_at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2470
3038
|
parent_pid: pid
|
|
2471
3039
|
});
|
|
@@ -2487,28 +3055,28 @@ function createManager({ ledger, log, redactor, faults = noFaults }) {
|
|
|
2487
3055
|
child.on("disconnect", () => connected.close());
|
|
2488
3056
|
}
|
|
2489
3057
|
const registered = (async () => {
|
|
2490
|
-
const info = await
|
|
3058
|
+
const info = await launched.identify();
|
|
2491
3059
|
faults.at("spawn:before-record");
|
|
2492
|
-
|
|
2493
|
-
|
|
2494
|
-
|
|
2495
|
-
|
|
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;
|
|
2496
3064
|
record({
|
|
2497
|
-
pid,
|
|
3065
|
+
pid: info.pid,
|
|
2498
3066
|
start_time: info.startTime,
|
|
2499
3067
|
kind: spec.kind,
|
|
2500
3068
|
owner_ref: spec.ownerRef,
|
|
2501
|
-
pgid: pid,
|
|
3069
|
+
pgid: info.pid,
|
|
2502
3070
|
started_at: startedAt,
|
|
2503
3071
|
parent_pid: null
|
|
2504
3072
|
});
|
|
2505
|
-
|
|
3073
|
+
launched.release();
|
|
2506
3074
|
})();
|
|
2507
3075
|
const exited = exit.then(async ({ code, signal }) => {
|
|
2508
|
-
await
|
|
3076
|
+
await launched.sweep([...adopted.values()]);
|
|
2509
3077
|
await settleWithin(Promise.all(drained), 2e3);
|
|
2510
3078
|
await registered.catch(() => {});
|
|
2511
|
-
running.delete(pid);
|
|
3079
|
+
running.delete(child.pid ?? 0);
|
|
2512
3080
|
try {
|
|
2513
3081
|
forget(pid);
|
|
2514
3082
|
} catch (error) {
|
|
@@ -2535,8 +3103,14 @@ function createManager({ ledger, log, redactor, faults = noFaults }) {
|
|
|
2535
3103
|
pid,
|
|
2536
3104
|
error
|
|
2537
3105
|
}));
|
|
3106
|
+
const stop = async (graceMs = DEFAULT_GRACE_MS) => {
|
|
3107
|
+
if (launched.running()) await launched.end(graceMs, [...adopted.values()]);
|
|
3108
|
+
return exited;
|
|
3109
|
+
};
|
|
2538
3110
|
const handle = {
|
|
2539
|
-
pid
|
|
3111
|
+
get pid() {
|
|
3112
|
+
return pid;
|
|
3113
|
+
},
|
|
2540
3114
|
kind: spec.kind,
|
|
2541
3115
|
ownerRef: spec.ownerRef,
|
|
2542
3116
|
startedAt,
|
|
@@ -2546,12 +3120,12 @@ function createManager({ ledger, log, redactor, faults = noFaults }) {
|
|
|
2546
3120
|
if (!peer) return Promise.reject(/* @__PURE__ */ new Error(`${spec.kind} was started without IPC.`));
|
|
2547
3121
|
return peer.request(method, params, options);
|
|
2548
3122
|
},
|
|
2549
|
-
|
|
2550
|
-
if (child.exitCode === null && child.signalCode === null) await endGroups([pid, ...adopted.values()], graceMs);
|
|
2551
|
-
return exited;
|
|
2552
|
-
}
|
|
3123
|
+
stop
|
|
2553
3124
|
};
|
|
2554
|
-
running.set(pid,
|
|
3125
|
+
running.set(child.pid ?? 0, {
|
|
3126
|
+
handle,
|
|
3127
|
+
kill: () => launched.kill()
|
|
3128
|
+
});
|
|
2555
3129
|
try {
|
|
2556
3130
|
await registered;
|
|
2557
3131
|
} catch (error) {
|
|
@@ -2581,16 +3155,19 @@ function createManager({ ledger, log, redactor, faults = noFaults }) {
|
|
|
2581
3155
|
};
|
|
2582
3156
|
return {
|
|
2583
3157
|
spawn: trackedSpawn,
|
|
2584
|
-
list: () => [...running.values()].map((
|
|
2585
|
-
pid:
|
|
2586
|
-
kind:
|
|
2587
|
-
ownerRef:
|
|
2588
|
-
startedAt:
|
|
3158
|
+
list: () => [...running.values()].map(({ handle }) => ({
|
|
3159
|
+
pid: handle.pid,
|
|
3160
|
+
kind: handle.kind,
|
|
3161
|
+
ownerRef: handle.ownerRef,
|
|
3162
|
+
startedAt: handle.startedAt
|
|
2589
3163
|
})),
|
|
2590
3164
|
async stopAll(graceMs = DEFAULT_GRACE_MS) {
|
|
2591
3165
|
stopping = true;
|
|
2592
3166
|
await Promise.all(inflight);
|
|
2593
|
-
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();
|
|
2594
3171
|
}
|
|
2595
3172
|
};
|
|
2596
3173
|
}
|
|
@@ -2600,20 +3177,6 @@ function createManager({ ledger, log, redactor, faults = noFaults }) {
|
|
|
2600
3177
|
* The warm set (D91, D95): the pre-built, read-only layout every artifact resolves without an
|
|
2601
3178
|
* install. `@mostra/warm`'s `dependencies` are the warm packages; its `node_modules` is the layout.
|
|
2602
3179
|
*/
|
|
2603
|
-
/** The directory of `@mostra/runtime`'s package.json. */
|
|
2604
|
-
function runtimeRoot() {
|
|
2605
|
-
let dir = dirname(fileURLToPath(import.meta.url));
|
|
2606
|
-
for (;;) {
|
|
2607
|
-
const manifest = join(dir, "package.json");
|
|
2608
|
-
if (existsSync(manifest)) {
|
|
2609
|
-
const { name } = JSON.parse(readFileSync(manifest, "utf8"));
|
|
2610
|
-
if (name === "@mostra/runtime") return dir;
|
|
2611
|
-
}
|
|
2612
|
-
const parent = dirname(dir);
|
|
2613
|
-
if (parent === dir) throw new Error("Couldn't find @mostra/runtime's package.json.");
|
|
2614
|
-
dir = parent;
|
|
2615
|
-
}
|
|
2616
|
-
}
|
|
2617
3180
|
function warmMissing(message) {
|
|
2618
3181
|
return new RpcError(createDiagnostic("MOSTRA_ENV_WARM_MISSING", { message }));
|
|
2619
3182
|
}
|
|
@@ -2622,7 +3185,7 @@ function warmMissing(message) {
|
|
|
2622
3185
|
* the runtime bundle and this repository lay it out. Every listed package must be installed.
|
|
2623
3186
|
*/
|
|
2624
3187
|
function locateWarmSet(env) {
|
|
2625
|
-
const dir = env["MOSTRA_WARM_DIR"] ?? resolve(runtimeRoot(), "..", "warm");
|
|
3188
|
+
const dir = env["MOSTRA_WARM_DIR"] ?? resolve(runtimeRoot$1(), "..", "warm");
|
|
2626
3189
|
const manifestFile = join(dir, "package.json");
|
|
2627
3190
|
if (!existsSync(manifestFile)) throw warmMissing(`No warm package set at ${dir}.`);
|
|
2628
3191
|
const { dependencies = {} } = JSON.parse(readFileSync(manifestFile, "utf8"));
|
|
@@ -2652,11 +3215,11 @@ function packageNamed(record, message) {
|
|
|
2652
3215
|
}
|
|
2653
3216
|
/** The install child's entry: the compiled one beside the compiled supervisor, else the source. */
|
|
2654
3217
|
function childEntry() {
|
|
2655
|
-
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");
|
|
2656
3219
|
}
|
|
2657
3220
|
/** Finds pnpm 10 beside the runtime; anything else is refused (D94). */
|
|
2658
3221
|
function locatePnpm() {
|
|
2659
|
-
let dir = runtimeRoot();
|
|
3222
|
+
let dir = runtimeRoot$1();
|
|
2660
3223
|
for (;;) {
|
|
2661
3224
|
const candidate = join(dir, "node_modules", "pnpm");
|
|
2662
3225
|
if (existsSync(join(candidate, "package.json"))) {
|
|
@@ -3230,8 +3793,13 @@ function isOffline(env) {
|
|
|
3230
3793
|
if (flag !== void 0 && flag !== "" && !/^(?:0|false|no)$/i.test(flag)) return true;
|
|
3231
3794
|
return !Object.values(networkInterfaces()).some((addresses) => (addresses ?? []).some((address) => !address.internal && !address.address.startsWith("169.254.") && !/^fe[89ab]/i.test(address.address)));
|
|
3232
3795
|
}
|
|
3233
|
-
/**
|
|
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
|
+
*/
|
|
3234
3801
|
function shellQuote(value) {
|
|
3802
|
+
if (WINDOWS) return /^[\w@%+=:,./\\-]+$/.test(value) ? value : `"${value}"`;
|
|
3235
3803
|
return /^[\w@%+=:,./-]+$/.test(value) ? value : `'${value.replaceAll("'", `'\\''`)}'`;
|
|
3236
3804
|
}
|
|
3237
3805
|
/** Serializes work per key; one supervisor, so in-process order is the order. */
|
|
@@ -3312,7 +3880,7 @@ function createDependencies(options) {
|
|
|
3312
3880
|
const work = join(dirs.tmp, `resolve-${randomBytes(6).toString("hex")}`);
|
|
3313
3881
|
await mkdir(work);
|
|
3314
3882
|
try {
|
|
3315
|
-
await
|
|
3883
|
+
await linkDirectory(warm.nodeModules, join(work, "warm"));
|
|
3316
3884
|
await writeFile(join(work, "package.json"), manifestOf(input.pins));
|
|
3317
3885
|
if (input.previous !== void 0) await writeFile(join(work, "pnpm-lock.yaml"), input.previous);
|
|
3318
3886
|
const outcome = await install().run({
|
|
@@ -3354,16 +3922,9 @@ function createDependencies(options) {
|
|
|
3354
3922
|
/** Points a layout's `warm` symlink at the current warm set (the runtime may have moved). */
|
|
3355
3923
|
const relinkWarm = async (dir) => {
|
|
3356
3924
|
const link = join(dir, "warm");
|
|
3357
|
-
|
|
3358
|
-
|
|
3359
|
-
|
|
3360
|
-
} catch {
|
|
3361
|
-
target = void 0;
|
|
3362
|
-
}
|
|
3363
|
-
if (target === warm.nodeModules) return;
|
|
3364
|
-
const fresh = `${link}.${randomBytes(4).toString("hex")}`;
|
|
3365
|
-
await symlink(warm.nodeModules, fresh, "dir");
|
|
3366
|
-
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);
|
|
3367
3928
|
};
|
|
3368
3929
|
/**
|
|
3369
3930
|
* The layout of `lock`, installed from the store (and the registry for what the store lacks)
|
|
@@ -3388,7 +3949,7 @@ function createDependencies(options) {
|
|
|
3388
3949
|
});
|
|
3389
3950
|
await mkdir(dir, { recursive: true });
|
|
3390
3951
|
try {
|
|
3391
|
-
await
|
|
3952
|
+
await linkDirectory(warm.nodeModules, join(dir, "warm"));
|
|
3392
3953
|
await writeFile(join(dir, "package.json"), manifestOf(lock.packages));
|
|
3393
3954
|
await writeFile(join(dir, "pnpm-lock.yaml"), pnpm);
|
|
3394
3955
|
const outcome = await install().run({
|
|
@@ -3448,7 +4009,7 @@ function createDependencies(options) {
|
|
|
3448
4009
|
});
|
|
3449
4010
|
await mkdir(dir, { recursive: true });
|
|
3450
4011
|
try {
|
|
3451
|
-
await
|
|
4012
|
+
await linkDirectory(warm.nodeModules, join(dir, "warm"));
|
|
3452
4013
|
await writeFile(join(dir, "package.json"), `${JSON.stringify({
|
|
3453
4014
|
name: "mostra-artifact-dependencies",
|
|
3454
4015
|
private: true,
|
|
@@ -3799,12 +4360,6 @@ function writeLine(output, message) {
|
|
|
3799
4360
|
}
|
|
3800
4361
|
//#endregion
|
|
3801
4362
|
//#region src/protocol-server/server.ts
|
|
3802
|
-
/**
|
|
3803
|
-
* The host protocol server (D59, INTERFACES §6, HO-02): one dispatcher for every connection,
|
|
3804
|
-
* whether `mostra-runtime host`'s stdio or an attached client's Unix socket. It owns the session
|
|
3805
|
-
* rules (initialize first and once, revision negotiation, the home check, port registration on
|
|
3806
|
-
* the registering connection) and routes every other method to the handler a module registered.
|
|
3807
|
-
*/
|
|
3808
4363
|
/** Builds a handler with its types checked against the method definition. */
|
|
3809
4364
|
function handler(definition, handle) {
|
|
3810
4365
|
return {
|
|
@@ -3820,7 +4375,14 @@ var ProtocolServer = class {
|
|
|
3820
4375
|
#nextId = 1;
|
|
3821
4376
|
#refusal;
|
|
3822
4377
|
#listener;
|
|
4378
|
+
#endpoint;
|
|
4379
|
+
#listenOptions = {};
|
|
3823
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;
|
|
3824
4386
|
constructor(options) {
|
|
3825
4387
|
this.#options = options;
|
|
3826
4388
|
this.#handlers = new Map(options.handlers.map((entry) => [entry.definition.method, entry]));
|
|
@@ -3898,62 +4460,52 @@ var ProtocolServer = class {
|
|
|
3898
4460
|
return session;
|
|
3899
4461
|
}
|
|
3900
4462
|
/**
|
|
3901
|
-
* Listens on the home's control
|
|
3902
|
-
* lock holder calls this)
|
|
3903
|
-
* 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.
|
|
3904
4467
|
*/
|
|
3905
|
-
async listen(path, healMs = 5e3) {
|
|
3906
|
-
this.#
|
|
4468
|
+
async listen(path, healMs = 5e3, options = {}) {
|
|
4469
|
+
this.#endpoint = path;
|
|
4470
|
+
this.#listenOptions = options;
|
|
4471
|
+
this.#listener = await this.#bind();
|
|
3907
4472
|
this.#healTimer = setInterval(() => void this.#heal(), Math.min(healMs, 1e4));
|
|
3908
4473
|
this.#healTimer.unref();
|
|
3909
4474
|
}
|
|
3910
|
-
/** The
|
|
4475
|
+
/** The endpoint the server listens on, as clients connect to it. */
|
|
3911
4476
|
get socketPath() {
|
|
3912
4477
|
return this.#listener?.path;
|
|
3913
4478
|
}
|
|
3914
|
-
|
|
3915
|
-
|
|
3916
|
-
|
|
3917
|
-
|
|
3918
|
-
|
|
3919
|
-
|
|
3920
|
-
unlinkSync(path);
|
|
3921
|
-
} catch (error) {
|
|
3922
|
-
if (error.code !== "ENOENT") throw error;
|
|
3923
|
-
}
|
|
3924
|
-
const server = createServer((socket) => {
|
|
3925
|
-
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 })
|
|
3926
4485
|
});
|
|
3927
|
-
|
|
3928
|
-
|
|
3929
|
-
|
|
3930
|
-
|
|
3931
|
-
|
|
3932
|
-
});
|
|
4486
|
+
}
|
|
4487
|
+
#heal() {
|
|
4488
|
+
if (this.#closed) return Promise.resolve();
|
|
4489
|
+
this.#healing ??= this.#healOnce().finally(() => {
|
|
4490
|
+
this.#healing = void 0;
|
|
3933
4491
|
});
|
|
3934
|
-
|
|
3935
|
-
server.on("error", (error) => this.#options.log.error("protocol.listener_error", { error }));
|
|
3936
|
-
return {
|
|
3937
|
-
server,
|
|
3938
|
-
path,
|
|
3939
|
-
stats: statSync(path)
|
|
3940
|
-
};
|
|
4492
|
+
return this.#healing;
|
|
3941
4493
|
}
|
|
3942
|
-
async #
|
|
4494
|
+
async #healOnce() {
|
|
4495
|
+
if (this.#unannounced !== void 0) this.#announce(this.#unannounced);
|
|
3943
4496
|
const listener = this.#listener;
|
|
3944
|
-
if (!listener) return;
|
|
3945
|
-
|
|
3946
|
-
|
|
3947
|
-
current = statSync(listener.path);
|
|
3948
|
-
} catch {
|
|
3949
|
-
current = void 0;
|
|
3950
|
-
}
|
|
3951
|
-
if (current && current.ino === listener.stats.ino && current.dev === listener.stats.dev) return;
|
|
3952
|
-
listener.server.close();
|
|
4497
|
+
if (!listener || listener.intact()) return;
|
|
4498
|
+
await listener.close();
|
|
4499
|
+
if (this.#closed) return;
|
|
3953
4500
|
try {
|
|
3954
|
-
const replacement = await this.#bind(
|
|
4501
|
+
const replacement = await this.#bind();
|
|
4502
|
+
if (this.#closed) {
|
|
4503
|
+
await replacement.close();
|
|
4504
|
+
return;
|
|
4505
|
+
}
|
|
3955
4506
|
this.#listener = replacement;
|
|
3956
|
-
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);
|
|
3957
4509
|
} catch (error) {
|
|
3958
4510
|
this.#options.log.warn("protocol.socket_recreate_failed", {
|
|
3959
4511
|
path: listener.path,
|
|
@@ -3962,6 +4514,22 @@ var ProtocolServer = class {
|
|
|
3962
4514
|
}
|
|
3963
4515
|
}
|
|
3964
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
|
+
/**
|
|
3965
4533
|
* Answers every request from now on with `diagnostic`, for an instance that can no longer serve
|
|
3966
4534
|
* (`MOSTRA_HOME_GONE`).
|
|
3967
4535
|
*/
|
|
@@ -3977,6 +4545,10 @@ var ProtocolServer = class {
|
|
|
3977
4545
|
if (!registrant) return Promise.reject(/* @__PURE__ */ new Error(`No connection registered the ${port} port.`));
|
|
3978
4546
|
return registrant.peer.request(method, params, options);
|
|
3979
4547
|
}
|
|
4548
|
+
/** The names of the clients connected now (initialized sessions). */
|
|
4549
|
+
connectedClients() {
|
|
4550
|
+
return new Set([...this.#connections].filter((connection) => connection.session.initialized).map((connection) => connection.session.client?.name ?? ""));
|
|
4551
|
+
}
|
|
3980
4552
|
/**
|
|
3981
4553
|
* The initialized connections that registered `port`, oldest first, with their clients' names:
|
|
3982
4554
|
* the hosts a port call can reach (D105).
|
|
@@ -4027,20 +4599,17 @@ var ProtocolServer = class {
|
|
|
4027
4599
|
}
|
|
4028
4600
|
/**
|
|
4029
4601
|
* Stops listening, removes the socket file if it is still this server's, and closes every
|
|
4030
|
-
* 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.
|
|
4031
4604
|
*/
|
|
4032
|
-
close() {
|
|
4605
|
+
async close() {
|
|
4606
|
+
this.#closed = true;
|
|
4033
4607
|
if (this.#healTimer) clearInterval(this.#healTimer);
|
|
4608
|
+
await this.#healing;
|
|
4609
|
+
for (const connection of this.#connections) connection.close();
|
|
4034
4610
|
const listener = this.#listener;
|
|
4035
4611
|
this.#listener = void 0;
|
|
4036
|
-
|
|
4037
|
-
listener.server.close();
|
|
4038
|
-
try {
|
|
4039
|
-
const current = statSync(listener.path);
|
|
4040
|
-
if (current.ino === listener.stats.ino && current.dev === listener.stats.dev) unlinkSync(listener.path);
|
|
4041
|
-
} catch {}
|
|
4042
|
-
}
|
|
4043
|
-
for (const connection of this.#connections) connection.close();
|
|
4612
|
+
await listener?.close();
|
|
4044
4613
|
}
|
|
4045
4614
|
async #dispatch(session, method, params) {
|
|
4046
4615
|
try {
|
|
@@ -4133,43 +4702,34 @@ var ProtocolServer = class {
|
|
|
4133
4702
|
*/
|
|
4134
4703
|
/**
|
|
4135
4704
|
* Connects to a control socket. Rejects with `MOSTRA_HOST_CONNECTION_CLOSED` when nothing
|
|
4136
|
-
* 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.
|
|
4137
4707
|
*/
|
|
4138
4708
|
function connectSocket(path, timeoutMs = 5e3) {
|
|
4139
|
-
return
|
|
4140
|
-
const
|
|
4141
|
-
|
|
4142
|
-
|
|
4143
|
-
|
|
4144
|
-
}, timeoutMs);
|
|
4145
|
-
socket.once("error", (error) => {
|
|
4146
|
-
clearTimeout(timer);
|
|
4147
|
-
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;
|
|
4148
4714
|
});
|
|
4149
|
-
socket.
|
|
4150
|
-
|
|
4151
|
-
|
|
4152
|
-
|
|
4153
|
-
|
|
4154
|
-
|
|
4155
|
-
|
|
4156
|
-
socket.on("error", () => socket.destroy());
|
|
4157
|
-
pump({
|
|
4158
|
-
input: socket,
|
|
4159
|
-
output: socket
|
|
4160
|
-
}, () => peer, () => {
|
|
4161
|
-
peer.close();
|
|
4162
|
-
markClosed();
|
|
4163
|
-
});
|
|
4164
|
-
resolve({
|
|
4165
|
-
peer,
|
|
4166
|
-
closed,
|
|
4167
|
-
close: () => {
|
|
4168
|
-
peer.close();
|
|
4169
|
-
socket.end();
|
|
4170
|
-
}
|
|
4171
|
-
});
|
|
4715
|
+
socket.on("error", () => socket.destroy());
|
|
4716
|
+
pump({
|
|
4717
|
+
input: socket,
|
|
4718
|
+
output: socket
|
|
4719
|
+
}, () => peer, () => {
|
|
4720
|
+
peer.close();
|
|
4721
|
+
markClosed();
|
|
4172
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");
|
|
4173
4733
|
});
|
|
4174
4734
|
}
|
|
4175
4735
|
function refused(path, why) {
|
|
@@ -4750,13 +5310,23 @@ function localViewerId(db) {
|
|
|
4750
5310
|
* a `name` given again replaces the stored one.
|
|
4751
5311
|
*/
|
|
4752
5312
|
function viewerForSpec(db, spec) {
|
|
4753
|
-
|
|
5313
|
+
return viewerByRef(db, "token", spec);
|
|
5314
|
+
}
|
|
5315
|
+
/**
|
|
5316
|
+
* The viewer a host's identity port named (D143 item 2): one viewer of kind `host` per `ref`,
|
|
5317
|
+
* kept apart from `view/url`'s viewers, which a host names for links it mints.
|
|
5318
|
+
*/
|
|
5319
|
+
function viewerForHost(db, spec) {
|
|
5320
|
+
return viewerByRef(db, "host", spec);
|
|
5321
|
+
}
|
|
5322
|
+
function viewerByRef(db, kind, spec) {
|
|
5323
|
+
const found = db.get("SELECT * FROM viewer WHERE kind = ? AND external_ref = ?", kind, spec.ref);
|
|
4754
5324
|
if (found) {
|
|
4755
5325
|
if (spec.name !== void 0 && spec.name !== found.name) db.run("UPDATE viewer SET name = ? WHERE id = ?", spec.name, found.id);
|
|
4756
5326
|
return found.id;
|
|
4757
5327
|
}
|
|
4758
5328
|
const id = ViewerId.create();
|
|
4759
|
-
db.run("INSERT INTO viewer (id, kind, external_ref, name, created_at) VALUES (?,
|
|
5329
|
+
db.run("INSERT INTO viewer (id, kind, external_ref, name, created_at) VALUES (?, ?, ?, ?, ?)", id, kind, spec.ref, spec.name ?? null, (/* @__PURE__ */ new Date()).toISOString());
|
|
4760
5330
|
return id;
|
|
4761
5331
|
}
|
|
4762
5332
|
/** A viewer by ID; throws for an unknown one, which would be a defect. */
|
|
@@ -6331,6 +6901,7 @@ function createInteraction(options) {
|
|
|
6331
6901
|
},
|
|
6332
6902
|
viewer: (viewerId) => ledger.read((db) => viewer(db, viewerId)),
|
|
6333
6903
|
viewerForSpec,
|
|
6904
|
+
viewerForHost: (spec) => ledger.write((db) => viewerForHost(db, spec)),
|
|
6334
6905
|
openView(input) {
|
|
6335
6906
|
return ledger.write((db) => openView(db, input));
|
|
6336
6907
|
},
|
|
@@ -6761,69 +7332,10 @@ function createInteraction(options) {
|
|
|
6761
7332
|
/**
|
|
6762
7333
|
* The content-addressed version store on disk (DATA_MODEL §1, FAILURE_MODEL §3): `versions/<id>/`
|
|
6763
7334
|
* and `sources/<artifactId>/<sourceDigest>.tar.zst`. A version directory is assembled in staging,
|
|
6764
|
-
* 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
|
|
6765
7337
|
* commits, and anything without a row is removed at the next start.
|
|
6766
7338
|
*/
|
|
6767
|
-
/** Calls `visit` for every entry under `dir`, children before their directory. */
|
|
6768
|
-
async function walk(dir, visit) {
|
|
6769
|
-
for (const entry of await readdir(dir, { withFileTypes: true })) {
|
|
6770
|
-
const path = join(dir, entry.name);
|
|
6771
|
-
if (entry.isDirectory()) await walk(path, visit);
|
|
6772
|
-
await visit(path, entry.isDirectory());
|
|
6773
|
-
}
|
|
6774
|
-
}
|
|
6775
|
-
/**
|
|
6776
|
-
* Syncs a file or a directory to disk. A file that can't be synced fails the caller (its bytes
|
|
6777
|
-
* would not be durable); a directory may not support it on some file systems, and only that
|
|
6778
|
-
* case is tolerated (EINVAL, ENOTSUP, EISDIR, EPERM, EACCES on `open`).
|
|
6779
|
-
*/
|
|
6780
|
-
function fsyncPath(path, directory = false) {
|
|
6781
|
-
let fd;
|
|
6782
|
-
try {
|
|
6783
|
-
fd = openSync(path, "r");
|
|
6784
|
-
fsyncSync(fd);
|
|
6785
|
-
} catch (error) {
|
|
6786
|
-
const code = error.code;
|
|
6787
|
-
if (!directory || ![
|
|
6788
|
-
"EINVAL",
|
|
6789
|
-
"ENOTSUP",
|
|
6790
|
-
"EISDIR",
|
|
6791
|
-
"EPERM",
|
|
6792
|
-
"EACCES"
|
|
6793
|
-
].includes(code ?? "")) throw error;
|
|
6794
|
-
} finally {
|
|
6795
|
-
if (fd !== void 0) closeSync(fd);
|
|
6796
|
-
}
|
|
6797
|
-
}
|
|
6798
|
-
/**
|
|
6799
|
-
* Makes a tree read-only (files 0444, directories 0555) and syncs it to disk. The top directory is
|
|
6800
|
-
* left writable when `keepTop` is set: renaming a directory needs write access to it, to update `..`.
|
|
6801
|
-
*/
|
|
6802
|
-
async function sealTree(dir, keepTop = false) {
|
|
6803
|
-
await walk(dir, async (path, isDirectory) => {
|
|
6804
|
-
await chmod(path, isDirectory ? 365 : 292);
|
|
6805
|
-
fsyncPath(path, isDirectory);
|
|
6806
|
-
});
|
|
6807
|
-
if (!keepTop) await chmod(dir, 365);
|
|
6808
|
-
fsyncPath(dir, true);
|
|
6809
|
-
}
|
|
6810
|
-
/** Removes a tree, sealed or not. Missing trees are fine. */
|
|
6811
|
-
async function removeTree(dir) {
|
|
6812
|
-
try {
|
|
6813
|
-
if ((await lstat(dir)).isDirectory()) {
|
|
6814
|
-
await chmod(dir, 493);
|
|
6815
|
-
await walk(dir, async (path, isDirectory) => {
|
|
6816
|
-
if (isDirectory) await chmod(path, 493);
|
|
6817
|
-
}).catch(() => {});
|
|
6818
|
-
}
|
|
6819
|
-
} catch {
|
|
6820
|
-
return;
|
|
6821
|
-
}
|
|
6822
|
-
await rm(dir, {
|
|
6823
|
-
recursive: true,
|
|
6824
|
-
force: true
|
|
6825
|
-
});
|
|
6826
|
-
}
|
|
6827
7339
|
/** Opens the version store of the home at `home`, creating its directories. */
|
|
6828
7340
|
async function openVersionStore(home) {
|
|
6829
7341
|
const versionsDir = join(home, "versions");
|
|
@@ -6848,9 +7360,8 @@ async function openVersionStore(home) {
|
|
|
6848
7360
|
await sealTree(built, true);
|
|
6849
7361
|
const target = versionDir(versionId);
|
|
6850
7362
|
await removeTree(target);
|
|
6851
|
-
await
|
|
6852
|
-
await
|
|
6853
|
-
fsyncPath(target, true);
|
|
7363
|
+
await renamePath(built, target);
|
|
7364
|
+
await sealPlaced(target);
|
|
6854
7365
|
fsyncPath(versionsDir, true);
|
|
6855
7366
|
},
|
|
6856
7367
|
async sweep(known) {
|
|
@@ -7475,7 +7986,7 @@ function actionRoutes(options) {
|
|
|
7475
7986
|
if (!session || artifactId === void 0) throw new Error("session route without a session");
|
|
7476
7987
|
return {
|
|
7477
7988
|
artifactId,
|
|
7478
|
-
viewerId: interaction.viewerOf(session.
|
|
7989
|
+
viewerId: interaction.viewerOf(session.viewerId),
|
|
7479
7990
|
tokenId: session.grant.tokenId,
|
|
7480
7991
|
scopes: session.grant.scopes
|
|
7481
7992
|
};
|
|
@@ -7685,7 +8196,7 @@ function browserRoutes(options) {
|
|
|
7685
8196
|
if (!session || artifactId === void 0) throw new Error("session route without a session");
|
|
7686
8197
|
return {
|
|
7687
8198
|
artifactId,
|
|
7688
|
-
viewerId: interaction.viewerOf(session.
|
|
8199
|
+
viewerId: interaction.viewerOf(session.viewerId),
|
|
7689
8200
|
tokenId: session.grant.tokenId,
|
|
7690
8201
|
scopes: session.grant.scopes
|
|
7691
8202
|
};
|
|
@@ -8143,7 +8654,7 @@ function capabilityKey(home, log) {
|
|
|
8143
8654
|
} finally {
|
|
8144
8655
|
closeSync(fd);
|
|
8145
8656
|
}
|
|
8146
|
-
|
|
8657
|
+
renamePathSync(aside, file);
|
|
8147
8658
|
chmodSync(file, 384);
|
|
8148
8659
|
return key;
|
|
8149
8660
|
}
|
|
@@ -8377,7 +8888,7 @@ var Capabilities = class {
|
|
|
8377
8888
|
const csrf = csrfOf(cookie);
|
|
8378
8889
|
const id = hashSecret(cookie);
|
|
8379
8890
|
const now = this.#iso(this.#now());
|
|
8380
|
-
this.#ledger.write((db) => db.run("INSERT INTO session (id, token_id, origin, mode, csrf, version_id, created_at, last_seen_at) VALUES (?, ?, ?, 'cookie', ?, ?, ?, ?)", id, input.tokenId, input.origin, hashSecret(csrf), input.versionId ?? null, now, now));
|
|
8891
|
+
this.#ledger.write((db) => db.run("INSERT INTO session (id, token_id, origin, mode, csrf, version_id, created_at, last_seen_at, viewer_id) VALUES (?, ?, ?, 'cookie', ?, ?, ?, ?, ?)", id, input.tokenId, input.origin, hashSecret(csrf), input.versionId ?? null, now, now, input.viewerId ?? null));
|
|
8381
8892
|
return {
|
|
8382
8893
|
cookie,
|
|
8383
8894
|
csrf,
|
|
@@ -8410,11 +8921,14 @@ var Capabilities = class {
|
|
|
8410
8921
|
const csrf = csrfOf(value);
|
|
8411
8922
|
if (!safeEqual(hashSecret(csrf), found.session.csrf)) continue;
|
|
8412
8923
|
this.#touch(found.session.id);
|
|
8924
|
+
const grant = grantOf(found.token);
|
|
8925
|
+
const viewerId = grant.viewerId ?? found.session.viewer_id ?? void 0;
|
|
8413
8926
|
return {
|
|
8414
8927
|
id: found.session.id,
|
|
8415
8928
|
csrf,
|
|
8416
8929
|
...found.session.version_id !== null ? { versionId: found.session.version_id } : {},
|
|
8417
|
-
grant
|
|
8930
|
+
grant,
|
|
8931
|
+
...viewerId !== void 0 ? { viewerId } : {}
|
|
8418
8932
|
};
|
|
8419
8933
|
}
|
|
8420
8934
|
return revoked ? refusal("MOSTRA_HYGIENE_TOKEN_REVOKED", "The link this session came from was revoked or has expired.") : refusal("MOSTRA_HYGIENE_SESSION_MISSING", "The request carries no session for this origin.");
|
|
@@ -8506,9 +9020,14 @@ var Capabilities = class {
|
|
|
8506
9020
|
const { live: _live, ...rest } = grant;
|
|
8507
9021
|
return rest;
|
|
8508
9022
|
}
|
|
8509
|
-
/**
|
|
9023
|
+
/**
|
|
9024
|
+
* Spends a launch ticket that started a session: `true` only for the caller that spent it, so
|
|
9025
|
+
* two exchanges that both presented it while a host's identity port was answering get one
|
|
9026
|
+
* session between them (GPT review of WP-12, finding 1).
|
|
9027
|
+
*/
|
|
8510
9028
|
spendLaunch(ticket) {
|
|
8511
|
-
|
|
9029
|
+
this.#sweepTickets();
|
|
9030
|
+
return looksLikeSecret(ticket) && this.#launches.delete(hashSecret(ticket));
|
|
8512
9031
|
}
|
|
8513
9032
|
/** Removes sessions unseen for longer than their cookie lives; no browser holds them any more. */
|
|
8514
9033
|
prune() {
|
|
@@ -9124,6 +9643,73 @@ function normalize(policy) {
|
|
|
9124
9643
|
};
|
|
9125
9644
|
}
|
|
9126
9645
|
//#endregion
|
|
9646
|
+
//#region src/gateway/identity.ts
|
|
9647
|
+
/**
|
|
9648
|
+
* Who a browser is (D143 item 2). A link minted with a viewer acts for that viewer (D104) and asks
|
|
9649
|
+
* nothing. For a link without one, a host that registered the `identity` port names the person
|
|
9650
|
+
* from the request's headers; without such a host, the session acts as the home's local user.
|
|
9651
|
+
*/
|
|
9652
|
+
/** How long a host has to answer `port/identity.resolve`: a page waits for it, as for D108. */
|
|
9653
|
+
const IDENTITY_TIMEOUT_MS = 5e3;
|
|
9654
|
+
/**
|
|
9655
|
+
* The headers a host sees: names in lower case, without `cookie` (Mostra's sessions and every
|
|
9656
|
+
* other page's of this host) and without Mostra's own `x-mostra-*` headers.
|
|
9657
|
+
*/
|
|
9658
|
+
function identityHeaders(headers) {
|
|
9659
|
+
const seen = {};
|
|
9660
|
+
headers.forEach((value, name) => {
|
|
9661
|
+
const key = name.toLowerCase();
|
|
9662
|
+
if (key === "cookie" || key.startsWith("x-mostra-")) return;
|
|
9663
|
+
seen[key] = value;
|
|
9664
|
+
});
|
|
9665
|
+
return seen;
|
|
9666
|
+
}
|
|
9667
|
+
/**
|
|
9668
|
+
* Asks the host that took identity over. Its outage never makes the session someone else: a
|
|
9669
|
+
* failure, a timeout, an answer the schema refuses, or an expected host that isn't connected is
|
|
9670
|
+
* `unavailable`, and the exchange is refused.
|
|
9671
|
+
*/
|
|
9672
|
+
async function resolveIdentity(input) {
|
|
9673
|
+
const registrant = input.registrant();
|
|
9674
|
+
const unavailable = (message) => ({
|
|
9675
|
+
kind: "unavailable",
|
|
9676
|
+
diagnostic: createDiagnostic("MOSTRA_HOST_IDENTITY_UNAVAILABLE", { message })
|
|
9677
|
+
});
|
|
9678
|
+
if (registrant) try {
|
|
9679
|
+
const answer = await input.call(registrant.session, {
|
|
9680
|
+
artifactId: input.artifactId,
|
|
9681
|
+
via: input.via,
|
|
9682
|
+
headers: identityHeaders(input.headers)
|
|
9683
|
+
});
|
|
9684
|
+
const parsed = portIdentityResolveMethod.result.safeParse(answer);
|
|
9685
|
+
if (parsed.success) return parsed.data === null ? { kind: "default" } : {
|
|
9686
|
+
kind: "person",
|
|
9687
|
+
viewer: parsed.data
|
|
9688
|
+
};
|
|
9689
|
+
input.log.warn("gateway.identity_invalid", {
|
|
9690
|
+
owner: registrant.owner,
|
|
9691
|
+
artifactId: input.artifactId
|
|
9692
|
+
});
|
|
9693
|
+
return unavailable(`The host ${registrant.owner} answered who this is in a form Mostra refuses.`);
|
|
9694
|
+
} catch (error) {
|
|
9695
|
+
input.log.warn("gateway.identity_failed", {
|
|
9696
|
+
owner: registrant.owner,
|
|
9697
|
+
artifactId: input.artifactId,
|
|
9698
|
+
error: error.message
|
|
9699
|
+
});
|
|
9700
|
+
return unavailable(`The host ${registrant.owner} didn't say who this is.`);
|
|
9701
|
+
}
|
|
9702
|
+
const away = input.expected();
|
|
9703
|
+
if (away.length > 0) {
|
|
9704
|
+
input.log.warn("gateway.identity_host_away", {
|
|
9705
|
+
owners: away,
|
|
9706
|
+
artifactId: input.artifactId
|
|
9707
|
+
});
|
|
9708
|
+
return unavailable(`The host that identifies this home's viewers (${away.join(", ")}) isn't running.`);
|
|
9709
|
+
}
|
|
9710
|
+
return { kind: "default" };
|
|
9711
|
+
}
|
|
9712
|
+
//#endregion
|
|
9127
9713
|
//#region src/gateway/index.ts
|
|
9128
9714
|
/**
|
|
9129
9715
|
* The gateway (ARCHITECTURE §5, §10; D38, D96 to D99): the HTTP side of an instance. It serves
|
|
@@ -9370,8 +9956,20 @@ function createGateway(options) {
|
|
|
9370
9956
|
...access(grant)
|
|
9371
9957
|
};
|
|
9372
9958
|
};
|
|
9959
|
+
/**
|
|
9960
|
+
* The sessions exchanges made, by artifact and browser (the shell's own random key, kept in its
|
|
9961
|
+
* origin's storage and sent with every exchange), each with the order it was made in. An
|
|
9962
|
+
* exchange that waited (the identity port answering) checks here whether another link's
|
|
9963
|
+
* session was made for the same browser meanwhile: its request carried no cookie of that session,
|
|
9964
|
+
* so D98 item 8's check alone would let the later answer silently replace it (Opus review of
|
|
9965
|
+
* WP-12, finding 2). Only the last few thousand are kept; the window that matters is seconds.
|
|
9966
|
+
*/
|
|
9967
|
+
const madeSessions = /* @__PURE__ */ new Map();
|
|
9968
|
+
let exchangeOrder = 0;
|
|
9969
|
+
const browserKey = (artifactId, browser) => typeof browser === "string" && /^[A-Za-z0-9_-]{16,64}$/.test(browser) ? `${artifactId}\u0000${browser}` : void 0;
|
|
9373
9970
|
const exchange = async (context) => {
|
|
9374
9971
|
const artifactId = context.artifactId;
|
|
9972
|
+
const startedAt = exchangeOrder;
|
|
9375
9973
|
const meta = {
|
|
9376
9974
|
method: "POST",
|
|
9377
9975
|
path: new URL(context.request.url).pathname,
|
|
@@ -9380,7 +9978,8 @@ function createGateway(options) {
|
|
|
9380
9978
|
const body = await readJsonObject(context.request);
|
|
9381
9979
|
if (isRefusal(body)) return refuse(shellChecks, body, meta);
|
|
9382
9980
|
const launch = body["token"] === void 0 && body["launch"] !== void 0;
|
|
9383
|
-
const
|
|
9981
|
+
const browser = browserKey(artifactId, body["browser"]);
|
|
9982
|
+
let grant = launch ? capabilities.presentLaunch(body["launch"], artifactId, false) : capabilities.presentToken(body["token"], artifactId);
|
|
9384
9983
|
if (isRefusal(grant)) return refuse(shellChecks, grant, meta);
|
|
9385
9984
|
const existing = capabilities.session(cookieValues(context.request.headers.get("cookie"), shellChecks.cookieName()), shellOrigin(), artifactId);
|
|
9386
9985
|
if (!isRefusal(existing)) {
|
|
@@ -9403,11 +10002,51 @@ function createGateway(options) {
|
|
|
9403
10002
|
}, { status: 409 });
|
|
9404
10003
|
}
|
|
9405
10004
|
}
|
|
10005
|
+
let viewerId;
|
|
10006
|
+
if (grant.viewerId === void 0 && options.identity) {
|
|
10007
|
+
const outcome = await options.identity({
|
|
10008
|
+
artifactId,
|
|
10009
|
+
via: "local",
|
|
10010
|
+
headers: context.request.headers
|
|
10011
|
+
});
|
|
10012
|
+
if (outcome.kind === "unavailable") {
|
|
10013
|
+
log.warn("gateway.session_refused", {
|
|
10014
|
+
artifactId,
|
|
10015
|
+
code: outcome.diagnostic.code
|
|
10016
|
+
});
|
|
10017
|
+
return jsonResponse(outcome.diagnostic, { status: 503 });
|
|
10018
|
+
}
|
|
10019
|
+
if (outcome.kind === "person") viewerId = interaction.viewerForHost(outcome.viewer);
|
|
10020
|
+
}
|
|
10021
|
+
const now = launch ? capabilities.presentLaunch(body["launch"], artifactId, true) : capabilities.presentToken(body["token"], artifactId);
|
|
10022
|
+
if (isRefusal(now)) return refuse(shellChecks, now, meta);
|
|
10023
|
+
grant = now;
|
|
10024
|
+
const made = browser === void 0 ? void 0 : madeSessions.get(browser);
|
|
10025
|
+
if (made !== void 0 && made.order > startedAt && made.grant.tokenId !== grant.tokenId && body["replace"] !== true) {
|
|
10026
|
+
log.info("gateway.session_conflict", {
|
|
10027
|
+
artifactId,
|
|
10028
|
+
origin: shellOrigin()
|
|
10029
|
+
});
|
|
10030
|
+
return jsonResponse({
|
|
10031
|
+
...refusal("MOSTRA_HYGIENE_SESSION_CONFLICT", "This browser already has this artifact open from another link.").diagnostic,
|
|
10032
|
+
current: access(made.grant),
|
|
10033
|
+
offered: access(grant)
|
|
10034
|
+
}, { status: 409 });
|
|
10035
|
+
}
|
|
9406
10036
|
const session = capabilities.createSession({
|
|
9407
10037
|
tokenId: grant.tokenId,
|
|
9408
|
-
origin: shellOrigin()
|
|
10038
|
+
origin: shellOrigin(),
|
|
10039
|
+
viewerId
|
|
9409
10040
|
});
|
|
9410
|
-
if (
|
|
10041
|
+
if (browser !== void 0) {
|
|
10042
|
+
exchangeOrder += 1;
|
|
10043
|
+
madeSessions.delete(browser);
|
|
10044
|
+
madeSessions.set(browser, {
|
|
10045
|
+
order: exchangeOrder,
|
|
10046
|
+
grant
|
|
10047
|
+
});
|
|
10048
|
+
if (madeSessions.size > 4096) madeSessions.delete(madeSessions.keys().next().value);
|
|
10049
|
+
}
|
|
9411
10050
|
log.info("gateway.session_started", {
|
|
9412
10051
|
origin: shellOrigin(),
|
|
9413
10052
|
artifactId,
|
|
@@ -9457,10 +10096,11 @@ function createGateway(options) {
|
|
|
9457
10096
|
versionId: version.id,
|
|
9458
10097
|
origin: artifactOrigin,
|
|
9459
10098
|
shellOrigin: shellOrigin(),
|
|
9460
|
-
shellSessionId: session.id
|
|
10099
|
+
shellSessionId: session.id,
|
|
10100
|
+
viewerId: session.viewerId
|
|
9461
10101
|
});
|
|
9462
10102
|
const controls = await options.controls(detail);
|
|
9463
|
-
const viewerId = interaction.viewerOf(session.
|
|
10103
|
+
const viewerId = interaction.viewerOf(session.viewerId);
|
|
9464
10104
|
return jsonResponse({
|
|
9465
10105
|
artifactId,
|
|
9466
10106
|
viewId: interaction.openView({
|
|
@@ -9622,12 +10262,13 @@ function createGateway(options) {
|
|
|
9622
10262
|
location: "/"
|
|
9623
10263
|
};
|
|
9624
10264
|
const existing = capabilities.session(cookieValues(context.request.headers.get("cookie"), checks().cookieName()), origin(), artifactId);
|
|
9625
|
-
if (!isRefusal(existing) && existing.grant.tokenId === redeemed.tokenId) capabilities.enterVersion(existing.id, redeemed.versionId);
|
|
10265
|
+
if (!isRefusal(existing) && existing.grant.tokenId === redeemed.tokenId && existing.viewerId === redeemed.viewerId) capabilities.enterVersion(existing.id, redeemed.versionId);
|
|
9626
10266
|
else {
|
|
9627
10267
|
const session = capabilities.createSession({
|
|
9628
10268
|
tokenId: redeemed.tokenId,
|
|
9629
10269
|
origin: origin(),
|
|
9630
|
-
versionId: redeemed.versionId
|
|
10270
|
+
versionId: redeemed.versionId,
|
|
10271
|
+
viewerId: redeemed.viewerId
|
|
9631
10272
|
});
|
|
9632
10273
|
headers["set-cookie"] = sessionCookie(checks().cookieName(), session.cookie, "/", SESSION_MAX_AGE_S);
|
|
9633
10274
|
log.info("gateway.session_started", {
|
|
@@ -9650,7 +10291,7 @@ function createGateway(options) {
|
|
|
9650
10291
|
artifactId,
|
|
9651
10292
|
shellOrigin: shellOrigin(),
|
|
9652
10293
|
scopes: session.grant.scopes,
|
|
9653
|
-
viewer: interaction.viewer(interaction.viewerOf(session.
|
|
10294
|
+
viewer: interaction.viewer(interaction.viewerOf(session.viewerId)),
|
|
9654
10295
|
...version ? { version: {
|
|
9655
10296
|
id: version.id,
|
|
9656
10297
|
number: version.number
|
|
@@ -9953,7 +10594,7 @@ async function verifyDocument(path, request, headers) {
|
|
|
9953
10594
|
* `MOSTRA_ENV_SHELL_MISSING`.
|
|
9954
10595
|
*/
|
|
9955
10596
|
function locateShell(env) {
|
|
9956
|
-
const dir = env["MOSTRA_SHELL_DIR"] ?? resolve(runtimeRoot(), "..", "shell", "dist");
|
|
10597
|
+
const dir = env["MOSTRA_SHELL_DIR"] ?? resolve(runtimeRoot$1(), "..", "shell", "dist");
|
|
9957
10598
|
return existsSync(join(dir, "index.html")) ? dir : void 0;
|
|
9958
10599
|
}
|
|
9959
10600
|
//#endregion
|
|
@@ -10343,7 +10984,7 @@ function localLauncher(options) {
|
|
|
10343
10984
|
resolve(options.home, "versions"),
|
|
10344
10985
|
resolve(options.home, "cache", "builds"),
|
|
10345
10986
|
resolve(options.home, "cache", "dev")
|
|
10346
|
-
].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.");
|
|
10347
10988
|
const modules = await options.modules?.({
|
|
10348
10989
|
artifactId: spec.artifactId,
|
|
10349
10990
|
versionDir,
|
|
@@ -11337,7 +11978,7 @@ function parseTscOutput(lines, alreadyReported, ownConfig = false) {
|
|
|
11337
11978
|
}
|
|
11338
11979
|
/** Where `@mostra/server`'s declarations are: the worker provides the package, so no layout has it (D129). */
|
|
11339
11980
|
function serverTypes() {
|
|
11340
|
-
const root = runtimeRoot();
|
|
11981
|
+
const root = runtimeRoot$1();
|
|
11341
11982
|
for (const candidate of [join(root, "..", "server", "dist", "index.d.ts"), join(root, "..", "server", "src", "index.ts")]) if (existsSync(candidate)) return candidate;
|
|
11342
11983
|
}
|
|
11343
11984
|
/** Runs the type check of the snapshot in `sourceDir` against `nodeModules`. */
|
|
@@ -11350,7 +11991,7 @@ async function typecheck(options) {
|
|
|
11350
11991
|
await mkdir(join(workDir, ".mostra-check"), { recursive: true });
|
|
11351
11992
|
try {
|
|
11352
11993
|
await cp(options.sourceDir, join(workDir, "source"), { recursive: true });
|
|
11353
|
-
await
|
|
11994
|
+
await linkDirectory(options.nodeModules, join(workDir, "node_modules"));
|
|
11354
11995
|
await writeFile(join(workDir, ".mostra-check", "assets.d.ts"), AMBIENT);
|
|
11355
11996
|
if (options.hasLive) await writeFile(join(workDir, ".mostra-check", "mostra-env.d.ts"), LIVE_DECLARATION);
|
|
11356
11997
|
const own = existsSync(join(workDir, "source", "tsconfig.json"));
|
|
@@ -11773,7 +12414,7 @@ function createVerifier(options) {
|
|
|
11773
12414
|
recursive: true,
|
|
11774
12415
|
force: true
|
|
11775
12416
|
});
|
|
11776
|
-
await
|
|
12417
|
+
await renamePath(temporary, join(buildsDir, prepared.versionId));
|
|
11777
12418
|
await pruneBuilds(prepared.versionId);
|
|
11778
12419
|
return outcome;
|
|
11779
12420
|
} finally {
|
|
@@ -12083,7 +12724,7 @@ function createVerifier(options) {
|
|
|
12083
12724
|
verdict: checkedVerdict,
|
|
12084
12725
|
built: built.ok
|
|
12085
12726
|
}, null, 2)}\n`);
|
|
12086
|
-
await
|
|
12727
|
+
await renamePath(temporary, target);
|
|
12087
12728
|
await pruneVerdicts();
|
|
12088
12729
|
} else {
|
|
12089
12730
|
await rm(join(cacheDir, `${key}.json`), { force: true });
|
|
@@ -12622,7 +13263,7 @@ async function listSource(source) {
|
|
|
12622
13263
|
continue;
|
|
12623
13264
|
}
|
|
12624
13265
|
if (kind === "dir") {
|
|
12625
|
-
if (IGNORED_DIRS.has(entry.name) || rules.ignores(`${path}/`)) continue;
|
|
13266
|
+
if (IGNORED_DIRS.has(nameKey(entry.name)) || rules.ignores(`${path}/`)) continue;
|
|
12626
13267
|
let real;
|
|
12627
13268
|
try {
|
|
12628
13269
|
real = await realpath(absolute);
|
|
@@ -12633,9 +13274,9 @@ async function listSource(source) {
|
|
|
12633
13274
|
await walk(absolute, path, /* @__PURE__ */ new Set([...ancestors, real]));
|
|
12634
13275
|
} else if (kind === "file") {
|
|
12635
13276
|
if (IGNORED_FILE.test(entry.name) || rules.ignores(path)) continue;
|
|
12636
|
-
const clash = seen.get(path);
|
|
12637
|
-
if (clash !== void 0) throw artifactError("MOSTRA_ARTIFACT_SOURCE_UNREADABLE", `${clash} and ${absolute} have the same name after Unicode normalization (NFC).`);
|
|
12638
|
-
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);
|
|
12639
13280
|
files.push({
|
|
12640
13281
|
path,
|
|
12641
13282
|
absolute
|
|
@@ -12883,15 +13524,15 @@ async function archiveSnapshot(source, files, target) {
|
|
|
12883
13524
|
}
|
|
12884
13525
|
yield TAR_END;
|
|
12885
13526
|
}
|
|
12886
|
-
const output = createWriteStream(temporary, { mode: 256 });
|
|
12887
|
-
await pipeline(Readable.from(blocks()), createZstdCompress(), output);
|
|
12888
|
-
const handle = await import("node:fs/promises").then((fs) => fs.open(temporary, "r"));
|
|
12889
13527
|
try {
|
|
12890
|
-
await
|
|
12891
|
-
|
|
12892
|
-
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;
|
|
12893
13534
|
}
|
|
12894
|
-
await
|
|
13535
|
+
await renamePath(temporary, target);
|
|
12895
13536
|
fsyncPath(dirname(target), true);
|
|
12896
13537
|
return true;
|
|
12897
13538
|
}
|
|
@@ -13250,7 +13891,7 @@ function createPublisher(options) {
|
|
|
13250
13891
|
};
|
|
13251
13892
|
const cachedBuild = verifier().builtVersion(versionId);
|
|
13252
13893
|
if (cachedBuild && await versionDamage(cachedBuild) === void 0) {
|
|
13253
|
-
await
|
|
13894
|
+
await renamePath(cachedBuild, out);
|
|
13254
13895
|
outputDigest = JSON.parse(await readFile(join(out, "manifest.json"), "utf8")).outputDigest;
|
|
13255
13896
|
} else {
|
|
13256
13897
|
log.info("publish.rebuild", {
|
|
@@ -14170,82 +14811,35 @@ function gcMethods(gc) {
|
|
|
14170
14811
|
//#endregion
|
|
14171
14812
|
//#region src/home/paths.ts
|
|
14172
14813
|
/**
|
|
14173
|
-
* Where a home and its control
|
|
14174
|
-
* touches the file system; preparing a directory creates it
|
|
14175
|
-
* 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.
|
|
14176
14817
|
*/
|
|
14177
14818
|
const nonEmpty = (value) => value === void 0 || value === "" ? void 0 : value;
|
|
14178
14819
|
/**
|
|
14179
14820
|
* The home path, resolved in D84's order: `--home`, then `MOSTRA_HOME`, then the platform default
|
|
14180
|
-
* (`~/.mostra` on macOS, `${XDG_DATA_HOME:-~/.local/share}/mostra` on Linux
|
|
14181
|
-
* `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`.
|
|
14182
14823
|
*/
|
|
14183
14824
|
function resolveHomePath(inputs) {
|
|
14184
14825
|
const cwd = inputs.cwd ?? process.cwd();
|
|
14185
14826
|
const chosen = nonEmpty(inputs.home) ?? nonEmpty(inputs.env["MOSTRA_HOME"]);
|
|
14186
|
-
if (chosen !== void 0) return resolve(cwd, chosen);
|
|
14187
|
-
|
|
14188
|
-
if ((inputs.platform ?? process.platform) === "darwin") return join(user, ".mostra");
|
|
14189
|
-
const data = nonEmpty(inputs.env["XDG_DATA_HOME"]);
|
|
14190
|
-
return join(data !== void 0 && isAbsolute(data) ? data : join(user, ".local", "share"), "mostra");
|
|
14191
|
-
}
|
|
14192
|
-
/** The current user's ID. */
|
|
14193
|
-
function uid$1() {
|
|
14194
|
-
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());
|
|
14195
14829
|
}
|
|
14196
14830
|
/**
|
|
14197
14831
|
* The runtime directory for control sockets (D82): `MOSTRA_RUNTIME_DIR`; else `~/.mostra/run` on
|
|
14198
14832
|
* macOS; on Linux `$XDG_RUNTIME_DIR/mostra` when `$XDG_RUNTIME_DIR` is a directory the user owns
|
|
14199
|
-
* 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.
|
|
14200
14835
|
*/
|
|
14201
14836
|
function resolveRuntimeDir(inputs) {
|
|
14202
|
-
|
|
14203
|
-
|
|
14204
|
-
|
|
14205
|
-
|
|
14206
|
-
|
|
14207
|
-
|
|
14208
|
-
if ((inputs.platform ?? process.platform) === "darwin") return {
|
|
14209
|
-
dir: join(user, ".mostra", "run"),
|
|
14210
|
-
source: "fallback"
|
|
14211
|
-
};
|
|
14212
|
-
const xdg = nonEmpty(inputs.env["XDG_RUNTIME_DIR"]);
|
|
14213
|
-
let rejected;
|
|
14214
|
-
if (xdg !== void 0) {
|
|
14215
|
-
rejected = unsafeXdgRuntimeDir(xdg);
|
|
14216
|
-
if (rejected === void 0) return {
|
|
14217
|
-
dir: join(xdg, "mostra"),
|
|
14218
|
-
source: "xdg"
|
|
14219
|
-
};
|
|
14220
|
-
}
|
|
14221
|
-
const state = nonEmpty(inputs.env["XDG_STATE_HOME"]);
|
|
14222
|
-
const base = state !== void 0 && isAbsolute(state) ? state : join(user, ".local", "state");
|
|
14223
|
-
const dir = join(base, "mostra", "run");
|
|
14224
|
-
return rejected === void 0 ? {
|
|
14225
|
-
dir,
|
|
14226
|
-
source: "fallback"
|
|
14227
|
-
} : {
|
|
14228
|
-
dir,
|
|
14229
|
-
source: "fallback",
|
|
14230
|
-
rejected
|
|
14231
|
-
};
|
|
14232
|
-
}
|
|
14233
|
-
/** Why `$XDG_RUNTIME_DIR` can't be used, or `undefined` when it can (XDG Base Directory spec). */
|
|
14234
|
-
function unsafeXdgRuntimeDir(dir) {
|
|
14235
|
-
if (!isAbsolute(dir)) return "it isn't an absolute path";
|
|
14236
|
-
let stats;
|
|
14237
|
-
try {
|
|
14238
|
-
stats = statSync(dir);
|
|
14239
|
-
} catch {
|
|
14240
|
-
return "it doesn't exist";
|
|
14241
|
-
}
|
|
14242
|
-
if (!stats.isDirectory()) return "it isn't a directory";
|
|
14243
|
-
if (stats.uid !== uid$1()) return "another user owns it";
|
|
14244
|
-
if ((stats.mode & 63) !== 0) return "other users can access it";
|
|
14245
|
-
}
|
|
14246
|
-
/** The longest control socket path the operating system accepts, in bytes (VERIFIED_FACTS). */
|
|
14247
|
-
function socketPathLimit(platform = process.platform) {
|
|
14248
|
-
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
|
+
});
|
|
14249
14843
|
}
|
|
14250
14844
|
/**
|
|
14251
14845
|
* A home's hash (D82): 16 Crockford base32 characters of the SHA-256 of its real path, which
|
|
@@ -14256,73 +14850,20 @@ function homeHash(realHome) {
|
|
|
14256
14850
|
return VersionId.fromSha256(new Uint8Array(digest)).slice(4, 20);
|
|
14257
14851
|
}
|
|
14258
14852
|
/**
|
|
14259
|
-
* The control
|
|
14260
|
-
* `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.
|
|
14261
14856
|
*/
|
|
14262
|
-
function socketPathFor(runtimeDir, realHome, platform) {
|
|
14263
|
-
|
|
14264
|
-
const path = join(runtimeDir, `${hash}.sock`);
|
|
14265
|
-
const limit = socketPathLimit(platform);
|
|
14266
|
-
const length = Buffer.byteLength(path);
|
|
14267
|
-
if (length > limit) throw new RpcError(createDiagnostic("MOSTRA_HOME_SOCKET_TOO_LONG", {
|
|
14268
|
-
message: `The control socket path ${path} is ${length} bytes; this system allows ${limit}.`,
|
|
14269
|
-
fix: {
|
|
14270
|
-
kind: "command",
|
|
14271
|
-
command: "export MOSTRA_RUNTIME_DIR=/tmp/mostra-$USER"
|
|
14272
|
-
}
|
|
14273
|
-
}));
|
|
14274
|
-
return path;
|
|
14275
|
-
}
|
|
14276
|
-
function notOwned(path, why) {
|
|
14277
|
-
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);
|
|
14278
14859
|
}
|
|
14279
14860
|
/**
|
|
14280
|
-
* Makes `path` a directory only its owner can use (D85): creates it
|
|
14281
|
-
* tightens one the user owns
|
|
14282
|
-
* 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.
|
|
14283
14864
|
*/
|
|
14284
14865
|
function prepareOwnedDirectory(path) {
|
|
14285
|
-
|
|
14286
|
-
return prepare(path);
|
|
14287
|
-
} catch (error) {
|
|
14288
|
-
const code = error.code;
|
|
14289
|
-
if (code === "ENOTDIR" || code === "EEXIST") throw notOwned(path, "a part of the path isn't a directory");
|
|
14290
|
-
if (code === "EACCES" || code === "EPERM") throw notOwned(path, "you have no permission to use it");
|
|
14291
|
-
throw error;
|
|
14292
|
-
}
|
|
14293
|
-
}
|
|
14294
|
-
function prepare(path) {
|
|
14295
|
-
let created = false;
|
|
14296
|
-
try {
|
|
14297
|
-
statSync(path);
|
|
14298
|
-
} catch (error) {
|
|
14299
|
-
if (error.code !== "ENOENT") throw error;
|
|
14300
|
-
mkdirSync(path, {
|
|
14301
|
-
recursive: true,
|
|
14302
|
-
mode: 448
|
|
14303
|
-
});
|
|
14304
|
-
created = true;
|
|
14305
|
-
}
|
|
14306
|
-
const realPath = realpathSync(path);
|
|
14307
|
-
const stats = statSync(realPath);
|
|
14308
|
-
if (!stats.isDirectory()) throw notOwned(path, "it isn't a directory");
|
|
14309
|
-
if (stats.uid !== uid$1()) throw notOwned(path, `it belongs to user ${stats.uid}, not to you`);
|
|
14310
|
-
const mode = stats.mode & 511;
|
|
14311
|
-
if (mode !== 448) {
|
|
14312
|
-
chmodSync(realPath, 448);
|
|
14313
|
-
return created ? {
|
|
14314
|
-
realPath,
|
|
14315
|
-
created
|
|
14316
|
-
} : {
|
|
14317
|
-
realPath,
|
|
14318
|
-
created,
|
|
14319
|
-
tightenedFrom: mode
|
|
14320
|
-
};
|
|
14321
|
-
}
|
|
14322
|
-
return {
|
|
14323
|
-
realPath,
|
|
14324
|
-
created
|
|
14325
|
-
};
|
|
14866
|
+
return ownedDirectory(path);
|
|
14326
14867
|
}
|
|
14327
14868
|
//#endregion
|
|
14328
14869
|
//#region src/home/record.ts
|
|
@@ -14363,7 +14904,7 @@ function writeInstanceRecord(home, record) {
|
|
|
14363
14904
|
const file = join(home, INSTANCE_FILE);
|
|
14364
14905
|
const temp = `${file}.${process.pid}.tmp`;
|
|
14365
14906
|
writeFileSync(temp, `${JSON.stringify(record, null, 2)}\n`, { mode: 384 });
|
|
14366
|
-
|
|
14907
|
+
renamePathSync(temp, file);
|
|
14367
14908
|
}
|
|
14368
14909
|
/** Removes the record when it is still this process's (a clean exit). */
|
|
14369
14910
|
function removeInstanceRecord(home, pid, startTime) {
|
|
@@ -14396,8 +14937,12 @@ async function acquireHome(options) {
|
|
|
14396
14937
|
const prepared = prepareOwnedDirectory(options.home);
|
|
14397
14938
|
const home = prepared.realPath;
|
|
14398
14939
|
const runtimeDir = resolveRuntimeDir({ env: options.env });
|
|
14399
|
-
|
|
14400
|
-
|
|
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
|
+
}
|
|
14401
14946
|
const redactor = new Redactor();
|
|
14402
14947
|
redactor.protectEnvironment(options.env);
|
|
14403
14948
|
const log = openFileLog({
|
|
@@ -14407,10 +14952,10 @@ async function acquireHome(options) {
|
|
|
14407
14952
|
});
|
|
14408
14953
|
if (prepared.tightenedFrom !== void 0) log.warn("home.tightened", {
|
|
14409
14954
|
home,
|
|
14410
|
-
from: prepared.tightenedFrom
|
|
14411
|
-
to: "
|
|
14955
|
+
from: prepared.tightenedFrom,
|
|
14956
|
+
to: "owner only"
|
|
14412
14957
|
});
|
|
14413
|
-
if (runtimeDir
|
|
14958
|
+
if (runtimeDir?.rejected !== void 0) log.warn("home.xdg_runtime_dir_rejected", {
|
|
14414
14959
|
reason: runtimeDir.rejected,
|
|
14415
14960
|
using: runtimeDir.dir
|
|
14416
14961
|
});
|
|
@@ -14501,11 +15046,11 @@ function own(inputs) {
|
|
|
14501
15046
|
redactor,
|
|
14502
15047
|
self,
|
|
14503
15048
|
startedAt,
|
|
14504
|
-
publish(mode) {
|
|
15049
|
+
publish(mode, socket) {
|
|
14505
15050
|
writeInstanceRecord(home, {
|
|
14506
15051
|
pid: self.pid,
|
|
14507
15052
|
startTime: self.startTime,
|
|
14508
|
-
socket
|
|
15053
|
+
socket,
|
|
14509
15054
|
runtimeVersion: inputs.options.runtimeVersion,
|
|
14510
15055
|
revisions: [...HOST_PROTOCOL_REVISIONS],
|
|
14511
15056
|
mode,
|
|
@@ -14540,21 +15085,27 @@ function own(inputs) {
|
|
|
14540
15085
|
//#endregion
|
|
14541
15086
|
//#region src/home/platform.ts
|
|
14542
15087
|
/**
|
|
14543
|
-
* The unsupported-platform gate (D35, RT-07). Every entry point calls it before it touches
|
|
14544
|
-
* 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.
|
|
14545
15093
|
*/
|
|
14546
15094
|
const OPERATING_SYSTEMS = ["darwin", "linux"];
|
|
14547
15095
|
const ARCHITECTURES = ["x64", "arm64"];
|
|
14548
15096
|
/** The platform as `<os>-<arch>`, as `InstanceInfo.platform` reports it. */
|
|
14549
|
-
function platformName(platform =
|
|
15097
|
+
function platformName(platform = OS, arch = process.arch) {
|
|
14550
15098
|
return `${platform}-${arch}`;
|
|
14551
15099
|
}
|
|
14552
15100
|
/**
|
|
14553
15101
|
* Returns `MOSTRA_PLATFORM_UNSUPPORTED` for a platform Mostra doesn't run on, or `undefined` for
|
|
14554
|
-
* a supported one.
|
|
15102
|
+
* a supported one. Windows is supported only while `env` sets the development switch to `1`.
|
|
14555
15103
|
*/
|
|
14556
|
-
function checkPlatform(platform = process.
|
|
14557
|
-
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
|
+
}
|
|
14558
15109
|
const name = platform === "win32" ? `Windows (${platformName(platform, arch)})` : platformName(platform, arch);
|
|
14559
15110
|
return createDiagnostic("MOSTRA_PLATFORM_UNSUPPORTED", { message: `Mostra doesn't run on ${name}; it supports macOS and Linux on x64 and arm64.` });
|
|
14560
15111
|
}
|
|
@@ -14617,19 +15168,9 @@ function writeHomeSettings(home, change) {
|
|
|
14617
15168
|
const file = join(home, SETTINGS_FILE);
|
|
14618
15169
|
const temporary = `${file}.${process.pid}.tmp`;
|
|
14619
15170
|
writeFileSync(temporary, `${JSON.stringify(next, null, 2)}\n`, { mode: 384 });
|
|
14620
|
-
|
|
14621
|
-
|
|
14622
|
-
|
|
14623
|
-
} finally {
|
|
14624
|
-
closeSync(handle);
|
|
14625
|
-
}
|
|
14626
|
-
renameSync(temporary, file);
|
|
14627
|
-
const dir = openSync(home, "r");
|
|
14628
|
-
try {
|
|
14629
|
-
fsyncSync(dir);
|
|
14630
|
-
} catch {} finally {
|
|
14631
|
-
closeSync(dir);
|
|
14632
|
-
}
|
|
15171
|
+
fsyncPath(temporary);
|
|
15172
|
+
renamePathSync(temporary, file);
|
|
15173
|
+
fsyncPath(home, true);
|
|
14633
15174
|
}
|
|
14634
15175
|
/**
|
|
14635
15176
|
* Marks the home as configured by a host (D140 item 4), once: the first host's client name and
|
|
@@ -14649,7 +15190,7 @@ function markHostConfigured(home, client, at = /* @__PURE__ */ new Date()) {
|
|
|
14649
15190
|
* Secrets (D44, AC-06): named values server code reads with `secret(name)`, kept outside artifact
|
|
14650
15191
|
* source in the home's owner-only store, `secrets/<scope>/<name>` (mode 0600, directories 0700),
|
|
14651
15192
|
* where the scope is `home` for a secret every artifact shares or the artifact's ID for its own.
|
|
14652
|
-
* A host may supply secrets through its `secrets` port instead (
|
|
15193
|
+
* A host may supply secrets through its `secrets` port instead (a host's own credential store).
|
|
14653
15194
|
*
|
|
14654
15195
|
* Every value Mostra holds or hands out is registered with the instance's redactor, so it never
|
|
14655
15196
|
* reaches a log, a run log, an event, a diagnostic or a report. Nothing derived from a value is
|
|
@@ -14719,7 +15260,7 @@ function openSecrets(options) {
|
|
|
14719
15260
|
flag: "w"
|
|
14720
15261
|
});
|
|
14721
15262
|
chmodSync(temporary, 384);
|
|
14722
|
-
|
|
15263
|
+
renamePathSync(temporary, join(dir, name));
|
|
14723
15264
|
options.log.info("secret.set", {
|
|
14724
15265
|
name,
|
|
14725
15266
|
scope: scope.kind
|
|
@@ -14835,7 +15376,7 @@ function userHome(env) {
|
|
|
14835
15376
|
/** The service a home's daemon would be, installed or not. */
|
|
14836
15377
|
function serviceFor(spec) {
|
|
14837
15378
|
const env = spec.env ?? process.env;
|
|
14838
|
-
const platform = spec.platform ??
|
|
15379
|
+
const platform = spec.platform ?? OS;
|
|
14839
15380
|
const hash = homeHash(spec.home);
|
|
14840
15381
|
const command = [
|
|
14841
15382
|
spec.node,
|
|
@@ -15085,6 +15626,14 @@ const CLIENT = {
|
|
|
15085
15626
|
name: "mostra-runtime",
|
|
15086
15627
|
version: ""
|
|
15087
15628
|
};
|
|
15629
|
+
/** Every port this instance calls when a client registers it (`capabilities.ports`). */
|
|
15630
|
+
const SUPPORTED_PORTS = [
|
|
15631
|
+
"identity",
|
|
15632
|
+
"submissions",
|
|
15633
|
+
"drafts",
|
|
15634
|
+
"trustedControls",
|
|
15635
|
+
"secrets"
|
|
15636
|
+
];
|
|
15088
15637
|
/**
|
|
15089
15638
|
* Starts an instance for a home (RT-06): the platform gate, then the home's lock, migrations,
|
|
15090
15639
|
* reaping, the socket and `instance.json`. A daemon starter that finds the home owned attaches
|
|
@@ -15210,7 +15759,7 @@ async function assemble(home, options) {
|
|
|
15210
15759
|
let runner;
|
|
15211
15760
|
let verifier;
|
|
15212
15761
|
const sandboxOptions = () => {
|
|
15213
|
-
const workerLocation = locateWorker(environment, runtimeRoot());
|
|
15762
|
+
const workerLocation = locateWorker(environment, runtimeRoot$1());
|
|
15214
15763
|
return {
|
|
15215
15764
|
home: home.path,
|
|
15216
15765
|
log,
|
|
@@ -15232,7 +15781,7 @@ async function assemble(home, options) {
|
|
|
15232
15781
|
};
|
|
15233
15782
|
const getVerifier = () => {
|
|
15234
15783
|
if (verifier) return verifier;
|
|
15235
|
-
const located = locateRunner(environment, runtimeRoot());
|
|
15784
|
+
const located = locateRunner(environment, runtimeRoot$1());
|
|
15236
15785
|
runner = createRunnerClient({
|
|
15237
15786
|
processes: manager,
|
|
15238
15787
|
log,
|
|
@@ -15260,6 +15809,7 @@ async function assemble(home, options) {
|
|
|
15260
15809
|
});
|
|
15261
15810
|
return verifier;
|
|
15262
15811
|
};
|
|
15812
|
+
const expectedOwners = (port) => Object.entries(readHomeSettings(home.path).expectedPorts ?? {}).filter(([, ports]) => ports.includes(port)).map(([owner]) => owner);
|
|
15263
15813
|
const clockOffset = testClockOffset(environment["MOSTRA_TEST_CLOCK_OFFSET_MS"], log);
|
|
15264
15814
|
const addressing = createAddressing({
|
|
15265
15815
|
ledger: home.ledger,
|
|
@@ -15319,7 +15869,7 @@ async function assemble(home, options) {
|
|
|
15319
15869
|
const testLease = Number(environment["MOSTRA_TEST_INTEREST_LEASE_MS"]);
|
|
15320
15870
|
const bus = createEphemeralBus(testLease > 0 ? { leaseMs: testLease } : {});
|
|
15321
15871
|
const workerSocket = environment["MOSTRA_TEST_WORKER_HOST"];
|
|
15322
|
-
const located = locateWorker(environment, runtimeRoot());
|
|
15872
|
+
const located = locateWorker(environment, runtimeRoot$1());
|
|
15323
15873
|
const launcher = workerSocket ? socketLauncher(workerSocket) : localLauncher({
|
|
15324
15874
|
processes: manager,
|
|
15325
15875
|
home: home.path,
|
|
@@ -15452,10 +16002,20 @@ async function assemble(home, options) {
|
|
|
15452
16002
|
artifact,
|
|
15453
16003
|
log,
|
|
15454
16004
|
home: () => readHomeSettings(home.path).submitChannels,
|
|
15455
|
-
expected: () =>
|
|
16005
|
+
expected: () => expectedOwners("trustedControls"),
|
|
15456
16006
|
registrant: () => server.registrants("trustedControls").at(-1),
|
|
15457
16007
|
call: (session, params) => server.callSession(session, portTrustedControlsPolicyMethod.method, params, CONTROLS_POLICY_TIMEOUT_MS)
|
|
15458
16008
|
}),
|
|
16009
|
+
identity: (input) => resolveIdentity({
|
|
16010
|
+
...input,
|
|
16011
|
+
log,
|
|
16012
|
+
expected: () => {
|
|
16013
|
+
const connected = server.connectedClients();
|
|
16014
|
+
return expectedOwners("identity").filter((owner) => !connected.has(owner));
|
|
16015
|
+
},
|
|
16016
|
+
registrant: () => server.registrants("identity").at(-1),
|
|
16017
|
+
call: (session, params) => server.callSession(session, portIdentityResolveMethod.method, params, IDENTITY_TIMEOUT_MS)
|
|
16018
|
+
}),
|
|
15459
16019
|
activated: (event) => {
|
|
15460
16020
|
for (const registrant of server.registrants("trustedControls")) {
|
|
15461
16021
|
const params = {
|
|
@@ -15527,12 +16087,7 @@ async function assemble(home, options) {
|
|
|
15527
16087
|
markHostConfigured: (client) => {
|
|
15528
16088
|
if (markHostConfigured(home.path, client.name)) log.info("home.host_configured", { client: client.name });
|
|
15529
16089
|
},
|
|
15530
|
-
supportedPorts:
|
|
15531
|
-
"submissions",
|
|
15532
|
-
"drafts",
|
|
15533
|
-
"trustedControls",
|
|
15534
|
-
"secrets"
|
|
15535
|
-
],
|
|
16090
|
+
supportedPorts: SUPPORTED_PORTS,
|
|
15536
16091
|
notifications: [
|
|
15537
16092
|
EVENTS_NOTIFY,
|
|
15538
16093
|
ARTIFACT_PROGRESS,
|
|
@@ -15574,7 +16129,7 @@ async function assemble(home, options) {
|
|
|
15574
16129
|
...sessionMethods({
|
|
15575
16130
|
describe: () => info,
|
|
15576
16131
|
startedAt: home.startedAt,
|
|
15577
|
-
socketPath: () => home.socketPath,
|
|
16132
|
+
socketPath: () => server.socketPath ?? home.socketPath,
|
|
15578
16133
|
connections: () => server.connections,
|
|
15579
16134
|
processes: () => manager.list(),
|
|
15580
16135
|
gateway: () => gatewayStarted ? {
|
|
@@ -15601,7 +16156,9 @@ async function assemble(home, options) {
|
|
|
15601
16156
|
});
|
|
15602
16157
|
const instance = {
|
|
15603
16158
|
info,
|
|
15604
|
-
socketPath
|
|
16159
|
+
get socketPath() {
|
|
16160
|
+
return server.socketPath ?? home.socketPath;
|
|
16161
|
+
},
|
|
15605
16162
|
processes: manager,
|
|
15606
16163
|
reaped,
|
|
15607
16164
|
stopped,
|
|
@@ -15615,7 +16172,7 @@ async function assemble(home, options) {
|
|
|
15615
16172
|
stopWatchingPublishes();
|
|
15616
16173
|
live.stop();
|
|
15617
16174
|
interaction.stop();
|
|
15618
|
-
server.close();
|
|
16175
|
+
await server.close();
|
|
15619
16176
|
await dev.stopAll();
|
|
15620
16177
|
await gateway.close();
|
|
15621
16178
|
await pool.stopAll();
|
|
@@ -15649,15 +16206,37 @@ async function assemble(home, options) {
|
|
|
15649
16206
|
try {
|
|
15650
16207
|
await gateway.start();
|
|
15651
16208
|
gatewayStarted = true;
|
|
15652
|
-
|
|
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
|
+
});
|
|
15653
16232
|
interaction.start();
|
|
15654
16233
|
live.start();
|
|
15655
|
-
home.publish(options.mode);
|
|
16234
|
+
home.publish(options.mode, server.socketPath ?? home.socketPath);
|
|
15656
16235
|
if (options.mode === "host" && markHostConfigured(home.path, "mostra-runtime host")) log.info("home.host_configured", { client: "mostra-runtime host" });
|
|
15657
16236
|
} catch (error) {
|
|
15658
16237
|
live.stop();
|
|
15659
16238
|
interaction.stop();
|
|
15660
|
-
server.close();
|
|
16239
|
+
await server.close();
|
|
15661
16240
|
await gateway.close();
|
|
15662
16241
|
await pool.stopAll();
|
|
15663
16242
|
await manager.stopAll();
|
|
@@ -15696,7 +16275,7 @@ async function assemble(home, options) {
|
|
|
15696
16275
|
log.info("instance.started", {
|
|
15697
16276
|
mode: options.mode,
|
|
15698
16277
|
pid: process.pid,
|
|
15699
|
-
socket: home.socketPath,
|
|
16278
|
+
socket: server.socketPath ?? home.socketPath,
|
|
15700
16279
|
shell: gateway.shellOrigin()
|
|
15701
16280
|
});
|
|
15702
16281
|
return instance;
|
|
@@ -15749,4 +16328,4 @@ function sourceDirectory(path) {
|
|
|
15749
16328
|
//#endregion
|
|
15750
16329
|
export { uninstallService as a, serviceStatus as i, startInstance as n, checkPlatform as o, installService as r, resolveHomePath as s, runtimeVersion as t };
|
|
15751
16330
|
|
|
15752
|
-
//# sourceMappingURL=instance-
|
|
16331
|
+
//# sourceMappingURL=instance-DiKSe7s6.js.map
|