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

serviceProtocol.ts

258 lines8.8 KB

1import type { ServerSelfUpdateOutcome } from "@t3tools/contracts";
2​
3// Bump for incompatible runtime layout changes; launchers survive self-updates. Protocol 3 requires standalone executables.
4export const SERVICE_LAUNCHER_PROTOCOL = 3 as const;
5export const SERVICE_LAUNCHER_CONTEXT_ENV = "T3_SERVICE_LAUNCHER_CONTEXT";
6export const SERVICE_ENV_FILE = "service.env";
7export const SERVICE_STATE_FILE = "service-state.json";
8/** Written before explicit stop to distinguish shutdown from update handoff. */
9export const SERVICE_STOP_MARKER_FILE = ".service-stopping";
10/** Marks a repointed unit whose service still runs the old version; launcher startup clears it. */
11export const SERVICE_RESTART_PENDING_FILE = ".restart-pending";
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​
29export interface ServiceLauncherContext {
30 readonly protocol: typeof SERVICE_LAUNCHER_PROTOCOL;
31 readonly childVersion: string;
32 readonly update?: ServiceUpdateRecord;
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​
66export const isExactServiceVersion = (version: string): boolean =>
67 EXACT_SERVICE_VERSION.test(version);
68​
69const isRecord = (value: unknown): value is Record<string, unknown> =>
70 typeof value === "object" && value !== null && !Array.isArray(value);
71​
72function decodeServiceUpdate(value: unknown): ServiceUpdateRecord | undefined {
73 if (!isRecord(value)) return undefined;
74 const { id, fromVersion, targetVersion, status } = value;
75 if (
76 typeof id !== "string" ||
77 id.trim() === "" ||
78 typeof fromVersion !== "string" ||
79 !isExactServiceVersion(fromVersion) ||
80 typeof targetVersion !== "string" ||
81 !isExactServiceVersion(targetVersion)
82 ) {
83 return undefined;
84 }
85 if (status === "pending") {
86 return typeof value.dbPath === "string" && value.dbPath.trim() !== ""
87 ? { id, fromVersion, targetVersion, dbPath: value.dbPath, status }
88 : undefined;
89 }
90 if (
91 (status === "committed" || status === "rolled-back" || status === "failed") &&
92 (value.reason === undefined || (typeof value.reason === "string" && value.reason.trim() !== ""))
93 ) {
94 return {
95 id,
96 fromVersion,
97 targetVersion,
98 status,
99 ...(typeof value.reason === "string" ? { reason: value.reason } : {}),
100 };
101 }
102 return undefined;
104​
105export function compareExactServiceVersions(left: string, right: string): number {
106 const parse = (version: string) => {
107 const withoutBuild = version.split("+", 1)[0] ?? version;
108 const separator = withoutBuild.indexOf("-");
109 const core = separator === -1 ? withoutBuild : withoutBuild.slice(0, separator);
110 const prerelease = separator === -1 ? undefined : withoutBuild.slice(separator + 1);
111 const [major = "0", minor = "0", patch = "0"] = core.split(".");
112 return {
113 core: [BigInt(major), BigInt(minor), BigInt(patch)] as const,
114 prerelease: prerelease?.split(".") ?? [],
115 };
116 };
117 const a = parse(left);
118 const b = parse(right);
119 for (let index = 0; index < 3; index += 1) {
120 const x = a.core[index] ?? 0n;
121 const y = b.core[index] ?? 0n;
122 if (x !== y) return x < y ? -1 : 1;
123 }
124 if (a.prerelease.length === 0 || b.prerelease.length === 0) {
125 return a.prerelease.length === b.prerelease.length ? 0 : a.prerelease.length === 0 ? 1 : -1;
126 }
127 const count = Math.max(a.prerelease.length, b.prerelease.length);
128 for (let index = 0; index < count; index += 1) {
129 const x = a.prerelease[index];
130 const y = b.prerelease[index];
131 if (x === undefined || y === undefined) return x === undefined ? -1 : 1;
132 if (x === y) continue;
133 const xNumeric = /^\d+$/.test(x);
134 const yNumeric = /^\d+$/.test(y);
135 if (xNumeric && yNumeric) return BigInt(x) < BigInt(y) ? -1 : 1;
136 if (xNumeric !== yNumeric) return xNumeric ? -1 : 1;
137 return x < y ? -1 : 1;
138 }
139 return 0;
141​
142export function decodeServiceState(value: unknown): ServiceState | undefined {
143 if (!isRecord(value)) return undefined;
144 const update = value.update === undefined ? undefined : decodeServiceUpdate(value.update);
145 if (
146 value.protocol !== SERVICE_LAUNCHER_PROTOCOL ||
147 typeof value.activeVersion !== "string" ||
148 !isExactServiceVersion(value.activeVersion) ||
149 (value.update !== undefined && update === undefined) ||
150 (update !== undefined &&
151 compareExactServiceVersions(update.targetVersion, update.fromVersion) <= 0) ||
152 (update?.status === "pending" && update.fromVersion !== value.activeVersion) ||
153 (update?.status === "committed" && update.targetVersion !== value.activeVersion) ||
154 ((update?.status === "rolled-back" || update?.status === "failed") &&
155 update.fromVersion !== value.activeVersion)
156 ) {
157 return undefined;
158 }
159 return {
160 protocol: SERVICE_LAUNCHER_PROTOCOL,
161 activeVersion: value.activeVersion,
162 ...(update === undefined ? {} : { update }),
163 };
165​
166export function parseServiceState(value: string): ServiceState | undefined {
167 try {
168 return decodeServiceState(JSON.parse(value) as unknown);
169 } catch {
170 return undefined;
171 }
173​
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 serviceStateActiveVersion(value: string): string | undefined {
184 try {
185 const parsed: unknown = JSON.parse(value);
186 return isRecord(parsed) &&
187 typeof parsed.activeVersion === "string" &&
188 isExactServiceVersion(parsed.activeVersion)
189 ? parsed.activeVersion
190 : undefined;
191 } catch {
192 return undefined;
193 }
195​
196export function decodeServiceLauncherContext(value: string): ServiceLauncherContext | undefined {
197 let parsed: unknown;
198 try {
199 parsed = JSON.parse(value) as unknown;
200 } catch {
201 return undefined;
202 }
203 if (
204 !isRecord(parsed) ||
205 parsed.protocol !== SERVICE_LAUNCHER_PROTOCOL ||
206 typeof parsed.childVersion !== "string" ||
207 !isExactServiceVersion(parsed.childVersion)
208 ) {
209 return undefined;
210 }
211 const update = parsed.update === undefined ? undefined : decodeServiceUpdate(parsed.update);
212 if (parsed.update !== undefined && update === undefined) return undefined;
213 const selectedVersion =
214 update?.status === "pending" || update?.status === "committed"
215 ? update.targetVersion
216 : update === undefined
217 ? parsed.childVersion
218 : update.fromVersion;
219 if (parsed.childVersion !== selectedVersion) {
220 return undefined;
221 }
222 return {
223 protocol: SERVICE_LAUNCHER_PROTOCOL,
224 childVersion: parsed.childVersion,
225 ...(update === undefined ? {} : { update }),
226 };
228​
229export function decodeServiceLauncherChildMessage(
230 value: unknown,
231): ServiceLauncherChildMessage | undefined {
232 if (!isRecord(value)) return undefined;
233 if (
234 value.type === "request-update" &&
235 typeof value.targetVersion === "string" &&
236 typeof value.dbPath === "string"
237 ) {
238 return { type: value.type, targetVersion: value.targetVersion, dbPath: value.dbPath };
239 }
240 return value.type === "prepared" && typeof value.updateId === "string"
241 ? { type: value.type, updateId: value.updateId }
242 : undefined;
244​
245export function decodeServiceLauncherParentMessage(
246 value: unknown,
247): ServiceLauncherParentMessage | undefined {
248 if (!isRecord(value)) return undefined;
249 if (value.type === "update-rejected" && typeof value.reason === "string") {
250 return { type: value.type, reason: value.reason };
251 }
252 if (value.type === "update-accepted" && typeof value.updateId === "string") {
253 return { type: value.type, updateId: value.updateId };
254 }
255 return value.type === "committed" && typeof value.updateId === "string"
256 ? { type: value.type, updateId: value.updateId }
257 : undefined;