@mostra/runtime 0.2.0 → 0.4.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 +23 -12
- package/dist/bin.js.map +1 -1
- package/dist/builder/child/main.js +20 -18
- package/dist/builder/child/main.js.map +1 -1
- package/dist/{child-xrHmytks.js → child-Chiavhdx.js} +7 -3
- package/dist/child-Chiavhdx.js.map +1 -0
- package/dist/deps/child/install.js +9 -6
- package/dist/deps/child/install.js.map +1 -1
- package/dist/directories-mJ1qlVht.js +322 -0
- package/dist/directories-mJ1qlVht.js.map +1 -0
- package/dist/files-FygSJIzK.js +388 -0
- package/dist/files-FygSJIzK.js.map +1 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -2
- package/dist/{instance-CzBkUyHu.js → instance-DxcGEQj_.js} +1680 -934
- package/dist/instance-DxcGEQj_.js.map +1 -0
- package/package.json +5 -5
- package/src/bin.ts +18 -16
- package/src/builder/child/dev.ts +8 -4
- 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/dev/index.ts +37 -19
- package/src/faults.ts +9 -2
- package/src/gateway/capabilities.ts +2 -2
- package/src/gateway/listener.ts +36 -0
- package/src/home/acquire.ts +27 -11
- package/src/home/index.ts +1 -1
- 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 +41 -9
- package/src/ledger/index.ts +5 -27
- package/src/platform/control.ts +409 -0
- package/src/platform/directories.ts +212 -0
- package/src/platform/environment.ts +64 -0
- package/src/platform/files.ts +386 -0
- package/src/platform/helper.ts +178 -0
- package/src/{processes → platform}/identity.ts +40 -8
- package/src/platform/index.ts +53 -0
- package/src/platform/launch.ts +373 -0
- package/src/processes/child.ts +11 -5
- package/src/processes/environment.ts +22 -3
- package/src/processes/index.ts +2 -1
- package/src/processes/manager.ts +76 -179
- package/src/protocol-server/client.ts +19 -18
- package/src/protocol-server/server.ts +75 -54
- package/src/publish/index.ts +2 -1
- package/src/publish/publisher.ts +17 -10
- package/src/publish/source.ts +7 -4
- package/src/registry/store.ts +7 -65
- package/src/secrets/index.ts +2 -2
- package/src/service/unit.ts +353 -33
- package/src/verify/index.ts +5 -3
- package/src/verify/typecheck.ts +3 -2
- package/src/workers/launcher.ts +3 -1
- package/src/workers/pool.ts +14 -1
- package/dist/child-xrHmytks.js.map +0 -1
- package/dist/instance-CzBkUyHu.js.map +0 -1
- package/dist/types-NjNy7gXX.js +0 -57
- package/dist/types-NjNy7gXX.js.map +0 -1
package/src/service/unit.ts
CHANGED
|
@@ -1,25 +1,45 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* The home's login service (D62, D63, RT-08): `mostra daemon install` registers the home's
|
|
3
|
-
* with the user's service manager, so an artifact answers at any hour, even after a reboot.
|
|
4
|
-
* launchd agent on macOS, a systemd user unit on Linux
|
|
5
|
-
* --always-on --home <home>`, which never
|
|
6
|
-
*
|
|
2
|
+
* The home's login service (D62, D63, RT-08, RT-11): `mostra daemon install` registers the home's
|
|
3
|
+
* daemon with the user's service manager, so an artifact answers at any hour, even after a reboot.
|
|
4
|
+
* A launchd agent on macOS, a systemd user unit on Linux, a Task Scheduler task at the user's logon
|
|
5
|
+
* on Windows (D151); each runs `mostra-runtime daemon --always-on --home <home>`, which never
|
|
6
|
+
* exits for lack of work, and restarts it when it ends unexpectedly. On Windows the task runs the
|
|
7
|
+
* daemon through `mostra-win-service`, a launcher without a console, so no window opens at logon,
|
|
8
|
+
* which also does the restarting (Task Scheduler's own setting didn't, VERIFIED_FACTS WP-W2). The
|
|
9
|
+
* definition carries no secret: the daemon reads them from the home (D44).
|
|
7
10
|
*/
|
|
8
|
-
import { execFileSync } from "node:child_process";
|
|
9
|
-
import {
|
|
11
|
+
import { execFile, execFileSync } from "node:child_process";
|
|
12
|
+
import { randomBytes } from "node:crypto";
|
|
13
|
+
import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
|
|
10
14
|
import { homedir } from "node:os";
|
|
11
|
-
import { dirname, join } from "node:path";
|
|
12
|
-
import {
|
|
13
|
-
|
|
15
|
+
import { dirname, join, win32 } from "node:path";
|
|
16
|
+
import {
|
|
17
|
+
type ClientInfo,
|
|
18
|
+
createDiagnostic,
|
|
19
|
+
mostraShutdownMethod,
|
|
20
|
+
RpcError,
|
|
21
|
+
} from "@mostra/protocol";
|
|
22
|
+
import { homeHash, readLiveInstanceRecord } from "../home/index.ts";
|
|
14
23
|
import type { Environment } from "../log.ts";
|
|
24
|
+
import {
|
|
25
|
+
currentUserSid,
|
|
26
|
+
isSameProcess,
|
|
27
|
+
OS,
|
|
28
|
+
serviceLauncherPath,
|
|
29
|
+
stopServiceLauncher,
|
|
30
|
+
} from "../platform/index.ts";
|
|
31
|
+
import { attach } from "../protocol-server/index.ts";
|
|
15
32
|
|
|
16
33
|
/** Where a home's service is, and whether it is there. */
|
|
17
34
|
export interface ServiceStatus {
|
|
18
|
-
/** `launchd` (macOS)
|
|
19
|
-
readonly manager: "launchd" | "systemd";
|
|
20
|
-
/** The service's name: the launchd label, or the
|
|
35
|
+
/** `launchd` (macOS), `systemd` (Linux) or `task-scheduler` (Windows). */
|
|
36
|
+
readonly manager: "launchd" | "systemd" | "task-scheduler";
|
|
37
|
+
/** The service's name: the launchd label, the systemd unit, or the scheduled task. */
|
|
21
38
|
readonly name: string;
|
|
22
|
-
/**
|
|
39
|
+
/**
|
|
40
|
+
* The file that defines it. On Windows the task's definition as Mostra registered it, kept in
|
|
41
|
+
* the home (`<home>\service\task.xml`): Task Scheduler keeps its own copy.
|
|
42
|
+
*/
|
|
23
43
|
readonly file: string;
|
|
24
44
|
/** Whether the file exists. */
|
|
25
45
|
readonly installed: boolean;
|
|
@@ -35,8 +55,12 @@ export interface ServiceSpec {
|
|
|
35
55
|
readonly node: string;
|
|
36
56
|
readonly entry: string;
|
|
37
57
|
readonly env?: Environment;
|
|
38
|
-
/** `
|
|
58
|
+
/** The operating system (`OS` of the platform layer). */
|
|
39
59
|
readonly platform?: string;
|
|
60
|
+
/** Windows: the user the task runs as, a SID; default the current user. */
|
|
61
|
+
readonly user?: string;
|
|
62
|
+
/** Windows: the launcher; default `mostra-win-service.exe` beside the helper. */
|
|
63
|
+
readonly launcher?: string;
|
|
40
64
|
}
|
|
41
65
|
|
|
42
66
|
function failed(message: string): RpcError {
|
|
@@ -50,7 +74,7 @@ function userHome(env: Environment): string {
|
|
|
50
74
|
/** The service a home's daemon would be, installed or not. */
|
|
51
75
|
export function serviceFor(spec: ServiceSpec): ServiceStatus {
|
|
52
76
|
const env = spec.env ?? process.env;
|
|
53
|
-
const platform = spec.platform ??
|
|
77
|
+
const platform = spec.platform ?? OS;
|
|
54
78
|
const hash = homeHash(spec.home);
|
|
55
79
|
const command = [spec.node, spec.entry, "daemon", "--always-on", "--home", spec.home];
|
|
56
80
|
if (platform === "darwin") {
|
|
@@ -69,6 +93,25 @@ export function serviceFor(spec: ServiceSpec): ServiceStatus {
|
|
|
69
93
|
const file = join(config, "systemd", "user", name);
|
|
70
94
|
return { manager: "systemd", name, file, installed: existsSync(file), command };
|
|
71
95
|
}
|
|
96
|
+
if (platform === "win32") {
|
|
97
|
+
const file = win32.join(spec.home, "service", "task.xml");
|
|
98
|
+
return {
|
|
99
|
+
manager: "task-scheduler",
|
|
100
|
+
name: `mostra-${hash.toLowerCase()}`,
|
|
101
|
+
file,
|
|
102
|
+
installed: existsSync(file),
|
|
103
|
+
command: [
|
|
104
|
+
spec.launcher ?? launcherOrName(),
|
|
105
|
+
"--stop-event",
|
|
106
|
+
stopEventOf(file) ?? newStopEvent(hash),
|
|
107
|
+
"--log",
|
|
108
|
+
win32.join(spec.home, "logs", "service.log"),
|
|
109
|
+
...windowsServiceVariables(env).flatMap(([name, value]) => ["--env", `${name}=${value}`]),
|
|
110
|
+
"--",
|
|
111
|
+
...command,
|
|
112
|
+
],
|
|
113
|
+
};
|
|
114
|
+
}
|
|
72
115
|
throw new RpcError(
|
|
73
116
|
createDiagnostic("MOSTRA_PLATFORM_UNSUPPORTED", {
|
|
74
117
|
message: `Mostra can't install a login service on ${platform}.`,
|
|
@@ -76,18 +119,156 @@ export function serviceFor(spec: ServiceSpec): ServiceStatus {
|
|
|
76
119
|
);
|
|
77
120
|
}
|
|
78
121
|
|
|
122
|
+
/**
|
|
123
|
+
* What a Windows task passes on besides the user's logon environment, which Task Scheduler gives
|
|
124
|
+
* it: the development switch while Windows needs it (D150 item 7, until WP-W3), the helper a
|
|
125
|
+
* checkout names, and the locale and time zone, as the POSIX units carry theirs. Nothing secret.
|
|
126
|
+
*/
|
|
127
|
+
function windowsServiceVariables(env: Environment): [string, string][] {
|
|
128
|
+
return ["MOSTRA_DEV_WINDOWS", "MOSTRA_WIN_HELPER", "LANG", "TZ"].flatMap((name) => {
|
|
129
|
+
const value = env[name];
|
|
130
|
+
return value ? [[name, value] as [string, string]] : [];
|
|
131
|
+
});
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* A new name for the event that asks a home's launcher to stop: in `Local\` (the logon session's
|
|
136
|
+
* namespace, the only one an ordinary user may create names in), with a random part, so nobody who
|
|
137
|
+
* can't read the task or the home can create it first (Opus review of WP-W2, finding 6).
|
|
138
|
+
*/
|
|
139
|
+
const newStopEvent = (hash: string): string =>
|
|
140
|
+
`Local\\mostra-service-${hash.toLowerCase()}-${randomBytes(8).toString("hex")}`;
|
|
141
|
+
|
|
142
|
+
/** The stop event a definition Mostra wrote names, if the file is there. */
|
|
143
|
+
function stopEventOf(file: string): string | undefined {
|
|
144
|
+
try {
|
|
145
|
+
const text = readFileSync(file).toString("utf16le");
|
|
146
|
+
return /--stop-event (Local\\mostra-service-[0-9a-z]+-[0-9a-f]{16})\b/.exec(text)?.[1];
|
|
147
|
+
} catch {
|
|
148
|
+
return undefined;
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/** The launcher's path, or its bare name where it isn't installed (a status only reads it). */
|
|
153
|
+
function launcherOrName(): string {
|
|
154
|
+
try {
|
|
155
|
+
return serviceLauncherPath();
|
|
156
|
+
} catch {
|
|
157
|
+
return "mostra-win-service.exe";
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/** One word of a Windows command line, quoted as the Microsoft C runtime parses it. */
|
|
162
|
+
export function windowsArgument(word: string): string {
|
|
163
|
+
if (word !== "" && !/[\s"]/.test(word)) return word;
|
|
164
|
+
let out = '"';
|
|
165
|
+
let backslashes = 0;
|
|
166
|
+
for (const char of word) {
|
|
167
|
+
if (char === "\\") {
|
|
168
|
+
backslashes += 1;
|
|
169
|
+
continue;
|
|
170
|
+
}
|
|
171
|
+
out += "\\".repeat(char === '"' ? backslashes * 2 + 1 : backslashes) + char;
|
|
172
|
+
backslashes = 0;
|
|
173
|
+
}
|
|
174
|
+
return `${out}${"\\".repeat(backslashes * 2)}"`;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/** The Task Scheduler definition (schema 1.2) of a home's task. */
|
|
178
|
+
function taskFile(spec: ServiceSpec, status: ServiceStatus): string {
|
|
179
|
+
const user = xml(spec.user ?? currentUserSid());
|
|
180
|
+
const [program = "", ...args] = status.command;
|
|
181
|
+
return `<?xml version="1.0" encoding="UTF-16"?>
|
|
182
|
+
<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
|
|
183
|
+
<RegistrationInfo>
|
|
184
|
+
<Description>${xml(`Mostra daemon for ${spec.home}`)}</Description>
|
|
185
|
+
</RegistrationInfo>
|
|
186
|
+
<Triggers>
|
|
187
|
+
<LogonTrigger>
|
|
188
|
+
<Enabled>true</Enabled>
|
|
189
|
+
<UserId>${user}</UserId>
|
|
190
|
+
</LogonTrigger>
|
|
191
|
+
</Triggers>
|
|
192
|
+
<Principals>
|
|
193
|
+
<Principal id="Author">
|
|
194
|
+
<UserId>${user}</UserId>
|
|
195
|
+
<LogonType>InteractiveToken</LogonType>
|
|
196
|
+
<RunLevel>LeastPrivilege</RunLevel>
|
|
197
|
+
</Principal>
|
|
198
|
+
</Principals>
|
|
199
|
+
<Settings>
|
|
200
|
+
<MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
|
|
201
|
+
<DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>
|
|
202
|
+
<StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>
|
|
203
|
+
<AllowHardTerminate>true</AllowHardTerminate>
|
|
204
|
+
<StartWhenAvailable>false</StartWhenAvailable>
|
|
205
|
+
<RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>
|
|
206
|
+
<IdleSettings>
|
|
207
|
+
<StopOnIdleEnd>false</StopOnIdleEnd>
|
|
208
|
+
<RestartOnIdle>false</RestartOnIdle>
|
|
209
|
+
</IdleSettings>
|
|
210
|
+
<AllowStartOnDemand>true</AllowStartOnDemand>
|
|
211
|
+
<Enabled>true</Enabled>
|
|
212
|
+
<Hidden>false</Hidden>
|
|
213
|
+
<RunOnlyIfIdle>false</RunOnlyIfIdle>
|
|
214
|
+
<WakeToRun>false</WakeToRun>
|
|
215
|
+
<ExecutionTimeLimit>PT0S</ExecutionTimeLimit>
|
|
216
|
+
<Priority>5</Priority>
|
|
217
|
+
</Settings>
|
|
218
|
+
<Actions Context="Author">
|
|
219
|
+
<Exec>
|
|
220
|
+
<Command>${xml(program)}</Command>
|
|
221
|
+
<Arguments>${xml(args.map(windowsArgument).join(" "))}</Arguments>
|
|
222
|
+
</Exec>
|
|
223
|
+
</Actions>
|
|
224
|
+
</Task>
|
|
225
|
+
`;
|
|
226
|
+
}
|
|
227
|
+
|
|
79
228
|
/**
|
|
80
229
|
* Whether `home` has a login service installed: its daemon then never exits for lack of work,
|
|
81
230
|
* whoever started it, so a daemon started by hand before `install` keeps the artifacts answering.
|
|
82
231
|
*/
|
|
83
232
|
export function hasLoginService(home: string, env: Environment = process.env): boolean {
|
|
84
233
|
try {
|
|
85
|
-
|
|
234
|
+
const status = serviceFor({ home, node: "", entry: "", env });
|
|
235
|
+
if (!status.installed) return false;
|
|
236
|
+
return status.manager !== "task-scheduler" || registeredLately(status);
|
|
86
237
|
} catch {
|
|
87
238
|
return false;
|
|
88
239
|
}
|
|
89
240
|
}
|
|
90
241
|
|
|
242
|
+
/** What the idle check last learnt of each task: whether Task Scheduler holds it, and when. */
|
|
243
|
+
const registrations = new Map<string, { registered?: boolean; at: number; asking: boolean }>();
|
|
244
|
+
|
|
245
|
+
/**
|
|
246
|
+
* Whether Task Scheduler held the task when last asked, asking again in the background at most
|
|
247
|
+
* once a minute: the idle check runs every few seconds and must never wait for `schtasks`. A task
|
|
248
|
+
* removed in Task Scheduler's own window then stops counting, so a daemon started by hand exits
|
|
249
|
+
* when idle again (Opus review of WP-W2, finding 5). Until the first answer, the definition in the
|
|
250
|
+
* home counts.
|
|
251
|
+
*/
|
|
252
|
+
function registeredLately(status: ServiceStatus): boolean {
|
|
253
|
+
const interval = Number(process.env["MOSTRA_TEST_SERVICE_QUERY_MS"]) || 60_000;
|
|
254
|
+
const entry = registrations.get(status.name) ?? { at: Number.NEGATIVE_INFINITY, asking: false };
|
|
255
|
+
registrations.set(status.name, entry);
|
|
256
|
+
if (!entry.asking && Date.now() - entry.at >= interval) {
|
|
257
|
+
entry.asking = true;
|
|
258
|
+
execFile(
|
|
259
|
+
"schtasks",
|
|
260
|
+
["/Query", "/TN", status.name],
|
|
261
|
+
{ timeout: 30_000, windowsHide: true },
|
|
262
|
+
(error) => {
|
|
263
|
+
entry.registered = error === null;
|
|
264
|
+
entry.at = Date.now();
|
|
265
|
+
entry.asking = false;
|
|
266
|
+
},
|
|
267
|
+
);
|
|
268
|
+
}
|
|
269
|
+
return entry.registered ?? true;
|
|
270
|
+
}
|
|
271
|
+
|
|
91
272
|
const xml = (text: string): string =>
|
|
92
273
|
text.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
|
|
93
274
|
|
|
@@ -117,6 +298,8 @@ function serviceEnvironment(env: Environment): Record<string, string> {
|
|
|
117
298
|
|
|
118
299
|
/** The text of the service's file. */
|
|
119
300
|
export function serviceFile(spec: ServiceSpec, status: ServiceStatus): string {
|
|
301
|
+
// The task runs in the user's own logon environment, as any program they start does.
|
|
302
|
+
if (status.manager === "task-scheduler") return taskFile(spec, status);
|
|
120
303
|
const env = serviceEnvironment(spec.env ?? process.env);
|
|
121
304
|
const log = join(spec.home, "logs", "service.log");
|
|
122
305
|
if (status.manager === "launchd") {
|
|
@@ -178,6 +361,8 @@ WantedBy=default.target
|
|
|
178
361
|
export interface ServiceOptions {
|
|
179
362
|
/** Write the file only, without asking the service manager to start it (tests). */
|
|
180
363
|
readonly noStart?: boolean;
|
|
364
|
+
/** Who asks, when a Windows uninstall stops the daemon over its pipe. */
|
|
365
|
+
readonly client?: ClientInfo;
|
|
181
366
|
}
|
|
182
367
|
|
|
183
368
|
function run(command: string, args: readonly string[]): void {
|
|
@@ -192,44 +377,169 @@ function run(command: string, args: readonly string[]): void {
|
|
|
192
377
|
|
|
193
378
|
const uid = (): number => process.getuid?.() ?? 0;
|
|
194
379
|
|
|
380
|
+
/** The definition's bytes: Task Scheduler reads UTF-16 with its byte order mark. */
|
|
381
|
+
function encoded(status: ServiceStatus, text: string): Buffer | string {
|
|
382
|
+
return status.manager === "task-scheduler" ? Buffer.from(`\ufeff${text}`, "utf16le") : text;
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
/** The definition as written, decoded as {@link encoded} wrote it. */
|
|
386
|
+
function readDefinition(status: ServiceStatus): string {
|
|
387
|
+
const bytes = readFileSync(status.file);
|
|
388
|
+
if (status.manager !== "task-scheduler") return bytes.toString("utf8");
|
|
389
|
+
return bytes.toString("utf16le").replace(/^\ufeff/, "");
|
|
390
|
+
}
|
|
391
|
+
|
|
195
392
|
/** Installs the home's daemon as a login service and starts it, replacing an earlier one. */
|
|
196
|
-
export function installService(
|
|
197
|
-
|
|
393
|
+
export async function installService(
|
|
394
|
+
spec: ServiceSpec,
|
|
395
|
+
options: ServiceOptions = {},
|
|
396
|
+
): Promise<ServiceStatus> {
|
|
397
|
+
// On Windows a launcher that isn't there is MOSTRA_ENV_HELPER_MISSING before anything is written.
|
|
398
|
+
const status = serviceFor(
|
|
399
|
+
(spec.platform ?? OS) === "win32" && spec.launcher === undefined
|
|
400
|
+
? { ...spec, launcher: serviceLauncherPath() }
|
|
401
|
+
: spec,
|
|
402
|
+
);
|
|
198
403
|
const text = serviceFile(spec, status);
|
|
404
|
+
// Windows: the home keeps the definition only once Task Scheduler took it, so a definition in
|
|
405
|
+
// the home names a task that was registered (Opus review of WP-W2, finding 5).
|
|
406
|
+
const registering = status.manager === "task-scheduler" && !options.noStart;
|
|
407
|
+
const written = registering ? `${status.file}.new` : status.file;
|
|
199
408
|
try {
|
|
200
409
|
mkdirSync(dirname(status.file), { recursive: true });
|
|
201
410
|
mkdirSync(join(spec.home, "logs"), { recursive: true, mode: 0o700 });
|
|
202
|
-
if (status.installed && !options.noStart) stopService(status);
|
|
203
|
-
writeFileSync(status
|
|
411
|
+
if (status.installed && !options.noStart) await stopService(status, spec.home, options);
|
|
412
|
+
writeFileSync(written, encoded(status, text), { mode: 0o644 });
|
|
204
413
|
} catch (error) {
|
|
205
414
|
if (error instanceof RpcError) throw error;
|
|
206
415
|
throw failed(`Writing ${status.file} failed: ${(error as Error).message}`);
|
|
207
416
|
}
|
|
417
|
+
if (registering) {
|
|
418
|
+
try {
|
|
419
|
+
run("schtasks", ["/Create", "/TN", status.name, "/XML", written, "/F"]);
|
|
420
|
+
renameSync(written, status.file);
|
|
421
|
+
} finally {
|
|
422
|
+
rmSync(written, { force: true });
|
|
423
|
+
}
|
|
424
|
+
registrations.delete(status.name);
|
|
425
|
+
}
|
|
208
426
|
if (!options.noStart) {
|
|
209
427
|
if (status.manager === "launchd") {
|
|
210
428
|
run("launchctl", ["bootstrap", `gui/${uid()}`, status.file]);
|
|
211
|
-
} else {
|
|
429
|
+
} else if (status.manager === "systemd") {
|
|
212
430
|
run("systemctl", ["--user", "daemon-reload"]);
|
|
213
431
|
run("systemctl", ["--user", "enable", "--now", status.name]);
|
|
432
|
+
} else {
|
|
433
|
+
// Registered above for the user's own logons, which needs no elevation (InteractiveToken),
|
|
434
|
+
// and started now, as launchd's RunAtLoad and systemd's `--now` start theirs.
|
|
435
|
+
run("schtasks", ["/Run", "/TN", status.name]);
|
|
214
436
|
}
|
|
215
437
|
}
|
|
216
438
|
return { ...status, installed: true };
|
|
217
439
|
}
|
|
218
440
|
|
|
219
|
-
function stopService(
|
|
441
|
+
async function stopService(
|
|
442
|
+
status: ServiceStatus,
|
|
443
|
+
home: string,
|
|
444
|
+
options: ServiceOptions,
|
|
445
|
+
): Promise<void> {
|
|
220
446
|
try {
|
|
221
447
|
if (status.manager === "launchd") run("launchctl", ["bootout", `gui/${uid()}/${status.name}`]);
|
|
222
|
-
else
|
|
448
|
+
else if (status.manager === "systemd")
|
|
449
|
+
run("systemctl", ["--user", "disable", "--now", status.name]);
|
|
450
|
+
else await stopTask(status, home, options);
|
|
223
451
|
} catch {
|
|
224
452
|
// Not loaded: nothing to stop.
|
|
225
453
|
}
|
|
226
454
|
}
|
|
227
455
|
|
|
228
|
-
/**
|
|
229
|
-
|
|
456
|
+
/**
|
|
457
|
+
* Stops and deletes a home's task, the daemon first and in order (D87), as launchd's `bootout`
|
|
458
|
+
* and systemd's `disable --now` send it SIGTERM:
|
|
459
|
+
* - through the launcher's stop event, when this logon session has it: the launcher gives the
|
|
460
|
+
* daemon Ctrl+Break, which the runtime handles as `mostra/shutdown`;
|
|
461
|
+
* - otherwise (the launcher runs in another session, as when the user is logged on at the console
|
|
462
|
+
* and uninstalls over SSH, or the home lost the definition naming the event) with
|
|
463
|
+
* `mostra/shutdown` over the home's pipe, which reaches the daemon from any session; its exit
|
|
464
|
+
* with code 0 ends the launcher (Opus review of WP-W2, finding 4);
|
|
465
|
+
*
|
|
466
|
+
* then the task is ended, which ends whatever its job still holds, and deleted.
|
|
467
|
+
*/
|
|
468
|
+
async function stopTask(
|
|
469
|
+
status: ServiceStatus,
|
|
470
|
+
home: string,
|
|
471
|
+
options: ServiceOptions,
|
|
472
|
+
): Promise<void> {
|
|
473
|
+
const event = status.installed
|
|
474
|
+
? status.command[status.command.indexOf("--stop-event") + 1]
|
|
475
|
+
: undefined;
|
|
476
|
+
let signalled = false;
|
|
477
|
+
// A test stands for another session's launcher, whose event this session can't see.
|
|
478
|
+
if (event !== undefined && process.env["MOSTRA_TEST_SERVICE_STOP"] !== "pipe") {
|
|
479
|
+
try {
|
|
480
|
+
signalled = stopServiceLauncher(event).signalled;
|
|
481
|
+
} catch {
|
|
482
|
+
// The helper couldn't ask: the pipe below stops the daemon.
|
|
483
|
+
}
|
|
484
|
+
}
|
|
485
|
+
if (!signalled) await shutDownInstance(home, options.client);
|
|
486
|
+
try {
|
|
487
|
+
run("schtasks", ["/End", "/TN", status.name]);
|
|
488
|
+
} catch {
|
|
489
|
+
// Not running.
|
|
490
|
+
}
|
|
491
|
+
run("schtasks", ["/Delete", "/TN", status.name, "/F"]);
|
|
492
|
+
registrations.delete(status.name);
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
/** Asks the home's running daemon, if any, to stop (`mostra/shutdown`), and waits until it has. */
|
|
496
|
+
async function shutDownInstance(home: string, client: ClientInfo | undefined): Promise<void> {
|
|
497
|
+
const record = await readLiveInstanceRecord(home);
|
|
498
|
+
if (record === undefined || record.mode !== "daemon") return;
|
|
499
|
+
try {
|
|
500
|
+
const session = await attach(record.socket, client ?? { name: "mostra-service", version: "0" });
|
|
501
|
+
await session.client.peer
|
|
502
|
+
.call(mostraShutdownMethod, {}, { timeoutMs: 10_000 })
|
|
503
|
+
.catch(() => undefined);
|
|
504
|
+
session.client.close();
|
|
505
|
+
} catch {
|
|
506
|
+
// Unreachable: ending the task stops it.
|
|
507
|
+
return;
|
|
508
|
+
}
|
|
509
|
+
const deadline = Date.now() + 20_000;
|
|
510
|
+
while (Date.now() < deadline && (await isSameProcess(record.pid, record.startTime))) {
|
|
511
|
+
await new Promise((resolve) => setTimeout(resolve, 100));
|
|
512
|
+
}
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
/** Whether Task Scheduler holds the home's task. */
|
|
516
|
+
function taskRegistered(status: ServiceStatus): boolean {
|
|
517
|
+
try {
|
|
518
|
+
run("schtasks", ["/Query", "/TN", status.name]);
|
|
519
|
+
return true;
|
|
520
|
+
} catch {
|
|
521
|
+
return false;
|
|
522
|
+
}
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
/**
|
|
526
|
+
* Stops and removes the home's login service; a home without one is left as it is. On Windows a
|
|
527
|
+
* task Task Scheduler still holds is removed though the home lost its definition (restored from a
|
|
528
|
+
* backup, removed by hand), or the task would keep starting the daemon at every logon (Opus review
|
|
529
|
+
* of WP-W2, finding 5).
|
|
530
|
+
*/
|
|
531
|
+
export async function uninstallService(
|
|
532
|
+
spec: ServiceSpec,
|
|
533
|
+
options: ServiceOptions = {},
|
|
534
|
+
): Promise<ServiceStatus> {
|
|
230
535
|
const status = serviceFor(spec);
|
|
231
|
-
|
|
232
|
-
|
|
536
|
+
const orphaned =
|
|
537
|
+
!status.installed &&
|
|
538
|
+
status.manager === "task-scheduler" &&
|
|
539
|
+
!options.noStart &&
|
|
540
|
+
taskRegistered(status);
|
|
541
|
+
if (!status.installed && !orphaned) return status;
|
|
542
|
+
if (!options.noStart) await stopService(status, spec.home, options);
|
|
233
543
|
rmSync(status.file, { force: true });
|
|
234
544
|
if (!options.noStart && status.manager === "systemd") {
|
|
235
545
|
try {
|
|
@@ -241,10 +551,20 @@ export function uninstallService(spec: ServiceSpec, options: ServiceOptions = {}
|
|
|
241
551
|
return { ...status, installed: false };
|
|
242
552
|
}
|
|
243
553
|
|
|
244
|
-
/**
|
|
245
|
-
|
|
554
|
+
/**
|
|
555
|
+
* Whether the home has a login service whose file runs this home's daemon (`mostra doctor`); on
|
|
556
|
+
* Windows also whether Task Scheduler holds its task (`registered`).
|
|
557
|
+
*/
|
|
558
|
+
export function serviceStatus(
|
|
559
|
+
spec: ServiceSpec,
|
|
560
|
+
): ServiceStatus & { readonly current: boolean; readonly registered?: boolean } {
|
|
246
561
|
const status = serviceFor(spec);
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
return { ...status, current:
|
|
562
|
+
const registered =
|
|
563
|
+
status.manager === "task-scheduler" ? { registered: taskRegistered(status) } : {};
|
|
564
|
+
if (!status.installed) return { ...status, current: false, ...registered };
|
|
565
|
+
return {
|
|
566
|
+
...status,
|
|
567
|
+
current: readDefinition(status) === serviceFile(spec, status),
|
|
568
|
+
...registered,
|
|
569
|
+
};
|
|
250
570
|
}
|
package/src/verify/index.ts
CHANGED
|
@@ -16,7 +16,7 @@
|
|
|
16
16
|
*/
|
|
17
17
|
import { createHash, randomUUID } from "node:crypto";
|
|
18
18
|
import { existsSync, readFileSync } from "node:fs";
|
|
19
|
-
import { mkdir, readdir,
|
|
19
|
+
import { mkdir, readdir, rm, stat, utimes, writeFile } from "node:fs/promises";
|
|
20
20
|
import { join } from "node:path";
|
|
21
21
|
import {
|
|
22
22
|
type ArtifactManifest,
|
|
@@ -59,6 +59,8 @@ export {
|
|
|
59
59
|
startSandbox,
|
|
60
60
|
} from "./sandbox.ts";
|
|
61
61
|
|
|
62
|
+
import { renamePath } from "../platform/index.ts";
|
|
63
|
+
|
|
62
64
|
/** The revision of verify's rules: a cached verdict made under other rules is never reused. */
|
|
63
65
|
export const VERIFY_REVISION: string = createHash("sha256")
|
|
64
66
|
.update(`verify 2 ${TYPECHECK_REVISION}`)
|
|
@@ -339,7 +341,7 @@ export function createVerifier(options: VerifierOptions): Verifier {
|
|
|
339
341
|
const outcome = await run.build(temporary);
|
|
340
342
|
if (!outcome.ok) return outcome;
|
|
341
343
|
await rm(join(buildsDir, prepared.versionId), { recursive: true, force: true });
|
|
342
|
-
await
|
|
344
|
+
await renamePath(temporary, join(buildsDir, prepared.versionId));
|
|
343
345
|
await pruneBuilds(prepared.versionId);
|
|
344
346
|
return outcome;
|
|
345
347
|
} finally {
|
|
@@ -756,7 +758,7 @@ export function createVerifier(options: VerifierOptions): Verifier {
|
|
|
756
758
|
temporary,
|
|
757
759
|
`${JSON.stringify({ verdict: checkedVerdict, built: built.ok }, null, 2)}\n`,
|
|
758
760
|
);
|
|
759
|
-
await
|
|
761
|
+
await renamePath(temporary, target);
|
|
760
762
|
await pruneVerdicts();
|
|
761
763
|
} else {
|
|
762
764
|
// Its screenshots stay for the caller who reads this verdict; the cache's pruning removes
|
package/src/verify/typecheck.ts
CHANGED
|
@@ -12,13 +12,14 @@
|
|
|
12
12
|
*/
|
|
13
13
|
import { createHash } from "node:crypto";
|
|
14
14
|
import { existsSync, readFileSync } from "node:fs";
|
|
15
|
-
import { cp, mkdir, rm,
|
|
15
|
+
import { cp, mkdir, rm, writeFile } from "node:fs/promises";
|
|
16
16
|
import { createRequire } from "node:module";
|
|
17
17
|
import { dirname, join } from "node:path";
|
|
18
18
|
import { createDiagnostic, type Diagnostic } from "@mostra/protocol";
|
|
19
19
|
import { LIVE_DECLARATION } from "../builder/index.ts";
|
|
20
20
|
import { runtimeRoot } from "../deps/index.ts";
|
|
21
21
|
import type { Environment, Log } from "../log.ts";
|
|
22
|
+
import { linkDirectory } from "../platform/index.ts";
|
|
22
23
|
import type { ProcessManager } from "../processes/index.ts";
|
|
23
24
|
|
|
24
25
|
/** How long the check may take: the build's own limit, which it runs beside (FAILURE_MODEL §9). */
|
|
@@ -247,7 +248,7 @@ export async function typecheck(options: {
|
|
|
247
248
|
await mkdir(join(workDir, ".mostra-check"), { recursive: true });
|
|
248
249
|
try {
|
|
249
250
|
await cp(options.sourceDir, join(workDir, "source"), { recursive: true });
|
|
250
|
-
await
|
|
251
|
+
await linkDirectory(options.nodeModules, join(workDir, "node_modules"));
|
|
251
252
|
await writeFile(join(workDir, ".mostra-check", "assets.d.ts"), AMBIENT);
|
|
252
253
|
if (options.hasLive)
|
|
253
254
|
await writeFile(join(workDir, ".mostra-check", "mostra-env.d.ts"), LIVE_DECLARATION);
|
package/src/workers/launcher.ts
CHANGED
|
@@ -16,6 +16,7 @@ import {
|
|
|
16
16
|
type WorkerVersionRef,
|
|
17
17
|
} from "@mostra/protocol";
|
|
18
18
|
import type { Environment } from "../log.ts";
|
|
19
|
+
import { pathKey } from "../platform/index.ts";
|
|
19
20
|
import type { ProcessManager } from "../processes/index.ts";
|
|
20
21
|
|
|
21
22
|
/** How a worker ended. */
|
|
@@ -121,7 +122,8 @@ export function localLauncher(options: LocalLauncherOptions): WorkerLauncher {
|
|
|
121
122
|
resolve(options.home, "cache", "builds"),
|
|
122
123
|
resolve(options.home, "cache", "dev"),
|
|
123
124
|
];
|
|
124
|
-
|
|
125
|
+
// Strictly inside one of them, compared as the platform compares paths (WP-W1).
|
|
126
|
+
if (!roots.some((root) => pathKey(versionDir).startsWith(`${pathKey(root)}/`))) {
|
|
125
127
|
throw new Error(
|
|
126
128
|
"A home: locator names a version directory, a verify build or a dev session of the home.",
|
|
127
129
|
);
|
package/src/workers/pool.ts
CHANGED
|
@@ -210,6 +210,19 @@ const PINGS_MISSED_BEFORE_STOP = 3;
|
|
|
210
210
|
*/
|
|
211
211
|
const OOM_STALL_FRACTION = 0.8;
|
|
212
212
|
|
|
213
|
+
/**
|
|
214
|
+
* An exit code as people look it up: a Windows status (`0xC0000005`, an access violation) in
|
|
215
|
+
* hexadecimal, any other code as a number. Node.js reports a Windows status as an unsigned
|
|
216
|
+
* 32-bit number; on POSIX codes are below 256.
|
|
217
|
+
*/
|
|
218
|
+
export function exitCodeText(code: number | null): string {
|
|
219
|
+
if (code === null) return "?";
|
|
220
|
+
if (code >= 0x80000000 || code < 0) {
|
|
221
|
+
return `0x${(code >>> 0).toString(16).toUpperCase().padStart(8, "0")}`;
|
|
222
|
+
}
|
|
223
|
+
return String(code);
|
|
224
|
+
}
|
|
225
|
+
|
|
213
226
|
function crashed(message: string): RpcError {
|
|
214
227
|
return new RpcError(createDiagnostic("MOSTRA_RUNTIME_WORKER_CRASHED", { message }));
|
|
215
228
|
}
|
|
@@ -298,7 +311,7 @@ export function createWorkerPool(options: WorkerPoolOptions): WorkerPool {
|
|
|
298
311
|
const how =
|
|
299
312
|
exit.signal !== null
|
|
300
313
|
? `it was ended by ${exit.signal}`
|
|
301
|
-
: `it exited with code ${exit.code
|
|
314
|
+
: `it exited with code ${exitCodeText(exit.code)}`;
|
|
302
315
|
return { kind: "crash", cause: last ? `${how}: ${last.slice(0, 300)}` : how };
|
|
303
316
|
};
|
|
304
317
|
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"child-xrHmytks.js","names":[],"sources":["../src/processes/child.ts"],"sourcesContent":["/**\n * The child side of supervisor messaging, for Node children the process manager starts with an\n * IPC channel. It wires the JSON-RPC core to Node IPC and keeps the rule that a child never\n * outlives its supervisor: when the channel disconnects (the supervisor exited or was killed), the\n * child signals its own process group, so grandchildren go too, and exits (FAILURE_MODEL §2).\n *\n * ```ts\n * const supervisor = connectToSupervisor({ onRequest: (method, params) => handle(method, params) });\n * await supervisor.request(\"child/adopt\", { pid: pty.pid }); // a program in its own session\n * ```\n */\nimport { type JsonRpcParams, RpcPeer } from \"@mostra/protocol\";\n\n/** Options for {@link connectToSupervisor}. */\nexport interface SupervisorConnectionOptions {\n /** Answers the supervisor's requests. */\n readonly onRequest?: (method: string, params: unknown) => unknown;\n /** Receives the supervisor's notifications. */\n readonly onNotification?: (method: string, params: unknown) => void;\n}\n\n/** The child's end of the connection. */\nexport interface SupervisorConnection {\n /** Sends a request to the supervisor, such as `child/adopt`. */\n request(method: string, params?: JsonRpcParams): Promise<unknown>;\n /** Sends a notification to the supervisor. */\n notify(method: string, params?: JsonRpcParams): void;\n}\n\n/**\n * Connects a Node child to its supervisor over the IPC channel.\n *\n * @throws Error when the process wasn't started with an IPC channel.\n */\nexport function connectToSupervisor(\n options: SupervisorConnectionOptions = {},\n): SupervisorConnection {\n const send = process.send?.bind(process);\n if (!send)\n throw new Error(\"This process wasn't started by a Mostra supervisor (no IPC channel).\");\n const peer = new RpcPeer({\n send: (message) => {\n send(message);\n },\n ...(options.onRequest ? { onRequest: options.onRequest } : {}),\n ...(options.onNotification ? { onNotification: options.onNotification } : {}),\n });\n process.on(\"message\", (message) => peer.receive(message));\n process.on(\"disconnect\", () => {\n peer.close();\n exitWithGroup();\n });\n return {\n request: (method, params) => peer.request(method, params),\n notify: (method, params) => peer.notify(method, params),\n };\n}\n\n/** Signals this child's whole process group (it leads it) and exits. */\nfunction exitWithGroup(): void {\n try {\n process.kill(-process.pid, \"SIGTERM\");\n } catch {\n // The group is already gone.\n }\n process.exit(0);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAkCA,SAAgB,oBACd,UAAuC,CAAC,GAClB;CACtB,MAAM,OAAO,QAAQ,MAAM,KAAK,OAAO;CACvC,IAAI,CAAC,MACH,MAAM,IAAI,MAAM,sEAAsE;CACxF,MAAM,OAAO,IAAI,QAAQ;EACvB,OAAO,YAAY;GACjB,KAAK,OAAO;EACd;EACA,GAAI,QAAQ,YAAY,EAAE,WAAW,QAAQ,UAAU,IAAI,CAAC;EAC5D,GAAI,QAAQ,iBAAiB,EAAE,gBAAgB,QAAQ,eAAe,IAAI,CAAC;CAC7E,CAAC;CACD,QAAQ,GAAG,YAAY,YAAY,KAAK,QAAQ,OAAO,CAAC;CACxD,QAAQ,GAAG,oBAAoB;EAC7B,KAAK,MAAM;EACX,cAAc;CAChB,CAAC;CACD,OAAO;EACL,UAAU,QAAQ,WAAW,KAAK,QAAQ,QAAQ,MAAM;EACxD,SAAS,QAAQ,WAAW,KAAK,OAAO,QAAQ,MAAM;CACxD;AACF;;AAGA,SAAS,gBAAsB;CAC7B,IAAI;EACF,QAAQ,KAAK,CAAC,QAAQ,KAAK,SAAS;CACtC,QAAQ,CAER;CACA,QAAQ,KAAK,CAAC;AAChB"}
|