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