Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 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
32 changes: 27 additions & 5 deletions packages/nuxt-cli/src/dev/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import type { NuxtDevContext, NuxtDevIPCMessage, NuxtParentIPCMessage } from './
import process from 'node:process'
import defu from 'defu'
import { overrideEnv } from '../utils/env.ts'
import { isBrokenPipe } from '../utils/errors'
import { isAbortedConnection, isBrokenPipe } from '../utils/errors'
import { debug } from '../utils/logger'
import { startCpuProfile, stopCpuProfile } from '../utils/profile.ts'
import { openInspector } from './inspect'
Expand All @@ -18,6 +18,22 @@ function formatErrorMessage(error: unknown): string {
return error instanceof Error ? error.toString() : 'Unhandled Rejection'
}

/**
* Hand an unhandled rejection to the parent process and stop this one, unless
* it is only a client that went away — that is traffic, not a crash, and the
* session has to survive it.
*/
export function createRejectionHandler(report: (message: string) => void, stop: () => void): (reason: unknown) => void {
return (reason: unknown) => {
if (isAbortedConnection(reason)) {
debug('Ignoring aborted connection:', reason)
return
}
report(formatErrorMessage(reason))
stop()
}
}

interface InitializeOptions {
data?: {
overrides?: NuxtConfig
Expand All @@ -37,10 +53,12 @@ class IPC {
process.once('disconnect', () => {
process.exit(0)
})
process.once('unhandledRejection', (reason) => {
this.send({ type: 'nuxt:internal:dev:rejection', message: formatErrorMessage(reason) })
process.exit()
})
// `on` rather than `once`, so that an ignored connection error does not
// consume the listener and leave a later genuine rejection unreported.
process.on('unhandledRejection', createRejectionHandler(
message => this.send({ type: 'nuxt:internal:dev:rejection', message }),
() => process.exit(),
))
}
process.on('message', async (message: NuxtParentIPCMessage) => {
if (message.type === 'nuxt:internal:dev:context') {
Expand Down Expand Up @@ -223,6 +241,10 @@ export function createRestartHook(source: RestartSource): (callback: (reason?: D
debug('Ignoring broken pipe:', error)
return
}
if (isAbortedConnection(error)) {
debug('Ignoring aborted connection:', error)
return
}
restart({ type: 'error', message: formatErrorMessage(error) })
}

Expand Down
12 changes: 12 additions & 0 deletions packages/nuxt-cli/src/utils/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,15 @@ export function isBrokenPipe(error: unknown): boolean {
const code = (error as NodeJS.ErrnoException | undefined)?.code
return code === 'EPIPE' || code === 'ERR_STREAM_DESTROYED'
}

/**
* A client hanging up mid-request is normal traffic for a dev server: a browser
* reloading while a page is still streaming, a proxied websocket dropped when a
* worker is replaced, or a tab closed mid-navigation. Like a broken pipe, this
* says something about the other end of the connection rather than about this
* process, so it must not be treated as a crash or trigger a restart.
*/
export function isAbortedConnection(error: unknown): boolean {
const code = (error as NodeJS.ErrnoException | undefined)?.code
return code === 'ECONNRESET' || code === 'ECONNABORTED' || code === 'ERR_STREAM_PREMATURE_CLOSE'
}
16 changes: 15 additions & 1 deletion packages/nuxt-cli/test/unit/errors.spec.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { describe, expect, it } from 'vitest'

import { stripCwd } from '../../src/dev/error'
import { isBrokenPipe } from '../../src/utils/errors'
import { isAbortedConnection, isBrokenPipe } from '../../src/utils/errors'

describe('isBrokenPipe', () => {
it('should detect closed pipes', () => {
Expand All @@ -16,6 +16,20 @@ describe('isBrokenPipe', () => {
})
})

describe('isAbortedConnection', () => {
it('should detect connections dropped by the other end', () => {
expect(isAbortedConnection(Object.assign(new Error('read ECONNRESET'), { code: 'ECONNRESET' }))).toBe(true)
expect(isAbortedConnection(Object.assign(new Error('aborted'), { code: 'ECONNABORTED' }))).toBe(true)
expect(isAbortedConnection(Object.assign(new Error('premature close'), { code: 'ERR_STREAM_PREMATURE_CLOSE' }))).toBe(true)
})

it('should ignore other errors', () => {
expect(isAbortedConnection(new Error('boom'))).toBe(false)
expect(isAbortedConnection(Object.assign(new Error('nope'), { code: 'EADDRINUSE' }))).toBe(false)
expect(isAbortedConnection(undefined)).toBe(false)
})
})

describe('stripCwd', () => {
it('should strip posix working directories', () => {
expect(stripCwd('at /home/me/app/pages/index.vue:3:1', '/home/me/app')).toBe('at ./pages/index.vue:3:1')
Expand Down
39 changes: 37 additions & 2 deletions packages/nuxt-cli/test/unit/restart-hook.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import process from 'node:process'

import { afterEach, describe, expect, it, vi } from 'vitest'

import { createRestartHook } from '../../src/dev'
import { createRejectionHandler, createRestartHook } from '../../src/dev'

const ERROR_EVENTS = ['uncaughtException', 'unhandledRejection'] as const

Expand Down Expand Up @@ -48,7 +48,7 @@ describe('restart hook', () => {
expect(callback).toHaveBeenCalledExactlyOnceWith({ type: 'shortcut' })
})

it('should restart on an error that is not a broken pipe', () => {
it('should restart on an error that is not a broken pipe or an aborted connection', () => {
const source = new EventEmitter()
const callback = vi.fn()
arm(source, callback)
Expand All @@ -57,6 +57,9 @@ describe('restart hook', () => {
onError!(Object.assign(new Error('write EPIPE'), { code: 'EPIPE' }))
expect(callback).not.toHaveBeenCalled()

onError!(Object.assign(new Error('read ECONNRESET'), { code: 'ECONNRESET' }))
expect(callback).not.toHaveBeenCalled()

onError!(new Error('boom'))
expect(callback).toHaveBeenCalledWith({ type: 'error', message: expect.stringContaining('boom') })
})
Expand Down Expand Up @@ -106,3 +109,35 @@ describe('restart hook', () => {
expect(second).toHaveBeenCalledTimes(1)
})
})

describe('rejection handler', () => {
it('should report the rejection and stop', () => {
const report = vi.fn()
const stop = vi.fn()

createRejectionHandler(report, stop)(new Error('boom'))

expect(report).toHaveBeenCalledExactlyOnceWith(expect.stringContaining('boom'))
expect(stop).toHaveBeenCalledTimes(1)
})

it('should describe a rejection that is not an error', () => {
const report = vi.fn()

createRejectionHandler(report, vi.fn())('nope')

expect(report).toHaveBeenCalledExactlyOnceWith('Unhandled Rejection')
})

it('should keep the process alive when a client aborted the connection', () => {
const report = vi.fn()
const stop = vi.fn()
const handle = createRejectionHandler(report, stop)

handle(Object.assign(new Error('read ECONNRESET'), { code: 'ECONNRESET' }))
handle(Object.assign(new Error('premature close'), { code: 'ERR_STREAM_PREMATURE_CLOSE' }))

expect(report).not.toHaveBeenCalled()
expect(stop).not.toHaveBeenCalled()
})

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

📐 Maintainability & Code Quality | 🟠 Major | ⚡ Quick win

Cover the IPC listener lifecycle.

These tests call the returned callback directly, so they cannot detect a regression from process.on back to process.once. Add a test that enables IPC, emits an aborted rejection followed by a genuine one, and verifies the latter is reported/stops the child.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/nuxt-cli/test/unit/restart-hook.spec.ts` around lines 132 - 142,
Extend the restart-hook tests around createRejectionHandler to cover the IPC
listener lifecycle: enable IPC, register the returned rejection handler on the
process event listener, emit an aborted rejection first, then a genuine
rejection, and assert the genuine rejection is reported and stops the child.
Ensure the test would fail if the listener were registered with process.once
instead of process.on.

})
Loading