Open History to see the last commit
1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { assert, it } from "@effect/vitest";
3import { SERVER_EXIT_CODE_STATE_DIR_OWNED } from "@t3tools/contracts";
4import { vi } from "vite-plus/test";
5import * as Effect from "effect/Effect";
6import * as FileSystem from "effect/FileSystem";
7import * as Path from "effect/Path";
8
9import { Launcher, readServiceState, writeServiceState } from "./serviceLauncher.ts";
10import {
11 compareExactServiceVersions,
12 decodeServiceState,
13 isExactServiceVersion,
14 SERVICE_LAUNCHER_PROTOCOL,
15 SERVICE_RESTART_PENDING_FILE,
16 SERVICE_STOP_MARKER_FILE,
17} from "./cloud/serviceProtocol.ts";
18
19it("accepts only exact semantic versions", () => {
20 for (const version of ["0.0.0", "1.2.3", "1.2.3-alpha.1", "1.2.3-0", "1.2.3+001"]) {
21 assert.isTrue(isExactServiceVersion(version), version);
22 }
23 for (const version of ["latest", "01.2.3", "1.2.3-01", "1.2.3-alpha..1", "1.2.3+."]) {
24 assert.isFalse(isExactServiceVersion(version), version);
25 }
26});
27
28it("orders exact semantic versions without treating build metadata as precedence", () => {
29 assert.equal(compareExactServiceVersions("1.2.3", "1.2.3"), 0);
30 assert.equal(compareExactServiceVersions("1.2.4", "1.2.3"), 1);
31 assert.equal(compareExactServiceVersions("2.0.0-alpha.1", "2.0.0-alpha.2"), -1);
32 assert.equal(compareExactServiceVersions("2.0.0-alpha.2", "2.0.0-alpha.beta"), -1);
33 assert.equal(compareExactServiceVersions("2.0.0-alpha-beta", "2.0.0-alpha-alpha"), 1);
34 assert.equal(compareExactServiceVersions("2.0.0", "2.0.0-rc.1"), 1);
35 assert.equal(compareExactServiceVersions("2.0.0+one", "2.0.0+two"), 0);
36});
37
38it("rejects contradictory service state", () => {
39 assert.isUndefined(
40 decodeServiceState({
41 protocol: SERVICE_LAUNCHER_PROTOCOL,
42 activeVersion: "0.0.31",
43 update: {
44 id: "update-1",
45 fromVersion: "0.0.30",
46 targetVersion: "0.0.32",
47 dbPath: "/tmp/state.sqlite",
48 status: "pending",
49 },
50 }),
51 );
52
53 assert.isUndefined(
54 decodeServiceState({
55 protocol: SERVICE_LAUNCHER_PROTOCOL,
56 activeVersion: "1.0.0",
57 update: {
58 id: "update-3",
59 fromVersion: "1.0.0",
60 targetVersion: "1.1.0",
61 status: "pending",
62 },
63 }),
64 );
65
66 assert.isUndefined(
67 decodeServiceState({
68 protocol: SERVICE_LAUNCHER_PROTOCOL,
69 activeVersion: "1.0.0",
70 update: {
71 id: "update-2",
72 fromVersion: "1.0.0",
73 targetVersion: "0.9.0",
74 dbPath: "/tmp/state.sqlite",
75 status: "pending",
76 },
77 }),
78 );
79});
80
81// A pinned runtime is an executable at <versionDir>/t3. The tests stand one up
82// as a Node shebang script so the launcher spawns it the way it spawns the
83// real single-executable, IPC channel included.
84const writeFakeRuntime = (
85 fs: FileSystem.FileSystem,
86 path: Path.Path,
87 versionDir: string,
88 childSource: string,
89) =>
90 Effect.gen(function* () {
91 const entryPath = path.join(versionDir, "t3");
92 yield* fs.makeDirectory(versionDir, { recursive: true });
93 yield* fs.writeFileString(entryPath, `#!${process.execPath}\n${childSource}`);
94 yield* fs.chmod(entryPath, 0o755);
95 yield* fs.writeFileString(
96 path.join(versionDir, ".install-complete"),
97 `${path.basename(versionDir)}\n`,
98 );
99 return entryPath;
100 });
101
102it.layer(NodeServices.layer)("service state persistence", (it) => {
103 it.effect("durably replaces and strictly reads one state document", () =>
104 Effect.gen(function* () {
105 const fs = yield* FileSystem.FileSystem;
106 const path = yield* Path.Path;
107 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-launcher-test-" });
108 const statePath = path.join(root, "runtime", "service-state.json");
109 const state = {
110 protocol: SERVICE_LAUNCHER_PROTOCOL,
111 activeVersion: "0.0.31",
112 } as const;
113
114 yield* Effect.promise(() => writeServiceState(statePath, state));
115 assert.deepEqual(yield* Effect.promise(() => readServiceState(statePath)), state);
116 }),
117 );
118
119 it.effect("a fresh launcher clears a restart deferred by t3 update", () =>
120 Effect.gen(function* () {
121 const fs = yield* FileSystem.FileSystem;
122 const path = yield* Path.Path;
123 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-launcher-restart-" });
124 const statePath = path.join(root, "runtime", "service-state.json");
125 const restartPending = path.join(root, "runtime", SERVICE_RESTART_PENDING_FILE);
126 yield* writeFakeRuntime(
127 fs,
128 path,
129 path.join(root, "runtime", "versions", "1.0.0"),
130 "setInterval(() => {}, 1_000);\n",
131 );
132 yield* Effect.promise(() =>
133 writeServiceState(statePath, {
134 protocol: SERVICE_LAUNCHER_PROTOCOL,
135 activeVersion: "1.0.0",
136 }),
137 );
138 const run = () =>
139 Effect.gen(function* () {
140 const launcher = new Launcher(
141 root,
142 yield* Effect.promise(() => readServiceState(statePath)),
143 );
144 const running = launcher.run();
145 yield* Effect.promise(() => launcher.stop("SIGTERM"));
146 yield* Effect.promise(() => running);
147 });
148
149 // A launcher that is still the old version leaves a marker that waits
150 // for a newer one.
151 yield* fs.writeFileString(restartPending, "1.0.1\n");
152 yield* run();
153 assert.isTrue(yield* fs.exists(restartPending));
154
155 // Whoever restarted the service, the launcher now runs what the unit
156 // names, so the deferred-restart marker is gone.
157 yield* fs.writeFileString(restartPending, "1.0.0\n");
158 yield* run();
159 assert.isFalse(yield* fs.exists(restartPending));
160 }),
161 );
162
163 it.effect("stays idle instead of exiting when another server owns the T3 home", () =>
164 Effect.gen(function* () {
165 const fs = yield* FileSystem.FileSystem;
166 const path = yield* Path.Path;
167 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-refused-" });
168 const statePath = path.join(root, "runtime", "service-state.json");
169 yield* writeFakeRuntime(
170 fs,
171 path,
172 path.join(root, "runtime", "versions", "1.0.0"),
173 `process.exit(${SERVER_EXIT_CODE_STATE_DIR_OWNED});\n`,
174 );
175 yield* Effect.promise(() =>
176 writeServiceState(statePath, {
177 protocol: SERVICE_LAUNCHER_PROTOCOL,
178 activeVersion: "1.0.0",
179 }),
180 );
181 const refused = Promise.withResolvers<void>();
182 yield* Effect.acquireRelease(
183 Effect.sync(() =>
184 vi.spyOn(process.stderr, "write").mockImplementation((chunk) => {
185 if (String(chunk).includes("owns this T3 home")) refused.resolve();
186 return true;
187 }),
188 ),
189 (spy) => Effect.sync(() => spy.mockRestore()),
190 );
191 const launcher = new Launcher(root, yield* Effect.promise(() => readServiceState(statePath)));
192 let completed = false;
193 const running = launcher.run().finally(() => {
194 completed = true;
195 });
196 yield* Effect.promise(() => refused.promise);
197 assert.isFalse(completed);
198 yield* Effect.promise(() => launcher.stop("SIGTERM"));
199 yield* Effect.promise(() => running);
200 }),
201 );
202
203 it.effect("serializes shutdown with launcher recovery", () =>
204 Effect.gen(function* () {
205 const fs = yield* FileSystem.FileSystem;
206 const path = yield* Path.Path;
207 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-launcher-stop-" });
208 const statePath = path.join(root, "runtime", "service-state.json");
209 yield* writeFakeRuntime(
210 fs,
211 path,
212 path.join(root, "runtime", "versions", "1.0.0"),
213 "setInterval(() => {}, 1_000);\n",
214 );
215 yield* Effect.promise(() =>
216 writeServiceState(statePath, {
217 protocol: SERVICE_LAUNCHER_PROTOCOL,
218 activeVersion: "1.0.0",
219 }),
220 );
221
222 const launcher = new Launcher(root, yield* Effect.promise(() => readServiceState(statePath)));
223 const running = launcher.run();
224 const stopping = launcher.stop("SIGTERM");
225 // An explicit stop leaves the marker that tells a child shutting down
226 // mid-update that no replacement server is coming. It is present as
227 // soon as stop() returns its promise, before queued transitions run.
228 assert.isTrue(yield* fs.exists(path.join(root, "runtime", SERVICE_STOP_MARKER_FILE)));
229 yield* Effect.promise(() => stopping);
230 yield* Effect.promise(() => running);
231 }),
232 );
233
234 it.effect("commits only after the trial reports prepared", () =>
235 Effect.gen(function* () {
236 const fs = yield* FileSystem.FileSystem;
237 const path = yield* Path.Path;
238 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-launcher-flow-" });
239 const statePath = path.join(root, "runtime", "service-state.json");
240 const databasePath = path.join(root, "userdata", "state.sqlite");
241 yield* fs.makeDirectory(path.dirname(databasePath), { recursive: true });
242 yield* fs.writeFileString(databasePath, "before trial");
243 const encodedDatabasePath = JSON.stringify(databasePath);
244 const childSource = `
245const context = JSON.parse(process.env.T3_SERVICE_LAUNCHER_CONTEXT);
246if (context.update?.status === "pending") {
247 process.send({ type: "prepared", updateId: context.update.id });
248 process.on("message", (message) => {
249 if (message.type === "committed") process.exit(0);
250 });
251} else if (context.update === undefined) {
252 process.send({ type: "request-update", targetVersion: "1.1.0", dbPath: ${encodedDatabasePath} });
253 setInterval(() => {}, 1_000);
254} else {
255 process.exit(0);
256}
257`;
258 for (const version of ["1.0.0", "1.1.0"]) {
259 yield* writeFakeRuntime(
260 fs,
261 path,
262 path.join(root, "runtime", "versions", version),
263 childSource,
264 );
265 }
266 yield* Effect.promise(() =>
267 writeServiceState(statePath, {
268 protocol: SERVICE_LAUNCHER_PROTOCOL,
269 activeVersion: "1.0.0",
270 }),
271 );
272
273 const launcher = new Launcher(root, yield* Effect.promise(() => readServiceState(statePath)));
274 yield* Effect.promise(() =>
275 launcher.run().then(
276 () => Promise.reject(new Error("launcher unexpectedly completed")),
277 () => Promise.resolve(),
278 ),
279 );
280
281 const state = yield* Effect.promise(() => readServiceState(statePath));
282 assert.equal(state.activeVersion, "1.1.0");
283 assert.equal(state.update?.status, "committed");
284 }),
285 );
286
287 it.effect("rolls back a trial that reports the wrong update ID", () =>
288 Effect.gen(function* () {
289 const fs = yield* FileSystem.FileSystem;
290 const path = yield* Path.Path;
291 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-launcher-rollback-" });
292 const statePath = path.join(root, "runtime", "service-state.json");
293 const databasePath = path.join(root, "userdata", "state.sqlite");
294 yield* fs.makeDirectory(path.dirname(databasePath), { recursive: true });
295 yield* fs.writeFileString(databasePath, "before trial");
296 const encodedDatabasePath = JSON.stringify(databasePath);
297 const childSource = `
298const context = JSON.parse(process.env.T3_SERVICE_LAUNCHER_CONTEXT);
299if (context.update?.status === "pending") {
300 process.send({ type: "prepared", updateId: "wrong-update" });
301} else if (context.update === undefined) {
302 process.send({ type: "request-update", targetVersion: "1.1.0", dbPath: ${encodedDatabasePath} });
303 setInterval(() => {}, 1_000);
304} else {
305 process.exit(0);
306}
307`;
308 for (const version of ["1.0.0", "1.1.0"]) {
309 yield* writeFakeRuntime(
310 fs,
311 path,
312 path.join(root, "runtime", "versions", version),
313 childSource,
314 );
315 }
316 yield* Effect.promise(() =>
317 writeServiceState(statePath, {
318 protocol: SERVICE_LAUNCHER_PROTOCOL,
319 activeVersion: "1.0.0",
320 }),
321 );
322
323 const launcher = new Launcher(root, yield* Effect.promise(() => readServiceState(statePath)));
324 yield* Effect.promise(() =>
325 launcher.run().then(
326 () => Promise.reject(new Error("launcher unexpectedly completed")),
327 () => Promise.resolve(),
328 ),
329 );
330
331 const state = yield* Effect.promise(() => readServiceState(statePath));
332 assert.equal(state.activeVersion, "1.0.0");
333 assert.equal(state.update?.status, "rolled-back");
334 assert.equal(
335 state.update?.status === "rolled-back" ? state.update.reason : undefined,
336 "invalid-prepared",
337 );
338 }),
339 );
340
341 it.effect("restores the database when a migrating trial exits", () =>
342 Effect.gen(function* () {
343 const fs = yield* FileSystem.FileSystem;
344 const path = yield* Path.Path;
345 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-launcher-db-" });
346 const statePath = path.join(root, "runtime", "service-state.json");
347 const databasePath = path.join(root, "userdata", "state.sqlite");
348 const original = "database before migration";
349 yield* fs.makeDirectory(path.dirname(databasePath), { recursive: true });
350 yield* fs.writeFileString(databasePath, original);
351 const encodedDatabasePath = JSON.stringify(databasePath);
352 const childSource = `
353import { writeFileSync } from "node:fs";
354const context = JSON.parse(process.env.T3_SERVICE_LAUNCHER_CONTEXT);
355if (context.update?.status === "pending") {
356 writeFileSync(context.update.dbPath, "database after migration");
357 writeFileSync(context.update.dbPath + "-wal", "trial wal");
358 writeFileSync(context.update.dbPath + "-shm", "trial shm");
359 process.exit(1);
360} else if (context.update === undefined) {
361 process.send({ type: "request-update", targetVersion: "1.1.0", dbPath: ${encodedDatabasePath} });
362 setInterval(() => {}, 1_000);
363} else {
364 process.exit(0);
365}
366`;
367 for (const version of ["1.0.0", "1.1.0"]) {
368 yield* writeFakeRuntime(
369 fs,
370 path,
371 path.join(root, "runtime", "versions", version),
372 childSource,
373 );
374 }
375 yield* Effect.promise(() =>
376 writeServiceState(statePath, {
377 protocol: SERVICE_LAUNCHER_PROTOCOL,
378 activeVersion: "1.0.0",
379 }),
380 );
381
382 const launcher = new Launcher(root, yield* Effect.promise(() => readServiceState(statePath)));
383 yield* Effect.promise(() =>
384 launcher.run().then(
385 () => Promise.reject(new Error("launcher unexpectedly completed")),
386 () => Promise.resolve(),
387 ),
388 );
389
390 const state = yield* Effect.promise(() => readServiceState(statePath));
391 assert.equal(state.activeVersion, "1.0.0");
392 assert.equal(state.update?.status, "rolled-back");
393 assert.equal(yield* fs.readFileString(databasePath), original);
394 assert.isFalse(yield* fs.exists(`${databasePath}-wal`));
395 assert.isFalse(yield* fs.exists(`${databasePath}-shm`));
396 const updateId = state.update?.id;
397 assert.isDefined(updateId);
398 assert.isFalse(yield* fs.exists(path.join(root, "runtime", "db-backup", updateId)));
399 }),
400 );
401});