Open History to see the last commit
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
18export interface PendingServiceUpdate {
19 readonly id: string;
20 readonly fromVersion: string;
21 readonly targetVersion: string;
22 readonly dbPath: string;
23 readonly status: "pending";
24}
25
26export type ServiceUpdateRecord = PendingServiceUpdate | ServerSelfUpdateOutcome;
27
28export interface ServiceState {
29 readonly protocol: typeof SERVICE_LAUNCHER_PROTOCOL;
30 readonly activeVersion: string;
31 readonly update?: ServiceUpdateRecord;
32}
33
34export interface ServiceLauncherContext {
35 readonly protocol: typeof SERVICE_LAUNCHER_PROTOCOL;
36 readonly childVersion: string;
37 readonly update?: ServiceUpdateRecord;
38}
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
71export const isExactServiceVersion = (version: string): boolean =>
72 EXACT_SERVICE_VERSION.test(version);
73
74const isRecord = (value: unknown): value is Record<string, unknown> =>
75 typeof value === "object" && value !== null && !Array.isArray(value);
76
77function decodeServiceUpdate(value: unknown): ServiceUpdateRecord | undefined {
78 if (!isRecord(value)) return undefined;
79 const { id, fromVersion, targetVersion, status } = value;
80 if (
81 typeof id !== "string" ||
82 id.trim() === "" ||
83 typeof fromVersion !== "string" ||
84 !isExactServiceVersion(fromVersion) ||
85 typeof targetVersion !== "string" ||
86 !isExactServiceVersion(targetVersion)
87 ) {
88 return undefined;
89 }
90 if (status === "pending") {
91 return typeof value.dbPath === "string" && value.dbPath.trim() !== ""
92 ? { id, fromVersion, targetVersion, dbPath: value.dbPath, status }
93 : undefined;
94 }
95 if (
96 (status === "committed" || status === "rolled-back" || status === "failed") &&
97 (value.reason === undefined || (typeof value.reason === "string" && value.reason.trim() !== ""))
98 ) {
99 return {
100 id,
101 fromVersion,
102 targetVersion,
103 status,
104 ...(typeof value.reason === "string" ? { reason: value.reason } : {}),
105 };
106 }
107 return undefined;
108}
109
110export function compareExactServiceVersions(left: string, right: string): number {
111 const parse = (version: string) => {
112 const withoutBuild = version.split("+", 1)[0] ?? version;
113 const separator = withoutBuild.indexOf("-");
114 const core = separator === -1 ? withoutBuild : withoutBuild.slice(0, separator);
115 const prerelease = separator === -1 ? undefined : withoutBuild.slice(separator + 1);
116 const [major = "0", minor = "0", patch = "0"] = core.split(".");
117 return {
118 core: [BigInt(major), BigInt(minor), BigInt(patch)] as const,
119 prerelease: prerelease?.split(".") ?? [],
120 };
121 };
122 const a = parse(left);
123 const b = parse(right);
124 for (let index = 0; index < 3; index += 1) {
125 const x = a.core[index] ?? 0n;
126 const y = b.core[index] ?? 0n;
127 if (x !== y) return x < y ? -1 : 1;
128 }
129 if (a.prerelease.length === 0 || b.prerelease.length === 0) {
130 return a.prerelease.length === b.prerelease.length ? 0 : a.prerelease.length === 0 ? 1 : -1;
131 }
132 const count = Math.max(a.prerelease.length, b.prerelease.length);
133 for (let index = 0; index < count; index += 1) {
134 const x = a.prerelease[index];
135 const y = b.prerelease[index];
136 if (x === undefined || y === undefined) return x === undefined ? -1 : 1;
137 if (x === y) continue;
138 const xNumeric = /^\d+$/.test(x);
139 const yNumeric = /^\d+$/.test(y);
140 if (xNumeric && yNumeric) return BigInt(x) < BigInt(y) ? -1 : 1;
141 if (xNumeric !== yNumeric) return xNumeric ? -1 : 1;
142 return x < y ? -1 : 1;
143 }
144 return 0;
145}
146
147export function decodeServiceState(value: unknown): ServiceState | undefined {
148 if (!isRecord(value)) return undefined;
149 const update = value.update === undefined ? undefined : decodeServiceUpdate(value.update);
150 if (
151 value.protocol !== SERVICE_LAUNCHER_PROTOCOL ||
152 typeof value.activeVersion !== "string" ||
153 !isExactServiceVersion(value.activeVersion) ||
154 (value.update !== undefined && update === undefined) ||
155 (update !== undefined &&
156 compareExactServiceVersions(update.targetVersion, update.fromVersion) <= 0) ||
157 (update?.status === "pending" && update.fromVersion !== value.activeVersion) ||
158 (update?.status === "committed" && update.targetVersion !== value.activeVersion) ||
159 ((update?.status === "rolled-back" || update?.status === "failed") &&
160 update.fromVersion !== value.activeVersion)
161 ) {
162 return undefined;
163 }
164 return {
165 protocol: SERVICE_LAUNCHER_PROTOCOL,
166 activeVersion: value.activeVersion,
167 ...(update === undefined ? {} : { update }),
168 };
169}
170
171export function parseServiceState(value: string): ServiceState | undefined {
172 try {
173 return decodeServiceState(JSON.parse(value) as unknown);
174 } catch {
175 return undefined;
176 }
177}
178
179export function serviceStateHasPendingUpdate(value: string): boolean {
180 try {
181 const parsed: unknown = JSON.parse(value);
182 return isRecord(parsed) && isRecord(parsed.update) && parsed.update.status === "pending";
183 } catch {
184 return false;
185 }
186}
187
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 }
199}
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 };
232}
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;
248}
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;
263}