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

export: fail with an actionable error when a static generation batch is too large for IPC

Static generation sends each batch's results, including every page's resume
data cache, back to the main process as a single JSON IPC message. When that
message exceeds V8's maximum string length, process.send throws inside
jest-worker after exportPages has returned, and the build hangs forever
(#99850).

Measure the exact length of the outgoing messages (results from child process
workers, and seed data sent to workers) without building the full string, and
throw an error that names the cause and suggests making batches smaller or
reducing cached data.
Co-authored-by: 's avatarTobias Koppers <1365881+sokra@users.noreply.github.com>
parent e2be0379
......@@ -3,6 +3,7 @@ import type {
ExportAppOptions,
WorkerRenderOptsPartial,
ExportPagesResult,
ExportPagesInput,
ExportPathEntry,
} from './types'
import {
......@@ -77,6 +78,7 @@ import { normalizeAppPath } from '../shared/lib/router/utils/app-paths'
import type { Params } from '../server/request/params'
import { Bundler } from '../lib/bundler'
import { getBuildDistDir, getExportPathPageKey } from './utils'
import { assertExportPagesInputFitsInIpcMessage } from './ipc-message-size'
export class ExportError extends Error {
code = 'NEXT_EXPORT_ERROR'
......@@ -738,7 +740,7 @@ async function exportAppImpl(
}
}
return worker.exportPages({
const input: ExportPagesInput = {
buildId,
deploymentId: nextConfig.deploymentId,
clientAssetToken: nextConfig.supportsImmutableAssets
......@@ -760,7 +762,21 @@ async function exportAppImpl(
fetchCache: true,
fetchCacheKeyPrefix: nextConfig.experimental.fetchCacheKeyPrefix,
renderResumeDataCachesByPage: batchRenderResumeDataCaches,
})
}
// The seeds can be large, so make sure the call can still be sent
// to the worker, and fail with an actionable error if it can't.
if (input.renderResumeDataCachesByPage) {
assertExportPagesInputFitsInIpcMessage(
input,
batch.length,
nextConfig.experimental.workerThreads
? 'worker-thread'
: 'child-process'
)
}
return worker.exportPages(input)
})
)
).flat()
......
import { constants as bufferConstants } from 'buffer'
/**
* Static generation batches are sent between the main build process and the
* export workers as JSON. Node's child process IPC channel serializes each
* message into a single string (`JSON.stringify(message) + '\n'`), and Next's
* worker thread transport JSON-stringifies the call arguments, so a message can
* never be longer than V8's maximum string length. When it is, serialization
* throws `RangeError: Invalid string length`; for worker results this happens
* inside the IPC layer and would otherwise leave the build waiting forever.
*
* The helpers below compute the exact length of those messages without ever
* building the full string, so that we can fail with an actionable error
* before sending.
*/
export const MAX_IPC_MESSAGE_LENGTH: number = bufferConstants.MAX_STRING_LENGTH
/**
* jest-worker message type for a successful result (`PARENT_MESSAGE_OK`),
* sent as `[PARENT_MESSAGE_OK, result]`.
*/
const PARENT_MESSAGE_OK = 0
/**
* jest-worker message type for a method call (`CHILD_MESSAGE_CALL`), sent as
* `[CHILD_MESSAGE_CALL, false, method, args]`.
*/
const CHILD_MESSAGE_CALL = 1
const EXPORT_PAGES_METHOD = 'exportPages'
/** Length of the newline Node's JSON IPC channel appends to every message. */
const IPC_MESSAGE_DELIMITER_LENGTH = 1
export type ExportWorkerTransport = 'child-process' | 'worker-thread'
type MessageDirection = 'results' | 'seeds'
export class ExportIpcMessageTooLargeError extends Error {
constructor({
direction,
pageCount,
length,
limit,
}: {
direction: MessageDirection
pageCount: number
/** `undefined` when a single value was too large to measure. */
length: number | undefined
limit: number
}) {
const what =
direction === 'results'
? 'the static generation results'
: 'the resume data cache seeds'
const from =
direction === 'results'
? 'from a build worker back to the main build process'
: 'from the main build process to a build worker'
const size =
length === undefined
? `at least ${limit} characters`
: `${length} characters`
super(
`Static generation failed because ${what} for a batch of ${pageCount} ` +
`pages are too large to send ${from} (${size}, the maximum is ${limit}).\n` +
`This can happen with Cache Components when pages cache large ` +
`amounts of data with 'use cache', because each page's resume data ` +
`cache is sent between build workers.\n` +
`To fix this, reduce the size of the cached data, or make each batch ` +
`smaller by lowering \`experimental.staticGenerationMinPagesPerWorker\` ` +
`and/or increasing \`experimental.cpus\` in your Next.js config.`
)
this.name = 'ExportIpcMessageTooLargeError'
}
}
function isInvalidStringLengthError(err: unknown): boolean {
return err instanceof RangeError && err.message === 'Invalid string length'
}
/**
* Length of a value's JSON encoding as an array element (where `undefined`,
* functions and symbols are encoded as `null`).
*/
function getArrayElementJsonLength(value: unknown): number {
return (JSON.stringify(value) ?? 'null').length
}
/**
* Length of a JSON array's encoding, given the encoded length of each element:
* `[` + elements joined by `,` + `]`.
*/
function getJsonArrayLength(elementLengths: number, elementCount: number) {
return 2 + elementLengths + Math.max(elementCount - 1, 0)
}
/**
* Exact length of the IPC message a child process export worker sends back to
* the main process for `results`:
* `JSON.stringify([PARENT_MESSAGE_OK, results]) + '\n'`.
*
* May throw if a single result cannot be stringified on its own.
*/
export function getExportResultsMessageLength(
results: ReadonlyArray<unknown>
): number {
let resultsLength = 0
for (const result of results) {
resultsLength += getArrayElementJsonLength(result)
}
return (
getJsonArrayLength(
String(PARENT_MESSAGE_OK).length +
getJsonArrayLength(resultsLength, results.length),
2
) + IPC_MESSAGE_DELIMITER_LENGTH
)
}
/**
* Exact length of the message that carries an `exportPages` call with `input`:
* - child process: `JSON.stringify([CHILD_MESSAGE_CALL, false, 'exportPages', [input]]) + '\n'`
* - worker thread: `JSON.stringify([input])` (the argument sanitizer in
* `lib/worker.ts`)
*
* The seed map (`renderResumeDataCachesByPage`), which holds the large values,
* is measured entry by entry. May throw if a single value cannot be
* stringified on its own.
*/
export function getExportPagesInputMessageLength(
input: { renderResumeDataCachesByPage?: Record<string, string> },
transport: ExportWorkerTransport
): number {
const { renderResumeDataCachesByPage } = input
let inputLength: number
if (renderResumeDataCachesByPage) {
// Measure everything but the seed map in one go, then add the encoded
// length of the map in place of the `{}` placeholder.
inputLength =
JSON.stringify({ ...input, renderResumeDataCachesByPage: {} }).length -
2 +
getSeedMapJsonLength(renderResumeDataCachesByPage)
} else {
inputLength = JSON.stringify(input).length
}
// The input is the single element of the arguments array.
const argsLength = getJsonArrayLength(inputLength, 1)
if (transport === 'worker-thread') {
return argsLength
}
const headerLength =
String(CHILD_MESSAGE_CALL).length +
JSON.stringify(false).length +
JSON.stringify(EXPORT_PAGES_METHOD).length
return (
getJsonArrayLength(headerLength + argsLength, 4) +
IPC_MESSAGE_DELIMITER_LENGTH
)
}
function getSeedMapJsonLength(seeds: Record<string, string>): number {
let entriesLength = 0
let entryCount = 0
for (const key of Object.keys(seeds)) {
const value = JSON.stringify(seeds[key])
// Properties whose value can't be represented in JSON are omitted.
if (value === undefined) continue
// `"key":value`
entriesLength += JSON.stringify(key).length + 1 + value.length
entryCount++
}
// `{` + entries joined by `,` + `}`
return getJsonArrayLength(entriesLength, entryCount)
}
function measure(
getLength: () => number,
error: Omit<
ConstructorParameters<typeof ExportIpcMessageTooLargeError>[0],
'length'
>
): void {
let length: number
try {
length = getLength()
} catch (err) {
if (isInvalidStringLengthError(err)) {
throw new ExportIpcMessageTooLargeError({ ...error, length: undefined })
}
throw err
}
if (length > error.limit) {
throw new ExportIpcMessageTooLargeError({ ...error, length })
}
}
/**
* Throws an `ExportIpcMessageTooLargeError` if the results of a batch would be
* too large to send back to the main process over the child process IPC
* channel.
*/
export function assertExportResultsFitInIpcMessage(
results: ReadonlyArray<unknown>,
pageCount: number,
limit: number = MAX_IPC_MESSAGE_LENGTH
): void {
measure(() => getExportResultsMessageLength(results), {
direction: 'results',
pageCount,
limit,
})
}
/**
* Throws an `ExportIpcMessageTooLargeError` if an `exportPages` call with
* `input` would be too large to send to a build worker.
*/
export function assertExportPagesInputFitsInIpcMessage(
input: { renderResumeDataCachesByPage?: Record<string, string> },
pageCount: number,
transport: ExportWorkerTransport,
limit: number = MAX_IPC_MESSAGE_LENGTH
): void {
measure(() => getExportPagesInputMessageLength(input, transport), {
direction: 'seeds',
pageCount,
limit,
})
}
/**
* Results only need to be checked when they are sent back over a child
* process IPC channel. Worker threads transfer results with the structured
* clone algorithm, which does not build a single string for the message.
*/
export function shouldCheckExportResultsMessageSize({
isMainThread,
hasIpcChannel,
}: {
isMainThread: boolean
hasIpcChannel: boolean
}): boolean {
return isMainThread && hasIpcChannel
}
......@@ -60,6 +60,11 @@ import type { AppSharedContext } from '../server/app-render/app-render'
import { MultiFileWriter } from '../lib/multi-file-writer'
import { createRenderResumeDataCache } from '../server/resume-data-cache/resume-data-cache'
import { getExportPathPageKey } from './utils'
import {
assertExportResultsFitInIpcMessage,
shouldCheckExportResultsMessageSize,
} from './ipc-message-size'
import { isMainThread } from 'worker_threads'
import { installGlobalBehaviors } from '../server/node-environment-extensions/global-behaviors'
;(globalThis as any).__NEXT_DATA__ = {
nextExport: true,
......@@ -580,6 +585,19 @@ export async function exportPages(
results.push(...subsetResults)
}
// The results are sent back to the main process as one IPC message. When
// that message is too large, the child process IPC channel fails to
// serialize it outside of this function, and the main process would wait
// for the results forever. Fail with an actionable error instead.
if (
shouldCheckExportResultsMessageSize({
isMainThread,
hasIpcChannel: typeof process.send === 'function',
})
) {
assertExportResultsFitInIpcMessage(results, exportPaths.length)
}
return results
}
......
/* eslint-env jest */
import {
assertExportPagesInputFitsInIpcMessage,
assertExportResultsFitInIpcMessage,
ExportIpcMessageTooLargeError,
getExportPagesInputMessageLength,
getExportResultsMessageLength,
shouldCheckExportResultsMessageSize,
} from 'next/dist/export/ipc-message-size'
// The exact strings Node's JSON IPC channel and Next's worker-thread argument
// sanitizer build for these messages.
const resultsMessage = (results: unknown[]) =>
JSON.stringify([0, results]) + '\n'
const childProcessCallMessage = (input: unknown) =>
JSON.stringify([1, false, 'exportPages', [input]]) + '\n'
const workerThreadArgs = (input: unknown) => JSON.stringify([input])
const awkwardStrings = [
'plain',
'quote " and backslash \\',
'newline \n tab \t control \u0001 \u001f',
'non-ascii äöü ß 日本語',
'emoji 🎉 and lone surrogate \ud800',
'</script><!-- -->',
'',
]
const sampleResults = () => [
{
page: '/p/[id]',
path: '/p/0',
pageKey: '/p/[id]: /p/0',
result: {
renderResumeDataCache: awkwardStrings.join('|'),
htmlSize: 12,
metadata: { segmentPaths: ['/a', '/b'], prefetchHints: undefined },
},
},
{
page: '/p/[id]',
path: '/p/1',
pageKey: '/p/[id]: /p/1',
result: undefined,
},
...awkwardStrings.map((s, i) => ({
page: s,
path: `/s/${i}`,
pageKey: s,
result: { error: true, duration: i },
})),
]
const sampleInput = (seeds?: Record<string, string>) => ({
buildId: 'build "id"',
exportPaths: [{ page: '/[lang]/[slug]', path: '/en/[slug]' }],
nextConfig: {
// Functions are dropped by JSON serialization.
generateBuildId: () => 'x',
experimental: { cpus: 4, nested: { emoji: '🎉', fn: () => {} } },
},
renderOpts: { a: undefined, b: null, c: [1, 'two', undefined] },
renderResumeDataCachesByPage: seeds,
})
const sampleSeeds = () =>
Object.fromEntries(
awkwardStrings.map((s, i) => [`/[lang]/[slug]: /${s}/${i}`, s.repeat(3)])
)
const throwingToJSON = (error: Error) => ({
toJSON() {
throw error
},
})
describe('getExportResultsMessageLength', () => {
it.each([
['no results', []],
['one empty object', [{}]],
['awkward strings and undefined fields', sampleResults()],
['non-object entries', [undefined, null, 1, 'x', () => {}]],
])(
'matches the length of the JSON IPC message (%s)',
(_name, results: unknown[]) => {
expect(getExportResultsMessageLength(results)).toBe(
resultsMessage(results).length
)
}
)
})
describe('assertExportResultsFitInIpcMessage', () => {
it('allows a message that is exactly at the limit', () => {
const results = sampleResults()
const length = resultsMessage(results).length
expect(() =>
assertExportResultsFitInIpcMessage(results, results.length, length)
).not.toThrow()
})
it('rejects a message that is one character over the limit', () => {
const results = sampleResults()
const length = resultsMessage(results).length
let error: unknown
try {
assertExportResultsFitInIpcMessage(results, 42, length - 1)
} catch (err) {
error = err
}
expect(error).toBeInstanceOf(ExportIpcMessageTooLargeError)
const { message } = error as Error
expect(message).toContain('batch of 42 pages')
expect(message).toContain('results')
expect(message).toContain(`${length} characters`)
expect(message).toContain(`maximum is ${length - 1}`)
expect(message).toContain("'use cache'")
expect(message).toContain('experimental.staticGenerationMinPagesPerWorker')
expect(message).toContain('experimental.cpus')
})
it('translates a single entry that is too large to stringify on its own', () => {
const results = [
{ page: '/a', path: '/a' },
throwingToJSON(new RangeError('Invalid string length')),
]
expect(() =>
assertExportResultsFitInIpcMessage(results, 2, 1_000_000)
).toThrow(ExportIpcMessageTooLargeError)
expect(() =>
assertExportResultsFitInIpcMessage(results, 2, 1_000_000)
).toThrow('at least 1000000 characters')
})
it('rethrows a cyclic structure error unchanged', () => {
const cyclic: Record<string, unknown> = {}
cyclic.self = cyclic
expect(() => assertExportResultsFitInIpcMessage([cyclic], 1)).toThrow(
TypeError
)
expect(() => assertExportResultsFitInIpcMessage([cyclic], 1)).not.toThrow(
ExportIpcMessageTooLargeError
)
})
it('rethrows unrelated errors unchanged', () => {
const boom = new Error('boom')
let error: unknown
try {
assertExportResultsFitInIpcMessage([throwingToJSON(boom)], 1)
} catch (err) {
error = err
}
expect(error).toBe(boom)
const otherRangeError = new RangeError('Maximum call stack size exceeded')
try {
assertExportResultsFitInIpcMessage([throwingToJSON(otherRangeError)], 1)
} catch (err) {
error = err
}
expect(error).toBe(otherRangeError)
})
})
describe('getExportPagesInputMessageLength', () => {
it.each([
['without a seed map', undefined],
['with an empty seed map', {}],
['with seeds that need escaping', sampleSeeds()],
])('matches the child-process call message length (%s)', (_name, seeds) => {
const input = sampleInput(seeds)
expect(getExportPagesInputMessageLength(input, 'child-process')).toBe(
childProcessCallMessage(input).length
)
})
it.each([
['without a seed map', undefined],
['with seeds that need escaping', sampleSeeds()],
])(
'matches the worker-thread sanitized arguments length (%s)',
(_name, seeds) => {
const input = sampleInput(seeds)
expect(getExportPagesInputMessageLength(input, 'worker-thread')).toBe(
workerThreadArgs(input).length
)
}
)
})
describe('assertExportPagesInputFitsInIpcMessage', () => {
it.each(['child-process', 'worker-thread'] as const)(
'allows a message exactly at the limit and rejects one over it (%s)',
(transport) => {
const input = sampleInput(sampleSeeds())
const length =
transport === 'child-process'
? childProcessCallMessage(input).length
: workerThreadArgs(input).length
expect(() =>
assertExportPagesInputFitsInIpcMessage(input, 3, transport, length)
).not.toThrow()
let error: unknown
try {
assertExportPagesInputFitsInIpcMessage(input, 3, transport, length - 1)
} catch (err) {
error = err
}
expect(error).toBeInstanceOf(ExportIpcMessageTooLargeError)
const { message } = error as Error
expect(message).toContain('batch of 3 pages')
expect(message).toContain('resume data cache seeds')
expect(message).toContain(`${length} characters`)
expect(message).toContain(
'experimental.staticGenerationMinPagesPerWorker'
)
}
)
it('rejects an oversized filtered batch with the seed-direction error', () => {
const batch = [
{ page: '/[lang]/[slug]', path: '/en/[slug]' },
{ page: '/[lang]/[slug]', path: '/de/[slug]' },
]
const input = {
...sampleInput(),
exportPaths: batch,
// The batch's seed map has already been filtered by the caller.
renderResumeDataCachesByPage: {
'/[lang]/[slug]: /en/[slug]': 'e'.repeat(500),
'/[lang]/[slug]: /de/[slug]': 'd'.repeat(500),
},
}
// Both seeds fit individually, but the batch is too large together.
const oneSeedInput = {
...input,
exportPaths: batch.slice(0, 1),
renderResumeDataCachesByPage: {
'/[lang]/[slug]: /en/[slug]': 'e'.repeat(500),
},
}
expect(() =>
assertExportPagesInputFitsInIpcMessage(
oneSeedInput,
1,
'child-process',
1000
)
).not.toThrow()
let error: unknown
try {
assertExportPagesInputFitsInIpcMessage(input, 2, 'child-process', 1000)
} catch (err) {
error = err
}
expect(error).toBeInstanceOf(ExportIpcMessageTooLargeError)
expect((error as Error).message).toContain('resume data cache seeds')
expect((error as Error).message).toContain('batch of 2 pages')
})
it('translates a seed that is too large to stringify on its own', () => {
const input = sampleInput({
'/a': throwingToJSON(
new RangeError('Invalid string length')
) as unknown as string,
})
expect(() =>
assertExportPagesInputFitsInIpcMessage(input, 1, 'child-process', 5000)
).toThrow('at least 5000 characters')
})
})
describe('shouldCheckExportResultsMessageSize', () => {
it('checks in a forked child process', () => {
expect(
shouldCheckExportResultsMessageSize({
isMainThread: true,
hasIpcChannel: true,
})
).toBe(true)
})
it('skips in a worker thread (results are structured-cloned)', () => {
expect(
shouldCheckExportResultsMessageSize({
isMainThread: false,
hasIpcChannel: true,
})
).toBe(false)
})
it('skips when there is no IPC channel', () => {
expect(
shouldCheckExportResultsMessageSize({
isMainThread: true,
hasIpcChannel: false,
})
).toBe(false)
})
})
{
"compilerOptions": {
"target": "ES2017",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "react-jsx",
"incremental": true,
"paths": {
"@/*": ["./*"]
}
},
"include": [
"next-env.d.ts",
"**/*.ts",
"**/*.tsx",
".next/types/**/*.ts",
".next/dev/types/**/*.ts",
"**/*.mts"
],
"exclude": ["node_modules", "**/*.test.ts", "**/*.test.tsx"]
}
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