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

DesktopWslServerTree.ts

226 lines8.9 KB

1import * as Context from "effect/Context";
2import * as Effect from "effect/Effect";
3import * as FileSystem from "effect/FileSystem";
4import * as Layer from "effect/Layer";
5import * as PlatformError from "effect/PlatformError";
6import * as Schema from "effect/Schema";
7import * as Semaphore from "effect/Semaphore";
8​
9import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
10​
11// Packaged Windows builds ship the server tree inside resources/server.asar
12// (see scripts/build-desktop-artifact.ts). The Windows primary reads it in
13// place through the asar-aware ELECTRON_RUN_AS_NODE runtime, but the WSL
14// backend launches plain `wsl.exe -- node`, which cannot read an asar
15// archive. This service materializes the archive into a real, version-keyed
16// directory the first time the WSL backend starts, and reuses it afterwards —
17// so only users who enable WSL ever pay for a loose copy of the server tree.
18//
19// Reading through Electron's patched fs also transparently returns the
20// contents of files that electron-builder/asar left in the server.asar.unpacked
21// sibling (native binaries), so a single walk of the archive yields the
22// complete tree.
23​
24export type WslServerTreeResult =
25 | { readonly ok: true; readonly root: string }
26 | { readonly ok: false; readonly reason: string; readonly fatal: boolean };
27​
28const MARKER_FILE_NAME = "t3code-wsl-server-tree.json";
29const COPY_CONCURRENCY = 8;
30​
31const Marker = Schema.Struct({ version: Schema.String });
32const decodeMarker = Schema.decodeUnknownEffect(Schema.fromJsonString(Marker));
33const encodeMarker = Schema.encodeEffect(Schema.fromJsonString(Marker));
34​
35export class DesktopWslServerTreeExtractError extends Schema.TaggedErrorClass<DesktopWslServerTreeExtractError>()(
36 "DesktopWslServerTreeExtractError",
37 {
38 targetDir: Schema.String,
39 cause: Schema.Defect(),
40 },
41) {
42 override get message(): string {
43 return `Failed to extract the WSL server tree to ${this.targetDir}.`;
44 }
46​
47export class DesktopWslServerTree extends Context.Service<
48 DesktopWslServerTree,
49 {
50 // Resolves the directory the WSL backend should treat as the app root
51 // (the directory containing apps/server/dist and node_modules). In dev
52 // the checkout already is that directory; packaged Windows builds extract
53 // server.asar on first use.
54 readonly ensure: Effect.Effect<WslServerTreeResult>;
55 }
56>()("@t3tools/desktop/wsl/DesktopWslServerTree") {}
57​
58// Child scheduling stays here instead of inside `visit`, so nested directories
59// cannot create independent concurrency pools. The LIFO work list also keeps
60// traversal memory proportional to the remaining frontier rather than the
61// number of active fibers.
62export const forEachBoundedTree = <Node, E, R>(
63 roots: ReadonlyArray<Node>,
64 visit: (node: Node) => Effect.Effect<ReadonlyArray<Node>, E, R>,
65): Effect.Effect<void, E, R> =>
66 Effect.gen(function* () {
67 const pending = [...roots];
68 while (pending.length > 0) {
69 const batch = pending.splice(-COPY_CONCURRENCY);
70 const children = yield* Effect.forEach(batch, visit, {
71 concurrency: COPY_CONCURRENCY,
72 });
73 for (const entries of children) {
74 pending.push(...entries);
75 }
76 }
77 });
78​
79interface CopyTreeEntry {
80 readonly sourcePath: string;
81 readonly targetPath: string;
83​
84// Copy using only operations supported by Electron's asar-patched fs. Symlinks
85// are not expected because the sidecar is installed with a hoisted, physical
86// layout; anything that is neither a file nor a directory is skipped.
87const copyTree = (
88 fs: FileSystem.FileSystem,
89 join: (first: string, ...rest: string[]) => string,
90 from: string,
91 to: string,
92): Effect.Effect<void, PlatformError.PlatformError> =>
93 forEachBoundedTree<CopyTreeEntry, PlatformError.PlatformError, never>(
94 [{ sourcePath: from, targetPath: to }],
95 ({ sourcePath, targetPath }) =>
96 Effect.gen(function* () {
97 const info = yield* fs.stat(sourcePath);
98 if (info.type === "Directory") {
99 yield* fs.makeDirectory(targetPath, { recursive: true });
100 const entries = yield* fs.readDirectory(sourcePath);
101 return entries.map((entry) => ({
102 sourcePath: join(sourcePath, entry),
103 targetPath: join(targetPath, entry),
104 }));
105 }
106 if (info.type === "File") {
107 // Read and write stay in the same bounded task, so at most eight file
108 // buffers can be retained while their writes complete.
109 const bytes = yield* fs.readFile(sourcePath);
110 yield* fs.writeFile(targetPath, bytes);
111 }
112 return [];
113 }),
114 );
115​
116export const make = Effect.gen(function* () {
117 const environment = yield* DesktopEnvironment.DesktopEnvironment;
118 const fs = yield* FileSystem.FileSystem;
119 const join = environment.path.join;
120​
121 const serverRoot = environment.serverRoot;
122 const needsExtraction = environment.isPackaged && environment.platform === "win32";
123 const treeRoot = join(environment.stateDir, "wsl-server-tree");
124 const version = environment.appVersion;
125 const versionDir = join(treeRoot, version);
126​
127 // Remove sibling trees left behind by previous app versions (and aborted
128 // extractions). Best-effort: a locked file must not block the backend.
129 const sweepStale = Effect.gen(function* () {
130 const entries = yield* fs.readDirectory(treeRoot).pipe(Effect.orElseSucceed(() => []));
131 yield* Effect.forEach(
132 entries.filter((entry) => entry !== version),
133 (entry) => fs.remove(join(treeRoot, entry), { recursive: true }).pipe(Effect.ignore),
134 { discard: true },
135 );
136 });
137​
138 const markerMatches = Effect.gen(function* () {
139 const raw = yield* fs.readFileString(join(versionDir, MARKER_FILE_NAME));
140 const marker = yield* decodeMarker(raw);
141 return marker.version === version;
142 }).pipe(Effect.orElseSucceed(() => false));
143​
144 const extract = Effect.gen(function* () {
145 yield* Effect.log(`[wsl-server-tree] Extracting ${serverRoot} to ${versionDir}...`);
146 yield* fs.makeDirectory(treeRoot, { recursive: true });
147 // Keep the temporary tree beside the target so rename is atomic. Cleanup
148 // is owned explicitly because a scoped temp-directory finalizer treats the
149 // successful rename (and therefore missing original path) as an error.
150 const partialDir = yield* fs.makeTempDirectory({
151 directory: treeRoot,
152 prefix: `.${version}.extract-`,
153 });
154 yield* Effect.gen(function* () {
155 yield* copyTree(fs, join, serverRoot, partialDir);
156 const markerJson = yield* encodeMarker({ version });
157 yield* fs.writeFileString(join(partialDir, MARKER_FILE_NAME), `${markerJson}\n`);
158 // The marker is written before the rename, so a directory named after
159 // the version is complete by construction.
160 yield* fs.remove(versionDir, { recursive: true }).pipe(Effect.ignore);
161 yield* fs.rename(partialDir, versionDir);
162 }).pipe(
163 Effect.ensuring(fs.remove(partialDir, { recursive: true, force: true }).pipe(Effect.ignore)),
164 );
165 yield* Effect.log(`[wsl-server-tree] Extraction complete at ${versionDir}.`);
166 }).pipe(
167 Effect.mapError(
168 (cause) => new DesktopWslServerTreeExtractError({ targetDir: versionDir, cause }),
169 ),
170 );
171​
172 // Serialize concurrent ensure calls (backend restarts can overlap): the
173 // first caller extracts, later callers see the marker and reuse the tree.
174 const gate = yield* Semaphore.make(1);
175​
176 const ensure: Effect.Effect<WslServerTreeResult> = gate
177 .withPermits(1)(
178 Effect.gen(function* () {
179 if (!needsExtraction) {
180 return { ok: true, root: serverRoot } as const;
181 }
182 if (yield* markerMatches) {
183 yield* sweepStale;
184 return { ok: true, root: versionDir } as const;
185 }
186 const result = yield* extract.pipe(
187 Effect.map(() => ({ ok: true, root: versionDir }) as const),
188 // Retryable: transient antivirus locks and slow disks are the common
189 // causes, and the backend manager already bounds preflight retries.
190 Effect.catch((error) =>
191 Effect.succeed({
192 ok: false,
193 reason: `WSL server files could not be extracted to ${versionDir}: ${
194 error.cause instanceof Error ? error.cause.message : String(error.cause)
195 }`,
196 fatal: false,
197 } as const),
198 ),
199 );
200 if (result.ok) {
201 yield* sweepStale;
202 }
203 return result;
204 }),
205 )
206 .pipe(Effect.withSpan("desktop.wslServerTree.ensure"));
207​
208 return DesktopWslServerTree.of({ ensure });
209});
210​
211export const layer = Layer.effect(DesktopWslServerTree, make);
212​
213export interface DesktopWslServerTreeTestStub {
214 readonly result?: WslServerTreeResult;
216​
217export const layerTest = (stub: DesktopWslServerTreeTestStub = {}) =>
218 Layer.effect(
219 DesktopWslServerTree,
220 Effect.gen(function* () {
221 const environment = yield* DesktopEnvironment.DesktopEnvironment;
222 return DesktopWslServerTree.of({
223 ensure: Effect.succeed(stub.result ?? { ok: true, root: environment.appRoot }),
224 });
225 }),
226 );