Open History to see the last commit
1import type { ServerSelfUpdateOutcome } from "@t3tools/contracts";
2
3// Protocol 4 requires coordinated selection writes and unit reconciliation. An
4// installed protocol-3 launcher needs one local update or service install with a restart:
5// remote updates replace its child, so cannot add these launcher guarantees.
6export const SERVICE_LAUNCHER_PROTOCOL = 4 as const;
7export const SERVICE_LAUNCHER_CONTEXT_ENV = "T3_SERVICE_LAUNCHER_CONTEXT";
8export const SERVICE_ENV_FILE = "service.env";
9export const SERVICE_STATE_FILE = "service-state.json";
10/** Set by the unit or launch agent to its own file name, so the launcher can
11 find the definition that started it. */
12export const SERVICE_UNIT_ENV = "T3_BOOT_SERVICE_UNIT";
13/** Written before explicit stop to distinguish shutdown from update handoff. */
14export const SERVICE_STOP_MARKER_FILE = ".service-stopping";
15/** Marks a repointed unit whose service still runs the old version; launcher startup clears it. */
16export const SERVICE_RESTART_PENDING_FILE = ".restart-pending";
17
18const unquoteSystemdValue = (raw: string) =>
19 (raw.startsWith('"') && raw.endsWith('"')
20 ? raw.slice(1, -1).replaceAll('\\"', '"').replaceAll("\\\\", "\\")
21 : raw
22 ).replaceAll("%%", "%");
23
24const unescapeXmlText = (value: string) =>
25 value.replaceAll("<", "<").replaceAll(">", ">").replaceAll("&", "&");
26
27export function serviceUnitBaseDirOf(contents: string): string | undefined {
28 const systemd = /^Environment=T3CODE_HOME=(.*)$/m.exec(contents)?.[1];
29 if (systemd !== undefined) return unquoteSystemdValue(systemd.trim());
30 const plist = /<key>T3CODE_HOME<\/key>\s*<string>([^<]*)<\/string>/.exec(contents)?.[1];
31 return plist === undefined ? undefined : unescapeXmlText(plist);
32}
33
34/** The executable an installed unit or plist starts: the launcher's runtime. */
35export function serviceUnitProgramOf(contents: string): string | undefined {
36 const systemd = /^ExecStart=("(?:\\.|[^"\\])*"|\S+)/m.exec(contents)?.[1];
37 if (systemd !== undefined) return unquoteSystemdValue(systemd);
38 const plist = /<key>ProgramArguments<\/key>\s*<array>\s*<string>([^<]*)<\/string>/.exec(
39 contents,
40 )?.[1];
41 return plist === undefined ? undefined : unescapeXmlText(plist);
42}
43
44export interface PendingServiceUpdate {
45 readonly id: string;
46 readonly fromVersion: string;
47 readonly targetVersion: string;
48 readonly dbPath: string;
49 readonly status: "pending";
50}
51
52export type ServiceUpdateRecord = PendingServiceUpdate | ServerSelfUpdateOutcome;
53
54export interface ServiceState {
55 readonly protocol: typeof SERVICE_LAUNCHER_PROTOCOL;
56 readonly activeVersion: string;
57 readonly update?: ServiceUpdateRecord;
58}
59
60export interface ServiceLauncherContext {
61 readonly protocol: typeof SERVICE_LAUNCHER_PROTOCOL;
62 readonly childVersion: string;
63 readonly update?: ServiceUpdateRecord;
64}
65
66export type ServiceLauncherChildMessage =
67 | {
68 readonly type: "request-update";
69 readonly targetVersion: string;
70 readonly dbPath: string;
71 }
72 | {
73 readonly type: "prepared";
74 readonly updateId: string;
75 };
76
77export type ServiceLauncherParentMessage =
78 | {
79 readonly type: "update-accepted";
80 readonly updateId: string;
81 }
82 | {
83 readonly type: "update-rejected";
84 readonly reason: string;
85 }
86 | {
87 readonly type: "committed";
88 readonly updateId: string;
89 };
90
91const SEMVER_NUMBER = "(?:0|[1-9]\\d*)";
92const SEMVER_PRERELEASE = `(?:${SEMVER_NUMBER}|[0-9]*[A-Za-z-][0-9A-Za-z-]*)`;
93const EXACT_SERVICE_VERSION = new RegExp(
94 `^${SEMVER_NUMBER}\\.${SEMVER_NUMBER}\\.${SEMVER_NUMBER}(?:-${SEMVER_PRERELEASE}(?:\\.${SEMVER_PRERELEASE})*)?(?:\\+[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?$`,
95);
96
97export const isExactServiceVersion = (version: string): boolean =>
98 EXACT_SERVICE_VERSION.test(version);
99
100const isRecord = (value: unknown): value is Record<string, unknown> =>
101 typeof value === "object" && value !== null && !Array.isArray(value);
102
103function decodeServiceUpdate(value: unknown): ServiceUpdateRecord | undefined {
104 if (!isRecord(value)) return undefined;
105 const { id, fromVersion, targetVersion, status } = value;
106 if (
107 typeof id !== "string" ||
108 id.trim() === "" ||
109 typeof fromVersion !== "string" ||
110 !isExactServiceVersion(fromVersion) ||
111 typeof targetVersion !== "string" ||
112 !isExactServiceVersion(targetVersion)
113 ) {
114 return undefined;
115 }
116 if (status === "pending") {
117 return typeof value.dbPath === "string" && value.dbPath.trim() !== ""
118 ? { id, fromVersion, targetVersion, dbPath: value.dbPath, status }
119 : undefined;
120 }
121 if (
122 (status === "committed" || status === "rolled-back" || status === "failed") &&
123 (value.reason === undefined || (typeof value.reason === "string" && value.reason.trim() !== ""))
124 ) {
125 return {
126 id,
127 fromVersion,
128 targetVersion,
129 status,
130 ...(typeof value.reason === "string" ? { reason: value.reason } : {}),
131 };
132 }
133 return undefined;
134}
135
136export function compareExactServiceVersions(left: string, right: string): number {
137 const parse = (version: string) => {
138 const withoutBuild = version.split("+", 1)[0] ?? version;
139 const separator = withoutBuild.indexOf("-");
140 const core = separator === -1 ? withoutBuild : withoutBuild.slice(0, separator);
141 const prerelease = separator === -1 ? undefined : withoutBuild.slice(separator + 1);
142 const [major = "0", minor = "0", patch = "0"] = core.split(".");
143 return {
144 core: [BigInt(major), BigInt(minor), BigInt(patch)] as const,
145 prerelease: prerelease?.split(".") ?? [],
146 };
147 };
148 const a = parse(left);
149 const b = parse(right);
150 for (let index = 0; index < 3; index += 1) {
151 const x = a.core[index] ?? 0n;
152 const y = b.core[index] ?? 0n;
153 if (x !== y) return x < y ? -1 : 1;
154 }
155 if (a.prerelease.length === 0 || b.prerelease.length === 0) {
156 return a.prerelease.length === b.prerelease.length ? 0 : a.prerelease.length === 0 ? 1 : -1;
157 }
158 const count = Math.max(a.prerelease.length, b.prerelease.length);
159 for (let index = 0; index < count; index += 1) {
160 const x = a.prerelease[index];
161 const y = b.prerelease[index];
162 if (x === undefined || y === undefined) return x === undefined ? -1 : 1;
163 if (x === y) continue;
164 const xNumeric = /^\d+$/.test(x);
165 const yNumeric = /^\d+$/.test(y);
166 if (xNumeric && yNumeric) return BigInt(x) < BigInt(y) ? -1 : 1;
167 if (xNumeric !== yNumeric) return xNumeric ? -1 : 1;
168 return x < y ? -1 : 1;
169 }
170 return 0;
171}
172
173export function decodeServiceState(value: unknown): ServiceState | undefined {
174 if (!isRecord(value)) return undefined;
175 const update = value.update === undefined ? undefined : decodeServiceUpdate(value.update);
176 if (
177 // Protocol 3 has the same durable format; its installer can select a protocol-4 runtime.
178 (value.protocol !== 3 && value.protocol !== SERVICE_LAUNCHER_PROTOCOL) ||
179 typeof value.activeVersion !== "string" ||
180 !isExactServiceVersion(value.activeVersion) ||
181 (value.update !== undefined && update === undefined) ||
182 (update !== undefined &&
183 compareExactServiceVersions(update.targetVersion, update.fromVersion) <= 0) ||
184 (update?.status === "pending" && update.fromVersion !== value.activeVersion) ||
185 (update?.status === "committed" && update.targetVersion !== value.activeVersion) ||
186 ((update?.status === "rolled-back" || update?.status === "failed") &&
187 update.fromVersion !== value.activeVersion)
188 ) {
189 return undefined;
190 }
191 return {
192 protocol: SERVICE_LAUNCHER_PROTOCOL,
193 activeVersion: value.activeVersion,
194 ...(update === undefined ? {} : { update }),
195 };
196}
197
198export function parseServiceState(value: string): ServiceState | undefined {
199 try {
200 return decodeServiceState(JSON.parse(value) as unknown);
201 } catch {
202 return undefined;
203 }
204}
205
206export function serviceStateHasPendingUpdate(value: string): boolean {
207 try {
208 const parsed: unknown = JSON.parse(value);
209 return isRecord(parsed) && isRecord(parsed.update) && parsed.update.status === "pending";
210 } catch {
211 return false;
212 }
213}
214
215export function serviceStateActiveVersion(value: string): string | undefined {
216 try {
217 const parsed: unknown = JSON.parse(value);
218 return isRecord(parsed) &&
219 typeof parsed.activeVersion === "string" &&
220 isExactServiceVersion(parsed.activeVersion)
221 ? parsed.activeVersion
222 : undefined;
223 } catch {
224 return undefined;
225 }
226}
227
228export function decodeServiceLauncherContext(value: string): ServiceLauncherContext | undefined {
229 let parsed: unknown;
230 try {
231 parsed = JSON.parse(value) as unknown;
232 } catch {
233 return undefined;
234 }
235 if (
236 !isRecord(parsed) ||
237 parsed.protocol !== SERVICE_LAUNCHER_PROTOCOL ||
238 typeof parsed.childVersion !== "string" ||
239 !isExactServiceVersion(parsed.childVersion)
240 ) {
241 return undefined;
242 }
243 const update = parsed.update === undefined ? undefined : decodeServiceUpdate(parsed.update);
244 if (parsed.update !== undefined && update === undefined) return undefined;
245 const selectedVersion =
246 update?.status === "pending" || update?.status === "committed"
247 ? update.targetVersion
248 : update === undefined
249 ? parsed.childVersion
250 : update.fromVersion;
251 if (parsed.childVersion !== selectedVersion) {
252 return undefined;
253 }
254 return {
255 protocol: SERVICE_LAUNCHER_PROTOCOL,
256 childVersion: parsed.childVersion,
257 ...(update === undefined ? {} : { update }),
258 };
259}
260
261export function decodeServiceLauncherChildMessage(
262 value: unknown,
263): ServiceLauncherChildMessage | undefined {
264 if (!isRecord(value)) return undefined;
265 if (
266 value.type === "request-update" &&
267 typeof value.targetVersion === "string" &&
268 typeof value.dbPath === "string"
269 ) {
270 return { type: value.type, targetVersion: value.targetVersion, dbPath: value.dbPath };
271 }
272 return value.type === "prepared" && typeof value.updateId === "string"
273 ? { type: value.type, updateId: value.updateId }
274 : undefined;
275}
276
277export function decodeServiceLauncherParentMessage(
278 value: unknown,
279): ServiceLauncherParentMessage | undefined {
280 if (!isRecord(value)) return undefined;
281 if (value.type === "update-rejected" && typeof value.reason === "string") {
282 return { type: value.type, reason: value.reason };
283 }
284 if (value.type === "update-accepted" && typeof value.updateId === "string") {
285 return { type: value.type, updateId: value.updateId };
286 }
287 return value.type === "committed" && typeof value.updateId === "string"
288 ? { type: value.type, updateId: value.updateId }
289 : undefined;
290}