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_ENV_FILE = "service.env";
8export const SERVICE_STATE_FILE = "service-state.json";
9/** Written by the launcher just before an explicit stop kills its child, so
10 the child can tell "the service is going away" from "the launcher is about
11 to start my replacement" while a pending update is recorded. */
12export const SERVICE_STOP_MARKER_FILE = ".service-stopping";
13/** Written by `t3 update` when the unit was repointed at a new version but the
14 running service was deliberately left on the old one. The launcher removes
15 it when it starts (whoever restarted the service), so while it exists the
16 service is known to be behind its unit and status reports it that way. */
17export const SERVICE_RESTART_PENDING_FILE = ".restart-pending";
18
19export interface PendingServiceUpdate {
20 readonly id: string;
21 readonly fromVersion: string;
22 readonly targetVersion: string;
23 readonly dbPath: string;
24 readonly status: "pending";
25}
26
27export type ServiceUpdateRecord = PendingServiceUpdate | ServerSelfUpdateOutcome;
28
29export interface ServiceState {
30 readonly protocol: typeof SERVICE_LAUNCHER_PROTOCOL;
31 readonly activeVersion: string;
32 readonly update?: ServiceUpdateRecord;
33}
34
35export interface ServiceLauncherContext {
36 readonly protocol: typeof SERVICE_LAUNCHER_PROTOCOL;
37 readonly childVersion: string;
38 readonly update?: ServiceUpdateRecord;
39}
40
41export type ServiceLauncherChildMessage =
42 | {
43 readonly type: "request-update";
44 readonly targetVersion: string;
45 readonly dbPath: string;
46 }
47 | {
48 readonly type: "prepared";
49 readonly updateId: string;
50 };
51
52export type ServiceLauncherParentMessage =
53 | {
54 readonly type: "update-accepted";
55 readonly updateId: string;
56 }
57 | {
58 readonly type: "update-rejected";
59 readonly reason: string;
60 }
61 | {
62 readonly type: "committed";
63 readonly updateId: string;
64 };
65
66const SEMVER_NUMBER = "(?:0|[1-9]\\d*)";
67const SEMVER_PRERELEASE = `(?:${SEMVER_NUMBER}|[0-9]*[A-Za-z-][0-9A-Za-z-]*)`;
68const EXACT_SERVICE_VERSION = new RegExp(
69 `^${SEMVER_NUMBER}\\.${SEMVER_NUMBER}\\.${SEMVER_NUMBER}(?:-${SEMVER_PRERELEASE}(?:\\.${SEMVER_PRERELEASE})*)?(?:\\+[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?$`,
70);
71
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;
109}
110
111export function compareExactServiceVersions(left: string, right: string): number {
112 const parse = (version: string) => {
113 const withoutBuild = version.split("+", 1)[0] ?? version;
114 const separator = withoutBuild.indexOf("-");
115 const core = separator === -1 ? withoutBuild : withoutBuild.slice(0, separator);
116 const prerelease = separator === -1 ? undefined : withoutBuild.slice(separator + 1);
117 const [major = "0", minor = "0", patch = "0"] = core.split(".");
118 return {
119 core: [BigInt(major), BigInt(minor), BigInt(patch)] as const,
120 prerelease: prerelease?.split(".") ?? [],
121 };
122 };
123 const a = parse(left);
124 const b = parse(right);
125 for (let index = 0; index < 3; index += 1) {
126 const x = a.core[index] ?? 0n;
127 const y = b.core[index] ?? 0n;
128 if (x !== y) return x < y ? -1 : 1;
129 }
130 if (a.prerelease.length === 0 || b.prerelease.length === 0) {
131 return a.prerelease.length === b.prerelease.length ? 0 : a.prerelease.length === 0 ? 1 : -1;
132 }
133 const count = Math.max(a.prerelease.length, b.prerelease.length);
134 for (let index = 0; index < count; index += 1) {
135 const x = a.prerelease[index];
136 const y = b.prerelease[index];
137 if (x === undefined || y === undefined) return x === undefined ? -1 : 1;
138 if (x === y) continue;
139 const xNumeric = /^\d+$/.test(x);
140 const yNumeric = /^\d+$/.test(y);
141 if (xNumeric && yNumeric) return BigInt(x) < BigInt(y) ? -1 : 1;
142 if (xNumeric !== yNumeric) return xNumeric ? -1 : 1;
143 return x < y ? -1 : 1;
144 }
145 return 0;
146}
147
148export function decodeServiceState(value: unknown): ServiceState | undefined {
149 if (!isRecord(value)) return undefined;
150 const update = value.update === undefined ? undefined : decodeServiceUpdate(value.update);
151 if (
152 value.protocol !== SERVICE_LAUNCHER_PROTOCOL ||
153 typeof value.activeVersion !== "string" ||
154 !isExactServiceVersion(value.activeVersion) ||
155 (value.update !== undefined && update === undefined) ||
156 (update !== undefined &&
157 compareExactServiceVersions(update.targetVersion, update.fromVersion) <= 0) ||
158 (update?.status === "pending" && update.fromVersion !== value.activeVersion) ||
159 (update?.status === "committed" && update.targetVersion !== value.activeVersion) ||
160 ((update?.status === "rolled-back" || update?.status === "failed") &&
161 update.fromVersion !== value.activeVersion)
162 ) {
163 return undefined;
164 }
165 return {
166 protocol: SERVICE_LAUNCHER_PROTOCOL,
167 activeVersion: value.activeVersion,
168 ...(update === undefined ? {} : { update }),
169 };
170}
171
172export function parseServiceState(value: string): ServiceState | undefined {
173 try {
174 return decodeServiceState(JSON.parse(value) as unknown);
175 } catch {
176 return undefined;
177 }
178}
179
180export function serviceStateHasPendingUpdate(value: string): boolean {
181 try {
182 const parsed: unknown = JSON.parse(value);
183 return isRecord(parsed) && isRecord(parsed.update) && parsed.update.status === "pending";
184 } catch {
185 return false;
186 }
187}
188
189export function serviceStateActiveVersion(value: string): string | undefined {
190 try {
191 const parsed: unknown = JSON.parse(value);
192 return isRecord(parsed) &&
193 typeof parsed.activeVersion === "string" &&
194 isExactServiceVersion(parsed.activeVersion)
195 ? parsed.activeVersion
196 : undefined;
197 } catch {
198 return undefined;
199 }
200}
201
202export function decodeServiceLauncherContext(value: string): ServiceLauncherContext | undefined {
203 let parsed: unknown;
204 try {
205 parsed = JSON.parse(value) as unknown;
206 } catch {
207 return undefined;
208 }
209 if (
210 !isRecord(parsed) ||
211 parsed.protocol !== SERVICE_LAUNCHER_PROTOCOL ||
212 typeof parsed.childVersion !== "string" ||
213 !isExactServiceVersion(parsed.childVersion)
214 ) {
215 return undefined;
216 }
217 const update = parsed.update === undefined ? undefined : decodeServiceUpdate(parsed.update);
218 if (parsed.update !== undefined && update === undefined) return undefined;
219 const selectedVersion =
220 update?.status === "pending" || update?.status === "committed"
221 ? update.targetVersion
222 : update === undefined
223 ? parsed.childVersion
224 : update.fromVersion;
225 if (parsed.childVersion !== selectedVersion) {
226 return undefined;
227 }
228 return {
229 protocol: SERVICE_LAUNCHER_PROTOCOL,
230 childVersion: parsed.childVersion,
231 ...(update === undefined ? {} : { update }),
232 };
233}
234
235export function decodeServiceLauncherChildMessage(
236 value: unknown,
237): ServiceLauncherChildMessage | undefined {
238 if (!isRecord(value)) return undefined;
239 if (
240 value.type === "request-update" &&
241 typeof value.targetVersion === "string" &&
242 typeof value.dbPath === "string"
243 ) {
244 return { type: value.type, targetVersion: value.targetVersion, dbPath: value.dbPath };
245 }
246 return value.type === "prepared" && typeof value.updateId === "string"
247 ? { type: value.type, updateId: value.updateId }
248 : undefined;
249}
250
251export function decodeServiceLauncherParentMessage(
252 value: unknown,
253): ServiceLauncherParentMessage | undefined {
254 if (!isRecord(value)) return undefined;
255 if (value.type === "update-rejected" && typeof value.reason === "string") {
256 return { type: value.type, reason: value.reason };
257 }
258 if (value.type === "update-accepted" && typeof value.updateId === "string") {
259 return { type: value.type, updateId: value.updateId };
260 }
261 return value.type === "committed" && typeof value.updateId === "string"
262 ? { type: value.type, updateId: value.updateId }
263 : undefined;
264}