Open History to see the last commit
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 const link = yield* fs.readLink(entry).pipe(Effect.option);
110 if (Option.isNone(link)) return watchChild;
111
112 let childEnded = false;
113 const watchContents = Stream.suspend(() => {
114 childEnded = false;
115 return watchChild.pipe(
116 Stream.onEnd(
117 Effect.sync(() => {
118 childEnded = true;
119 }),
120 ),
121 );
122 });
123
124 // One stat per second for linked paths catches ancestor replacements the watches cannot see.
125 const identity = fs.stat(entry).pipe(
126 Effect.map(
127 (info) =>
128 `${info.dev}:${info.ino.valueOrUndefined}:${info.birthtime.valueOrUndefined?.getTime()}`,
129 ),
130 Effect.orElseSucceed(() => null),
131 );
132 // The identity of the tree the current watches were acquired on.
133 let previous: string | null | undefined;
134 return watchDirectoryReplacements(
135 (ready) => {
136 let retryDelay = 1;
137 let nextRetry = 0;
138 return Stream.tick("1 second").pipe(
139 Stream.mapEffect(() => identity),
140 Stream.zipWithIndex,
141 Stream.mapEffect(([current, tick]) =>
142 Effect.gen(function* () {
143 // A catalog read can see the path missing even if both probes see the same inode.
144 const sawMissing = current !== null && (yield* consumeMissingObservation);
145 const replaced = previous !== undefined && current !== previous;
146 const firstProbe = previous === undefined;
147 previous = current;
148
149 if (replaced || sawMissing || !childEnded) {
150 retryDelay = 1;
151 nextRetry = tick + 1;
152 }
153 if (firstProbe) return false;
154 if (replaced || sawMissing) return true;
155 if (!childEnded || current === null || tick < nextRetry) return false;
156
157 // A stable inode can stay unwatchable due to permissions or OS watch limits.
158 retryDelay = Math.min(60, retryDelay * 2);
159 nextRetry = tick + retryDelay;
160 return true;
161 }),
162 ),
163 Stream.tap(() => Deferred.succeed(ready, undefined)),
164 Stream.filter((rebuild) => rebuild),
165 );
166 },
167 Stream.unwrap(
168 // Probe before resolving so a tree swapped in between reads as a replacement.
169 identity.pipe(
170 Effect.tap((acquired) =>
171 Effect.sync(() => {
172 previous = acquired;
173 }),
174 ),
175 Effect.andThen(resolveLinkedPath(entry, link.value)),
176 Effect.map((target) => {
177 if (target === entry || target === NodePath.dirname(target)) return watchContents;
178 return watchDirectoryReplacements(
179 (ready) => watchDirectoryEntry(NodePath.dirname(target), ready),
180 watchDirectoryReplacements(
181 (ready) => watchDirectoryEntry(target, ready),
182 watchContents,
183 ),
184 );
185 }),
186 ),
187 ),
188 );
189 }),
190 ),
191 );
192};