Open History to see the last commit
1import type { ServerSelfUpdateOutcome } from "@t3tools/contracts";
2
3/** Protocol 2 snapshots SQLite before trials so migrations can be rolled back safely. */
4export const SERVICE_LAUNCHER_PROTOCOL = 2 as const;
5export const SERVICE_LAUNCHER_CONTEXT_ENV = "T3_SERVICE_LAUNCHER_CONTEXT";
6export const SERVICE_LAUNCHER_FILE = "service-launcher.mjs";
7export const SERVICE_STATE_FILE = "service-state.json";
8/** Written by the launcher just before an explicit stop kills its child, so
9 the child can tell "the service is going away" from "the launcher is about
10 to start my replacement" while a pending update is recorded. */
11export const SERVICE_STOP_MARKER_FILE = ".service-stopping";
12
13export interface PendingServiceUpdate {
14 readonly id: string;
15 readonly fromVersion: string;
16 readonly targetVersion: string;
17 readonly dbPath: string;
18 readonly status: "pending";
19}
20
21export type ServiceUpdateRecord = PendingServiceUpdate | ServerSelfUpdateOutcome;
22
23export interface ServiceState {
24 readonly protocol: typeof SERVICE_LAUNCHER_PROTOCOL;
25 readonly activeVersion: string;
26 readonly update?: ServiceUpdateRecord;
27}
28
29/** Context is copied from launcher-owned state when a child is spawned. */
30export interface ServiceLauncherContext {
31 readonly protocol: typeof SERVICE_LAUNCHER_PROTOCOL;
32 readonly childVersion: string;
33 readonly update?: ServiceUpdateRecord;
34}
35
36export type ServiceLauncherChildMessage =
37 | {
38 readonly type: "request-update";
39 readonly targetVersion: string;
40 readonly dbPath: string;
41 }
42 | {
43 readonly type: "prepared";
44 readonly updateId: string;
45 };
46
47export type ServiceLauncherParentMessage =
48 | {
49 readonly type: "update-accepted";
50 readonly updateId: string;
51 }
52 | {
53 readonly type: "update-rejected";
54 readonly reason: string;
55 }
56 | {
57 readonly type: "committed";
58 readonly updateId: string;
59 };
60
61const SEMVER_NUMBER = "(?:0|[1-9]\\d*)";
62const SEMVER_PRERELEASE = `(?:${SEMVER_NUMBER}|[0-9]*[A-Za-z-][0-9A-Za-z-]*)`;
63const EXACT_SERVICE_VERSION = new RegExp(
64 `^${SEMVER_NUMBER}\\.${SEMVER_NUMBER}\\.${SEMVER_NUMBER}(?:-${SEMVER_PRERELEASE}(?:\\.${SEMVER_PRERELEASE})*)?(?:\\+[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?$`,
65);
66
67/** Accepts exact SemVer only: never dist-tags or ranges passed to npm or filesystem paths. */
68export const isExactServiceVersion = (version: string): boolean =>
69 EXACT_SERVICE_VERSION.test(version);
70
71const isRecord = (value: unknown): value is Record<string, unknown> =>
72 typeof value === "object" && value !== null && !Array.isArray(value);
73
74export function decodeServiceUpdate(value: unknown): ServiceUpdateRecord | undefined {
75 if (!isRecord(value)) return undefined;
76 const { id, fromVersion, targetVersion, status } = value;
77 if (
78 typeof id !== "string" ||
79 id.trim() === "" ||
80 typeof fromVersion !== "string" ||
81 !isExactServiceVersion(fromVersion) ||
82 typeof targetVersion !== "string" ||
83 !isExactServiceVersion(targetVersion)
84 ) {
85 return undefined;
86 }
87 if (status === "pending") {
88 return typeof value.dbPath === "string" && value.dbPath.trim() !== ""
89 ? { id, fromVersion, targetVersion, dbPath: value.dbPath, status }
90 : undefined;
91 }
92 if (
93 (status === "committed" || status === "rolled-back" || status === "failed") &&
94 (value.reason === undefined || (typeof value.reason === "string" && value.reason.trim() !== ""))
95 ) {
96 return {
97 id,
98 fromVersion,
99 targetVersion,
100 status,
101 ...(typeof value.reason === "string" ? { reason: value.reason } : {}),
102 };
103 }
104 return undefined;
105}
106
107/** SemVer precedence for exact versions. Build metadata is ignored. */
108export function compareExactServiceVersions(left: string, right: string): number {
109 const parse = (version: string) => {
110 const withoutBuild = version.split("+", 1)[0] ?? version;
111 const separator = withoutBuild.indexOf("-");
112 const core = separator === -1 ? withoutBuild : withoutBuild.slice(0, separator);
113 const prerelease = separator === -1 ? undefined : withoutBuild.slice(separator + 1);
114 const [major = "0", minor = "0", patch = "0"] = core.split(".");
115 return {
116 core: [BigInt(major), BigInt(minor), BigInt(patch)] as const,
117 prerelease: prerelease?.split(".") ?? [],
118 };
119 };
120 const a = parse(left);
121 const b = parse(right);
122 for (let index = 0; index < 3; index += 1) {
123 const x = a.core[index] ?? 0n;
124 const y = b.core[index] ?? 0n;
125 if (x !== y) return x < y ? -1 : 1;
126 }
127 if (a.prerelease.length === 0 || b.prerelease.length === 0) {
128 return a.prerelease.length === b.prerelease.length ? 0 : a.prerelease.length === 0 ? 1 : -1;
129 }
130 const count = Math.max(a.prerelease.length, b.prerelease.length);
131 for (let index = 0; index < count; index += 1) {
132 const x = a.prerelease[index];
133 const y = b.prerelease[index];
134 if (x === undefined || y === undefined) return x === undefined ? -1 : 1;
135 if (x === y) continue;
136 const xNumeric = /^\d+$/.test(x);
137 const yNumeric = /^\d+$/.test(y);
138 if (xNumeric && yNumeric) return BigInt(x) < BigInt(y) ? -1 : 1;
139 if (xNumeric !== yNumeric) return xNumeric ? -1 : 1;
140 return x < y ? -1 : 1;
141 }
142 return 0;
143}
144
145export function decodeServiceState(value: unknown): ServiceState | undefined {
146 if (!isRecord(value)) return undefined;
147 const update = value.update === undefined ? undefined : decodeServiceUpdate(value.update);
148 if (
149 value.protocol !== SERVICE_LAUNCHER_PROTOCOL ||
150 typeof value.activeVersion !== "string" ||
151 !isExactServiceVersion(value.activeVersion) ||
152 (value.update !== undefined && update === undefined) ||
153 (update !== undefined &&
154 compareExactServiceVersions(update.targetVersion, update.fromVersion) <= 0) ||
155 (update?.status === "pending" && update.fromVersion !== value.activeVersion) ||
156 (update?.status === "committed" && update.targetVersion !== value.activeVersion) ||
157 ((update?.status === "rolled-back" || update?.status === "failed") &&
158 update.fromVersion !== value.activeVersion)
159 ) {
160 return undefined;
161 }
162 return {
163 protocol: SERVICE_LAUNCHER_PROTOCOL,
164 activeVersion: value.activeVersion,
165 ...(update === undefined ? {} : { update }),
166 };
167}
168
169export function parseServiceState(value: string): ServiceState | undefined {
170 try {
171 return decodeServiceState(JSON.parse(value) as unknown);
172 } catch {
173 return undefined;
174 }
175}
176
177/** Detects an in-flight update across launcher protocol versions before replacing its state. */
178export function serviceStateHasPendingUpdate(value: string): boolean {
179 try {
180 const parsed: unknown = JSON.parse(value);
181 return isRecord(parsed) && isRecord(parsed.update) && parsed.update.status === "pending";
182 } catch {
183 return false;
184 }
185}
186
187export function decodeServiceLauncherContext(value: string): ServiceLauncherContext | undefined {
188 let parsed: unknown;
189 try {
190 parsed = JSON.parse(value) as unknown;
191 } catch {
192 return undefined;
193 }
194 if (
195 !isRecord(parsed) ||
196 parsed.protocol !== SERVICE_LAUNCHER_PROTOCOL ||
197 typeof parsed.childVersion !== "string" ||
198 !isExactServiceVersion(parsed.childVersion)
199 ) {
200 return undefined;
201 }
202 const update = parsed.update === undefined ? undefined : decodeServiceUpdate(parsed.update);
203 if (parsed.update !== undefined && update === undefined) return undefined;
204 const selectedVersion =
205 update?.status === "pending" || update?.status === "committed"
206 ? update.targetVersion
207 : update === undefined
208 ? parsed.childVersion
209 : update.fromVersion;
210 if (parsed.childVersion !== selectedVersion) {
211 return undefined;
212 }
213 return {
214 protocol: SERVICE_LAUNCHER_PROTOCOL,
215 childVersion: parsed.childVersion,
216 ...(update === undefined ? {} : { update }),
217 };
218}
219
220export function decodeServiceLauncherChildMessage(
221 value: unknown,
222): ServiceLauncherChildMessage | undefined {
223 if (!isRecord(value)) return undefined;
224 if (
225 value.type === "request-update" &&
226 typeof value.targetVersion === "string" &&
227 typeof value.dbPath === "string"
228 ) {
229 return { type: value.type, targetVersion: value.targetVersion, dbPath: value.dbPath };
230 }
231 return value.type === "prepared" && typeof value.updateId === "string"
232 ? { type: value.type, updateId: value.updateId }
233 : undefined;
234}
235
236export function decodeServiceLauncherParentMessage(
237 value: unknown,
238): ServiceLauncherParentMessage | undefined {
239 if (!isRecord(value)) return undefined;
240 if (value.type === "update-rejected" && typeof value.reason === "string") {
241 return { type: value.type, reason: value.reason };
242 }
243 if (value.type === "update-accepted" && typeof value.updateId === "string") {
244 return { type: value.type, updateId: value.updateId };
245 }
246 return value.type === "committed" && typeof value.updateId === "string"
247 ? { type: value.type, updateId: value.updateId }
248 : undefined;
249}