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/** The executable an installed unit, plist, or task starts: the launcher's runtime. */
67export function serviceUnitProgramOf(contents: string): string | undefined {
68 const systemd = /^ExecStart=("(?:\\.|[^"\\])*"|\S+)/m.exec(contents)?.[1];
69 if (systemd !== undefined) return unquoteSystemdValue(systemd);
70 const plist = /<key>ProgramArguments<\/key>\s*<array>\s*<string>([^<]*)<\/string>/.exec(
71 contents,
72 )?.[1];
73 if (plist !== undefined) return unescapeXmlText(plist);
74 const task = /<Arguments>--headless "([^"]*)"/.exec(contents)?.[1];
75 return task === undefined ? undefined : unquoteWindowsArgument(task);
76}
77
78export interface PendingServiceUpdate {
79 readonly id: string;
80 readonly fromVersion: string;
81 readonly targetVersion: string;
82 readonly dbPath: string;
83 readonly status: "pending";
84}
85
86export type ServiceUpdateRecord = PendingServiceUpdate | ServerSelfUpdateOutcome;
87
88export interface ServiceState {
89 readonly protocol: typeof SERVICE_LAUNCHER_PROTOCOL;
90 readonly activeVersion: string;
91 readonly update?: ServiceUpdateRecord;
92}
93
94export interface ServiceLauncherContext {
95 readonly protocol: SupportedLauncherProtocol;
96 readonly childVersion: string;
97 readonly update?: ServiceUpdateRecord;
98}
99
100export type ServiceLauncherChildMessage =
101 | {
102 readonly type: "request-update";
103 readonly targetVersion: string;
104 readonly dbPath: string;
105 }
106 | {
107 readonly type: "prepared";
108 readonly updateId: string;
109 };
110
111export type ServiceLauncherParentMessage =
112 | {
113 readonly type: "update-accepted";
114 readonly updateId: string;
115 }
116 | {
117 readonly type: "update-rejected";
118 readonly reason: string;
119 }
120 | {
121 readonly type: "committed";
122 readonly updateId: string;
123 }
124 | {
125 /** Shut down as on SIGTERM, which Windows cannot deliver. */
126 readonly type: "stop";
127 };
128
129const SEMVER_NUMBER = "(?:0|[1-9]\\d*)";
130const SEMVER_PRERELEASE = `(?:${SEMVER_NUMBER}|[0-9]*[A-Za-z-][0-9A-Za-z-]*)`;
131const EXACT_SERVICE_VERSION = new RegExp(
132 `^${SEMVER_NUMBER}\\.${SEMVER_NUMBER}\\.${SEMVER_NUMBER}(?:-${SEMVER_PRERELEASE}(?:\\.${SEMVER_PRERELEASE})*)?(?:\\+[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?$`,
133);
134
135export const isExactServiceVersion = (version: string): boolean =>
136 EXACT_SERVICE_VERSION.test(version);
137
138const isRecord = (value: unknown): value is Record<string, unknown> =>
139 typeof value === "object" && value !== null && !Array.isArray(value);
140
141function decodeServiceUpdate(value: unknown): ServiceUpdateRecord | undefined {
142 if (!isRecord(value)) return undefined;
143 const { id, fromVersion, targetVersion, status } = value;
144 if (
145 typeof id !== "string" ||
146 id.trim() === "" ||
147 typeof fromVersion !== "string" ||
148 !isExactServiceVersion(fromVersion) ||
149 typeof targetVersion !== "string" ||
150 !isExactServiceVersion(targetVersion)
151 ) {
152 return undefined;
153 }
154 if (status === "pending") {
155 return typeof value.dbPath === "string" && value.dbPath.trim() !== ""
156 ? { id, fromVersion, targetVersion, dbPath: value.dbPath, status }
157 : undefined;
158 }
159 if (
160 (status === "committed" || status === "rolled-back" || status === "failed") &&
161 (value.reason === undefined || (typeof value.reason === "string" && value.reason.trim() !== ""))
162 ) {
163 return {
164 id,
165 fromVersion,
166 targetVersion,
167 status,
168 ...(typeof value.reason === "string" ? { reason: value.reason } : {}),
169 };
170 }
171 return undefined;
172}
173
174export function compareExactServiceVersions(left: string, right: string): number {
175 const parse = (version: string) => {
176 const withoutBuild = version.split("+", 1)[0] ?? version;
177 const separator = withoutBuild.indexOf("-");
178 const core = separator === -1 ? withoutBuild : withoutBuild.slice(0, separator);
179 const prerelease = separator === -1 ? undefined : withoutBuild.slice(separator + 1);
180 const [major = "0", minor = "0", patch = "0"] = core.split(".");
181 return {
182 core: [BigInt(major), BigInt(minor), BigInt(patch)] as const,
183 prerelease: prerelease?.split(".") ?? [],
184 };
185 };
186 const a = parse(left);
187 const b = parse(right);
188 for (let index = 0; index < 3; index += 1) {
189 const x = a.core[index] ?? 0n;
190 const y = b.core[index] ?? 0n;
191 if (x !== y) return x < y ? -1 : 1;
192 }
193 if (a.prerelease.length === 0 || b.prerelease.length === 0) {
194 return a.prerelease.length === b.prerelease.length ? 0 : a.prerelease.length === 0 ? 1 : -1;
195 }
196 const count = Math.max(a.prerelease.length, b.prerelease.length);
197 for (let index = 0; index < count; index += 1) {
198 const x = a.prerelease[index];
199 const y = b.prerelease[index];
200 if (x === undefined || y === undefined) return x === undefined ? -1 : 1;
201 if (x === y) continue;
202 const xNumeric = /^\d+$/.test(x);
203 const yNumeric = /^\d+$/.test(y);
204 if (xNumeric && yNumeric) return BigInt(x) < BigInt(y) ? -1 : 1;
205 if (xNumeric !== yNumeric) return xNumeric ? -1 : 1;
206 return x < y ? -1 : 1;
207 }
208 return 0;
209}
210
211export function decodeServiceState(value: unknown): ServiceState | undefined {
212 if (!isRecord(value)) return undefined;
213 const update = value.update === undefined ? undefined : decodeServiceUpdate(value.update);
214 if (
215 // A protocol-3 installer can select a protocol-4 runtime.
216 !isSupportedLauncherProtocol(value.protocol) ||
217 typeof value.activeVersion !== "string" ||
218 !isExactServiceVersion(value.activeVersion) ||
219 (value.update !== undefined && update === undefined) ||
220 (update !== undefined &&
221 compareExactServiceVersions(update.targetVersion, update.fromVersion) <= 0) ||
222 (update?.status === "pending" && update.fromVersion !== value.activeVersion) ||
223 (update?.status === "committed" && update.targetVersion !== value.activeVersion) ||
224 ((update?.status === "rolled-back" || update?.status === "failed") &&
225 update.fromVersion !== value.activeVersion)
226 ) {
227 return undefined;
228 }
229 return {
230 protocol: SERVICE_LAUNCHER_PROTOCOL,
231 activeVersion: value.activeVersion,
232 ...(update === undefined ? {} : { update }),
233 };
234}
235
236export function parseServiceState(value: string): ServiceState | undefined {
237 try {
238 return decodeServiceState(JSON.parse(value) as unknown);
239 } catch {
240 return undefined;
241 }
242}
243
244export function parseLegacyServiceState(value: string) {
245 try {
246 const parsed: unknown = JSON.parse(value);
247 if (
248 !isRecord(parsed) ||
249 Object.keys(parsed).length !== 2 ||
250 parsed.protocol !== 2 ||
251 typeof parsed.activeVersion !== "string" ||
252 !isExactServiceVersion(parsed.activeVersion)
253 ) {
254 return undefined;
255 }
256 return { protocol: 2, activeVersion: parsed.activeVersion } as const;
257 } catch {
258 return undefined;
259 }
260}
261
262export function serviceStateHasPendingUpdate(value: string): boolean {
263 try {
264 const parsed: unknown = JSON.parse(value);
265 return isRecord(parsed) && isRecord(parsed.update) && parsed.update.status === "pending";
266 } catch {
267 return false;
268 }
269}
270
271export function serviceStateActiveVersion(value: string): string | undefined {
272 try {
273 const parsed: unknown = JSON.parse(value);
274 return isRecord(parsed) &&
275 typeof parsed.activeVersion === "string" &&
276 isExactServiceVersion(parsed.activeVersion)
277 ? parsed.activeVersion
278 : undefined;
279 } catch {
280 return undefined;
281 }
282}
283
284export function decodeServiceLauncherContext(value: string): ServiceLauncherContext | undefined {
285 let parsed: unknown;
286 try {
287 parsed = JSON.parse(value) as unknown;
288 } catch {
289 return undefined;
290 }
291 if (
292 !isRecord(parsed) ||
293 !isSupportedLauncherProtocol(parsed.protocol) ||
294 typeof parsed.childVersion !== "string" ||
295 !isExactServiceVersion(parsed.childVersion)
296 ) {
297 return undefined;
298 }
299 const update = parsed.update === undefined ? undefined : decodeServiceUpdate(parsed.update);
300 if (parsed.update !== undefined && update === undefined) return undefined;
301 const selectedVersion =
302 update?.status === "pending" || update?.status === "committed"
303 ? update.targetVersion
304 : update === undefined
305 ? parsed.childVersion
306 : update.fromVersion;
307 if (parsed.childVersion !== selectedVersion) {
308 return undefined;
309 }
310 return {
311 protocol: parsed.protocol,
312 childVersion: parsed.childVersion,
313 ...(update === undefined ? {} : { update }),
314 };
315}
316
317export function decodeServiceLauncherChildMessage(
318 value: unknown,
319): ServiceLauncherChildMessage | undefined {
320 if (!isRecord(value)) return undefined;
321 if (
322 value.type === "request-update" &&
323 typeof value.targetVersion === "string" &&
324 typeof value.dbPath === "string"
325 ) {
326 return { type: value.type, targetVersion: value.targetVersion, dbPath: value.dbPath };
327 }
328 return value.type === "prepared" && typeof value.updateId === "string"
329 ? { type: value.type, updateId: value.updateId }
330 : undefined;
331}
332
333export function decodeServiceLauncherParentMessage(
334 value: unknown,
335): ServiceLauncherParentMessage | undefined {
336 if (!isRecord(value)) return undefined;
337 if (value.type === "update-rejected" && typeof value.reason === "string") {
338 return { type: value.type, reason: value.reason };
339 }
340 if (value.type === "update-accepted" && typeof value.updateId === "string") {
341 return { type: value.type, updateId: value.updateId };
342 }
343 if (value.type === "stop") return { type: value.type };
344 return value.type === "committed" && typeof value.updateId === "string"
345 ? { type: value.type, updateId: value.updateId }
346 : undefined;
347}