Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

serviceLauncher.test.ts

292 lines12.1 KB

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​
78it.layer(NodeServices.layer)("service state persistence", (it) => {
79 it.effect("durably replaces and strictly reads one state document", () =>
80 Effect.gen(function* () {
81 const fs = yield* FileSystem.FileSystem;
82 const path = yield* Path.Path;
83 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-launcher-test-" });
84 const statePath = path.join(root, "runtime", "service-state.json");
85 const state = {
86 protocol: SERVICE_LAUNCHER_PROTOCOL,
87 activeVersion: "0.0.31",
88 } as const;
89​
90 yield* Effect.promise(() => writeServiceState(statePath, state));
91 assert.deepEqual(yield* Effect.promise(() => readServiceState(statePath)), state);
92 }),
93 );
94​
95 it.effect("serializes shutdown with launcher recovery", () =>
96 Effect.gen(function* () {
97 const fs = yield* FileSystem.FileSystem;
98 const path = yield* Path.Path;
99 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-launcher-stop-" });
100 const statePath = path.join(root, "runtime", "service-state.json");
101 const versionDir = path.join(root, "runtime", "versions", "1.0.0");
102 const entryPath = path.join(versionDir, "node_modules", "t3", "dist", "bin.mjs");
103 yield* fs.makeDirectory(path.dirname(entryPath), { recursive: true });
104 yield* fs.writeFileString(entryPath, "setInterval(() => {}, 1_000);\n");
105 yield* fs.writeFileString(path.join(versionDir, ".install-complete"), "1.0.0\n");
106 yield* Effect.promise(() =>
107 writeServiceState(statePath, {
108 protocol: SERVICE_LAUNCHER_PROTOCOL,
109 activeVersion: "1.0.0",
110 }),
111 );
112​
113 const launcher = new Launcher(root, yield* Effect.promise(() => readServiceState(statePath)));
114 const running = launcher.run();
115 const stopping = launcher.stop("SIGTERM");
116 // An explicit stop leaves the marker that tells a child shutting down
117 // mid-update that no replacement server is coming. It is present as
118 // soon as stop() returns its promise, before queued transitions run.
119 assert.isTrue(yield* fs.exists(path.join(root, "runtime", SERVICE_STOP_MARKER_FILE)));
120 yield* Effect.promise(() => stopping);
121 yield* Effect.promise(() => running);
122 }),
123 );
124​
125 it.effect("commits only after the trial reports prepared", () =>
126 Effect.gen(function* () {
127 const fs = yield* FileSystem.FileSystem;
128 const path = yield* Path.Path;
129 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-launcher-flow-" });
130 const statePath = path.join(root, "runtime", "service-state.json");
131 const databasePath = path.join(root, "userdata", "state.sqlite");
132 yield* fs.makeDirectory(path.dirname(databasePath), { recursive: true });
133 yield* fs.writeFileString(databasePath, "before trial");
134 // @effect-diagnostics-next-line preferSchemaOverJson:off - embeds a path in fake child source.
135 const encodedDatabasePath = JSON.stringify(databasePath);
136 const childSource = `
137const context = JSON.parse(process.env.T3_SERVICE_LAUNCHER_CONTEXT);
138if (context.update?.status === "pending") {
139 process.send({ type: "prepared", updateId: context.update.id });
140 process.on("message", (message) => {
141 if (message.type === "committed") process.exit(0);
142 });
143} else if (context.update === undefined) {
144 process.send({ type: "request-update", targetVersion: "1.1.0", dbPath: ${encodedDatabasePath} });
145 setInterval(() => {}, 1_000);
146} else {
147 process.exit(0);
149`;
150 for (const version of ["1.0.0", "1.1.0"]) {
151 const versionDir = path.join(root, "runtime", "versions", version);
152 const entryPath = path.join(versionDir, "node_modules", "t3", "dist", "bin.mjs");
153 yield* fs.makeDirectory(path.dirname(entryPath), { recursive: true });
154 yield* fs.writeFileString(entryPath, childSource);
155 yield* fs.writeFileString(path.join(versionDir, ".install-complete"), `${version}\n`);
156 }
157 yield* Effect.promise(() =>
158 writeServiceState(statePath, {
159 protocol: SERVICE_LAUNCHER_PROTOCOL,
160 activeVersion: "1.0.0",
161 }),
162 );
163​
164 const launcher = new Launcher(root, yield* Effect.promise(() => readServiceState(statePath)));
165 yield* Effect.promise(() =>
166 launcher.run().then(
167 () => Promise.reject(new Error("launcher unexpectedly completed")),
168 () => Promise.resolve(),
169 ),
170 );
171​
172 const state = yield* Effect.promise(() => readServiceState(statePath));
173 assert.equal(state.activeVersion, "1.1.0");
174 assert.equal(state.update?.status, "committed");
175 }),
176 );
177​
178 it.effect("rolls back a trial that reports the wrong update ID", () =>
179 Effect.gen(function* () {
180 const fs = yield* FileSystem.FileSystem;
181 const path = yield* Path.Path;
182 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-launcher-rollback-" });
183 const statePath = path.join(root, "runtime", "service-state.json");
184 const databasePath = path.join(root, "userdata", "state.sqlite");
185 yield* fs.makeDirectory(path.dirname(databasePath), { recursive: true });
186 yield* fs.writeFileString(databasePath, "before trial");
187 // @effect-diagnostics-next-line preferSchemaOverJson:off - embeds a path in fake child source.
188 const encodedDatabasePath = JSON.stringify(databasePath);
189 const childSource = `
190const context = JSON.parse(process.env.T3_SERVICE_LAUNCHER_CONTEXT);
191if (context.update?.status === "pending") {
192 process.send({ type: "prepared", updateId: "wrong-update" });
193} else if (context.update === undefined) {
194 process.send({ type: "request-update", targetVersion: "1.1.0", dbPath: ${encodedDatabasePath} });
195 setInterval(() => {}, 1_000);
196} else {
197 process.exit(0);
199`;
200 for (const version of ["1.0.0", "1.1.0"]) {
201 const versionDir = path.join(root, "runtime", "versions", version);
202 const entryPath = path.join(versionDir, "node_modules", "t3", "dist", "bin.mjs");
203 yield* fs.makeDirectory(path.dirname(entryPath), { recursive: true });
204 yield* fs.writeFileString(entryPath, childSource);
205 yield* fs.writeFileString(path.join(versionDir, ".install-complete"), `${version}\n`);
206 }
207 yield* Effect.promise(() =>
208 writeServiceState(statePath, {
209 protocol: SERVICE_LAUNCHER_PROTOCOL,
210 activeVersion: "1.0.0",
211 }),
212 );
213​
214 const launcher = new Launcher(root, yield* Effect.promise(() => readServiceState(statePath)));
215 yield* Effect.promise(() =>
216 launcher.run().then(
217 () => Promise.reject(new Error("launcher unexpectedly completed")),
218 () => Promise.resolve(),
219 ),
220 );
221​
222 const state = yield* Effect.promise(() => readServiceState(statePath));
223 assert.equal(state.activeVersion, "1.0.0");
224 assert.equal(state.update?.status, "rolled-back");
225 assert.equal(
226 state.update?.status === "rolled-back" ? state.update.reason : undefined,
227 "invalid-prepared",
228 );
229 }),
230 );
231​
232 it.effect("restores the database when a migrating trial exits", () =>
233 Effect.gen(function* () {
234 const fs = yield* FileSystem.FileSystem;
235 const path = yield* Path.Path;
236 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-launcher-db-" });
237 const statePath = path.join(root, "runtime", "service-state.json");
238 const databasePath = path.join(root, "userdata", "state.sqlite");
239 const original = "database before migration";
240 yield* fs.makeDirectory(path.dirname(databasePath), { recursive: true });
241 yield* fs.writeFileString(databasePath, original);
242 // @effect-diagnostics-next-line preferSchemaOverJson:off - embeds a path in fake child source.
243 const encodedDatabasePath = JSON.stringify(databasePath);
244 const childSource = `
245import { writeFileSync } from "node:fs";
246const context = JSON.parse(process.env.T3_SERVICE_LAUNCHER_CONTEXT);
247if (context.update?.status === "pending") {
248 writeFileSync(context.update.dbPath, "database after migration");
249 writeFileSync(context.update.dbPath + "-wal", "trial wal");
250 writeFileSync(context.update.dbPath + "-shm", "trial shm");
251 process.exit(1);
252} else if (context.update === undefined) {
253 process.send({ type: "request-update", targetVersion: "1.1.0", dbPath: ${encodedDatabasePath} });
254 setInterval(() => {}, 1_000);
255} else {
256 process.exit(0);
258`;
259 for (const version of ["1.0.0", "1.1.0"]) {
260 const versionDir = path.join(root, "runtime", "versions", version);
261 const entryPath = path.join(versionDir, "node_modules", "t3", "dist", "bin.mjs");
262 yield* fs.makeDirectory(path.dirname(entryPath), { recursive: true });
263 yield* fs.writeFileString(entryPath, childSource);
264 yield* fs.writeFileString(path.join(versionDir, ".install-complete"), `${version}\n`);
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.0.0");
283 assert.equal(state.update?.status, "rolled-back");
284 assert.equal(yield* fs.readFileString(databasePath), original);
285 assert.isFalse(yield* fs.exists(`${databasePath}-wal`));
286 assert.isFalse(yield* fs.exists(`${databasePath}-shm`));
287 const updateId = state.update?.id;
288 assert.isDefined(updateId);
289 assert.isFalse(yield* fs.exists(path.join(root, "runtime", "db-backup", updateId)));
290 }),
291 );
292});