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 {
8 applyServiceEnvFile,
9 Launcher,
10 parseServiceEnvFile,
11 readServiceEnvFile,
12 readServiceState,
13 writeServiceState,
14} from "./serviceLauncher.ts";
15import {
16 compareExactServiceVersions,
17 decodeServiceState,
18 isExactServiceVersion,
19 SERVICE_ENV_FILE,
20 SERVICE_LAUNCHER_PROTOCOL,
21 SERVICE_RESTART_PENDING_FILE,
22 SERVICE_STOP_MARKER_FILE,
23} from "./cloud/serviceProtocol.ts";
24
25it("accepts only exact semantic versions", () => {
26 for (const version of ["0.0.0", "1.2.3", "1.2.3-alpha.1", "1.2.3-0", "1.2.3+001"]) {
27 assert.isTrue(isExactServiceVersion(version), version);
28 }
29 for (const version of ["latest", "01.2.3", "1.2.3-01", "1.2.3-alpha..1", "1.2.3+."]) {
30 assert.isFalse(isExactServiceVersion(version), version);
31 }
32});
33
34it("orders exact semantic versions without treating build metadata as precedence", () => {
35 assert.equal(compareExactServiceVersions("1.2.3", "1.2.3"), 0);
36 assert.equal(compareExactServiceVersions("1.2.4", "1.2.3"), 1);
37 assert.equal(compareExactServiceVersions("2.0.0-alpha.1", "2.0.0-alpha.2"), -1);
38 assert.equal(compareExactServiceVersions("2.0.0-alpha.2", "2.0.0-alpha.beta"), -1);
39 assert.equal(compareExactServiceVersions("2.0.0-alpha-beta", "2.0.0-alpha-alpha"), 1);
40 assert.equal(compareExactServiceVersions("2.0.0", "2.0.0-rc.1"), 1);
41 assert.equal(compareExactServiceVersions("2.0.0+one", "2.0.0+two"), 0);
42});
43
44it("parses KEY=VALUE assignments from the T3 home service env file", () => {
45 assert.deepEqual(
46 parseServiceEnvFile(
47 [
48 "# Bitbucket credentials",
49 "export T3CODE_BITBUCKET_EMAIL=you@example.com",
50 'T3CODE_BITBUCKET_API_TOKEN="token with spaces"',
51 "T3CODE_PORT=1234",
52 "T3CODE_HOST=0.0.0.0",
53 "NOTE=A & <B>",
54 "EMPTY=",
55 "PATH=/should-not-override",
56 "T3CODE_HOME=/should-not-override",
57 "T3_BOOT_SERVICE_UNIT=should-not-override",
58 "T3_SERVICE_LAUNCHER_CONTEXT=should-not-override",
59 "Path=/should-not-override-case",
60 "t3code_home=/should-not-override-case",
61 "T3_boot_service_unit=should-not-override-case",
62 "t3_service_launcher_context=should-not-override-case",
63 "123BAD=x",
64 "INVALID NAME=x",
65 "",
66 ].join("\n"),
67 ),
68 {
69 T3CODE_BITBUCKET_EMAIL: "you@example.com",
70 T3CODE_BITBUCKET_API_TOKEN: "token with spaces",
71 T3CODE_PORT: "1234",
72 T3CODE_HOST: "0.0.0.0",
73 NOTE: "A & <B>",
74 EMPTY: "",
75 },
76 );
77});
78
79it("rejects contradictory service state", () => {
80 assert.isUndefined(
81 decodeServiceState({
82 protocol: SERVICE_LAUNCHER_PROTOCOL,
83 activeVersion: "0.0.31",
84 update: {
85 id: "update-1",
86 fromVersion: "0.0.30",
87 targetVersion: "0.0.32",
88 dbPath: "/tmp/state.sqlite",
89 status: "pending",
90 },
91 }),
92 );
93
94 assert.isUndefined(
95 decodeServiceState({
96 protocol: SERVICE_LAUNCHER_PROTOCOL,
97 activeVersion: "1.0.0",
98 update: {
99 id: "update-3",
100 fromVersion: "1.0.0",
101 targetVersion: "1.1.0",
102 status: "pending",
103 },
104 }),
105 );
106
107 assert.isUndefined(
108 decodeServiceState({
109 protocol: SERVICE_LAUNCHER_PROTOCOL,
110 activeVersion: "1.0.0",
111 update: {
112 id: "update-2",
113 fromVersion: "1.0.0",
114 targetVersion: "0.9.0",
115 dbPath: "/tmp/state.sqlite",
116 status: "pending",
117 },
118 }),
119 );
120});
121
122// A pinned runtime is an executable at <versionDir>/t3. The tests stand one up
123// as a Node shebang script so the launcher spawns it the way it spawns the
124// real single-executable, IPC channel included.
125const writeFakeRuntime = (
126 fs: FileSystem.FileSystem,
127 path: Path.Path,
128 versionDir: string,
129 childSource: string,
130) =>
131 Effect.gen(function* () {
132 const entryPath = path.join(versionDir, "t3");
133 yield* fs.makeDirectory(versionDir, { recursive: true });
134 yield* fs.writeFileString(entryPath, `#!${process.execPath}\n${childSource}`);
135 yield* fs.chmod(entryPath, 0o755);
136 yield* fs.writeFileString(
137 path.join(versionDir, ".install-complete"),
138 `${path.basename(versionDir)}\n`,
139 );
140 return entryPath;
141 });
142
143it.layer(NodeServices.layer)("service state persistence", (it) => {
144 it.effect("merges T3 home service.env into a provided environment and into the child", () =>
145 Effect.gen(function* () {
146 const fs = yield* FileSystem.FileSystem;
147 const path = yield* Path.Path;
148 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-env-" });
149 const statePath = path.join(root, "runtime", "service-state.json");
150 const seenPath = path.join(root, "seen-env.json");
151 yield* fs.writeFileString(
152 path.join(root, SERVICE_ENV_FILE),
153 [
154 "T3CODE_BITBUCKET_EMAIL=you@example.com",
155 'T3CODE_BITBUCKET_API_TOKEN="token with spaces"',
156 "T3CODE_PORT=1234",
157 "T3CODE_HOME=/should-not-override",
158 "PATH=/should-not-override",
159 "Path=/should-not-override-case",
160 "t3code_home=/should-not-override-case",
161 "",
162 ].join("\n"),
163 );
164
165 assert.deepEqual(
166 yield* Effect.promise(() => readServiceEnvFile(path.join(root, "missing"))),
167 {},
168 );
169 const env: NodeJS.ProcessEnv = {
170 PATH: "/bin",
171 T3CODE_HOME: root,
172 T3CODE_PORT: "old",
173 };
174 const serviceEnv = yield* Effect.promise(() => applyServiceEnvFile(root, env));
175 assert.equal(env.T3CODE_BITBUCKET_EMAIL, "you@example.com");
176 assert.equal(env.T3CODE_BITBUCKET_API_TOKEN, "token with spaces");
177 assert.equal(env.T3CODE_PORT, "1234");
178 assert.equal(env.T3CODE_HOME, root);
179 assert.equal(env.PATH, "/bin");
180 assert.isUndefined(serviceEnv.Path);
181 assert.isUndefined(serviceEnv.t3code_home);
182 assert.isUndefined(env.Path);
183 assert.isUndefined(env.t3code_home);
184 // Later file edits wait for a service restart; children reuse the startup map.
185 yield* fs.writeFileString(path.join(root, SERVICE_ENV_FILE), "T3CODE_PORT=9999\n");
186
187 const encodedSeenPath = JSON.stringify(seenPath);
188 yield* writeFakeRuntime(
189 fs,
190 path,
191 path.join(root, "runtime", "versions", "1.0.0"),
192 `import { writeFileSync } from "node:fs";
193writeFileSync(${encodedSeenPath}, JSON.stringify({
194 email: process.env.T3CODE_BITBUCKET_EMAIL,
195 token: process.env.T3CODE_BITBUCKET_API_TOKEN,
196 port: process.env.T3CODE_PORT,
197 home: process.env.T3CODE_HOME,
198 path: process.env.PATH,
199}));
200process.exit(0);
201`,
202 );
203 yield* Effect.promise(() =>
204 writeServiceState(statePath, {
205 protocol: SERVICE_LAUNCHER_PROTOCOL,
206 activeVersion: "1.0.0",
207 }),
208 );
209
210 const launcher = new Launcher(
211 root,
212 yield* Effect.promise(() => readServiceState(statePath)),
213 serviceEnv,
214 );
215 yield* Effect.promise(() =>
216 launcher.run().then(
217 () => Promise.reject(new Error("launcher unexpectedly completed")),
218 () => Promise.resolve(),
219 ),
220 );
221
222 const seen = JSON.parse(yield* fs.readFileString(seenPath)) as {
223 email: string;
224 token: string;
225 port: string;
226 home: string | undefined;
227 path: string | undefined;
228 };
229 assert.equal(seen.email, "you@example.com");
230 assert.equal(seen.token, "token with spaces");
231 assert.equal(seen.port, "1234");
232 assert.notEqual(seen.home, "/should-not-override");
233 assert.notEqual(seen.path, "/should-not-override");
234 }),
235 );
236
237 it.effect("durably replaces and strictly reads one state document", () =>
238 Effect.gen(function* () {
239 const fs = yield* FileSystem.FileSystem;
240 const path = yield* Path.Path;
241 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-launcher-test-" });
242 const statePath = path.join(root, "runtime", "service-state.json");
243 const state = {
244 protocol: SERVICE_LAUNCHER_PROTOCOL,
245 activeVersion: "0.0.31",
246 } as const;
247
248 yield* Effect.promise(() => writeServiceState(statePath, state));
249 assert.deepEqual(yield* Effect.promise(() => readServiceState(statePath)), state);
250 }),
251 );
252
253 it.effect("a fresh launcher clears a restart deferred by t3 update", () =>
254 Effect.gen(function* () {
255 const fs = yield* FileSystem.FileSystem;
256 const path = yield* Path.Path;
257 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-launcher-restart-" });
258 const statePath = path.join(root, "runtime", "service-state.json");
259 const restartPending = path.join(root, "runtime", SERVICE_RESTART_PENDING_FILE);
260 yield* writeFakeRuntime(
261 fs,
262 path,
263 path.join(root, "runtime", "versions", "1.0.0"),
264 "setInterval(() => {}, 1_000);\n",
265 );
266 yield* Effect.promise(() =>
267 writeServiceState(statePath, {
268 protocol: SERVICE_LAUNCHER_PROTOCOL,
269 activeVersion: "1.0.0",
270 }),
271 );
272 const run = () =>
273 Effect.gen(function* () {
274 const launcher = new Launcher(
275 root,
276 yield* Effect.promise(() => readServiceState(statePath)),
277 );
278 const running = launcher.run();
279 yield* Effect.promise(() => launcher.stop("SIGTERM"));
280 yield* Effect.promise(() => running);
281 });
282
283 // A launcher that is still the old version leaves a marker that waits
284 // for a newer one.
285 yield* fs.writeFileString(restartPending, "1.0.1\n");
286 yield* run();
287 assert.isTrue(yield* fs.exists(restartPending));
288
289 // Whoever restarted the service, the launcher now runs what the unit
290 // names, so the deferred-restart marker is gone.
291 yield* fs.writeFileString(restartPending, "1.0.0\n");
292 yield* run();
293 assert.isFalse(yield* fs.exists(restartPending));
294 }),
295 );
296
297 it.effect("serializes shutdown with launcher recovery", () =>
298 Effect.gen(function* () {
299 const fs = yield* FileSystem.FileSystem;
300 const path = yield* Path.Path;
301 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-launcher-stop-" });
302 const statePath = path.join(root, "runtime", "service-state.json");
303 yield* writeFakeRuntime(
304 fs,
305 path,
306 path.join(root, "runtime", "versions", "1.0.0"),
307 "setInterval(() => {}, 1_000);\n",
308 );
309 yield* Effect.promise(() =>
310 writeServiceState(statePath, {
311 protocol: SERVICE_LAUNCHER_PROTOCOL,
312 activeVersion: "1.0.0",
313 }),
314 );
315
316 const launcher = new Launcher(root, yield* Effect.promise(() => readServiceState(statePath)));
317 const running = launcher.run();
318 const stopping = launcher.stop("SIGTERM");
319 // An explicit stop leaves the marker that tells a child shutting down
320 // mid-update that no replacement server is coming. It is present as
321 // soon as stop() returns its promise, before queued transitions run.
322 assert.isTrue(yield* fs.exists(path.join(root, "runtime", SERVICE_STOP_MARKER_FILE)));
323 yield* Effect.promise(() => stopping);
324 yield* Effect.promise(() => running);
325 }),
326 );
327
328 it.effect("commits only after the trial reports prepared", () =>
329 Effect.gen(function* () {
330 const fs = yield* FileSystem.FileSystem;
331 const path = yield* Path.Path;
332 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-launcher-flow-" });
333 const statePath = path.join(root, "runtime", "service-state.json");
334 const databasePath = path.join(root, "userdata", "state.sqlite");
335 yield* fs.makeDirectory(path.dirname(databasePath), { recursive: true });
336 yield* fs.writeFileString(databasePath, "before trial");
337 const encodedDatabasePath = JSON.stringify(databasePath);
338 const childSource = `
339const context = JSON.parse(process.env.T3_SERVICE_LAUNCHER_CONTEXT);
340if (context.update?.status === "pending") {
341 process.send({ type: "prepared", updateId: context.update.id });
342 process.on("message", (message) => {
343 if (message.type === "committed") process.exit(0);
344 });
345} else if (context.update === undefined) {
346 process.send({ type: "request-update", targetVersion: "1.1.0", dbPath: ${encodedDatabasePath} });
347 setInterval(() => {}, 1_000);
348} else {
349 process.exit(0);
350}
351`;
352 for (const version of ["1.0.0", "1.1.0"]) {
353 yield* writeFakeRuntime(
354 fs,
355 path,
356 path.join(root, "runtime", "versions", version),
357 childSource,
358 );
359 }
360 yield* Effect.promise(() =>
361 writeServiceState(statePath, {
362 protocol: SERVICE_LAUNCHER_PROTOCOL,
363 activeVersion: "1.0.0",
364 }),
365 );
366
367 const launcher = new Launcher(root, yield* Effect.promise(() => readServiceState(statePath)));
368 yield* Effect.promise(() =>
369 launcher.run().then(
370 () => Promise.reject(new Error("launcher unexpectedly completed")),
371 () => Promise.resolve(),
372 ),
373 );
374
375 const state = yield* Effect.promise(() => readServiceState(statePath));
376 assert.equal(state.activeVersion, "1.1.0");
377 assert.equal(state.update?.status, "committed");
378 }),
379 );
380
381 it.effect("rolls back a trial that reports the wrong update ID", () =>
382 Effect.gen(function* () {
383 const fs = yield* FileSystem.FileSystem;
384 const path = yield* Path.Path;
385 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-launcher-rollback-" });
386 const statePath = path.join(root, "runtime", "service-state.json");
387 const databasePath = path.join(root, "userdata", "state.sqlite");
388 yield* fs.makeDirectory(path.dirname(databasePath), { recursive: true });
389 yield* fs.writeFileString(databasePath, "before trial");
390 const encodedDatabasePath = JSON.stringify(databasePath);
391 const childSource = `
392const context = JSON.parse(process.env.T3_SERVICE_LAUNCHER_CONTEXT);
393if (context.update?.status === "pending") {
394 process.send({ type: "prepared", updateId: "wrong-update" });
395} else if (context.update === undefined) {
396 process.send({ type: "request-update", targetVersion: "1.1.0", dbPath: ${encodedDatabasePath} });
397 setInterval(() => {}, 1_000);
398} else {
399 process.exit(0);
400}
401`;
402 for (const version of ["1.0.0", "1.1.0"]) {
403 yield* writeFakeRuntime(
404 fs,
405 path,
406 path.join(root, "runtime", "versions", version),
407 childSource,
408 );
409 }
410 yield* Effect.promise(() =>
411 writeServiceState(statePath, {
412 protocol: SERVICE_LAUNCHER_PROTOCOL,
413 activeVersion: "1.0.0",
414 }),
415 );
416
417 const launcher = new Launcher(root, yield* Effect.promise(() => readServiceState(statePath)));
418 yield* Effect.promise(() =>
419 launcher.run().then(
420 () => Promise.reject(new Error("launcher unexpectedly completed")),
421 () => Promise.resolve(),
422 ),
423 );
424
425 const state = yield* Effect.promise(() => readServiceState(statePath));
426 assert.equal(state.activeVersion, "1.0.0");
427 assert.equal(state.update?.status, "rolled-back");
428 assert.equal(
429 state.update?.status === "rolled-back" ? state.update.reason : undefined,
430 "invalid-prepared",
431 );
432 }),
433 );
434
435 it.effect("restores the database when a migrating trial exits", () =>
436 Effect.gen(function* () {
437 const fs = yield* FileSystem.FileSystem;
438 const path = yield* Path.Path;
439 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-launcher-db-" });
440 const statePath = path.join(root, "runtime", "service-state.json");
441 const databasePath = path.join(root, "userdata", "state.sqlite");
442 const original = "database before migration";
443 yield* fs.makeDirectory(path.dirname(databasePath), { recursive: true });
444 yield* fs.writeFileString(databasePath, original);
445 const encodedDatabasePath = JSON.stringify(databasePath);
446 const childSource = `
447import { writeFileSync } from "node:fs";
448const context = JSON.parse(process.env.T3_SERVICE_LAUNCHER_CONTEXT);
449if (context.update?.status === "pending") {
450 writeFileSync(context.update.dbPath, "database after migration");
451 writeFileSync(context.update.dbPath + "-wal", "trial wal");
452 writeFileSync(context.update.dbPath + "-shm", "trial shm");
453 process.exit(1);
454} else if (context.update === undefined) {
455 process.send({ type: "request-update", targetVersion: "1.1.0", dbPath: ${encodedDatabasePath} });
456 setInterval(() => {}, 1_000);
457} else {
458 process.exit(0);
459}
460`;
461 for (const version of ["1.0.0", "1.1.0"]) {
462 yield* writeFakeRuntime(
463 fs,
464 path,
465 path.join(root, "runtime", "versions", version),
466 childSource,
467 );
468 }
469 yield* Effect.promise(() =>
470 writeServiceState(statePath, {
471 protocol: SERVICE_LAUNCHER_PROTOCOL,
472 activeVersion: "1.0.0",
473 }),
474 );
475
476 const launcher = new Launcher(root, yield* Effect.promise(() => readServiceState(statePath)));
477 yield* Effect.promise(() =>
478 launcher.run().then(
479 () => Promise.reject(new Error("launcher unexpectedly completed")),
480 () => Promise.resolve(),
481 ),
482 );
483
484 const state = yield* Effect.promise(() => readServiceState(statePath));
485 assert.equal(state.activeVersion, "1.0.0");
486 assert.equal(state.update?.status, "rolled-back");
487 assert.equal(yield* fs.readFileString(databasePath), original);
488 assert.isFalse(yield* fs.exists(`${databasePath}-wal`));
489 assert.isFalse(yield* fs.exists(`${databasePath}-shm`));
490 const updateId = state.update?.id;
491 assert.isDefined(updateId);
492 assert.isFalse(yield* fs.exists(path.join(root, "runtime", "db-backup", updateId)));
493 }),
494 );
495});