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

serverRuntimeState.test.ts

399 lines15.5 KB

1import { assert, describe, it } from "@effect/vitest";
2import * as NodeServices from "@effect/platform-node/NodeServices";
3import * as HostProcess from "@t3tools/shared/HostProcess";
4import * as Effect from "effect/Effect";
5import * as FileSystem from "effect/FileSystem";
6import * as Layer from "effect/Layer";
7import * as Option from "effect/Option";
8import * as Path from "effect/Path";
9import * as Runtime from "effect/Runtime";
10import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
11​
12import { renderBootServicePlist, renderBootServiceUnit } from "./cloud/bootService.ts";
13import { ServiceLauncherHostProcess } from "./cloud/serviceLauncherClient.ts";
14import { SERVICE_LAUNCHER_CONTEXT_ENV } from "./cloud/serviceProtocol.ts";
15import * as ProcessRunner from "./processRunner.ts";
16import * as ServerOwnership from "./serverOwnership.ts";
17import * as ServerRuntimeState from "./serverRuntimeState.ts";
18​
19const startBesideBootService = Effect.fn("test.startBesideBootService")(function* (input: {
20 readonly platform: "darwin" | "linux";
21 readonly outputs: Readonly<Record<string, { readonly code: number; readonly stdout?: string }>>;
22 readonly unitServesOtherHome?: boolean;
23 readonly restartPending?: boolean;
24 readonly activeVersion?: string;
25 readonly npmRuntime?: boolean;
26 readonly missingServiceState?: boolean;
27 readonly environment?: NodeJS.ProcessEnv;
28 readonly connected?: boolean;
29}) {
30 const fs = yield* FileSystem.FileSystem;
31 const path = yield* Path.Path;
32 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-owner-boot-service-" });
33 const t3Home = path.join(root, ".t3");
34 const serviceHome = input.unitServesOtherHome ? path.join(root, "other") : t3Home;
35 for (const home of [t3Home, serviceHome]) {
36 yield* fs.makeDirectory(path.join(home, "userdata"), { recursive: true });
37 }
38 yield* fs.makeDirectory(path.join(serviceHome, "runtime"));
39 const activeVersion = input.activeVersion ?? "0.0.42";
40 if (!input.missingServiceState) {
41 yield* fs.writeFileString(
42 path.join(serviceHome, "runtime", "service-state.json"),
43 JSON.stringify({ protocol: input.npmRuntime ? 2 : 3, activeVersion }),
44 );
45 }
46 if (input.npmRuntime) {
47 const versionDir = path.join(serviceHome, "runtime", "versions", activeVersion);
48 const entryPath = path.join(versionDir, "node_modules", "t3", "dist", "bin.mjs");
49 yield* fs.makeDirectory(path.dirname(entryPath), { recursive: true });
50 yield* fs.writeFileString(entryPath, "");
51 }
52​
53 if (input.restartPending) {
54 yield* fs.writeFileString(
55 path.join(serviceHome, "runtime", ".restart-pending"),
56 `${activeVersion}\n`,
57 );
58 }
59 const plan = {
60 program: input.npmRuntime
61 ? ["/usr/bin/node", path.join(serviceHome, "runtime", "service-launcher.mjs")]
62 : [],
63 baseDir: serviceHome,
64 logPath: "",
65 unitPath: "",
66 };
67 const [unitPath, unit] =
68 input.platform === "darwin"
69 ? [
70 path.join(root, "Library", "LaunchAgents", "com.t3tools.t3code.service.plist"),
71 renderBootServicePlist(plan, { homeDir: root, environmentPath: "" }),
72 ]
73 : [
74 path.join(root, ".config", "systemd", "user", "t3code.service"),
75 renderBootServiceUnit(plan),
76 ];
77 yield* fs.makeDirectory(path.dirname(unitPath), { recursive: true });
78 yield* fs.writeFileString(unitPath, unit);
79​
80 const probes: string[] = [];
81 const runner = ProcessRunner.ProcessRunner.of({
82 run: (run) =>
83 Effect.gen(function* () {
84 const probe = `${path.basename(run.command)} ${run.args.find((arg) => !arg.startsWith("--"))}`;
85 probes.push(probe);
86 const output = input.outputs[probe];
87 return yield* output === undefined
88 ? Effect.fail(
89 new ProcessRunner.ProcessSpawnError({
90 command: run.command,
91 argumentCount: run.args.length,
92 cause: new Error("not found"),
93 }),
94 )
95 : Effect.succeed({
96 stdout: output.stdout ?? "",
97 stderr: "",
98 code: ChildProcessSpawner.ExitCode(output.code),
99 timedOut: false,
100 stdoutTruncated: false,
101 stderrTruncated: false,
102 stdoutInvalidUtf8: false,
103 stderrInvalidUtf8: false,
104 });
105 }),
106 });
107 const result = yield* Effect.scoped(
108 ServerOwnership.acquireServerOwnership(path.join(t3Home, "userdata", "server-runtime.json")),
109 ).pipe(
110 Effect.provideService(ProcessRunner.ProcessRunner, runner),
111 Effect.provideService(HostProcess.Platform, input.platform),
112 Effect.provideService(HostProcess.UserId, 501),
113 Effect.provideService(HostProcess.HomeDirectory, root),
114 Effect.provideService(HostProcess.Environment, input.environment ?? {}),
115 Effect.provideService(ServiceLauncherHostProcess, {
116 connected: input.connected ?? false,
117 send: () => false,
118 on: () => undefined,
119 off: () => undefined,
120 }),
121 Effect.result,
122 );
123 assert.includeMembers(
124 ["launchctl print", "launchctl print-disabled", "systemctl is-active", "systemctl is-enabled"],
125 probes,
126 );
127 return { result, t3Home };
128});
129​
130describe("server ownership", () => {
131 // An empty home, so no boot service unit installed on this machine is read.
132 const layerOwnership = Layer.mergeAll(
133 ProcessRunner.layer,
134 Layer.effect(
135 HostProcess.HomeDirectory,
136 Effect.gen(function* () {
137 return yield* (yield* FileSystem.FileSystem).makeTempDirectoryScoped();
138 }),
139 ),
140 Layer.succeed(HostProcess.Environment, {}),
141 ).pipe(Layer.provideMerge(NodeServices.layer));
142 const makeState = ServerRuntimeState.makePersistedServerRuntimeState({
143 config: { host: undefined, devUrl: undefined },
144 port: 3773,
145 });
146​
147 it.effect("lets only one of two racing starts own a state directory", () =>
148 Effect.gen(function* () {
149 const fs = yield* FileSystem.FileSystem;
150 const path = yield* Path.Path;
151 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-owner-race-" });
152 const statePath = path.join(root, "server-runtime.json");
153 const attempts = yield* Effect.all(
154 [
155 ServerOwnership.acquireServerOwnership(statePath).pipe(Effect.result),
156 ServerOwnership.acquireServerOwnership(statePath).pipe(Effect.result),
157 ],
158 { concurrency: "unbounded" },
159 );
160 assert.equal(attempts.filter((result) => result._tag === "Success").length, 1);
161 const refused = attempts.find((result) => result._tag === "Failure");
162 assert.equal(refused?.failure._tag, "ServerAlreadyRunningError");
163 }).pipe(Effect.provide(layerOwnership)),
164 );
165​
166 it.effect("refuses a second owner without touching its record, then allows a restart", () =>
167 Effect.gen(function* () {
168 const fs = yield* FileSystem.FileSystem;
169 const path = yield* Path.Path;
170 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-owner-" });
171 const statePath = path.join(root, "server-runtime.json");
172 const state = yield* makeState;
173 yield* Effect.scoped(
174 Effect.gen(function* () {
175 const owner = yield* ServerOwnership.acquireServerOwnership(statePath);
176 yield* owner.publish(state);
177 const before = yield* fs.readFileString(statePath);
178 const refused = yield* ServerOwnership.acquireServerOwnership(statePath).pipe(
179 Effect.flip,
180 );
181 assert.equal(refused._tag, "ServerAlreadyRunningError");
182 assert.equal(yield* fs.readFileString(statePath), before);
183 }),
184 );
185 assert.isFalse(yield* fs.exists(statePath));
186 yield* Effect.scoped(ServerOwnership.acquireServerOwnership(statePath));
187 }).pipe(Effect.provide(layerOwnership)),
188 );
189​
190 it.effect("refuses beside a live pre-lock server and ignores a stale record", () =>
191 Effect.gen(function* () {
192 const fs = yield* FileSystem.FileSystem;
193 const path = yield* Path.Path;
194 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-owner-legacy-" });
195 const statePath = path.join(root, "server-runtime.json");
196 const state = yield* makeState;
197 yield* ServerRuntimeState.persistServerRuntimeState({
198 path: statePath,
199 // Any record time after this process started proves the PID was not reused.
200 state: { ...state, startedAt: "2100-01-01T00:00:00.000Z" },
201 });
202 const refused = yield* Effect.scoped(ServerOwnership.acquireServerOwnership(statePath)).pipe(
203 Effect.flip,
204 );
205 assert.equal(refused._tag, "ServerAlreadyRunningError");
206 yield* ServerRuntimeState.persistServerRuntimeState({
207 path: statePath,
208 state: { ...state, pid: 0 },
209 });
210 yield* Effect.scoped(ServerOwnership.acquireServerOwnership(statePath));
211 }).pipe(Effect.provide(layerOwnership)),
212 );
213​
214 it.effect("never removes a runtime record another server published", () =>
215 Effect.gen(function* () {
216 const fs = yield* FileSystem.FileSystem;
217 const path = yield* Path.Path;
218 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-owner-cleanup-" });
219 const statePath = path.join(root, "server-runtime.json");
220 const state = yield* makeState;
221 yield* Effect.scoped(
222 Effect.gen(function* () {
223 const owner = yield* ServerOwnership.acquireServerOwnership(statePath);
224 yield* owner.publish(state);
225 yield* ServerRuntimeState.persistServerRuntimeState({
226 path: statePath,
227 state: { ...state, ownerId: "other-owner" },
228 });
229 }),
230 );
231 const remaining = yield* ServerRuntimeState.readPersistedServerRuntimeState(statePath);
232 assert.equal(Option.getOrThrow(remaining).ownerId, "other-owner");
233 }).pipe(Effect.provide(layerOwnership)),
234 );
235​
236 describe("beside an installed boot service", () => {
237 it.effect("refuses an old active or scheduled service even without its runtime record", () =>
238 Effect.gen(function* () {
239 for (const fixture of [
240 {
241 platform: "darwin",
242 outputs: { "launchctl print": { code: 0 } },
243 },
244 {
245 platform: "darwin",
246 outputs: {
247 "launchctl print": { code: 113 },
248 "launchctl print-disabled": {
249 code: 0,
250 stdout: '"com.t3tools.t3code.service" => false',
251 },
252 },
253 },
254 {
255 platform: "linux",
256 outputs: {
257 // Restart= keeps an otherwise disabled service alive during its restart delay.
258 "systemctl is-active": { code: 3, stdout: "activating\n" },
259 "systemctl is-enabled": { code: 1, stdout: "disabled\n" },
260 },
261 },
262 {
263 platform: "linux",
264 outputs: {
265 "systemctl is-active": { code: 3, stdout: "inactive\n" },
266 "systemctl is-enabled": { code: 0, stdout: "enabled\n" },
267 },
268 },
269 {
270 platform: "darwin",
271 outputs: { "launchctl print": { code: 0 } },
272 environment: { [SERVICE_LAUNCHER_CONTEXT_ENV]: "{}" },
273 },
274 ] as const) {
275 const { result, t3Home } = yield* startBesideBootService(fixture);
276 assert.equal(result._tag, "Failure");
277 if (result._tag !== "Failure") return;
278 assert.equal(result.failure._tag, "OlderBootServiceError");
279 assert.equal(Runtime.getErrorExitCode(result.failure), 78);
280 assert.include(result.failure.message, t3Home);
281 assert.include(result.failure.message, "t3 update");
282 assert.include(result.failure.message, "t3 service restart");
283 assert.include(result.failure.message, "No server was stopped");
284 }
285 }).pipe(Effect.provide(NodeServices.layer)),
286 );
287​
288 it.effect(
289 "refuses an active npm-installed service with no standalone executable or runtime record",
290 () =>
291 Effect.gen(function* () {
292 const { result } = yield* startBesideBootService({
293 platform: "linux",
294 activeVersion: "0.0.40",
295 npmRuntime: true,
296 outputs: {
297 "systemctl is-active": { code: 0, stdout: "active\n" },
298 },
299 });
300 assert.equal(result._tag, "Failure");
301 if (result._tag !== "Failure") return;
302 assert.equal(result.failure._tag, "OlderBootServiceError");
303 assert.equal(Runtime.getErrorExitCode(result.failure), 78);
304 }).pipe(Effect.provide(NodeServices.layer)),
305 );
306​
307 it.effect("refuses while the loaded service has not restarted into its lock-aware update", () =>
308 Effect.gen(function* () {
309 const { result } = yield* startBesideBootService({
310 platform: "darwin",
311 restartPending: true,
312 activeVersion: "0.1.0",
313 outputs: {
314 "launchctl print": { code: 0 },
315 },
316 });
317 assert.equal(result._tag === "Failure" && result.failure._tag, "OlderBootServiceError");
318 }).pipe(Effect.provide(NodeServices.layer)),
319 );
320​
321 it.effect("allows lock-aware stable services that are loaded or stopped and enabled", () =>
322 Effect.gen(function* () {
323 for (const fixture of [
324 {
325 platform: "darwin",
326 outputs: {
327 "launchctl print": { code: 0 },
328 },
329 },
330 {
331 platform: "linux",
332 outputs: {
333 "systemctl is-active": { code: 3, stdout: "inactive\n" },
334 "systemctl is-enabled": { code: 0, stdout: "enabled\n" },
335 },
336 },
337 ] as const) {
338 const { result } = yield* startBesideBootService({ ...fixture, activeVersion: "0.1.0" });
339 assert.equal(result._tag, "Success");
340 }
341 }).pipe(Effect.provide(NodeServices.layer)),
342 );
343​
344 it.effect("allows services that cannot compete for this home", () =>
345 Effect.gen(function* () {
346 const outputs = {
347 "launchctl print": { code: 0 },
348 };
349 for (const fixture of [
350 { platform: "darwin", outputs, unitServesOtherHome: true },
351 {
352 platform: "darwin",
353 outputs,
354 environment: { [SERVICE_LAUNCHER_CONTEXT_ENV]: "{}" },
355 connected: true,
356 },
357 {
358 platform: "darwin",
359 outputs: {
360 "launchctl print": { code: 113 },
361 "launchctl print-disabled": {
362 code: 0,
363 stdout: '"com.t3tools.t3code.service" => disabled',
364 },
365 },
366 },
367 {
368 platform: "linux",
369 outputs: {
370 "systemctl is-active": { code: 3, stdout: "inactive\n" },
371 "systemctl is-enabled": { code: 1, stdout: "disabled\n" },
372 },
373 },
374 ] as const) {
375 const { result } = yield* startBesideBootService(fixture);
376 assert.equal(result._tag, "Success");
377 }
378 }).pipe(Effect.provide(NodeServices.layer)),
379 );
380​
381 it.effect("allows startup when the service configuration or manager is unavailable", () =>
382 Effect.gen(function* () {
383 for (const fixture of [
384 { outputs: {} },
385 {
386 outputs: {
387 "launchctl print": { code: 113 },
388 "launchctl print-disabled": { code: 1 },
389 },
390 },
391 { outputs: { "launchctl print": { code: 0 } }, missingServiceState: true },
392 ]) {
393 const { result } = yield* startBesideBootService({ platform: "darwin", ...fixture });
394 assert.equal(result._tag, "Success");
395 }
396 }).pipe(Effect.provide(NodeServices.layer)),
397 );
398 });
399});