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

serviceProtocol.ts

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