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

serviceProtocol.ts

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