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

DesktopWslServerTree.ts

227 lines8.4 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 archive.
15// Reading through Electron's patched fs also transparently returns the
16// contents of files that electron-builder/asar left in the server.asar.unpacked
17// sibling (native binaries), so a single walk of the archive yields the
18// complete tree.
19​
20export type WslServerTreeResult =
21 | { readonly ok: true; readonly root: string }
22 | { readonly ok: false; readonly reason: string; readonly fatal: boolean };
23​
24const MARKER_FILE_NAME = "t3code-wsl-server-tree.json";
25const COPY_CONCURRENCY = 8;
26​
27const Marker = Schema.Struct({ version: Schema.String });
28const decodeMarker = Schema.decodeUnknownEffect(Schema.fromJsonString(Marker));
29const encodeMarker = Schema.encodeEffect(Schema.fromJsonString(Marker));
30​
31export class DesktopWslServerTreeExtractError extends Schema.TaggedError<DesktopWslServerTreeExtractError>()(
32 "DesktopWslServerTreeExtractError",
33 {
34 targetDir: Schema.String,
35 cause: Schema.Defect(),
36 },
37) {
38 override get message(): string {
39 return `Failed to extract the WSL server tree to ${this.targetDir}.`;
40 }
42​
43export class DesktopWslServerTree extends Context.Service<
44 DesktopWslServerTree,
45 {
46 readonly ensure: Effect.Effect<WslServerTreeResult>;
47 readonly cleanupLegacy: Effect.Effect<void>;
48 }
49>()("@t3tools/desktop/wsl/DesktopWslServerTree") {}
50​
51export const forEachBoundedTree = <Node, E, R>(
52 roots: ReadonlyArray<Node>,
53 visit: (node: Node) => Effect.Effect<ReadonlyArray<Node>, E, R>,
54): Effect.Effect<void, E, R> =>
55 Effect.gen(function* () {
56 const pending = [...roots];
57 while (pending.length > 0) {
58 const batch = pending.splice(-COPY_CONCURRENCY);
59 const children = yield* Effect.forEach(batch, visit, {
60 concurrency: COPY_CONCURRENCY,
61 });
62 for (const entries of children) {
63 pending.push(...entries);
64 }
65 }
66 });
67​
68interface CopyTreeEntry {
69 readonly sourcePath: string;
70 readonly targetPath: string;
72​
73const copyTree = (
74 fs: FileSystem.FileSystem,
75 join: (first: string, ...rest: string[]) => string,
76 from: string,
77 to: string,
78): Effect.Effect<void, PlatformError.PlatformError> =>
79 forEachBoundedTree<CopyTreeEntry, PlatformError.PlatformError, never>(
80 [{ sourcePath: from, targetPath: to }],
81 ({ sourcePath, targetPath }) =>
82 Effect.gen(function* () {
83 const info = yield* fs.stat(sourcePath);
84 if (info.type === "Directory") {
85 yield* fs.makeDirectory(targetPath, { recursive: true });
86 const entries = yield* fs.readDirectory(sourcePath);
87 return entries.map((entry) => ({
88 sourcePath: join(sourcePath, entry),
89 targetPath: join(targetPath, entry),
90 }));
91 }
92 if (info.type === "File") {
93 const bytes = yield* fs.readFile(sourcePath);
94 yield* fs.writeFile(targetPath, bytes);
95 }
96 return [];
97 }),
98 );
99​
100/** @public Service construction is part of the canonical Effect module API. */
101export const make = Effect.gen(function* () {
102 const environment = yield* DesktopEnvironment.DesktopEnvironment;
103 const fs = yield* FileSystem.FileSystem;
104 const join = environment.path.join;
105​
106 const serverRoot = environment.serverRoot;
107 const needsExtraction = environment.isPackaged && environment.platform === "win32";
108 const treeRoot = join(environment.stateDir, "wsl-server-tree");
109 const version = environment.appVersion;
110 const versionDir = join(treeRoot, version);
111​
112 const sweepStale = Effect.gen(function* () {
113 const entries = yield* fs.readDirectory(treeRoot).pipe(Effect.orElseSucceed(() => []));
114 yield* Effect.forEach(
115 entries.filter((entry) => entry !== version),
116 (entry) => fs.remove(join(treeRoot, entry), { recursive: true }).pipe(Effect.ignore),
117 { discard: true },
118 );
119 });
120​
121 const markerMatches = Effect.gen(function* () {
122 const raw = yield* fs.readFileString(join(versionDir, MARKER_FILE_NAME));
123 const marker = yield* decodeMarker(raw);
124 return marker.version === version;
125 }).pipe(Effect.orElseSucceed(() => false));
126​
127 const extract = Effect.gen(function* () {
128 yield* Effect.log(`[wsl-server-tree] Extracting ${serverRoot} to ${versionDir}...`);
129 yield* fs.makeDirectory(treeRoot, { recursive: true });
130 // Keep the temporary tree beside the target so rename is atomic. Cleanup
131 // is owned explicitly because a scoped temp-directory finalizer treats the
132 // successful rename (and therefore missing original path) as an error.
133 const partialDir = yield* fs.makeTempDirectory({
134 directory: treeRoot,
135 prefix: `.${version}.extract-`,
136 });
137 yield* Effect.gen(function* () {
138 yield* copyTree(fs, join, serverRoot, partialDir);
139 const markerJson = yield* encodeMarker({ version });
140 yield* fs.writeFileString(join(partialDir, MARKER_FILE_NAME), `${markerJson}\n`);
141 yield* fs.remove(versionDir, { recursive: true }).pipe(Effect.ignore);
142 yield* fs.rename(partialDir, versionDir);
143 }).pipe(
144 Effect.ensuring(fs.remove(partialDir, { recursive: true, force: true }).pipe(Effect.ignore)),
145 );
146 yield* Effect.log(`[wsl-server-tree] Extraction complete at ${versionDir}.`);
147 }).pipe(
148 Effect.mapError(
149 (cause) => new DesktopWslServerTreeExtractError({ targetDir: versionDir, cause }),
150 ),
151 );
152​
153 const gate = yield* Semaphore.make(1);
154​
155 const cleanupLegacy = gate
156 .withPermits(1)(
157 needsExtraction
158 ? Effect.gen(function* () {
159 // Invalidate completeness before recursive deletion. Windows can
160 // remove part of a tree and then fail on a locked file; without
161 // this ordering, a surviving marker makes ensure reuse that
162 // half-deleted fallback instead of extracting it again.
163 yield* fs.remove(join(versionDir, MARKER_FILE_NAME), { force: true });
164 yield* fs.remove(treeRoot, { recursive: true, force: true });
165 }).pipe(
166 Effect.catch((cause) =>
167 Effect.logWarning("[wsl-server-tree] Could not remove the legacy extraction cache.", {
168 treeRoot,
169 cause,
170 }),
171 ),
172 )
173 : Effect.void,
174 )
175 .pipe(Effect.withSpan("desktop.wslServerTree.cleanupLegacy"));
176​
177 const ensure: Effect.Effect<WslServerTreeResult> = gate
178 .withPermits(1)(
179 Effect.gen(function* () {
180 if (!needsExtraction) {
181 return { ok: true, root: serverRoot } as const;
182 }
183 if (yield* markerMatches) {
184 yield* sweepStale;
185 return { ok: true, root: versionDir } as const;
186 }
187 const result = yield* extract.pipe(
188 Effect.map(() => ({ ok: true, root: versionDir }) as const),
189 Effect.catch((error) =>
190 Effect.succeed({
191 ok: false,
192 reason: `WSL server files could not be extracted to ${versionDir}: ${
193 error.cause instanceof Error ? error.cause.message : String(error.cause)
194 }`,
195 fatal: false,
196 } as const),
197 ),
198 );
199 if (result.ok) {
200 yield* sweepStale;
201 }
202 return result;
203 }),
204 )
205 .pipe(Effect.withSpan("desktop.wslServerTree.ensure"));
206​
207 return DesktopWslServerTree.of({ ensure, cleanupLegacy });
208});
209​
210export const layer = Layer.effect(DesktopWslServerTree, make);
211​
212export interface DesktopWslServerTreeTestStub {
213 readonly result?: WslServerTreeResult;
214 readonly cleanupLegacy?: Effect.Effect<void>;
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 cleanupLegacy: stub.cleanupLegacy ?? Effect.void,
225 });
226 }),
227 );