Repository navigation
metro-file-map: Don't exit when a watcher reports an error - #2151
ramya-2196 wants to merge 1 commit into
Conversation
Summary:
## Motivation
When a `metro-file-map` watcher backend reports an error, the Metro server exits.
### Example
Without Watchman, taking the permissions off a watched folder (`chmod 000 watched`) makes `FallbackWatcher` fail to `lstat` it, and the server dies with:
```
Error: EACCES: permission denied, lstat '…/watched/watched'
Emitted 'error' event at:
at FallbackWatcher.emitError (…/metro-file-map/src/watchers/AbstractWatcher.js:77:19)
```
`Watcher` subscribes each backend with `onFileEvent` only. A backend reports errors by emitting `'error'` on its own `EventEmitter`, and with no `'error'` listener Node throws, so any error a backend reports (from `FallbackWatcher`, `NativeWatcher`, or a Watchman client error) ends the process. `stopWatching()` removes every listener, so an error reported by work still in flight while a backend shuts down throws the same way.
Fixes react#2143
## The fix
- `Watcher` subscribes each backend's `onError` next to its `onFileEvent`, and logs the error to the file map's `console` with the watch root and the error's message. Watching continues. Errors reported after `close()` are ignored.
- `AbstractWatcher.emitError()` does nothing once `stopWatching()` has been called, so late errors from in-flight work no longer throw.
## More details
- The error is logged rather than re-emitted as an `'error'` event on `Watcher`, because a new event would crash the same way unless every consumer added a listener.
- Subscribing inside `createWatcherBackend` covers both the initial roots and roots added later with `watchRoot()`.
- The backends already call `emitError` only for errors they cannot handle themselves (for example, `FallbackWatcher` ignores `ENOENT`), so this doesn't add noise for routine file churn.
Changelog: [Fix] metro-file-map: An error reported by a file watcher backend, such as a watched folder becoming unreadable, is now logged instead of ending the Metro server
Differential Revision: D129077567
|
@ramya-2196 has exported this pull request. If you are a Meta employee, you can view the originating Diff in D129077567. |
Metro review: Needs discussionRisk: medium · Commit: Duplicate first: #2147 is also open for #2143 and also changes Findings
Verified
Not run: Windows and Linux weren't run; Automated review by Claude. Advisory only: it never approves or blocks, and a maintainer makes the call. |
| debug('Ignoring an error reported after close for %s: %s', root, error); | ||
| return; | ||
| } | ||
| this.#options.console.error( |
There was a problem hiding this comment.
should fix · Hitting the watch limit logs once per directory, then starts normally with those directories unwatched
FallbackWatcher.#watchdir catches each fs.watch failure, reports it and continues, and #reportBackendError logs every report. On Linux at the inotify limit, a project gets one console.error per remaining directory, and then watch() resolves as if all were well.
Each message only says the watcher reported an error. Nothing tells the user that changes in those directories won't be picked up, so they get stale bundles after startup output that scrolled past. On base, the same case ends the process with the ENOSPC error, which is blunt but can't be missed.
The description's "this doesn't add noise for routine file churn" is true of churn, but not of this case.
Suggested fix: report resource-limit errors (ENOSPC, EMFILE) once per root and code, and say that changes in unwatched directories will be missed, with a pointer to raising the limit or installing Watchman.
Reproduced: __repro__/enospc.js: a real FallbackWatcher on 1,000 directories, with fs.watch throwing ENOSPC after 100 calls. Head: watch() resolved; console.error calls: 901. Base: UNHANDLED REJECTION: ENOSPC..., exit 71. · id d489ba45
| MAX_WAIT_TIME, | ||
| ); | ||
|
|
||
| watcher.onError(error => this.#reportBackendError(root, error)); |
There was a problem hiding this comment.
should fix · A failed Watchman reconnect now leaves a permanently dead watcher behind one log line
WatchmanWatcher.#init reconnects once on end. If that connection fails, the error goes to emitError and nothing retries, because a failed connect never emits another end.
On base, this ended the process. With this subscription, Metro stays up and receives no more file events for that root for the rest of the session. That happens on any Watchman restart or upgrade where the socket isn't back in time for the single attempt. The log line doesn't say that changes are no longer being seen, and the health check that could expose it is opt-in.
Failure case: Watchman goes down, the reconnect gets ECONNREFUSED, and Watchman comes back. Metro makes no further attempts and keeps serving old code until restarted.
Suggested fix: retry with backoff in WatchmanWatcher. At a minimum, say in the message that watching has stopped. Watcher.js:348 rejects recrawl events under Watchman, so a recrawl on recovery would need more work.
Reproduced: __repro__/watchman.js reconnect (real fb-watchman client, fake in-process socket). Head: connection attempts after Watchman returned: 0 ; live connections: 0 ; errors logged: 1. Base: UNCAUGHT: connect ECONNREFUSED. · id 324c2660
| emitError(error: Error) { | ||
| // Work still in flight after stopWatching() can report an error, when | ||
| // nothing listens any more and emitting 'error' would throw. | ||
| if (this.#stopped) { |
There was a problem hiding this comment.
should fix · Late errors still throw when the Watchman client's connect is in flight at close
The description says late errors from in-flight work no longer throw, but this guard only covers the backend's own emitter. WatchmanWatcher.stopWatching calls removeAllListeners() on the fb-watchman client and then end(). The client's socket error handler re-emits on the client, which now has no error listener, so Node throws.
Failure case: Watchman drops, #init starts a reconnect, and close() runs before the connect fails (for example, Ctrl-C or a test teardown during a Watchman restart). The process dies with an uncaught connect error after close() has resolved.
The PR does fix a neighboring case. On base, the same sequence fails earlier, with an unhandled rejection of The client was ended.
Suggested fix: in stopWatching, leave a no-op error listener on the client after removing the others, and call end() after that. Add a WatchmanWatcher test for it.
Reproduced: __repro__/watchman.js late on head: closed, then UNCAUGHT: connect ECONNREFUSED. __repro__/realclient.js applies the same removeAllListeners() and end() to a real client with a real net socket: UNCAUGHT: connect ENOENT .../missing-socket. · id 9660d57d
| MAX_WAIT_TIME, | ||
| ); | ||
|
|
||
| watcher.onError(error => this.#reportBackendError(root, error)); |
There was a problem hiding this comment.
nit · NativeWatcher's own FSWatcher errors bypass this subscription and stay uncaught
The description names NativeWatcher among the backends that no longer end the process. That holds for errors it passes to emitError, such as the lstat path. But NativeWatcher.startWatching attaches no error listener to the FSWatcher it creates, unlike FallbackWatcher.js:216, so an error emitted on that object is still uncaught.
I couldn't trigger one with real filesystem operations on macOS, so this is a robustness gap and not a known user-facing crash. Forwarding it to emitError takes one line, because NativeWatcher.js already routes its other failures there.
Evidence: __repro__/native.js emit emits error on the captured FSWatcher, on head: UNCAUGHT: simulated FSWatcher failure. Real triggers produced no such error on head: rmroot gave a delete:root event, chmodsub gave recrawl:sub, and chmodroot went through emitError and was logged. · id ffffef3c
|
Please study #2147 and see if that fix is any better than yours. c.c @robhogan- there seems to be a problem fixed in slightly different ways here. |
|
Please link https://nodejs.org/api/events.html#error-events in the summary to help understand the issue |
|
|
||
| async stopWatching(): Promise<void> { | ||
| this.#stopped = true; | ||
| this.#emitter.removeAllListeners(); |
There was a problem hiding this comment.
maybe
this.#emitter.removeAllListeners();
this.#emitter.on('error', (err) => {
logger.warn('Error reported after close', err, /** other args? **/);
});
To keep the emitter from not having any listeners anymore?
|
Is there a way to prevent the error that is thrown after "stopListening" instead? So, to abort whatever throws the error? Even in that case, we probably wouldn't want the process to crash though. |
|
Closing this in favour of #2147, which fixes the same crash and also covers the follow-ups raised in review here (de-duplicating ENOSPC/EMFILE, Watchman reconnects and late client errors). Thanks @vzaidman for the pointer and the review. One gap that's still open in #2147 and that I hit while testing: NativeWatcher creates its recursive fs.watch handle without an 'error' listener (unlike FallbackWatcher), so an error emitted on that handle is still uncaught and ends the process. Forwarding it fixes it: It can be tested with the existing fs.watch mock in NativeWatcher-test.js by returning an EventEmitter as the handle and emitting 'error' on it. @sorinc03, happy to help there if useful. |
|
Thanks @ramya-2196, please mention this on #2147 itself |
Summary:
Motivation
When a
metro-file-mapwatcher backend reports an error, the Metro server exits.Example
Without Watchman, taking the permissions off a watched folder (
chmod 000 watched) makesFallbackWatcherfail tolstatit, and the server dies with:Watchersubscribes each backend withonFileEventonly. A backend reports errors by emitting'error'on its ownEventEmitter, and with no'error'listener Node throws, so any error a backend reports (fromFallbackWatcher,NativeWatcher, or a Watchman client error) ends the process.stopWatching()removes every listener, so an error reported by work still in flight while a backend shuts down throws the same way.Fixes #2143
The fix
Watchersubscribes each backend'sonErrornext to itsonFileEvent, and logs the error to the file map'sconsolewith the watch root and the error's message. Watching continues. Errors reported afterclose()are ignored.AbstractWatcher.emitError()does nothing oncestopWatching()has been called, so late errors from in-flight work no longer throw.More details
'error'event onWatcher, because a new event would crash the same way unless every consumer added a listener.createWatcherBackendcovers both the initial roots and roots added later withwatchRoot().emitErroronly for errors they cannot handle themselves (for example,FallbackWatcherignoresENOENT), so this doesn't add noise for routine file churn.Changelog: [Fix] metro-file-map: An error reported by a file watcher backend, such as a watched folder becoming unreadable, is now logged instead of ending the Metro server
Differential Revision: D129077567