|
| 1 | +import * as common from '../common/index.mjs'; |
| 2 | +import * as fixtures from '../common/fixtures.mjs'; |
| 3 | +import tmpdir from '../common/tmpdir.js'; |
| 4 | +import assert from 'node:assert'; |
| 5 | +import path from 'node:path'; |
| 6 | +import { execPath } from 'node:process'; |
| 7 | +import { describe, it } from 'node:test'; |
| 8 | +import { spawn } from 'node:child_process'; |
| 9 | +import { writeFileSync, readFileSync } from 'node:fs'; |
| 10 | +import { inspect } from 'node:util'; |
| 11 | +import { once } from 'node:events'; |
| 12 | +import { setTimeout } from 'node:timers/promises'; |
| 13 | +import { NodeInstance } from '../common/inspector-helper.js'; |
| 14 | + |
| 15 | + |
| 16 | +if (common.isIBMi) |
| 17 | + common.skip('IBMi does not support `fs.watch()`'); |
| 18 | + |
| 19 | +async function spawnWithRestarts({ |
| 20 | + args, |
| 21 | + file, |
| 22 | + restarts, |
| 23 | + startedPredicate, |
| 24 | + restartMethod, |
| 25 | +}) { |
| 26 | + args ??= [file]; |
| 27 | + const printedArgs = inspect(args.slice(args.indexOf(file)).join(' ')); |
| 28 | + startedPredicate ??= (data) => Boolean(data.match(new RegExp(`(Failed|Completed) running ${printedArgs.replace(/\\/g, '\\\\')}`, 'g'))?.length); |
| 29 | + restartMethod ??= () => writeFileSync(file, readFileSync(file)); |
| 30 | + |
| 31 | + let stderr = ''; |
| 32 | + let stdout = ''; |
| 33 | + let restartCount = 0; |
| 34 | + let completedStart = false; |
| 35 | + let finished = false; |
| 36 | + |
| 37 | + const child = spawn(execPath, ['--watch', '--no-warnings', ...args], { encoding: 'utf8' }); |
| 38 | + child.stderr.on('data', (data) => { |
| 39 | + stderr += data; |
| 40 | + }); |
| 41 | + child.stdout.on('data', async (data) => { |
| 42 | + if (finished) return; |
| 43 | + stdout += data; |
| 44 | + const restartMessages = stdout.match(new RegExp(`Restarting ${printedArgs.replace(/\\/g, '\\\\')}`, 'g'))?.length ?? 0; |
| 45 | + completedStart = completedStart || startedPredicate(data.toString()); |
| 46 | + if (restartMessages >= restarts && completedStart) { |
| 47 | + finished = true; |
| 48 | + child.kill(); |
| 49 | + return; |
| 50 | + } |
| 51 | + if (restartCount <= restartMessages && completedStart) { |
| 52 | + await setTimeout(restartCount > 0 ? 1000 : 50, { ref: false }); // Prevent throttling |
| 53 | + restartCount++; |
| 54 | + completedStart = false; |
| 55 | + restartMethod(); |
| 56 | + } |
| 57 | + }); |
| 58 | + |
| 59 | + await Promise.race([once(child, 'exit'), once(child, 'error')]); |
| 60 | + return { stderr, stdout }; |
| 61 | +} |
| 62 | + |
| 63 | +let tmpFiles = 0; |
| 64 | +function createTmpFile(content = 'console.log("running");') { |
| 65 | + const file = path.join(tmpdir.path, `${tmpFiles++}.js`); |
| 66 | + writeFileSync(file, content); |
| 67 | + return file; |
| 68 | +} |
| 69 | + |
| 70 | +function removeGraceMessage(stdout, file) { |
| 71 | + // Remove the message in case restart took long to avoid flakiness |
| 72 | + return stdout |
| 73 | + .replaceAll('Waiting for graceful termination...', '') |
| 74 | + .replaceAll(`Gracefully restarted ${inspect(file)}`, ''); |
| 75 | +} |
| 76 | + |
| 77 | +tmpdir.refresh(); |
| 78 | + |
| 79 | +// Warning: this suite can run safely with concurrency: true |
| 80 | +// only if tests do not watch/depend on the same files |
| 81 | +describe('watch mode', { concurrency: false, timeout: 60_0000 }, () => { |
| 82 | + it('should watch changes to a file - event loop ended', async () => { |
| 83 | + const file = createTmpFile(); |
| 84 | + const { stderr, stdout } = await spawnWithRestarts({ file, restarts: 1 }); |
| 85 | + |
| 86 | + assert.strictEqual(stderr, ''); |
| 87 | + assert.strictEqual(removeGraceMessage(stdout, file), [ |
| 88 | + 'running', `Completed running ${inspect(file)}`, `Restarting ${inspect(file)}`, |
| 89 | + 'running', `Completed running ${inspect(file)}`, '', |
| 90 | + ].join('\n')); |
| 91 | + }); |
| 92 | + |
| 93 | + it('should watch changes to a failing file', async () => { |
| 94 | + const file = fixtures.path('watch-mode/failing.js'); |
| 95 | + const { stderr, stdout } = await spawnWithRestarts({ file, restarts: 1 }); |
| 96 | + |
| 97 | + assert.match(stderr, /Error: fails\r?\n/); |
| 98 | + assert.strictEqual(stderr.match(/Error: fails\r?\n/g).length, 2); |
| 99 | + assert.strictEqual(removeGraceMessage(stdout, file), [`Failed running ${inspect(file)}`, `Restarting ${inspect(file)}`, |
| 100 | + `Failed running ${inspect(file)}`, ''].join('\n')); |
| 101 | + }); |
| 102 | + |
| 103 | + it('should not watch when running an non-existing file', async () => { |
| 104 | + const file = fixtures.path('watch-mode/non-existing.js'); |
| 105 | + const { stderr, stdout } = await spawnWithRestarts({ file, restarts: 0, restartMethod: () => {} }); |
| 106 | + |
| 107 | + assert.match(stderr, /code: 'MODULE_NOT_FOUND'/); |
| 108 | + assert.strictEqual(stdout, [`Failed running ${inspect(file)}`, ''].join('\n')); |
| 109 | + }); |
| 110 | + |
| 111 | + it('should watch when running an non-existing file - when specified under --watch-path', { |
| 112 | + skip: !common.isOSX && !common.isWindows |
| 113 | + }, async () => { |
| 114 | + const file = fixtures.path('watch-mode/subdir/non-existing.js'); |
| 115 | + const watched = fixtures.path('watch-mode/subdir/file.js'); |
| 116 | + const { stderr, stdout } = await spawnWithRestarts({ |
| 117 | + file, |
| 118 | + args: ['--watch-path', fixtures.path('./watch-mode/subdir/'), file], |
| 119 | + restarts: 1, |
| 120 | + restartMethod: () => writeFileSync(watched, readFileSync(watched)) |
| 121 | + }); |
| 122 | + |
| 123 | + assert.strictEqual(stderr, ''); |
| 124 | + assert.strictEqual(removeGraceMessage(stdout, file), [`Failed running ${inspect(file)}`, `Restarting ${inspect(file)}`, |
| 125 | + `Failed running ${inspect(file)}`, ''].join('\n')); |
| 126 | + }); |
| 127 | + |
| 128 | + it('should watch changes to a file - event loop blocked', async () => { |
| 129 | + const file = fixtures.path('watch-mode/infinite-loop.js'); |
| 130 | + const { stderr, stdout } = await spawnWithRestarts({ |
| 131 | + file, |
| 132 | + restarts: 2, |
| 133 | + startedPredicate: (data) => data.startsWith('running'), |
| 134 | + }); |
| 135 | + |
| 136 | + assert.strictEqual(stderr, ''); |
| 137 | + assert.strictEqual(removeGraceMessage(stdout, file), |
| 138 | + ['running', `Restarting ${inspect(file)}`, 'running', `Restarting ${inspect(file)}`, 'running', ''].join('\n')); |
| 139 | + }); |
| 140 | + |
| 141 | + it('should watch changes to dependencies - cjs', async () => { |
| 142 | + const file = fixtures.path('watch-mode/dependant.js'); |
| 143 | + const dependency = fixtures.path('watch-mode/dependency.js'); |
| 144 | + const { stderr, stdout } = await spawnWithRestarts({ |
| 145 | + file, |
| 146 | + restarts: 1, |
| 147 | + restartMethod: () => writeFileSync(dependency, readFileSync(dependency)), |
| 148 | + }); |
| 149 | + |
| 150 | + assert.strictEqual(stderr, ''); |
| 151 | + assert.strictEqual(removeGraceMessage(stdout, file), [ |
| 152 | + '{}', `Completed running ${inspect(file)}`, `Restarting ${inspect(file)}`, |
| 153 | + '{}', `Completed running ${inspect(file)}`, '', |
| 154 | + ].join('\n')); |
| 155 | + }); |
| 156 | + |
| 157 | + it('should watch changes to dependencies - esm', async () => { |
| 158 | + const file = fixtures.path('watch-mode/dependant.mjs'); |
| 159 | + const dependency = fixtures.path('watch-mode/dependency.mjs'); |
| 160 | + const { stderr, stdout } = await spawnWithRestarts({ |
| 161 | + file, |
| 162 | + restarts: 1, |
| 163 | + restartMethod: () => writeFileSync(dependency, readFileSync(dependency)), |
| 164 | + }); |
| 165 | + |
| 166 | + assert.strictEqual(stderr, ''); |
| 167 | + assert.strictEqual(removeGraceMessage(stdout, file), [ |
| 168 | + '{}', `Completed running ${inspect(file)}`, `Restarting ${inspect(file)}`, |
| 169 | + '{}', `Completed running ${inspect(file)}`, '', |
| 170 | + ].join('\n')); |
| 171 | + }); |
| 172 | + |
| 173 | + it('should restart multiple times', async () => { |
| 174 | + const file = createTmpFile(); |
| 175 | + const { stderr, stdout } = await spawnWithRestarts({ file, restarts: 3 }); |
| 176 | + |
| 177 | + assert.strictEqual(stderr, ''); |
| 178 | + assert.strictEqual(stdout.match(new RegExp(`Restarting ${inspect(file).replace(/\\/g, '\\\\')}`, 'g')).length, 3); |
| 179 | + }); |
| 180 | + |
| 181 | + it('should gracefully wait when restarting', { skip: common.isWindows }, async () => { |
| 182 | + const file = fixtures.path('watch-mode/graceful-sigterm.js'); |
| 183 | + const { stderr, stdout } = await spawnWithRestarts({ |
| 184 | + file, |
| 185 | + restarts: 1, |
| 186 | + startedPredicate: (data) => data.startsWith('running'), |
| 187 | + }); |
| 188 | + |
| 189 | + // This message appearing is very flaky depending on a race between the |
| 190 | + // inner process and the outer process. it is acceptable for the message not to appear |
| 191 | + // as long as the SIGTERM handler is respected. |
| 192 | + if (stdout.includes('Waiting for graceful termination...')) { |
| 193 | + assert.strictEqual(stdout, ['running', `Restarting ${inspect(file)}`, 'Waiting for graceful termination...', |
| 194 | + 'exiting gracefully', `Gracefully restarted ${inspect(file)}`, 'running', ''].join('\n')); |
| 195 | + } else { |
| 196 | + assert.strictEqual(stdout, ['running', `Restarting ${inspect(file)}`, 'exiting gracefully', 'running', ''].join('\n')); |
| 197 | + } |
| 198 | + assert.strictEqual(stderr, ''); |
| 199 | + }); |
| 200 | + |
| 201 | + it('should pass arguments to file', async () => { |
| 202 | + const file = fixtures.path('watch-mode/parse_args.js'); |
| 203 | + const random = Date.now().toString(); |
| 204 | + const args = [file, '--random', random]; |
| 205 | + const { stderr, stdout } = await spawnWithRestarts({ file, args, restarts: 1 }); |
| 206 | + |
| 207 | + assert.strictEqual(stderr, ''); |
| 208 | + assert.strictEqual(removeGraceMessage(stdout, args.join(' ')), [ |
| 209 | + random, `Completed running ${inspect(args.join(' '))}`, `Restarting ${inspect(args.join(' '))}`, |
| 210 | + random, `Completed running ${inspect(args.join(' '))}`, '', |
| 211 | + ].join('\n')); |
| 212 | + }); |
| 213 | + |
| 214 | + it('should not load --require modules in main process', async () => { |
| 215 | + const file = createTmpFile(''); |
| 216 | + const required = fixtures.path('watch-mode/process_exit.js'); |
| 217 | + const args = ['--require', required, file]; |
| 218 | + const { stderr, stdout } = await spawnWithRestarts({ file, args, restarts: 1 }); |
| 219 | + |
| 220 | + assert.strictEqual(stderr, ''); |
| 221 | + assert.strictEqual(removeGraceMessage(stdout, file), [ |
| 222 | + `Completed running ${inspect(file)}`, `Restarting ${inspect(file)}`, `Completed running ${inspect(file)}`, '', |
| 223 | + ].join('\n')); |
| 224 | + }); |
| 225 | + |
| 226 | + it('should not load --import modules in main process', async () => { |
| 227 | + const file = createTmpFile(''); |
| 228 | + const imported = fixtures.fileURL('watch-mode/process_exit.js'); |
| 229 | + const args = ['--import', imported, file]; |
| 230 | + const { stderr, stdout } = await spawnWithRestarts({ file, args, restarts: 1 }); |
| 231 | + |
| 232 | + assert.strictEqual(stderr, ''); |
| 233 | + assert.strictEqual(removeGraceMessage(stdout, file), [ |
| 234 | + `Completed running ${inspect(file)}`, `Restarting ${inspect(file)}`, `Completed running ${inspect(file)}`, '', |
| 235 | + ].join('\n')); |
| 236 | + }); |
| 237 | + |
| 238 | + describe('inspect', { |
| 239 | + skip: Boolean(process.config.variables.coverage || !process.features.inspector), |
| 240 | + }, () => { |
| 241 | + const silentLogger = { log: () => {}, error: () => {} }; |
| 242 | + async function getDebuggedPid(instance, waitForLog = true) { |
| 243 | + const session = await instance.connectInspectorSession(); |
| 244 | + await session.send({ method: 'Runtime.enable' }); |
| 245 | + if (waitForLog) { |
| 246 | + await session.waitForConsoleOutput('log', 'safe to debug now'); |
| 247 | + } |
| 248 | + const { value: innerPid } = (await session.send({ |
| 249 | + 'method': 'Runtime.evaluate', 'params': { 'expression': 'process.pid' } |
| 250 | + })).result; |
| 251 | + session.disconnect(); |
| 252 | + return innerPid; |
| 253 | + } |
| 254 | + |
| 255 | + it('should start debugger on inner process', async () => { |
| 256 | + const file = fixtures.path('watch-mode/inspect.js'); |
| 257 | + const instance = new NodeInstance(['--inspect=0', '--watch'], undefined, file, silentLogger); |
| 258 | + let stderr = ''; |
| 259 | + instance.on('stderr', (data) => { stderr += data; }); |
| 260 | + |
| 261 | + const pids = [instance.pid]; |
| 262 | + pids.push(await getDebuggedPid(instance)); |
| 263 | + instance.resetPort(); |
| 264 | + writeFileSync(file, readFileSync(file)); |
| 265 | + pids.push(await getDebuggedPid(instance)); |
| 266 | + |
| 267 | + await instance.kill(); |
| 268 | + |
| 269 | + // There should be 3 pids (one parent + 2 restarts). |
| 270 | + // Message about Debugger should only appear twice. |
| 271 | + assert.strictEqual(stderr.match(/Debugger listening on ws:\/\//g).length, 2); |
| 272 | + assert.strictEqual(new Set(pids).size, 3); |
| 273 | + }); |
| 274 | + |
| 275 | + it('should prevent attaching debugger with SIGUSR1 to outer process', { skip: common.isWindows }, async () => { |
| 276 | + const file = fixtures.path('watch-mode/inspect_with_signal.js'); |
| 277 | + const instance = new NodeInstance(['--inspect-port=0', '--watch'], undefined, file, silentLogger); |
| 278 | + let stderr = ''; |
| 279 | + instance.on('stderr', (data) => { stderr += data; }); |
| 280 | + |
| 281 | + const loggedPid = await new Promise((resolve) => { |
| 282 | + instance.on('stdout', (data) => { |
| 283 | + const matches = data.match(/pid is (\d+)/); |
| 284 | + if (matches) resolve(Number(matches[1])); |
| 285 | + }); |
| 286 | + }); |
| 287 | + |
| 288 | + |
| 289 | + process.kill(instance.pid, 'SIGUSR1'); |
| 290 | + process.kill(loggedPid, 'SIGUSR1'); |
| 291 | + const debuggedPid = await getDebuggedPid(instance, false); |
| 292 | + |
| 293 | + await instance.kill(); |
| 294 | + |
| 295 | + // Message about Debugger should only appear once in inner process. |
| 296 | + assert.strictEqual(stderr.match(/Debugger listening on ws:\/\//g).length, 1); |
| 297 | + assert.strictEqual(loggedPid, debuggedPid); |
| 298 | + }); |
| 299 | + }); |
| 300 | +}); |
0 commit comments