Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

watch: ensure watch mode detects deleted and re-added files #52879

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
56 changes: 51 additions & 5 deletions lib/internal/watch_mode/files_watcher.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,10 @@ const { TIMEOUT_MAX } = require('internal/timers');

const EventEmitter = require('events');
const { addAbortListener } = require('internal/events/abort_listener');
const { watch } = require('fs');
const { watch, existsSync } = require('fs');
const { fileURLToPath } = require('internal/url');
const { resolve, dirname } = require('path');
const { setTimeout } = require('timers');
const { setTimeout, clearTimeout, setInterval, clearInterval } = require('timers');

const supportsRecursiveWatching = process.platform === 'win32' ||
process.platform === 'darwin';
Expand All @@ -31,18 +31,28 @@ class FilesWatcher extends EventEmitter {
#depencencyOwners = new SafeMap();
#ownerDependencies = new SafeMap();
#debounce;
#renameInterval;
#renameTimeout;
#mode;
#signal;
#passthroughIPC = false;
#ipcHandlers = new SafeWeakMap();

constructor({ debounce = 200, mode = 'filter', signal } = kEmptyObject) {
constructor({
debounce = 200,
mode = 'filter',
renameInterval = 1000,
renameTimeout = 60_000,
signal,
} = kEmptyObject) {
super({ __proto__: null, captureRejections: true });

validateNumber(debounce, 'options.debounce', 0, TIMEOUT_MAX);
validateOneOf(mode, 'options.mode', ['filter', 'all']);
this.#debounce = debounce;
this.#mode = mode;
this.#renameInterval = renameInterval;
this.#renameTimeout = renameTimeout;
this.#signal = signal;
this.#passthroughIPC = Boolean(process.send);

Expand Down Expand Up @@ -79,7 +89,10 @@ class FilesWatcher extends EventEmitter {
watcher.handle.close();
}

#onChange(trigger) {
#onChange(eventType, trigger, recursive) {
if (eventType === 'rename' && !recursive) {
return this.#rewatch(trigger);
}
if (this.#debouncing.has(trigger)) {
return;
}
Expand All @@ -94,6 +107,39 @@ class FilesWatcher extends EventEmitter {
}, this.#debounce).unref();
}

// When a file is removed, wait for it to be re-added.
// Often this re-add is immediate - some editors (e.g., gedit) and some docker mount modes do this.
#rewatch(path) {
if (this.#isPathWatched(path)) {
this.#unwatch(this.#watchers.get(path));
this.#watchers.delete(path);
if (existsSync(path)) {
this.watchPath(path, false);
// This might be redundant. If the file was re-added due to a save event, we will probably see change -> rename.
// However, in certain situations it's entirely possible for the content to have changed after the rename
// In these situations we'd miss the change after the rename event
this.#onChange('change', path, false);
return;
}
let timeout;

// Wait for the file to exist - check every `renameInterval` ms
const interval = setInterval(async () => {
if (existsSync(path)) {
clearInterval(interval);
clearTimeout(timeout);
this.watchPath(path, false);
this.#onChange('change', path, false);
}
}, this.#renameInterval).unref();

// Don't wait forever - after `renameTimeout` ms, stop trying
timeout = setTimeout(() => {
clearInterval(interval);
}, this.#renameTimeout).unref();
}
}

get watchedPaths() {
return [...this.#watchers.keys()];
}
Expand All @@ -106,7 +152,7 @@ class FilesWatcher extends EventEmitter {
watcher.on('change', (eventType, fileName) => {
// `fileName` can be `null` if it cannot be determined. See
// https://github.com/nodejs/node/pull/49891#issuecomment-1744673430.
this.#onChange(recursive ? resolve(path, fileName ?? '') : path);
this.#onChange(eventType, recursive ? resolve(path, fileName) : path, recursive);
});
this.#watchers.set(path, { handle: watcher, recursive });
if (recursive) {
Expand Down
45 changes: 44 additions & 1 deletion test/parallel/test-watch-mode-files_watcher.mjs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// Flags: --expose-internals

Check failure on line 1 in test/parallel/test-watch-mode-files_watcher.mjs

View workflow job for this annotation

GitHub Actions / test-macOS

--- stdout --- ▶ watch mode file watcher ✔ should watch changed files (120.112459ms) ::debug::starting to run watch mode file watcher ::debug::starting to run should watch changed files ::debug::completed running should watch changed files ✔ should debounce changes (431.266459ms) ::debug::starting to run should debounce changes ::debug::completed running should debounce changes ✔ should ignore files in watched directory if they are not filtered (1004.641791ms) ::debug::starting to run should ignore files in watched directory if they are not filtered ::debug::completed running should ignore files in watched directory if they are not filtered ✔ should allow clearing filters (1124.795625ms) ::debug::starting to run should allow clearing filters ::debug::completed running should allow clearing filters ✔ should watch all files in watched path when in "all" mode (231.62325ms) ✔ should ruse existing watcher if it exists (0.831458ms) ✔ should ruse existing watcher of a parent directory (0.348375ms) ✔ should remove existing watcher if adding a parent directory watcher (0.826292ms) ::debug::starting to run should watch all files in watched path when in "all" mode ::debug::completed running should watch all files in watched path when in "all" mode ::debug::starting to run should ruse existing watcher if it exists ::debug::completed running should ruse existing watcher if it exists ::debug::starting to run should ruse existing watcher of a parent directory ::debug::completed running should ruse existing watcher of a parent directory ::debug::starting to run should remove existing watcher if adding a parent directory watcher ::debug::completed running should remove existing watcher if adding a parent directory watcher ✔ should clear all watchers when calling clear (0.263292ms) ::debug::starting to run should clear all watchers when calling clear ::debug::completed running should clear all watchers when calling clear ✔ should watch files from subprocess IPC events (34.164625ms) ::debug::starting to run should watch files from subprocess IPC events ::debug::completed running should watch files from subprocess IPC events Command: out/Release/node --expose-internals --test-reporter=spec --test-reporter-destination=stdout --test-reporter=./tools/github_reporter/index.js --test-reporter-destination=stdout /Users/runner/work/node/node/test/parallel/test-watch-mode-files_watcher.mjs --- TIMEOUT ---
import * as common from '../common/index.mjs';
import * as fixtures from '../common/fixtures.mjs';
import tmpdir from '../common/tmpdir.js';
Expand All @@ -6,7 +6,7 @@
import assert from 'node:assert';
import process from 'node:process';
import { describe, it, beforeEach, afterEach } from 'node:test';
import { writeFileSync, mkdirSync } from 'node:fs';
import { writeFileSync, mkdirSync, rmSync } from 'node:fs';
import { setTimeout } from 'node:timers/promises';
import { once } from 'node:events';
import { spawn } from 'node:child_process';
Expand Down Expand Up @@ -159,4 +159,47 @@
}
assert.deepStrictEqual(watcher.watchedPaths, expected);
});

it('should capture changes of a renamed file when re-written within the timeout', async () => {
watcher = new FilesWatcher({ debounce: 100, renameInterval: 100, renameTimeout: 400, mode: 'all' });
watcher.on('changed', () => changesCount++);

const file = tmpdir.resolve('file5');
writeFileSync(file, 'changed');
watcher.watchPath(file, false);

let changed = once(watcher, 'changed');
rmSync(file);
await setTimeout(200); // debounce * 2
await changed;
changed = once(watcher, 'changed');
writeFileSync(file, 'changed1');
await setTimeout(200); // debounce * 2
await changed;
changed = once(watcher, 'changed');
writeFileSync(file, 'changed1');
await setTimeout(200); // debounce * 2
await changed;
assert.strictEqual(changesCount, 3);
});

it('should NOT capture changes of a renamed file when re-written after the timeout', async () => {
watcher = new FilesWatcher({ debounce: 100, renameInterval: 200, renameTimeout: 100, mode: 'all' });
watcher.on('changed', () => changesCount++);

const file = tmpdir.resolve('file5');
writeFileSync(file, 'changed');
watcher.watchPath(file, false);

const changed = once(watcher, 'changed');

rmSync(file);
await setTimeout(200); // debounce * 2
await changed;
writeFileSync(file, 'changed1');
await setTimeout(5);
writeFileSync(file, 'changed2');
await setTimeout(5);
assert.strictEqual(changesCount, 1);
});
});
41 changes: 38 additions & 3 deletions test/sequential/test-watch-mode.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import path from 'node:path';
import { execPath } from 'node:process';
import { describe, it } from 'node:test';
import { spawn } from 'node:child_process';
import { writeFileSync, readFileSync, mkdirSync } from 'node:fs';
import { writeFileSync, readFileSync, mkdirSync, rmSync } from 'node:fs';
import { inspect } from 'node:util';
import { pathToFileURL } from 'node:url';
import { once } from 'node:events';
Expand Down Expand Up @@ -38,7 +38,8 @@ async function runWriteSucceed({
completed = 'Completed running',
restarts = 2,
options = {},
shouldFail = false
shouldFail = false,
restartFn = restart
}) {
args.unshift('--no-warnings');
if (watchFlag !== null) args.unshift(watchFlag);
Expand All @@ -64,7 +65,7 @@ async function runWriteSucceed({
break;
}
if (completes === 1) {
cancelRestarts = restart(watchedFile);
cancelRestarts = restartFn(watchedFile);
}
}

Expand Down Expand Up @@ -655,4 +656,38 @@ process.on('message', (message) => {
`Completed running ${inspect(file)}`,
]);
});

it('should watch changes to removed and readded files', async () => {
const file = createTmpFile();
let restartCount = 0;
const { stderr, stdout } = await runWriteSucceed({
file,
watchedFile: file,
watchFlag: '--watch=true',
options: {
timeout: 10000
},
restarts: 3,
restartFn(fileName) {
const content = readFileSync(fileName);
if (restartCount === 0) {
rmSync(fileName);
}
restartCount++;
return restart(fileName, content);
}
});

assert.strictEqual(stderr, '');
assert.deepStrictEqual(stdout, [
'running',
`Completed running ${inspect(file)}`,
`Restarting ${inspect(file)}`,
'running',
`Completed running ${inspect(file)}`,
`Restarting ${inspect(file)}`,
'running',
`Completed running ${inspect(file)}`,
]);
});
});