Unverified Commit 1e139ad6 authored by vercel-fleet-prod[bot]'s avatar vercel-fleet-prod[bot] Committed by GitHub

test: check cliOutput for Rust panics instead of a stream detector

Co-authored-by: 's avatarTobias Koppers <1365881+sokra@users.noreply.github.com>
parent 181f6246
......@@ -45,7 +45,26 @@ import { Page, Response } from 'playwright'
import { PHASE_PRODUCTION_BUILD } from 'next/constants'
import { loadResolvedConfig } from '../gate/load-resolved-config'
import type { ResolvedNextConfig } from '../gate/resolved-config'
import { RustPanicDetector, RustPanicError } from './rust-panic-detector'
import stripAnsi from 'strip-ansi'
/**
* Matches a Rust panic or a fatal Turbopack internal error in Next.js output.
*
* - Rust's default panic hook prints `thread '<name>' panicked at <location>:`
* or `thread panicked at <location>:` (newer toolchains can also include
* the thread id: `thread '<name>' (1234) panicked at`).
* - `log_internal_error_and_inform` in `crates/next-napi-bindings` prints
* `FATAL: An unexpected Turbopack error occurred` for internal errors.
*/
const RUST_PANIC_REGEX =
/thread(?: '[^'\n]*')?(?: \(\d+\))? panicked at |FATAL: An unexpected Turbopack error occurred/
/** Lines of output after a panic that are included in the error. */
const RUST_PANIC_CONTEXT_LINES = 20
export class RustPanicError extends Error {
name = 'RustPanicError'
}
type Event = 'stdout' | 'stderr' | 'error' | 'destroy'
export type InstallCommand =
......@@ -141,7 +160,8 @@ export class NextInstance {
patchFileDelay: number = 0
public deleteWorkspaceFile: boolean = false
public allowRustPanics: boolean = false
protected rustPanicDetector = new RustPanicDetector()
/** How much of `cliOutput` `throwOnRustPanics` already checked. */
protected rustPanicCheckedLength = 0
private _resolvedConfig?: Promise<ResolvedNextConfig>
constructor(opts: NextInstanceOpts) {
......@@ -936,27 +956,31 @@ export class NextInstance {
}
/**
* Feed output of the Next.js child process to the Rust panic detector.
*/
protected detectRustPanics(stream: 'stdout' | 'stderr', msg: string) {
this.rustPanicDetector.write(stream, msg)
}
/**
* Throw a `RustPanicError` if a Rust panic or fatal Turbopack error was
* printed since the last check. Call once the process' output is complete
* (after a build or after stopping the server).
* Throw a `RustPanicError` if `cliOutput` contains a Rust panic or a fatal
* Turbopack error that wasn't checked yet. Call once the process' output is
* complete (after a build or after stopping the server).
*/
protected throwOnRustPanics(processName: string, cause?: unknown) {
this.rustPanicDetector.flush()
const report = this.rustPanicDetector.takeReport()
if (report === null || this.allowRustPanics) {
// Only the output of local `next dev`/`next build`/`next start` processes
// is checked. In deploy mode `cliOutput` holds fetched deployment logs.
if (isNextDeploy) {
return
}
const output = this.cliOutput
const unchecked = output.slice(this.rustPanicCheckedLength)
this.rustPanicCheckedLength = output.length
if (this.allowRustPanics) {
return
}
const lines = stripAnsi(unchecked).split('\n')
const index = lines.findIndex((line) => RUST_PANIC_REGEX.test(line))
if (index === -1) {
return
}
throw new RustPanicError(
`The ${processName} output contains a Rust panic or a fatal Turbopack error. ` +
'Pass `allowRustPanics: true` to `nextTestSetup` if this is expected.\n\n' +
report,
lines.slice(index, index + 1 + RUST_PANIC_CONTEXT_LINES).join('\n'),
cause === undefined ? undefined : { cause }
)
}
......
......@@ -31,14 +31,12 @@ export class NextDevInstance extends NextInstance {
const msg = chunk.toString()
process.stdout.write(chunk)
this._cliOutput += msg
this.detectRustPanics('stdout', msg)
this.emit('stdout', [msg])
})
childProcess.stderr.on('data', (chunk) => {
const msg = chunk.toString()
process.stderr.write(chunk)
this._cliOutput += msg
this.detectRustPanics('stderr', msg)
this.emit('stderr', [msg])
})
}
......@@ -162,19 +160,18 @@ export class NextDevInstance extends NextInstance {
})
this._cliOutput = ''
this.rustPanicCheckedLength = 0
this.childProcess.stdout!.on('data', (chunk) => {
const msg = chunk.toString()
process.stdout.write(chunk)
this._cliOutput += msg
this.detectRustPanics('stdout', msg)
this.emit('stdout', [msg])
})
this.childProcess.stderr!.on('data', (chunk) => {
const msg = chunk.toString()
process.stderr.write(chunk)
this._cliOutput += msg
this.detectRustPanics('stderr', msg)
this.emit('stderr', [msg])
})
......
......@@ -66,14 +66,12 @@ export class NextStartInstance extends NextInstance {
const msg = chunk.toString()
process.stdout.write(chunk)
this._cliOutput += msg
this.detectRustPanics('stdout', msg)
this.emit('stdout', [msg])
})
childProcess.stderr.on('data', (chunk) => {
const msg = chunk.toString()
process.stderr.write(chunk)
this._cliOutput += msg
this.detectRustPanics('stderr', msg)
this.emit('stderr', [msg])
})
}
......@@ -102,6 +100,7 @@ export class NextStartInstance extends NextInstance {
await this.stopLeftoverBuildOrThrow('next already started')
this._cliOutput = ''
this.rustPanicCheckedLength = 0
const spawnOpts = this.getSpawnOpts(options.env)
let startArgs = ['pnpm', 'next', 'start']
......
import stripAnsi from 'strip-ansi'
/**
* Lines that indicate a Rust panic or a fatal Turbopack internal error in the
* output of a Next.js process.
*
* - Rust's default panic hook prints `thread '<name>' panicked at <location>:`
* or `thread panicked at <location>:` (newer toolchains can also include
* the thread id: `thread '<name>' (1234) panicked at`). The Next.js napi
* bindings chain to the default hook, so this is printed even when
* turbo-tasks catches the panic.
* - `log_internal_error_and_inform` in `crates/next-napi-bindings` prints
* `FATAL: An unexpected Turbopack error occurred` for internal errors.
*/
const RUST_PANIC_PATTERNS: RegExp[] = [
/thread(?: '[^'\n]*')?(?: \(\d+\))? panicked at /,
/FATAL: An unexpected Turbopack error occurred/,
]
/** Lines of output captured after a match, to give the report context. */
const CONTEXT_LINES = 20
/** Matches beyond this are counted but not printed in the report. */
const MAX_REPORTED_MATCHES = 10
type Stream = 'stdout' | 'stderr'
interface Match {
stream: Stream
lines: string[]
}
export class RustPanicError extends Error {
name = 'RustPanicError'
}
/**
* Scans the stdout/stderr of a Next.js child process for Rust panics. Output
* arrives in arbitrary chunks, so lines are buffered per stream and only
* complete lines are matched.
*/
export class RustPanicDetector {
private partialLines: Record<Stream, string> = { stdout: '', stderr: '' }
private matches: Match[] = []
private matchCount = 0
/** The match still collecting context lines, per stream. */
private collecting: Partial<
Record<Stream, { match: Match; remaining: number }>
> = {}
public write(stream: Stream, chunk: string): void {
const lines = (this.partialLines[stream] + chunk).split('\n')
this.partialLines[stream] = lines.pop()!
for (const line of lines) {
this.processLine(stream, line)
}
}
/** Process any buffered partial lines, e.g. once the process exited. */
public flush(): void {
for (const stream of ['stdout', 'stderr'] as const) {
if (this.partialLines[stream]) {
this.processLine(stream, this.partialLines[stream])
this.partialLines[stream] = ''
}
}
}
/**
* Return a report of all matches seen since the last call, or `null` if
* there were none. Reported matches are cleared so they are only reported
* once.
*/
public takeReport(): string | null {
if (this.matchCount === 0) {
return null
}
const sections = this.matches.map(
(match) => `[${match.stream}]\n${match.lines.join('\n')}`
)
const omitted = this.matchCount - this.matches.length
if (omitted > 0) {
sections.push(`... and ${omitted} more`)
}
this.matches = []
this.matchCount = 0
this.collecting = {}
return sections.join('\n\n')
}
private processLine(stream: Stream, rawLine: string): void {
const line = stripAnsi(rawLine).replace(/\r$/, '')
if (RUST_PANIC_PATTERNS.some((pattern) => pattern.test(line))) {
this.matchCount++
if (this.matches.length < MAX_REPORTED_MATCHES) {
const match: Match = { stream, lines: [line] }
this.matches.push(match)
this.collecting[stream] = { match, remaining: CONTEXT_LINES }
} else {
delete this.collecting[stream]
}
return
}
const collecting = this.collecting[stream]
if (collecting) {
collecting.match.lines.push(line)
if (--collecting.remaining === 0) {
delete this.collecting[stream]
}
}
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment