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