diff --git a/packages/metro-file-map/src/Watcher.js b/packages/metro-file-map/src/Watcher.js index 797f79944c..9a469f3247 100644 --- a/packages/metro-file-map/src/Watcher.js +++ b/packages/metro-file-map/src/Watcher.js @@ -76,7 +76,6 @@ type WatcherOptions = { healthCheckFilePrefix: string, ignoreForCrawl: (filePath: string) => boolean, ignorePatternForWatch: RegExp, - previousState: CrawlerOptions['previousState'], perfLogger: ?PerfLogger, roots: ReadonlyArray, rootDir: string, @@ -107,6 +106,7 @@ export class Watcher extends EventEmitter { #nextHealthCheckId: number = 0; #onChange: ?(change: WatcherBackendChangeEvent) => void; readonly #options: WatcherOptions; + #prepared: ?Promise>; readonly #pendingHealthChecks: Map< /* basename */ string, /* resolve */ () => void, @@ -122,8 +122,20 @@ export class Watcher extends EventEmitter { this.#useWatchmanWatcher = options.useWatchman; } - async crawl(): Promise { - this.#options.perfLogger?.point('crawl_start'); + /** + * Start anything that must be running before the crawl begins, which in + * watch mode without Watchman is the backends, with their watches + * confirmed. crawl() waits for this, and calling it earlier lets other work, + * such as reading a cache, overlap with it. Resolves to the node crawl's + * watchers, if any. + */ + prepareCrawl(): Promise> { + this.#prepared ??= this.#prepareCrawl(); + return this.#prepared; + } + + async #prepareCrawl(): Promise> { + this.#options.perfLogger?.point('prepareCrawl_start'); const options = this.#options; // Non-Watchman backends have no clock to subscribe `since`, so they must @@ -148,10 +160,20 @@ export class Watcher extends EventEmitter { ); } } + this.#options.perfLogger?.point('prepareCrawl_end'); + return crawlWatchers; + } + + async crawl( + previousState: CrawlerOptions['previousState'], + ): Promise { + this.#options.perfLogger?.point('crawl_start'); + const options = this.#options; + const crawlWatchers = await this.prepareCrawl(); const result = await this.#crawl({ crawlWatchers, - previousState: options.previousState, + previousState, roots: options.roots, useWatchman: options.useWatchman, }); diff --git a/packages/metro-file-map/src/__tests__/Watcher-test.js b/packages/metro-file-map/src/__tests__/Watcher-test.js index 54dc67145b..791cf5914a 100644 --- a/packages/metro-file-map/src/__tests__/Watcher-test.js +++ b/packages/metro-file-map/src/__tests__/Watcher-test.js @@ -156,15 +156,6 @@ function createWatcher( ignoreForCrawl: () => false, ignorePatternForWatch: /^$/, perfLogger: null, - previousState: { - clocks: new Map(), - fileSystem: new TreeFS({ - processFile: () => { - throw new Error('not implemented'); - }, - rootDir, - }), - }, rootDir, roots: [rootDir], useWatchman, @@ -173,6 +164,18 @@ function createWatcher( }); } +function emptyState(): CrawlerOptions['previousState'] { + return { + clocks: new Map(), + fileSystem: new TreeFS({ + processFile: () => { + throw new Error('not implemented'); + }, + rootDir, + }), + }; +} + beforeEach(() => { mockStartedBackends.length = 0; mockNativeLiveOnStart = true; @@ -191,7 +194,7 @@ describe('Watcher crawl fallback', () => { const canonicalPath = path.join('src', 'index.js'); mockNodeCrawl.mockImplementation(async () => crawlResult([canonicalPath])); - const result = await createWatcher(false).crawl(); + const result = await createWatcher(false).crawl(emptyState()); expect([...result.changedFiles.keys()]).toEqual([canonicalPath]); expect(mockNodeCrawl).toHaveBeenCalledTimes(1); @@ -201,7 +204,7 @@ describe('Watcher crawl fallback', () => { test('a failing node crawler propagates, with no retry', async () => { mockNodeCrawl.mockImplementation(rejectWith('node crawl failed')); - await expect(createWatcher(false).crawl()).rejects.toThrow( + await expect(createWatcher(false).crawl(emptyState())).rejects.toThrow( 'node crawl failed', ); // The retry exists for Watchman only - retrying node with node is pointless. @@ -214,7 +217,7 @@ describe('Watcher crawl fallback', () => { crawlResult([canonicalPath]), ); - const result = await createWatcher(true).crawl(); + const result = await createWatcher(true).crawl(emptyState()); expect([...result.changedFiles.keys()]).toEqual([canonicalPath]); expect(mockWatchmanCrawl).toHaveBeenCalledTimes(1); @@ -226,7 +229,7 @@ describe('Watcher crawl fallback', () => { mockWatchmanCrawl.mockImplementation(rejectWith('watchman unavailable')); mockNodeCrawl.mockImplementation(async () => crawlResult([canonicalPath])); - const result = await createWatcher(true).crawl(); + const result = await createWatcher(true).crawl(emptyState()); expect([...result.changedFiles.keys()]).toEqual([canonicalPath]); expect(mockNodeCrawl).toHaveBeenCalledTimes(1); @@ -238,7 +241,7 @@ describe('Watcher crawl fallback', () => { mockNodeCrawl.mockImplementation(rejectWith('node crawl failed')); const thrown = await createWatcher(true) - .crawl() + .crawl(emptyState()) .then( () => null, (error: Error) => error, @@ -253,7 +256,7 @@ describe('Watcher crawl fallback', () => { mockWatchmanCrawl.mockImplementation(rejectWith('watchman unavailable')); mockNodeCrawl.mockImplementation(async () => crawlResult([])); - await createWatcher(true).crawl(); + await createWatcher(true).crawl(emptyState()); expect(mockNodeCrawl.mock.calls[0][0]).toBe( mockWatchmanCrawl.mock.calls[0][0], @@ -273,7 +276,7 @@ describe('Watcher backend choice in watch mode', () => { mockWatchmanCrawl.mockImplementation(async () => crawlResult([])); const watcher = createWatcher(true, null, true); - await watcher.crawl(); + await watcher.crawl(emptyState()); expect(mockStartedBackends).toEqual([]); await watcher.watch(() => {}); @@ -284,7 +287,7 @@ describe('Watcher backend choice in watch mode', () => { mockWatchmanCrawl.mockImplementation(async () => crawlResult([])); const watcher = createWatcher(true, null, true); - await watcher.crawl(); + await watcher.crawl(emptyState()); await watcher.watch(() => {}, new Map([['', 'c:crawl-clock:1']])); const addedRoot = path.join(path.sep, 'other'); await watcher.watchRoot(addedRoot); @@ -307,7 +310,7 @@ describe('Watcher backend choice in watch mode', () => { }); const watcher = createWatcher(true, null, true); - await watcher.crawl(); + await watcher.crawl(emptyState()); const onChange = jest.fn<[WatcherBackendChangeEvent], void>(); await watcher.watch(onChange); @@ -366,7 +369,7 @@ describe('Watcher with a backend that is not live on start', () => { const watcher = createWatcher(false, null, true); const warn = jest.spyOn(console, 'warn'); - await watcher.crawl(); + await watcher.crawl(emptyState()); // The first health check went unreported, the second was reported. expect(writesBeforeCrawl).toBe(2); @@ -386,7 +389,7 @@ describe('Watcher with a backend that is not live on start', () => { const watcher = createWatcher(false, null, true); const warn = jest.spyOn(console, 'warn'); - const crawled = watcher.crawl(); + const crawled = watcher.crawl(emptyState()); // $FlowFixMe[prop-missing] - in Jest 29.5+, missing from flow-typed's defs await jest.advanceTimersByTimeAsync(11000); await crawled; @@ -402,7 +405,7 @@ describe('Watcher with a backend that is not live on start', () => { test('confirms the watch of a root added later', async () => { mockNodeCrawl.mockImplementation(async () => crawlResult([])); const watcher = createWatcher(false, null, true); - await watcher.crawl(); + await watcher.crawl(emptyState()); await watcher.watch(() => {}); writtenFiles = []; @@ -412,12 +415,30 @@ describe('Watcher with a backend that is not live on start', () => { expect(writtenFiles.map(f => path.dirname(f))).toEqual([addedRoot]); }); + test('prepareCrawl() starts and confirms the watch, which the crawl then uses', async () => { + mockNodeCrawl.mockImplementation(async () => crawlResult([])); + const watcher = createWatcher(false, null, true); + + await watcher.prepareCrawl(); + + expect(mockStartedBackends.map(b => b.root)).toEqual([rootDir]); + expect(writtenFiles.map(f => path.dirname(f))).toEqual([rootDir]); + expect(mockNodeCrawl).not.toHaveBeenCalled(); + + await watcher.crawl(emptyState()); + + // Neither started nor confirmed again + expect(mockStartedBackends).toHaveLength(1); + expect(writtenFiles).toHaveLength(1); + expect(mockNodeCrawl).toHaveBeenCalledTimes(1); + }); + test('a backend that is live on start is not checked', async () => { mockNativeLiveOnStart = true; mockNodeCrawl.mockImplementation(async () => crawlResult([])); const watcher = createWatcher(false, null, true); - await watcher.crawl(); + await watcher.crawl(emptyState()); expect(writtenFiles).toEqual([]); }); @@ -441,7 +462,7 @@ describe('Watcher with FallbackWatcher and the node crawler', () => { }); const watcher = createWatcher(false, null, true); - await watcher.crawl(); + await watcher.crawl(emptyState()); expect(mockStartedBackends[0].crawledDirectories).toEqual([src]); }); @@ -449,7 +470,7 @@ describe('Watcher with FallbackWatcher and the node crawler', () => { test('a scoped recrawl is not reported to the watcher', async () => { mockNodeCrawl.mockImplementation(async () => crawlResult([])); const watcher = createWatcher(false, null, true); - await watcher.crawl(); + await watcher.crawl(emptyState()); mockNodeCrawl.mockClear(); await watcher.recrawl( @@ -468,7 +489,7 @@ describe('Watcher with FallbackWatcher and the node crawler', () => { test('with a custom crawler, the watcher walks the roots itself', async () => { const watcher = createWatcher(false, async () => crawlResult([]), true); - await watcher.crawl(); + await watcher.crawl(emptyState()); expect(mockStartedBackends.map(b => [b.kind, b.crawlFed])).toEqual([ ['fallback', false], @@ -488,7 +509,7 @@ describe('Watcher crawl option', () => { const result = await createWatcher( true, stubCrawler([canonicalPath]), - ).crawl(); + ).crawl(emptyState()); expect([...result.changedFiles.keys()]).toEqual([canonicalPath]); expect(mockWatchmanCrawl).not.toHaveBeenCalled(); @@ -500,7 +521,7 @@ describe('Watcher crawl option', () => { stubCrawler([]), ); - await createWatcher(true, crawl).crawl(); + await createWatcher(true, crawl).crawl(emptyState()); const options = crawl.mock.calls[0][0]; expect(options).toMatchObject({ @@ -543,9 +564,9 @@ describe('Watcher crawl option', () => { // what a supplied crawler exists to avoid. const crawl: Crawler = rejectWith('crawler exploded'); - await expect(createWatcher(true, crawl).crawl()).rejects.toThrow( - 'crawler exploded', - ); + await expect( + createWatcher(true, crawl).crawl(emptyState()), + ).rejects.toThrow('crawler exploded'); expect(mockNodeCrawl).not.toHaveBeenCalled(); }); }); diff --git a/packages/metro-file-map/src/__tests__/index-test.js b/packages/metro-file-map/src/__tests__/index-test.js index ec7a0d8c0d..92b264e4c3 100644 --- a/packages/metro-file-map/src/__tests__/index-test.js +++ b/packages/metro-file-map/src/__tests__/index-test.js @@ -1857,6 +1857,62 @@ describe('FileMap', () => { }, ); + test('starts watching while the cache is read', async () => { + let watchedRoots: ?Array = null; + mockNodeCrawler.mockImplementationOnce(async () => ({ + changedFiles: new Map(), + removedFiles: new Set(), + })); + mockCacheManager.read.mockImplementationOnce(async () => { + await new Promise(resolve => setTimeout(resolve, 10)); + watchedRoots = Object.keys(mockEmitters); + return null; + }); + + const {fileMap} = await buildNewFileMap({ + useWatchman: false, + watch: true, + }); + await fileMap.end(); + + expect(watchedRoots).toEqual([ + p('/project/fruits'), + p('/project/vegetables'), + ]); + }); + + test('end() while the cache is read stops the watch started meanwhile', async () => { + let finishRead: () => void = () => {}; + mockCacheManager.read.mockImplementationOnce( + () => + new Promise(resolve => { + finishRead = () => resolve(null); + }), + ); + const fileMap = new FileMap({ + ...defaultConfig, + plugins: [], + useWatchman: false, + watch: true, + }); + + const built = fileMap.build(); + await new Promise(resolve => setTimeout(resolve, 10)); + const backends = Object.values(mockEmitters); + expect(backends).toHaveLength(2); + const stops = backends.map(backend => + jest.spyOn(backend, 'stopWatching'), + ); + await fileMap.end(); + finishRead(); + + await expect(built).rejects.toMatchObject({name: 'AbortError'}); + for (const stop of stops) { + expect(stop).toHaveBeenCalled(); + } + expect(mockNodeCrawler).not.toHaveBeenCalled(); + }); + test('does not miss a change made while the file map is being built', async () => { mockNodeCrawler.mockImplementationOnce(async () => { // The watcher is already running at this point, so this reports a diff --git a/packages/metro-file-map/src/index.js b/packages/metro-file-map/src/index.js index fd22a8107f..05b5497e62 100644 --- a/packages/metro-file-map/src/index.js +++ b/packages/metro-file-map/src/index.js @@ -409,10 +409,12 @@ export default class FileMap extends EventEmitter { this.#startupPerfLogger?.point('build_start'); if (!this.#buildPromise) { this.#buildPromise = (async () => { - let initialData: ?CacheData; - if (this.#options.resetCache !== true) { - initialData = await this.read(); - } + // Creating and preparing the watcher doesn't depend on the cache, so + // it runs while the cache is read. + const [initialData] = await Promise.all([ + this.#options.resetCache !== true ? this.read() : null, + this.#createWatcher().then(watcher => watcher.prepareCrawl()), + ]); if (!initialData) { debug('Not using a cache'); } else { @@ -726,14 +728,7 @@ export default class FileMap extends EventEmitter { return data; } - /** - * 2. crawl the file system. - */ - async #buildFileDelta( - previousState: CrawlerOptions['previousState'], - ): Promise { - this.#startupPerfLogger?.point('buildFileDelta_start'); - + async #createWatcher(): Promise { const { computeSha1, enableSymlinks, @@ -763,7 +758,6 @@ export default class FileMap extends EventEmitter { }, ignorePatternForWatch: ignorePattern, perfLogger: this.#startupPerfLogger, - previousState, rootDir, roots, // A supplied crawler makes the Watchman capability probe - which spawns @@ -773,10 +767,20 @@ export default class FileMap extends EventEmitter { watchmanDeferStates, }); const watcher = this.#watcher; - watcher.on('status', status => this.emit('status', status)); + return watcher; + } - const result = await watcher.crawl(); + /** + * 2. crawl the file system. + */ + async #buildFileDelta( + previousState: CrawlerOptions['previousState'], + ): Promise { + this.#startupPerfLogger?.point('buildFileDelta_start'); + const watcher = this.#watcher; + invariant(watcher != null, 'Expected #createWatcher() to have been called'); + const result = await watcher.crawl(previousState); this.#startupPerfLogger?.point('buildFileDelta_end'); return result; }