返回源码地图

packages/env/src/watch.ts

v1.3.0 · 71023aec1546 · 21:断线重建与overflow

完整原文供逐行核对;页面收录不代表每行都经过人工语义审核。MIT 许可见 许可证。

1import type { Context } from "@earendil-works/chord";
2import { FileError, type FileWatcher, type WatchChange, type WatchTarget } from "@earendil-works/pi-durable/env";
3import { type Connection, isConnectionLost } from "./connection.ts";
4import { toFileError } from "./errors.ts";
5
6/** How the daemon watches, like `NodeExecutionEnv`'s `NodeWatchOptions`. */
7export interface RemoteWatchOptions {
8 /** Force a mode; by default Windows and file systems that do not report remote changes poll. */
9 mode?: "native" | "polling";
10 /** Interval between snapshots in `polling` mode; default 2000 ms. */
11 pollIntervalMs?: number;
12 /** Most directories one watcher covers; default 10,000. */
13 maxDirectories?: number;
14}
15
16const RECONNECT_FIRST_MS = 1000;
17const RECONNECT_MAX_MS = 30_000;
18
19/**
20 * A watcher running in the daemon (Durable's `NodeFileWatcher` next to the files). When the connection is lost, it is
21 * opened again once the connection can be started again, and reports `overflow`: changes in between were not seen.
22 */
23export class RemoteWatcher implements FileWatcher {
24 readonly #connection: Connection;
25 readonly #targets: readonly WatchTarget[];
26 readonly #onChange: (change: WatchChange) => void;
27 readonly #options: RemoteWatchOptions;
28 #mode: "native" | "polling" = "native";
29 #closed = false;
30 #controller: AbortController | undefined;
31 #request: Promise<void> | undefined;
32 #wake: (() => void) | undefined;
33
34 private constructor(
35 connection: Connection,
36 targets: readonly WatchTarget[],
37 onChange: (change: WatchChange) => void,
38 options: RemoteWatchOptions,
39 ) {
40 this.#connection = connection;
41 this.#targets = targets;
42 this.#onChange = onChange;
43 this.#options = options;
44 }
45
46 /** Watch `targets` (resolved paths); fails like `NodeFileWatcher.open` if coverage cannot be established. */
47 static async open(
48 connection: Connection,
49 targets: readonly WatchTarget[],
50 onChange: (change: WatchChange) => void,
51 options: RemoteWatchOptions = {},
52 ): Promise<RemoteWatcher> {
53 const watcher = new RemoteWatcher(connection, targets, onChange, options);
54 await watcher.#start();
55 return watcher;
56 }
57
58 get mode(): "native" | "polling" {
59 return this.#mode;
60 }
61
62 async close(_context: Context): Promise<void> {
63 if (this.#closed) return;
64 this.#closed = true;
65 this.#wake?.();
66 this.#controller?.abort();
67 await this.#request;
68 }
69
70 #deliver(change: WatchChange): void {
71 if (this.#closed) return;
72 try {
73 this.#onChange(change);
74 } catch {
75 // A throwing callback must not stop watching.
76 }
77 }
78
79 /** Open the daemon's watcher; resolves once it reports coverage. */
80 #start(): Promise<void> {
81 return new Promise((resolve, reject) => {
82 let ready = false;
83 const controller = new AbortController();
84 this.#controller = controller;
85 const request = this.#connection.request(
86 "watch",
87 {
88 targets: this.#targets.map((target) => ({
89 path: target.path,
90 recursive: target.recursive === true,
91 exclude: { hidden: target.exclude?.hidden === true, names: [...(target.exclude?.names ?? [])] },
92 })),
93 ...this.#options,
94 },
95 {
96 signal: controller.signal,
97 onEvent: (event) => {
98 if (event.kind === "ready") {
99 ready = true;
100 this.#mode = event.mode === "polling" ? "polling" : "native";
101 resolve();
102 } else if (event.kind === "change") {
103 if (event.mode === "polling") this.#mode = "polling";
104 if (event.overflow === true) this.#deliver({ overflow: true });
105 else this.#deliver({ paths: event.paths as string[] });
106 } else if (event.kind === "error") {
107 const code = event.code === "permission_denied" ? "permission_denied" : "invalid";
108 this.#deliver({ error: new FileError(code, String(event.message)) });
109 this.#closed = true;
110 }
111 },
112 },
113 );
114 this.#request = request.then(
115 () => {},
116 (error: unknown) => {
117 if (!ready) {
118 reject(error);
119 return;
120 }
121 if (this.#closed) return;
122 if (isConnectionLost(error)) {
123 void this.#reconnect();
124 return;
125 }
126 this.#deliver({ error: toFileError(error) });
127 this.#closed = true;
128 },
129 );
130 });
131 }
132
133 async #reconnect(): Promise<void> {
134 for (let delay = RECONNECT_FIRST_MS; !this.#closed; delay = Math.min(delay * 2, RECONNECT_MAX_MS)) {
135 await new Promise<void>((resolve) => {
136 const timer = setTimeout(resolve, delay);
137 timer.unref();
138 this.#wake = () => {
139 clearTimeout(timer);
140 resolve();
141 };
142 });
143 this.#wake = undefined;
144 if (this.#closed) return;
145 try {
146 await this.#start();
147 // Changes while disconnected were not seen.
148 this.#deliver({ overflow: true });
149 return;
150 } catch (error) {
151 if (isConnectionLost(error)) continue;
152 this.#deliver({ error: toFileError(error) });
153 this.#closed = true;
154 return;
155 }
156 }
157 }
158}