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

serviceProtocol.ts

270 lines9.7 KB

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