@mostra/runtime 0.3.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 +17 -6
- package/dist/bin.js.map +1 -1
- package/dist/builder/child/main.js +4 -3
- package/dist/builder/child/main.js.map +1 -1
- package/dist/{child-BQc3arf7.js → child-Chiavhdx.js} +3 -2
- package/dist/child-Chiavhdx.js.map +1 -0
- package/dist/deps/child/install.js +1 -1
- package/dist/directories-mJ1qlVht.js +322 -0
- package/dist/directories-mJ1qlVht.js.map +1 -0
- package/dist/{files-KxzOxckl.js → files-FygSJIzK.js} +14 -300
- package/dist/files-FygSJIzK.js.map +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -2
- package/dist/{instance-DiKSe7s6.js → instance-DxcGEQj_.js} +379 -44
- package/dist/instance-DxcGEQj_.js.map +1 -0
- package/package.json +5 -5
- package/src/bin.ts +14 -6
- package/src/builder/child/dev.ts +4 -1
- package/src/dev/index.ts +37 -19
- package/src/gateway/listener.ts +36 -0
- package/src/home/index.ts +1 -1
- package/src/instance/index.ts +11 -3
- package/src/platform/files.ts +19 -1
- package/src/platform/helper.ts +26 -0
- package/src/platform/index.ts +8 -1
- package/src/processes/child.ts +7 -4
- package/src/publish/index.ts +2 -1
- package/src/publish/publisher.ts +1 -1
- package/src/service/unit.ts +351 -32
- package/src/workers/pool.ts +14 -1
- package/dist/child-BQc3arf7.js.map +0 -1
- package/dist/files-KxzOxckl.js.map +0 -1
- package/dist/instance-DiKSe7s6.js.map +0 -1
|
@@ -1,7 +1,8 @@
|
|
|
1
|
-
import { C as
|
|
1
|
+
import { C as STAGING_FILES, S as LIVE_DECLARATION, _ as DEV_METHOD, a as nameKey, c as removeTree, d as replaceDirectoryLink, f as samePath, g as DEV_CHANGED_METHOD, h as BUILD_METHOD, i as linkTarget, l as renamePath, m as sealTree, o as pathKey, p as sealPlaced, r as linkDirectory, s as realPath, t as fsyncPath, u as renamePathSync, v as DEV_RELOAD_METHOD, y as DEV_SECRET_HEADER } from "./files-FygSJIzK.js";
|
|
2
|
+
import { a as pathsOf, c as currentUserSid, d as runtimeRoot$1, f as serviceLauncherPath, i as ownedDirectory, l as helperPath, n as WINDOWS, o as runtimeDirFor, p as stopServiceLauncher, r as defaultHome, s as socketPathLimit, t as OS, u as runHelperAsync } from "./directories-mJ1qlVht.js";
|
|
2
3
|
import { builtinModules, createRequire } from "node:module";
|
|
3
4
|
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
|
+
import { basename, delimiter, dirname, extname, join, relative, resolve, sep, win32 } from "node:path";
|
|
5
6
|
import { fileURLToPath } from "node:url";
|
|
6
7
|
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
8
|
import { createHash, createHmac, randomBytes, randomInt, randomUUID } from "node:crypto";
|
|
@@ -9348,6 +9349,36 @@ function writeRaw(socket, refused, extra = {}) {
|
|
|
9348
9349
|
...extra.headers ?? []
|
|
9349
9350
|
];
|
|
9350
9351
|
socket.end(`${headers.join("\r\n")}\r\n\r\n${body}`);
|
|
9352
|
+
lingerAfterRefusal(socket);
|
|
9353
|
+
}
|
|
9354
|
+
/** Connections already answered with a refusal: a later parse error on them changes nothing. */
|
|
9355
|
+
const refusedSockets = /* @__PURE__ */ new WeakSet();
|
|
9356
|
+
/** How long a refused connection is read before it is closed regardless. */
|
|
9357
|
+
const LINGER_MS = 5e3;
|
|
9358
|
+
/** How much of a refused request is read and dropped before the connection is closed. */
|
|
9359
|
+
const LINGER_BYTES = 16777216;
|
|
9360
|
+
/**
|
|
9361
|
+
* Reads and drops what the client is still sending after its refusal, until it closes the
|
|
9362
|
+
* connection, for at most {@link LINGER_MS} and {@link LINGER_BYTES}. A socket closed with unread
|
|
9363
|
+
* bytes is reset, and a reset can reach the client before it read the answer, which it then never
|
|
9364
|
+
* sees: on Windows a browser sending a megabyte of cookies got a reset instead of the page that
|
|
9365
|
+
* clears them (WP-W2). The answer is already written; this only keeps the connection open long
|
|
9366
|
+
* enough for it to be read, as HTTP servers do for a "lingering close".
|
|
9367
|
+
*/
|
|
9368
|
+
function lingerAfterRefusal(socket) {
|
|
9369
|
+
refusedSockets.add(socket);
|
|
9370
|
+
socket.removeAllListeners("data");
|
|
9371
|
+
socket.once("end", () => socket.destroy());
|
|
9372
|
+
let read = 0;
|
|
9373
|
+
const timer = setTimeout(() => socket.destroy(), LINGER_MS);
|
|
9374
|
+
timer.unref();
|
|
9375
|
+
socket.once("close", () => clearTimeout(timer));
|
|
9376
|
+
socket.on("error", () => socket.destroy());
|
|
9377
|
+
socket.on("data", (chunk) => {
|
|
9378
|
+
read += chunk.length;
|
|
9379
|
+
if (read > LINGER_BYTES) socket.destroy();
|
|
9380
|
+
});
|
|
9381
|
+
socket.resume();
|
|
9351
9382
|
}
|
|
9352
9383
|
/**
|
|
9353
9384
|
* The answer to headers past {@link MAX_HEADER_SIZE}: a page that says what happened and clears
|
|
@@ -9414,6 +9445,7 @@ function createListener(options) {
|
|
|
9414
9445
|
listener(incoming, outgoing);
|
|
9415
9446
|
});
|
|
9416
9447
|
server.on("clientError", (error, socket) => {
|
|
9448
|
+
if (refusedSockets.has(socket)) return;
|
|
9417
9449
|
if (!socket.writable) {
|
|
9418
9450
|
socket.destroy();
|
|
9419
9451
|
return;
|
|
@@ -11127,6 +11159,16 @@ const PINGS_MISSED_BEFORE_STOP = 3;
|
|
|
11127
11159
|
* to count as running out of memory rather than hanging.
|
|
11128
11160
|
*/
|
|
11129
11161
|
const OOM_STALL_FRACTION = .8;
|
|
11162
|
+
/**
|
|
11163
|
+
* An exit code as people look it up: a Windows status (`0xC0000005`, an access violation) in
|
|
11164
|
+
* hexadecimal, any other code as a number. Node.js reports a Windows status as an unsigned
|
|
11165
|
+
* 32-bit number; on POSIX codes are below 256.
|
|
11166
|
+
*/
|
|
11167
|
+
function exitCodeText(code) {
|
|
11168
|
+
if (code === null) return "?";
|
|
11169
|
+
if (code >= 2147483648 || code < 0) return `0x${(code >>> 0).toString(16).toUpperCase().padStart(8, "0")}`;
|
|
11170
|
+
return String(code);
|
|
11171
|
+
}
|
|
11130
11172
|
function crashed(message) {
|
|
11131
11173
|
return new RpcError(createDiagnostic("MOSTRA_RUNTIME_WORKER_CRASHED", { message }));
|
|
11132
11174
|
}
|
|
@@ -11185,7 +11227,7 @@ function createWorkerPool(options) {
|
|
|
11185
11227
|
}
|
|
11186
11228
|
const lines = exit.stderrTail.filter((line) => line.trim() !== "" && !/^Node\.js v\d/.test(line.trim()));
|
|
11187
11229
|
const last = lines.findLast((line) => /^[A-Za-z_$][\w$.]*(?:Error|Exception)\b.*:/.test(line.trim())) ?? lines.findLast((line) => !/^\s+at\s/.test(line)) ?? lines.at(-1);
|
|
11188
|
-
const how = exit.signal !== null ? `it was ended by ${exit.signal}` : `it exited with code ${exit.code
|
|
11230
|
+
const how = exit.signal !== null ? `it was ended by ${exit.signal}` : `it exited with code ${exitCodeText(exit.code)}`;
|
|
11189
11231
|
return {
|
|
11190
11232
|
kind: "crash",
|
|
11191
11233
|
cause: last ? `${how}: ${last.slice(0, 300)}` : how
|
|
@@ -14158,10 +14200,7 @@ async function recoverDev(home, log) {
|
|
|
14158
14200
|
} catch {
|
|
14159
14201
|
return;
|
|
14160
14202
|
}
|
|
14161
|
-
for (const name of left) await
|
|
14162
|
-
recursive: true,
|
|
14163
|
-
force: true
|
|
14164
|
-
});
|
|
14203
|
+
for (const name of left) await removeTree(join(devRoot(home), name));
|
|
14165
14204
|
if (left.length > 0) log.info("dev.sessions_removed", { count: left.length });
|
|
14166
14205
|
}
|
|
14167
14206
|
const LOOPBACK = /* @__PURE__ */ new Set([
|
|
@@ -14214,13 +14253,23 @@ function createDev(options) {
|
|
|
14214
14253
|
let manifestKey = "";
|
|
14215
14254
|
let artifactId = "";
|
|
14216
14255
|
const mirrored = /* @__PURE__ */ new Map();
|
|
14217
|
-
/**
|
|
14256
|
+
/** When each mirrored file was first missed: a save that moves the old file aside first. */
|
|
14257
|
+
const missing = /* @__PURE__ */ new Map();
|
|
14258
|
+
/**
|
|
14259
|
+
* Copies changed files into the mirror and removes deleted ones; what changed. Editors save
|
|
14260
|
+
* in several ways (in place, a temporary file renamed over the old one, the old one renamed
|
|
14261
|
+
* to a backup first), and on Windows an editor may hold a file it is writing so that nothing
|
|
14262
|
+
* else can read it: a file that can't be read now is left for the next sync, never recorded,
|
|
14263
|
+
* and a file is removed from the mirror only once it has been missing for
|
|
14264
|
+
* {@link MISSING_GRACE_MS}, so a save never looks like a deletion (WP-W2).
|
|
14265
|
+
*/
|
|
14218
14266
|
const sync = async () => {
|
|
14219
14267
|
const files = await listSource(source);
|
|
14220
14268
|
const changed = [];
|
|
14221
14269
|
const seen = /* @__PURE__ */ new Set();
|
|
14222
14270
|
for (const file of files) {
|
|
14223
14271
|
seen.add(file.path);
|
|
14272
|
+
missing.delete(file.path);
|
|
14224
14273
|
let info;
|
|
14225
14274
|
try {
|
|
14226
14275
|
info = await stat(file.absolute);
|
|
@@ -14231,16 +14280,30 @@ function createDev(options) {
|
|
|
14231
14280
|
const before = mirrored.get(file.path);
|
|
14232
14281
|
if (before === key) continue;
|
|
14233
14282
|
const target = join(root, "source", ...file.path.split("/"));
|
|
14234
|
-
|
|
14235
|
-
|
|
14283
|
+
try {
|
|
14284
|
+
await mkdir(dirname(target), { recursive: true });
|
|
14285
|
+
await copyFile(file.absolute, target);
|
|
14286
|
+
} catch (error) {
|
|
14287
|
+
log.info("dev.sync_deferred", {
|
|
14288
|
+
sessionId,
|
|
14289
|
+
file: file.path,
|
|
14290
|
+
error
|
|
14291
|
+
});
|
|
14292
|
+
continue;
|
|
14293
|
+
}
|
|
14236
14294
|
mirrored.set(file.path, key);
|
|
14237
14295
|
changed.push({
|
|
14238
14296
|
file: file.path,
|
|
14239
14297
|
kind: before === void 0 ? "add" : "change"
|
|
14240
14298
|
});
|
|
14241
14299
|
}
|
|
14300
|
+
const now = Date.now();
|
|
14242
14301
|
for (const path of [...mirrored.keys()]) {
|
|
14243
14302
|
if (seen.has(path)) continue;
|
|
14303
|
+
const since = missing.get(path) ?? now;
|
|
14304
|
+
missing.set(path, since);
|
|
14305
|
+
if (now - since < MISSING_GRACE_MS) continue;
|
|
14306
|
+
missing.delete(path);
|
|
14244
14307
|
mirrored.delete(path);
|
|
14245
14308
|
await unlink(join(root, "source", ...path.split("/"))).catch(() => {});
|
|
14246
14309
|
changed.push({
|
|
@@ -14253,7 +14316,7 @@ function createDev(options) {
|
|
|
14253
14316
|
/** The manifest and identity of the mirrored source. */
|
|
14254
14317
|
const describe = async () => {
|
|
14255
14318
|
const extracted = extractManifest(source.entry, await readFile(join(root, "source", source.entry), "utf8"));
|
|
14256
|
-
const manifest = extracted.manifest ?? { title:
|
|
14319
|
+
const manifest = extracted.manifest ?? { title: defaultTitle(source) };
|
|
14257
14320
|
return {
|
|
14258
14321
|
manifest,
|
|
14259
14322
|
artifactId: manifest.id ?? options.registry.artifactAt(source.bindingPath) ?? stableId(source.bindingPath),
|
|
@@ -14373,10 +14436,7 @@ function createDev(options) {
|
|
|
14373
14436
|
await child?.stop().catch(() => {});
|
|
14374
14437
|
await sandbox?.close().catch(() => {});
|
|
14375
14438
|
locksInUse.delete(sessionId);
|
|
14376
|
-
await
|
|
14377
|
-
recursive: true,
|
|
14378
|
-
force: true
|
|
14379
|
-
});
|
|
14439
|
+
await removeTree(dir);
|
|
14380
14440
|
};
|
|
14381
14441
|
const stop = async () => {
|
|
14382
14442
|
if (closed) return;
|
|
@@ -14481,10 +14541,12 @@ function createDev(options) {
|
|
|
14481
14541
|
}
|
|
14482
14542
|
};
|
|
14483
14543
|
}
|
|
14484
|
-
/**
|
|
14485
|
-
|
|
14486
|
-
|
|
14487
|
-
|
|
14544
|
+
/**
|
|
14545
|
+
* How long a mirrored file must stay missing before `mostra dev` removes it: an editor that moves
|
|
14546
|
+
* the old file aside before writing the new one leaves a gap of milliseconds, a deletion lasts.
|
|
14547
|
+
* The 1 s comparison notices the removal within this and a second more.
|
|
14548
|
+
*/
|
|
14549
|
+
const MISSING_GRACE_MS = 1500;
|
|
14488
14550
|
const CROCKFORD = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
|
|
14489
14551
|
/** A stand-in artifact ID for a source no manifest `id` or binding names: stable per path. */
|
|
14490
14552
|
function stableId(bindingPath) {
|
|
@@ -15361,11 +15423,14 @@ function watchIdle(options) {
|
|
|
15361
15423
|
//#endregion
|
|
15362
15424
|
//#region src/service/unit.ts
|
|
15363
15425
|
/**
|
|
15364
|
-
* The home's login service (D62, D63, RT-08): `mostra daemon install` registers the home's
|
|
15365
|
-
* with the user's service manager, so an artifact answers at any hour, even after a reboot.
|
|
15366
|
-
* launchd agent on macOS, a systemd user unit on Linux
|
|
15367
|
-
* --always-on --home <home>`, which never
|
|
15368
|
-
*
|
|
15426
|
+
* The home's login service (D62, D63, RT-08, RT-11): `mostra daemon install` registers the home's
|
|
15427
|
+
* daemon with the user's service manager, so an artifact answers at any hour, even after a reboot.
|
|
15428
|
+
* A launchd agent on macOS, a systemd user unit on Linux, a Task Scheduler task at the user's logon
|
|
15429
|
+
* on Windows (D151); each runs `mostra-runtime daemon --always-on --home <home>`, which never
|
|
15430
|
+
* exits for lack of work, and restarts it when it ends unexpectedly. On Windows the task runs the
|
|
15431
|
+
* daemon through `mostra-win-service`, a launcher without a console, so no window opens at logon,
|
|
15432
|
+
* which also does the restarting (Task Scheduler's own setting didn't, VERIFIED_FACTS WP-W2). The
|
|
15433
|
+
* definition carries no secret: the daemon reads them from the home (D44).
|
|
15369
15434
|
*/
|
|
15370
15435
|
function failed(message) {
|
|
15371
15436
|
return new RpcError(createDiagnostic("MOSTRA_ENV_SERVICE_FAILED", { message }));
|
|
@@ -15408,24 +15473,182 @@ function serviceFor(spec) {
|
|
|
15408
15473
|
command
|
|
15409
15474
|
};
|
|
15410
15475
|
}
|
|
15476
|
+
if (platform === "win32") {
|
|
15477
|
+
const file = win32.join(spec.home, "service", "task.xml");
|
|
15478
|
+
return {
|
|
15479
|
+
manager: "task-scheduler",
|
|
15480
|
+
name: `mostra-${hash.toLowerCase()}`,
|
|
15481
|
+
file,
|
|
15482
|
+
installed: existsSync(file),
|
|
15483
|
+
command: [
|
|
15484
|
+
spec.launcher ?? launcherOrName(),
|
|
15485
|
+
"--stop-event",
|
|
15486
|
+
stopEventOf(file) ?? newStopEvent(hash),
|
|
15487
|
+
"--log",
|
|
15488
|
+
win32.join(spec.home, "logs", "service.log"),
|
|
15489
|
+
...windowsServiceVariables(env).flatMap(([name, value]) => ["--env", `${name}=${value}`]),
|
|
15490
|
+
"--",
|
|
15491
|
+
...command
|
|
15492
|
+
]
|
|
15493
|
+
};
|
|
15494
|
+
}
|
|
15411
15495
|
throw new RpcError(createDiagnostic("MOSTRA_PLATFORM_UNSUPPORTED", { message: `Mostra can't install a login service on ${platform}.` }));
|
|
15412
15496
|
}
|
|
15413
15497
|
/**
|
|
15498
|
+
* What a Windows task passes on besides the user's logon environment, which Task Scheduler gives
|
|
15499
|
+
* it: the development switch while Windows needs it (D150 item 7, until WP-W3), the helper a
|
|
15500
|
+
* checkout names, and the locale and time zone, as the POSIX units carry theirs. Nothing secret.
|
|
15501
|
+
*/
|
|
15502
|
+
function windowsServiceVariables(env) {
|
|
15503
|
+
return [
|
|
15504
|
+
"MOSTRA_DEV_WINDOWS",
|
|
15505
|
+
"MOSTRA_WIN_HELPER",
|
|
15506
|
+
"LANG",
|
|
15507
|
+
"TZ"
|
|
15508
|
+
].flatMap((name) => {
|
|
15509
|
+
const value = env[name];
|
|
15510
|
+
return value ? [[name, value]] : [];
|
|
15511
|
+
});
|
|
15512
|
+
}
|
|
15513
|
+
/**
|
|
15514
|
+
* A new name for the event that asks a home's launcher to stop: in `Local\` (the logon session's
|
|
15515
|
+
* namespace, the only one an ordinary user may create names in), with a random part, so nobody who
|
|
15516
|
+
* can't read the task or the home can create it first (Opus review of WP-W2, finding 6).
|
|
15517
|
+
*/
|
|
15518
|
+
const newStopEvent = (hash) => `Local\\mostra-service-${hash.toLowerCase()}-${randomBytes(8).toString("hex")}`;
|
|
15519
|
+
/** The stop event a definition Mostra wrote names, if the file is there. */
|
|
15520
|
+
function stopEventOf(file) {
|
|
15521
|
+
try {
|
|
15522
|
+
const text = readFileSync(file).toString("utf16le");
|
|
15523
|
+
return /--stop-event (Local\\mostra-service-[0-9a-z]+-[0-9a-f]{16})\b/.exec(text)?.[1];
|
|
15524
|
+
} catch {
|
|
15525
|
+
return;
|
|
15526
|
+
}
|
|
15527
|
+
}
|
|
15528
|
+
/** The launcher's path, or its bare name where it isn't installed (a status only reads it). */
|
|
15529
|
+
function launcherOrName() {
|
|
15530
|
+
try {
|
|
15531
|
+
return serviceLauncherPath();
|
|
15532
|
+
} catch {
|
|
15533
|
+
return "mostra-win-service.exe";
|
|
15534
|
+
}
|
|
15535
|
+
}
|
|
15536
|
+
/** One word of a Windows command line, quoted as the Microsoft C runtime parses it. */
|
|
15537
|
+
function windowsArgument(word) {
|
|
15538
|
+
if (word !== "" && !/[\s"]/.test(word)) return word;
|
|
15539
|
+
let out = "\"";
|
|
15540
|
+
let backslashes = 0;
|
|
15541
|
+
for (const char of word) {
|
|
15542
|
+
if (char === "\\") {
|
|
15543
|
+
backslashes += 1;
|
|
15544
|
+
continue;
|
|
15545
|
+
}
|
|
15546
|
+
out += "\\".repeat(char === "\"" ? backslashes * 2 + 1 : backslashes) + char;
|
|
15547
|
+
backslashes = 0;
|
|
15548
|
+
}
|
|
15549
|
+
return `${out}${"\\".repeat(backslashes * 2)}"`;
|
|
15550
|
+
}
|
|
15551
|
+
/** The Task Scheduler definition (schema 1.2) of a home's task. */
|
|
15552
|
+
function taskFile(spec, status) {
|
|
15553
|
+
const user = xml(spec.user ?? currentUserSid());
|
|
15554
|
+
const [program = "", ...args] = status.command;
|
|
15555
|
+
return `<?xml version="1.0" encoding="UTF-16"?>
|
|
15556
|
+
<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
|
|
15557
|
+
<RegistrationInfo>
|
|
15558
|
+
<Description>${xml(`Mostra daemon for ${spec.home}`)}</Description>
|
|
15559
|
+
</RegistrationInfo>
|
|
15560
|
+
<Triggers>
|
|
15561
|
+
<LogonTrigger>
|
|
15562
|
+
<Enabled>true</Enabled>
|
|
15563
|
+
<UserId>${user}</UserId>
|
|
15564
|
+
</LogonTrigger>
|
|
15565
|
+
</Triggers>
|
|
15566
|
+
<Principals>
|
|
15567
|
+
<Principal id="Author">
|
|
15568
|
+
<UserId>${user}</UserId>
|
|
15569
|
+
<LogonType>InteractiveToken</LogonType>
|
|
15570
|
+
<RunLevel>LeastPrivilege</RunLevel>
|
|
15571
|
+
</Principal>
|
|
15572
|
+
</Principals>
|
|
15573
|
+
<Settings>
|
|
15574
|
+
<MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
|
|
15575
|
+
<DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>
|
|
15576
|
+
<StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>
|
|
15577
|
+
<AllowHardTerminate>true</AllowHardTerminate>
|
|
15578
|
+
<StartWhenAvailable>false</StartWhenAvailable>
|
|
15579
|
+
<RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>
|
|
15580
|
+
<IdleSettings>
|
|
15581
|
+
<StopOnIdleEnd>false</StopOnIdleEnd>
|
|
15582
|
+
<RestartOnIdle>false</RestartOnIdle>
|
|
15583
|
+
</IdleSettings>
|
|
15584
|
+
<AllowStartOnDemand>true</AllowStartOnDemand>
|
|
15585
|
+
<Enabled>true</Enabled>
|
|
15586
|
+
<Hidden>false</Hidden>
|
|
15587
|
+
<RunOnlyIfIdle>false</RunOnlyIfIdle>
|
|
15588
|
+
<WakeToRun>false</WakeToRun>
|
|
15589
|
+
<ExecutionTimeLimit>PT0S</ExecutionTimeLimit>
|
|
15590
|
+
<Priority>5</Priority>
|
|
15591
|
+
</Settings>
|
|
15592
|
+
<Actions Context="Author">
|
|
15593
|
+
<Exec>
|
|
15594
|
+
<Command>${xml(program)}</Command>
|
|
15595
|
+
<Arguments>${xml(args.map(windowsArgument).join(" "))}</Arguments>
|
|
15596
|
+
</Exec>
|
|
15597
|
+
</Actions>
|
|
15598
|
+
</Task>
|
|
15599
|
+
`;
|
|
15600
|
+
}
|
|
15601
|
+
/**
|
|
15414
15602
|
* Whether `home` has a login service installed: its daemon then never exits for lack of work,
|
|
15415
15603
|
* whoever started it, so a daemon started by hand before `install` keeps the artifacts answering.
|
|
15416
15604
|
*/
|
|
15417
15605
|
function hasLoginService(home, env = process.env) {
|
|
15418
15606
|
try {
|
|
15419
|
-
|
|
15607
|
+
const status = serviceFor({
|
|
15420
15608
|
home,
|
|
15421
15609
|
node: "",
|
|
15422
15610
|
entry: "",
|
|
15423
15611
|
env
|
|
15424
|
-
})
|
|
15612
|
+
});
|
|
15613
|
+
if (!status.installed) return false;
|
|
15614
|
+
return status.manager !== "task-scheduler" || registeredLately(status);
|
|
15425
15615
|
} catch {
|
|
15426
15616
|
return false;
|
|
15427
15617
|
}
|
|
15428
15618
|
}
|
|
15619
|
+
/** What the idle check last learnt of each task: whether Task Scheduler holds it, and when. */
|
|
15620
|
+
const registrations = /* @__PURE__ */ new Map();
|
|
15621
|
+
/**
|
|
15622
|
+
* Whether Task Scheduler held the task when last asked, asking again in the background at most
|
|
15623
|
+
* once a minute: the idle check runs every few seconds and must never wait for `schtasks`. A task
|
|
15624
|
+
* removed in Task Scheduler's own window then stops counting, so a daemon started by hand exits
|
|
15625
|
+
* when idle again (Opus review of WP-W2, finding 5). Until the first answer, the definition in the
|
|
15626
|
+
* home counts.
|
|
15627
|
+
*/
|
|
15628
|
+
function registeredLately(status) {
|
|
15629
|
+
const interval = Number(process.env["MOSTRA_TEST_SERVICE_QUERY_MS"]) || 6e4;
|
|
15630
|
+
const entry = registrations.get(status.name) ?? {
|
|
15631
|
+
at: Number.NEGATIVE_INFINITY,
|
|
15632
|
+
asking: false
|
|
15633
|
+
};
|
|
15634
|
+
registrations.set(status.name, entry);
|
|
15635
|
+
if (!entry.asking && Date.now() - entry.at >= interval) {
|
|
15636
|
+
entry.asking = true;
|
|
15637
|
+
execFile("schtasks", [
|
|
15638
|
+
"/Query",
|
|
15639
|
+
"/TN",
|
|
15640
|
+
status.name
|
|
15641
|
+
], {
|
|
15642
|
+
timeout: 3e4,
|
|
15643
|
+
windowsHide: true
|
|
15644
|
+
}, (error) => {
|
|
15645
|
+
entry.registered = error === null;
|
|
15646
|
+
entry.at = Date.now();
|
|
15647
|
+
entry.asking = false;
|
|
15648
|
+
});
|
|
15649
|
+
}
|
|
15650
|
+
return entry.registered ?? true;
|
|
15651
|
+
}
|
|
15429
15652
|
const xml = (text) => text.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
|
|
15430
15653
|
/** systemd's quoting for one `ExecStart` word. */
|
|
15431
15654
|
const systemdWord = (word) => /^[A-Za-z0-9_./:@=+-]+$/.test(word) ? word : `"${word.replace(/\\/g, "\\\\").replace(/"/g, "\\\"").replace(/\n/g, "\\n").replace(/%/g, "%%").replace(/\$/g, "$$$$")}"`;
|
|
@@ -15447,6 +15670,7 @@ function serviceEnvironment(env) {
|
|
|
15447
15670
|
}
|
|
15448
15671
|
/** The text of the service's file. */
|
|
15449
15672
|
function serviceFile(spec, status) {
|
|
15673
|
+
if (status.manager === "task-scheduler") return taskFile(spec, status);
|
|
15450
15674
|
const env = serviceEnvironment(spec.env ?? process.env);
|
|
15451
15675
|
const log = join(spec.home, "logs", "service.log");
|
|
15452
15676
|
if (status.manager === "launchd") {
|
|
@@ -15516,29 +15740,60 @@ function run(command, args) {
|
|
|
15516
15740
|
}
|
|
15517
15741
|
}
|
|
15518
15742
|
const uid = () => process.getuid?.() ?? 0;
|
|
15743
|
+
/** The definition's bytes: Task Scheduler reads UTF-16 with its byte order mark. */
|
|
15744
|
+
function encoded(status, text) {
|
|
15745
|
+
return status.manager === "task-scheduler" ? Buffer.from(`\ufeff${text}`, "utf16le") : text;
|
|
15746
|
+
}
|
|
15747
|
+
/** The definition as written, decoded as {@link encoded} wrote it. */
|
|
15748
|
+
function readDefinition(status) {
|
|
15749
|
+
const bytes = readFileSync(status.file);
|
|
15750
|
+
if (status.manager !== "task-scheduler") return bytes.toString("utf8");
|
|
15751
|
+
return bytes.toString("utf16le").replace(/^\ufeff/, "");
|
|
15752
|
+
}
|
|
15519
15753
|
/** Installs the home's daemon as a login service and starts it, replacing an earlier one. */
|
|
15520
|
-
function installService(spec, options = {}) {
|
|
15521
|
-
const status = serviceFor(spec)
|
|
15754
|
+
async function installService(spec, options = {}) {
|
|
15755
|
+
const status = serviceFor((spec.platform ?? OS) === "win32" && spec.launcher === void 0 ? {
|
|
15756
|
+
...spec,
|
|
15757
|
+
launcher: serviceLauncherPath()
|
|
15758
|
+
} : spec);
|
|
15522
15759
|
const text = serviceFile(spec, status);
|
|
15760
|
+
const registering = status.manager === "task-scheduler" && !options.noStart;
|
|
15761
|
+
const written = registering ? `${status.file}.new` : status.file;
|
|
15523
15762
|
try {
|
|
15524
15763
|
mkdirSync(dirname(status.file), { recursive: true });
|
|
15525
15764
|
mkdirSync(join(spec.home, "logs"), {
|
|
15526
15765
|
recursive: true,
|
|
15527
15766
|
mode: 448
|
|
15528
15767
|
});
|
|
15529
|
-
if (status.installed && !options.noStart) stopService(status);
|
|
15530
|
-
writeFileSync(status
|
|
15768
|
+
if (status.installed && !options.noStart) await stopService(status, spec.home, options);
|
|
15769
|
+
writeFileSync(written, encoded(status, text), { mode: 420 });
|
|
15531
15770
|
} catch (error) {
|
|
15532
15771
|
if (error instanceof RpcError) throw error;
|
|
15533
15772
|
throw failed(`Writing ${status.file} failed: ${error.message}`);
|
|
15534
15773
|
}
|
|
15774
|
+
if (registering) {
|
|
15775
|
+
try {
|
|
15776
|
+
run("schtasks", [
|
|
15777
|
+
"/Create",
|
|
15778
|
+
"/TN",
|
|
15779
|
+
status.name,
|
|
15780
|
+
"/XML",
|
|
15781
|
+
written,
|
|
15782
|
+
"/F"
|
|
15783
|
+
]);
|
|
15784
|
+
renameSync(written, status.file);
|
|
15785
|
+
} finally {
|
|
15786
|
+
rmSync(written, { force: true });
|
|
15787
|
+
}
|
|
15788
|
+
registrations.delete(status.name);
|
|
15789
|
+
}
|
|
15535
15790
|
if (!options.noStart) {
|
|
15536
15791
|
if (status.manager === "launchd") run("launchctl", [
|
|
15537
15792
|
"bootstrap",
|
|
15538
15793
|
`gui/${uid()}`,
|
|
15539
15794
|
status.file
|
|
15540
15795
|
]);
|
|
15541
|
-
else {
|
|
15796
|
+
else if (status.manager === "systemd") {
|
|
15542
15797
|
run("systemctl", ["--user", "daemon-reload"]);
|
|
15543
15798
|
run("systemctl", [
|
|
15544
15799
|
"--user",
|
|
@@ -15546,29 +15801,104 @@ function installService(spec, options = {}) {
|
|
|
15546
15801
|
"--now",
|
|
15547
15802
|
status.name
|
|
15548
15803
|
]);
|
|
15549
|
-
}
|
|
15804
|
+
} else run("schtasks", [
|
|
15805
|
+
"/Run",
|
|
15806
|
+
"/TN",
|
|
15807
|
+
status.name
|
|
15808
|
+
]);
|
|
15550
15809
|
}
|
|
15551
15810
|
return {
|
|
15552
15811
|
...status,
|
|
15553
15812
|
installed: true
|
|
15554
15813
|
};
|
|
15555
15814
|
}
|
|
15556
|
-
function stopService(status) {
|
|
15815
|
+
async function stopService(status, home, options) {
|
|
15557
15816
|
try {
|
|
15558
15817
|
if (status.manager === "launchd") run("launchctl", ["bootout", `gui/${uid()}/${status.name}`]);
|
|
15559
|
-
else run("systemctl", [
|
|
15818
|
+
else if (status.manager === "systemd") run("systemctl", [
|
|
15560
15819
|
"--user",
|
|
15561
15820
|
"disable",
|
|
15562
15821
|
"--now",
|
|
15563
15822
|
status.name
|
|
15564
15823
|
]);
|
|
15824
|
+
else await stopTask(status, home, options);
|
|
15565
15825
|
} catch {}
|
|
15566
15826
|
}
|
|
15567
|
-
/**
|
|
15568
|
-
|
|
15827
|
+
/**
|
|
15828
|
+
* Stops and deletes a home's task, the daemon first and in order (D87), as launchd's `bootout`
|
|
15829
|
+
* and systemd's `disable --now` send it SIGTERM:
|
|
15830
|
+
* - through the launcher's stop event, when this logon session has it: the launcher gives the
|
|
15831
|
+
* daemon Ctrl+Break, which the runtime handles as `mostra/shutdown`;
|
|
15832
|
+
* - otherwise (the launcher runs in another session, as when the user is logged on at the console
|
|
15833
|
+
* and uninstalls over SSH, or the home lost the definition naming the event) with
|
|
15834
|
+
* `mostra/shutdown` over the home's pipe, which reaches the daemon from any session; its exit
|
|
15835
|
+
* with code 0 ends the launcher (Opus review of WP-W2, finding 4);
|
|
15836
|
+
*
|
|
15837
|
+
* then the task is ended, which ends whatever its job still holds, and deleted.
|
|
15838
|
+
*/
|
|
15839
|
+
async function stopTask(status, home, options) {
|
|
15840
|
+
const event = status.installed ? status.command[status.command.indexOf("--stop-event") + 1] : void 0;
|
|
15841
|
+
let signalled = false;
|
|
15842
|
+
if (event !== void 0 && process.env["MOSTRA_TEST_SERVICE_STOP"] !== "pipe") try {
|
|
15843
|
+
signalled = stopServiceLauncher(event).signalled;
|
|
15844
|
+
} catch {}
|
|
15845
|
+
if (!signalled) await shutDownInstance(home, options.client);
|
|
15846
|
+
try {
|
|
15847
|
+
run("schtasks", [
|
|
15848
|
+
"/End",
|
|
15849
|
+
"/TN",
|
|
15850
|
+
status.name
|
|
15851
|
+
]);
|
|
15852
|
+
} catch {}
|
|
15853
|
+
run("schtasks", [
|
|
15854
|
+
"/Delete",
|
|
15855
|
+
"/TN",
|
|
15856
|
+
status.name,
|
|
15857
|
+
"/F"
|
|
15858
|
+
]);
|
|
15859
|
+
registrations.delete(status.name);
|
|
15860
|
+
}
|
|
15861
|
+
/** Asks the home's running daemon, if any, to stop (`mostra/shutdown`), and waits until it has. */
|
|
15862
|
+
async function shutDownInstance(home, client) {
|
|
15863
|
+
const record = await readLiveInstanceRecord(home);
|
|
15864
|
+
if (record === void 0 || record.mode !== "daemon") return;
|
|
15865
|
+
try {
|
|
15866
|
+
const session = await attach(record.socket, client ?? {
|
|
15867
|
+
name: "mostra-service",
|
|
15868
|
+
version: "0"
|
|
15869
|
+
});
|
|
15870
|
+
await session.client.peer.call(mostraShutdownMethod, {}, { timeoutMs: 1e4 }).catch(() => void 0);
|
|
15871
|
+
session.client.close();
|
|
15872
|
+
} catch {
|
|
15873
|
+
return;
|
|
15874
|
+
}
|
|
15875
|
+
const deadline = Date.now() + 2e4;
|
|
15876
|
+
while (Date.now() < deadline && await isSameProcess(record.pid, record.startTime)) await new Promise((resolve) => setTimeout(resolve, 100));
|
|
15877
|
+
}
|
|
15878
|
+
/** Whether Task Scheduler holds the home's task. */
|
|
15879
|
+
function taskRegistered(status) {
|
|
15880
|
+
try {
|
|
15881
|
+
run("schtasks", [
|
|
15882
|
+
"/Query",
|
|
15883
|
+
"/TN",
|
|
15884
|
+
status.name
|
|
15885
|
+
]);
|
|
15886
|
+
return true;
|
|
15887
|
+
} catch {
|
|
15888
|
+
return false;
|
|
15889
|
+
}
|
|
15890
|
+
}
|
|
15891
|
+
/**
|
|
15892
|
+
* Stops and removes the home's login service; a home without one is left as it is. On Windows a
|
|
15893
|
+
* task Task Scheduler still holds is removed though the home lost its definition (restored from a
|
|
15894
|
+
* backup, removed by hand), or the task would keep starting the daemon at every logon (Opus review
|
|
15895
|
+
* of WP-W2, finding 5).
|
|
15896
|
+
*/
|
|
15897
|
+
async function uninstallService(spec, options = {}) {
|
|
15569
15898
|
const status = serviceFor(spec);
|
|
15570
|
-
|
|
15571
|
-
if (!
|
|
15899
|
+
const orphaned = !status.installed && status.manager === "task-scheduler" && !options.noStart && taskRegistered(status);
|
|
15900
|
+
if (!status.installed && !orphaned) return status;
|
|
15901
|
+
if (!options.noStart) await stopService(status, spec.home, options);
|
|
15572
15902
|
rmSync(status.file, { force: true });
|
|
15573
15903
|
if (!options.noStart && status.manager === "systemd") try {
|
|
15574
15904
|
run("systemctl", ["--user", "daemon-reload"]);
|
|
@@ -15578,17 +15908,22 @@ function uninstallService(spec, options = {}) {
|
|
|
15578
15908
|
installed: false
|
|
15579
15909
|
};
|
|
15580
15910
|
}
|
|
15581
|
-
/**
|
|
15911
|
+
/**
|
|
15912
|
+
* Whether the home has a login service whose file runs this home's daemon (`mostra doctor`); on
|
|
15913
|
+
* Windows also whether Task Scheduler holds its task (`registered`).
|
|
15914
|
+
*/
|
|
15582
15915
|
function serviceStatus(spec) {
|
|
15583
15916
|
const status = serviceFor(spec);
|
|
15917
|
+
const registered = status.manager === "task-scheduler" ? { registered: taskRegistered(status) } : {};
|
|
15584
15918
|
if (!status.installed) return {
|
|
15585
15919
|
...status,
|
|
15586
|
-
current: false
|
|
15920
|
+
current: false,
|
|
15921
|
+
...registered
|
|
15587
15922
|
};
|
|
15588
|
-
const text = readFileSync(status.file, "utf8");
|
|
15589
15923
|
return {
|
|
15590
15924
|
...status,
|
|
15591
|
-
current:
|
|
15925
|
+
current: readDefinition(status) === serviceFile(spec, status),
|
|
15926
|
+
...registered
|
|
15592
15927
|
};
|
|
15593
15928
|
}
|
|
15594
15929
|
//#endregion
|
|
@@ -15683,7 +16018,7 @@ async function startInstance(options) {
|
|
|
15683
16018
|
}
|
|
15684
16019
|
function sameHome(home, path) {
|
|
15685
16020
|
try {
|
|
15686
|
-
return
|
|
16021
|
+
return realPath(path) === home;
|
|
15687
16022
|
} catch {
|
|
15688
16023
|
return resolve(path) === home;
|
|
15689
16024
|
}
|
|
@@ -16328,4 +16663,4 @@ function sourceDirectory(path) {
|
|
|
16328
16663
|
//#endregion
|
|
16329
16664
|
export { uninstallService as a, serviceStatus as i, startInstance as n, checkPlatform as o, installService as r, resolveHomePath as s, runtimeVersion as t };
|
|
16330
16665
|
|
|
16331
|
-
//# sourceMappingURL=instance-
|
|
16666
|
+
//# sourceMappingURL=instance-DxcGEQj_.js.map
|