Skip to content

Commit

Permalink
Refactor to unify writeFile, readFile, and add readManifest (#60137)
Browse files Browse the repository at this point in the history
## What?

Consolidates similar function calls, sets up `readManifest` and the
foundation for `writeManifest` too.

<!-- 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 #

-->


Closes NEXT-1954
  • Loading branch information
timneutkens authored Jan 3, 2024
1 parent 930f820 commit 4e9a3ba
Showing 1 changed file with 71 additions and 78 deletions.
149 changes: 71 additions & 78 deletions packages/next/src/build/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -337,7 +337,7 @@ async function generateClientSsgManifest(
ssgPages
)};self.__SSG_MANIFEST_CB&&self.__SSG_MANIFEST_CB()`

await fs.writeFile(
await writeFileUtf8(
path.join(distDir, CLIENT_STATIC_FILES_PATH, buildId, '_ssgManifest.js'),
clientSsgManifestContent
)
Expand Down Expand Up @@ -369,6 +369,42 @@ function getCacheDir(distDir: string): string {
return cacheDir
}

function getNumberOfWorkers(config: NextConfigComplete) {
if (
config.experimental.cpus &&
config.experimental.cpus !== defaultConfig.experimental!.cpus
) {
return config.experimental.cpus
}

if (config.experimental.memoryBasedWorkersCount) {
return Math.max(
Math.min(config.experimental.cpus || 1, Math.floor(os.freemem() / 1e9)),
// enforce a minimum of 4 workers
4
)
}

if (config.experimental.cpus) {
return config.experimental.cpus
}

// Fall back to 4 workers if a count is not specified
return 4
}

async function writeFileUtf8(filePath: string, content: string) {
await fs.writeFile(filePath, content, 'utf-8')
}

function readFileUtf8(filePath: string) {
return fs.readFile(filePath, 'utf8')
}

async function readManifest<T extends object>(filePath: string): Promise<T> {
return JSON.parse(await readFileUtf8(filePath))
}

export default async function build(
dir: string,
reactProductionProfiling = false,
Expand Down Expand Up @@ -427,7 +463,7 @@ export default async function build(
let buildId: string = ''

if (isGenerateMode) {
buildId = await fs.readFile(path.join(distDir, 'BUILD_ID'), 'utf8')
buildId = await readFileUtf8(path.join(distDir, 'BUILD_ID'))
} else {
buildId = await nextBuildSpan
.traceChild('generate-buildid')
Expand Down Expand Up @@ -913,7 +949,7 @@ export default async function build(

// Ensure commonjs handling is used for files in the distDir (generally .next)
// Files outside of the distDir can be "type": "module"
await fs.writeFile(
await writeFileUtf8(
path.join(distDir, 'package.json'),
'{"type": "commonjs"}'
)
Expand All @@ -922,24 +958,19 @@ export default async function build(
await nextBuildSpan
.traceChild('write-routes-manifest')
.traceAsyncFn(() =>
fs.writeFile(
routesManifestPath,
formatManifest(routesManifest),
'utf8'
)
writeFileUtf8(routesManifestPath, formatManifest(routesManifest))
)

// We need to write a partial prerender manifest to make preview mode settings available in edge middleware
const partialManifest: Partial<PrerenderManifest> = {
preview: previewProps,
}

await fs.writeFile(
await writeFileUtf8(
path.join(distDir, PRERENDER_MANIFEST).replace(/\.json$/, '.js'),
`self.__PRERENDER_MANIFEST=${JSON.stringify(
JSON.stringify(partialManifest)
)}`,
'utf8'
)}`
)

const outputFileTracingRoot =
Expand Down Expand Up @@ -1206,16 +1237,10 @@ export default async function build(
const appDynamicParamPaths = new Set<string>()
const appDefaultConfigs = new Map<string, AppConfig>()
const pageInfos: PageInfos = new Map<string, PageInfo>()
const pagesManifest = JSON.parse(
await fs.readFile(pagesManifestPath, 'utf8')
) as PagesManifest
const buildManifest = JSON.parse(
await fs.readFile(buildManifestPath, 'utf8')
) as BuildManifest
const pagesManifest = await readManifest<PagesManifest>(pagesManifestPath)
const buildManifest = await readManifest<BuildManifest>(buildManifestPath)
const appBuildManifest = appDir
? (JSON.parse(
await fs.readFile(appBuildManifestPath, 'utf8')
) as AppBuildManifest)
? await readManifest<AppBuildManifest>(appBuildManifestPath)
: undefined

const timeout = config.staticPageGenerationTimeout || 0
Expand All @@ -1226,36 +1251,23 @@ export default async function build(

if (appDir) {
appPathsManifest = JSON.parse(
await fs.readFile(
path.join(distDir, SERVER_DIRECTORY, APP_PATHS_MANIFEST),
'utf8'
await readFileUtf8(
path.join(distDir, SERVER_DIRECTORY, APP_PATHS_MANIFEST)
)
)

Object.keys(appPathsManifest).forEach((entry) => {
appPathRoutes[entry] = normalizeAppPath(entry)
})
await fs.writeFile(
await writeFileUtf8(
path.join(distDir, APP_PATH_ROUTES_MANIFEST),
formatManifest(appPathRoutes),
'utf-8'
formatManifest(appPathRoutes)
)
}

process.env.NEXT_PHASE = PHASE_PRODUCTION_BUILD

const numWorkers = config.experimental.memoryBasedWorkersCount
? Math.max(
config.experimental.cpus !== defaultConfig.experimental!.cpus
? (config.experimental.cpus as number)
: Math.min(
config.experimental.cpus || 1,
Math.floor(os.freemem() / 1e9)
),
// enforce a minimum of 4 workers
4
)
: config.experimental.cpus || 4
const numberOfWorkers = getNumberOfWorkers(config)

function createStaticWorker(
incrementalCacheIpcPort?: number,
Expand Down Expand Up @@ -1295,7 +1307,7 @@ export default async function build(
infoPrinted = true
}
},
numWorkers,
numWorkers: numberOfWorkers,
forkOptions: {
env: {
...process.env,
Expand Down Expand Up @@ -1938,10 +1950,9 @@ export default async function build(
functions: functionsConfigManifest,
}

await fs.writeFile(
await writeFileUtf8(
path.join(distDir, SERVER_DIRECTORY, FUNCTIONS_CONFIG_MANIFEST),
formatManifest(manifest),
'utf8'
formatManifest(manifest)
)
}

Expand Down Expand Up @@ -1972,11 +1983,7 @@ export default async function build(
return buildDataRoute(page, buildId)
})

await fs.writeFile(
routesManifestPath,
formatManifest(routesManifest),
'utf8'
)
await writeFileUtf8(routesManifestPath, formatManifest(routesManifest))
}

// Since custom _app.js can wrap the 404 page we have to opt-out of static optimization if it has getInitialProps
Expand Down Expand Up @@ -2047,17 +2054,13 @@ export default async function build(
})
)

await fs.writeFile(
await writeFileUtf8(
path.join(distDir, SERVER_FILES_MANIFEST),
formatManifest(requiredServerFiles),
'utf8'
formatManifest(requiredServerFiles)
)

const middlewareManifest: MiddlewareManifest = JSON.parse(
await fs.readFile(
path.join(distDir, SERVER_DIRECTORY, MIDDLEWARE_MANIFEST),
'utf8'
)
const middlewareManifest: MiddlewareManifest = await readManifest(
path.join(distDir, SERVER_DIRECTORY, MIDDLEWARE_MANIFEST)
)

const finalPrerenderRoutes: { [route: string]: SsgRoute } = {}
Expand Down Expand Up @@ -2786,11 +2789,7 @@ export default async function build(

// remove temporary export folder
await fs.rm(exportOptions.outdir, { recursive: true, force: true })
await fs.writeFile(
pagesManifestPath,
formatManifest(pagesManifest),
'utf8'
)
await writeFileUtf8(pagesManifestPath, formatManifest(pagesManifest))
})
}

Expand Down Expand Up @@ -2886,17 +2885,15 @@ export default async function build(
NextBuildContext.allowedRevalidateHeaderKeys =
config.experimental.allowedRevalidateHeaderKeys

await fs.writeFile(
await writeFileUtf8(
path.join(distDir, PRERENDER_MANIFEST),
formatManifest(prerenderManifest),
'utf8'
formatManifest(prerenderManifest)
)
await fs.writeFile(
await writeFileUtf8(
path.join(distDir, PRERENDER_MANIFEST).replace(/\.json$/, '.js'),
`self.__PRERENDER_MANIFEST=${JSON.stringify(
JSON.stringify(prerenderManifest)
)}`,
'utf8'
)}`
)
await generateClientSsgManifest(prerenderManifest, {
distDir,
Expand All @@ -2911,17 +2908,15 @@ export default async function build(
preview: previewProps,
notFoundRoutes: [],
}
await fs.writeFile(
await writeFileUtf8(
path.join(distDir, PRERENDER_MANIFEST),
formatManifest(prerenderManifest),
'utf8'
formatManifest(prerenderManifest)
)
await fs.writeFile(
await writeFileUtf8(
path.join(distDir, PRERENDER_MANIFEST).replace(/\.json$/, '.js'),
`self.__PRERENDER_MANIFEST=${JSON.stringify(
JSON.stringify(prerenderManifest)
)}`,
'utf8'
)}`
)
}

Expand All @@ -2938,23 +2933,21 @@ export default async function build(
})
)

await fs.writeFile(
await writeFileUtf8(
path.join(distDir, IMAGES_MANIFEST),
formatManifest({
version: 1,
images,
}),
'utf8'
})
)
await fs.writeFile(
await writeFileUtf8(
path.join(distDir, EXPORT_MARKER),
formatManifest({
version: 1,
hasExportPathMap: typeof config.exportPathMap === 'function',
exportTrailingSlash: config.trailingSlash === true,
isNextImageImported: isNextImageImported === true,
}),
'utf8'
})
)
await fs.unlink(path.join(distDir, EXPORT_DETAIL)).catch((err) => {
if (err.code === 'ENOENT') {
Expand Down

0 comments on commit 4e9a3ba

Please sign in to comment.