Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

serviceProtocol.ts

372 lines13.9 KB

1import type { ServerSelfUpdateOutcome } from "@t3tools/contracts";
2​
3// Protocol 4 launchers coordinate selection writes and reconcile the unit. A remote update
4// replaces only the child, so an installed protocol-3 launcher stays until a local update or
5// service install restarts the service.
6export const SERVICE_LAUNCHER_PROTOCOL = 4 as const;
7/** Launchers this runtime runs under. Protocol 3 has the same IPC and durable format, and
8 refusing it stops every remote update until someone opens a shell on the host. */
9export type SupportedLauncherProtocol = 3 | typeof SERVICE_LAUNCHER_PROTOCOL;
10export const isSupportedLauncherProtocol = (
11 protocol: unknown,
12): protocol is SupportedLauncherProtocol =>
13 protocol === 3 || protocol === SERVICE_LAUNCHER_PROTOCOL;
14export const SERVICE_LAUNCHER_CONTEXT_ENV = "T3_SERVICE_LAUNCHER_CONTEXT";
15export const SERVICE_ENV_FILE = "service.env";
16export const SERVICE_STATE_FILE = "service-state.json";
17/** Set by the unit or launch agent to its own file name, so the launcher can
18 find the definition that started it. */
19export const SERVICE_UNIT_ENV = "T3_BOOT_SERVICE_UNIT";
20/** Written before explicit stop to distinguish shutdown from update handoff. */
21export const SERVICE_STOP_MARKER_FILE = ".service-stopping";
22/** Marks a repointed unit whose service still runs the old version; launcher startup clears it. */
23export const SERVICE_RESTART_PENDING_FILE = ".restart-pending";
24/** Held by a Windows launcher while it runs: Task Scheduler tracks only the task's console host. */
25export const SERVICE_LAUNCHER_LOCK_FILE = "service-launcher.lock";
26/** Held by a launcher while it has, or is about to start, a server: an SSH launch waits for that
27 server instead of starting its own. Released while the launcher idles. */
28export const SERVICE_SERVING_LOCK_FILE = "service-serving.lock";
29​
30const unquoteSystemdValue = (raw: string) =>
31 (raw.startsWith('"') && raw.endsWith('"')
32 ? raw.slice(1, -1).replaceAll('\\"', '"').replaceAll("\\\\", "\\")
33 : raw
34 ).replaceAll("%%", "%");
35​
36const unescapeXmlText = (value: string) =>
37 value.replaceAll("&lt;", "<").replaceAll("&gt;", ">").replaceAll("&amp;", "&");
38​
39const unquoteWindowsArgument = (raw: string) =>
40 unescapeXmlText(raw).replace(/(\\+)$/, (slashes) => slashes.slice(slashes.length / 2));
41​
42/** Whether Task Scheduler's copy of a task is disabled as a whole, not one of its triggers. */
43export const serviceTaskIsDisabled = (taskXml: string): boolean =>
44 /<Settings>[\s\S]*?<\/Settings>/.exec(taskXml)?.[0].includes("<Enabled>false</Enabled>") === true;
45​
46/** A task as Task Scheduler should hold it while its service must stay stopped. */
47export const disabledServiceTask = (taskXml: string): string =>
48 serviceTaskIsDisabled(taskXml)
49 ? taskXml
50 : taskXml.replace(" </Settings>", " <Enabled>false</Enabled>\n </Settings>");
51​
52export function serviceUnitEnvironmentValueOf(
53 contents: string,
54 name: "T3CODE_HOME" | "T3CODE_INSTALL_BIN_DIR",
55): string | undefined {
56 const systemd = new RegExp(`^Environment=${name}=(.*)$`, "m").exec(contents)?.[1];
57 if (systemd !== undefined) return unquoteSystemdValue(systemd.trim());
58 const plist = new RegExp(`<key>${name}</key>\\s*<string>([^<]*)</string>`).exec(contents)?.[1];
59 return plist === undefined ? undefined : unescapeXmlText(plist);
61​
62export function serviceUnitBaseDirOf(contents: string): string | undefined {
63 const unix = serviceUnitEnvironmentValueOf(contents, "T3CODE_HOME");
64 if (unix !== undefined) return unix;
65 const task = /<Arguments>[^<]* "--base-dir" "([^"]*)"/.exec(contents)?.[1];
66 return task === undefined ? undefined : unquoteWindowsArgument(task);
68​
69/**
70 * The user unit directory a systemd manager reads, from its UnitPath property. The persistent
71 * control directory identifies the manager's config root despite UnitPath overrides.
72 */
73export function systemdUnitDirectoryOf(unitPath: ReadonlyArray<string>): string | undefined {
74 const controlDirectory = unitPath.find(
75 (directory) =>
76 directory.startsWith("/") &&
77 directory.endsWith("/systemd/user.control") &&
78 unitPath.includes(directory.slice(0, -".control".length)),
79 );
80 return controlDirectory?.slice(0, -".control".length);
82​
83/** The file systemd or launchd appends the service's output to. */
84export function serviceUnitLogPathOf(contents: string): string | undefined {
85 const systemd = /^StandardOutput=append:(.*)$/m.exec(contents)?.[1];
86 if (systemd !== undefined) return unquoteSystemdValue(systemd.trim());
87 const plist = /<key>StandardOutPath<\/key>\s*<string>([^<]*)<\/string>/.exec(contents)?.[1];
88 return plist === undefined ? undefined : unescapeXmlText(plist);
90​
91/** The executable an installed unit, plist, or task starts: the launcher's runtime. */
92export function serviceUnitProgramOf(contents: string): string | undefined {
93 const systemd = /^ExecStart=("(?:\\.|[^"\\])*"|\S+)/m.exec(contents)?.[1];
94 if (systemd !== undefined) return unquoteSystemdValue(systemd);
95 const plist = /<key>ProgramArguments<\/key>\s*<array>\s*<string>([^<]*)<\/string>/.exec(
96 contents,
97 )?.[1];
98 if (plist !== undefined) return unescapeXmlText(plist);
99 const task = /<Arguments>--headless "([^"]*)"/.exec(contents)?.[1];
100 return task === undefined ? undefined : unquoteWindowsArgument(task);
102​
103export interface PendingServiceUpdate {
104 readonly id: string;
105 readonly fromVersion: string;
106 readonly targetVersion: string;
107 readonly dbPath: string;
108 readonly status: "pending";
110​
111export type ServiceUpdateRecord = PendingServiceUpdate | ServerSelfUpdateOutcome;
112​
113export interface ServiceState {
114 readonly protocol: typeof SERVICE_LAUNCHER_PROTOCOL;
115 readonly activeVersion: string;
116 readonly update?: ServiceUpdateRecord;
118​
119export interface ServiceLauncherContext {
120 readonly protocol: SupportedLauncherProtocol;
121 readonly childVersion: string;
122 readonly update?: ServiceUpdateRecord;
124​
125export type ServiceLauncherChildMessage =
126 | {
127 readonly type: "request-update";
128 readonly targetVersion: string;
129 readonly dbPath: string;
130 }
131 | {
132 readonly type: "prepared";
133 readonly updateId: string;
134 };
135​
136export type ServiceLauncherParentMessage =
137 | {
138 readonly type: "update-accepted";
139 readonly updateId: string;
140 }
141 | {
142 readonly type: "update-rejected";
143 readonly reason: string;
144 }
145 | {
146 readonly type: "committed";
147 readonly updateId: string;
148 }
149 | {
150 /** Shut down as on SIGTERM, which Windows cannot deliver. */
151 readonly type: "stop";
152 };
153​
154const SEMVER_NUMBER = "(?:0|[1-9]\\d*)";
155const SEMVER_PRERELEASE = `(?:${SEMVER_NUMBER}|[0-9]*[A-Za-z-][0-9A-Za-z-]*)`;
156const EXACT_SERVICE_VERSION = new RegExp(
157 `^${SEMVER_NUMBER}\\.${SEMVER_NUMBER}\\.${SEMVER_NUMBER}(?:-${SEMVER_PRERELEASE}(?:\\.${SEMVER_PRERELEASE})*)?(?:\\+[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?$`,
158);
159​
160export const isExactServiceVersion = (version: string): boolean =>
161 EXACT_SERVICE_VERSION.test(version);
162​
163const isRecord = (value: unknown): value is Record<string, unknown> =>
164 typeof value === "object" && value !== null && !Array.isArray(value);
165​
166function decodeServiceUpdate(value: unknown): ServiceUpdateRecord | undefined {
167 if (!isRecord(value)) return undefined;
168 const { id, fromVersion, targetVersion, status } = value;
169 if (
170 typeof id !== "string" ||
171 id.trim() === "" ||
172 typeof fromVersion !== "string" ||
173 !isExactServiceVersion(fromVersion) ||
174 typeof targetVersion !== "string" ||
175 !isExactServiceVersion(targetVersion)
176 ) {
177 return undefined;
178 }
179 if (status === "pending") {
180 return typeof value.dbPath === "string" && value.dbPath.trim() !== ""
181 ? { id, fromVersion, targetVersion, dbPath: value.dbPath, status }
182 : undefined;
183 }
184 if (
185 (status === "committed" || status === "rolled-back" || status === "failed") &&
186 (value.reason === undefined || (typeof value.reason === "string" && value.reason.trim() !== ""))
187 ) {
188 return {
189 id,
190 fromVersion,
191 targetVersion,
192 status,
193 ...(typeof value.reason === "string" ? { reason: value.reason } : {}),
194 };
195 }
196 return undefined;
198​
199export function compareExactServiceVersions(left: string, right: string): number {
200 const parse = (version: string) => {
201 const withoutBuild = version.split("+", 1)[0] ?? version;
202 const separator = withoutBuild.indexOf("-");
203 const core = separator === -1 ? withoutBuild : withoutBuild.slice(0, separator);
204 const prerelease = separator === -1 ? undefined : withoutBuild.slice(separator + 1);
205 const [major = "0", minor = "0", patch = "0"] = core.split(".");
206 return {
207 core: [BigInt(major), BigInt(minor), BigInt(patch)] as const,
208 prerelease: prerelease?.split(".") ?? [],
209 };
210 };
211 const a = parse(left);
212 const b = parse(right);
213 for (let index = 0; index < 3; index += 1) {
214 const x = a.core[index] ?? 0n;
215 const y = b.core[index] ?? 0n;
216 if (x !== y) return x < y ? -1 : 1;
217 }
218 if (a.prerelease.length === 0 || b.prerelease.length === 0) {
219 return a.prerelease.length === b.prerelease.length ? 0 : a.prerelease.length === 0 ? 1 : -1;
220 }
221 const count = Math.max(a.prerelease.length, b.prerelease.length);
222 for (let index = 0; index < count; index += 1) {
223 const x = a.prerelease[index];
224 const y = b.prerelease[index];
225 if (x === undefined || y === undefined) return x === undefined ? -1 : 1;
226 if (x === y) continue;
227 const xNumeric = /^\d+$/.test(x);
228 const yNumeric = /^\d+$/.test(y);
229 if (xNumeric && yNumeric) return BigInt(x) < BigInt(y) ? -1 : 1;
230 if (xNumeric !== yNumeric) return xNumeric ? -1 : 1;
231 return x < y ? -1 : 1;
232 }
233 return 0;
235​
236export function decodeServiceState(value: unknown): ServiceState | undefined {
237 if (!isRecord(value)) return undefined;
238 const update = value.update === undefined ? undefined : decodeServiceUpdate(value.update);
239 if (
240 // A protocol-3 installer can select a protocol-4 runtime.
241 !isSupportedLauncherProtocol(value.protocol) ||
242 typeof value.activeVersion !== "string" ||
243 !isExactServiceVersion(value.activeVersion) ||
244 (value.update !== undefined && update === undefined) ||
245 (update !== undefined &&
246 compareExactServiceVersions(update.targetVersion, update.fromVersion) <= 0) ||
247 (update?.status === "pending" && update.fromVersion !== value.activeVersion) ||
248 (update?.status === "committed" && update.targetVersion !== value.activeVersion) ||
249 ((update?.status === "rolled-back" || update?.status === "failed") &&
250 update.fromVersion !== value.activeVersion)
251 ) {
252 return undefined;
253 }
254 return {
255 protocol: SERVICE_LAUNCHER_PROTOCOL,
256 activeVersion: value.activeVersion,
257 ...(update === undefined ? {} : { update }),
258 };
260​
261export function parseServiceState(value: string): ServiceState | undefined {
262 try {
263 return decodeServiceState(JSON.parse(value) as unknown);
264 } catch {
265 return undefined;
266 }
268​
269export function parseLegacyServiceState(value: string) {
270 try {
271 const parsed: unknown = JSON.parse(value);
272 if (
273 !isRecord(parsed) ||
274 Object.keys(parsed).length !== 2 ||
275 parsed.protocol !== 2 ||
276 typeof parsed.activeVersion !== "string" ||
277 !isExactServiceVersion(parsed.activeVersion)
278 ) {
279 return undefined;
280 }
281 return { protocol: 2, activeVersion: parsed.activeVersion } as const;
282 } catch {
283 return undefined;
284 }
286​
287export function serviceStateHasPendingUpdate(value: string): boolean {
288 try {
289 const parsed: unknown = JSON.parse(value);
290 return isRecord(parsed) && isRecord(parsed.update) && parsed.update.status === "pending";
291 } catch {
292 return false;
293 }
295​
296export function serviceStateActiveVersion(value: string): string | undefined {
297 try {
298 const parsed: unknown = JSON.parse(value);
299 return isRecord(parsed) &&
300 typeof parsed.activeVersion === "string" &&
301 isExactServiceVersion(parsed.activeVersion)
302 ? parsed.activeVersion
303 : undefined;
304 } catch {
305 return undefined;
306 }
308​
309export function decodeServiceLauncherContext(value: string): ServiceLauncherContext | undefined {
310 let parsed: unknown;
311 try {
312 parsed = JSON.parse(value) as unknown;
313 } catch {
314 return undefined;
315 }
316 if (
317 !isRecord(parsed) ||
318 !isSupportedLauncherProtocol(parsed.protocol) ||
319 typeof parsed.childVersion !== "string" ||
320 !isExactServiceVersion(parsed.childVersion)
321 ) {
322 return undefined;
323 }
324 const update = parsed.update === undefined ? undefined : decodeServiceUpdate(parsed.update);
325 if (parsed.update !== undefined && update === undefined) return undefined;
326 const selectedVersion =
327 update?.status === "pending" || update?.status === "committed"
328 ? update.targetVersion
329 : update === undefined
330 ? parsed.childVersion
331 : update.fromVersion;
332 if (parsed.childVersion !== selectedVersion) {
333 return undefined;
334 }
335 return {
336 protocol: parsed.protocol,
337 childVersion: parsed.childVersion,
338 ...(update === undefined ? {} : { update }),
339 };
341​
342export function decodeServiceLauncherChildMessage(
343 value: unknown,
344): ServiceLauncherChildMessage | undefined {
345 if (!isRecord(value)) return undefined;
346 if (
347 value.type === "request-update" &&
348 typeof value.targetVersion === "string" &&
349 typeof value.dbPath === "string"
350 ) {
351 return { type: value.type, targetVersion: value.targetVersion, dbPath: value.dbPath };
352 }
353 return value.type === "prepared" && typeof value.updateId === "string"
354 ? { type: value.type, updateId: value.updateId }
355 : undefined;
357​
358export function decodeServiceLauncherParentMessage(
359 value: unknown,
360): ServiceLauncherParentMessage | undefined {
361 if (!isRecord(value)) return undefined;
362 if (value.type === "update-rejected" && typeof value.reason === "string") {
363 return { type: value.type, reason: value.reason };
364 }
365 if (value.type === "update-accepted" && typeof value.updateId === "string") {
366 return { type: value.type, updateId: value.updateId };
367 }
368 if (value.type === "stop") return { type: value.type };
369 return value.type === "committed" && typeof value.updateId === "string"
370 ? { type: value.type, updateId: value.updateId }
371 : undefined;