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