Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

serviceProtocol.ts

263 lines9.1 KB

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";
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;
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;
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​
74function 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;
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;
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 };
168​
169export function parseServiceState(value: string): ServiceState | undefined {
170 try {
171 return decodeServiceState(JSON.parse(value) as unknown);
172 } catch {
173 return undefined;
174 }
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 }
186​
187/** Reads the active version across launcher protocol revisions for downgrade protection. */
188export function serviceStateActiveVersion(value: string): string | undefined {
189 try {
190 const parsed: unknown = JSON.parse(value);
191 return isRecord(parsed) &&
192 typeof parsed.activeVersion === "string" &&
193 isExactServiceVersion(parsed.activeVersion)
194 ? parsed.activeVersion
195 : undefined;
196 } catch {
197 return undefined;
198 }
200​
201export function decodeServiceLauncherContext(value: string): ServiceLauncherContext | undefined {
202 let parsed: unknown;
203 try {
204 parsed = JSON.parse(value) as unknown;
205 } catch {
206 return undefined;
207 }
208 if (
209 !isRecord(parsed) ||
210 parsed.protocol !== SERVICE_LAUNCHER_PROTOCOL ||
211 typeof parsed.childVersion !== "string" ||
212 !isExactServiceVersion(parsed.childVersion)
213 ) {
214 return undefined;
215 }
216 const update = parsed.update === undefined ? undefined : decodeServiceUpdate(parsed.update);
217 if (parsed.update !== undefined && update === undefined) return undefined;
218 const selectedVersion =
219 update?.status === "pending" || update?.status === "committed"
220 ? update.targetVersion
221 : update === undefined
222 ? parsed.childVersion
223 : update.fromVersion;
224 if (parsed.childVersion !== selectedVersion) {
225 return undefined;
226 }
227 return {
228 protocol: SERVICE_LAUNCHER_PROTOCOL,
229 childVersion: parsed.childVersion,
230 ...(update === undefined ? {} : { update }),
231 };
233​
234export function decodeServiceLauncherChildMessage(
235 value: unknown,
236): ServiceLauncherChildMessage | undefined {
237 if (!isRecord(value)) return undefined;
238 if (
239 value.type === "request-update" &&
240 typeof value.targetVersion === "string" &&
241 typeof value.dbPath === "string"
242 ) {
243 return { type: value.type, targetVersion: value.targetVersion, dbPath: value.dbPath };
244 }
245 return value.type === "prepared" && typeof value.updateId === "string"
246 ? { type: value.type, updateId: value.updateId }
247 : undefined;
249​
250export function decodeServiceLauncherParentMessage(
251 value: unknown,
252): ServiceLauncherParentMessage | undefined {
253 if (!isRecord(value)) return undefined;
254 if (value.type === "update-rejected" && typeof value.reason === "string") {
255 return { type: value.type, reason: value.reason };
256 }
257 if (value.type === "update-accepted" && typeof value.updateId === "string") {
258 return { type: value.type, updateId: value.updateId };
259 }
260 return value.type === "committed" && typeof value.updateId === "string"
261 ? { type: value.type, updateId: value.updateId }
262 : undefined;