Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions packages/metro-file-map/src/Watcher.js
Original file line number Diff line number Diff line change
Expand Up @@ -329,6 +329,7 @@ export class Watcher extends EventEmitter {
MAX_WAIT_TIME,
);

watcher.onError(error => this.#reportBackendError(root, error));

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

watcher.onFileEvent(change => {
const basename = path.basename(change.relativePath);
if (basename.startsWith(this.#options.healthCheckFilePrefix)) {
Expand Down Expand Up @@ -410,6 +411,17 @@ export class Watcher extends EventEmitter {
}
}

#reportBackendError(root: Path, error: Error): void {
if (this.#closed) {
debug('Ignoring an error reported after close for %s: %s', root, error);
return;
}
this.#options.console.error(

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

`metro-file-map: The watcher of ${root} reported an error: ` +
error.message,
);
}

/**
* Watch a root in addition to those given at construction, reporting its
* changes to the `onChange` passed to `watch()`. Does nothing outside watch
Expand Down
64 changes: 61 additions & 3 deletions packages/metro-file-map/src/__tests__/Watcher-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import type {

import TreeFS from '../lib/TreeFS';
import {Watcher} from '../Watcher';
import EventEmitter from 'node:events';
import * as fs from 'node:fs';
import * as path from 'node:path';

Expand All @@ -39,14 +40,16 @@ type MockBackend = {
root: string,
clocks: ?Map<string, string>,
emit: (event: WatcherBackendChangeEvent) => void,
emitError: (error: Error) => void,
};
const mockStartedBackends: Array<MockBackend> = [];
let mockNativeLiveOnStart = true;
function mockBackendClass(kind: MockBackend['kind']) {
return class {
#root: string;
#clocks: ?Map<string, string>;
#listener: ?(event: WatcherBackendChangeEvent) => void;
// Like a real backend, an 'error' with no listener throws.
#emitter: EventEmitter = new EventEmitter();
static isSupported(): boolean {
return true;
}
Expand All @@ -58,14 +61,22 @@ function mockBackendClass(kind: MockBackend['kind']) {
this.#clocks = opts.clocks;
}
onFileEvent(listener: (event: WatcherBackendChangeEvent) => void) {
this.#listener = listener;
this.#emitter.on('fileevent', listener);
}
onError(listener: (error: Error) => void) {
this.#emitter.on('error', listener);
}
async startWatching() {
mockStartedBackends.push({
kind,
root: this.#root,
clocks: this.#clocks,
emit: event => this.#listener?.(event),
emit: event => {
this.#emitter.emit('fileevent', event);
},
emitError: error => {
this.#emitter.emit('error', error);
},
});
}
async stopWatching() {}
Expand Down Expand Up @@ -461,3 +472,50 @@ describe('Watcher crawl option', () => {
expect(mockNodeCrawl).not.toHaveBeenCalled();
});
});

describe('Watcher backend errors', () => {
const event: WatcherBackendChangeEvent = {
event: 'touch',
relativePath: 'index.js',
root: rootDir,
metadata: {modifiedTime: 1, size: 1, type: 'f'},
};

async function startWatching(
onChange: (change: WatcherBackendChangeEvent) => void,
): Promise<{watcher: Watcher, backend: MockBackend}> {
mockNodeCrawl.mockImplementation(async () => crawlResult([]));
const watcher = createWatcher(false, null, true);
await watcher.crawl();
await watcher.watch(onChange);
return {watcher, backend: mockStartedBackends[0]};
}

test('logs an error a backend reports, and keeps reporting changes', async () => {
const consoleError = jest
.spyOn(console, 'error')
.mockImplementation(() => {});
const onChange = jest.fn<[WatcherBackendChangeEvent], void>();
const {backend} = await startWatching(onChange);

backend.emitError(new Error('EACCES: permission denied'));
backend.emit(event);

expect(consoleError).toHaveBeenCalledWith(
expect.stringContaining('EACCES: permission denied'),
);
expect(onChange.mock.calls).toEqual([[event]]);
});

test('ignores an error a backend reports after close', async () => {
const consoleError = jest
.spyOn(console, 'error')
.mockImplementation(() => {});
const {watcher, backend} = await startWatching(() => {});

await watcher.close();
backend.emitError(new Error('late error'));

expect(consoleError).not.toHaveBeenCalled();
});
});
7 changes: 7 additions & 0 deletions packages/metro-file-map/src/watchers/AbstractWatcher.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ export class AbstractWatcher implements WatcherBackend {
readonly doIgnore: (path: string) => boolean;

#emitter: EventEmitter = new EventEmitter();
#stopped: boolean = false;

/**
* Whether a watch reports every change made after `startWatching` resolves.
Expand Down Expand Up @@ -73,6 +74,7 @@ export class AbstractWatcher implements WatcherBackend {
}

async stopWatching(): Promise<void> {
this.#stopped = true;
this.#emitter.removeAllListeners();

@vzaidman vzaidman Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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?

}

Expand All @@ -84,6 +86,11 @@ export class AbstractWatcher implements WatcherBackend {
}

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) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

return;
}
this.#emitter.emit('error', error);
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow strict-local
* @format
* @oncall react_native
*/

import {AbstractWatcher} from '../AbstractWatcher';
import {join} from 'node:path';

const options = {
included: null,
ignored: null,
watchmanDeferStates: [],
};

describe('AbstractWatcher errors', () => {
test('reports an error to its listeners while watching', async () => {
const watcher = new AbstractWatcher(join('/', 'project'), options);
const onError = jest.fn<[Error], void>();
watcher.onError(onError);
await watcher.startWatching();

const error = new Error('watch failed');
watcher.emitError(error);

expect(onError.mock.calls).toEqual([[error]]);
});

test('does not throw for an error reported after stopWatching', async () => {
const watcher = new AbstractWatcher(join('/', 'project'), options);
watcher.onError(() => {});
await watcher.startWatching();
await watcher.stopWatching();

expect(() => watcher.emitError(new Error('late error'))).not.toThrow();
});
});
Loading