@mark1russell7/service 0.8.12 → 0.8.14
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/build/grpc.js +1 -1
- package/build/host.js +3 -3
- package/build/host.js.map +1 -1
- package/build/http-client.js +1 -1
- package/build/index.js +1 -1
- package/build/{machine-mIW1qgEE.js → machine-BhVeHr_m.js} +2 -2
- package/build/{machine-mIW1qgEE.js.map → machine-BhVeHr_m.js.map} +1 -1
- package/build/mongodb.js +1 -1
- package/build/pg.js +1 -1
- package/build/rabbitmq.js +1 -1
- package/build/redis.js +1 -1
- package/build/{retrier-BObZq10-.js → retrier-Dnjhvxol.js} +8 -13
- package/build/retrier-Dnjhvxol.js.map +1 -0
- package/build/testing.js +5 -5
- package/build/testing.js.map +1 -1
- package/build/websocket.js +1 -1
- package/package.json +4 -4
- package/build/retrier-BObZq10-.js.map +0 -1
package/build/host.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"host.js","names":["NAME","xmlText","record","ms","isTimeAtLeast","spawnChild"],"sources":["../src/host/ports.ts","../src/host/render.ts","../src/host/processes.ts","../src/host/lock.ts","../src/host/discovery.ts","../src/host/install.ts","../src/host/probes.ts","../src/host/watch.ts","../src/host/env.ts","../src/host/logs.ts","../src/host/group.ts","../src/host/node.ts"],"sourcesContent":["import type { Clock } from \"../clock.ts\";\nimport type { Logger } from \"../logger.ts\";\n\n/** These options go with one command: the folder that it runs in, and the most time that it can take. */\nexport interface CommandOptions {\n readonly cwd?: string | undefined;\n /** This time is the most that the command can take, in milliseconds. After it, the command stops, and its code is 124. */\n readonly timeout?: number | undefined;\n}\n\n/** A command result is the exit code of a command and the text that it wrote to its output and its error output. */\nexport interface CommandResult {\n /** This code is the exit code. A program that is not found gives 127, and a command at its timeout gives 124. */\n readonly code: number;\n readonly out: string;\n}\n\n/**\n * A command port starts a program with a list of arguments and gives its result. It does not use a\n * shell, thus no argument needs a quote. The host uses it for `schtasks`, `systemctl` and `taskkill`.\n */\nexport interface CommandPort {\n run(file: string, args: readonly string[], options?: CommandOptions): Promise<CommandResult>;\n}\n\n/** A file port is the part of a file system that the host uses. Each path is a full path. */\nexport interface FilePort {\n /** This method gives the text of a file in UTF-8, or null when the file does not exist. */\n read(path: string): Promise<string | null>;\n /** This method writes a file. It makes the folders of the path, and it replaces the file in one step. */\n write(path: string, data: string | Uint8Array): Promise<void>;\n /** This method makes a file only when no file has the path, and tells if it made it. It makes the folders of the path. */\n create(path: string, data: string): Promise<boolean>;\n /** This method adds data at the end of a file. It makes the file and its folders when they do not exist. */\n append(path: string, data: string | Uint8Array): Promise<void>;\n /** This method gives the size of a file in bytes, or null when the file does not exist. */\n size(path: string): Promise<number | null>;\n /** This method gives a file a new path. It replaces a file at the new path. */\n rename(from: string, to: string): Promise<void>;\n /** This method removes a file. A file that does not exist is not an error. */\n remove(path: string): Promise<void>;\n}\n\n/** These are the signals that the host sends to a process. */\nexport type StopSignal = \"SIGINT\" | \"SIGTERM\" | \"SIGKILL\";\n\n/** A spawn request tells the program that a child process runs, with its arguments, its folder and its environment. */\nexport interface SpawnRequest {\n readonly program: string;\n readonly args: readonly string[];\n readonly cwd?: string | undefined;\n readonly env: Readonly<Record<string, string>>;\n /** True gives the child an IPC channel. Only a child that is a Node program can use it. */\n readonly ipc: boolean;\n}\n\n/** A child handle is a child process that the host started. */\nexport interface ChildHandle {\n /** This number is the process ID, or null when the program did not start. */\n readonly pid: number | null;\n /** This flag tells if the child has an IPC channel. */\n readonly ipc: boolean;\n /** This method adds a handler for each part of the output and of the error output of the child. */\n onOutput(handler: (stream: \"stdout\" | \"stderr\", chunk: string | Uint8Array) => void): void;\n /**\n * This method adds a handler for the end of the child. The handler gets the exit code, or null after\n * a signal, and the signal. A program that did not start also ends, with a null code.\n */\n onExit(handler: (code: number | null, signal: string | null) => void): void;\n /** This method sends a message on the IPC channel, and tells if it went. */\n send(message: unknown): boolean;\n}\n\n/**\n * A process port is the part of the processes of the system that the host uses. It finds if a\n * process is alive, it gives its start time, it sends signals and it starts a child.\n */\nexport interface ProcessesPort {\n /** This method tells if a process with this ID is alive. A process of a different user is alive too. */\n alive(pid: number): boolean;\n /** This method gives the start time of a process, in milliseconds after the epoch, or null when the system does not tell. */\n startOf(pid: number): Promise<number | null>;\n /** This method sends a signal to one process, and tells if the signal went. */\n signal(pid: number, signal: StopSignal): boolean;\n /** This method sends a signal to the process group whose leader is `pid`, and tells if the signal went. Windows has no process groups. */\n signalGroup(pid: number, signal: StopSignal): boolean;\n /** This method starts a child process. On Linux, the child leads a new process group. */\n spawn(request: SpawnRequest): ChildHandle;\n}\n\n/** An HTTP answer is the status and the text of an answer. `complete` is false when the text stopped at the limit. */\nexport interface HttpAnswer {\n readonly status: number;\n readonly body: string;\n readonly complete: boolean;\n}\n\n/** A net port does the network part of a readiness probe. */\nexport interface NetPort {\n /** This method sends a GET request, and gives the status of the answer, or null when no answer came in the timeout. */\n httpStatus(url: string, timeout: number): Promise<number | null>;\n /**\n * This method sends a GET request, and gives the status and up to `limit` bytes of the text. It gives\n * null when the answer did not end in the timeout. A probe with freshness bounds uses it. It is optional\n * for the net ports that callers wrote before it. `nodeHostPorts` and `fakeHost` have it.\n */\n httpText?(url: string, timeout: number, limit: number): Promise<HttpAnswer | null>;\n /** This method tells if a TCP connection to the host and the port opens in the timeout, in milliseconds. */\n tcpConnect(host: string, port: number, timeout: number): Promise<boolean>;\n}\n\n/** This record names a process: its ID and its start time, in milliseconds after the epoch. */\nexport interface ProcessMark {\n readonly pid: number;\n readonly startedAt: number;\n}\n\n/**\n * The host ports are each effect of the system that the host uses. A test gives fakes (`fakeHost` of\n * `./testing`), thus a test installs no task and starts no process. `nodeHostPorts()` gives the ports of Node.\n */\nexport interface HostPorts {\n /** This text is the platform, as `process.platform` gives it, for example `win32` or `linux`. */\n readonly platform: string;\n readonly commands: CommandPort;\n readonly files: FilePort;\n readonly processes: ProcessesPort;\n readonly net: NetPort;\n /** This clock gives the monotonic time and the timers. */\n readonly clock: Clock;\n /** This function gives the wall time, in milliseconds after the epoch. */\n readonly wall: () => number;\n /** This record names the process of the host itself. */\n readonly self: ProcessMark;\n /** These are the environment variables of the host. */\n readonly env: Readonly<Record<string, string | undefined>>;\n /** This text is the home folder of the user. */\n readonly homeDir: string;\n /** This function gives the user that a Windows task runs as, for example `HOST\\name`. */\n readonly user: () => string;\n /** This logger gets the log entries of the host. Without it, the host writes no log. */\n readonly logger?: Logger | undefined;\n}\n\n/** This function joins the parts of a path with the separator of the platform. */\nexport const joinPath = (platform: string, ...parts: readonly string[]): string => {\n const separator = platform === \"win32\" ? \"\\\\\" : \"/\";\n // a scan and not a regular expression, thus a long run of separators takes linear time\n const isSeparator = (char: string | undefined): boolean => char === \"/\" || char === \"\\\\\";\n const trim = (part: string, head: boolean): string => {\n let start = 0;\n let end = part.length;\n while (head && start < end && isSeparator(part[start])) start += 1;\n while (end > start && isSeparator(part[end - 1])) end -= 1;\n return part.slice(start, end);\n };\n const trimmed = parts.map((part, at) => trim(part, at !== 0));\n return trimmed.filter((part, at) => at === 0 || part !== \"\").join(separator);\n};\n","import type { Quantity } from \"@mark1russell7/quantity\";\nimport { convertible, isQuantity, valueIn } from \"@mark1russell7/quantity\";\nimport { escapeAttribute as xmlText } from \"@mark1russell7/text\";\n\n/**\n * A service start tells when the system starts the program.\n * - `logon`: at the logon of the user. The program runs until it stops.\n * - `boot`: at the start of the computer, before a logon. The program runs until it stops. It runs in the background.\n * - `{ daily: \"HH:MM\" }`: each day at that local time, as a job that runs to its end.\n */\nexport type ServiceStart = \"logon\" | \"boot\" | { readonly daily: string };\n\n/** A restart policy tells how long the system waits before it starts a program again after it stops. */\nexport interface RestartPolicy {\n /** This time is the wait before the next start. On Windows, the task starts again at whole minutes, 1 minute or more. */\n readonly after: Quantity;\n}\n\n/** A service spec tells which program the system runs as a user service, and when. */\nexport interface ServiceSpec {\n /** This name is the name of the Windows task and of the systemd unit: letters, digits, `.`, `_` and `-`. */\n readonly name: string;\n readonly description: string;\n /** This path is the full path of the program, for example the path of Node. */\n readonly program: string;\n readonly args: readonly string[];\n /** This folder is the working folder of the program. */\n readonly cwd?: string | undefined;\n readonly start: ServiceStart;\n /** This policy starts a program at logon or at boot again after it stops. Null starts it only at its start. A daily job has no restart. */\n readonly restart: RestartPolicy | null;\n /**\n * True runs the program when the user is not logged on. On Windows, the task gets an S4U logon, and Task Scheduler\n * then refuses the task from a shell that is not elevated. On Linux, the install sets the linger of the user\n * (`loginctl enable-linger`), thus the user manager of systemd starts at boot and stays after the logout.\n * The default is true for a boot start, and false for the other starts.\n */\n readonly background?: boolean | undefined;\n /** This folder keeps the files of the host, for example the task file of Windows. */\n readonly stateDir: string;\n /** On Windows, `hidden` starts the program through `conhost --headless`, thus no window opens. The default is `hidden`. */\n readonly console?: \"hidden\" | \"visible\" | undefined;\n /** This time is the most that one run can take. The default is no limit. */\n readonly timeLimit?: Quantity | undefined;\n}\n\n/** These are the parts of the task of Windows that come from the system, not from the spec. */\nexport interface TaskContext {\n /** This text is the user of the task, for example `HOST\\name`. */\n readonly user: string;\n /** This path is the path of `conhost.exe`, for a hidden console. */\n readonly conhost: string;\n}\n\nconst NAME = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;\nconst DAILY = /^([01]\\d|2[0-3]):([0-5]\\d)$/;\n/** This function tells if a text has a control character. Such a character can add a line to a unit, or break the task file. */\nconst hasControl = (text: string): boolean => {\n for (let at = 0; at < text.length; at += 1) {\n const code = text.charCodeAt(at);\n if (code < 0x20 || code === 0x7f) return true;\n }\n return false;\n};\n\n/** This function gives the time of a daily start, or null when the text is not `HH:MM`. */\nexport const dailyTime = (text: string): { readonly hour: string; readonly minute: string } | null => {\n const found = DAILY.exec(text);\n return found === null ? null : { hour: found[1]!, minute: found[2]! };\n};\n\n/** This function tells if the program of a spec runs until it stops: a start at logon or at boot, not a daily job. */\nexport const runsUntilStop = (start: ServiceStart): start is \"logon\" | \"boot\" => start === \"logon\" || start === \"boot\";\n\n/** This function tells if a spec runs when the user is not logged on: its `background`, or true for a boot start. */\nexport const inBackground = (spec: ServiceSpec): boolean => spec.background ?? spec.start === \"boot\";\n\n/** This function tells if a value is a time: a quantity in a unit of time. */\nexport const isTime = (value: unknown): value is Quantity => isQuantity(value) && convertible(value.unit, \"ms\");\n\n/** This function gives the problems of a service spec: each value that the task or the unit cannot use. */\nexport const serviceProblems = (spec: ServiceSpec): string[] => {\n const problems: string[] = [];\n if (!NAME.test(spec.name)) problems.push(`the name ${JSON.stringify(spec.name)} is not letters, digits, \".\", \"_\" and \"-\"`);\n const fields: Array<[string, string]> = [\n [\"description\", spec.description],\n [\"program\", spec.program],\n [\"stateDir\", spec.stateDir],\n ...spec.args.map((arg, at): [string, string] => [`argument ${at}`, arg]),\n ...(spec.cwd === undefined ? [] : [[\"cwd\", spec.cwd] as [string, string]]),\n ];\n for (const [field, value] of fields) if (hasControl(value)) problems.push(`the ${field} has a control character`);\n if (spec.program === \"\") problems.push(\"the program is empty\");\n if (spec.stateDir === \"\") problems.push(\"the stateDir is empty\");\n if (!runsUntilStop(spec.start) && dailyTime(spec.start.daily) === null)\n problems.push(`the daily start ${JSON.stringify(spec.start.daily)} is not a time HH:MM`);\n if (!runsUntilStop(spec.start) && spec.restart !== null) problems.push(\"a daily job has no restart: give null\");\n if (spec.background !== undefined && typeof spec.background !== \"boolean\") problems.push(\"the background is not true or false\");\n if (spec.start === \"boot\" && spec.background === false) problems.push(\"a boot start runs before a logon: give background true, or leave it out\");\n if (inBackground(spec) && spec.console === \"visible\") problems.push(\"a program in the background has no desktop: give the console hidden, or leave it out\");\n if (spec.restart !== null && !(isTime(spec.restart.after) && valueIn(spec.restart.after, \"ms\") >= 0))\n problems.push(\"the restart wait is not a time of zero or more\");\n if (spec.timeLimit !== undefined && !(isTime(spec.timeLimit) && valueIn(spec.timeLimit, \"ms\") > 0))\n problems.push(\"the time limit is not a time above zero\");\n if (spec.console !== undefined && spec.console !== \"hidden\" && spec.console !== \"visible\")\n problems.push(`the console ${JSON.stringify(spec.console)} is not \"hidden\" or \"visible\"`);\n return problems;\n};\n\n/**\n * This function quotes one argument for a command line of Windows, by the rules of `CommandLineToArgvW`.\n * It doubles each backslash before a quote and at the end. One pass keeps the time linear.\n */\nexport const windowsArg = (arg: string): string => {\n if (arg !== \"\" && !/[\\s\"]/.test(arg)) return arg;\n let quoted = '\"';\n let slashes = 0;\n for (const char of arg) {\n if (char === \"\\\\\") {\n slashes += 1;\n continue;\n }\n quoted += char === '\"' ? `${\"\\\\\".repeat(slashes * 2 + 1)}\"` : `${\"\\\\\".repeat(slashes)}${char}`;\n slashes = 0;\n }\n return `${quoted}${\"\\\\\".repeat(slashes * 2)}\"`;\n};\n\n/**\n * This function quotes one argument for the `ExecStart` line of a systemd unit. It writes `%` as\n * `%%` and `$` as `$$`, thus systemd expands no specifier and no variable. An argument with a space,\n * a quote, a backslash or a `;` goes in double quotes.\n */\nexport const systemdArg = (arg: string): string => {\n const escaped = arg.replace(/%/g, () => \"%%\").replace(/\\$/g, () => \"$$\");\n if (escaped !== \"\" && !/[\\s\"'\\\\;]/.test(escaped)) return escaped;\n return `\"${escaped.replace(/\\\\/g, () => \"\\\\\\\\\").replace(/\"/g, () => '\\\\\"')}\"`;\n};\n\n/** This function gives a time as an ISO 8601 duration of Task Scheduler in whole seconds, for example `PT90S`. */\nconst isoSeconds = (time: Quantity): string => `PT${Math.max(1, Math.ceil(valueIn(time, \"s\")))}S`;\n\n/** This function gives the interval of the repeat trigger of a task: whole minutes, 1 minute or more. */\nconst repeatMinutes = (time: Quantity): number => Math.max(1, Math.ceil(valueIn(time, \"min\")));\n\n/** This function gives the seconds of a restart wait for systemd, a whole number. */\nconst restartSeconds = (time: Quantity): number => Math.max(0, Math.ceil(valueIn(time, \"s\")));\n\nconst refuse = (spec: ServiceSpec): void => {\n const problems = serviceProblems(spec);\n if (problems.length > 0) throw new Error(`the service spec has problems: ${problems.join(\"; \")}`);\n};\n\n/**\n * This function gives the task file of Windows for a spec, as text. It is a pure function: the same\n * spec and context give the same text. Each start boundary is in the past, thus the task does not wait for a date.\n * - A start at logon gets a logon trigger, and a start at boot gets a boot trigger. With a restart, a time trigger\n * also starts the task each few minutes. The task ignores a start while its program runs (`IgnoreNew`).\n * - A daily start gets a calendar trigger at its time. A start that the computer missed occurs when it can (`StartWhenAvailable`).\n * - A spec in the background gets an S4U logon: the task runs when the user is not logged on, and Windows keeps no password.\n * Otherwise the task runs only in the session of the user (`InteractiveToken`).\n * Task Scheduler reads the file as UTF-16 with a byte order mark: give the text to `utf16le`.\n */\nexport const renderTaskXml = (spec: ServiceSpec, context: TaskContext): string => {\n refuse(spec);\n const user = xmlText(context.user);\n const hidden = (spec.console ?? \"hidden\") === \"hidden\";\n const command = hidden ? context.conhost : spec.program;\n const args = (hidden ? [\"--headless\", spec.program, ...spec.args] : [...spec.args]).map(windowsArg).join(\" \");\n const triggers: string[] = [];\n if (runsUntilStop(spec.start)) {\n triggers.push(\n spec.start === \"logon\"\n ? ` <LogonTrigger>\n <Enabled>true</Enabled>\n <UserId>${user}</UserId>\n </LogonTrigger>`\n : ` <BootTrigger>\n <Enabled>true</Enabled>\n </BootTrigger>`,\n );\n if (spec.restart !== null)\n triggers.push(` <TimeTrigger>\n <Enabled>true</Enabled>\n <StartBoundary>2000-01-01T00:00:00</StartBoundary>\n <Repetition>\n <Interval>PT${repeatMinutes(spec.restart.after)}M</Interval>\n <StopAtDurationEnd>false</StopAtDurationEnd>\n </Repetition>\n </TimeTrigger>`);\n } else {\n const time = dailyTime(spec.start.daily)!;\n triggers.push(` <CalendarTrigger>\n <Enabled>true</Enabled>\n <StartBoundary>2000-01-01T${time.hour}:${time.minute}:00</StartBoundary>\n <ScheduleByDay>\n <DaysInterval>1</DaysInterval>\n </ScheduleByDay>\n </CalendarTrigger>`);\n }\n const cwd = spec.cwd === undefined ? \"\" : `\\n <WorkingDirectory>${xmlText(spec.cwd)}</WorkingDirectory>`;\n const limit = spec.timeLimit === undefined ? \"PT0S\" : isoSeconds(spec.timeLimit);\n return `<?xml version=\"1.0\" encoding=\"UTF-16\"?>\n<Task version=\"1.4\" xmlns=\"http://schemas.microsoft.com/windows/2004/02/mit/task\">\n <RegistrationInfo>\n <Description>${xmlText(spec.description)}</Description>\n <URI>\\\\${xmlText(spec.name)}</URI>\n </RegistrationInfo>\n <Triggers>\n${triggers.join(\"\\n\")}\n </Triggers>\n <Principals>\n <Principal id=\"Author\">\n <UserId>${user}</UserId>\n <LogonType>${inBackground(spec) ? \"S4U\" : \"InteractiveToken\"}</LogonType>\n <RunLevel>LeastPrivilege</RunLevel>\n </Principal>\n </Principals>\n <Settings>\n <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>\n <DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>\n <StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>\n <AllowHardTerminate>true</AllowHardTerminate>\n <StartWhenAvailable>true</StartWhenAvailable>\n <RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>\n <IdleSettings>\n <StopOnIdleEnd>false</StopOnIdleEnd>\n <RestartOnIdle>false</RestartOnIdle>\n </IdleSettings>\n <AllowStartOnDemand>true</AllowStartOnDemand>\n <Enabled>true</Enabled>\n <Hidden>false</Hidden>\n <RunOnlyIfIdle>false</RunOnlyIfIdle>\n <WakeToRun>false</WakeToRun>\n <ExecutionTimeLimit>${limit}</ExecutionTimeLimit>\n <Priority>5</Priority>\n </Settings>\n <Actions Context=\"Author\">\n <Exec>\n <Command>${xmlText(windowsArg(command))}</Command>\n <Arguments>${xmlText(args)}</Arguments>${cwd}\n </Exec>\n </Actions>\n</Task>\n`;\n};\n\n/** This function encodes a text as UTF-16, little-endian, with a byte order mark: the encoding that Task Scheduler reads. */\nexport const utf16le = (text: string): Uint8Array => {\n const bytes = new Uint8Array(2 + text.length * 2);\n bytes[0] = 0xff;\n bytes[1] = 0xfe;\n for (let at = 0; at < text.length; at += 1) {\n const unit = text.charCodeAt(at);\n bytes[2 + at * 2] = unit & 0xff;\n bytes[3 + at * 2] = unit >> 8;\n }\n return bytes;\n};\n\n/**\n * This function gives the systemd user unit of a spec (`<name>.service`), as text. It is a pure function.\n * - A start at logon or at boot is a service of the type `simple`, wanted by `default.target`. With a restart, it has `Restart=on-failure`.\n * The unit is the same for the two starts: the linger of the user (`installService`) starts the user manager at boot.\n * - A daily start is a service of the type `oneshot` with no `[Install]` section. Its timer (`renderSystemdTimer`) starts it.\n */\nexport const renderSystemdUnit = (spec: ServiceSpec): string => {\n refuse(spec);\n const lines = [\"[Unit]\", `Description=${spec.description.replace(/%/g, \"%%\")}`, \"\", \"[Service]\"];\n lines.push(runsUntilStop(spec.start) ? \"Type=simple\" : \"Type=oneshot\");\n lines.push(`ExecStart=${[spec.program, ...spec.args].map(systemdArg).join(\" \")}`);\n if (spec.cwd !== undefined) lines.push(`WorkingDirectory=${spec.cwd.replace(/%/g, \"%%\")}`);\n if (spec.restart !== null) lines.push(\"Restart=on-failure\", `RestartSec=${restartSeconds(spec.restart.after)}`);\n if (spec.timeLimit !== undefined) lines.push(`RuntimeMaxSec=${Math.max(1, Math.ceil(valueIn(spec.timeLimit, \"s\")))}`);\n if (runsUntilStop(spec.start)) lines.push(\"\", \"[Install]\", \"WantedBy=default.target\");\n return `${lines.join(\"\\n\")}\\n`;\n};\n\n/** This function gives the systemd timer (`<name>.timer`) of a daily spec, or null for a start at logon or at boot. It is a pure function. */\nexport const renderSystemdTimer = (spec: ServiceSpec): string | null => {\n refuse(spec);\n if (runsUntilStop(spec.start)) return null;\n const time = dailyTime(spec.start.daily)!;\n return `${[\n \"[Unit]\",\n `Description=${spec.description.replace(/%/g, \"%%\")}`,\n \"\",\n \"[Timer]\",\n `OnCalendar=*-*-* ${time.hour}:${time.minute}:00`,\n \"Persistent=true\",\n \"\",\n \"[Install]\",\n \"WantedBy=timers.target\",\n ].join(\"\\n\")}\\n`;\n};\n","import type { HostPorts, ProcessMark } from \"./ports.ts\";\n\n/**\n * This margin is the time after a recorded start in which a process can start and still be the same\n * process, in milliseconds. A start time on Linux comes in ticks of 10 ms, and a step of the wall clock moves a time.\n */\nexport const START_MARGIN_MS = 1000;\n\n/**\n * This function tells if the process of a mark is alive and is the same process. Windows and Linux\n * use a process ID again after a process stops. Thus a live process that started after the mark is a\n * different process. A start time that the system does not give proves nothing, and the process counts as the same.\n */\nexport const sameProcess = async (mark: ProcessMark, ports: HostPorts): Promise<boolean> => {\n if (!Number.isInteger(mark.pid) || mark.pid <= 0) return false;\n if (mark.pid === ports.self.pid) return Math.abs(mark.startedAt - ports.self.startedAt) <= START_MARGIN_MS;\n if (!ports.processes.alive(mark.pid)) return false;\n let started: number | null;\n try {\n started = await ports.processes.startOf(mark.pid);\n } catch {\n started = null;\n }\n return started === null || started <= mark.startedAt + START_MARGIN_MS;\n};\n\n/**\n * A tree stop outcome tells what a tree stop did.\n * - `stopped`: the stop went to the process and to each process under it.\n * - `absent`: no process with the ID was alive.\n * - `failed`: the process is alive and the stop did not go. The problem tells why.\n */\nexport type TreeStopOutcome =\n | { readonly kind: \"stopped\" }\n | { readonly kind: \"absent\" }\n | { readonly kind: \"failed\"; readonly problem: string };\n\n/**\n * This function stops a process and each process under it, by its ID only. It does not find a process by\n * its name or its command line. On Windows, it starts `taskkill /T /F /PID <pid>`. On Linux, it sends\n * SIGKILL to the process group of the ID, or to the process when it leads no group. It does not throw.\n */\nexport const stopTree = async (pid: number, ports: HostPorts): Promise<TreeStopOutcome> => {\n if (!Number.isInteger(pid) || pid <= 0) return { kind: \"failed\", problem: `${pid} is not a process ID` };\n if (pid === ports.self.pid) return { kind: \"failed\", problem: \"the host does not stop its own process\" };\n if (!ports.processes.alive(pid)) return { kind: \"absent\" };\n if (ports.platform === \"win32\") {\n const result = await ports.commands\n .run(\"taskkill\", [\"/T\", \"/F\", \"/PID\", String(pid)])\n .catch((error: unknown) => ({ code: 127, out: error instanceof Error ? error.message : String(error) }));\n if (result.code === 0 || !ports.processes.alive(pid)) return { kind: \"stopped\" };\n return { kind: \"failed\", problem: `taskkill gave the code ${result.code}: ${result.out}` };\n }\n if (ports.processes.signalGroup(pid, \"SIGKILL\") || ports.processes.signal(pid, \"SIGKILL\")) return { kind: \"stopped\" };\n return ports.processes.alive(pid) ? { kind: \"failed\", problem: `the signal SIGKILL did not go to the process ${pid}` } : { kind: \"absent\" };\n};\n","import type { HostPorts, ProcessMark } from \"./ports.ts\";\nimport { sameProcess } from \"./processes.ts\";\n\n/**\n * A lock owner is the record in a lock file: the process that holds the lock. The record can also\n * have the child process that it holds the lock for. The lock is held while one of the two is alive.\n */\nexport interface LockOwner extends ProcessMark {\n readonly child?: ProcessMark | undefined;\n}\n\n/** An instance lock is a lock that this process holds. */\nexport interface InstanceLock {\n readonly path: string;\n readonly owner: LockOwner;\n /** This method writes a new child process in the record, or no child with null. */\n update(child: ProcessMark | null): Promise<void>;\n /** This method removes the lock file, when it still has the record of this lock. A second use does nothing. */\n release(): Promise<void>;\n}\n\n/**\n * A lock result tells what a try to take the lock found.\n * - `acquired`: this process holds the lock. `recovered` tells why a stale lock went first, or it is null.\n * - `held`: a live process holds the lock. Its owner is in the result.\n * - `failed`: the lock did not come free, or the file system failed. The problem tells why.\n */\nexport type LockResult =\n | { readonly kind: \"acquired\"; readonly lock: InstanceLock; readonly recovered: string | null }\n | { readonly kind: \"held\"; readonly owner: LockOwner }\n | { readonly kind: \"failed\"; readonly problem: string };\n\n/**\n * A lock state is what an examination of a lock file found. An examination does not throw.\n * - `free`: no file.\n * - `held`: the record names a live process.\n * - `stale`: the record names processes that stopped. The next take removes the file.\n * - `malformed`: the file is not a record, or the read failed.\n */\nexport type LockState =\n | { readonly kind: \"free\" }\n | { readonly kind: \"held\"; readonly owner: LockOwner }\n | { readonly kind: \"stale\"; readonly owner: LockOwner; readonly why: string }\n | { readonly kind: \"malformed\"; readonly problem: string };\n\n/** These options go with a take of the lock. */\nexport interface LockOptions {\n /** This count is the number of reads of a malformed file before the take removes it. The default is 3. */\n readonly tries?: number | undefined;\n /** This time is the pause between two reads of a malformed file, in milliseconds. The default is 100. */\n readonly pause?: number | undefined;\n /** This child process goes in the record at the take. */\n readonly child?: ProcessMark | undefined;\n}\n\nconst isMark = (value: unknown): value is ProcessMark => {\n if (typeof value !== \"object\" || value === null) return false;\n const { pid, startedAt } = value as { pid?: unknown; startedAt?: unknown };\n return typeof pid === \"number\" && Number.isInteger(pid) && pid > 0 && typeof startedAt === \"number\" && Number.isFinite(startedAt);\n};\n\n/** This function reads a lock owner from the text of a lock file, or gives null for a text that is not a record. */\nexport const parseLockOwner = (text: string): LockOwner | null => {\n try {\n const value = JSON.parse(text) as unknown;\n if (!isMark(value)) return null;\n const child = (value as { child?: unknown }).child;\n if (child !== undefined && child !== null && !isMark(child)) return null;\n return { pid: value.pid, startedAt: value.startedAt, ...(isMark(child) ? { child: { pid: child.pid, startedAt: child.startedAt } } : {}) };\n } catch {\n return null;\n }\n};\n\n/** This function gives the text of a lock file for an owner. */\nexport const lockText = (owner: LockOwner): string => `${JSON.stringify(owner)}\\n`;\n\n/** This function tells if the owner of a lock is alive: its process, or its child. */\nconst ownerAlive = async (owner: LockOwner, ports: HostPorts): Promise<boolean> =>\n (await sameProcess(owner, ports)) || (owner.child !== undefined && (await sameProcess(owner.child, ports)));\n\nconst sleep = (ports: HostPorts, ms: number): Promise<void> => new Promise((resolve) => ports.clock.after(ms, resolve));\n\n/**\n * This function removes a file only when it has this text: a lock file or a discovery file. The\n * removal holds the removal lock `<path>.rm` for its read and its delete. Thus two processes that find\n * the same stale file do not remove each other's new file. A removal lock whose owner stopped goes first.\n */\nexport const removeIfSame = async (path: string, text: string, ports: HostPorts): Promise<boolean> => {\n const removal = `${path}.rm`;\n const mine = lockText({ pid: ports.self.pid, startedAt: ports.self.startedAt });\n if (!(await ports.files.create(removal, mine))) {\n const other = parseLockOwner((await ports.files.read(removal)) ?? \"\");\n if (other !== null && (await ownerAlive(other, ports))) return false;\n await ports.files.remove(removal);\n if (!(await ports.files.create(removal, mine))) return false;\n }\n try {\n if ((await ports.files.read(path)) !== text) return false;\n await ports.files.remove(path);\n return true;\n } finally {\n if ((await ports.files.read(removal)) === mine) await ports.files.remove(removal);\n }\n};\n\n/** This function examines a lock file. It does not throw. */\nexport const inspectInstanceLock = async (path: string, ports: HostPorts): Promise<LockState> => {\n try {\n const text = await ports.files.read(path);\n if (text === null) return { kind: \"free\" };\n const owner = parseLockOwner(text);\n if (owner === null) return { kind: \"malformed\", problem: \"the lock file is not a lock record\" };\n if (await ownerAlive(owner, ports)) return { kind: \"held\", owner };\n return { kind: \"stale\", owner, why: `the owner process ${owner.pid} stopped` };\n } catch (error) {\n return { kind: \"malformed\", problem: `the read failed: ${error instanceof Error ? error.message : String(error)}` };\n }\n};\n\n/**\n * This function takes the lock of one instance: a lock file with the record of this process. Thus a\n * second instance does not start. It does not throw.\n * - A file whose owner and child stopped is stale: it goes, and the take tries again.\n * - A malformed file can be the file of a take that writes at this time. The take reads it again after\n * a pause, and after `tries` reads, it removes it.\n * - A file whose owner or child is alive gives `held`.\n */\nexport const acquireInstanceLock = async (path: string, ports: HostPorts, options: LockOptions = {}): Promise<LockResult> => {\n const tries = options.tries ?? 3;\n const pause = options.pause ?? 100;\n const owner: LockOwner = { pid: ports.self.pid, startedAt: ports.self.startedAt, ...(options.child === undefined ? {} : { child: options.child }) };\n let recovered: string | null = null;\n let malformed = 0;\n try {\n for (let attempt = 0; attempt < tries + 3; attempt += 1) {\n const text = lockText(owner);\n if (await ports.files.create(path, text)) {\n ports.logger?.log(\"info\", `the host took the lock ${path}`, { path, pid: owner.pid, ...(recovered === null ? {} : { recovered }) });\n return { kind: \"acquired\", lock: held(path, owner, text, ports), recovered };\n }\n const found = await ports.files.read(path);\n if (found === null) continue;\n const other = parseLockOwner(found);\n if (other === null) {\n malformed += 1;\n if (malformed < tries) {\n await sleep(ports, pause);\n continue;\n }\n if (await removeIfSame(path, found, ports)) recovered = \"the lock file was not a lock record\";\n continue;\n }\n if (await ownerAlive(other, ports)) return { kind: \"held\", owner: other };\n if (await removeIfSame(path, found, ports)) {\n recovered = `the owner process ${other.pid} stopped`;\n ports.logger?.log(\"warn\", `the host removed the stale lock ${path}: ${recovered}`, { path, owner: other });\n }\n }\n return { kind: \"failed\", problem: `the lock ${path} did not come free after ${tries + 3} tries` };\n } catch (error) {\n return { kind: \"failed\", problem: `the file system failed: ${error instanceof Error ? error.message : String(error)}` };\n }\n};\n\n/** This function gives the handle of a lock that this process holds. */\nconst held = (path: string, first: LockOwner, firstText: string, ports: HostPorts): InstanceLock => {\n let owner = first;\n let text = firstText;\n let released = false;\n // the updates and the release occur in sequence, thus a late write does not make the file again after the release\n let queue: Promise<void> = Promise.resolve();\n const enqueue = (work: () => Promise<void>): Promise<void> => {\n const next = queue.then(work);\n queue = next.catch(() => {});\n return next;\n };\n return {\n path,\n get owner() {\n return owner;\n },\n update: (child) =>\n enqueue(async () => {\n if (released) return;\n const next: LockOwner = { pid: owner.pid, startedAt: owner.startedAt, ...(child === null ? {} : { child }) };\n const nextText = lockText(next);\n await ports.files.write(path, nextText);\n owner = next;\n text = nextText;\n }),\n release: () =>\n enqueue(async () => {\n if (released) return;\n released = true;\n try {\n await removeIfSame(path, text, ports);\n } catch {\n // a lock file that stays is stale after the exit of this process\n }\n }),\n };\n};\n","import type { HostPorts } from \"./ports.ts\";\nimport { removeIfSame } from \"./lock.ts\";\nimport { sameProcess } from \"./processes.ts\";\n\n/**\n * A discovery record tells where a running instance listens. The instance writes it after its start,\n * and a client reads it to find the instance. The file is JSON, one record.\n */\nexport interface Discovery {\n /** This number is the process ID of the instance. */\n readonly pid: number;\n /** This text is the start time of the process, as an ISO 8601 time. */\n readonly startedAt: string;\n /** This number is the port that the instance listens on, or null. */\n readonly port: number | null;\n /** This text is the address of the instance, for example `http://127.0.0.1:8080/`, or null. */\n readonly url: string | null;\n /** These fields are more data of the instance, for example its version. */\n readonly extra?: Readonly<Record<string, unknown>> | undefined;\n}\n\n/**\n * A discovery read is what a read of the discovery file found. A read does not throw.\n * - `running`: the file names a live process, and its start time does not prove that it is a different process.\n * - `absent`: no file.\n * - `stale`: the file names a process that stopped, or a new process with the same ID.\n * - `malformed`: the file is not a discovery record, or the read failed. The problem tells why.\n */\nexport type DiscoveryRead =\n | { readonly kind: \"running\"; readonly record: Discovery }\n | { readonly kind: \"absent\" }\n | { readonly kind: \"stale\"; readonly record: Discovery; readonly why: string }\n | { readonly kind: \"malformed\"; readonly problem: string };\n\n/** These options go with a read of the discovery file. */\nexport interface ReadDiscoveryOptions {\n /** True removes a stale or malformed file. The default is false. */\n readonly clean?: boolean | undefined;\n}\n\nconst isPort = (value: unknown): value is number => typeof value === \"number\" && Number.isInteger(value) && value >= 1 && value <= 65_535;\n\n/** This function reads a discovery record from a text. It gives the record, or the problem as a text. */\nexport const parseDiscovery = (text: string): Discovery | string => {\n let value: unknown;\n try {\n value = JSON.parse(text);\n } catch (error) {\n return `the file is not JSON: ${error instanceof Error ? error.message : String(error)}`;\n }\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) return \"the file is not a JSON object\";\n const record = value as Readonly<Record<string, unknown>>;\n const { pid, startedAt, port, url, extra } = record;\n if (typeof pid !== \"number\" || !Number.isInteger(pid) || pid <= 0) return \"the field pid is not a process ID\";\n if (typeof startedAt !== \"string\" || !Number.isFinite(Date.parse(startedAt))) return \"the field startedAt is not an ISO time\";\n if (port !== null && port !== undefined && !isPort(port)) return \"the field port is not a port from 1 to 65535\";\n if (url !== null && url !== undefined && typeof url !== \"string\") return \"the field url is not a text\";\n if (extra !== undefined && (typeof extra !== \"object\" || extra === null || Array.isArray(extra))) return \"the field extra is not an object\";\n return {\n pid,\n startedAt,\n port: isPort(port) ? port : null,\n url: typeof url === \"string\" ? url : null,\n ...(extra === undefined ? {} : { extra: extra as Readonly<Record<string, unknown>> }),\n };\n};\n\n/** These fields describe where this process listens. */\nexport interface DiscoveryFields {\n readonly port?: number | null | undefined;\n readonly url?: string | null | undefined;\n readonly extra?: Readonly<Record<string, unknown>> | undefined;\n}\n\n/** This function gives the discovery record of the process of the host, with its start time. */\nexport const discoveryOf = (fields: DiscoveryFields, ports: HostPorts): Discovery => ({\n pid: ports.self.pid,\n startedAt: new Date(ports.self.startedAt).toISOString(),\n port: fields.port ?? null,\n url: fields.url ?? null,\n ...(fields.extra === undefined ? {} : { extra: fields.extra }),\n});\n\n/** This function writes a discovery file. The write replaces the file in one step, thus a reader sees the old record or the new one. */\nexport const writeDiscovery = async (path: string, record: Discovery, ports: HostPorts): Promise<void> => {\n await ports.files.write(path, `${JSON.stringify(record, null, 2)}\\n`);\n};\n\n/**\n * This function reads a discovery file and examines its process. It does not throw: a file that is not\n * a record, or a failed read, gives `malformed`. With `clean`, it removes a stale or malformed file.\n */\nexport const readDiscovery = async (path: string, ports: HostPorts, options: ReadDiscoveryOptions = {}): Promise<DiscoveryRead> => {\n const { found, text } = await examine(path, ports);\n // The clean removes only the text that it examined: a new instance can write its file after the read.\n if (options.clean === true && text !== null && (found.kind === \"stale\" || found.kind === \"malformed\")) {\n try {\n if (await removeIfSame(path, text, ports)) ports.logger?.log(\"info\", `the host removed the ${found.kind} discovery file ${path}`, { path, kind: found.kind });\n } catch {\n // the next read examines the file again\n }\n }\n return found;\n};\n\nconst examine = async (path: string, ports: HostPorts): Promise<{ readonly found: DiscoveryRead; readonly text: string | null }> => {\n let text: string | null;\n try {\n text = await ports.files.read(path);\n } catch (error) {\n return { found: { kind: \"malformed\", problem: `the read failed: ${error instanceof Error ? error.message : String(error)}` }, text: null };\n }\n if (text === null) return { found: { kind: \"absent\" }, text };\n const record = parseDiscovery(text);\n if (typeof record === \"string\") return { found: { kind: \"malformed\", problem: record }, text };\n const mark = { pid: record.pid, startedAt: Date.parse(record.startedAt) };\n if (await sameProcess(mark, ports)) return { found: { kind: \"running\", record }, text };\n const why = ports.processes.alive(record.pid)\n ? `the process ${record.pid} started after the record, thus it is a different process`\n : `the process ${record.pid} stopped`;\n return { found: { kind: \"stale\", record, why }, text };\n};\n\n/** This function removes a discovery file when it names the process `pid`, by default the process of the host. It tells if it removed the file. */\nexport const removeDiscovery = async (path: string, ports: HostPorts, pid: number = ports.self.pid): Promise<boolean> => {\n try {\n const text = await ports.files.read(path);\n if (text === null) return false;\n const record = parseDiscovery(text);\n if (typeof record === \"string\" || record.pid !== pid) return false;\n return await removeIfSame(path, text, ports);\n } catch {\n return false;\n }\n};\n","import type { DiscoveryRead } from \"./discovery.ts\";\nimport { readDiscovery } from \"./discovery.ts\";\nimport type { HostPorts } from \"./ports.ts\";\nimport { joinPath } from \"./ports.ts\";\nimport { stopTree } from \"./processes.ts\";\nimport type { ServiceSpec } from \"./render.ts\";\nimport { inBackground, renderSystemdTimer, renderSystemdUnit, renderTaskXml, runsUntilStop, serviceProblems, utf16le } from \"./render.ts\";\n\n/** A command record is one command that a service operation started, and its result. */\nexport interface CommandRecord {\n readonly file: string;\n readonly args: readonly string[];\n readonly code: number;\n readonly out: string;\n}\n\n/**\n * A service outcome tells what a service operation did. An operation does not throw.\n * - `done`: each command gave 0. `commands` and `files` tell what the operation did.\n * - `failed`: a command gave a code that is not 0, or the file system failed. The problem tells which.\n * - `refused`: the spec has problems, and the operation did nothing.\n * - `unsupported`: the platform is not Windows or Linux, and the operation did nothing.\n */\nexport type ServiceOutcome =\n | { readonly kind: \"done\"; readonly commands: readonly CommandRecord[]; readonly files: readonly string[] }\n | { readonly kind: \"failed\"; readonly commands: readonly CommandRecord[]; readonly problem: string }\n | { readonly kind: \"refused\"; readonly problems: readonly string[] }\n | { readonly kind: \"unsupported\"; readonly platform: string };\n\n/** A service status tells if the system has the service, its state, and the instance of the discovery file. */\nexport interface ServiceStatus {\n /** This flag tells if the system has the task or the unit. */\n readonly installed: boolean;\n /**\n * This text is the state that the system gives, for example `Running` or `Ready` from `schtasks`, or\n * `active` or `inactive` from `systemctl`. It is `unknown` when the system gives no state.\n */\n readonly state: string;\n /** This is the read of the discovery file, or null without a discovery path. */\n readonly instance: DiscoveryRead | null;\n /** These are the commands that the status started. */\n readonly commands: readonly CommandRecord[];\n}\n\n/** These options go with an install. */\nexport interface InstallOptions {\n /** True starts the service after the install. The default is true. */\n readonly start?: boolean | undefined;\n}\n\n/** These options go with an operation that stops the instance: the discovery file that names it. */\nexport interface InstanceOptions {\n /** This path is the discovery file of the instance. With it, the operation stops the process tree of a live instance. */\n readonly discovery?: string | undefined;\n}\n\n/** These are the files of a service on this platform. */\nexport interface ServicePaths {\n /** This path is the task file on Windows, or the unit on Linux. */\n readonly unit: string;\n /** This path is the timer of a daily job on Linux, or null. */\n readonly timer: string | null;\n}\n\n/** This function gives the folder of the systemd user units: `$XDG_CONFIG_HOME/systemd/user`, or `~/.config/systemd/user`. */\nconst unitDir = (ports: HostPorts): string => {\n const config = ports.env[\"XDG_CONFIG_HOME\"];\n return joinPath(\"linux\", config === undefined || config === \"\" ? joinPath(\"linux\", ports.homeDir, \".config\") : config, \"systemd\", \"user\");\n};\n\n/** This function gives the files of a service on the platform of the ports. */\nexport const servicePaths = (spec: ServiceSpec, ports: HostPorts): ServicePaths => {\n if (ports.platform === \"win32\") return { unit: joinPath(\"win32\", spec.stateDir, `${spec.name}.task.xml`), timer: null };\n const dir = unitDir(ports);\n return { unit: joinPath(\"linux\", dir, `${spec.name}.service`), timer: runsUntilStop(spec.start) ? null : joinPath(\"linux\", dir, `${spec.name}.timer`) };\n};\n\n/** This function gives the unit that `systemctl` enables: the timer of a daily job, or the service. */\nconst enabledUnit = (spec: ServiceSpec): string => (runsUntilStop(spec.start) ? `${spec.name}.service` : `${spec.name}.timer`);\n\n/**\n * This text goes with a failure of `schtasks` for a spec in the background. Task Scheduler refuses a boot trigger\n * and an S4U logon from a shell that is not elevated: `Access is denied`, with the code 1 (Windows 11, 2026-11).\n */\nconst ELEVATION =\n \"Task Scheduler refuses a boot trigger and an S4U logon from a shell that is not elevated: start the same operation in a shell of an administrator\";\n\n/** This function gives the path of `conhost.exe` from `SystemRoot`. Without it, Task Scheduler expands `%SystemRoot%` at the start. */\nconst conhostPath = (ports: HostPorts): string => joinPath(\"win32\", ports.env[\"SystemRoot\"] ?? \"%SystemRoot%\", \"System32\", \"conhost.exe\");\n\n/** A runner starts commands, and keeps a record of each. */\ninterface Runner {\n readonly commands: CommandRecord[];\n run(file: string, args: readonly string[]): Promise<CommandRecord>;\n}\n\nconst runner = (ports: HostPorts): Runner => {\n const commands: CommandRecord[] = [];\n return {\n commands,\n async run(file, args) {\n let record: CommandRecord;\n try {\n const result = await ports.commands.run(file, args);\n record = { file, args, code: result.code, out: result.out.trim() };\n } catch (error) {\n record = { file, args, code: 127, out: error instanceof Error ? error.message : String(error) };\n }\n commands.push(record);\n ports.logger?.log(record.code === 0 ? \"debug\" : \"warn\", `${file} ${args.join(\" \")} gave the code ${record.code}`, { ...record });\n return record;\n },\n };\n};\n\nconst failed = (commands: readonly CommandRecord[], record: CommandRecord, note: string | null): ServiceOutcome => ({\n kind: \"failed\",\n commands,\n problem: `${record.file} ${record.args.join(\" \")} gave the code ${record.code}${record.out === \"\" ? \"\" : `: ${record.out}`}${note === null ? \"\" : ` (${note})`}`,\n});\n\n/** This function gives the note of a failed command: the elevation of Task Scheduler for a spec in the background, or null. */\nconst noteOf = (spec: ServiceSpec, ports: HostPorts, record: CommandRecord): string | null =>\n ports.platform === \"win32\" && record.file === \"schtasks\" && inBackground(spec) ? ELEVATION : null;\n\nconst problemOf = (error: unknown): string => (error instanceof Error ? error.message : String(error));\n\n/**\n * This function runs the steps of an operation. It refuses a spec with problems and a platform that\n * is not Windows or Linux, and it catches each failure of the file system.\n */\nconst operate = async (\n spec: ServiceSpec,\n ports: HostPorts,\n steps: (run: Runner, files: string[]) => Promise<CommandRecord | null>,\n): Promise<ServiceOutcome> => {\n const problems = serviceProblems(spec);\n if (problems.length > 0) return { kind: \"refused\", problems };\n if (ports.platform !== \"win32\" && ports.platform !== \"linux\") return { kind: \"unsupported\", platform: ports.platform };\n const run = runner(ports);\n const files: string[] = [];\n try {\n const failure = await steps(run, files);\n if (failure !== null) return failed(run.commands, failure, noteOf(spec, ports, failure));\n } catch (error) {\n return { kind: \"failed\", commands: run.commands, problem: `the file system failed: ${problemOf(error)}` };\n }\n return { kind: \"done\", commands: run.commands, files };\n};\n\n/** This function gives the first record whose code is not 0, or null. */\nconst firstFailure = (...records: readonly CommandRecord[]): CommandRecord | null => records.find((record) => record.code !== 0) ?? null;\n\n/**\n * This function installs a service of the user, and by default starts it. It does not throw.\n * - On Windows, it writes the task file in UTF-16 to `stateDir`, and starts `schtasks /Create /XML <file> /F`, then `schtasks /Run`.\n * - On Linux, it writes the unit (and the timer of a daily job), then starts `systemctl --user daemon-reload` and `enable`.\n * For a spec in the background, it first starts `loginctl enable-linger` for the user.\n * A second install replaces the first. Give it the ports of a test, thus no test installs a real task.\n * On Windows, Task Scheduler refuses a spec in the background from a shell that is not elevated: the problem then tells so.\n */\nexport const installService = (spec: ServiceSpec, ports: HostPorts, options: InstallOptions = {}): Promise<ServiceOutcome> =>\n operate(spec, ports, async (run, files) => {\n const start = options.start ?? true;\n const paths = servicePaths(spec, ports);\n if (ports.platform === \"win32\") {\n await ports.files.write(paths.unit, utf16le(renderTaskXml(spec, { user: ports.user(), conhost: conhostPath(ports) })));\n files.push(paths.unit);\n const created = await run.run(\"schtasks\", [\"/Create\", \"/TN\", spec.name, \"/XML\", paths.unit, \"/F\"]);\n if (created.code !== 0 || !start) return firstFailure(created);\n return firstFailure(await run.run(\"schtasks\", [\"/Run\", \"/TN\", spec.name]));\n }\n await ports.files.write(paths.unit, renderSystemdUnit(spec));\n files.push(paths.unit);\n const timer = renderSystemdTimer(spec);\n if (paths.timer !== null && timer !== null) {\n await ports.files.write(paths.timer, timer);\n files.push(paths.timer);\n }\n if (inBackground(spec)) {\n // the linger starts the user manager at boot and keeps it after the logout. The removal keeps the linger, because other units can need it\n const lingered = await run.run(\"loginctl\", [\"enable-linger\"]);\n if (lingered.code !== 0) return lingered;\n }\n const reloaded = await run.run(\"systemctl\", [\"--user\", \"daemon-reload\"]);\n if (reloaded.code !== 0) return reloaded;\n return firstFailure(await run.run(\"systemctl\", [\"--user\", \"enable\", ...(start ? [\"--now\"] : []), enabledUnit(spec)]));\n });\n\n/** This function stops the instance of a discovery file, when it is alive and is the same process. */\nconst stopInstance = async (ports: HostPorts, options: InstanceOptions): Promise<void> => {\n if (options.discovery === undefined) return;\n const found = await readDiscovery(options.discovery, ports, { clean: true });\n if (found.kind !== \"running\") return;\n const stopped = await stopTree(found.record.pid, ports);\n ports.logger?.log(stopped.kind === \"failed\" ? \"warn\" : \"info\", `the host stopped the instance ${found.record.pid}: ${stopped.kind}`, {\n pid: found.record.pid,\n outcome: stopped.kind,\n });\n};\n\n/**\n * This function removes a service. It does not throw. On Windows, it ends the task and deletes it. On\n * Linux, it disables and stops the unit, removes its files and reloads systemd. With a discovery file,\n * it then stops the process tree of an instance that stays.\n */\nexport const uninstallService = (spec: ServiceSpec, ports: HostPorts, options: InstanceOptions = {}): Promise<ServiceOutcome> =>\n operate(spec, ports, async (run, files) => {\n const paths = servicePaths(spec, ports);\n let failure: CommandRecord | null;\n if (ports.platform === \"win32\") {\n // the end of a task that does not run gives a code that is not 0: it is not a failure of the removal\n await run.run(\"schtasks\", [\"/End\", \"/TN\", spec.name]);\n failure = firstFailure(await run.run(\"schtasks\", [\"/Delete\", \"/TN\", spec.name, \"/F\"]));\n await ports.files.remove(paths.unit);\n } else {\n failure = firstFailure(await run.run(\"systemctl\", [\"--user\", \"disable\", \"--now\", enabledUnit(spec)]));\n if (paths.timer !== null) await run.run(\"systemctl\", [\"--user\", \"stop\", `${spec.name}.service`]);\n await ports.files.remove(paths.unit);\n if (paths.timer !== null) await ports.files.remove(paths.timer);\n await run.run(\"systemctl\", [\"--user\", \"daemon-reload\"]);\n }\n files.push(paths.unit, ...(paths.timer === null ? [] : [paths.timer]));\n await stopInstance(ports, options);\n return failure;\n });\n\n/** This function enables a service and starts it. It does not throw. On Windows, it enables the task and runs it. */\nexport const startService = (spec: ServiceSpec, ports: HostPorts): Promise<ServiceOutcome> =>\n operate(spec, ports, async (run) => {\n if (ports.platform === \"win32\") {\n const enabled = await run.run(\"schtasks\", [\"/Change\", \"/TN\", spec.name, \"/ENABLE\"]);\n if (enabled.code !== 0) return enabled;\n return firstFailure(await run.run(\"schtasks\", [\"/Run\", \"/TN\", spec.name]));\n }\n // stopService disables the unit or its timer, thus the start enables it again\n return firstFailure(await run.run(\"systemctl\", [\"--user\", \"enable\", \"--now\", enabledUnit(spec)]));\n });\n\n/**\n * This function stops a service, and keeps it stopped until `startService`. It does not throw.\n * - On Windows, it disables the task, thus its time trigger does not start it again, and ends the task.\n * With a discovery file, it then stops the process tree of the instance. Windows has no signal that a child can catch.\n * - On Linux, it disables the unit of a service at logon or at boot, or the timer of a daily job, and stops it.\n * Thus the next login, the next boot or the next calendar time does not start it again. The stop sends SIGTERM,\n * thus `run()` stops in its stages. A daily job that operates stops too.\n */\nexport const stopService = (spec: ServiceSpec, ports: HostPorts, options: InstanceOptions = {}): Promise<ServiceOutcome> =>\n operate(spec, ports, async (run) => {\n if (ports.platform === \"win32\") {\n const disabled = await run.run(\"schtasks\", [\"/Change\", \"/TN\", spec.name, \"/DISABLE\"]);\n if (disabled.code !== 0) return disabled;\n await run.run(\"schtasks\", [\"/End\", \"/TN\", spec.name]);\n await stopInstance(ports, options);\n return null;\n }\n const disabled = await run.run(\"systemctl\", [\"--user\", \"disable\", \"--now\", enabledUnit(spec)]);\n if (disabled.code !== 0 || runsUntilStop(spec.start)) return firstFailure(disabled);\n return firstFailure(await run.run(\"systemctl\", [\"--user\", \"stop\", `${spec.name}.service`]));\n });\n\n/** This function gives the value of a line `Key: value` of the list of `schtasks /Query /FO LIST`. */\nconst listValue = (out: string, key: string): string | null => {\n for (const line of out.split(/\\r?\\n/)) {\n const at = line.indexOf(\":\");\n if (at > 0 && line.slice(0, at).trim() === key) return line.slice(at + 1).trim();\n }\n return null;\n};\n\n/**\n * This function gives the status of a service. It does not throw. A service that the system does not\n * have gives `installed: false`. A malformed or stale discovery file gives its read, and not a throw.\n */\nexport const serviceStatus = async (spec: ServiceSpec, ports: HostPorts, options: InstanceOptions = {}): Promise<ServiceStatus> => {\n const run = runner(ports);\n const instance = options.discovery === undefined ? null : await readDiscovery(options.discovery, ports);\n if (serviceProblems(spec).length > 0 || (ports.platform !== \"win32\" && ports.platform !== \"linux\"))\n return { installed: false, state: \"unknown\", instance, commands: run.commands };\n if (ports.platform === \"win32\") {\n const query = await run.run(\"schtasks\", [\"/Query\", \"/TN\", spec.name, \"/V\", \"/FO\", \"LIST\"]);\n if (query.code !== 0) return { installed: false, state: \"unknown\", instance, commands: run.commands };\n return { installed: true, state: listValue(query.out, \"Status\") ?? \"unknown\", instance, commands: run.commands };\n }\n let installed: boolean;\n try {\n installed = (await ports.files.read(servicePaths(spec, ports).unit)) !== null;\n } catch {\n installed = false;\n }\n const active = await run.run(\"systemctl\", [\"--user\", \"is-active\", `${spec.name}.service`]);\n const state = active.out.split(/\\r?\\n/)[0]?.trim() ?? \"\";\n return { installed, state: state === \"\" ? \"unknown\" : state, instance, commands: run.commands };\n};\n","import type { Quantity } from \"@mark1russell7/quantity\";\nimport { convertible, formatDuration, isQuantity, valueIn } from \"@mark1russell7/quantity\";\nimport type { HostPorts } from \"./ports.ts\";\n\n/**\n * A freshness bound reads one time in the JSON answer of an http probe. The time is epoch\n * milliseconds or an ISO 8601 text. The probe fails when the time is older than `within`, or when\n * the answer does not have it.\n */\nexport interface FreshnessBound {\n /** This JSON Pointer (RFC 6901) names the time in the answer, for example `/delivery/lastTestSendAt`. */\n readonly pointer: string;\n /** This time is the largest age that passes. */\n readonly within: Quantity;\n}\n\n/**\n * A ready probe tells when a program is ready.\n * - `http`: a GET request to the address gives the status, 200 by default. With `fresh`, the answer\n * is also JSON, and each bound of `fresh` passes. The age of a time is measured from `now`: a\n * JSON Pointer to the time of the target in the answer. Without `now`, the wall clock of the host\n * gives the time.\n * - `tcp`: a TCP connection to the port opens. The default host is `127.0.0.1`.\n * - `command`: a command gives the exit code 0.\n */\nexport type ReadyProbe =\n | {\n readonly kind: \"http\";\n readonly url: string;\n readonly status?: number | undefined;\n readonly fresh?: readonly FreshnessBound[] | undefined;\n readonly now?: string | undefined;\n }\n | { readonly kind: \"tcp\"; readonly port: number; readonly host?: string | undefined }\n | { readonly kind: \"command\"; readonly program: string; readonly args: readonly string[]; readonly cwd?: string | undefined };\n\n/** A probe result is the result of one use of a probe. A failure tells why. */\nexport type ProbeResult = { readonly ok: true } | { readonly ok: false; readonly why: string };\n\n/** This size is the largest answer that a probe with freshness bounds reads: 1 MiB. */\nexport const PROBE_BODY_LIMIT = 1_048_576;\n\nconst isPointer = (pointer: unknown): pointer is string =>\n typeof pointer === \"string\" && (pointer === \"\" || (pointer.startsWith(\"/\") && !/~[^01]|~$/.test(pointer)));\n\n/** This function gives the problems of a probe: each value that a probe cannot use. */\nexport const probeProblems = (probe: ReadyProbe): string[] => {\n if (probe.kind === \"http\") {\n const problems: string[] = [];\n if (!/^https?:\\/\\//.test(probe.url)) problems.push(`the address ${JSON.stringify(probe.url)} is not an http or https address`);\n if (probe.status !== undefined && !(Number.isInteger(probe.status) && probe.status >= 100 && probe.status <= 599))\n problems.push(`the status ${probe.status} is not an HTTP status`);\n if (probe.now !== undefined && !isPointer(probe.now)) problems.push(`the now ${JSON.stringify(probe.now)} is not a JSON Pointer`);\n if (probe.now !== undefined && probe.fresh === undefined) problems.push(\"the probe has a now, but no fresh list\");\n if (probe.fresh !== undefined && probe.fresh.length === 0) problems.push(\"the fresh list is empty\");\n for (const bound of probe.fresh ?? []) {\n if (!isPointer(bound.pointer)) problems.push(`the freshness pointer ${JSON.stringify(bound.pointer)} is not a JSON Pointer`);\n if (!(isQuantity(bound.within) && convertible(bound.within.unit, \"ms\") && valueIn(bound.within, \"ms\") >= 0))\n problems.push(`the freshness bound of ${JSON.stringify(bound.pointer)} is not a time of zero or more`);\n }\n return problems;\n }\n if (probe.kind === \"tcp\")\n return Number.isInteger(probe.port) && probe.port >= 1 && probe.port <= 65_535 ? [] : [`the port ${probe.port} is not a port from 1 to 65535`];\n if (probe.kind === \"command\") return probe.program === \"\" ? [\"the program of the command probe is empty\"] : [];\n return [`the probe kind ${JSON.stringify((probe as { kind: unknown }).kind)} is not http, tcp or command`];\n};\n\n/** This function gives the value at a JSON Pointer (RFC 6901), or undefined when the document does not have it. */\nconst pointAt = (document: unknown, pointer: string): unknown => {\n if (pointer === \"\") return document;\n let at = document;\n for (const token of pointer.slice(1).split(\"/\")) {\n const key = token.replaceAll(\"~1\", \"/\").replaceAll(\"~0\", \"~\");\n if (Array.isArray(at)) {\n if (!/^(0|[1-9]\\d*)$/.test(key) || Number(key) >= at.length) return undefined;\n at = at[Number(key)];\n } else if (at !== null && typeof at === \"object\" && Object.hasOwn(at, key)) {\n at = (at as Record<string, unknown>)[key];\n } else return undefined;\n }\n return at;\n};\n\n/** This function gives the time of a value in epoch milliseconds: a finite number, or an ISO 8601 text. */\nconst timeOf = (value: unknown): number | null => {\n if (typeof value === \"number\") return Number.isFinite(value) ? value : null;\n if (typeof value === \"string\") {\n const time = Date.parse(value);\n return Number.isNaN(time) ? null : time;\n }\n return null;\n};\n\n/** This function examines the JSON answer of an http probe against its freshness bounds. */\nconst freshness = (url: string, body: string, bounds: readonly FreshnessBound[], nowPointer: string | undefined, wall: number): ProbeResult => {\n let document: unknown;\n try {\n document = JSON.parse(body);\n } catch {\n return { ok: false, why: `${url} did not give JSON` };\n }\n const now = nowPointer === undefined ? wall : timeOf(pointAt(document, nowPointer));\n if (now === null) return { ok: false, why: `${url} has no time at ${nowPointer}` };\n const stale: string[] = [];\n for (const bound of bounds) {\n const time = timeOf(pointAt(document, bound.pointer));\n if (time === null) {\n stale.push(`${bound.pointer} has no time`);\n continue;\n }\n const age = Math.max(0, now - time);\n if (age > valueIn(bound.within, \"ms\"))\n stale.push(`${bound.pointer} is ${formatDuration({ value: age, unit: \"ms\" })} old, above ${formatDuration(bound.within)}`);\n }\n return stale.length === 0 ? { ok: true } : { ok: false, why: `${url}: ${stale.join(\"; \")}` };\n};\n\n/** This function uses a probe one time, in a timeout of milliseconds. It does not throw. */\nexport const probeOnce = async (probe: ReadyProbe, timeout: number, ports: HostPorts): Promise<ProbeResult> => {\n try {\n if (probe.kind === \"http\") {\n const want = probe.status ?? 200;\n if (probe.fresh !== undefined) {\n if (ports.net.httpText === undefined) return { ok: false, why: \"the net port cannot read an answer, thus it cannot examine freshness\" };\n const answer = await ports.net.httpText(probe.url, timeout, PROBE_BODY_LIMIT);\n if (answer === null) return { ok: false, why: `${probe.url} gave no answer in ${timeout} ms` };\n if (answer.status !== want) return { ok: false, why: `${probe.url} gave ${answer.status}, not ${want}` };\n if (!answer.complete) return { ok: false, why: `the answer of ${probe.url} is above ${PROBE_BODY_LIMIT} bytes` };\n return freshness(probe.url, answer.body, probe.fresh, probe.now, ports.wall());\n }\n const status = await ports.net.httpStatus(probe.url, timeout);\n if (status === want) return { ok: true };\n return { ok: false, why: status === null ? `${probe.url} gave no answer in ${timeout} ms` : `${probe.url} gave ${status}, not ${want}` };\n }\n if (probe.kind === \"tcp\") {\n const host = probe.host ?? \"127.0.0.1\";\n if (await ports.net.tcpConnect(host, probe.port, timeout)) return { ok: true };\n return { ok: false, why: `no TCP connection to ${host}:${probe.port} in ${timeout} ms` };\n }\n const result = await ports.commands.run(probe.program, probe.args, { cwd: probe.cwd, timeout });\n return result.code === 0 ? { ok: true } : { ok: false, why: `${probe.program} gave the code ${result.code}` };\n } catch (error) {\n return { ok: false, why: `the probe failed: ${error instanceof Error ? error.message : String(error)}` };\n }\n};\n","import type { Quantity } from \"@mark1russell7/quantity\";\nimport { valueIn } from \"@mark1russell7/quantity\";\nimport type { Latch, Result, Trace } from \"../latch.ts\";\nimport { latch } from \"../latch.ts\";\nimport type { Poller } from \"../poller.ts\";\nimport { poller } from \"../poller.ts\";\nimport type { Timing } from \"../timing.ts\";\nimport type { HostPorts } from \"./ports.ts\";\nimport type { ProbeResult, ReadyProbe } from \"./probes.ts\";\nimport { probeOnce, probeProblems } from \"./probes.ts\";\nimport { isTime } from \"./render.ts\";\n\n/**\n * A verdict tells when a target goes down and when it comes up again.\n * - `debounce`: `failAfter` failed polls in sequence make it down, and `recoverAfter` passed polls in sequence make it up.\n * - `window`: failures for the time `failAfter` make it down. Passes for the time `recoverAfter` make it up. Without\n * `recoverAfter`, the first pass makes it up.\n */\nexport type TargetVerdict =\n | { readonly type: \"debounce\"; readonly failAfter: number; readonly recoverAfter: number }\n | { readonly type: \"window\"; readonly failAfter: Quantity; readonly recoverAfter?: Quantity | undefined };\n\n/** A watch target is one thing that a watcher probes on its own loop. */\nexport interface WatchTarget {\n /** This name is unique in the spec. A change names its target with it. */\n readonly name: string;\n readonly probe: ReadyProbe;\n /** This time is between the starts of two polls. */\n readonly interval: Quantity;\n /** This time is the most that one poll waits. It is not above the interval. */\n readonly timeout: Quantity;\n /** This fraction moves each interval by up to ± its part, thus two watchers do not poll in step. The default is 0.1. */\n readonly jitter?: number | undefined;\n /** The default is a debounce: 3 failures make it down, and 2 passes make it up. */\n readonly verdict?: TargetVerdict | undefined;\n}\n\n/** A watch spec lists the targets of one watcher. */\nexport interface WatchSpec {\n readonly targets: readonly WatchTarget[];\n}\n\n/** The health of a target is `unknown` until its first verdict. */\nexport type TargetHealth = \"unknown\" | \"up\" | \"down\";\n\n/** A target change is one transition of the health of a target. */\nexport interface TargetChange {\n readonly target: string;\n readonly from: TargetHealth;\n readonly to: \"up\" | \"down\";\n /** This time is the wall time of the change, in milliseconds after the epoch. */\n readonly at: number;\n /** This text tells why the latest poll failed, for a change to down. It is null for a change to up. */\n readonly why: string | null;\n}\n\n/** A target state is what a watcher knows of one target at this time. */\nexport interface TargetState {\n readonly name: string;\n readonly health: TargetHealth;\n /** This time is the wall time of the latest change of the health, or of the start. */\n readonly since: number;\n /** This result is the latest poll, or null before the first poll. */\n readonly last: ProbeResult | null;\n /** This time is the wall time of the latest poll, or null. */\n readonly lastAt: number | null;\n /** This count is the failed polls in sequence. */\n readonly failures: number;\n}\n\nexport interface WatchOptions {\n /** This function gets each change of the health of a target. A throw in it does not stop the watcher. */\n readonly onChange: (change: TargetChange) => void;\n /** This function gives a number in [0, 1) for the jitter. The default is `Math.random`. */\n readonly random?: (() => number) | undefined;\n /** This function gets each transition of the poller and the latch of each target, with the name of the target. */\n readonly trace?: ((target: string, from: string, to: string, on: string) => void) | undefined;\n}\n\n/** A target watch is a running watcher. */\nexport interface TargetWatch {\n /** This method gives the state of each target, in the sequence of the spec. */\n states(): TargetState[];\n /** This method polls each target one time at once, outside its loop, and gives the states after the polls. */\n pollNow(): Promise<TargetState[]>;\n /** This method stops each loop. A stopped watcher gives no change. */\n stop(): void;\n}\n\n/** This verdict is the default: 3 failures in sequence make a target down, and 2 passes make it up. */\nexport const DEFAULT_VERDICT: TargetVerdict = { type: \"debounce\", failAfter: 3, recoverAfter: 2 };\nconst DEFAULT_JITTER = 0.1;\n\nconst ms = (amount: Quantity): number => valueIn(amount, \"ms\");\nconst isTimeAtLeast = (value: unknown, floor: number, strict: boolean): boolean => isTime(value) && (strict ? ms(value) > floor : ms(value) >= floor);\nconst whole = (value: number): boolean => Number.isInteger(value) && value >= 1;\n\n/** This function gives the problems of a watch spec: each value that the watcher cannot use. */\nexport const watchProblems = (spec: WatchSpec): string[] => {\n const problems: string[] = [];\n if (spec.targets.length === 0) problems.push(\"the spec has no target\");\n const names = new Set<string>();\n for (const target of spec.targets) {\n const of = `the target ${JSON.stringify(target.name)}`;\n if (target.name === \"\") problems.push(\"a target name is empty\");\n if (names.has(target.name)) problems.push(`${of} is in the spec two times`);\n names.add(target.name);\n problems.push(...probeProblems(target.probe).map((problem) => `${of}: ${problem}`));\n if (!isTimeAtLeast(target.interval, 0, true)) problems.push(`${of}: the interval is not a time above zero`);\n if (!isTimeAtLeast(target.timeout, 0, true)) problems.push(`${of}: the timeout is not a time above zero`);\n else if (isTimeAtLeast(target.interval, 0, true) && ms(target.timeout) > ms(target.interval)) problems.push(`${of}: the timeout is above the interval`);\n const jitter = target.jitter ?? DEFAULT_JITTER;\n if (!(Number.isFinite(jitter) && jitter >= 0 && jitter < 1)) problems.push(`${of}: the jitter ${jitter} is not a fraction from 0 to below 1`);\n const verdict = target.verdict ?? DEFAULT_VERDICT;\n if (verdict.type === \"debounce\") {\n if (!whole(verdict.failAfter)) problems.push(`${of}: the verdict fails after ${verdict.failAfter} polls, not a whole number above zero`);\n if (!whole(verdict.recoverAfter)) problems.push(`${of}: the verdict recovers after ${verdict.recoverAfter} polls, not a whole number above zero`);\n } else if (verdict.type === \"window\") {\n if (!isTimeAtLeast(verdict.failAfter, 0, false)) problems.push(`${of}: the failAfter of the window is not a time of zero or more`);\n if (verdict.recoverAfter !== undefined && !isTimeAtLeast(verdict.recoverAfter, 0, false))\n problems.push(`${of}: the recoverAfter of the window is not a time of zero or more`);\n } else problems.push(`${of}: the verdict type ${JSON.stringify((verdict as { type: unknown }).type)} is not debounce or window`);\n }\n return problems;\n};\n\nconst timingOf = (target: WatchTarget): Timing => {\n const verdict = target.verdict ?? DEFAULT_VERDICT;\n return verdict.type === \"debounce\"\n ? { type: \"debounce\", interval: target.interval, failAfter: verdict.failAfter, recoverAfter: verdict.recoverAfter }\n : { type: \"window\", failAfter: verdict.failAfter, recoverAfter: verdict.recoverAfter };\n};\n\ninterface Unit {\n readonly target: WatchTarget;\n health: TargetHealth;\n since: number;\n last: ProbeResult | null;\n lastAt: number | null;\n failures: number;\n /** This text is the reason of the latest failed poll. */\n why: string | null;\n}\n\n/**\n * This function starts a watcher of targets: an outside prober. Each target has its own loop of polls, on the\n * clock of the ports, with a jitter. A verdict turns the polls into the health of the target: a debounce or a\n * window. A target is `unknown` at the start. Its first pass makes it up, and its verdict makes it down. Each change\n * goes to `onChange`, with the reason of the latest failed poll. The watcher throws at the start when the spec has a\n * problem.\n */\nexport const watchTargets = (spec: WatchSpec, ports: HostPorts, options: WatchOptions): TargetWatch => {\n const problems = watchProblems(spec);\n if (problems.length > 0) throw new Error(`the watch spec has problems: ${problems.join(\"; \")}`);\n const random = options.random ?? Math.random;\n let stopped = false;\n\n const emit = (unit: Unit, to: \"up\" | \"down\"): void => {\n if (unit.health === to) return;\n const change: TargetChange = { target: unit.target.name, from: unit.health, to, at: ports.wall(), why: to === \"down\" ? unit.why : null };\n unit.health = to;\n unit.since = change.at;\n if (stopped) return;\n try {\n options.onChange(change);\n } catch (error) {\n ports.logger?.log(\"warn\", `the change handler of the watch failed: ${error instanceof Error ? error.message : String(error)}`, { target: change.target });\n }\n };\n\n const watched = spec.targets.map((target): { readonly unit: Unit; readonly gate: Latch; readonly loop: Poller } => {\n const unit: Unit = { target, health: \"unknown\", since: ports.wall(), last: null, lastAt: null, failures: 0, why: null };\n const trace: Trace | undefined = options.trace === undefined ? undefined : (from, to, on) => options.trace?.(target.name, from, to, on);\n const timeout = ms(target.timeout);\n // the result of the latest probe: a poller result tells only the outcome\n let probed: ProbeResult | null = null;\n const gate: Latch = latch(timingOf(target), ports.clock, false, () => emit(unit, gate.tripped ? \"down\" : \"up\"), trace);\n const record = (result: Result): void => {\n const own = probed;\n probed = null;\n // a timeout or a pending call has the cause of the poller: the probe gave no result for this poll\n const seen: ProbeResult =\n result.outcome === \"ok\" ? { ok: true } : { ok: false, why: !result.timedOut && own !== null && !own.ok ? own.why : (result.cause ?? \"the poll failed\") };\n unit.last = seen;\n unit.lastAt = ports.wall();\n unit.failures = seen.ok ? 0 : unit.failures + 1;\n if (!seen.ok) unit.why = seen.why;\n gate.record(result);\n if (seen.ok && unit.health === \"unknown\" && !gate.tripped) emit(unit, \"up\");\n };\n const loop = poller({\n name: target.name,\n poll: { interval: target.interval, jitter: target.jitter ?? DEFAULT_JITTER, timeout: target.timeout },\n run: async () => {\n const result = await probeOnce(target.probe, timeout, ports);\n probed = result;\n return result.ok ? \"ok\" : \"error\";\n },\n clock: ports.clock,\n random,\n forced: () => false,\n record,\n trace,\n });\n return { unit, gate, loop };\n });\n\n const states = (): TargetState[] =>\n watched.map(({ unit }) => ({ name: unit.target.name, health: unit.health, since: unit.since, last: unit.last, lastAt: unit.lastAt, failures: unit.failures }));\n\n for (const { loop } of watched) loop.start(0);\n\n return {\n states,\n async pollNow() {\n await Promise.all(watched.map(({ loop }) => loop.pollNow()));\n return states();\n },\n stop() {\n if (stopped) return;\n stopped = true;\n for (const { gate, loop } of watched) {\n loop.stop();\n gate.stop();\n }\n },\n };\n};\n","/** An env file is the variables of a file of environment variables, and the problem of each line that it skipped. */\nexport interface EnvFile {\n readonly env: Readonly<Record<string, string>>;\n readonly problems: readonly string[];\n}\n\nconst KEY = /^[A-Za-z_][A-Za-z0-9_]*$/;\n\n/** This function reads a value in double quotes: `\\n`, `\\t`, `\\\"` and `\\\\` are escapes. */\nconst doubleQuoted = (body: string): string =>\n body.replace(/\\\\(.)/g, (_match, char: string) => (char === \"n\" ? \"\\n\" : char === \"t\" ? \"\\t\" : char === \"r\" ? \"\\r\" : char));\n\n/**\n * This function reads a file of environment variables, one `KEY=value` on each line. It is a pure\n * function. It does not throw: it skips a bad line and gives its problem.\n * - A blank line and a line that starts with `#` are skipped. A line can start with `export `.\n * - A value in single quotes is literal. A value in double quotes has the escapes `\\n`, `\\t`, `\\\"` and `\\\\`.\n * - A value without quotes ends at ` #`, and its spaces at the two ends go.\n * - A key that comes again replaces its value.\n */\nexport const parseEnvFile = (text: string): EnvFile => {\n const env: Record<string, string> = {};\n const problems: string[] = [];\n // a byte order mark at the start is not a part of the first key\n const lines = (text.charCodeAt(0) === 0xfeff ? text.slice(1) : text).split(/\\r?\\n/);\n lines.forEach((raw, at) => {\n const line = raw.trim();\n if (line === \"\" || line.startsWith(\"#\")) return;\n const body = line.startsWith(\"export \") ? line.slice(\"export \".length).trimStart() : line;\n const equals = body.indexOf(\"=\");\n if (equals <= 0) {\n problems.push(`line ${at + 1} has no KEY=value`);\n return;\n }\n const key = body.slice(0, equals).trim();\n if (!KEY.test(key)) {\n problems.push(`line ${at + 1}: ${JSON.stringify(key)} is not a name of a variable`);\n return;\n }\n const rest = body.slice(equals + 1).trim();\n const quote = rest[0];\n if (quote === '\"' || quote === \"'\") {\n const end = quote === \"'\" ? rest.indexOf(\"'\", 1) : closingQuote(rest);\n if (end < 0) {\n problems.push(`line ${at + 1}: the value of ${key} has no closing quote`);\n return;\n }\n env[key] = quote === \"'\" ? rest.slice(1, end) : doubleQuoted(rest.slice(1, end));\n return;\n }\n const comment = rest.search(/\\s#/);\n env[key] = (comment < 0 ? rest : rest.slice(0, comment)).trim();\n });\n return { env, problems };\n};\n\n/** This function gives the place of the double quote that closes a value, or -1. A quote after a backslash does not close it. */\nconst closingQuote = (text: string): number => {\n for (let at = 1; at < text.length; at += 1) {\n if (text[at] === \"\\\\\") at += 1;\n else if (text[at] === '\"') return at;\n }\n return -1;\n};\n","import type { Quantity } from \"@mark1russell7/quantity\";\nimport { valueIn } from \"@mark1russell7/quantity\";\nimport type { FilePort } from \"./ports.ts\";\n\n/** A log spec tells where the output of a program goes, and when the file rotates. */\nexport interface LogSpec {\n /** This path is the log file. */\n readonly path: string;\n /** This size is the most that the file gets before it rotates, for example `{ value: 10, unit: \"MB\" }`. */\n readonly maxSize: Quantity;\n /** This count is the number of old files that stay: `<path>.1` is the newest. 0 keeps no old file. */\n readonly keep: number;\n}\n\n/** A rotating log writes data to a file, and rotates the file at its size. */\nexport interface RotatingLog {\n /** This method adds data to the log. The writes occur in sequence. A failed write does not throw. */\n write(chunk: string | Uint8Array): void;\n /** This promise ends when each write before it is done. */\n flush(): Promise<void>;\n /** This count is the number of writes that failed. */\n readonly failures: number;\n}\n\nconst byteLength = (chunk: string | Uint8Array): number => (typeof chunk === \"string\" ? new TextEncoder().encode(chunk).length : chunk.length);\n\n/**\n * This function makes a rotating log on a file port. Before a write that makes the file larger than\n * `maxSize`, the file rotates: `<path>.<keep>` goes, each `<path>.<n>` becomes `<path>.<n + 1>`, and the\n * file becomes `<path>.1`. A chunk larger than the size goes into a new file of its own.\n */\nexport const rotatingLog = (spec: LogSpec, files: FilePort): RotatingLog => {\n const max = valueIn(spec.maxSize, \"B\");\n let chain: Promise<void> = Promise.resolve();\n let size: number | null = null;\n let failures = 0;\n const rotate = async (): Promise<void> => {\n if (spec.keep <= 0) {\n await files.remove(spec.path);\n return;\n }\n await files.remove(`${spec.path}.${spec.keep}`);\n for (let at = spec.keep - 1; at >= 1; at -= 1)\n if ((await files.size(`${spec.path}.${at}`)) !== null) await files.rename(`${spec.path}.${at}`, `${spec.path}.${at + 1}`);\n await files.rename(spec.path, `${spec.path}.1`);\n };\n const append = async (chunk: string | Uint8Array): Promise<void> => {\n const length = byteLength(chunk);\n size ??= (await files.size(spec.path)) ?? 0;\n if (size > 0 && size + length > max) {\n await rotate();\n size = 0;\n }\n await files.append(spec.path, chunk);\n size += length;\n };\n return {\n write(chunk) {\n chain = chain.then(() => append(chunk)).catch(() => {\n failures += 1;\n // the size is not known after a failure: the next write reads it again\n size = null;\n });\n },\n flush: () => chain,\n get failures() {\n return failures;\n },\n };\n};\n","import type { Quantity } from \"@mark1russell7/quantity\";\nimport { convertible, isQuantity, valueIn } from \"@mark1russell7/quantity\";\nimport type { Backoff } from \"../backoff.ts\";\nimport { backoffProblems } from \"../backoff.ts\";\nimport type { Cancel } from \"../clock.ts\";\nimport type { LogFields, LogLevel } from \"../logger.ts\";\nimport type { MessageShape } from \"../process.ts\";\nimport { isMessageShape } from \"../process.ts\";\nimport type { Retrier } from \"../retrier.ts\";\nimport { retrier } from \"../retrier.ts\";\nimport { removeDiscovery, writeDiscovery } from \"./discovery.ts\";\nimport { parseEnvFile } from \"./env.ts\";\nimport type { InstanceLock } from \"./lock.ts\";\nimport { acquireInstanceLock } from \"./lock.ts\";\nimport type { LogSpec, RotatingLog } from \"./logs.ts\";\nimport { rotatingLog } from \"./logs.ts\";\nimport type { ChildHandle, HostPorts } from \"./ports.ts\";\nimport { joinPath } from \"./ports.ts\";\nimport type { ReadyProbe } from \"./probes.ts\";\nimport { probeOnce, probeProblems } from \"./probes.ts\";\nimport { stopTree } from \"./processes.ts\";\nimport { isTime } from \"./render.ts\";\n\n/** A ready spec tells how the supervisor finds that a program is ready. */\nexport interface ReadySpec {\n readonly probe: ReadyProbe;\n /** This time is the pause between two uses of the probe. */\n readonly interval: Quantity;\n /** This time is the most that one use of the probe can take. */\n readonly timeout: Quantity;\n /** This time is the most that the program can take to be ready. After it, the supervisor stops the program and starts it again. */\n readonly within: Quantity;\n}\n\n/**\n * An alive spec tells how the supervisor finds that a ready program still works. A program can hang and not exit:\n * its process stays, and only a probe finds it. After `failures` failures in sequence, the supervisor stops the\n * program in stages and starts it again after its backoff.\n */\nexport interface AliveSpec {\n readonly probe: ReadyProbe;\n /** This time is the pause between two uses of the probe. The first use is one interval after the program is ready. */\n readonly interval: Quantity;\n /** This time is the most that one use of the probe can take. */\n readonly timeout: Quantity;\n /** This count of failures in sequence stops the program: a whole number of 1 or more. A pass sets the count to 0. */\n readonly failures: number;\n}\n\n/** A program restart tells how the supervisor starts a program again after it stops. */\nexport interface ProgramRestart {\n /** This backoff gives the wait before each start again, in milliseconds, as `retrier` uses it. */\n readonly backoff: Backoff;\n /** This time is how long a program is ready before its count of tries goes back to 0. */\n readonly resetAfter: Quantity;\n}\n\n/** A stop spec tells how the supervisor stops a program. */\nexport interface StopSpec {\n /** This time is the wait for the staged stop, before the supervisor stops the process tree. */\n readonly grace: Quantity;\n /** This message goes on the IPC channel of a child that has one. The default is `\"shutdown\"`, which `run()` can match. */\n readonly message?: MessageShape | undefined;\n /** This signal goes to a child without an IPC channel on Linux. The default is `SIGTERM`. */\n readonly signal?: \"SIGINT\" | \"SIGTERM\" | undefined;\n}\n\n/** A program spec tells one program of a group, and what it needs before it starts. */\nexport interface ProgramSpec {\n /** This name is the name of the program in the group: letters, digits, `.`, `_` and `-`. */\n readonly name: string;\n readonly program: string;\n readonly args?: readonly string[] | undefined;\n readonly cwd?: string | undefined;\n /** These variables go to the program. They replace the variables of the env file and of the host. */\n readonly env?: Readonly<Record<string, string>> | undefined;\n /** This file gives variables to the program at each start (`parseEnvFile`). They replace the variables of the host. */\n readonly envFile?: string | undefined;\n /** These are the programs that must be ready before this program starts. */\n readonly after?: readonly string[] | undefined;\n /** This spec tells when the program is ready. Without it, the program is ready when it starts. */\n readonly ready?: ReadySpec | undefined;\n /** This spec tells how the supervisor finds that the ready program still works. Without it, only an exit starts the program again. */\n readonly alive?: AliveSpec | undefined;\n /** This policy starts the program again after it stops. The default is `DEFAULT_RESTART`. Null does not start it again. */\n readonly restart?: ProgramRestart | null | undefined;\n /** This spec tells the log file. The default is `<stateDir>/logs/<name>.log`, 10 MB, with 3 old files. Null keeps no log. */\n readonly log?: LogSpec | null | undefined;\n /** True gives the child an IPC channel, for the staged stop of a Node program. The default is false. */\n readonly ipc?: boolean | undefined;\n /** This spec tells the stop. The default is a grace of 10 s. */\n readonly stop?: StopSpec | undefined;\n /** These fields go in the discovery file of the program, `<stateDir>/<name>.json`. */\n readonly listen?: { readonly port?: number | null | undefined; readonly url?: string | null | undefined } | undefined;\n}\n\n/** A group spec tells a group of programs that one supervisor starts in sequence and keeps alive. */\nexport interface GroupSpec {\n readonly name: string;\n /** This folder keeps the lock, the discovery file and the log of each program. */\n readonly stateDir: string;\n readonly programs: readonly ProgramSpec[];\n}\n\n/** These options go with a supervisor. */\nexport interface GroupOptions {\n /** This function gives a number in [0, 1) for the jitter of the backoff. The default is `Math.random`. */\n readonly random?: (() => number) | undefined;\n}\n\n/**\n * A program phase tells where a program of a group is.\n * - `waiting`: a program that it needs is not ready.\n * - `starting`: it runs, and its probe did not pass.\n * - `ready`: it runs, and its probe passed.\n * - `backoff`: it stopped, and it starts again after its backoff.\n * - `held`: another instance holds its lock. The supervisor tries again after the backoff.\n * - `exited`: it stopped, and it has no restart.\n * - `stopping`, `stopped`: the stop of the group.\n */\nexport type ProgramPhase = \"waiting\" | \"starting\" | \"ready\" | \"backoff\" | \"held\" | \"exited\" | \"stopping\" | \"stopped\";\n\n/** A program state is the state of one program of a group, for a status. */\nexport interface ProgramState {\n readonly name: string;\n readonly phase: ProgramPhase;\n /** This number is the process ID of the child, or null. */\n readonly pid: number | null;\n /** This count is the number of starts again since the start of the group. */\n readonly restarts: number;\n /** This text tells the last problem, for example why the probe failed, or it is null. */\n readonly detail: string | null;\n}\n\n/** A group supervisor starts the programs of a group in sequence, starts each again after it stops, and stops them in stages. */\nexport interface GroupSupervisor {\n /** This method starts each program whose programs are ready. A second use does nothing. */\n start(): void;\n /** This method stops each program in the reverse sequence of the start. A second use gives the same promise. */\n stop(): Promise<void>;\n /** This method gives the state of each program, in the sequence of the spec. */\n states(): readonly ProgramState[];\n}\n\n/**\n * This restart is the default. The first wait is 1 s, and each wait after it is two times longer, to 1 min.\n * The jitter subtracts up to half of each wait. The count of tries goes back to 0 after 1 min ready.\n */\nexport const DEFAULT_RESTART: ProgramRestart = {\n backoff: { base: 1000, factor: 2, cap: 60_000, jitter: { kind: \"subtract\", fraction: 0.5 } },\n resetAfter: { value: 60, unit: \"s\" },\n};\n\nconst DEFAULT_GRACE: Quantity = { value: 10, unit: \"s\" };\nconst DEFAULT_LOG_SIZE: Quantity = { value: 10, unit: \"MB\" };\nconst DEFAULT_LOG_KEEP = 3;\nconst NAME = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;\n\nconst ms = (time: Quantity): number => valueIn(time, \"ms\");\n\n/**\n * This function gives the start sequence of a group, as layers of names. Each program of a layer needs only programs of the\n * layers before it. A program in a cycle, or after an unknown program, is in no layer. `groupProblems` names it.\n */\nexport const startOrder = (spec: GroupSpec): string[][] => {\n const names = new Set(spec.programs.map((program) => program.name));\n const placed = new Set<string>();\n const layers: string[][] = [];\n for (;;) {\n const layer = spec.programs\n .filter((program) => !placed.has(program.name))\n .filter((program) => (program.after ?? []).every((name) => names.has(name) && placed.has(name)))\n .map((program) => program.name);\n if (layer.length === 0) return layers;\n for (const name of layer) placed.add(name);\n layers.push([...new Set(layer)]);\n }\n};\n\nconst isTimeAtLeast = (value: unknown, floor: number, strict: boolean): boolean =>\n isTime(value) && (strict ? ms(value) > floor : ms(value) >= floor);\n\n/** This function gives the problems of a group spec: each value that the supervisor cannot use. */\nexport const groupProblems = (spec: GroupSpec): string[] => {\n const problems: string[] = [];\n if (!NAME.test(spec.name)) problems.push(`the group name ${JSON.stringify(spec.name)} is not letters, digits, \".\", \"_\" and \"-\"`);\n if (spec.stateDir === \"\") problems.push(\"the stateDir is empty\");\n if (spec.programs.length === 0) problems.push(\"the group has no programs\");\n const seen = new Set<string>();\n const names = new Set(spec.programs.map((program) => program.name));\n for (const program of spec.programs) {\n const name = program.name;\n const of = `the program ${JSON.stringify(name)}`;\n if (!NAME.test(name)) problems.push(`${of}: the name is not letters, digits, \".\", \"_\" and \"-\"`);\n if (seen.has(name)) problems.push(`${of} comes two times`);\n seen.add(name);\n if (program.program === \"\") problems.push(`${of}: the program is empty`);\n for (const need of program.after ?? []) {\n if (need === name) problems.push(`${of} is after itself`);\n else if (!names.has(need)) problems.push(`${of} is after ${JSON.stringify(need)}, which is not in the group`);\n }\n if (program.ready !== undefined) {\n problems.push(...probeProblems(program.ready.probe).map((problem) => `${of}: ${problem}`));\n for (const field of [\"interval\", \"timeout\", \"within\"] as const)\n if (!isTimeAtLeast(program.ready[field], 0, true)) problems.push(`${of}: the ${field} of the probe is not a time above zero`);\n }\n if (program.alive !== undefined) {\n problems.push(...probeProblems(program.alive.probe).map((problem) => `${of}: the liveness probe: ${problem}`));\n for (const field of [\"interval\", \"timeout\"] as const)\n if (!isTimeAtLeast(program.alive[field], 0, true)) problems.push(`${of}: the ${field} of the liveness probe is not a time above zero`);\n if (!(Number.isInteger(program.alive.failures) && program.alive.failures >= 1))\n problems.push(`${of}: the failures of the liveness probe is not a whole number of 1 or more`);\n }\n if (program.restart !== undefined && program.restart !== null) {\n problems.push(...backoffProblems(program.restart.backoff).map((problem) => `${of}: ${problem}`));\n if (!isTimeAtLeast(program.restart.resetAfter, 0, false)) problems.push(`${of}: the resetAfter is not a time of zero or more`);\n }\n if (program.log !== undefined && program.log !== null) {\n const size = program.log.maxSize;\n if (!(isQuantity(size) && convertible(size.unit, \"B\") && valueIn(size, \"B\") > 0)) problems.push(`${of}: the maxSize of the log is not a size above zero`);\n if (!(Number.isInteger(program.log.keep) && program.log.keep >= 0)) problems.push(`${of}: the keep of the log is not a whole number of zero or more`);\n if (program.log.path === \"\") problems.push(`${of}: the path of the log is empty`);\n }\n if (program.stop !== undefined) {\n if (!isTimeAtLeast(program.stop.grace, 0, false)) problems.push(`${of}: the grace of the stop is not a time of zero or more`);\n if (program.stop.message !== undefined && !isMessageShape(program.stop.message)) problems.push(`${of}: the stop message is not a value of JSON`);\n const signal = program.stop.signal;\n if (signal !== undefined && signal !== \"SIGINT\" && signal !== \"SIGTERM\") problems.push(`${of}: the stop signal ${JSON.stringify(signal)} is not SIGINT or SIGTERM`);\n }\n const port = program.listen?.port;\n if (port !== undefined && port !== null && !(Number.isInteger(port) && port >= 1 && port <= 65_535))\n problems.push(`${of}: the port ${port} is not a port from 1 to 65535`);\n }\n const placed = new Set(startOrder(spec).flat());\n const left = spec.programs.filter((program) => !placed.has(program.name) && (program.after ?? []).every((need) => names.has(need) && need !== program.name));\n if (left.length > 0) problems.push(`the programs ${left.map((program) => JSON.stringify(program.name)).join(\", \")} are in a cycle of \"after\", or after a program in one`);\n return problems;\n};\n\n/** The supervisor keeps one unit for each program: its spec, its files and its state. */\ninterface Unit {\n readonly spec: ProgramSpec;\n readonly lockPath: string;\n readonly discoveryPath: string;\n readonly log: RotatingLog | null;\n readonly retry: Retrier | null;\n phase: ProgramPhase;\n child: ChildHandle | null;\n lock: InstanceLock | null;\n timers: Cancel[];\n /** This cancel stops the next use of the liveness probe. It is one timer, thus a long life adds no timers. */\n watch: Cancel | null;\n restarts: number;\n detail: string | null;\n /** This text tells why the supervisor stopped the child, or it is null. */\n reason: string | null;\n waiters: Array<() => void>;\n}\n\n/**\n * This function makes the supervisor of a group. It refuses a spec with problems. Each effect goes\n * through the ports, thus a test gives `fakeHost()` and starts no process.\n * - A program starts when each program of its `after` is ready. It takes its lock first, thus a second instance does not start.\n * - A program with a probe is ready when its probe passes. A program that is not ready in `within` stops, and starts again.\n * - A program that stops starts again after the backoff of its `retrier`, when its programs are ready.\n * - Its output goes to its rotating log. Its environment is the host, then its env file, then its `env`.\n * - The stop goes in the reverse sequence: the staged stop first, and after the grace, the stop of the process tree by its ID.\n */\nexport const superviseGroup = (spec: GroupSpec, ports: HostPorts, options: GroupOptions = {}): GroupSupervisor => {\n const problems = groupProblems(spec);\n if (problems.length > 0) throw new Error(`the group ${spec.name} has problems: ${problems.join(\"; \")}`);\n const abort = new AbortController();\n const layers = startOrder(spec);\n let started = false;\n let stopping = false;\n let stopped: Promise<void> | null = null;\n\n const say = (level: LogLevel, message: string, fields: LogFields): void => {\n try {\n ports.logger?.log(level, message, { group: spec.name, ...fields });\n } catch {\n // the supervisor does not depend on its logger\n }\n };\n\n const units = new Map<string, Unit>();\n for (const program of spec.programs) {\n const restart = program.restart === undefined ? DEFAULT_RESTART : program.restart;\n const logSpec =\n program.log === undefined\n ? { path: joinPath(ports.platform, spec.stateDir, \"logs\", `${program.name}.log`), maxSize: DEFAULT_LOG_SIZE, keep: DEFAULT_LOG_KEEP }\n : program.log;\n units.set(program.name, {\n spec: program,\n lockPath: joinPath(ports.platform, spec.stateDir, `${program.name}.lock`),\n discoveryPath: joinPath(ports.platform, spec.stateDir, `${program.name}.json`),\n log: logSpec === null ? null : rotatingLog(logSpec, ports.files),\n retry:\n restart === null\n ? null\n : retrier({ ...restart.backoff, clock: ports.clock, signal: abort.signal, ...(options.random === undefined ? {} : { random: options.random }) }),\n phase: \"waiting\",\n child: null,\n lock: null,\n timers: [],\n watch: null,\n restarts: 0,\n detail: null,\n reason: null,\n waiters: [],\n });\n }\n const unitOf = (name: string): Unit => units.get(name)!;\n\n const clearTimers = (unit: Unit): void => {\n for (const cancel of unit.timers.splice(0)) cancel();\n unit.watch?.();\n unit.watch = null;\n };\n\n const environment = async (unit: Unit): Promise<Record<string, string>> => {\n const env: Record<string, string> = {};\n for (const [key, value] of Object.entries(ports.env)) if (value !== undefined) env[key] = value;\n const file = unit.spec.envFile;\n if (file !== undefined) {\n try {\n const text = await ports.files.read(file);\n if (text === null) say(\"warn\", `the env file ${file} of ${unit.spec.name} does not exist`, { program: unit.spec.name, file });\n else {\n const parsed = parseEnvFile(text);\n Object.assign(env, parsed.env);\n for (const problem of parsed.problems) say(\"warn\", `the env file ${file} of ${unit.spec.name}: ${problem}`, { program: unit.spec.name, file });\n }\n } catch (error) {\n say(\"warn\", `the read of the env file ${file} of ${unit.spec.name} failed`, { program: unit.spec.name, file, error });\n }\n }\n return Object.assign(env, unit.spec.env ?? {});\n };\n\n const consider = (unit: Unit): void => {\n if (!started || stopping || unit.phase !== \"waiting\") return;\n if (!(unit.spec.after ?? []).every((name) => unitOf(name).phase === \"ready\")) return;\n void launch(unit);\n };\n const considerAll = (): void => {\n for (const layer of layers) for (const name of layer) consider(unitOf(name));\n };\n\n /** This function starts the program again after the backoff, or ends it when it has no restart. */\n const later = (unit: Unit, phase: \"backoff\" | \"held\"): void => {\n const delay = unit.retry?.schedule(() => {\n if (stopping) return;\n unit.phase = \"waiting\";\n unit.restarts += 1;\n consider(unit);\n });\n if (delay === undefined || delay === null) {\n unit.phase = phase === \"held\" ? \"held\" : \"exited\";\n void unit.lock?.release();\n unit.lock = null;\n return;\n }\n unit.phase = phase;\n say(\"info\", `${unit.spec.name} starts again in ${delay} ms`, { program: unit.spec.name, delay: { value: delay, unit: \"ms\" }, attempt: unit.retry?.attempts });\n };\n\n const markReady = (unit: Unit, child: ChildHandle): void => {\n if (unit.child !== child || stopping) return;\n unit.phase = \"ready\";\n unit.detail = null;\n say(\"info\", `${unit.spec.name} is ready`, { program: unit.spec.name, pid: child.pid });\n const restart = unit.spec.restart === undefined ? DEFAULT_RESTART : unit.spec.restart;\n if (unit.retry !== null && restart !== null)\n unit.timers.push(\n ports.clock.after(ms(restart.resetAfter), () => {\n if (unit.child === child && unit.phase === \"ready\") unit.retry?.reset();\n }),\n );\n if (unit.spec.alive !== undefined) watch(unit, child, unit.spec.alive);\n considerAll();\n };\n\n /** This function uses the liveness probe of a ready program each interval, and stops the program after `failures` failures in sequence. */\n const watch = (unit: Unit, child: ChildHandle, alive: AliveSpec): void => {\n let failures = 0;\n const current = (): boolean => unit.child === child && unit.phase === \"ready\" && !stopping;\n const next = (): void => {\n unit.watch = ports.clock.after(ms(alive.interval), () => {\n unit.watch = null;\n void check();\n });\n };\n const check = async (): Promise<void> => {\n if (!current()) return;\n const result = await probeOnce(alive.probe, ms(alive.timeout), ports);\n if (!current()) return;\n if (result.ok) {\n if (failures > 0) say(\"info\", `${unit.spec.name} is alive again`, { program: unit.spec.name, pid: child.pid, failures });\n failures = 0;\n unit.detail = null;\n next();\n return;\n }\n failures += 1;\n unit.detail = `the liveness probe failed ${failures} of ${alive.failures} times in sequence (${result.why})`;\n if (failures < alive.failures) {\n say(\"warn\", `${unit.spec.name}: ${unit.detail}`, { program: unit.spec.name, pid: child.pid, why: result.why });\n next();\n return;\n }\n unit.reason = `its liveness probe failed ${failures} times in sequence (${result.why})`;\n unit.detail = unit.reason;\n say(\"warn\", `${unit.spec.name} is not alive, thus it stops`, { program: unit.spec.name, pid: child.pid, why: result.why });\n void stagedStop(unit, child);\n };\n next();\n };\n\n const probe = (unit: Unit, child: ChildHandle, ready: ReadySpec): void => {\n const deadline = ports.clock.now() + ms(ready.within);\n const attempt = async (): Promise<void> => {\n if (unit.child !== child || stopping) return;\n const result = await probeOnce(ready.probe, ms(ready.timeout), ports);\n if (unit.child !== child || stopping) return;\n if (result.ok) {\n markReady(unit, child);\n return;\n }\n unit.detail = result.why;\n if (ports.clock.now() >= deadline) {\n unit.reason = `it was not ready in ${ms(ready.within)} ms (${result.why})`;\n unit.detail = unit.reason;\n say(\"warn\", `${unit.spec.name} is not ready in its time, thus it stops`, { program: unit.spec.name, pid: child.pid, why: result.why });\n void stagedStop(unit, child);\n return;\n }\n unit.timers.push(ports.clock.after(ms(ready.interval), () => void attempt()));\n };\n void attempt();\n };\n\n const exited = (unit: Unit, child: ChildHandle, code: number | null, signal: string | null): void => {\n if (unit.child !== child) return;\n clearTimers(unit);\n unit.child = null;\n for (const waiter of unit.waiters.splice(0)) waiter();\n if (child.pid !== null) void removeDiscovery(unit.discoveryPath, ports, child.pid);\n void unit.lock?.update(null).catch(() => {});\n if (stopping || unit.phase === \"stopping\") {\n unit.phase = \"stopped\";\n return;\n }\n const end = child.pid === null ? `${unit.spec.program} did not start` : `it exited with ${code === null ? `the signal ${signal ?? \"unknown\"}` : `the code ${code}`}`;\n unit.detail = unit.reason === null ? end : `${unit.reason}, then ${end}`;\n unit.reason = null;\n say(\"warn\", `${unit.spec.name} stopped: ${unit.detail}`, { program: unit.spec.name, pid: child.pid, code, signal });\n later(unit, \"backoff\");\n };\n\n const launch = async (unit: Unit): Promise<void> => {\n unit.phase = \"starting\";\n unit.detail = null;\n const name = unit.spec.name;\n if (unit.lock === null) {\n const taken = await acquireInstanceLock(unit.lockPath, ports);\n if (stopping) {\n if (taken.kind === \"acquired\") await taken.lock.release();\n return;\n }\n if (taken.kind !== \"acquired\") {\n unit.detail = taken.kind === \"held\" ? `the process ${taken.owner.child?.pid ?? taken.owner.pid} holds the lock ${unit.lockPath}` : taken.problem;\n say(\"warn\", `${name} does not start: ${unit.detail}`, { program: name, lock: unit.lockPath });\n later(unit, \"held\");\n return;\n }\n unit.lock = taken.lock;\n }\n const lock = unit.lock;\n const env = await environment(unit);\n if (stopping) {\n await lock.release();\n unit.lock = null;\n return;\n }\n const child = ports.processes.spawn({ program: unit.spec.program, args: unit.spec.args ?? [], cwd: unit.spec.cwd, env, ipc: unit.spec.ipc ?? false });\n const startedAt = ports.wall();\n unit.child = child;\n child.onOutput((_stream, chunk) => unit.log?.write(chunk));\n child.onExit((code, signal) => exited(unit, child, code, signal));\n const pid = child.pid;\n if (pid === null) return;\n say(\"info\", `${name} started`, { program: name, pid });\n const mark = { pid, startedAt };\n try {\n await lock.update(mark);\n await writeDiscovery(\n unit.discoveryPath,\n { pid, startedAt: new Date(startedAt).toISOString(), port: unit.spec.listen?.port ?? null, url: unit.spec.listen?.url ?? null, extra: { group: spec.name, program: name } },\n ports,\n );\n } catch (error) {\n say(\"warn\", `the files of ${name} were not written`, { program: name, error });\n }\n // a child that ended during the writes leaves no discovery file\n if (unit.child !== child) await removeDiscovery(unit.discoveryPath, ports, pid);\n if (unit.child !== child || stopping) return;\n if (unit.spec.ready === undefined) markReady(unit, child);\n else probe(unit, child, unit.spec.ready);\n };\n\n /** This function waits for the end of a child, for at most `wait` milliseconds. It tells if the child ended. */\n const ended = (unit: Unit, child: ChildHandle, wait: number): Promise<boolean> =>\n new Promise((resolve) => {\n if (unit.child !== child) {\n resolve(true);\n return;\n }\n const cancel = ports.clock.after(wait, () => resolve(unit.child !== child));\n unit.waiters.push(() => {\n cancel();\n resolve(true);\n });\n });\n\n /**\n * This function stops a child in stages. The message goes on its IPC channel when it has one. Else\n * Linux gets SIGTERM, and Windows gets `taskkill /T` without `/F`. After the grace, the process tree stops by its ID.\n */\n const stagedStop = async (unit: Unit, child: ChildHandle): Promise<void> => {\n const pid = child.pid;\n if (pid === null || unit.child !== child) return;\n const grace = ms(unit.spec.stop?.grace ?? DEFAULT_GRACE);\n const gone = ended(unit, child, grace);\n let asked: string | null = null;\n if (child.ipc && child.send(unit.spec.stop?.message ?? \"shutdown\")) asked = \"the IPC message\";\n else if (ports.platform === \"win32\") {\n const result = await ports.commands.run(\"taskkill\", [\"/T\", \"/PID\", String(pid)]).catch(() => null);\n if (result?.code === 0) asked = \"taskkill\";\n } else {\n const signal = unit.spec.stop?.signal ?? \"SIGTERM\";\n if (ports.processes.signal(pid, signal)) asked = signal;\n }\n say(\"info\", `${unit.spec.name} stops${asked === null ? \"\" : ` through ${asked}`}`, { program: unit.spec.name, pid, grace: { value: grace, unit: \"ms\" } });\n if (asked !== null && (await gone)) return;\n const tree = await stopTree(pid, ports);\n const why = asked === null ? \"the staged stop did not go\" : \"it did not stop in its grace\";\n say(tree.kind === \"failed\" ? \"error\" : \"warn\", `${unit.spec.name}: ${why}, thus its process tree stops: ${tree.kind}`, {\n program: unit.spec.name,\n pid,\n outcome: tree.kind,\n });\n if (!(await ended(unit, child, grace))) say(\"error\", `${unit.spec.name} did not end after the stop of its process tree`, { program: unit.spec.name, pid });\n };\n\n const stopUnit = async (unit: Unit): Promise<void> => {\n clearTimers(unit);\n const child = unit.child;\n const pid = child?.pid ?? null;\n if (child !== null && pid !== null) {\n unit.phase = \"stopping\";\n await stagedStop(unit, child);\n await removeDiscovery(unit.discoveryPath, ports, pid);\n }\n unit.phase = \"stopped\";\n await unit.lock?.release();\n unit.lock = null;\n };\n\n return {\n start() {\n if (started || stopping) return;\n started = true;\n say(\"info\", `the group ${spec.name} starts`, { layers });\n considerAll();\n },\n stop() {\n if (stopped !== null) return stopped;\n stopping = true;\n abort.abort();\n stopped = (async () => {\n for (const layer of [...layers].reverse()) await Promise.all(layer.map((name) => stopUnit(unitOf(name))));\n await Promise.all([...units.values()].map((unit) => unit.log?.flush()));\n say(\"info\", `the group ${spec.name} stopped`, {});\n })();\n return stopped;\n },\n states() {\n return spec.programs.map((program) => {\n const unit = unitOf(program.name);\n return { name: program.name, phase: unit.phase, pid: unit.child?.pid ?? null, restarts: unit.restarts, detail: unit.detail };\n });\n },\n };\n};\n","import type { Serializable } from \"node:child_process\";\nimport { execFile, spawn as spawnChild } from \"node:child_process\";\nimport { appendFile, mkdir, readFile, rename, rm, stat, writeFile } from \"node:fs/promises\";\nimport { connect } from \"node:net\";\nimport { homedir, userInfo } from \"node:os\";\nimport { dirname } from \"node:path\";\nimport type { Clock } from \"../clock.ts\";\nimport { realClock } from \"../clock.ts\";\nimport type { Logger } from \"../logger.ts\";\nimport type { ChildHandle, CommandPort, FilePort, HostPorts, HttpAnswer, NetPort, ProcessesPort, SpawnRequest, StopSignal } from \"./ports.ts\";\n\n/** These options go with the ports of Node. */\nexport interface NodeHostOptions {\n readonly logger?: Logger | undefined;\n /** This clock gives the time and the timers. The default is `realClock`. */\n readonly clock?: Clock | undefined;\n}\n\nconst codeOf = (error: unknown): string | undefined =>\n typeof error === \"object\" && error !== null && \"code\" in error ? String((error as { code: unknown }).code) : undefined;\n\nconst missing = (error: unknown): boolean => codeOf(error) === \"ENOENT\";\n\nconst nodeCommands: CommandPort = {\n run: (file, args, options = {}) =>\n new Promise((resolve) => {\n execFile(\n file,\n [...args],\n { ...(options.cwd === undefined ? {} : { cwd: options.cwd }), timeout: options.timeout ?? 0, windowsHide: true, encoding: \"utf8\", maxBuffer: 16 * 1024 * 1024 },\n (error, stdout, stderr) => {\n const out = `${stdout}${stderr}`;\n if (error === null) {\n resolve({ code: 0, out });\n return;\n }\n if (missing(error)) resolve({ code: 127, out: error.message });\n else if (error.killed === true && options.timeout !== undefined) resolve({ code: 124, out });\n else resolve({ code: typeof error.code === \"number\" ? error.code : 1, out: out === \"\" ? error.message : out });\n },\n );\n }),\n};\n\nlet serial = 0;\n\nconst nodeFiles: FilePort = {\n async read(path) {\n try {\n return await readFile(path, \"utf8\");\n } catch (error) {\n if (missing(error)) return null;\n throw error;\n }\n },\n async write(path, data) {\n await mkdir(dirname(path), { recursive: true });\n serial += 1;\n const temporary = `${path}.${process.pid}.${serial}.tmp`;\n await writeFile(temporary, data);\n try {\n await rename(temporary, path);\n } catch (error) {\n await rm(temporary, { force: true });\n throw error;\n }\n },\n async create(path, data) {\n await mkdir(dirname(path), { recursive: true });\n try {\n await writeFile(path, data, { flag: \"wx\" });\n return true;\n } catch (error) {\n if (codeOf(error) === \"EEXIST\") return false;\n throw error;\n }\n },\n async append(path, data) {\n await mkdir(dirname(path), { recursive: true });\n await appendFile(path, data);\n },\n async size(path) {\n try {\n return (await stat(path)).size;\n } catch (error) {\n if (missing(error)) return null;\n throw error;\n }\n },\n rename: (from, to) => rename(from, to),\n remove: (path) => rm(path, { force: true }),\n};\n\n/** This difference is the time from the start of the Windows file time (1601) to the start of the epoch (1970), in milliseconds. */\nconst FILETIME_EPOCH_MS = 11_644_473_600_000n;\n\n/**\n * This limit is the longest time of the query of a start time on Windows, in milliseconds. A cold start of PowerShell\n * on a loaded host can take more than 10 seconds (SYS-47). After the limit the start time is null, and the lock then\n * counts a live process ID as its owner. Thus a short limit can hold a stale lock, and the limit is wide.\n */\nconst WINDOWS_START_LIMIT_MS = 30_000;\n\n/** This function gives the start time of a Windows process from PowerShell, in milliseconds after the epoch, or null. */\nconst windowsStart = async (pid: number): Promise<number | null> => {\n const result = await nodeCommands.run(\n \"powershell.exe\",\n [\"-NoProfile\", \"-NonInteractive\", \"-Command\", `(Get-Process -Id ${pid} -ErrorAction Stop).StartTime.ToFileTimeUtc()`],\n { timeout: WINDOWS_START_LIMIT_MS },\n );\n const text = result.out.trim();\n if (result.code !== 0 || !/^\\d+$/.test(text)) return null;\n return Number(BigInt(text) / 10_000n - FILETIME_EPOCH_MS);\n};\n\n/** This count is the number of clock ticks in one second on Linux. It is 100 on each common kernel. */\nconst LINUX_TICKS = 100;\n\n/** This function gives the start time of a Linux process from `/proc`, in milliseconds after the epoch, or null. */\nconst linuxStart = async (pid: number): Promise<number | null> => {\n const record = await readFile(`/proc/${pid}/stat`, \"utf8\");\n // the name of the program is in parentheses and can have spaces: the fields start after the last \")\"\n const fields = record.slice(record.lastIndexOf(\")\") + 2).split(\" \");\n const ticks = Number(fields[19]);\n const boot = /^btime (\\d+)$/m.exec(await readFile(\"/proc/stat\", \"utf8\"));\n if (!Number.isFinite(ticks) || boot === null) return null;\n return Number(boot[1]) * 1000 + (ticks * 1000) / LINUX_TICKS;\n};\n\nconst sendSignal = (pid: number, signal: StopSignal | 0): boolean => {\n try {\n return process.kill(pid, signal);\n } catch {\n return false;\n }\n};\n\nconst nodeSpawn = (request: SpawnRequest): ChildHandle => {\n const outputs: Array<(stream: \"stdout\" | \"stderr\", chunk: string | Uint8Array) => void> = [];\n const exits: Array<(code: number | null, signal: string | null) => void> = [];\n let end: { code: number | null; signal: string | null } | null = null;\n const finish = (code: number | null, signal: string | null): void => {\n if (end !== null) return;\n end = { code, signal };\n for (const handler of exits) handler(code, signal);\n };\n const child = spawnChild(request.program, [...request.args], {\n ...(request.cwd === undefined ? {} : { cwd: request.cwd }),\n env: { ...request.env },\n stdio: request.ipc ? [\"ignore\", \"pipe\", \"pipe\", \"ipc\"] : [\"ignore\", \"pipe\", \"pipe\"],\n // on Linux the child leads its own process group, thus the tree stop reaches each process under it\n detached: process.platform !== \"win32\",\n windowsHide: true,\n });\n child.stdout?.on(\"data\", (chunk: Uint8Array) => {\n for (const handler of outputs) handler(\"stdout\", chunk);\n });\n child.stderr?.on(\"data\", (chunk: Uint8Array) => {\n for (const handler of outputs) handler(\"stderr\", chunk);\n });\n child.on(\"error\", () => {\n if (child.pid === undefined) finish(null, null);\n });\n child.on(\"exit\", (code, signal) => finish(code, signal));\n return {\n pid: child.pid ?? null,\n ipc: request.ipc,\n onOutput(handler) {\n outputs.push(handler);\n },\n onExit(handler) {\n exits.push(handler);\n if (end !== null) handler(end.code, end.signal);\n },\n send(message) {\n if (!child.connected) return false;\n try {\n return child.send(message as Serializable);\n } catch {\n return false;\n }\n },\n };\n};\n\nconst nodeProcesses: ProcessesPort = {\n alive(pid) {\n try {\n process.kill(pid, 0);\n return true;\n } catch (error) {\n // a process of a different user is alive, and the signal does not go to it\n return codeOf(error) === \"EPERM\";\n }\n },\n async startOf(pid) {\n try {\n if (process.platform === \"win32\") return await windowsStart(pid);\n if (process.platform === \"linux\") return await linuxStart(pid);\n return null;\n } catch {\n return null;\n }\n },\n signal: (pid, signal) => sendSignal(pid, signal),\n signalGroup: (pid, signal) => process.platform !== \"win32\" && sendSignal(-pid, signal),\n spawn: nodeSpawn,\n};\n\n/**\n * This function sends a GET request that does not follow a redirect. The timeout also stops the\n * read of the body. The status read and the text read use it, thus they have one timeout.\n */\nconst get = (url: string, timeout: number): Promise<Response> => fetch(url, { signal: AbortSignal.timeout(timeout), redirect: \"manual\" });\n\n/**\n * This function reads the body of an answer up to `limit` bytes, and gives the status and the text.\n * At the limit, it cancels the body, and `complete` is false. The decoder keeps the bytes of a\n * character that two parts of the body split. The unit tests give it answers with no network.\n */\nexport const answerText = async (response: Response, limit: number): Promise<HttpAnswer> => {\n const reader = response.body?.getReader();\n if (reader === undefined) return { status: response.status, body: \"\", complete: true };\n const decoder = new TextDecoder();\n let body = \"\";\n let size = 0;\n for (;;) {\n const read = await reader.read();\n if (read.done) return { status: response.status, body: body + decoder.decode(), complete: true };\n if (size + read.value.byteLength > limit) {\n body += decoder.decode(read.value.subarray(0, limit - size));\n await reader.cancel();\n return { status: response.status, body, complete: false };\n }\n body += decoder.decode(read.value, { stream: true });\n size += read.value.byteLength;\n }\n};\n\nconst nodeNet: NetPort = {\n async httpStatus(url, timeout) {\n try {\n const response = await get(url, timeout);\n await response.body?.cancel();\n return response.status;\n } catch {\n return null;\n }\n },\n async httpText(url, timeout, limit) {\n try {\n return await answerText(await get(url, timeout), limit);\n } catch {\n return null;\n }\n },\n tcpConnect: (host, port, timeout) =>\n new Promise((resolve) => {\n const socket = connect({ host, port });\n const done = (open: boolean): void => {\n socket.destroy();\n resolve(open);\n };\n socket.setTimeout(timeout, () => done(false));\n socket.once(\"connect\", () => done(true));\n socket.once(\"error\", () => done(false));\n }),\n};\n\n/**\n * This function gives the host ports of Node: `child_process`, `fs/promises`, `net`, `fetch` and `process`.\n * Only a program uses it. A test gives `fakeHost()` of `./testing`, thus it starts no process and installs no task.\n */\nexport const nodeHostPorts = (options: NodeHostOptions = {}): HostPorts => {\n const user = (): string => {\n const name = userInfo().username;\n const domain = process.env[\"USERDOMAIN\"];\n return process.platform === \"win32\" && domain !== undefined && domain !== \"\" ? `${domain}\\\\${name}` : name;\n };\n return {\n platform: process.platform,\n commands: nodeCommands,\n files: nodeFiles,\n processes: nodeProcesses,\n net: nodeNet,\n clock: options.clock ?? realClock,\n wall: () => Date.now(),\n self: { pid: process.pid, startedAt: Math.round(Date.now() - process.uptime() * 1000) },\n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;CACA,MAAM,SAAS,KAAK,SAAS,OAAO;EAClC,IAAI;GACF,OAAO,MAAM,WAAW,MAAM,IAAI,KAAK,OAAO,GAAG,KAAK;EACxD,QAAQ;GACN,OAAO;EACT;CACF;CACA,aAAa,MAAM,MAAM,YACvB,IAAI,SAAS,YAAY;EACvB,MAAM,SAAS,QAAQ;GAAE;GAAM;EAAK,CAAC;EACrC,MAAM,QAAQ,SAAwB;GACpC,OAAO,QAAQ;GACf,QAAQ,IAAI;EACd;EACA,OAAO,WAAW,eAAe,KAAK,KAAK,CAAC;EAC5C,OAAO,KAAK,iBAAiB,KAAK,IAAI,CAAC;EACvC,OAAO,KAAK,eAAe,KAAK,KAAK,CAAC;CACxC,CAAC;AACL;;;;;AAMA,MAAa,iBAAiB,UAA2B,CAAC,MAAiB;CACzE,MAAM,aAAqB;EACzB,MAAM,OAAO,SAAS,CAAC,CAAC;EACxB,MAAM,SAAS,QAAQ,IAAI;EAC3B,OAAO,QAAQ,aAAa,WAAW,WAAW,KAAA,KAAa,WAAW,KAAK,GAAG,OAAO,IAAI,SAAS;CACxG;CACA,OAAO;EACL,UAAU,QAAQ;EAClB,UAAU;EACV,OAAO;EACP,WAAW;EACX,KAAK;EACL,OAAO,QAAQ,SAAS;EACxB,YAAY,KAAK,IAAI;EACrB,MAAM;GAAE,KAAK,QAAQ;GAAK,WAAW,KAAK,MAAM,KAAK,IAAI,IAAI,QAAQ,OAAO,IAAI,GAAI;EAAE;EACtF,KAAK,QAAQ;EACb,SAAS,QAAQ;EACjB;EACA,GAAI,QAAQ,WAAW,KAAA,IAAY,CAAC,IAAI,EAAE,QAAQ,QAAQ,OAAO;CACnE;AACF"}
|
|
1
|
+
{"version":3,"file":"host.js","names":["NAME","xmlText","record","ms","isTimeAtLeast","spawnChild"],"sources":["../src/host/ports.ts","../src/host/render.ts","../src/host/processes.ts","../src/host/lock.ts","../src/host/discovery.ts","../src/host/install.ts","../src/host/probes.ts","../src/host/watch.ts","../src/host/env.ts","../src/host/logs.ts","../src/host/group.ts","../src/host/node.ts"],"sourcesContent":["import type { Clock } from \"../clock.ts\";\nimport type { Logger } from \"../logger.ts\";\n\n/** These options go with one command: the folder that it runs in, and the most time that it can take. */\nexport interface CommandOptions {\n readonly cwd?: string | undefined;\n /** This time is the most that the command can take, in milliseconds. After it, the command stops, and its code is 124. */\n readonly timeout?: number | undefined;\n}\n\n/** A command result is the exit code of a command and the text that it wrote to its output and its error output. */\nexport interface CommandResult {\n /** This code is the exit code. A program that is not found gives 127, and a command at its timeout gives 124. */\n readonly code: number;\n readonly out: string;\n}\n\n/**\n * A command port starts a program with a list of arguments and gives its result. It does not use a\n * shell, thus no argument needs a quote. The host uses it for `schtasks`, `systemctl` and `taskkill`.\n */\nexport interface CommandPort {\n run(file: string, args: readonly string[], options?: CommandOptions): Promise<CommandResult>;\n}\n\n/** A file port is the part of a file system that the host uses. Each path is a full path. */\nexport interface FilePort {\n /** This method gives the text of a file in UTF-8, or null when the file does not exist. */\n read(path: string): Promise<string | null>;\n /** This method writes a file. It makes the folders of the path, and it replaces the file in one step. */\n write(path: string, data: string | Uint8Array): Promise<void>;\n /** This method makes a file only when no file has the path, and tells if it made it. It makes the folders of the path. */\n create(path: string, data: string): Promise<boolean>;\n /** This method adds data at the end of a file. It makes the file and its folders when they do not exist. */\n append(path: string, data: string | Uint8Array): Promise<void>;\n /** This method gives the size of a file in bytes, or null when the file does not exist. */\n size(path: string): Promise<number | null>;\n /** This method gives a file a new path. It replaces a file at the new path. */\n rename(from: string, to: string): Promise<void>;\n /** This method removes a file. A file that does not exist is not an error. */\n remove(path: string): Promise<void>;\n}\n\n/** These are the signals that the host sends to a process. */\nexport type StopSignal = \"SIGINT\" | \"SIGTERM\" | \"SIGKILL\";\n\n/** A spawn request tells the program that a child process runs, with its arguments, its folder and its environment. */\nexport interface SpawnRequest {\n readonly program: string;\n readonly args: readonly string[];\n readonly cwd?: string | undefined;\n readonly env: Readonly<Record<string, string>>;\n /** True gives the child an IPC channel. Only a child that is a Node program can use it. */\n readonly ipc: boolean;\n}\n\n/** A child handle is a child process that the host started. */\nexport interface ChildHandle {\n /** This number is the process ID, or null when the program did not start. */\n readonly pid: number | null;\n /** This flag tells if the child has an IPC channel. */\n readonly ipc: boolean;\n /** This method adds a handler for each part of the output and of the error output of the child. */\n onOutput(handler: (stream: \"stdout\" | \"stderr\", chunk: string | Uint8Array) => void): void;\n /**\n * This method adds a handler for the end of the child. The handler gets the exit code, or null after\n * a signal, and the signal. A program that did not start also ends, with a null code.\n */\n onExit(handler: (code: number | null, signal: string | null) => void): void;\n /** This method sends a message on the IPC channel, and tells if it went. */\n send(message: unknown): boolean;\n}\n\n/**\n * A process port is the part of the processes of the system that the host uses. It finds if a\n * process is alive, it gives its start time, it sends signals and it starts a child.\n */\nexport interface ProcessesPort {\n /** This method tells if a process with this ID is alive. A process of a different user is alive too. */\n alive(pid: number): boolean;\n /** This method gives the start time of a process, in milliseconds after the epoch, or null when the system does not tell. */\n startOf(pid: number): Promise<number | null>;\n /** This method sends a signal to one process, and tells if the signal went. */\n signal(pid: number, signal: StopSignal): boolean;\n /** This method sends a signal to the process group whose leader is `pid`, and tells if the signal went. Windows has no process groups. */\n signalGroup(pid: number, signal: StopSignal): boolean;\n /** This method starts a child process. On Linux, the child leads a new process group. */\n spawn(request: SpawnRequest): ChildHandle;\n}\n\n/** An HTTP answer is the status and the text of an answer. `complete` is false when the text stopped at the limit. */\nexport interface HttpAnswer {\n readonly status: number;\n readonly body: string;\n readonly complete: boolean;\n}\n\n/** A net port does the network part of a readiness probe. */\nexport interface NetPort {\n /** This method sends a GET request, and gives the status of the answer, or null when no answer came in the timeout. */\n httpStatus(url: string, timeout: number): Promise<number | null>;\n /**\n * This method sends a GET request, and gives the status and up to `limit` bytes of the text. It gives\n * null when the answer did not end in the timeout. A probe with freshness bounds uses it. It is optional\n * for the net ports that callers wrote before it. `nodeHostPorts` and `fakeHost` have it.\n */\n httpText?(url: string, timeout: number, limit: number): Promise<HttpAnswer | null>;\n /** This method tells if a TCP connection to the host and the port opens in the timeout, in milliseconds. */\n tcpConnect(host: string, port: number, timeout: number): Promise<boolean>;\n}\n\n/** This record names a process: its ID and its start time, in milliseconds after the epoch. */\nexport interface ProcessMark {\n readonly pid: number;\n readonly startedAt: number;\n}\n\n/**\n * The host ports are each effect of the system that the host uses. A test gives fakes (`fakeHost` of\n * `./testing`), thus a test installs no task and starts no process. `nodeHostPorts()` gives the ports of Node.\n */\nexport interface HostPorts {\n /** This text is the platform, as `process.platform` gives it, for example `win32` or `linux`. */\n readonly platform: string;\n readonly commands: CommandPort;\n readonly files: FilePort;\n readonly processes: ProcessesPort;\n readonly net: NetPort;\n /** This clock gives the monotonic time and the timers. */\n readonly clock: Clock;\n /** This function gives the wall time, in milliseconds after the epoch. */\n readonly wall: () => number;\n /** This record names the process of the host itself. */\n readonly self: ProcessMark;\n /** These are the environment variables of the host. */\n readonly env: Readonly<Record<string, string | undefined>>;\n /** This text is the home folder of the user. */\n readonly homeDir: string;\n /** This function gives the user that a Windows task runs as, for example `HOST\\name`. */\n readonly user: () => string;\n /** This logger gets the log entries of the host. Without it, the host writes no log. */\n readonly logger?: Logger | undefined;\n}\n\n/** This function joins the parts of a path with the separator of the platform. */\nexport const joinPath = (platform: string, ...parts: readonly string[]): string => {\n const separator = platform === \"win32\" ? \"\\\\\" : \"/\";\n // a scan and not a regular expression, thus a long run of separators takes linear time\n const isSeparator = (char: string | undefined): boolean => char === \"/\" || char === \"\\\\\";\n const trim = (part: string, head: boolean): string => {\n let start = 0;\n let end = part.length;\n while (head && start < end && isSeparator(part[start])) start += 1;\n while (end > start && isSeparator(part[end - 1])) end -= 1;\n return part.slice(start, end);\n };\n const trimmed = parts.map((part, at) => trim(part, at !== 0));\n return trimmed.filter((part, at) => at === 0 || part !== \"\").join(separator);\n};\n","import type { Quantity } from \"@mark1russell7/quantity\";\nimport { convertible, isQuantity, valueIn } from \"@mark1russell7/quantity\";\nimport { escapeAttribute as xmlText } from \"@mark1russell7/text\";\n\n/**\n * A service start tells when the system starts the program.\n * - `logon`: at the logon of the user. The program runs until it stops.\n * - `boot`: at the start of the computer, before a logon. The program runs until it stops. It runs in the background.\n * - `{ daily: \"HH:MM\" }`: each day at that local time, as a job that runs to its end.\n */\nexport type ServiceStart = \"logon\" | \"boot\" | { readonly daily: string };\n\n/** A restart policy tells how long the system waits before it starts a program again after it stops. */\nexport interface RestartPolicy {\n /** This time is the wait before the next start. On Windows, the task starts again at whole minutes, 1 minute or more. */\n readonly after: Quantity;\n}\n\n/** A service spec tells which program the system runs as a user service, and when. */\nexport interface ServiceSpec {\n /** This name is the name of the Windows task and of the systemd unit: letters, digits, `.`, `_` and `-`. */\n readonly name: string;\n readonly description: string;\n /** This path is the full path of the program, for example the path of Node. */\n readonly program: string;\n readonly args: readonly string[];\n /** This folder is the working folder of the program. */\n readonly cwd?: string | undefined;\n readonly start: ServiceStart;\n /** This policy starts a program at logon or at boot again after it stops. Null starts it only at its start. A daily job has no restart. */\n readonly restart: RestartPolicy | null;\n /**\n * True runs the program when the user is not logged on. On Windows, the task gets an S4U logon, and Task Scheduler\n * then refuses the task from a shell that is not elevated. On Linux, the install sets the linger of the user\n * (`loginctl enable-linger`), thus the user manager of systemd starts at boot and stays after the logout.\n * The default is true for a boot start, and false for the other starts.\n */\n readonly background?: boolean | undefined;\n /** This folder keeps the files of the host, for example the task file of Windows. */\n readonly stateDir: string;\n /** On Windows, `hidden` starts the program through `conhost --headless`, thus no window opens. The default is `hidden`. */\n readonly console?: \"hidden\" | \"visible\" | undefined;\n /** This time is the most that one run can take. The default is no limit. */\n readonly timeLimit?: Quantity | undefined;\n}\n\n/** These are the parts of the task of Windows that come from the system, not from the spec. */\nexport interface TaskContext {\n /** This text is the user of the task, for example `HOST\\name`. */\n readonly user: string;\n /** This path is the path of `conhost.exe`, for a hidden console. */\n readonly conhost: string;\n}\n\nconst NAME = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;\nconst DAILY = /^([01]\\d|2[0-3]):([0-5]\\d)$/;\n/** This function tells if a text has a control character. Such a character can add a line to a unit, or break the task file. */\nconst hasControl = (text: string): boolean => {\n for (let at = 0; at < text.length; at += 1) {\n const code = text.charCodeAt(at);\n if (code < 0x20 || code === 0x7f) return true;\n }\n return false;\n};\n\n/** This function gives the time of a daily start, or null when the text is not `HH:MM`. */\nexport const dailyTime = (text: string): { readonly hour: string; readonly minute: string } | null => {\n const found = DAILY.exec(text);\n return found === null ? null : { hour: found[1]!, minute: found[2]! };\n};\n\n/** This function tells if the program of a spec runs until it stops: a start at logon or at boot, not a daily job. */\nexport const runsUntilStop = (start: ServiceStart): start is \"logon\" | \"boot\" => start === \"logon\" || start === \"boot\";\n\n/** This function tells if a spec runs when the user is not logged on: its `background`, or true for a boot start. */\nexport const inBackground = (spec: ServiceSpec): boolean => spec.background ?? spec.start === \"boot\";\n\n/** This function tells if a value is a time: a quantity in a unit of time. */\nexport const isTime = (value: unknown): value is Quantity => isQuantity(value) && convertible(value.unit, \"ms\");\n\n/** This function gives the problems of a service spec: each value that the task or the unit cannot use. */\nexport const serviceProblems = (spec: ServiceSpec): string[] => {\n const problems: string[] = [];\n if (!NAME.test(spec.name)) problems.push(`the name ${JSON.stringify(spec.name)} is not letters, digits, \".\", \"_\" and \"-\"`);\n const fields: Array<[string, string]> = [\n [\"description\", spec.description],\n [\"program\", spec.program],\n [\"stateDir\", spec.stateDir],\n ...spec.args.map((arg, at): [string, string] => [`argument ${at}`, arg]),\n ...(spec.cwd === undefined ? [] : [[\"cwd\", spec.cwd] as [string, string]]),\n ];\n for (const [field, value] of fields) if (hasControl(value)) problems.push(`the ${field} has a control character`);\n if (spec.program === \"\") problems.push(\"the program is empty\");\n if (spec.stateDir === \"\") problems.push(\"the stateDir is empty\");\n if (!runsUntilStop(spec.start) && dailyTime(spec.start.daily) === null)\n problems.push(`the daily start ${JSON.stringify(spec.start.daily)} is not a time HH:MM`);\n if (!runsUntilStop(spec.start) && spec.restart !== null) problems.push(\"a daily job has no restart: give null\");\n if (spec.background !== undefined && typeof spec.background !== \"boolean\") problems.push(\"the background is not true or false\");\n if (spec.start === \"boot\" && spec.background === false) problems.push(\"a boot start runs before a logon: give background true, or leave it out\");\n if (inBackground(spec) && spec.console === \"visible\") problems.push(\"a program in the background has no desktop: give the console hidden, or leave it out\");\n if (spec.restart !== null && !(isTime(spec.restart.after) && valueIn(spec.restart.after, \"ms\") >= 0))\n problems.push(\"the restart wait is not a time of zero or more\");\n if (spec.timeLimit !== undefined && !(isTime(spec.timeLimit) && valueIn(spec.timeLimit, \"ms\") > 0))\n problems.push(\"the time limit is not a time above zero\");\n if (spec.console !== undefined && spec.console !== \"hidden\" && spec.console !== \"visible\")\n problems.push(`the console ${JSON.stringify(spec.console)} is not \"hidden\" or \"visible\"`);\n return problems;\n};\n\n/**\n * This function quotes one argument for a command line of Windows, by the rules of `CommandLineToArgvW`.\n * It doubles each backslash before a quote and at the end. One pass keeps the time linear.\n */\nexport const windowsArg = (arg: string): string => {\n if (arg !== \"\" && !/[\\s\"]/.test(arg)) return arg;\n let quoted = '\"';\n let slashes = 0;\n for (const char of arg) {\n if (char === \"\\\\\") {\n slashes += 1;\n continue;\n }\n quoted += char === '\"' ? `${\"\\\\\".repeat(slashes * 2 + 1)}\"` : `${\"\\\\\".repeat(slashes)}${char}`;\n slashes = 0;\n }\n return `${quoted}${\"\\\\\".repeat(slashes * 2)}\"`;\n};\n\n/**\n * This function quotes one argument for the `ExecStart` line of a systemd unit. It writes `%` as\n * `%%` and `$` as `$$`, thus systemd expands no specifier and no variable. An argument with a space,\n * a quote, a backslash or a `;` goes in double quotes.\n */\nexport const systemdArg = (arg: string): string => {\n const escaped = arg.replace(/%/g, () => \"%%\").replace(/\\$/g, () => \"$$\");\n if (escaped !== \"\" && !/[\\s\"'\\\\;]/.test(escaped)) return escaped;\n return `\"${escaped.replace(/\\\\/g, () => \"\\\\\\\\\").replace(/\"/g, () => '\\\\\"')}\"`;\n};\n\n/** This function gives a time as an ISO 8601 duration of Task Scheduler in whole seconds, for example `PT90S`. */\nconst isoSeconds = (time: Quantity): string => `PT${Math.max(1, Math.ceil(valueIn(time, \"s\")))}S`;\n\n/** This function gives the interval of the repeat trigger of a task: whole minutes, 1 minute or more. */\nconst repeatMinutes = (time: Quantity): number => Math.max(1, Math.ceil(valueIn(time, \"min\")));\n\n/** This function gives the seconds of a restart wait for systemd, a whole number. */\nconst restartSeconds = (time: Quantity): number => Math.max(0, Math.ceil(valueIn(time, \"s\")));\n\nconst refuse = (spec: ServiceSpec): void => {\n const problems = serviceProblems(spec);\n if (problems.length > 0) throw new Error(`the service spec has problems: ${problems.join(\"; \")}`);\n};\n\n/**\n * This function gives the task file of Windows for a spec, as text. It is a pure function: the same\n * spec and context give the same text. Each start boundary is in the past, thus the task does not wait for a date.\n * - A start at logon gets a logon trigger, and a start at boot gets a boot trigger. With a restart, a time trigger\n * also starts the task each few minutes. The task ignores a start while its program runs (`IgnoreNew`).\n * - A daily start gets a calendar trigger at its time. A start that the computer missed occurs when it can (`StartWhenAvailable`).\n * - A spec in the background gets an S4U logon: the task runs when the user is not logged on, and Windows keeps no password.\n * Otherwise the task runs only in the session of the user (`InteractiveToken`).\n * Task Scheduler reads the file as UTF-16 with a byte order mark: give the text to `utf16le`.\n */\nexport const renderTaskXml = (spec: ServiceSpec, context: TaskContext): string => {\n refuse(spec);\n const user = xmlText(context.user);\n const hidden = (spec.console ?? \"hidden\") === \"hidden\";\n const command = hidden ? context.conhost : spec.program;\n const args = (hidden ? [\"--headless\", spec.program, ...spec.args] : [...spec.args]).map(windowsArg).join(\" \");\n const triggers: string[] = [];\n if (runsUntilStop(spec.start)) {\n triggers.push(\n spec.start === \"logon\"\n ? ` <LogonTrigger>\n <Enabled>true</Enabled>\n <UserId>${user}</UserId>\n </LogonTrigger>`\n : ` <BootTrigger>\n <Enabled>true</Enabled>\n </BootTrigger>`,\n );\n if (spec.restart !== null)\n triggers.push(` <TimeTrigger>\n <Enabled>true</Enabled>\n <StartBoundary>2000-01-01T00:00:00</StartBoundary>\n <Repetition>\n <Interval>PT${repeatMinutes(spec.restart.after)}M</Interval>\n <StopAtDurationEnd>false</StopAtDurationEnd>\n </Repetition>\n </TimeTrigger>`);\n } else {\n const time = dailyTime(spec.start.daily)!;\n triggers.push(` <CalendarTrigger>\n <Enabled>true</Enabled>\n <StartBoundary>2000-01-01T${time.hour}:${time.minute}:00</StartBoundary>\n <ScheduleByDay>\n <DaysInterval>1</DaysInterval>\n </ScheduleByDay>\n </CalendarTrigger>`);\n }\n const cwd = spec.cwd === undefined ? \"\" : `\\n <WorkingDirectory>${xmlText(spec.cwd)}</WorkingDirectory>`;\n const limit = spec.timeLimit === undefined ? \"PT0S\" : isoSeconds(spec.timeLimit);\n return `<?xml version=\"1.0\" encoding=\"UTF-16\"?>\n<Task version=\"1.4\" xmlns=\"http://schemas.microsoft.com/windows/2004/02/mit/task\">\n <RegistrationInfo>\n <Description>${xmlText(spec.description)}</Description>\n <URI>\\\\${xmlText(spec.name)}</URI>\n </RegistrationInfo>\n <Triggers>\n${triggers.join(\"\\n\")}\n </Triggers>\n <Principals>\n <Principal id=\"Author\">\n <UserId>${user}</UserId>\n <LogonType>${inBackground(spec) ? \"S4U\" : \"InteractiveToken\"}</LogonType>\n <RunLevel>LeastPrivilege</RunLevel>\n </Principal>\n </Principals>\n <Settings>\n <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>\n <DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>\n <StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>\n <AllowHardTerminate>true</AllowHardTerminate>\n <StartWhenAvailable>true</StartWhenAvailable>\n <RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>\n <IdleSettings>\n <StopOnIdleEnd>false</StopOnIdleEnd>\n <RestartOnIdle>false</RestartOnIdle>\n </IdleSettings>\n <AllowStartOnDemand>true</AllowStartOnDemand>\n <Enabled>true</Enabled>\n <Hidden>false</Hidden>\n <RunOnlyIfIdle>false</RunOnlyIfIdle>\n <WakeToRun>false</WakeToRun>\n <ExecutionTimeLimit>${limit}</ExecutionTimeLimit>\n <Priority>5</Priority>\n </Settings>\n <Actions Context=\"Author\">\n <Exec>\n <Command>${xmlText(windowsArg(command))}</Command>\n <Arguments>${xmlText(args)}</Arguments>${cwd}\n </Exec>\n </Actions>\n</Task>\n`;\n};\n\n/** This function encodes a text as UTF-16, little-endian, with a byte order mark: the encoding that Task Scheduler reads. */\nexport const utf16le = (text: string): Uint8Array => {\n const bytes = new Uint8Array(2 + text.length * 2);\n bytes[0] = 0xff;\n bytes[1] = 0xfe;\n for (let at = 0; at < text.length; at += 1) {\n const unit = text.charCodeAt(at);\n bytes[2 + at * 2] = unit & 0xff;\n bytes[3 + at * 2] = unit >> 8;\n }\n return bytes;\n};\n\n/**\n * This function gives the systemd user unit of a spec (`<name>.service`), as text. It is a pure function.\n * - A start at logon or at boot is a service of the type `simple`, wanted by `default.target`. With a restart, it has `Restart=on-failure`.\n * The unit is the same for the two starts: the linger of the user (`installService`) starts the user manager at boot.\n * - A daily start is a service of the type `oneshot` with no `[Install]` section. Its timer (`renderSystemdTimer`) starts it.\n */\nexport const renderSystemdUnit = (spec: ServiceSpec): string => {\n refuse(spec);\n const lines = [\"[Unit]\", `Description=${spec.description.replace(/%/g, \"%%\")}`, \"\", \"[Service]\"];\n lines.push(runsUntilStop(spec.start) ? \"Type=simple\" : \"Type=oneshot\");\n lines.push(`ExecStart=${[spec.program, ...spec.args].map(systemdArg).join(\" \")}`);\n if (spec.cwd !== undefined) lines.push(`WorkingDirectory=${spec.cwd.replace(/%/g, \"%%\")}`);\n if (spec.restart !== null) lines.push(\"Restart=on-failure\", `RestartSec=${restartSeconds(spec.restart.after)}`);\n if (spec.timeLimit !== undefined) lines.push(`RuntimeMaxSec=${Math.max(1, Math.ceil(valueIn(spec.timeLimit, \"s\")))}`);\n if (runsUntilStop(spec.start)) lines.push(\"\", \"[Install]\", \"WantedBy=default.target\");\n return `${lines.join(\"\\n\")}\\n`;\n};\n\n/** This function gives the systemd timer (`<name>.timer`) of a daily spec, or null for a start at logon or at boot. It is a pure function. */\nexport const renderSystemdTimer = (spec: ServiceSpec): string | null => {\n refuse(spec);\n if (runsUntilStop(spec.start)) return null;\n const time = dailyTime(spec.start.daily)!;\n return `${[\n \"[Unit]\",\n `Description=${spec.description.replace(/%/g, \"%%\")}`,\n \"\",\n \"[Timer]\",\n `OnCalendar=*-*-* ${time.hour}:${time.minute}:00`,\n \"Persistent=true\",\n \"\",\n \"[Install]\",\n \"WantedBy=timers.target\",\n ].join(\"\\n\")}\\n`;\n};\n","import type { HostPorts, ProcessMark } from \"./ports.ts\";\n\n/**\n * This margin is the time after a recorded start in which a process can start and still be the same\n * process, in milliseconds. A start time on Linux comes in ticks of 10 ms, and a step of the wall clock moves a time.\n */\nexport const START_MARGIN_MS = 1000;\n\n/**\n * This function tells if the process of a mark is alive and is the same process. Windows and Linux\n * use a process ID again after a process stops. Thus a live process that started after the mark is a\n * different process. A start time that the system does not give proves nothing, and the process counts as the same.\n */\nexport const sameProcess = async (mark: ProcessMark, ports: HostPorts): Promise<boolean> => {\n if (!Number.isInteger(mark.pid) || mark.pid <= 0) return false;\n if (mark.pid === ports.self.pid) return Math.abs(mark.startedAt - ports.self.startedAt) <= START_MARGIN_MS;\n if (!ports.processes.alive(mark.pid)) return false;\n let started: number | null;\n try {\n started = await ports.processes.startOf(mark.pid);\n } catch {\n started = null;\n }\n return started === null || started <= mark.startedAt + START_MARGIN_MS;\n};\n\n/**\n * A tree stop outcome tells what a tree stop did.\n * - `stopped`: the stop went to the process and to each process under it.\n * - `absent`: no process with the ID was alive.\n * - `failed`: the process is alive and the stop did not go. The problem tells why.\n */\nexport type TreeStopOutcome =\n | { readonly kind: \"stopped\" }\n | { readonly kind: \"absent\" }\n | { readonly kind: \"failed\"; readonly problem: string };\n\n/**\n * This function stops a process and each process under it, by its ID only. It does not find a process by\n * its name or its command line. On Windows, it starts `taskkill /T /F /PID <pid>`. On Linux, it sends\n * SIGKILL to the process group of the ID, or to the process when it leads no group. It does not throw.\n */\nexport const stopTree = async (pid: number, ports: HostPorts): Promise<TreeStopOutcome> => {\n if (!Number.isInteger(pid) || pid <= 0) return { kind: \"failed\", problem: `${pid} is not a process ID` };\n if (pid === ports.self.pid) return { kind: \"failed\", problem: \"the host does not stop its own process\" };\n if (!ports.processes.alive(pid)) return { kind: \"absent\" };\n if (ports.platform === \"win32\") {\n const result = await ports.commands\n .run(\"taskkill\", [\"/T\", \"/F\", \"/PID\", String(pid)])\n .catch((error: unknown) => ({ code: 127, out: error instanceof Error ? error.message : String(error) }));\n if (result.code === 0 || !ports.processes.alive(pid)) return { kind: \"stopped\" };\n return { kind: \"failed\", problem: `taskkill gave the code ${result.code}: ${result.out}` };\n }\n if (ports.processes.signalGroup(pid, \"SIGKILL\") || ports.processes.signal(pid, \"SIGKILL\")) return { kind: \"stopped\" };\n return ports.processes.alive(pid) ? { kind: \"failed\", problem: `the signal SIGKILL did not go to the process ${pid}` } : { kind: \"absent\" };\n};\n","import { delay } from \"@mark1russell7/algebra/clock\";\nimport type { HostPorts, ProcessMark } from \"./ports.ts\";\nimport { sameProcess } from \"./processes.ts\";\n\n/**\n * A lock owner is the record in a lock file: the process that holds the lock. The record can also\n * have the child process that it holds the lock for. The lock is held while one of the two is alive.\n */\nexport interface LockOwner extends ProcessMark {\n readonly child?: ProcessMark | undefined;\n}\n\n/** An instance lock is a lock that this process holds. */\nexport interface InstanceLock {\n readonly path: string;\n readonly owner: LockOwner;\n /** This method writes a new child process in the record, or no child with null. */\n update(child: ProcessMark | null): Promise<void>;\n /** This method removes the lock file, when it still has the record of this lock. A second use does nothing. */\n release(): Promise<void>;\n}\n\n/**\n * A lock result tells what a try to take the lock found.\n * - `acquired`: this process holds the lock. `recovered` tells why a stale lock went first, or it is null.\n * - `held`: a live process holds the lock. Its owner is in the result.\n * - `failed`: the lock did not come free, or the file system failed. The problem tells why.\n */\nexport type LockResult =\n | { readonly kind: \"acquired\"; readonly lock: InstanceLock; readonly recovered: string | null }\n | { readonly kind: \"held\"; readonly owner: LockOwner }\n | { readonly kind: \"failed\"; readonly problem: string };\n\n/**\n * A lock state is what an examination of a lock file found. An examination does not throw.\n * - `free`: no file.\n * - `held`: the record names a live process.\n * - `stale`: the record names processes that stopped. The next take removes the file.\n * - `malformed`: the file is not a record, or the read failed.\n */\nexport type LockState =\n | { readonly kind: \"free\" }\n | { readonly kind: \"held\"; readonly owner: LockOwner }\n | { readonly kind: \"stale\"; readonly owner: LockOwner; readonly why: string }\n | { readonly kind: \"malformed\"; readonly problem: string };\n\n/** These options go with a take of the lock. */\nexport interface LockOptions {\n /** This count is the number of reads of a malformed file before the take removes it. The default is 3. */\n readonly tries?: number | undefined;\n /** This time is the pause between two reads of a malformed file, in milliseconds. The default is 100. */\n readonly pause?: number | undefined;\n /** This child process goes in the record at the take. */\n readonly child?: ProcessMark | undefined;\n}\n\nconst isMark = (value: unknown): value is ProcessMark => {\n if (typeof value !== \"object\" || value === null) return false;\n const { pid, startedAt } = value as { pid?: unknown; startedAt?: unknown };\n return typeof pid === \"number\" && Number.isInteger(pid) && pid > 0 && typeof startedAt === \"number\" && Number.isFinite(startedAt);\n};\n\n/** This function reads a lock owner from the text of a lock file, or gives null for a text that is not a record. */\nexport const parseLockOwner = (text: string): LockOwner | null => {\n try {\n const value = JSON.parse(text) as unknown;\n if (!isMark(value)) return null;\n const child = (value as { child?: unknown }).child;\n if (child !== undefined && child !== null && !isMark(child)) return null;\n return { pid: value.pid, startedAt: value.startedAt, ...(isMark(child) ? { child: { pid: child.pid, startedAt: child.startedAt } } : {}) };\n } catch {\n return null;\n }\n};\n\n/** This function gives the text of a lock file for an owner. */\nexport const lockText = (owner: LockOwner): string => `${JSON.stringify(owner)}\\n`;\n\n/** This function tells if the owner of a lock is alive: its process, or its child. */\nconst ownerAlive = async (owner: LockOwner, ports: HostPorts): Promise<boolean> =>\n (await sameProcess(owner, ports)) || (owner.child !== undefined && (await sameProcess(owner.child, ports)));\n\n/**\n * This function removes a file only when it has this text: a lock file or a discovery file. The\n * removal holds the removal lock `<path>.rm` for its read and its delete. Thus two processes that find\n * the same stale file do not remove each other's new file. A removal lock whose owner stopped goes first.\n */\nexport const removeIfSame = async (path: string, text: string, ports: HostPorts): Promise<boolean> => {\n const removal = `${path}.rm`;\n const mine = lockText({ pid: ports.self.pid, startedAt: ports.self.startedAt });\n if (!(await ports.files.create(removal, mine))) {\n const other = parseLockOwner((await ports.files.read(removal)) ?? \"\");\n if (other !== null && (await ownerAlive(other, ports))) return false;\n await ports.files.remove(removal);\n if (!(await ports.files.create(removal, mine))) return false;\n }\n try {\n if ((await ports.files.read(path)) !== text) return false;\n await ports.files.remove(path);\n return true;\n } finally {\n if ((await ports.files.read(removal)) === mine) await ports.files.remove(removal);\n }\n};\n\n/** This function examines a lock file. It does not throw. */\nexport const inspectInstanceLock = async (path: string, ports: HostPorts): Promise<LockState> => {\n try {\n const text = await ports.files.read(path);\n if (text === null) return { kind: \"free\" };\n const owner = parseLockOwner(text);\n if (owner === null) return { kind: \"malformed\", problem: \"the lock file is not a lock record\" };\n if (await ownerAlive(owner, ports)) return { kind: \"held\", owner };\n return { kind: \"stale\", owner, why: `the owner process ${owner.pid} stopped` };\n } catch (error) {\n return { kind: \"malformed\", problem: `the read failed: ${error instanceof Error ? error.message : String(error)}` };\n }\n};\n\n/**\n * This function takes the lock of one instance: a lock file with the record of this process. Thus a\n * second instance does not start. It does not throw.\n * - A file whose owner and child stopped is stale: it goes, and the take tries again.\n * - A malformed file can be the file of a take that writes at this time. The take reads it again after\n * a pause, and after `tries` reads, it removes it.\n * - A file whose owner or child is alive gives `held`.\n */\nexport const acquireInstanceLock = async (path: string, ports: HostPorts, options: LockOptions = {}): Promise<LockResult> => {\n const tries = options.tries ?? 3;\n const pause = options.pause ?? 100;\n const owner: LockOwner = { pid: ports.self.pid, startedAt: ports.self.startedAt, ...(options.child === undefined ? {} : { child: options.child }) };\n let recovered: string | null = null;\n let malformed = 0;\n try {\n for (let attempt = 0; attempt < tries + 3; attempt += 1) {\n const text = lockText(owner);\n if (await ports.files.create(path, text)) {\n ports.logger?.log(\"info\", `the host took the lock ${path}`, { path, pid: owner.pid, ...(recovered === null ? {} : { recovered }) });\n return { kind: \"acquired\", lock: held(path, owner, text, ports), recovered };\n }\n const found = await ports.files.read(path);\n if (found === null) continue;\n const other = parseLockOwner(found);\n if (other === null) {\n malformed += 1;\n if (malformed < tries) {\n await delay(ports.clock, pause);\n continue;\n }\n if (await removeIfSame(path, found, ports)) recovered = \"the lock file was not a lock record\";\n continue;\n }\n if (await ownerAlive(other, ports)) return { kind: \"held\", owner: other };\n if (await removeIfSame(path, found, ports)) {\n recovered = `the owner process ${other.pid} stopped`;\n ports.logger?.log(\"warn\", `the host removed the stale lock ${path}: ${recovered}`, { path, owner: other });\n }\n }\n return { kind: \"failed\", problem: `the lock ${path} did not come free after ${tries + 3} tries` };\n } catch (error) {\n return { kind: \"failed\", problem: `the file system failed: ${error instanceof Error ? error.message : String(error)}` };\n }\n};\n\n/** This function gives the handle of a lock that this process holds. */\nconst held = (path: string, first: LockOwner, firstText: string, ports: HostPorts): InstanceLock => {\n let owner = first;\n let text = firstText;\n let released = false;\n // the updates and the release occur in sequence, thus a late write does not make the file again after the release\n let queue: Promise<void> = Promise.resolve();\n const enqueue = (work: () => Promise<void>): Promise<void> => {\n const next = queue.then(work);\n queue = next.catch(() => {});\n return next;\n };\n return {\n path,\n get owner() {\n return owner;\n },\n update: (child) =>\n enqueue(async () => {\n if (released) return;\n const next: LockOwner = { pid: owner.pid, startedAt: owner.startedAt, ...(child === null ? {} : { child }) };\n const nextText = lockText(next);\n await ports.files.write(path, nextText);\n owner = next;\n text = nextText;\n }),\n release: () =>\n enqueue(async () => {\n if (released) return;\n released = true;\n try {\n await removeIfSame(path, text, ports);\n } catch {\n // a lock file that stays is stale after the exit of this process\n }\n }),\n };\n};\n","import type { HostPorts } from \"./ports.ts\";\nimport { removeIfSame } from \"./lock.ts\";\nimport { sameProcess } from \"./processes.ts\";\n\n/**\n * A discovery record tells where a running instance listens. The instance writes it after its start,\n * and a client reads it to find the instance. The file is JSON, one record.\n */\nexport interface Discovery {\n /** This number is the process ID of the instance. */\n readonly pid: number;\n /** This text is the start time of the process, as an ISO 8601 time. */\n readonly startedAt: string;\n /** This number is the port that the instance listens on, or null. */\n readonly port: number | null;\n /** This text is the address of the instance, for example `http://127.0.0.1:8080/`, or null. */\n readonly url: string | null;\n /** These fields are more data of the instance, for example its version. */\n readonly extra?: Readonly<Record<string, unknown>> | undefined;\n}\n\n/**\n * A discovery read is what a read of the discovery file found. A read does not throw.\n * - `running`: the file names a live process, and its start time does not prove that it is a different process.\n * - `absent`: no file.\n * - `stale`: the file names a process that stopped, or a new process with the same ID.\n * - `malformed`: the file is not a discovery record, or the read failed. The problem tells why.\n */\nexport type DiscoveryRead =\n | { readonly kind: \"running\"; readonly record: Discovery }\n | { readonly kind: \"absent\" }\n | { readonly kind: \"stale\"; readonly record: Discovery; readonly why: string }\n | { readonly kind: \"malformed\"; readonly problem: string };\n\n/** These options go with a read of the discovery file. */\nexport interface ReadDiscoveryOptions {\n /** True removes a stale or malformed file. The default is false. */\n readonly clean?: boolean | undefined;\n}\n\nconst isPort = (value: unknown): value is number => typeof value === \"number\" && Number.isInteger(value) && value >= 1 && value <= 65_535;\n\n/** This function reads a discovery record from a text. It gives the record, or the problem as a text. */\nexport const parseDiscovery = (text: string): Discovery | string => {\n let value: unknown;\n try {\n value = JSON.parse(text);\n } catch (error) {\n return `the file is not JSON: ${error instanceof Error ? error.message : String(error)}`;\n }\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) return \"the file is not a JSON object\";\n const record = value as Readonly<Record<string, unknown>>;\n const { pid, startedAt, port, url, extra } = record;\n if (typeof pid !== \"number\" || !Number.isInteger(pid) || pid <= 0) return \"the field pid is not a process ID\";\n if (typeof startedAt !== \"string\" || !Number.isFinite(Date.parse(startedAt))) return \"the field startedAt is not an ISO time\";\n if (port !== null && port !== undefined && !isPort(port)) return \"the field port is not a port from 1 to 65535\";\n if (url !== null && url !== undefined && typeof url !== \"string\") return \"the field url is not a text\";\n if (extra !== undefined && (typeof extra !== \"object\" || extra === null || Array.isArray(extra))) return \"the field extra is not an object\";\n return {\n pid,\n startedAt,\n port: isPort(port) ? port : null,\n url: typeof url === \"string\" ? url : null,\n ...(extra === undefined ? {} : { extra: extra as Readonly<Record<string, unknown>> }),\n };\n};\n\n/** These fields describe where this process listens. */\nexport interface DiscoveryFields {\n readonly port?: number | null | undefined;\n readonly url?: string | null | undefined;\n readonly extra?: Readonly<Record<string, unknown>> | undefined;\n}\n\n/** This function gives the discovery record of the process of the host, with its start time. */\nexport const discoveryOf = (fields: DiscoveryFields, ports: HostPorts): Discovery => ({\n pid: ports.self.pid,\n startedAt: new Date(ports.self.startedAt).toISOString(),\n port: fields.port ?? null,\n url: fields.url ?? null,\n ...(fields.extra === undefined ? {} : { extra: fields.extra }),\n});\n\n/** This function writes a discovery file. The write replaces the file in one step, thus a reader sees the old record or the new one. */\nexport const writeDiscovery = async (path: string, record: Discovery, ports: HostPorts): Promise<void> => {\n await ports.files.write(path, `${JSON.stringify(record, null, 2)}\\n`);\n};\n\n/**\n * This function reads a discovery file and examines its process. It does not throw: a file that is not\n * a record, or a failed read, gives `malformed`. With `clean`, it removes a stale or malformed file.\n */\nexport const readDiscovery = async (path: string, ports: HostPorts, options: ReadDiscoveryOptions = {}): Promise<DiscoveryRead> => {\n const { found, text } = await examine(path, ports);\n // The clean removes only the text that it examined: a new instance can write its file after the read.\n if (options.clean === true && text !== null && (found.kind === \"stale\" || found.kind === \"malformed\")) {\n try {\n if (await removeIfSame(path, text, ports)) ports.logger?.log(\"info\", `the host removed the ${found.kind} discovery file ${path}`, { path, kind: found.kind });\n } catch {\n // the next read examines the file again\n }\n }\n return found;\n};\n\nconst examine = async (path: string, ports: HostPorts): Promise<{ readonly found: DiscoveryRead; readonly text: string | null }> => {\n let text: string | null;\n try {\n text = await ports.files.read(path);\n } catch (error) {\n return { found: { kind: \"malformed\", problem: `the read failed: ${error instanceof Error ? error.message : String(error)}` }, text: null };\n }\n if (text === null) return { found: { kind: \"absent\" }, text };\n const record = parseDiscovery(text);\n if (typeof record === \"string\") return { found: { kind: \"malformed\", problem: record }, text };\n const mark = { pid: record.pid, startedAt: Date.parse(record.startedAt) };\n if (await sameProcess(mark, ports)) return { found: { kind: \"running\", record }, text };\n const why = ports.processes.alive(record.pid)\n ? `the process ${record.pid} started after the record, thus it is a different process`\n : `the process ${record.pid} stopped`;\n return { found: { kind: \"stale\", record, why }, text };\n};\n\n/** This function removes a discovery file when it names the process `pid`, by default the process of the host. It tells if it removed the file. */\nexport const removeDiscovery = async (path: string, ports: HostPorts, pid: number = ports.self.pid): Promise<boolean> => {\n try {\n const text = await ports.files.read(path);\n if (text === null) return false;\n const record = parseDiscovery(text);\n if (typeof record === \"string\" || record.pid !== pid) return false;\n return await removeIfSame(path, text, ports);\n } catch {\n return false;\n }\n};\n","import type { DiscoveryRead } from \"./discovery.ts\";\nimport { readDiscovery } from \"./discovery.ts\";\nimport type { HostPorts } from \"./ports.ts\";\nimport { joinPath } from \"./ports.ts\";\nimport { stopTree } from \"./processes.ts\";\nimport type { ServiceSpec } from \"./render.ts\";\nimport { inBackground, renderSystemdTimer, renderSystemdUnit, renderTaskXml, runsUntilStop, serviceProblems, utf16le } from \"./render.ts\";\n\n/** A command record is one command that a service operation started, and its result. */\nexport interface CommandRecord {\n readonly file: string;\n readonly args: readonly string[];\n readonly code: number;\n readonly out: string;\n}\n\n/**\n * A service outcome tells what a service operation did. An operation does not throw.\n * - `done`: each command gave 0. `commands` and `files` tell what the operation did.\n * - `failed`: a command gave a code that is not 0, or the file system failed. The problem tells which.\n * - `refused`: the spec has problems, and the operation did nothing.\n * - `unsupported`: the platform is not Windows or Linux, and the operation did nothing.\n */\nexport type ServiceOutcome =\n | { readonly kind: \"done\"; readonly commands: readonly CommandRecord[]; readonly files: readonly string[] }\n | { readonly kind: \"failed\"; readonly commands: readonly CommandRecord[]; readonly problem: string }\n | { readonly kind: \"refused\"; readonly problems: readonly string[] }\n | { readonly kind: \"unsupported\"; readonly platform: string };\n\n/** A service status tells if the system has the service, its state, and the instance of the discovery file. */\nexport interface ServiceStatus {\n /** This flag tells if the system has the task or the unit. */\n readonly installed: boolean;\n /**\n * This text is the state that the system gives, for example `Running` or `Ready` from `schtasks`, or\n * `active` or `inactive` from `systemctl`. It is `unknown` when the system gives no state.\n */\n readonly state: string;\n /** This is the read of the discovery file, or null without a discovery path. */\n readonly instance: DiscoveryRead | null;\n /** These are the commands that the status started. */\n readonly commands: readonly CommandRecord[];\n}\n\n/** These options go with an install. */\nexport interface InstallOptions {\n /** True starts the service after the install. The default is true. */\n readonly start?: boolean | undefined;\n}\n\n/** These options go with an operation that stops the instance: the discovery file that names it. */\nexport interface InstanceOptions {\n /** This path is the discovery file of the instance. With it, the operation stops the process tree of a live instance. */\n readonly discovery?: string | undefined;\n}\n\n/** These are the files of a service on this platform. */\nexport interface ServicePaths {\n /** This path is the task file on Windows, or the unit on Linux. */\n readonly unit: string;\n /** This path is the timer of a daily job on Linux, or null. */\n readonly timer: string | null;\n}\n\n/** This function gives the folder of the systemd user units: `$XDG_CONFIG_HOME/systemd/user`, or `~/.config/systemd/user`. */\nconst unitDir = (ports: HostPorts): string => {\n const config = ports.env[\"XDG_CONFIG_HOME\"];\n return joinPath(\"linux\", config === undefined || config === \"\" ? joinPath(\"linux\", ports.homeDir, \".config\") : config, \"systemd\", \"user\");\n};\n\n/** This function gives the files of a service on the platform of the ports. */\nexport const servicePaths = (spec: ServiceSpec, ports: HostPorts): ServicePaths => {\n if (ports.platform === \"win32\") return { unit: joinPath(\"win32\", spec.stateDir, `${spec.name}.task.xml`), timer: null };\n const dir = unitDir(ports);\n return { unit: joinPath(\"linux\", dir, `${spec.name}.service`), timer: runsUntilStop(spec.start) ? null : joinPath(\"linux\", dir, `${spec.name}.timer`) };\n};\n\n/** This function gives the unit that `systemctl` enables: the timer of a daily job, or the service. */\nconst enabledUnit = (spec: ServiceSpec): string => (runsUntilStop(spec.start) ? `${spec.name}.service` : `${spec.name}.timer`);\n\n/**\n * This text goes with a failure of `schtasks` for a spec in the background. Task Scheduler refuses a boot trigger\n * and an S4U logon from a shell that is not elevated: `Access is denied`, with the code 1 (Windows 11, 2026-11).\n */\nconst ELEVATION =\n \"Task Scheduler refuses a boot trigger and an S4U logon from a shell that is not elevated: start the same operation in a shell of an administrator\";\n\n/** This function gives the path of `conhost.exe` from `SystemRoot`. Without it, Task Scheduler expands `%SystemRoot%` at the start. */\nconst conhostPath = (ports: HostPorts): string => joinPath(\"win32\", ports.env[\"SystemRoot\"] ?? \"%SystemRoot%\", \"System32\", \"conhost.exe\");\n\n/** A runner starts commands, and keeps a record of each. */\ninterface Runner {\n readonly commands: CommandRecord[];\n run(file: string, args: readonly string[]): Promise<CommandRecord>;\n}\n\nconst runner = (ports: HostPorts): Runner => {\n const commands: CommandRecord[] = [];\n return {\n commands,\n async run(file, args) {\n let record: CommandRecord;\n try {\n const result = await ports.commands.run(file, args);\n record = { file, args, code: result.code, out: result.out.trim() };\n } catch (error) {\n record = { file, args, code: 127, out: error instanceof Error ? error.message : String(error) };\n }\n commands.push(record);\n ports.logger?.log(record.code === 0 ? \"debug\" : \"warn\", `${file} ${args.join(\" \")} gave the code ${record.code}`, { ...record });\n return record;\n },\n };\n};\n\nconst failed = (commands: readonly CommandRecord[], record: CommandRecord, note: string | null): ServiceOutcome => ({\n kind: \"failed\",\n commands,\n problem: `${record.file} ${record.args.join(\" \")} gave the code ${record.code}${record.out === \"\" ? \"\" : `: ${record.out}`}${note === null ? \"\" : ` (${note})`}`,\n});\n\n/** This function gives the note of a failed command: the elevation of Task Scheduler for a spec in the background, or null. */\nconst noteOf = (spec: ServiceSpec, ports: HostPorts, record: CommandRecord): string | null =>\n ports.platform === \"win32\" && record.file === \"schtasks\" && inBackground(spec) ? ELEVATION : null;\n\nconst problemOf = (error: unknown): string => (error instanceof Error ? error.message : String(error));\n\n/**\n * This function runs the steps of an operation. It refuses a spec with problems and a platform that\n * is not Windows or Linux, and it catches each failure of the file system.\n */\nconst operate = async (\n spec: ServiceSpec,\n ports: HostPorts,\n steps: (run: Runner, files: string[]) => Promise<CommandRecord | null>,\n): Promise<ServiceOutcome> => {\n const problems = serviceProblems(spec);\n if (problems.length > 0) return { kind: \"refused\", problems };\n if (ports.platform !== \"win32\" && ports.platform !== \"linux\") return { kind: \"unsupported\", platform: ports.platform };\n const run = runner(ports);\n const files: string[] = [];\n try {\n const failure = await steps(run, files);\n if (failure !== null) return failed(run.commands, failure, noteOf(spec, ports, failure));\n } catch (error) {\n return { kind: \"failed\", commands: run.commands, problem: `the file system failed: ${problemOf(error)}` };\n }\n return { kind: \"done\", commands: run.commands, files };\n};\n\n/** This function gives the first record whose code is not 0, or null. */\nconst firstFailure = (...records: readonly CommandRecord[]): CommandRecord | null => records.find((record) => record.code !== 0) ?? null;\n\n/**\n * This function installs a service of the user, and by default starts it. It does not throw.\n * - On Windows, it writes the task file in UTF-16 to `stateDir`, and starts `schtasks /Create /XML <file> /F`, then `schtasks /Run`.\n * - On Linux, it writes the unit (and the timer of a daily job), then starts `systemctl --user daemon-reload` and `enable`.\n * For a spec in the background, it first starts `loginctl enable-linger` for the user.\n * A second install replaces the first. Give it the ports of a test, thus no test installs a real task.\n * On Windows, Task Scheduler refuses a spec in the background from a shell that is not elevated: the problem then tells so.\n */\nexport const installService = (spec: ServiceSpec, ports: HostPorts, options: InstallOptions = {}): Promise<ServiceOutcome> =>\n operate(spec, ports, async (run, files) => {\n const start = options.start ?? true;\n const paths = servicePaths(spec, ports);\n if (ports.platform === \"win32\") {\n await ports.files.write(paths.unit, utf16le(renderTaskXml(spec, { user: ports.user(), conhost: conhostPath(ports) })));\n files.push(paths.unit);\n const created = await run.run(\"schtasks\", [\"/Create\", \"/TN\", spec.name, \"/XML\", paths.unit, \"/F\"]);\n if (created.code !== 0 || !start) return firstFailure(created);\n return firstFailure(await run.run(\"schtasks\", [\"/Run\", \"/TN\", spec.name]));\n }\n await ports.files.write(paths.unit, renderSystemdUnit(spec));\n files.push(paths.unit);\n const timer = renderSystemdTimer(spec);\n if (paths.timer !== null && timer !== null) {\n await ports.files.write(paths.timer, timer);\n files.push(paths.timer);\n }\n if (inBackground(spec)) {\n // the linger starts the user manager at boot and keeps it after the logout. The removal keeps the linger, because other units can need it\n const lingered = await run.run(\"loginctl\", [\"enable-linger\"]);\n if (lingered.code !== 0) return lingered;\n }\n const reloaded = await run.run(\"systemctl\", [\"--user\", \"daemon-reload\"]);\n if (reloaded.code !== 0) return reloaded;\n return firstFailure(await run.run(\"systemctl\", [\"--user\", \"enable\", ...(start ? [\"--now\"] : []), enabledUnit(spec)]));\n });\n\n/** This function stops the instance of a discovery file, when it is alive and is the same process. */\nconst stopInstance = async (ports: HostPorts, options: InstanceOptions): Promise<void> => {\n if (options.discovery === undefined) return;\n const found = await readDiscovery(options.discovery, ports, { clean: true });\n if (found.kind !== \"running\") return;\n const stopped = await stopTree(found.record.pid, ports);\n ports.logger?.log(stopped.kind === \"failed\" ? \"warn\" : \"info\", `the host stopped the instance ${found.record.pid}: ${stopped.kind}`, {\n pid: found.record.pid,\n outcome: stopped.kind,\n });\n};\n\n/**\n * This function removes a service. It does not throw. On Windows, it ends the task and deletes it. On\n * Linux, it disables and stops the unit, removes its files and reloads systemd. With a discovery file,\n * it then stops the process tree of an instance that stays.\n */\nexport const uninstallService = (spec: ServiceSpec, ports: HostPorts, options: InstanceOptions = {}): Promise<ServiceOutcome> =>\n operate(spec, ports, async (run, files) => {\n const paths = servicePaths(spec, ports);\n let failure: CommandRecord | null;\n if (ports.platform === \"win32\") {\n // the end of a task that does not run gives a code that is not 0: it is not a failure of the removal\n await run.run(\"schtasks\", [\"/End\", \"/TN\", spec.name]);\n failure = firstFailure(await run.run(\"schtasks\", [\"/Delete\", \"/TN\", spec.name, \"/F\"]));\n await ports.files.remove(paths.unit);\n } else {\n failure = firstFailure(await run.run(\"systemctl\", [\"--user\", \"disable\", \"--now\", enabledUnit(spec)]));\n if (paths.timer !== null) await run.run(\"systemctl\", [\"--user\", \"stop\", `${spec.name}.service`]);\n await ports.files.remove(paths.unit);\n if (paths.timer !== null) await ports.files.remove(paths.timer);\n await run.run(\"systemctl\", [\"--user\", \"daemon-reload\"]);\n }\n files.push(paths.unit, ...(paths.timer === null ? [] : [paths.timer]));\n await stopInstance(ports, options);\n return failure;\n });\n\n/** This function enables a service and starts it. It does not throw. On Windows, it enables the task and runs it. */\nexport const startService = (spec: ServiceSpec, ports: HostPorts): Promise<ServiceOutcome> =>\n operate(spec, ports, async (run) => {\n if (ports.platform === \"win32\") {\n const enabled = await run.run(\"schtasks\", [\"/Change\", \"/TN\", spec.name, \"/ENABLE\"]);\n if (enabled.code !== 0) return enabled;\n return firstFailure(await run.run(\"schtasks\", [\"/Run\", \"/TN\", spec.name]));\n }\n // stopService disables the unit or its timer, thus the start enables it again\n return firstFailure(await run.run(\"systemctl\", [\"--user\", \"enable\", \"--now\", enabledUnit(spec)]));\n });\n\n/**\n * This function stops a service, and keeps it stopped until `startService`. It does not throw.\n * - On Windows, it disables the task, thus its time trigger does not start it again, and ends the task.\n * With a discovery file, it then stops the process tree of the instance. Windows has no signal that a child can catch.\n * - On Linux, it disables the unit of a service at logon or at boot, or the timer of a daily job, and stops it.\n * Thus the next login, the next boot or the next calendar time does not start it again. The stop sends SIGTERM,\n * thus `run()` stops in its stages. A daily job that operates stops too.\n */\nexport const stopService = (spec: ServiceSpec, ports: HostPorts, options: InstanceOptions = {}): Promise<ServiceOutcome> =>\n operate(spec, ports, async (run) => {\n if (ports.platform === \"win32\") {\n const disabled = await run.run(\"schtasks\", [\"/Change\", \"/TN\", spec.name, \"/DISABLE\"]);\n if (disabled.code !== 0) return disabled;\n await run.run(\"schtasks\", [\"/End\", \"/TN\", spec.name]);\n await stopInstance(ports, options);\n return null;\n }\n const disabled = await run.run(\"systemctl\", [\"--user\", \"disable\", \"--now\", enabledUnit(spec)]);\n if (disabled.code !== 0 || runsUntilStop(spec.start)) return firstFailure(disabled);\n return firstFailure(await run.run(\"systemctl\", [\"--user\", \"stop\", `${spec.name}.service`]));\n });\n\n/** This function gives the value of a line `Key: value` of the list of `schtasks /Query /FO LIST`. */\nconst listValue = (out: string, key: string): string | null => {\n for (const line of out.split(/\\r?\\n/)) {\n const at = line.indexOf(\":\");\n if (at > 0 && line.slice(0, at).trim() === key) return line.slice(at + 1).trim();\n }\n return null;\n};\n\n/**\n * This function gives the status of a service. It does not throw. A service that the system does not\n * have gives `installed: false`. A malformed or stale discovery file gives its read, and not a throw.\n */\nexport const serviceStatus = async (spec: ServiceSpec, ports: HostPorts, options: InstanceOptions = {}): Promise<ServiceStatus> => {\n const run = runner(ports);\n const instance = options.discovery === undefined ? null : await readDiscovery(options.discovery, ports);\n if (serviceProblems(spec).length > 0 || (ports.platform !== \"win32\" && ports.platform !== \"linux\"))\n return { installed: false, state: \"unknown\", instance, commands: run.commands };\n if (ports.platform === \"win32\") {\n const query = await run.run(\"schtasks\", [\"/Query\", \"/TN\", spec.name, \"/V\", \"/FO\", \"LIST\"]);\n if (query.code !== 0) return { installed: false, state: \"unknown\", instance, commands: run.commands };\n return { installed: true, state: listValue(query.out, \"Status\") ?? \"unknown\", instance, commands: run.commands };\n }\n let installed: boolean;\n try {\n installed = (await ports.files.read(servicePaths(spec, ports).unit)) !== null;\n } catch {\n installed = false;\n }\n const active = await run.run(\"systemctl\", [\"--user\", \"is-active\", `${spec.name}.service`]);\n const state = active.out.split(/\\r?\\n/)[0]?.trim() ?? \"\";\n return { installed, state: state === \"\" ? \"unknown\" : state, instance, commands: run.commands };\n};\n","import type { Quantity } from \"@mark1russell7/quantity\";\nimport { convertible, formatDuration, isQuantity, valueIn } from \"@mark1russell7/quantity\";\nimport type { HostPorts } from \"./ports.ts\";\n\n/**\n * A freshness bound reads one time in the JSON answer of an http probe. The time is epoch\n * milliseconds or an ISO 8601 text. The probe fails when the time is older than `within`, or when\n * the answer does not have it.\n */\nexport interface FreshnessBound {\n /** This JSON Pointer (RFC 6901) names the time in the answer, for example `/delivery/lastTestSendAt`. */\n readonly pointer: string;\n /** This time is the largest age that passes. */\n readonly within: Quantity;\n}\n\n/**\n * A ready probe tells when a program is ready.\n * - `http`: a GET request to the address gives the status, 200 by default. With `fresh`, the answer\n * is also JSON, and each bound of `fresh` passes. The age of a time is measured from `now`: a\n * JSON Pointer to the time of the target in the answer. Without `now`, the wall clock of the host\n * gives the time.\n * - `tcp`: a TCP connection to the port opens. The default host is `127.0.0.1`.\n * - `command`: a command gives the exit code 0.\n */\nexport type ReadyProbe =\n | {\n readonly kind: \"http\";\n readonly url: string;\n readonly status?: number | undefined;\n readonly fresh?: readonly FreshnessBound[] | undefined;\n readonly now?: string | undefined;\n }\n | { readonly kind: \"tcp\"; readonly port: number; readonly host?: string | undefined }\n | { readonly kind: \"command\"; readonly program: string; readonly args: readonly string[]; readonly cwd?: string | undefined };\n\n/** A probe result is the result of one use of a probe. A failure tells why. */\nexport type ProbeResult = { readonly ok: true } | { readonly ok: false; readonly why: string };\n\n/** This size is the largest answer that a probe with freshness bounds reads: 1 MiB. */\nexport const PROBE_BODY_LIMIT = 1_048_576;\n\nconst isPointer = (pointer: unknown): pointer is string =>\n typeof pointer === \"string\" && (pointer === \"\" || (pointer.startsWith(\"/\") && !/~[^01]|~$/.test(pointer)));\n\n/** This function gives the problems of a probe: each value that a probe cannot use. */\nexport const probeProblems = (probe: ReadyProbe): string[] => {\n if (probe.kind === \"http\") {\n const problems: string[] = [];\n if (!/^https?:\\/\\//.test(probe.url)) problems.push(`the address ${JSON.stringify(probe.url)} is not an http or https address`);\n if (probe.status !== undefined && !(Number.isInteger(probe.status) && probe.status >= 100 && probe.status <= 599))\n problems.push(`the status ${probe.status} is not an HTTP status`);\n if (probe.now !== undefined && !isPointer(probe.now)) problems.push(`the now ${JSON.stringify(probe.now)} is not a JSON Pointer`);\n if (probe.now !== undefined && probe.fresh === undefined) problems.push(\"the probe has a now, but no fresh list\");\n if (probe.fresh !== undefined && probe.fresh.length === 0) problems.push(\"the fresh list is empty\");\n for (const bound of probe.fresh ?? []) {\n if (!isPointer(bound.pointer)) problems.push(`the freshness pointer ${JSON.stringify(bound.pointer)} is not a JSON Pointer`);\n if (!(isQuantity(bound.within) && convertible(bound.within.unit, \"ms\") && valueIn(bound.within, \"ms\") >= 0))\n problems.push(`the freshness bound of ${JSON.stringify(bound.pointer)} is not a time of zero or more`);\n }\n return problems;\n }\n if (probe.kind === \"tcp\")\n return Number.isInteger(probe.port) && probe.port >= 1 && probe.port <= 65_535 ? [] : [`the port ${probe.port} is not a port from 1 to 65535`];\n if (probe.kind === \"command\") return probe.program === \"\" ? [\"the program of the command probe is empty\"] : [];\n return [`the probe kind ${JSON.stringify((probe as { kind: unknown }).kind)} is not http, tcp or command`];\n};\n\n/** This function gives the value at a JSON Pointer (RFC 6901), or undefined when the document does not have it. */\nconst pointAt = (document: unknown, pointer: string): unknown => {\n if (pointer === \"\") return document;\n let at = document;\n for (const token of pointer.slice(1).split(\"/\")) {\n const key = token.replaceAll(\"~1\", \"/\").replaceAll(\"~0\", \"~\");\n if (Array.isArray(at)) {\n if (!/^(0|[1-9]\\d*)$/.test(key) || Number(key) >= at.length) return undefined;\n at = at[Number(key)];\n } else if (at !== null && typeof at === \"object\" && Object.hasOwn(at, key)) {\n at = (at as Record<string, unknown>)[key];\n } else return undefined;\n }\n return at;\n};\n\n/** This function gives the time of a value in epoch milliseconds: a finite number, or an ISO 8601 text. */\nconst timeOf = (value: unknown): number | null => {\n if (typeof value === \"number\") return Number.isFinite(value) ? value : null;\n if (typeof value === \"string\") {\n const time = Date.parse(value);\n return Number.isNaN(time) ? null : time;\n }\n return null;\n};\n\n/** This function examines the JSON answer of an http probe against its freshness bounds. */\nconst freshness = (url: string, body: string, bounds: readonly FreshnessBound[], nowPointer: string | undefined, wall: number): ProbeResult => {\n let document: unknown;\n try {\n document = JSON.parse(body);\n } catch {\n return { ok: false, why: `${url} did not give JSON` };\n }\n const now = nowPointer === undefined ? wall : timeOf(pointAt(document, nowPointer));\n if (now === null) return { ok: false, why: `${url} has no time at ${nowPointer}` };\n const stale: string[] = [];\n for (const bound of bounds) {\n const time = timeOf(pointAt(document, bound.pointer));\n if (time === null) {\n stale.push(`${bound.pointer} has no time`);\n continue;\n }\n const age = Math.max(0, now - time);\n if (age > valueIn(bound.within, \"ms\"))\n stale.push(`${bound.pointer} is ${formatDuration({ value: age, unit: \"ms\" })} old, above ${formatDuration(bound.within)}`);\n }\n return stale.length === 0 ? { ok: true } : { ok: false, why: `${url}: ${stale.join(\"; \")}` };\n};\n\n/** This function uses a probe one time, in a timeout of milliseconds. It does not throw. */\nexport const probeOnce = async (probe: ReadyProbe, timeout: number, ports: HostPorts): Promise<ProbeResult> => {\n try {\n if (probe.kind === \"http\") {\n const want = probe.status ?? 200;\n if (probe.fresh !== undefined) {\n if (ports.net.httpText === undefined) return { ok: false, why: \"the net port cannot read an answer, thus it cannot examine freshness\" };\n const answer = await ports.net.httpText(probe.url, timeout, PROBE_BODY_LIMIT);\n if (answer === null) return { ok: false, why: `${probe.url} gave no answer in ${timeout} ms` };\n if (answer.status !== want) return { ok: false, why: `${probe.url} gave ${answer.status}, not ${want}` };\n if (!answer.complete) return { ok: false, why: `the answer of ${probe.url} is above ${PROBE_BODY_LIMIT} bytes` };\n return freshness(probe.url, answer.body, probe.fresh, probe.now, ports.wall());\n }\n const status = await ports.net.httpStatus(probe.url, timeout);\n if (status === want) return { ok: true };\n return { ok: false, why: status === null ? `${probe.url} gave no answer in ${timeout} ms` : `${probe.url} gave ${status}, not ${want}` };\n }\n if (probe.kind === \"tcp\") {\n const host = probe.host ?? \"127.0.0.1\";\n if (await ports.net.tcpConnect(host, probe.port, timeout)) return { ok: true };\n return { ok: false, why: `no TCP connection to ${host}:${probe.port} in ${timeout} ms` };\n }\n const result = await ports.commands.run(probe.program, probe.args, { cwd: probe.cwd, timeout });\n return result.code === 0 ? { ok: true } : { ok: false, why: `${probe.program} gave the code ${result.code}` };\n } catch (error) {\n return { ok: false, why: `the probe failed: ${error instanceof Error ? error.message : String(error)}` };\n }\n};\n","import type { Quantity } from \"@mark1russell7/quantity\";\nimport { valueIn } from \"@mark1russell7/quantity\";\nimport type { Latch, Result, Trace } from \"../latch.ts\";\nimport { latch } from \"../latch.ts\";\nimport type { Poller } from \"../poller.ts\";\nimport { poller } from \"../poller.ts\";\nimport type { Timing } from \"../timing.ts\";\nimport type { HostPorts } from \"./ports.ts\";\nimport type { ProbeResult, ReadyProbe } from \"./probes.ts\";\nimport { probeOnce, probeProblems } from \"./probes.ts\";\nimport { isTime } from \"./render.ts\";\n\n/**\n * A verdict tells when a target goes down and when it comes up again.\n * - `debounce`: `failAfter` failed polls in sequence make it down, and `recoverAfter` passed polls in sequence make it up.\n * - `window`: failures for the time `failAfter` make it down. Passes for the time `recoverAfter` make it up. Without\n * `recoverAfter`, the first pass makes it up.\n */\nexport type TargetVerdict =\n | { readonly type: \"debounce\"; readonly failAfter: number; readonly recoverAfter: number }\n | { readonly type: \"window\"; readonly failAfter: Quantity; readonly recoverAfter?: Quantity | undefined };\n\n/** A watch target is one thing that a watcher probes on its own loop. */\nexport interface WatchTarget {\n /** This name is unique in the spec. A change names its target with it. */\n readonly name: string;\n readonly probe: ReadyProbe;\n /** This time is between the starts of two polls. */\n readonly interval: Quantity;\n /** This time is the most that one poll waits. It is not above the interval. */\n readonly timeout: Quantity;\n /** This fraction moves each interval by up to ± its part, thus two watchers do not poll in step. The default is 0.1. */\n readonly jitter?: number | undefined;\n /** The default is a debounce: 3 failures make it down, and 2 passes make it up. */\n readonly verdict?: TargetVerdict | undefined;\n}\n\n/** A watch spec lists the targets of one watcher. */\nexport interface WatchSpec {\n readonly targets: readonly WatchTarget[];\n}\n\n/** The health of a target is `unknown` until its first verdict. */\nexport type TargetHealth = \"unknown\" | \"up\" | \"down\";\n\n/** A target change is one transition of the health of a target. */\nexport interface TargetChange {\n readonly target: string;\n readonly from: TargetHealth;\n readonly to: \"up\" | \"down\";\n /** This time is the wall time of the change, in milliseconds after the epoch. */\n readonly at: number;\n /** This text tells why the latest poll failed, for a change to down. It is null for a change to up. */\n readonly why: string | null;\n}\n\n/** A target state is what a watcher knows of one target at this time. */\nexport interface TargetState {\n readonly name: string;\n readonly health: TargetHealth;\n /** This time is the wall time of the latest change of the health, or of the start. */\n readonly since: number;\n /** This result is the latest poll, or null before the first poll. */\n readonly last: ProbeResult | null;\n /** This time is the wall time of the latest poll, or null. */\n readonly lastAt: number | null;\n /** This count is the failed polls in sequence. */\n readonly failures: number;\n}\n\nexport interface WatchOptions {\n /** This function gets each change of the health of a target. A throw in it does not stop the watcher. */\n readonly onChange: (change: TargetChange) => void;\n /** This function gives a number in [0, 1) for the jitter. The default is `Math.random`. */\n readonly random?: (() => number) | undefined;\n /** This function gets each transition of the poller and the latch of each target, with the name of the target. */\n readonly trace?: ((target: string, from: string, to: string, on: string) => void) | undefined;\n}\n\n/** A target watch is a running watcher. */\nexport interface TargetWatch {\n /** This method gives the state of each target, in the sequence of the spec. */\n states(): TargetState[];\n /** This method polls each target one time at once, outside its loop, and gives the states after the polls. */\n pollNow(): Promise<TargetState[]>;\n /** This method stops each loop. A stopped watcher gives no change. */\n stop(): void;\n}\n\n/** This verdict is the default: 3 failures in sequence make a target down, and 2 passes make it up. */\nexport const DEFAULT_VERDICT: TargetVerdict = { type: \"debounce\", failAfter: 3, recoverAfter: 2 };\nconst DEFAULT_JITTER = 0.1;\n\nconst ms = (amount: Quantity): number => valueIn(amount, \"ms\");\nconst isTimeAtLeast = (value: unknown, floor: number, strict: boolean): boolean => isTime(value) && (strict ? ms(value) > floor : ms(value) >= floor);\nconst whole = (value: number): boolean => Number.isInteger(value) && value >= 1;\n\n/** This function gives the problems of a watch spec: each value that the watcher cannot use. */\nexport const watchProblems = (spec: WatchSpec): string[] => {\n const problems: string[] = [];\n if (spec.targets.length === 0) problems.push(\"the spec has no target\");\n const names = new Set<string>();\n for (const target of spec.targets) {\n const of = `the target ${JSON.stringify(target.name)}`;\n if (target.name === \"\") problems.push(\"a target name is empty\");\n if (names.has(target.name)) problems.push(`${of} is in the spec two times`);\n names.add(target.name);\n problems.push(...probeProblems(target.probe).map((problem) => `${of}: ${problem}`));\n if (!isTimeAtLeast(target.interval, 0, true)) problems.push(`${of}: the interval is not a time above zero`);\n if (!isTimeAtLeast(target.timeout, 0, true)) problems.push(`${of}: the timeout is not a time above zero`);\n else if (isTimeAtLeast(target.interval, 0, true) && ms(target.timeout) > ms(target.interval)) problems.push(`${of}: the timeout is above the interval`);\n const jitter = target.jitter ?? DEFAULT_JITTER;\n if (!(Number.isFinite(jitter) && jitter >= 0 && jitter < 1)) problems.push(`${of}: the jitter ${jitter} is not a fraction from 0 to below 1`);\n const verdict = target.verdict ?? DEFAULT_VERDICT;\n if (verdict.type === \"debounce\") {\n if (!whole(verdict.failAfter)) problems.push(`${of}: the verdict fails after ${verdict.failAfter} polls, not a whole number above zero`);\n if (!whole(verdict.recoverAfter)) problems.push(`${of}: the verdict recovers after ${verdict.recoverAfter} polls, not a whole number above zero`);\n } else if (verdict.type === \"window\") {\n if (!isTimeAtLeast(verdict.failAfter, 0, false)) problems.push(`${of}: the failAfter of the window is not a time of zero or more`);\n if (verdict.recoverAfter !== undefined && !isTimeAtLeast(verdict.recoverAfter, 0, false))\n problems.push(`${of}: the recoverAfter of the window is not a time of zero or more`);\n } else problems.push(`${of}: the verdict type ${JSON.stringify((verdict as { type: unknown }).type)} is not debounce or window`);\n }\n return problems;\n};\n\nconst timingOf = (target: WatchTarget): Timing => {\n const verdict = target.verdict ?? DEFAULT_VERDICT;\n return verdict.type === \"debounce\"\n ? { type: \"debounce\", interval: target.interval, failAfter: verdict.failAfter, recoverAfter: verdict.recoverAfter }\n : { type: \"window\", failAfter: verdict.failAfter, recoverAfter: verdict.recoverAfter };\n};\n\ninterface Unit {\n readonly target: WatchTarget;\n health: TargetHealth;\n since: number;\n last: ProbeResult | null;\n lastAt: number | null;\n failures: number;\n /** This text is the reason of the latest failed poll. */\n why: string | null;\n}\n\n/**\n * This function starts a watcher of targets: an outside prober. Each target has its own loop of polls, on the\n * clock of the ports, with a jitter. A verdict turns the polls into the health of the target: a debounce or a\n * window. A target is `unknown` at the start. Its first pass makes it up, and its verdict makes it down. Each change\n * goes to `onChange`, with the reason of the latest failed poll. The watcher throws at the start when the spec has a\n * problem.\n */\nexport const watchTargets = (spec: WatchSpec, ports: HostPorts, options: WatchOptions): TargetWatch => {\n const problems = watchProblems(spec);\n if (problems.length > 0) throw new Error(`the watch spec has problems: ${problems.join(\"; \")}`);\n const random = options.random ?? Math.random;\n let stopped = false;\n\n const emit = (unit: Unit, to: \"up\" | \"down\"): void => {\n if (unit.health === to) return;\n const change: TargetChange = { target: unit.target.name, from: unit.health, to, at: ports.wall(), why: to === \"down\" ? unit.why : null };\n unit.health = to;\n unit.since = change.at;\n if (stopped) return;\n try {\n options.onChange(change);\n } catch (error) {\n ports.logger?.log(\"warn\", `the change handler of the watch failed: ${error instanceof Error ? error.message : String(error)}`, { target: change.target });\n }\n };\n\n const watched = spec.targets.map((target): { readonly unit: Unit; readonly gate: Latch; readonly loop: Poller } => {\n const unit: Unit = { target, health: \"unknown\", since: ports.wall(), last: null, lastAt: null, failures: 0, why: null };\n const trace: Trace | undefined = options.trace === undefined ? undefined : (from, to, on) => options.trace?.(target.name, from, to, on);\n const timeout = ms(target.timeout);\n // the result of the latest probe: a poller result tells only the outcome\n let probed: ProbeResult | null = null;\n const gate: Latch = latch(timingOf(target), ports.clock, false, () => emit(unit, gate.tripped ? \"down\" : \"up\"), trace);\n const record = (result: Result): void => {\n const own = probed;\n probed = null;\n // a timeout or a pending call has the cause of the poller: the probe gave no result for this poll\n const seen: ProbeResult =\n result.outcome === \"ok\" ? { ok: true } : { ok: false, why: !result.timedOut && own !== null && !own.ok ? own.why : (result.cause ?? \"the poll failed\") };\n unit.last = seen;\n unit.lastAt = ports.wall();\n unit.failures = seen.ok ? 0 : unit.failures + 1;\n if (!seen.ok) unit.why = seen.why;\n gate.record(result);\n if (seen.ok && unit.health === \"unknown\" && !gate.tripped) emit(unit, \"up\");\n };\n const loop = poller({\n name: target.name,\n poll: { interval: target.interval, jitter: target.jitter ?? DEFAULT_JITTER, timeout: target.timeout },\n run: async () => {\n const result = await probeOnce(target.probe, timeout, ports);\n probed = result;\n return result.ok ? \"ok\" : \"error\";\n },\n clock: ports.clock,\n random,\n forced: () => false,\n record,\n trace,\n });\n return { unit, gate, loop };\n });\n\n const states = (): TargetState[] =>\n watched.map(({ unit }) => ({ name: unit.target.name, health: unit.health, since: unit.since, last: unit.last, lastAt: unit.lastAt, failures: unit.failures }));\n\n for (const { loop } of watched) loop.start(0);\n\n return {\n states,\n async pollNow() {\n await Promise.all(watched.map(({ loop }) => loop.pollNow()));\n return states();\n },\n stop() {\n if (stopped) return;\n stopped = true;\n for (const { gate, loop } of watched) {\n loop.stop();\n gate.stop();\n }\n },\n };\n};\n","/** An env file is the variables of a file of environment variables, and the problem of each line that it skipped. */\nexport interface EnvFile {\n readonly env: Readonly<Record<string, string>>;\n readonly problems: readonly string[];\n}\n\nconst KEY = /^[A-Za-z_][A-Za-z0-9_]*$/;\n\n/** This function reads a value in double quotes: `\\n`, `\\t`, `\\\"` and `\\\\` are escapes. */\nconst doubleQuoted = (body: string): string =>\n body.replace(/\\\\(.)/g, (_match, char: string) => (char === \"n\" ? \"\\n\" : char === \"t\" ? \"\\t\" : char === \"r\" ? \"\\r\" : char));\n\n/**\n * This function reads a file of environment variables, one `KEY=value` on each line. It is a pure\n * function. It does not throw: it skips a bad line and gives its problem.\n * - A blank line and a line that starts with `#` are skipped. A line can start with `export `.\n * - A value in single quotes is literal. A value in double quotes has the escapes `\\n`, `\\t`, `\\\"` and `\\\\`.\n * - A value without quotes ends at ` #`, and its spaces at the two ends go.\n * - A key that comes again replaces its value.\n */\nexport const parseEnvFile = (text: string): EnvFile => {\n const env: Record<string, string> = {};\n const problems: string[] = [];\n // a byte order mark at the start is not a part of the first key\n const lines = (text.charCodeAt(0) === 0xfeff ? text.slice(1) : text).split(/\\r?\\n/);\n lines.forEach((raw, at) => {\n const line = raw.trim();\n if (line === \"\" || line.startsWith(\"#\")) return;\n const body = line.startsWith(\"export \") ? line.slice(\"export \".length).trimStart() : line;\n const equals = body.indexOf(\"=\");\n if (equals <= 0) {\n problems.push(`line ${at + 1} has no KEY=value`);\n return;\n }\n const key = body.slice(0, equals).trim();\n if (!KEY.test(key)) {\n problems.push(`line ${at + 1}: ${JSON.stringify(key)} is not a name of a variable`);\n return;\n }\n const rest = body.slice(equals + 1).trim();\n const quote = rest[0];\n if (quote === '\"' || quote === \"'\") {\n const end = quote === \"'\" ? rest.indexOf(\"'\", 1) : closingQuote(rest);\n if (end < 0) {\n problems.push(`line ${at + 1}: the value of ${key} has no closing quote`);\n return;\n }\n env[key] = quote === \"'\" ? rest.slice(1, end) : doubleQuoted(rest.slice(1, end));\n return;\n }\n const comment = rest.search(/\\s#/);\n env[key] = (comment < 0 ? rest : rest.slice(0, comment)).trim();\n });\n return { env, problems };\n};\n\n/** This function gives the place of the double quote that closes a value, or -1. A quote after a backslash does not close it. */\nconst closingQuote = (text: string): number => {\n for (let at = 1; at < text.length; at += 1) {\n if (text[at] === \"\\\\\") at += 1;\n else if (text[at] === '\"') return at;\n }\n return -1;\n};\n","import type { Quantity } from \"@mark1russell7/quantity\";\nimport { valueIn } from \"@mark1russell7/quantity\";\nimport type { FilePort } from \"./ports.ts\";\n\n/** A log spec tells where the output of a program goes, and when the file rotates. */\nexport interface LogSpec {\n /** This path is the log file. */\n readonly path: string;\n /** This size is the most that the file gets before it rotates, for example `{ value: 10, unit: \"MB\" }`. */\n readonly maxSize: Quantity;\n /** This count is the number of old files that stay: `<path>.1` is the newest. 0 keeps no old file. */\n readonly keep: number;\n}\n\n/** A rotating log writes data to a file, and rotates the file at its size. */\nexport interface RotatingLog {\n /** This method adds data to the log. The writes occur in sequence. A failed write does not throw. */\n write(chunk: string | Uint8Array): void;\n /** This promise ends when each write before it is done. */\n flush(): Promise<void>;\n /** This count is the number of writes that failed. */\n readonly failures: number;\n}\n\nconst byteLength = (chunk: string | Uint8Array): number => (typeof chunk === \"string\" ? new TextEncoder().encode(chunk).length : chunk.length);\n\n/**\n * This function makes a rotating log on a file port. Before a write that makes the file larger than\n * `maxSize`, the file rotates: `<path>.<keep>` goes, each `<path>.<n>` becomes `<path>.<n + 1>`, and the\n * file becomes `<path>.1`. A chunk larger than the size goes into a new file of its own.\n */\nexport const rotatingLog = (spec: LogSpec, files: FilePort): RotatingLog => {\n const max = valueIn(spec.maxSize, \"B\");\n let chain: Promise<void> = Promise.resolve();\n let size: number | null = null;\n let failures = 0;\n const rotate = async (): Promise<void> => {\n if (spec.keep <= 0) {\n await files.remove(spec.path);\n return;\n }\n await files.remove(`${spec.path}.${spec.keep}`);\n for (let at = spec.keep - 1; at >= 1; at -= 1)\n if ((await files.size(`${spec.path}.${at}`)) !== null) await files.rename(`${spec.path}.${at}`, `${spec.path}.${at + 1}`);\n await files.rename(spec.path, `${spec.path}.1`);\n };\n const append = async (chunk: string | Uint8Array): Promise<void> => {\n const length = byteLength(chunk);\n size ??= (await files.size(spec.path)) ?? 0;\n if (size > 0 && size + length > max) {\n await rotate();\n size = 0;\n }\n await files.append(spec.path, chunk);\n size += length;\n };\n return {\n write(chunk) {\n chain = chain.then(() => append(chunk)).catch(() => {\n failures += 1;\n // the size is not known after a failure: the next write reads it again\n size = null;\n });\n },\n flush: () => chain,\n get failures() {\n return failures;\n },\n };\n};\n","import type { Quantity } from \"@mark1russell7/quantity\";\nimport { convertible, isQuantity, valueIn } from \"@mark1russell7/quantity\";\nimport type { Backoff } from \"../backoff.ts\";\nimport { backoffProblems } from \"../backoff.ts\";\nimport type { Cancel } from \"../clock.ts\";\nimport type { LogFields, LogLevel } from \"../logger.ts\";\nimport type { MessageShape } from \"../process.ts\";\nimport { isMessageShape } from \"../process.ts\";\nimport type { Retrier } from \"../retrier.ts\";\nimport { retrier } from \"../retrier.ts\";\nimport { removeDiscovery, writeDiscovery } from \"./discovery.ts\";\nimport { parseEnvFile } from \"./env.ts\";\nimport type { InstanceLock } from \"./lock.ts\";\nimport { acquireInstanceLock } from \"./lock.ts\";\nimport type { LogSpec, RotatingLog } from \"./logs.ts\";\nimport { rotatingLog } from \"./logs.ts\";\nimport type { ChildHandle, HostPorts } from \"./ports.ts\";\nimport { joinPath } from \"./ports.ts\";\nimport type { ReadyProbe } from \"./probes.ts\";\nimport { probeOnce, probeProblems } from \"./probes.ts\";\nimport { stopTree } from \"./processes.ts\";\nimport { isTime } from \"./render.ts\";\n\n/** A ready spec tells how the supervisor finds that a program is ready. */\nexport interface ReadySpec {\n readonly probe: ReadyProbe;\n /** This time is the pause between two uses of the probe. */\n readonly interval: Quantity;\n /** This time is the most that one use of the probe can take. */\n readonly timeout: Quantity;\n /** This time is the most that the program can take to be ready. After it, the supervisor stops the program and starts it again. */\n readonly within: Quantity;\n}\n\n/**\n * An alive spec tells how the supervisor finds that a ready program still works. A program can hang and not exit:\n * its process stays, and only a probe finds it. After `failures` failures in sequence, the supervisor stops the\n * program in stages and starts it again after its backoff.\n */\nexport interface AliveSpec {\n readonly probe: ReadyProbe;\n /** This time is the pause between two uses of the probe. The first use is one interval after the program is ready. */\n readonly interval: Quantity;\n /** This time is the most that one use of the probe can take. */\n readonly timeout: Quantity;\n /** This count of failures in sequence stops the program: a whole number of 1 or more. A pass sets the count to 0. */\n readonly failures: number;\n}\n\n/** A program restart tells how the supervisor starts a program again after it stops. */\nexport interface ProgramRestart {\n /** This backoff gives the wait before each start again, in milliseconds, as `retrier` uses it. */\n readonly backoff: Backoff;\n /** This time is how long a program is ready before its count of tries goes back to 0. */\n readonly resetAfter: Quantity;\n}\n\n/** A stop spec tells how the supervisor stops a program. */\nexport interface StopSpec {\n /** This time is the wait for the staged stop, before the supervisor stops the process tree. */\n readonly grace: Quantity;\n /** This message goes on the IPC channel of a child that has one. The default is `\"shutdown\"`, which `run()` can match. */\n readonly message?: MessageShape | undefined;\n /** This signal goes to a child without an IPC channel on Linux. The default is `SIGTERM`. */\n readonly signal?: \"SIGINT\" | \"SIGTERM\" | undefined;\n}\n\n/** A program spec tells one program of a group, and what it needs before it starts. */\nexport interface ProgramSpec {\n /** This name is the name of the program in the group: letters, digits, `.`, `_` and `-`. */\n readonly name: string;\n readonly program: string;\n readonly args?: readonly string[] | undefined;\n readonly cwd?: string | undefined;\n /** These variables go to the program. They replace the variables of the env file and of the host. */\n readonly env?: Readonly<Record<string, string>> | undefined;\n /** This file gives variables to the program at each start (`parseEnvFile`). They replace the variables of the host. */\n readonly envFile?: string | undefined;\n /** These are the programs that must be ready before this program starts. */\n readonly after?: readonly string[] | undefined;\n /** This spec tells when the program is ready. Without it, the program is ready when it starts. */\n readonly ready?: ReadySpec | undefined;\n /** This spec tells how the supervisor finds that the ready program still works. Without it, only an exit starts the program again. */\n readonly alive?: AliveSpec | undefined;\n /** This policy starts the program again after it stops. The default is `DEFAULT_RESTART`. Null does not start it again. */\n readonly restart?: ProgramRestart | null | undefined;\n /** This spec tells the log file. The default is `<stateDir>/logs/<name>.log`, 10 MB, with 3 old files. Null keeps no log. */\n readonly log?: LogSpec | null | undefined;\n /** True gives the child an IPC channel, for the staged stop of a Node program. The default is false. */\n readonly ipc?: boolean | undefined;\n /** This spec tells the stop. The default is a grace of 10 s. */\n readonly stop?: StopSpec | undefined;\n /** These fields go in the discovery file of the program, `<stateDir>/<name>.json`. */\n readonly listen?: { readonly port?: number | null | undefined; readonly url?: string | null | undefined } | undefined;\n}\n\n/** A group spec tells a group of programs that one supervisor starts in sequence and keeps alive. */\nexport interface GroupSpec {\n readonly name: string;\n /** This folder keeps the lock, the discovery file and the log of each program. */\n readonly stateDir: string;\n readonly programs: readonly ProgramSpec[];\n}\n\n/** These options go with a supervisor. */\nexport interface GroupOptions {\n /** This function gives a number in [0, 1) for the jitter of the backoff. The default is `Math.random`. */\n readonly random?: (() => number) | undefined;\n}\n\n/**\n * A program phase tells where a program of a group is.\n * - `waiting`: a program that it needs is not ready.\n * - `starting`: it runs, and its probe did not pass.\n * - `ready`: it runs, and its probe passed.\n * - `backoff`: it stopped, and it starts again after its backoff.\n * - `held`: another instance holds its lock. The supervisor tries again after the backoff.\n * - `exited`: it stopped, and it has no restart.\n * - `stopping`, `stopped`: the stop of the group.\n */\nexport type ProgramPhase = \"waiting\" | \"starting\" | \"ready\" | \"backoff\" | \"held\" | \"exited\" | \"stopping\" | \"stopped\";\n\n/** A program state is the state of one program of a group, for a status. */\nexport interface ProgramState {\n readonly name: string;\n readonly phase: ProgramPhase;\n /** This number is the process ID of the child, or null. */\n readonly pid: number | null;\n /** This count is the number of starts again since the start of the group. */\n readonly restarts: number;\n /** This text tells the last problem, for example why the probe failed, or it is null. */\n readonly detail: string | null;\n}\n\n/** A group supervisor starts the programs of a group in sequence, starts each again after it stops, and stops them in stages. */\nexport interface GroupSupervisor {\n /** This method starts each program whose programs are ready. A second use does nothing. */\n start(): void;\n /** This method stops each program in the reverse sequence of the start. A second use gives the same promise. */\n stop(): Promise<void>;\n /** This method gives the state of each program, in the sequence of the spec. */\n states(): readonly ProgramState[];\n}\n\n/**\n * This restart is the default. The first wait is 1 s, and each wait after it is two times longer, to 1 min.\n * The jitter subtracts up to half of each wait. The count of tries goes back to 0 after 1 min ready.\n */\nexport const DEFAULT_RESTART: ProgramRestart = {\n backoff: { base: 1000, factor: 2, cap: 60_000, jitter: { kind: \"subtract\", fraction: 0.5 } },\n resetAfter: { value: 60, unit: \"s\" },\n};\n\nconst DEFAULT_GRACE: Quantity = { value: 10, unit: \"s\" };\nconst DEFAULT_LOG_SIZE: Quantity = { value: 10, unit: \"MB\" };\nconst DEFAULT_LOG_KEEP = 3;\nconst NAME = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;\n\nconst ms = (time: Quantity): number => valueIn(time, \"ms\");\n\n/**\n * This function gives the start sequence of a group, as layers of names. Each program of a layer needs only programs of the\n * layers before it. A program in a cycle, or after an unknown program, is in no layer. `groupProblems` names it.\n */\nexport const startOrder = (spec: GroupSpec): string[][] => {\n const names = new Set(spec.programs.map((program) => program.name));\n const placed = new Set<string>();\n const layers: string[][] = [];\n for (;;) {\n const layer = spec.programs\n .filter((program) => !placed.has(program.name))\n .filter((program) => (program.after ?? []).every((name) => names.has(name) && placed.has(name)))\n .map((program) => program.name);\n if (layer.length === 0) return layers;\n for (const name of layer) placed.add(name);\n layers.push([...new Set(layer)]);\n }\n};\n\nconst isTimeAtLeast = (value: unknown, floor: number, strict: boolean): boolean =>\n isTime(value) && (strict ? ms(value) > floor : ms(value) >= floor);\n\n/** This function gives the problems of a group spec: each value that the supervisor cannot use. */\nexport const groupProblems = (spec: GroupSpec): string[] => {\n const problems: string[] = [];\n if (!NAME.test(spec.name)) problems.push(`the group name ${JSON.stringify(spec.name)} is not letters, digits, \".\", \"_\" and \"-\"`);\n if (spec.stateDir === \"\") problems.push(\"the stateDir is empty\");\n if (spec.programs.length === 0) problems.push(\"the group has no programs\");\n const seen = new Set<string>();\n const names = new Set(spec.programs.map((program) => program.name));\n for (const program of spec.programs) {\n const name = program.name;\n const of = `the program ${JSON.stringify(name)}`;\n if (!NAME.test(name)) problems.push(`${of}: the name is not letters, digits, \".\", \"_\" and \"-\"`);\n if (seen.has(name)) problems.push(`${of} comes two times`);\n seen.add(name);\n if (program.program === \"\") problems.push(`${of}: the program is empty`);\n for (const need of program.after ?? []) {\n if (need === name) problems.push(`${of} is after itself`);\n else if (!names.has(need)) problems.push(`${of} is after ${JSON.stringify(need)}, which is not in the group`);\n }\n if (program.ready !== undefined) {\n problems.push(...probeProblems(program.ready.probe).map((problem) => `${of}: ${problem}`));\n for (const field of [\"interval\", \"timeout\", \"within\"] as const)\n if (!isTimeAtLeast(program.ready[field], 0, true)) problems.push(`${of}: the ${field} of the probe is not a time above zero`);\n }\n if (program.alive !== undefined) {\n problems.push(...probeProblems(program.alive.probe).map((problem) => `${of}: the liveness probe: ${problem}`));\n for (const field of [\"interval\", \"timeout\"] as const)\n if (!isTimeAtLeast(program.alive[field], 0, true)) problems.push(`${of}: the ${field} of the liveness probe is not a time above zero`);\n if (!(Number.isInteger(program.alive.failures) && program.alive.failures >= 1))\n problems.push(`${of}: the failures of the liveness probe is not a whole number of 1 or more`);\n }\n if (program.restart !== undefined && program.restart !== null) {\n problems.push(...backoffProblems(program.restart.backoff).map((problem) => `${of}: ${problem}`));\n if (!isTimeAtLeast(program.restart.resetAfter, 0, false)) problems.push(`${of}: the resetAfter is not a time of zero or more`);\n }\n if (program.log !== undefined && program.log !== null) {\n const size = program.log.maxSize;\n if (!(isQuantity(size) && convertible(size.unit, \"B\") && valueIn(size, \"B\") > 0)) problems.push(`${of}: the maxSize of the log is not a size above zero`);\n if (!(Number.isInteger(program.log.keep) && program.log.keep >= 0)) problems.push(`${of}: the keep of the log is not a whole number of zero or more`);\n if (program.log.path === \"\") problems.push(`${of}: the path of the log is empty`);\n }\n if (program.stop !== undefined) {\n if (!isTimeAtLeast(program.stop.grace, 0, false)) problems.push(`${of}: the grace of the stop is not a time of zero or more`);\n if (program.stop.message !== undefined && !isMessageShape(program.stop.message)) problems.push(`${of}: the stop message is not a value of JSON`);\n const signal = program.stop.signal;\n if (signal !== undefined && signal !== \"SIGINT\" && signal !== \"SIGTERM\") problems.push(`${of}: the stop signal ${JSON.stringify(signal)} is not SIGINT or SIGTERM`);\n }\n const port = program.listen?.port;\n if (port !== undefined && port !== null && !(Number.isInteger(port) && port >= 1 && port <= 65_535))\n problems.push(`${of}: the port ${port} is not a port from 1 to 65535`);\n }\n const placed = new Set(startOrder(spec).flat());\n const left = spec.programs.filter((program) => !placed.has(program.name) && (program.after ?? []).every((need) => names.has(need) && need !== program.name));\n if (left.length > 0) problems.push(`the programs ${left.map((program) => JSON.stringify(program.name)).join(\", \")} are in a cycle of \"after\", or after a program in one`);\n return problems;\n};\n\n/** The supervisor keeps one unit for each program: its spec, its files and its state. */\ninterface Unit {\n readonly spec: ProgramSpec;\n readonly lockPath: string;\n readonly discoveryPath: string;\n readonly log: RotatingLog | null;\n readonly retry: Retrier | null;\n phase: ProgramPhase;\n child: ChildHandle | null;\n lock: InstanceLock | null;\n timers: Cancel[];\n /** This cancel stops the next use of the liveness probe. It is one timer, thus a long life adds no timers. */\n watch: Cancel | null;\n restarts: number;\n detail: string | null;\n /** This text tells why the supervisor stopped the child, or it is null. */\n reason: string | null;\n waiters: Array<() => void>;\n}\n\n/**\n * This function makes the supervisor of a group. It refuses a spec with problems. Each effect goes\n * through the ports, thus a test gives `fakeHost()` and starts no process.\n * - A program starts when each program of its `after` is ready. It takes its lock first, thus a second instance does not start.\n * - A program with a probe is ready when its probe passes. A program that is not ready in `within` stops, and starts again.\n * - A program that stops starts again after the backoff of its `retrier`, when its programs are ready.\n * - Its output goes to its rotating log. Its environment is the host, then its env file, then its `env`.\n * - The stop goes in the reverse sequence: the staged stop first, and after the grace, the stop of the process tree by its ID.\n */\nexport const superviseGroup = (spec: GroupSpec, ports: HostPorts, options: GroupOptions = {}): GroupSupervisor => {\n const problems = groupProblems(spec);\n if (problems.length > 0) throw new Error(`the group ${spec.name} has problems: ${problems.join(\"; \")}`);\n const abort = new AbortController();\n const layers = startOrder(spec);\n let started = false;\n let stopping = false;\n let stopped: Promise<void> | null = null;\n\n const say = (level: LogLevel, message: string, fields: LogFields): void => {\n try {\n ports.logger?.log(level, message, { group: spec.name, ...fields });\n } catch {\n // the supervisor does not depend on its logger\n }\n };\n\n const units = new Map<string, Unit>();\n for (const program of spec.programs) {\n const restart = program.restart === undefined ? DEFAULT_RESTART : program.restart;\n const logSpec =\n program.log === undefined\n ? { path: joinPath(ports.platform, spec.stateDir, \"logs\", `${program.name}.log`), maxSize: DEFAULT_LOG_SIZE, keep: DEFAULT_LOG_KEEP }\n : program.log;\n units.set(program.name, {\n spec: program,\n lockPath: joinPath(ports.platform, spec.stateDir, `${program.name}.lock`),\n discoveryPath: joinPath(ports.platform, spec.stateDir, `${program.name}.json`),\n log: logSpec === null ? null : rotatingLog(logSpec, ports.files),\n retry:\n restart === null\n ? null\n : retrier({ ...restart.backoff, clock: ports.clock, signal: abort.signal, ...(options.random === undefined ? {} : { random: options.random }) }),\n phase: \"waiting\",\n child: null,\n lock: null,\n timers: [],\n watch: null,\n restarts: 0,\n detail: null,\n reason: null,\n waiters: [],\n });\n }\n const unitOf = (name: string): Unit => units.get(name)!;\n\n const clearTimers = (unit: Unit): void => {\n for (const cancel of unit.timers.splice(0)) cancel();\n unit.watch?.();\n unit.watch = null;\n };\n\n const environment = async (unit: Unit): Promise<Record<string, string>> => {\n const env: Record<string, string> = {};\n for (const [key, value] of Object.entries(ports.env)) if (value !== undefined) env[key] = value;\n const file = unit.spec.envFile;\n if (file !== undefined) {\n try {\n const text = await ports.files.read(file);\n if (text === null) say(\"warn\", `the env file ${file} of ${unit.spec.name} does not exist`, { program: unit.spec.name, file });\n else {\n const parsed = parseEnvFile(text);\n Object.assign(env, parsed.env);\n for (const problem of parsed.problems) say(\"warn\", `the env file ${file} of ${unit.spec.name}: ${problem}`, { program: unit.spec.name, file });\n }\n } catch (error) {\n say(\"warn\", `the read of the env file ${file} of ${unit.spec.name} failed`, { program: unit.spec.name, file, error });\n }\n }\n return Object.assign(env, unit.spec.env ?? {});\n };\n\n const consider = (unit: Unit): void => {\n if (!started || stopping || unit.phase !== \"waiting\") return;\n if (!(unit.spec.after ?? []).every((name) => unitOf(name).phase === \"ready\")) return;\n void launch(unit);\n };\n const considerAll = (): void => {\n for (const layer of layers) for (const name of layer) consider(unitOf(name));\n };\n\n /** This function starts the program again after the backoff, or ends it when it has no restart. */\n const later = (unit: Unit, phase: \"backoff\" | \"held\"): void => {\n const delay = unit.retry?.schedule(() => {\n if (stopping) return;\n unit.phase = \"waiting\";\n unit.restarts += 1;\n consider(unit);\n });\n if (delay === undefined || delay === null) {\n unit.phase = phase === \"held\" ? \"held\" : \"exited\";\n void unit.lock?.release();\n unit.lock = null;\n return;\n }\n unit.phase = phase;\n say(\"info\", `${unit.spec.name} starts again in ${delay} ms`, { program: unit.spec.name, delay: { value: delay, unit: \"ms\" }, attempt: unit.retry?.attempts });\n };\n\n const markReady = (unit: Unit, child: ChildHandle): void => {\n if (unit.child !== child || stopping) return;\n unit.phase = \"ready\";\n unit.detail = null;\n say(\"info\", `${unit.spec.name} is ready`, { program: unit.spec.name, pid: child.pid });\n const restart = unit.spec.restart === undefined ? DEFAULT_RESTART : unit.spec.restart;\n if (unit.retry !== null && restart !== null)\n unit.timers.push(\n ports.clock.after(ms(restart.resetAfter), () => {\n if (unit.child === child && unit.phase === \"ready\") unit.retry?.reset();\n }),\n );\n if (unit.spec.alive !== undefined) watch(unit, child, unit.spec.alive);\n considerAll();\n };\n\n /** This function uses the liveness probe of a ready program each interval, and stops the program after `failures` failures in sequence. */\n const watch = (unit: Unit, child: ChildHandle, alive: AliveSpec): void => {\n let failures = 0;\n const current = (): boolean => unit.child === child && unit.phase === \"ready\" && !stopping;\n const next = (): void => {\n unit.watch = ports.clock.after(ms(alive.interval), () => {\n unit.watch = null;\n void check();\n });\n };\n const check = async (): Promise<void> => {\n if (!current()) return;\n const result = await probeOnce(alive.probe, ms(alive.timeout), ports);\n if (!current()) return;\n if (result.ok) {\n if (failures > 0) say(\"info\", `${unit.spec.name} is alive again`, { program: unit.spec.name, pid: child.pid, failures });\n failures = 0;\n unit.detail = null;\n next();\n return;\n }\n failures += 1;\n unit.detail = `the liveness probe failed ${failures} of ${alive.failures} times in sequence (${result.why})`;\n if (failures < alive.failures) {\n say(\"warn\", `${unit.spec.name}: ${unit.detail}`, { program: unit.spec.name, pid: child.pid, why: result.why });\n next();\n return;\n }\n unit.reason = `its liveness probe failed ${failures} times in sequence (${result.why})`;\n unit.detail = unit.reason;\n say(\"warn\", `${unit.spec.name} is not alive, thus it stops`, { program: unit.spec.name, pid: child.pid, why: result.why });\n void stagedStop(unit, child);\n };\n next();\n };\n\n const probe = (unit: Unit, child: ChildHandle, ready: ReadySpec): void => {\n const deadline = ports.clock.now() + ms(ready.within);\n const attempt = async (): Promise<void> => {\n if (unit.child !== child || stopping) return;\n const result = await probeOnce(ready.probe, ms(ready.timeout), ports);\n if (unit.child !== child || stopping) return;\n if (result.ok) {\n markReady(unit, child);\n return;\n }\n unit.detail = result.why;\n if (ports.clock.now() >= deadline) {\n unit.reason = `it was not ready in ${ms(ready.within)} ms (${result.why})`;\n unit.detail = unit.reason;\n say(\"warn\", `${unit.spec.name} is not ready in its time, thus it stops`, { program: unit.spec.name, pid: child.pid, why: result.why });\n void stagedStop(unit, child);\n return;\n }\n unit.timers.push(ports.clock.after(ms(ready.interval), () => void attempt()));\n };\n void attempt();\n };\n\n const exited = (unit: Unit, child: ChildHandle, code: number | null, signal: string | null): void => {\n if (unit.child !== child) return;\n clearTimers(unit);\n unit.child = null;\n for (const waiter of unit.waiters.splice(0)) waiter();\n if (child.pid !== null) void removeDiscovery(unit.discoveryPath, ports, child.pid);\n void unit.lock?.update(null).catch(() => {});\n if (stopping || unit.phase === \"stopping\") {\n unit.phase = \"stopped\";\n return;\n }\n const end = child.pid === null ? `${unit.spec.program} did not start` : `it exited with ${code === null ? `the signal ${signal ?? \"unknown\"}` : `the code ${code}`}`;\n unit.detail = unit.reason === null ? end : `${unit.reason}, then ${end}`;\n unit.reason = null;\n say(\"warn\", `${unit.spec.name} stopped: ${unit.detail}`, { program: unit.spec.name, pid: child.pid, code, signal });\n later(unit, \"backoff\");\n };\n\n const launch = async (unit: Unit): Promise<void> => {\n unit.phase = \"starting\";\n unit.detail = null;\n const name = unit.spec.name;\n if (unit.lock === null) {\n const taken = await acquireInstanceLock(unit.lockPath, ports);\n if (stopping) {\n if (taken.kind === \"acquired\") await taken.lock.release();\n return;\n }\n if (taken.kind !== \"acquired\") {\n unit.detail = taken.kind === \"held\" ? `the process ${taken.owner.child?.pid ?? taken.owner.pid} holds the lock ${unit.lockPath}` : taken.problem;\n say(\"warn\", `${name} does not start: ${unit.detail}`, { program: name, lock: unit.lockPath });\n later(unit, \"held\");\n return;\n }\n unit.lock = taken.lock;\n }\n const lock = unit.lock;\n const env = await environment(unit);\n if (stopping) {\n await lock.release();\n unit.lock = null;\n return;\n }\n const child = ports.processes.spawn({ program: unit.spec.program, args: unit.spec.args ?? [], cwd: unit.spec.cwd, env, ipc: unit.spec.ipc ?? false });\n const startedAt = ports.wall();\n unit.child = child;\n child.onOutput((_stream, chunk) => unit.log?.write(chunk));\n child.onExit((code, signal) => exited(unit, child, code, signal));\n const pid = child.pid;\n if (pid === null) return;\n say(\"info\", `${name} started`, { program: name, pid });\n const mark = { pid, startedAt };\n try {\n await lock.update(mark);\n await writeDiscovery(\n unit.discoveryPath,\n { pid, startedAt: new Date(startedAt).toISOString(), port: unit.spec.listen?.port ?? null, url: unit.spec.listen?.url ?? null, extra: { group: spec.name, program: name } },\n ports,\n );\n } catch (error) {\n say(\"warn\", `the files of ${name} were not written`, { program: name, error });\n }\n // a child that ended during the writes leaves no discovery file\n if (unit.child !== child) await removeDiscovery(unit.discoveryPath, ports, pid);\n if (unit.child !== child || stopping) return;\n if (unit.spec.ready === undefined) markReady(unit, child);\n else probe(unit, child, unit.spec.ready);\n };\n\n /** This function waits for the end of a child, for at most `wait` milliseconds. It tells if the child ended. */\n const ended = (unit: Unit, child: ChildHandle, wait: number): Promise<boolean> =>\n new Promise((resolve) => {\n if (unit.child !== child) {\n resolve(true);\n return;\n }\n const cancel = ports.clock.after(wait, () => resolve(unit.child !== child));\n unit.waiters.push(() => {\n cancel();\n resolve(true);\n });\n });\n\n /**\n * This function stops a child in stages. The message goes on its IPC channel when it has one. Else\n * Linux gets SIGTERM, and Windows gets `taskkill /T` without `/F`. After the grace, the process tree stops by its ID.\n */\n const stagedStop = async (unit: Unit, child: ChildHandle): Promise<void> => {\n const pid = child.pid;\n if (pid === null || unit.child !== child) return;\n const grace = ms(unit.spec.stop?.grace ?? DEFAULT_GRACE);\n const gone = ended(unit, child, grace);\n let asked: string | null = null;\n if (child.ipc && child.send(unit.spec.stop?.message ?? \"shutdown\")) asked = \"the IPC message\";\n else if (ports.platform === \"win32\") {\n const result = await ports.commands.run(\"taskkill\", [\"/T\", \"/PID\", String(pid)]).catch(() => null);\n if (result?.code === 0) asked = \"taskkill\";\n } else {\n const signal = unit.spec.stop?.signal ?? \"SIGTERM\";\n if (ports.processes.signal(pid, signal)) asked = signal;\n }\n say(\"info\", `${unit.spec.name} stops${asked === null ? \"\" : ` through ${asked}`}`, { program: unit.spec.name, pid, grace: { value: grace, unit: \"ms\" } });\n if (asked !== null && (await gone)) return;\n const tree = await stopTree(pid, ports);\n const why = asked === null ? \"the staged stop did not go\" : \"it did not stop in its grace\";\n say(tree.kind === \"failed\" ? \"error\" : \"warn\", `${unit.spec.name}: ${why}, thus its process tree stops: ${tree.kind}`, {\n program: unit.spec.name,\n pid,\n outcome: tree.kind,\n });\n if (!(await ended(unit, child, grace))) say(\"error\", `${unit.spec.name} did not end after the stop of its process tree`, { program: unit.spec.name, pid });\n };\n\n const stopUnit = async (unit: Unit): Promise<void> => {\n clearTimers(unit);\n const child = unit.child;\n const pid = child?.pid ?? null;\n if (child !== null && pid !== null) {\n unit.phase = \"stopping\";\n await stagedStop(unit, child);\n await removeDiscovery(unit.discoveryPath, ports, pid);\n }\n unit.phase = \"stopped\";\n await unit.lock?.release();\n unit.lock = null;\n };\n\n return {\n start() {\n if (started || stopping) return;\n started = true;\n say(\"info\", `the group ${spec.name} starts`, { layers });\n considerAll();\n },\n stop() {\n if (stopped !== null) return stopped;\n stopping = true;\n abort.abort();\n stopped = (async () => {\n for (const layer of [...layers].reverse()) await Promise.all(layer.map((name) => stopUnit(unitOf(name))));\n await Promise.all([...units.values()].map((unit) => unit.log?.flush()));\n say(\"info\", `the group ${spec.name} stopped`, {});\n })();\n return stopped;\n },\n states() {\n return spec.programs.map((program) => {\n const unit = unitOf(program.name);\n return { name: program.name, phase: unit.phase, pid: unit.child?.pid ?? null, restarts: unit.restarts, detail: unit.detail };\n });\n },\n };\n};\n","import type { Serializable } from \"node:child_process\";\nimport { execFile, spawn as spawnChild } from \"node:child_process\";\nimport { appendFile, mkdir, readFile, rename, rm, stat, writeFile } from \"node:fs/promises\";\nimport { connect } from \"node:net\";\nimport { homedir, userInfo } from \"node:os\";\nimport { dirname } from \"node:path\";\nimport type { Clock } from \"../clock.ts\";\nimport { realClock } from \"../clock.ts\";\nimport type { Logger } from \"../logger.ts\";\nimport type { ChildHandle, CommandPort, FilePort, HostPorts, HttpAnswer, NetPort, ProcessesPort, SpawnRequest, StopSignal } from \"./ports.ts\";\n\n/** These options go with the ports of Node. */\nexport interface NodeHostOptions {\n readonly logger?: Logger | undefined;\n /** This clock gives the time and the timers. The default is `realClock`. */\n readonly clock?: Clock | undefined;\n}\n\nconst codeOf = (error: unknown): string | undefined =>\n typeof error === \"object\" && error !== null && \"code\" in error ? String((error as { code: unknown }).code) : undefined;\n\nconst missing = (error: unknown): boolean => codeOf(error) === \"ENOENT\";\n\nconst nodeCommands: CommandPort = {\n run: (file, args, options = {}) =>\n new Promise((resolve) => {\n execFile(\n file,\n [...args],\n { ...(options.cwd === undefined ? {} : { cwd: options.cwd }), timeout: options.timeout ?? 0, windowsHide: true, encoding: \"utf8\", maxBuffer: 16 * 1024 * 1024 },\n (error, stdout, stderr) => {\n const out = `${stdout}${stderr}`;\n if (error === null) {\n resolve({ code: 0, out });\n return;\n }\n if (missing(error)) resolve({ code: 127, out: error.message });\n else if (error.killed === true && options.timeout !== undefined) resolve({ code: 124, out });\n else resolve({ code: typeof error.code === \"number\" ? error.code : 1, out: out === \"\" ? error.message : out });\n },\n );\n }),\n};\n\nlet serial = 0;\n\nconst nodeFiles: FilePort = {\n async read(path) {\n try {\n return await readFile(path, \"utf8\");\n } catch (error) {\n if (missing(error)) return null;\n throw error;\n }\n },\n async write(path, data) {\n await mkdir(dirname(path), { recursive: true });\n serial += 1;\n const temporary = `${path}.${process.pid}.${serial}.tmp`;\n await writeFile(temporary, data);\n try {\n await rename(temporary, path);\n } catch (error) {\n await rm(temporary, { force: true });\n throw error;\n }\n },\n async create(path, data) {\n await mkdir(dirname(path), { recursive: true });\n try {\n await writeFile(path, data, { flag: \"wx\" });\n return true;\n } catch (error) {\n if (codeOf(error) === \"EEXIST\") return false;\n throw error;\n }\n },\n async append(path, data) {\n await mkdir(dirname(path), { recursive: true });\n await appendFile(path, data);\n },\n async size(path) {\n try {\n return (await stat(path)).size;\n } catch (error) {\n if (missing(error)) return null;\n throw error;\n }\n },\n rename: (from, to) => rename(from, to),\n remove: (path) => rm(path, { force: true }),\n};\n\n/** This difference is the time from the start of the Windows file time (1601) to the start of the epoch (1970), in milliseconds. */\nconst FILETIME_EPOCH_MS = 11_644_473_600_000n;\n\n/**\n * This limit is the longest time of the query of a start time on Windows, in milliseconds. A cold start of PowerShell\n * on a loaded host can take more than 10 seconds (SYS-47). After the limit the start time is null, and the lock then\n * counts a live process ID as its owner. Thus a short limit can hold a stale lock, and the limit is wide.\n */\nconst WINDOWS_START_LIMIT_MS = 30_000;\n\n/** This function gives the start time of a Windows process from PowerShell, in milliseconds after the epoch, or null. */\nconst windowsStart = async (pid: number): Promise<number | null> => {\n const result = await nodeCommands.run(\n \"powershell.exe\",\n [\"-NoProfile\", \"-NonInteractive\", \"-Command\", `(Get-Process -Id ${pid} -ErrorAction Stop).StartTime.ToFileTimeUtc()`],\n { timeout: WINDOWS_START_LIMIT_MS },\n );\n const text = result.out.trim();\n if (result.code !== 0 || !/^\\d+$/.test(text)) return null;\n return Number(BigInt(text) / 10_000n - FILETIME_EPOCH_MS);\n};\n\n/** This count is the number of clock ticks in one second on Linux. It is 100 on each common kernel. */\nconst LINUX_TICKS = 100;\n\n/** This function gives the start time of a Linux process from `/proc`, in milliseconds after the epoch, or null. */\nconst linuxStart = async (pid: number): Promise<number | null> => {\n const record = await readFile(`/proc/${pid}/stat`, \"utf8\");\n // the name of the program is in parentheses and can have spaces: the fields start after the last \")\"\n const fields = record.slice(record.lastIndexOf(\")\") + 2).split(\" \");\n const ticks = Number(fields[19]);\n const boot = /^btime (\\d+)$/m.exec(await readFile(\"/proc/stat\", \"utf8\"));\n if (!Number.isFinite(ticks) || boot === null) return null;\n return Number(boot[1]) * 1000 + (ticks * 1000) / LINUX_TICKS;\n};\n\nconst sendSignal = (pid: number, signal: StopSignal | 0): boolean => {\n try {\n return process.kill(pid, signal);\n } catch {\n return false;\n }\n};\n\nconst nodeSpawn = (request: SpawnRequest): ChildHandle => {\n const outputs: Array<(stream: \"stdout\" | \"stderr\", chunk: string | Uint8Array) => void> = [];\n const exits: Array<(code: number | null, signal: string | null) => void> = [];\n let end: { code: number | null; signal: string | null } | null = null;\n const finish = (code: number | null, signal: string | null): void => {\n if (end !== null) return;\n end = { code, signal };\n for (const handler of exits) handler(code, signal);\n };\n const child = spawnChild(request.program, [...request.args], {\n ...(request.cwd === undefined ? {} : { cwd: request.cwd }),\n env: { ...request.env },\n stdio: request.ipc ? [\"ignore\", \"pipe\", \"pipe\", \"ipc\"] : [\"ignore\", \"pipe\", \"pipe\"],\n // on Linux the child leads its own process group, thus the tree stop reaches each process under it\n detached: process.platform !== \"win32\",\n windowsHide: true,\n });\n child.stdout?.on(\"data\", (chunk: Uint8Array) => {\n for (const handler of outputs) handler(\"stdout\", chunk);\n });\n child.stderr?.on(\"data\", (chunk: Uint8Array) => {\n for (const handler of outputs) handler(\"stderr\", chunk);\n });\n child.on(\"error\", () => {\n if (child.pid === undefined) finish(null, null);\n });\n child.on(\"exit\", (code, signal) => finish(code, signal));\n return {\n pid: child.pid ?? null,\n ipc: request.ipc,\n onOutput(handler) {\n outputs.push(handler);\n },\n onExit(handler) {\n exits.push(handler);\n if (end !== null) handler(end.code, end.signal);\n },\n send(message) {\n if (!child.connected) return false;\n try {\n return child.send(message as Serializable);\n } catch {\n return false;\n }\n },\n };\n};\n\nconst nodeProcesses: ProcessesPort = {\n alive(pid) {\n try {\n process.kill(pid, 0);\n return true;\n } catch (error) {\n // a process of a different user is alive, and the signal does not go to it\n return codeOf(error) === \"EPERM\";\n }\n },\n async startOf(pid) {\n try {\n if (process.platform === \"win32\") return await windowsStart(pid);\n if (process.platform === \"linux\") return await linuxStart(pid);\n return null;\n } catch {\n return null;\n }\n },\n signal: (pid, signal) => sendSignal(pid, signal),\n signalGroup: (pid, signal) => process.platform !== \"win32\" && sendSignal(-pid, signal),\n spawn: nodeSpawn,\n};\n\n/**\n * This function sends a GET request that does not follow a redirect. The timeout also stops the\n * read of the body. The status read and the text read use it, thus they have one timeout.\n */\nconst get = (url: string, timeout: number): Promise<Response> => fetch(url, { signal: AbortSignal.timeout(timeout), redirect: \"manual\" });\n\n/**\n * This function reads the body of an answer up to `limit` bytes, and gives the status and the text.\n * At the limit, it cancels the body, and `complete` is false. The decoder keeps the bytes of a\n * character that two parts of the body split. The unit tests give it answers with no network.\n */\nexport const answerText = async (response: Response, limit: number): Promise<HttpAnswer> => {\n const reader = response.body?.getReader();\n if (reader === undefined) return { status: response.status, body: \"\", complete: true };\n const decoder = new TextDecoder();\n let body = \"\";\n let size = 0;\n for (;;) {\n const read = await reader.read();\n if (read.done) return { status: response.status, body: body + decoder.decode(), complete: true };\n if (size + read.value.byteLength > limit) {\n body += decoder.decode(read.value.subarray(0, limit - size));\n await reader.cancel();\n return { status: response.status, body, complete: false };\n }\n body += decoder.decode(read.value, { stream: true });\n size += read.value.byteLength;\n }\n};\n\nconst nodeNet: NetPort = {\n async httpStatus(url, timeout) {\n try {\n const response = await get(url, timeout);\n await response.body?.cancel();\n return response.status;\n } catch {\n return null;\n }\n },\n async httpText(url, timeout, limit) {\n try {\n return await answerText(await get(url, timeout), limit);\n } catch {\n return null;\n }\n },\n tcpConnect: (host, port, timeout) =>\n new Promise((resolve) => {\n const socket = connect({ host, port });\n const done = (open: boolean): void => {\n socket.destroy();\n resolve(open);\n };\n socket.setTimeout(timeout, () => done(false));\n socket.once(\"connect\", () => done(true));\n socket.once(\"error\", () => done(false));\n }),\n};\n\n/**\n * This function gives the host ports of Node: `child_process`, `fs/promises`, `net`, `fetch` and `process`.\n * Only a program uses it. A test gives `fakeHost()` of `./testing`, thus it starts no process and installs no task.\n */\nexport const nodeHostPorts = (options: NodeHostOptions = {}): HostPorts => {\n const user = (): string => {\n const name = userInfo().username;\n const domain = process.env[\"USERDOMAIN\"];\n return process.platform === \"win32\" && domain !== undefined && domain !== \"\" ? `${domain}\\\\${name}` : name;\n };\n return {\n platform: process.platform,\n commands: nodeCommands,\n files: nodeFiles,\n processes: nodeProcesses,\n net: nodeNet,\n clock: options.clock ?? realClock,\n wall: () => Date.now(),\n self: { pid: process.pid, startedAt: Math.round(Date.now() - process.uptime() * 1000) },\n env: process.env,\n homeDir: homedir(),\n user,\n ...(options.logger === undefined ? {} : { logger: options.logger }),\n };\n};\n"],"mappings":";;;;;;;;;;;;;;AAiJA,MAAa,YAAY,UAAkB,GAAG,UAAqC;CACjF,MAAM,YAAY,aAAa,UAAU,OAAO;CAEhD,MAAM,eAAe,SAAsC,SAAS,OAAO,SAAS;CACpF,MAAM,QAAQ,MAAc,SAA0B;EACpD,IAAI,QAAQ;EACZ,IAAI,MAAM,KAAK;EACf,OAAO,QAAQ,QAAQ,OAAO,YAAY,KAAK,MAAM,GAAG,SAAS;EACjE,OAAO,MAAM,SAAS,YAAY,KAAK,MAAM,EAAE,GAAG,OAAO;EACzD,OAAO,KAAK,MAAM,OAAO,GAAG;CAC9B;CAEA,OADgB,MAAM,KAAK,MAAM,OAAO,KAAK,MAAM,OAAO,CAAC,CAC9C,CAAC,CAAC,QAAQ,MAAM,OAAO,OAAO,KAAK,SAAS,EAAE,CAAC,CAAC,KAAK,SAAS;AAC7E;;ACxGA,MAAMA,SAAO;AACb,MAAM,QAAQ;;AAEd,MAAM,cAAc,SAA0B;CAC5C,KAAK,IAAI,KAAK,GAAG,KAAK,KAAK,QAAQ,MAAM,GAAG;EAC1C,MAAM,OAAO,KAAK,WAAW,EAAE;EAC/B,IAAI,OAAO,MAAQ,SAAS,KAAM,OAAO;CAC3C;CACA,OAAO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