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

watchDirectoryReplacements.test.ts

228 lines8.7 KB

1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { symlinksSupported } from "@t3tools/shared/testing/symlinks";
3import { assert, it } from "@effect/vitest";
4import * as Effect from "effect/Effect";
5import * as FileSystem from "effect/FileSystem";
6import * as Path from "effect/Path";
7import * as PlatformError from "effect/PlatformError";
8import * as Queue from "effect/Queue";
9import * as Stream from "effect/Stream";
10import * as TestClock from "effect/testing/TestClock";
11import { vi } from "vite-plus/test";
12​
13import { watchDirectoryPath } from "./watchDirectoryReplacements.ts";
14​
15// Watches under this root open but report only what a test sends, as a macOS watch can stay
16// silent before it is armed. Their paths resolve to themselves unless linked or missing.
17const silent = vi.hoisted(() => ({
18 root: "/silent-watch",
19 owns(path: unknown): path is string {
20 return (
21 typeof path === "string" &&
22 (path === this.root || path.startsWith(`${this.root}/`) || path.startsWith(`${this.root}\\`))
23 );
24 },
25 links: new Map<string, string>(),
26 missing: new Set<string>(),
27 listeners: new Map<string, (event: string, filename: string | null) => void>(),
28}));
29​
30vi.mock("node:fs", async (importOriginal) => {
31 const actual = await importOriginal<typeof import("node:fs")>();
32 const watch = (...args: Parameters<typeof actual.watch>) => {
33 const [path, listener] = args;
34 if (!silent.owns(path)) return actual.watch(...args);
35 const report = listener as (event: string, filename: string | null) => void;
36 silent.listeners.set(path, report);
37 return {
38 on: () => undefined,
39 close: () => silent.listeners.get(path) === report && silent.listeners.delete(path),
40 };
41 };
42 const native = (...args: Parameters<typeof actual.realpath.native>) => {
43 const [path, callback] = args;
44 if (!silent.owns(path)) return actual.realpath.native(...args);
45 if (silent.missing.has(path)) {
46 return callback(Object.assign(new Error(`ENOENT: ${path}`), { code: "ENOENT" }), "");
47 }
48 return callback(null, silent.links.get(path) ?? path);
49 };
50 return { ...actual, watch, realpath: Object.assign(actual.realpath.bind(undefined), { native }) };
51});
52​
53it.live.each(["linked", "plain"] as const)(
54 "backs off stopped watches for an unchanged %s directory",
55 (kind) =>
56 Effect.gen(function* () {
57 const fs = yield* FileSystem.FileSystem;
58 const path = yield* Path.Path;
59 const base = yield* fs.makeTempDirectoryScoped();
60 const entry = path.join(base, "linked");
61 const first = path.join(base, "first", "themes");
62 const second = path.join(base, "second", "themes");
63 yield* fs.makeDirectory(first, { recursive: true });
64 yield* fs.makeDirectory(second, { recursive: true });
65 if (kind === "linked" && !symlinksSupported) return;
66 yield* kind === "linked" ? fs.symlink(first, entry) : fs.makeDirectory(entry);
67 const firstIdentity = yield* fs.stat(first);
68 const secondIdentity = yield* fs.stat(second);
69 let identity = firstIdentity;
70 const events = yield* Queue.unbounded<"probe" | "refresh">();
71​
72 // An ended child emits a final refresh, as it does when registration fails.
73 yield* watchDirectoryPath(entry, Stream.succeed(undefined), Effect.succeed(false)).pipe(
74 Stream.runForEach(() => Queue.offer(events, "refresh")),
75 Effect.provideService(
76 FileSystem.FileSystem,
77 FileSystem.FileSystem.of({
78 ...fs,
79 stat: (file) =>
80 file === entry
81 ? Queue.offer(events, "probe").pipe(Effect.map(() => identity))
82 : fs.stat(file),
83 }),
84 ),
85 Effect.forkScoped,
86 );
87 assert.deepEqual(
88 yield* Queue.takeN(events, 10),
89 // Each acquire stats too: the first, a retry after 1 tick, then after 2 more.
90 [
91 "probe",
92 "probe",
93 "refresh",
94 "probe",
95 "probe",
96 "refresh",
97 "probe",
98 "probe",
99 "probe",
100 "refresh",
101 ],
102 );
103​
104 identity = secondIdentity;
105 assert.deepEqual(yield* Queue.takeN(events, 3), ["probe", "probe", "refresh"]);
106 }).pipe(Effect.provide(NodeServices.layer)),
107);
108​
109it.live.skipIf(!symlinksSupported)(
110 "rebuilds when a probe sees a tree other than the one the watches were acquired on",
111 () =>
112 Effect.gen(function* () {
113 const fs = yield* FileSystem.FileSystem;
114 const path = yield* Path.Path;
115 const base = yield* fs.makeTempDirectoryScoped();
116 const entry = path.join(base, "linked");
117 const first = path.join(base, "first");
118 const second = path.join(base, "second");
119 yield* fs.makeDirectory(first);
120 yield* fs.makeDirectory(second);
121 yield* fs.symlink(first, entry);
122 const a = yield* fs.stat(first);
123 const b = yield* fs.stat(second);
124 // Probe A, acquire A, probe B, swap back and acquire A, then B returns for the next probe.
125 const identities = [a, a, b, a, b, b];
126 const refreshes = yield* Queue.unbounded<void>();
127​
128 yield* watchDirectoryPath(
129 entry,
130 Stream.concat(Stream.succeed(undefined), Stream.never),
131 Effect.succeed(false),
132 ).pipe(
133 Stream.runForEach(() => Queue.offer(refreshes, undefined)),
134 Effect.provideService(
135 FileSystem.FileSystem,
136 FileSystem.FileSystem.of({
137 ...fs,
138 stat: (file) =>
139 file === entry ? Effect.sync(() => identities.shift() ?? b) : fs.stat(file),
140 }),
141 ),
142 Effect.forkScoped,
143 );
144 yield* Queue.takeN(refreshes, 3);
145 assert.deepEqual(identities, []);
146 }).pipe(Effect.provide(NodeServices.layer)),
147);
148​
149it.effect.each([
150 { name: "another directory", folder: "elsewhere", linkedStat: "other" },
151 { name: "a directory that is gone", folder: "gone", linkedStat: "missing" },
152] as const)(
153 "follows a directory replaced by a link to $name when its parent watch reports nothing",
154 ({ folder, linkedStat }) =>
155 Effect.gen(function* () {
156 const fs = yield* FileSystem.FileSystem;
157 const path = yield* Path.Path;
158 const plain = yield* fs.stat(yield* fs.makeTempDirectoryScoped());
159 const other = yield* fs.stat(yield* fs.makeTempDirectoryScoped());
160 silent.root = path.resolve("/silent-watch", folder);
161 const entry = path.join(silent.root, "userdata", "themes");
162 const target = path.join(silent.root, folder, "themes");
163 let linked = false;
164 const acquisitions = yield* Queue.unbounded<void>();
165 const fail = (method: string, _tag: "InvalidData" | "NotFound") =>
166 Effect.fail(
167 PlatformError.systemError({
168 _tag,
169 module: "FileSystem",
170 method,
171 pathOrDescriptor: entry,
172 }),
173 );
174 silent.links.clear();
175 silent.missing.clear();
176​
177 yield* watchDirectoryPath(
178 entry,
179 Stream.fromEffect(Effect.asVoid(Queue.offer(acquisitions, undefined))).pipe(
180 Stream.concat(Stream.never),
181 ),
182 Effect.succeed(false),
183 ).pipe(
184 Stream.runDrain,
185 Effect.provideService(
186 FileSystem.FileSystem,
187 FileSystem.FileSystem.of({
188 ...fs,
189 // The watcher reuses the effects it builds, so each run reads the fixture afresh.
190 readLink: (file) =>
191 silent.owns(file)
192 ? Effect.suspend(() =>
193 file === entry && linked
194 ? Effect.succeed(target)
195 : fail("readLink", "InvalidData"),
196 )
197 : fs.readLink(file),
198 stat: (file) =>
199 file !== entry
200 ? fs.stat(file)
201 : Effect.suspend(() =>
202 !linked
203 ? Effect.succeed(plain)
204 : linkedStat === "other"
205 ? Effect.succeed(other)
206 : fail("stat", "NotFound"),
207 ),
208 }),
209 ),
210 Effect.forkScoped,
211 );
212 yield* Queue.take(acquisitions);
213​
214 // Replaced by a link with no parent event: only the next probe can see it.
215 linked = true;
216 silent.links.set(entry, target);
217 if (linkedStat === "missing") silent.missing.add(entry);
218 yield* TestClock.adjust("1 second");
219 assert.equal(yield* Queue.size(acquisitions), 1);
220 yield* Queue.take(acquisitions);
221​
222 // The link target's parent is watched now: replacing the target rearms its contents.
223 const targetParent = silent.listeners.get(path.dirname(target));
224 assert.isDefined(targetParent);
225 targetParent("rename", path.basename(target));
226 yield* Queue.take(acquisitions);
227 }).pipe(Effect.provide(NodeServices.layer)),
228);