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