Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off - Drive actual subprocesses and their file permissions.
2import * as NodeChildProcess from "node:child_process";
3import * as NodeCrypto from "node:crypto";
4import * as NodeFS from "node:fs";
5import * as NodeEvents from "node:events";
6import * as NodeFSP from "node:fs/promises";
7import * as NodeNet from "node:net";
8import * as NodeOS from "node:os";
9import * as NodePath from "node:path";
10import * as NodeProcess from "node:process";
11
12import { assert, describe, expect, it } from "@effect/vitest";
13
14import { make } from "./DesktopBackendRecovery.ts";
15import { linuxProcessIdentity } from "./LinuxProcessIdentity.ts";
16import { loadMacProcessAuditToken } from "./MacProcessAuditToken.ts";
17
18const loadNative = () =>
19 NodeProcess.platform === "darwin"
20 ? loadMacProcessAuditToken()
21 : Promise.resolve(linuxProcessIdentity);
22
23const childCode = `
24 import { createServer } from "node:net";
25 process.once("message", () => {
26 const listener = createServer();
27 listener.listen(0, "127.0.0.1", () => process.send(listener.address().port));
28 setTimeout(() => listener.close(), 30_000).unref();
29 });
30`;
31
32const launcherCode = `
33 import { spawn } from "node:child_process";
34 import { once } from "node:events";
35 import { unlink } from "node:fs/promises";
36 const [moduleUrl, appDataDirectory, stateDir, childCode] = process.argv.slice(1);
37 const { make } = await import(moduleUrl);
38 const recovery = make({
39 appDataDirectory,
40 stateDir,
41 launcherPid: process.pid,
42 onRecovery: () => {},
43 onError: (operation, error) => { throw new Error(operation, { cause: error }); },
44 });
45 const backend = spawn(process.execPath, ["--input-type=module", "-e", childCode], {
46 stdio: ["ignore", "ignore", "inherit", "ipc"],
47 detached: true,
48 });
49 await once(backend, "spawn");
50 const record = await recovery.track(backend.pid);
51 if (!record) throw new Error("Backend fixture was not recorded");
52 const listening = once(backend, "message");
53 backend.send("start");
54 const [port] = await listening;
55 process.send({ pid: backend.pid, port });
56 await once(backend, "exit");
57 await unlink(record);
58`;
59
60async function spawnTrackedBackend(
61 appDataDirectory: string,
62 stateDir: string,
63 cleanup: AsyncDisposableStack,
64 options: { readonly execPath?: string; readonly env?: NodeJS.ProcessEnv } = {},
65) {
66 const moduleUrl = new URL("./DesktopBackendRecovery.ts", import.meta.url).href;
67 const launcher = NodeChildProcess.spawn(
68 options.execPath ?? NodeProcess.execPath,
69 ["--input-type=module", "-e", launcherCode, moduleUrl, appDataDirectory, stateDir, childCode],
70 { stdio: ["ignore", "ignore", "inherit", "ipc"], env: options.env ?? NodeProcess.env },
71 );
72 const exited = NodeEvents.EventEmitter.once(launcher, "exit");
73 const stopLauncher = async () => {
74 launcher.kill("SIGKILL");
75 await exited;
76 };
77 cleanup.defer(stopLauncher);
78 const backend = await Promise.race([
79 NodeEvents.EventEmitter.once(launcher, "message").then(
80 ([message]) => message as { pid: number; port: number },
81 ),
82 exited.then(() => {
83 throw new Error("Fixture launcher exited before its backend was ready");
84 }),
85 ]);
86 const native = await loadNative();
87 const token = native.read(backend.pid);
88 assert.isDefined(token);
89 cleanup.defer(() => native.signal(token, "SIGKILL"));
90 return { ...backend, token, stopLauncher };
91}
92
93async function checkPortIsFree(port: number) {
94 const listener = NodeNet.createServer();
95 listener.listen(port, "127.0.0.1");
96 try {
97 await NodeEvents.EventEmitter.once(listener, "listening");
98 } finally {
99 await new Promise<void>((resolve) => listener.close(() => resolve()));
100 }
101}
102
103describe.runIf(NodeProcess.platform === "darwin" || NodeProcess.platform === "linux")(
104 "desktop backend recovery",
105 () => {
106 it.runIf(NodeProcess.platform === "darwin")(
107 "cleans up a truncated record only after the writer releases it",
108 async () => {
109 await using cleanup = new AsyncDisposableStack();
110 const stateDir = await NodeFSP.realpath(
111 await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "t3-record-")),
112 );
113 cleanup.defer(() => NodeFSP.rm(stateDir, { recursive: true, force: true }));
114 const directory = NodePath.join(stateDir, "t3code-backend-recovery");
115 await NodeFSP.mkdir(directory, { mode: 0o700 });
116 const scope = NodeCrypto.createHash("sha256")
117 .update(JSON.stringify([stateDir, await NodeFSP.realpath(NodeProcess.execPath)]))
118 .digest("hex");
119 const path = () => NodePath.join(directory, `${scope}.${NodeCrypto.randomUUID()}.json`);
120 const partial = path();
121 const future = path();
122 const unsafe = path();
123 await NodeFSP.writeFile(future, '{"version":2}', { mode: 0o600 });
124 await NodeFSP.writeFile(unsafe, "{", { mode: 0o600 });
125 await NodeFSP.chmod(unsafe, 0o644);
126 const errors: unknown[] = [];
127 const recovered: number[] = [];
128 const recovery = make({
129 appDataDirectory: stateDir,
130 stateDir,
131 launcherPid: NodeProcess.pid,
132 onRecovery: (pid) => recovered.push(pid),
133 onError: (_, error) => errors.push(error),
134 });
135 {
136 // Darwin O_EXLOCK keeps the record private to the writer until close or exit.
137 await using writer = await NodeFSP.open(
138 partial,
139 NodeFS.constants.O_WRONLY | NodeFS.constants.O_CREAT | NodeFS.constants.O_EXCL | 0x20,
140 0o600,
141 );
142 await writer.writeFile('{"version":');
143 await recovery.recover();
144 assert.equal(await NodeFSP.readFile(partial, "utf8"), '{"version":');
145 }
146 await recovery.recover();
147 await recovery.recover();
148 await expect(NodeFSP.stat(partial)).rejects.toMatchObject({ code: "ENOENT" });
149 assert.equal(await NodeFSP.readFile(future, "utf8"), '{"version":2}');
150 assert.equal(await NodeFSP.readFile(unsafe, "utf8"), "{");
151 assert.deepEqual(recovered, []);
152 assert.deepEqual(errors, []);
153 },
154 );
155
156 it("releases a frozen orphan's port and leaves a backend with a live launcher running", async () => {
157 await using cleanup = new AsyncDisposableStack();
158 const appDataDirectory = await NodeFSP.mkdtemp(
159 NodePath.join(NodeOS.tmpdir(), "t3-backend-recovery-"),
160 );
161 cleanup.defer(() => NodeFSP.rm(appDataDirectory, { recursive: true, force: true }));
162 // The first launcher records ownership before the home exists.
163 const stateDir = NodePath.join(appDataDirectory, "home", "userdata");
164 const orphan = await spawnTrackedBackend(appDataDirectory, stateDir, cleanup);
165 await NodeFSP.mkdir(stateDir, { recursive: true });
166 const live = await spawnTrackedBackend(appDataDirectory, stateDir, cleanup);
167 const native = await loadNative();
168 const recovered: number[] = [];
169 const errors: unknown[] = [];
170 const recovery = make({
171 appDataDirectory,
172 stateDir,
173 launcherPid: NodeProcess.pid,
174 onRecovery: (pid) => recovered.push(pid),
175 onError: (_, error) => errors.push(error),
176 });
177
178 NodeProcess.kill(orphan.pid, "SIGSTOP");
179 await orphan.stopLauncher();
180 await expect(checkPortIsFree(orphan.port)).rejects.toMatchObject({ code: "EADDRINUSE" });
181
182 const wrongVersion = Buffer.from(live.token, "hex");
183 wrongVersion[28] = wrongVersion[28]! ^ 1;
184 native.signal(wrongVersion.toString("hex"), "SIGKILL");
185 assert.equal(native.read(live.pid), live.token);
186
187 const otherHome = make({
188 appDataDirectory,
189 stateDir: NodePath.join(stateDir, "other"),
190 launcherPid: NodeProcess.pid,
191 onRecovery: (pid) => recovered.push(pid),
192 onError: (_, error) => errors.push(error),
193 });
194 await otherHome.recover();
195 assert.deepEqual(recovered, []);
196
197 const records = NodePath.join(appDataDirectory, "t3code-backend-recovery");
198 for (const name of await NodeFSP.readdir(records))
199 await NodeFSP.chmod(NodePath.join(records, name), 0o644);
200 await recovery.recover();
201 assert.deepEqual(recovered, []);
202 assert.equal(native.read(orphan.pid), orphan.token);
203 for (const name of await NodeFSP.readdir(records))
204 await NodeFSP.chmod(NodePath.join(records, name), 0o600);
205
206 await recovery.recover();
207 assert.deepEqual(errors, []);
208 assert.deepEqual(recovered, [orphan.pid]);
209 assert.isUndefined(native.read(orphan.pid));
210 await checkPortIsFree(orphan.port);
211 assert.equal(native.read(live.pid), live.token);
212 });
213
214 it.runIf(NodeProcess.platform === "linux")(
215 "recovers an AppImage orphan after a relaunch mounts the app at a new path",
216 async () => {
217 await using cleanup = new AsyncDisposableStack();
218 const appDataDirectory = await NodeFSP.realpath(
219 await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "t3-appimage-recovery-")),
220 );
221 cleanup.defer(() => NodeFSP.rm(appDataDirectory, { recursive: true, force: true }));
222 const stateDir = NodePath.join(appDataDirectory, "home");
223 const appImage = NodePath.join(appDataDirectory, "T3-Code.AppImage");
224 await NodeFSP.writeFile(appImage, "");
225 // The previous launch ran from another mount, so its executable path differs from ours.
226 const previousMount = NodePath.join(appDataDirectory, "mount-previous");
227 await NodeFSP.mkdir(previousMount);
228 const previousExecutable = NodePath.join(previousMount, "node");
229 await NodeFSP.link(NodeProcess.execPath, previousExecutable).catch(() =>
230 NodeFSP.copyFile(NodeProcess.execPath, previousExecutable),
231 );
232 const orphan = await spawnTrackedBackend(appDataDirectory, stateDir, cleanup, {
233 execPath: previousExecutable,
234 env: { ...NodeProcess.env, APPIMAGE: appImage },
235 });
236 const native = await loadNative();
237 NodeProcess.kill(orphan.pid, "SIGSTOP");
238 await orphan.stopLauncher();
239
240 const recovered: number[] = [];
241 const errors: unknown[] = [];
242 const previousAppImage = NodeProcess.env.APPIMAGE;
243 NodeProcess.env.APPIMAGE = appImage;
244 cleanup.defer(() => {
245 if (previousAppImage === undefined) delete NodeProcess.env.APPIMAGE;
246 else NodeProcess.env.APPIMAGE = previousAppImage;
247 });
248 await make({
249 appDataDirectory,
250 stateDir,
251 launcherPid: NodeProcess.pid,
252 onRecovery: (pid) => recovered.push(pid),
253 onError: (_, error) => errors.push(error),
254 }).recover();
255 assert.deepEqual(errors, []);
256 assert.deepEqual(recovered, [orphan.pid]);
257 assert.isUndefined(native.read(orphan.pid));
258 },
259 );
260 },
261);