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