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

watchDirectoryReplacements.ts

209 lines8.1 KB

1// @effect-diagnostics nodeBuiltinImport:off - parent watches need native filename filtering and path resolution.
2import * as NodeFS from "node:fs";
3import * as NodePath from "node:path";
4​
5import { resolveSymlinkTarget } from "@t3tools/shared/symlink";
6import * as Cause from "effect/Cause";
7import * as Deferred from "effect/Deferred";
8import * as Effect from "effect/Effect";
9import * as FileSystem from "effect/FileSystem";
10import * as Option from "effect/Option";
11import * as Path from "effect/Path";
12import * as PlatformError from "effect/PlatformError";
13import * as Queue from "effect/Queue";
14import * as Stream from "effect/Stream";
15​
16/** Buffer parent events before opening the child watch so a replacement cannot strand it. */
17export const watchDirectoryReplacements = <R>(
18 watchParent: (ready: Deferred.Deferred<void>) => Stream.Stream<unknown, unknown>,
19 watchChild: Stream.Stream<void, never, R>,
20) =>
21 Stream.unwrap(
22 Effect.gen(function* () {
23 const ready = yield* Deferred.make<void>();
24 const replacements = yield* watchParent(ready).pipe(
25 Stream.ignoreCause({ log: true }),
26 Stream.ensuring(Deferred.succeed(ready, undefined)),
27 Stream.toQueue({ capacity: 1, strategy: "sliding" }),
28 );
29 yield* Deferred.await(ready);
30​
31 return Stream.make(watchChild).pipe(
32 Stream.concat(Stream.fromQueue(replacements).pipe(Stream.as(watchChild))),
33 Stream.switchMap((events) => events),
34 );
35 }),
36 );
37​
38const watchDirectoryEntry = (path: string, ready: Deferred.Deferred<void>) => {
39 const directory = NodePath.dirname(path);
40 const name = NodePath.basename(path);
41 const watchError = (cause: unknown) =>
42 PlatformError.systemError({
43 _tag: "Unknown",
44 module: "FileSystem",
45 method: "watch",
46 pathOrDescriptor: directory,
47 cause,
48 });
49 // Filter in the native callback to avoid queueing and statting unrelated entries.
50 return Stream.callback<void, PlatformError.PlatformError>(
51 (events) =>
52 Effect.acquireRelease(
53 Effect.try({
54 try: () => {
55 const watcher = NodeFS.watch(directory, (_, filename) => {
56 if (filename === name || filename === null) Queue.offerUnsafe(events, undefined);
57 });
58 watcher.on("error", (error) =>
59 Queue.failCauseUnsafe(events, Cause.fail(watchError(error))),
60 );
61 watcher.on("close", () => Queue.endUnsafe(events));
62 return watcher;
63 },
64 catch: watchError,
65 }),
66 (watcher) => Effect.sync(() => watcher.close()),
67 ).pipe(Effect.tap(() => Deferred.succeed(ready, undefined))),
68 { bufferSize: 1, strategy: "sliding" },
69 );
70};
71​
72// Node's JS realpath can collapse `..` before resolving a symlink in the preceding segment.
73const realPath = (entry: string) =>
74 Effect.callback<string, NodeJS.ErrnoException>((resume) => {
75 NodeFS.realpath.native(entry, (error, resolved) => {
76 resume(error ? Effect.fail(error) : Effect.succeed(resolved));
77 });
78 });
79​
80const resolveLinkedPath = Effect.fn("watchDirectoryReplacements.resolveLinkedPath")(function* (
81 entry: string,
82 link: string,
83) {
84 const path = yield* Path.Path;
85 const resolved = yield* realPath(entry).pipe(Effect.option);
86 if (Option.isSome(resolved)) return resolved.value;
87​
88 // A dangling link needs a watch on the directory where its target should appear.
89 const rawTarget = path.isAbsolute(link) ? link : `${path.dirname(entry)}${path.sep}${link}`;
90 const parent = yield* realPath(path.dirname(rawTarget)).pipe(Effect.option);
91 if (Option.isNone(parent)) return entry;
92​
93 const unresolved = path.join(parent.value, path.basename(rawTarget));
94 return yield* resolveSymlinkTarget(unresolved).pipe(Effect.orElseSucceed(() => unresolved));
95});
96​
97/** Watch replacements of a configured directory and nearby ancestors of its symlink target. */
98export const watchDirectoryPath = (
99 directory: string,
100 watchChild: Stream.Stream<void>,
101 consumeMissingObservation: Effect.Effect<boolean>,
102) => {
103 const entry = NodePath.resolve(directory);
104 return watchDirectoryReplacements(
105 (ready) => watchDirectoryEntry(entry, ready),
106 Stream.unwrap(
107 Effect.gen(function* () {
108 const fs = yield* FileSystem.FileSystem;
109 let childEnded = false;
110 const watchContents = Stream.suspend(() => {
111 childEnded = false;
112 return watchChild.pipe(
113 Stream.onEnd(
114 Effect.sync(() => {
115 childEnded = true;
116 }),
117 ),
118 );
119 });
120​
121 const statIdentity = fs
122 .stat(entry)
123 .pipe(
124 Effect.map(
125 (info) =>
126 `${info.dev}:${info.ino.valueOrUndefined}:${info.birthtime.valueOrUndefined?.getTime()}`,
127 ),
128 );
129 // One probe per second catches replacements the watches cannot see: a link target's
130 // ancestors, or the entry becoming a link before macOS has armed the parent watch.
131 // A missing entry probes as null and a link whose target is missing as "".
132 const identity = fs.readLink(entry).pipe(
133 Effect.matchEffect({
134 onSuccess: (link) =>
135 statIdentity.pipe(
136 Effect.map((id) => `link:${id}:${link}`),
137 Effect.orElseSucceed(() => ""),
138 ),
139 onFailure: () =>
140 statIdentity.pipe(
141 Effect.map((id) => `plain:${id}`),
142 Effect.orElseSucceed(() => null),
143 ),
144 }),
145 );
146 // The identity of the tree the current watches were acquired on.
147 let previous: string | null | undefined;
148 return watchDirectoryReplacements(
149 (ready) => {
150 let retryDelay = 1;
151 let nextRetry = 0;
152 return Stream.tick("1 second").pipe(
153 Stream.mapEffect(() => identity),
154 Stream.zipWithIndex,
155 Stream.mapEffect(([current, tick]) =>
156 Effect.gen(function* () {
157 // A catalog read can see the path missing even if both probes see the same inode.
158 const sawMissing = Boolean(current) && (yield* consumeMissingObservation);
159 const replaced = previous !== undefined && current !== previous;
160 const firstProbe = previous === undefined;
161 previous = current;
162​
163 if (replaced || sawMissing || !childEnded) {
164 retryDelay = 1;
165 nextRetry = tick + 1;
166 }
167 if (firstProbe) return false;
168 if (replaced || sawMissing) return true;
169 if (!childEnded || !current || tick < nextRetry) return false;
170​
171 // A stable inode can stay unwatchable due to permissions or OS watch limits.
172 retryDelay = Math.min(60, retryDelay * 2);
173 nextRetry = tick + retryDelay;
174 return true;
175 }),
176 ),
177 Stream.tap(() => Deferred.succeed(ready, undefined)),
178 Stream.filter((rebuild) => rebuild),
179 );
180 },
181 Stream.unwrap(
182 // Probe before resolving so a tree swapped in between reads as a replacement.
183 identity.pipe(
184 Effect.tap((acquired) =>
185 Effect.sync(() => {
186 previous = acquired;
187 }),
188 ),
189 Effect.andThen(fs.readLink(entry).pipe(Effect.option)),
190 Effect.flatMap((link) =>
191 Option.isSome(link) ? resolveLinkedPath(entry, link.value) : Effect.succeed(entry),
192 ),
193 Effect.map((target) => {
194 if (target === entry || target === NodePath.dirname(target)) return watchContents;
195 return watchDirectoryReplacements(
196 (ready) => watchDirectoryEntry(NodePath.dirname(target), ready),
197 watchDirectoryReplacements(
198 (ready) => watchDirectoryEntry(target, ready),
199 watchContents,
200 ),
201 );
202 }),
203 ),
204 ),
205 );
206 }),
207 ),
208 );
209};