Open History to see the last commit
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 }
41}
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 = Effect.fn("DesktopWslServerTree.forEachBoundedTree")(function* <
52 Node,
53 E,
54 R,
55>(
56 roots: ReadonlyArray<Node>,
57 visit: (node: Node) => Effect.Effect<ReadonlyArray<Node>, E, R>,
58): Effect.fn.Return<void, E, R> {
59 const pending = [...roots];
60 while (pending.length > 0) {
61 const batch = pending.splice(-COPY_CONCURRENCY);
62 const children = yield* Effect.forEach(batch, visit, {
63 concurrency: COPY_CONCURRENCY,
64 });
65 for (const entries of children) {
66 pending.push(...entries);
67 }
68 }
69});
70
71interface CopyTreeEntry {
72 readonly sourcePath: string;
73 readonly targetPath: string;
74}
75
76const copyTree = (
77 fs: FileSystem.FileSystem,
78 join: (first: string, ...rest: string[]) => string,
79 from: string,
80 to: string,
81): Effect.Effect<void, PlatformError.PlatformError> =>
82 forEachBoundedTree<CopyTreeEntry, PlatformError.PlatformError, never>(
83 [{ sourcePath: from, targetPath: to }],
84 ({ sourcePath, targetPath }) =>
85 Effect.gen(function* () {
86 const info = yield* fs.stat(sourcePath);
87 if (info.type === "Directory") {
88 yield* fs.makeDirectory(targetPath, { recursive: true });
89 const entries = yield* fs.readDirectory(sourcePath);
90 return entries.map((entry) => ({
91 sourcePath: join(sourcePath, entry),
92 targetPath: join(targetPath, entry),
93 }));
94 }
95 if (info.type === "File") {
96 const bytes = yield* fs.readFile(sourcePath);
97 yield* fs.writeFile(targetPath, bytes);
98 }
99 return [];
100 }),
101 );
102
103/** @public Service construction is part of the canonical Effect module API. */
104export const make = Effect.gen(function* () {
105 const environment = yield* DesktopEnvironment.DesktopEnvironment;
106 const fs = yield* FileSystem.FileSystem;
107 const join = environment.path.join;
108
109 const serverRoot = environment.serverRoot;
110 const needsExtraction = environment.isPackaged && environment.platform === "win32";
111 const treeRoot = join(environment.stateDir, "wsl-server-tree");
112 const version = environment.appVersion;
113 const versionDir = join(treeRoot, version);
114
115 const sweepStale = Effect.gen(function* () {
116 const entries = yield* fs.readDirectory(treeRoot).pipe(Effect.orElseSucceed(() => []));
117 yield* Effect.forEach(
118 entries.filter((entry) => entry !== version),
119 (entry) => fs.remove(join(treeRoot, entry), { recursive: true }).pipe(Effect.ignore),
120 { discard: true },
121 );
122 });
123
124 const markerMatches = Effect.gen(function* () {
125 const raw = yield* fs.readFileString(join(versionDir, MARKER_FILE_NAME));
126 const marker = yield* decodeMarker(raw);
127 return marker.version === version;
128 }).pipe(Effect.orElseSucceed(() => false));
129
130 const extract = Effect.gen(function* () {
131 yield* Effect.log(`[wsl-server-tree] Extracting ${serverRoot} to ${versionDir}...`);
132 yield* fs.makeDirectory(treeRoot, { recursive: true });
133 // Keep the temporary tree beside the target so rename is atomic. Cleanup
134 // is owned explicitly because a scoped temp-directory finalizer treats the
135 // successful rename (and therefore missing original path) as an error.
136 const partialDir = yield* fs.makeTempDirectory({
137 directory: treeRoot,
138 prefix: `.${version}.extract-`,
139 });
140 yield* Effect.gen(function* () {
141 yield* copyTree(fs, join, serverRoot, partialDir);
142 const markerJson = yield* encodeMarker({ version });
143 yield* fs.writeFileString(join(partialDir, MARKER_FILE_NAME), `${markerJson}\n`);
144 yield* fs.remove(versionDir, { recursive: true }).pipe(Effect.ignore);
145 yield* fs.rename(partialDir, versionDir);
146 }).pipe(
147 Effect.ensuring(fs.remove(partialDir, { recursive: true, force: true }).pipe(Effect.ignore)),
148 );
149 yield* Effect.log(`[wsl-server-tree] Extraction complete at ${versionDir}.`);
150 }).pipe(
151 Effect.mapError(
152 (cause) => new DesktopWslServerTreeExtractError({ targetDir: versionDir, cause }),
153 ),
154 );
155
156 const gate = yield* Semaphore.make(1);
157
158 const cleanupLegacy = gate
159 .withPermits(1)(
160 needsExtraction
161 ? Effect.gen(function* () {
162 // Invalidate completeness before recursive deletion. Windows can
163 // remove part of a tree and then fail on a locked file; without
164 // this ordering, a surviving marker makes ensure reuse that
165 // half-deleted fallback instead of extracting it again.
166 yield* fs.remove(join(versionDir, MARKER_FILE_NAME), { force: true });
167 yield* fs.remove(treeRoot, { recursive: true, force: true });
168 }).pipe(
169 Effect.catch((cause) =>
170 Effect.logWarning("[wsl-server-tree] Could not remove the legacy extraction cache.", {
171 treeRoot,
172 cause,
173 }),
174 ),
175 )
176 : Effect.void,
177 )
178 .pipe(Effect.withSpan("desktop.wslServerTree.cleanupLegacy"));
179
180 const ensure: Effect.Effect<WslServerTreeResult> = gate
181 .withPermits(1)(
182 Effect.gen(function* () {
183 if (!needsExtraction) {
184 return { ok: true, root: serverRoot } as const;
185 }
186 if (yield* markerMatches) {
187 yield* sweepStale;
188 return { ok: true, root: versionDir } as const;
189 }
190 const result = yield* extract.pipe(
191 Effect.map(() => ({ ok: true, root: versionDir }) as const),
192 Effect.catch((error) =>
193 Effect.succeed({
194 ok: false,
195 reason: `WSL server files could not be extracted to ${versionDir}: ${
196 error.cause instanceof Error ? error.cause.message : String(error.cause)
197 }`,
198 fatal: false,
199 } as const),
200 ),
201 );
202 if (result.ok) {
203 yield* sweepStale;
204 }
205 return result;
206 }),
207 )
208 .pipe(Effect.withSpan("desktop.wslServerTree.ensure"));
209
210 return DesktopWslServerTree.of({ ensure, cleanupLegacy });
211});
212
213export const layer = Layer.effect(DesktopWslServerTree, make);
214
215export interface DesktopWslServerTreeTestStub {
216 readonly result?: WslServerTreeResult;
217 readonly cleanupLegacy?: Effect.Effect<void>;
218}
219
220export const layerTest = (stub: DesktopWslServerTreeTestStub = {}) =>
221 Layer.effect(
222 DesktopWslServerTree,
223 Effect.gen(function* () {
224 const environment = yield* DesktopEnvironment.DesktopEnvironment;
225 return DesktopWslServerTree.of({
226 ensure: Effect.succeed(stub.result ?? { ok: true, root: environment.appRoot }),
227 cleanupLegacy: stub.cleanupLegacy ?? Effect.void,
228 });
229 }),
230 );