remove staticWorkerRequestDeduping flag & unused IPC code (#66655)

This flag remained experimental because the IPC implementation didn't
play nicely with requests containing large payloads, due to it being
stringified as GET parameters. This branching logic also poses
challenges for some upcoming work related to detecting IO.

This removes the handling for the
`experimental.staticWorkerRequestDeduping` flag which we can revisit in
the future with a sounder approach. This also cleans up some of the IPC
server utilities as it wasn't in use anywhere else.

<!-- Thanks for opening a PR! Your contribution is much appreciated.
To make sure your PR is handled as smoothly as possible we request that
you follow the checklist sections below.
Choose the right checklist for the change(s) that you're making:

## For Contributors

### Improving Documentation

- Run `pnpm prettier-fix` to fix formatting issues before opening the
PR.
- Read the Docs Contribution Guide to ensure your contribution follows
the docs guidelines:
https://nextjs.org/docs/community/contribution-guide

### Adding or Updating Examples

- The "examples guidelines" are followed from our contributing doc
https://github.com/vercel/next.js/blob/canary/contributing/examples/adding-examples.md
- Make sure the linting passes by running `pnpm build && pnpm lint`. See
https://github.com/vercel/next.js/blob/canary/contributing/repository/linting.md

### Fixing a bug

- Related issues linked using `fixes #number`
- Tests added. See:
https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs
- Errors have a helpful link attached, see
https://github.com/vercel/next.js/blob/canary/contributing.md

### Adding a feature

- Implements an existing feature request or RFC. Make sure the feature
request has been accepted for implementation before opening a PR. (A
discussion must be opened, see
https://github.com/vercel/next.js/discussions/new?category=ideas)
- Related issues/discussions are linked using `fixes #number`
- e2e tests added
(https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs)
- Documentation added
- Telemetry added. In case of a feature if it's used or not.
- Errors have a helpful link attached, see
https://github.com/vercel/next.js/blob/canary/contributing.md


## For Maintainers

- Minimal description (aim for explaining to someone not on the team to
understand the PR)
- When linking to a Slack thread, you might want to share details of the
conclusion
- Link both the Linear (Fixes NEXT-xxx) and the GitHub issues
- Add review comments if necessary to explain to the reviewer the logic
behind a change

### What?

### Why?

### How?

Closes NEXT-
Fixes #

-->
This commit is contained in:
Zack Tanner 2024-06-07 16:42:44 -07:00 committed by GitHub
parent 676a3bad83
commit a9d842a24e
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
9 changed files with 9 additions and 468 deletions

View file

@ -159,16 +159,12 @@ import { startTypeChecking } from './type-check'
import { generateInterceptionRoutesRewrites } from '../lib/generate-interception-routes-rewrites'
import { buildDataRoute } from '../server/lib/router-utils/build-data-route'
import { initialize as initializeIncrementalCache } from '../server/lib/incremental-cache-server'
import { nodeFs } from '../server/lib/node-fs-methods'
import { collectBuildTraces } from './collect-build-traces'
import type { BuildTraceContext } from './webpack/plugins/next-trace-entrypoints-plugin'
import { formatManifest } from './manifests/formatter/format-manifest'
import { getStartServerInfo, logStartInfo } from '../server/lib/app-info-log'
import type { NextEnabledDirectories } from '../server/base-server'
import { hasCustomExportOutput } from '../export/utils'
import { interopDefault } from '../lib/interop-default'
import { formatDynamicImportPath } from '../lib/format-dynamic-import-path'
import { isInterceptionRouteAppPath } from '../server/lib/interception-routes'
import {
getTurbopackJsConfig,
@ -578,11 +574,7 @@ type PageDataCollectionKeys = Exclude<
'exportPage'
>
function createStaticWorker(
config: NextConfigComplete,
incrementalCacheIpcPort?: number,
incrementalCacheIpcValidationKey?: string
): StaticWorker {
function createStaticWorker(config: NextConfigComplete): StaticWorker {
let infoPrinted = false
const timeout = config.staticPageGenerationTimeout || 0
@ -622,13 +614,7 @@ function createStaticWorker(
},
numWorkers: getNumberOfWorkers(config),
forkOptions: {
env: {
...process.env,
__NEXT_INCREMENTAL_CACHE_IPC_PORT: incrementalCacheIpcPort
? incrementalCacheIpcPort + ''
: undefined,
__NEXT_INCREMENTAL_CACHE_IPC_KEY: incrementalCacheIpcValidationKey,
},
env: process.env,
},
enableWorkerThreads: config.experimental.workerThreads,
exposedMethods: staticWorkerExposedMethods,
@ -637,8 +623,6 @@ function createStaticWorker(
async function writeFullyStaticExport(
config: NextConfigComplete,
incrementalCacheIpcPort: number | undefined,
incrementalCacheIpcValidationKey: string | undefined,
dir: string,
enabledDirectories: NextEnabledDirectories,
configOutDir: string,
@ -647,16 +631,8 @@ async function writeFullyStaticExport(
const exportApp = require('../export')
.default as typeof import('../export').default
const pagesWorker = createStaticWorker(
config,
incrementalCacheIpcPort,
incrementalCacheIpcValidationKey
)
const appWorker = createStaticWorker(
config,
incrementalCacheIpcPort,
incrementalCacheIpcValidationKey
)
const pagesWorker = createStaticWorker(config)
const appWorker = createStaticWorker(config)
await exportApp(
dir,
@ -1783,62 +1759,8 @@ export default async function build(
process.env.NEXT_PHASE = PHASE_PRODUCTION_BUILD
let incrementalCacheIpcPort
let incrementalCacheIpcValidationKey
if (config.experimental.staticWorkerRequestDeduping) {
let CacheHandler
if (cacheHandler) {
CacheHandler = interopDefault(
await import(formatDynamicImportPath(dir, cacheHandler)).then(
(mod) => mod.default || mod
)
)
}
const cacheInitialization = await initializeIncrementalCache({
fs: nodeFs,
dev: false,
pagesDir: true,
appDir: true,
fetchCache: true,
flushToDisk: ciEnvironment.hasNextSupport
? false
: config.experimental.isrFlushToDisk,
serverDistDir: path.join(distDir, 'server'),
fetchCacheKeyPrefix: config.experimental.fetchCacheKeyPrefix,
maxMemoryCacheSize: config.cacheMaxMemorySize,
getPrerenderManifest: () => ({
version: -1 as any, // letting us know this doesn't conform to spec
routes: {},
dynamicRoutes: {},
notFoundRoutes: [],
preview: null as any, // `preview` is special case read in next-dev-server
}),
requestHeaders: {},
CurCacheHandler: CacheHandler,
minimalMode: ciEnvironment.hasNextSupport,
allowedRevalidateHeaderKeys:
config.experimental.allowedRevalidateHeaderKeys,
})
incrementalCacheIpcPort = cacheInitialization.ipcPort
incrementalCacheIpcValidationKey = cacheInitialization.ipcValidationKey
}
const pagesStaticWorkers = createStaticWorker(
config,
incrementalCacheIpcPort,
incrementalCacheIpcValidationKey
)
const appStaticWorkers = appDir
? createStaticWorker(
config,
incrementalCacheIpcPort,
incrementalCacheIpcValidationKey
)
: undefined
const pagesStaticWorkers = createStaticWorker(config)
const appStaticWorkers = appDir ? createStaticWorker(config) : undefined
const analysisBegin = process.hrtime()
const staticCheckSpan = nextBuildSpan.traceChild('static-check')
@ -3392,8 +3314,6 @@ export default async function build(
if (config.output === 'export') {
await writeFullyStaticExport(
config,
incrementalCacheIpcPort,
incrementalCacheIpcValidationKey,
dir,
enabledDirectories,
configOutDir,

View file

@ -416,7 +416,6 @@ export const configSchema: zod.ZodType<NextConfig> = z.lazy(() =>
.optional(),
serverMinification: z.boolean().optional(),
serverSourceMaps: z.boolean().optional(),
staticWorkerRequestDeduping: z.boolean().optional(),
useWasmBinary: z.boolean().optional(),
useLightningcss: z.boolean().optional(),
useEarlyImport: z.boolean().optional(),

View file

@ -438,11 +438,6 @@ export interface ExperimentalConfig {
*/
trustHostHeader?: boolean
/**
* Uses an IPC server to dedupe build-time requests to the cache handler
*/
staticWorkerRequestDeduping?: boolean
useWasmBinary?: boolean
/**

View file

@ -1,44 +0,0 @@
import { createIpcServer } from './server-ipc'
import { IncrementalCache } from './incremental-cache'
let initializeResult:
| undefined
| {
ipcPort: number
ipcValidationKey: string
}
export async function initialize(
...constructorArgs: ConstructorParameters<typeof IncrementalCache>
): Promise<NonNullable<typeof initializeResult>> {
const incrementalCache = new IncrementalCache(...constructorArgs)
const { ipcPort, ipcValidationKey } = await createIpcServer({
async revalidateTag(
...args: Parameters<IncrementalCache['revalidateTag']>
) {
return incrementalCache.revalidateTag(...args)
},
async get(...args: Parameters<IncrementalCache['get']>) {
return incrementalCache.get(...args)
},
async set(...args: Parameters<IncrementalCache['set']>) {
return incrementalCache.set(...args)
},
async lock(...args: Parameters<IncrementalCache['lock']>) {
return incrementalCache.lock(...args)
},
async unlock(...args: Parameters<IncrementalCache['unlock']>) {
return incrementalCache.unlock(...args)
},
} as any)
return {
ipcPort,
ipcValidationKey,
}
}

View file

@ -234,31 +234,6 @@ export class IncrementalCache implements IncrementalCacheType {
}
async lock(cacheKey: string) {
if (
process.env.__NEXT_INCREMENTAL_CACHE_IPC_PORT &&
process.env.__NEXT_INCREMENTAL_CACHE_IPC_KEY &&
process.env.NEXT_RUNTIME !== 'edge'
) {
const invokeIpcMethod = require('../server-ipc/request-utils')
.invokeIpcMethod as typeof import('../server-ipc/request-utils').invokeIpcMethod
await invokeIpcMethod({
method: 'lock',
ipcPort: process.env.__NEXT_INCREMENTAL_CACHE_IPC_PORT,
ipcKey: process.env.__NEXT_INCREMENTAL_CACHE_IPC_KEY,
args: [cacheKey],
})
return async () => {
await invokeIpcMethod({
method: 'unlock',
ipcPort: process.env.__NEXT_INCREMENTAL_CACHE_IPC_PORT,
ipcKey: process.env.__NEXT_INCREMENTAL_CACHE_IPC_KEY,
args: [cacheKey],
})
}
}
let unlockNext: () => Promise<void> = () => Promise.resolve()
const existingLock = this.locks.get(cacheKey)
@ -279,21 +254,6 @@ export class IncrementalCache implements IncrementalCacheType {
}
async revalidateTag(tags: string | string[]): Promise<void> {
if (
process.env.__NEXT_INCREMENTAL_CACHE_IPC_PORT &&
process.env.__NEXT_INCREMENTAL_CACHE_IPC_KEY &&
process.env.NEXT_RUNTIME !== 'edge'
) {
const invokeIpcMethod = require('../server-ipc/request-utils')
.invokeIpcMethod as typeof import('../server-ipc/request-utils').invokeIpcMethod
return invokeIpcMethod({
method: 'revalidateTag',
ipcPort: process.env.__NEXT_INCREMENTAL_CACHE_IPC_PORT,
ipcKey: process.env.__NEXT_INCREMENTAL_CACHE_IPC_KEY,
args: [...arguments],
})
}
return this.cacheHandler?.revalidateTag?.(tags)
}
@ -433,22 +393,6 @@ export class IncrementalCache implements IncrementalCacheType {
isRoutePPREnabled?: boolean
} = {}
): Promise<IncrementalCacheEntry | null> {
if (
process.env.__NEXT_INCREMENTAL_CACHE_IPC_PORT &&
process.env.__NEXT_INCREMENTAL_CACHE_IPC_KEY &&
process.env.NEXT_RUNTIME !== 'edge'
) {
const invokeIpcMethod = require('../server-ipc/request-utils')
.invokeIpcMethod as typeof import('../server-ipc/request-utils').invokeIpcMethod
return invokeIpcMethod({
method: 'get',
ipcPort: process.env.__NEXT_INCREMENTAL_CACHE_IPC_PORT,
ipcKey: process.env.__NEXT_INCREMENTAL_CACHE_IPC_KEY,
args: [...arguments],
})
}
// we don't leverage the prerender cache in dev mode
// so that getStaticProps is always called for easier debugging
if (
@ -556,22 +500,6 @@ export class IncrementalCache implements IncrementalCacheType {
isRoutePPREnabled?: boolean
}
) {
if (
process.env.__NEXT_INCREMENTAL_CACHE_IPC_PORT &&
process.env.__NEXT_INCREMENTAL_CACHE_IPC_KEY &&
process.env.NEXT_RUNTIME !== 'edge'
) {
const invokeIpcMethod = require('../server-ipc/request-utils')
.invokeIpcMethod as typeof import('../server-ipc/request-utils').invokeIpcMethod
return invokeIpcMethod({
method: 'set',
ipcPort: process.env.__NEXT_INCREMENTAL_CACHE_IPC_PORT,
ipcKey: process.env.__NEXT_INCREMENTAL_CACHE_IPC_KEY,
args: [...arguments],
})
}
if (this.disableForTestmode || (this.dev && !ctx.fetchCache)) return
// FetchCache has upper limit of 2MB per-entry currently
const itemSize = JSON.stringify(data).length

View file

@ -1,96 +0,0 @@
import type NextServer from '../../next-server'
import { errorToJSON } from '../../render'
import crypto from 'crypto'
import isError from '../../../lib/is-error'
import { deserializeErr } from './request-utils'
// we can't use process.send as jest-worker relies on
// it already and can cause unexpected message errors
// so we create an IPC server for communicating
export async function createIpcServer(
server: InstanceType<typeof NextServer>
): Promise<{
ipcPort: number
ipcServer: import('http').Server
ipcValidationKey: string
}> {
// Generate a random key in memory to validate messages from other processes.
// This is just a simple guard against other processes attempting to send
// traffic to the IPC server.
const ipcValidationKey = crypto.randomBytes(32).toString('hex')
const ipcServer = (require('http') as typeof import('http')).createServer(
async (req, res) => {
try {
const url = new URL(req.url || '/', 'http://n')
const key = url.searchParams.get('key')
if (key !== ipcValidationKey) {
return res.end()
}
const method = url.searchParams.get('method')
let body = await new Promise<string>((resolve, reject) => {
let str = ''
req.on('data', (chunk) => {
str += chunk
})
req.on('end', () => {
resolve(str)
})
req.on('error', (err) => {
reject(err)
})
res.on('close', function () {
let aborted = !res.writableFinished
if (aborted) {
reject(new Error('ipc request aborted'))
}
})
})
const args: any[] = JSON.parse(body || '[]')
if (!method || !Array.isArray(args)) {
return res.end()
}
if (typeof (server as any)[method] === 'function') {
if (method === 'logErrorWithOriginalStack' && args[0]?.stack) {
args[0] = deserializeErr(args[0])
}
let result = await (server as any)[method](...args)
if (result && typeof result === 'object' && result.stack) {
result = errorToJSON(result)
}
res.end(JSON.stringify(result || ''))
}
} catch (err: any) {
if (isError(err) && err.code !== 'ENOENT') {
console.error(err)
}
res.end(
JSON.stringify({
err: { name: err.name, message: err.message, stack: err.stack },
})
)
}
}
)
const ipcPort = await new Promise<number>((resolveIpc) => {
ipcServer.listen(0, server.hostname, () => {
const addr = ipcServer.address()
if (addr && typeof addr === 'object') {
resolveIpc(addr.port)
}
})
})
return {
ipcPort,
ipcServer,
ipcValidationKey,
}
}

View file

@ -1,42 +0,0 @@
import type { IncomingMessage } from 'http'
import type { Readable } from 'stream'
import { filterReqHeaders, ipcForbiddenHeaders } from './utils'
export const invokeRequest = async (
targetUrl: string,
requestInit: {
headers: IncomingMessage['headers']
method: IncomingMessage['method']
signal?: AbortSignal
},
readableBody?: string | Readable | ReadableStream
) => {
const invokeHeaders = filterReqHeaders(
{
'cache-control': '',
...requestInit.headers,
},
ipcForbiddenHeaders
) as IncomingMessage['headers']
return await fetch(targetUrl, {
headers: invokeHeaders as any as Headers,
method: requestInit.method,
redirect: 'manual',
signal: requestInit.signal,
...(requestInit.method !== 'GET' &&
requestInit.method !== 'HEAD' &&
readableBody
? {
body: readableBody as BodyInit,
duplex: 'half',
}
: {}),
next: {
// @ts-ignore
internal: true,
},
})
}

View file

@ -1,73 +0,0 @@
import { decorateServerError } from '../../../shared/lib/error-source'
import { PageNotFoundError } from '../../../shared/lib/utils'
import { invokeRequest } from './invoke-request'
export const deserializeErr = (serializedErr: any) => {
if (
!serializedErr ||
typeof serializedErr !== 'object' ||
!serializedErr.stack
) {
return serializedErr
}
let ErrorType: any = Error
if (serializedErr.name === 'PageNotFoundError') {
ErrorType = PageNotFoundError
}
const err = new ErrorType(serializedErr.message)
err.stack = serializedErr.stack
err.name = serializedErr.name
;(err as any).digest = serializedErr.digest
if (
process.env.NODE_ENV === 'development' &&
process.env.NEXT_RUNTIME !== 'edge'
) {
decorateServerError(err, serializedErr.source || 'server')
}
return err
}
export async function invokeIpcMethod({
fetchHostname = 'localhost',
method,
args,
ipcPort,
ipcKey,
}: {
fetchHostname?: string
method: string
args: any[]
ipcPort?: string
ipcKey?: string
}): Promise<any> {
if (ipcPort) {
const res = await invokeRequest(
`http://${fetchHostname}:${ipcPort}?key=${ipcKey}&method=${
method as string
}`,
{
method: 'POST',
headers: {},
},
JSON.stringify(args)
)
const body = await res.text()
if (body.startsWith('{') && body.endsWith('}')) {
const parsedBody = JSON.parse(body)
if (
parsedBody &&
typeof parsedBody === 'object' &&
'err' in parsedBody &&
'stack' in parsedBody.err
) {
throw deserializeErr(parsedBody.err)
}
return parsedBody
}
}
}

View file

@ -1,55 +1,9 @@
import { findPort, waitFor } from 'next-test-utils'
import http from 'http'
import { waitFor } from 'next-test-utils'
import { outdent } from 'outdent'
import { isNextDev, isNextStart, nextTestSetup } from 'e2e-utils'
import { isNextDev, nextTestSetup } from 'e2e-utils'
describe('app-fetch-deduping', () => {
if (isNextStart) {
describe('during static generation', () => {
const { next } = nextTestSetup({ files: __dirname, skipStart: true })
let externalServerPort: number
let externalServer: http.Server
let requests = []
beforeAll(async () => {
externalServerPort = await findPort()
externalServer = http.createServer((req, res) => {
requests.push(req.url)
res.end(`Request ${req.url} received at ${Date.now()}`)
})
await new Promise<void>((resolve, reject) => {
externalServer.listen(externalServerPort, () => {
resolve()
})
externalServer.once('error', (err) => {
reject(err)
})
})
})
beforeEach(() => {
requests = []
})
afterAll(() => externalServer.close())
it('dedupes requests amongst static workers when experimental.staticWorkerRequestDeduping is enabled', async () => {
await next.patchFileFast(
'next.config.js',
`module.exports = {
env: { TEST_SERVER_PORT: "${externalServerPort}" },
experimental: {
staticWorkerRequestDeduping: true
}
}`
)
await next.build()
expect(requests.length).toBe(1)
})
})
} else if (isNextDev) {
if (isNextDev) {
describe('during next dev', () => {
const { next } = nextTestSetup({ files: __dirname })
function invocation(cliOutput: string): number {