Unverified Commit a01ada4e authored by Tim Neutkens's avatar Tim Neutkens Committed by GitHub

Turbopack: Use readFileSync / writeFileSync for manifest writing (#83694)

## What?

Use sync fs methods for reading/writing manifests after a Turbopack
writeToDisk. Next step will be not calling it when nothing changed.

Before:

```
 GET / 200 in 41ms
 GET / 200 in 54ms
 GET / 200 in 57ms
 GET / 200 in 165ms
 GET / 200 in 44ms
 GET / 200 in 52ms
 GET / 200 in 42ms
 GET / 200 in 50ms
 GET / 200 in 39ms
 GET / 200 in 53ms
 GET / 200 in 39ms
 GET / 200 in 49ms
 GET / 200 in 40ms
 GET / 200 in 49ms
 GET / 200 in 40ms
 GET / 200 in 54ms
 GET / 200 in 39ms
 GET / 200 in 52ms
 GET / 200 in 47ms
 GET / 200 in 50ms
 GET / 200 in 45ms
 GET / 200 in 59ms
 GET / 200 in 44ms
 GET / 200 in 55ms
 GET / 200 in 46ms
 GET / 200 in 51ms
```


After:

```
 GET / 200 in 31ms
 GET / 200 in 29ms
 GET / 200 in 32ms
 GET / 200 in 33ms
 GET / 200 in 33ms
 GET / 200 in 34ms
 GET / 200 in 32ms
 GET / 200 in 30ms
 GET / 200 in 33ms
 GET / 200 in 30ms
 GET / 200 in 31ms
 GET / 200 in 32ms
 GET / 200 in 31ms
 GET / 200 in 31ms
 GET / 200 in 30ms
 GET / 200 in 33ms
 GET / 200 in 33ms
 GET / 200 in 32ms
 GET / 200 in 29ms
 GET / 200 in 30ms
 GET / 200 in 36ms
 GET / 200 in 35ms
 GET / 200 in 34ms
 GET / 200 in 32ms
 GET / 200 in 30ms
```
parent 5b4cdc3d
......@@ -109,14 +109,14 @@ export async function handleRouteType({
manifestLoader.deleteMiddlewareManifest(key)
}
await manifestLoader.loadAppBuildManifest(page)
await manifestLoader.loadBuildManifest(page, 'app')
await manifestLoader.loadAppPathsManifest(page)
await manifestLoader.loadActionManifest(page)
await manifestLoader.loadFontManifest(page, 'app')
manifestLoader.loadAppBuildManifest(page)
manifestLoader.loadBuildManifest(page, 'app')
manifestLoader.loadAppPathsManifest(page)
manifestLoader.loadActionManifest(page)
manifestLoader.loadFontManifest(page, 'app')
if (shouldCreateWebpackStats) {
await manifestLoader.loadWebpackStats(page, 'app')
manifestLoader.loadWebpackStats(page, 'app')
}
break
......@@ -124,10 +124,12 @@ export async function handleRouteType({
case 'app-route': {
const key = getEntryKey('app', 'server', page)
await manifestLoader.loadAppPathsManifest(page)
manifestLoader.loadAppPathsManifest(page)
const middlewareManifestWritten =
await manifestLoader.loadMiddlewareManifest(page, 'app')
const middlewareManifestWritten = manifestLoader.loadMiddlewareManifest(
page,
'app'
)
if (!middlewareManifestWritten) {
manifestLoader.deleteMiddlewareManifest(key)
......
......@@ -202,7 +202,7 @@ export async function turbopackBuild(): Promise<{
)),
])
await manifestLoader.writeManifests({
manifestLoader.writeManifests({
devRewrites: undefined,
productionRewrites: rewrites,
entrypoints: currentEntrypoints,
......
......@@ -25,18 +25,18 @@ SOFTWARE.
// This file is based on https://github.com/microsoft/vscode/blob/f860fcf11022f10a992440fd54c6e45674e39617/src/vs/base/node/pfs.ts
// See the LICENSE at the top of the file
import { rename as fsRename, stat } from 'node:fs/promises'
import { renameSync as fsRenameSync, statSync } from 'node:fs'
/**
* A drop-in replacement for `fs.rename` that:
* - allows to move across multiple disks
* - attempts to retry the operation for certain error codes on Windows
*/
export async function rename(
export function renameSync(
source: string,
target: string,
windowsRetryTimeout: number | false = 60000 /* matches graceful-fs */
): Promise<void> {
): void {
if (source === target) {
return // simulate node.js behaviour here and do a no-op if paths match
}
......@@ -46,21 +46,21 @@ export async function rename(
// is locked by AV software. We do leverage graceful-fs to iron
// out these issues, however in case the target file exists,
// graceful-fs will immediately return without retry for fs.rename().
await renameWithRetry(source, target, Date.now(), windowsRetryTimeout)
renameSyncWithRetry(source, target, Date.now(), windowsRetryTimeout)
} else {
await fsRename(source, target)
fsRenameSync(source, target)
}
}
async function renameWithRetry(
function renameSyncWithRetry(
source: string,
target: string,
startTime: number,
retryTimeout: number,
attempt = 0
): Promise<void> {
): void {
try {
return await fsRename(source, target)
return fsRenameSync(source, target)
} catch (error: any) {
if (
error.code !== 'EACCES' &&
......@@ -72,16 +72,23 @@ async function renameWithRetry(
if (Date.now() - startTime >= retryTimeout) {
console.error(
`[node.js fs] rename failed after ${attempt} retries with error: ${error}`
`Node.js fs rename failed after ${attempt} retries with error: ${error}`
)
throw error // give up after configurable timeout
}
if (attempt > 100) {
console.error(
`Node.js fs rename failed after ${attempt} retries with error ${error}`
)
throw error
}
if (attempt === 0) {
let abortRetry = false
try {
const statTarget = await stat(target)
const statTarget = statSync(target)
if (!statTarget.isFile()) {
abortRetry = true // if target is not a file, EPERM error may be raised and we should not attempt to retry
}
......@@ -94,13 +101,13 @@ async function renameWithRetry(
}
}
// Delay with incremental backoff up to 100ms
await timeout(Math.min(100, attempt * 10))
// Attempt again
return renameWithRetry(source, target, startTime, retryTimeout, attempt + 1)
return renameSyncWithRetry(
source,
target,
startTime,
retryTimeout,
attempt + 1
)
}
}
const timeout = (millis: number) =>
new Promise((resolve) => setTimeout(resolve, millis))
import { unlink, writeFile } from 'fs/promises'
import { rename } from './rename'
import { unlinkSync, writeFileSync } from 'fs'
import { renameSync } from './rename'
export async function writeFileAtomic(
filePath: string,
content: string
): Promise<void> {
export function writeFileAtomic(filePath: string, content: string): void {
const tempPath = filePath + '.tmp.' + Math.random().toString(36).slice(2)
try {
await writeFile(tempPath, content, 'utf-8')
await rename(tempPath, filePath)
writeFileSync(tempPath, content, 'utf-8')
renameSync(tempPath, filePath)
} catch (e) {
try {
await unlink(tempPath)
unlinkSync(tempPath)
} catch {
// ignore
}
......
......@@ -243,7 +243,7 @@ export async function handleRouteType({
await manifestLoader.loadWebpackStats(page, 'pages')
}
await manifestLoader.writeManifests({
manifestLoader.writeManifests({
devRewrites,
productionRewrites,
entrypoints,
......@@ -334,7 +334,7 @@ export async function handleRouteType({
manifestLoader.deleteMiddlewareManifest(key)
}
await manifestLoader.writeManifests({
manifestLoader.writeManifests({
devRewrites,
productionRewrites,
entrypoints,
......@@ -382,22 +382,22 @@ export async function handleRouteType({
const type = writtenEndpoint.type
if (type === 'edge') {
await manifestLoader.loadMiddlewareManifest(page, 'app')
manifestLoader.loadMiddlewareManifest(page, 'app')
} else {
manifestLoader.deleteMiddlewareManifest(key)
}
await manifestLoader.loadAppBuildManifest(page)
await manifestLoader.loadBuildManifest(page, 'app')
await manifestLoader.loadAppPathsManifest(page)
await manifestLoader.loadActionManifest(page)
await manifestLoader.loadFontManifest(page, 'app')
manifestLoader.loadAppBuildManifest(page)
manifestLoader.loadBuildManifest(page, 'app')
manifestLoader.loadAppPathsManifest(page)
manifestLoader.loadActionManifest(page)
manifestLoader.loadFontManifest(page, 'app')
if (shouldCreateWebpackStats) {
await manifestLoader.loadWebpackStats(page, 'app')
manifestLoader.loadWebpackStats(page, 'app')
}
await manifestLoader.writeManifests({
manifestLoader.writeManifests({
devRewrites,
productionRewrites,
entrypoints,
......@@ -415,15 +415,15 @@ export async function handleRouteType({
const type = writtenEndpoint.type
await manifestLoader.loadAppPathsManifest(page)
manifestLoader.loadAppPathsManifest(page)
if (type === 'edge') {
await manifestLoader.loadMiddlewareManifest(page, 'app')
manifestLoader.loadMiddlewareManifest(page, 'app')
} else {
manifestLoader.deleteMiddlewareManifest(key)
}
await manifestLoader.writeManifests({
manifestLoader.writeManifests({
devRewrites,
productionRewrites,
entrypoints,
......@@ -690,7 +690,7 @@ export async function handleEntrypoints({
'instrumentation',
'instrumentation'
)
await manifestLoader.writeManifests({
manifestLoader.writeManifests({
devRewrites,
productionRewrites: undefined,
entrypoints: currentEntrypoints,
......@@ -758,7 +758,7 @@ export async function handleEntrypoints({
'middleware',
dev.serverFields.middleware
)
await manifestLoader.writeManifests({
manifestLoader.writeManifests({
devRewrites,
productionRewrites: undefined,
entrypoints: currentEntrypoints,
......@@ -956,7 +956,7 @@ export async function handlePagesErrorRoute({
await manifestLoader.loadPagesManifest('_error')
await manifestLoader.loadFontManifest('_error')
await manifestLoader.writeManifests({
manifestLoader.writeManifests({
devRewrites,
productionRewrites,
entrypoints,
......
......@@ -30,7 +30,7 @@ import {
WEBPACK_STATS,
} from '../constants'
import { join, posix } from 'path'
import { readFile } from 'fs/promises'
import { readFileSync } from 'fs'
import type { SetupOpts } from '../../../server/lib/router-utils/setup-dev-bundler'
import { deleteCache } from '../../../server/dev/require-cache'
import { writeFileAtomic } from '../../../lib/fs/write-atomic'
......@@ -121,15 +121,15 @@ const getManifestPath = (
return manifestPath
}
async function readPartialManifest<T>(
function readPartialManifest<T>(
distDir: string,
name: ManifestName,
pageName: string,
type: 'pages' | 'app' | 'middleware' | 'instrumentation' = 'pages'
): Promise<T> {
): T {
const page = pageName
const manifestPath = getManifestPath(page, distDir, name, type, true)
return JSON.parse(await readFile(posix.join(manifestPath), 'utf-8')) as T
return JSON.parse(readFileSync(posix.join(manifestPath), 'utf-8')) as T
}
export class TurbopackManifestLoader {
......@@ -174,10 +174,10 @@ export class TurbopackManifestLoader {
this.webpackStats.delete(key)
}
async loadActionManifest(pageName: string): Promise<void> {
loadActionManifest(pageName: string): void {
this.actionManifests.set(
getEntryKey('app', 'server', pageName),
await readPartialManifest(
readPartialManifest(
this.distDir,
`${SERVER_REFERENCE_MANIFEST}.json`,
pageName,
......@@ -186,7 +186,7 @@ export class TurbopackManifestLoader {
)
}
private async mergeActionManifests(manifests: Iterable<ActionManifest>) {
private mergeActionManifests(manifests: Iterable<ActionManifest>) {
type ActionEntries = ActionManifest['edge' | 'node']
const manifest: ActionManifest = {
node: {},
......@@ -228,8 +228,8 @@ export class TurbopackManifestLoader {
return manifest
}
private async writeActionManifest(): Promise<void> {
const actionManifest = await this.mergeActionManifests(
private writeActionManifest(): void {
const actionManifest = this.mergeActionManifests(
this.actionManifests.values()
)
const actionManifestJsonPath = join(
......@@ -245,22 +245,17 @@ export class TurbopackManifestLoader {
const json = JSON.stringify(actionManifest, null, 2)
deleteCache(actionManifestJsonPath)
deleteCache(actionManifestJsPath)
await writeFileAtomic(actionManifestJsonPath, json)
await writeFileAtomic(
writeFileAtomic(actionManifestJsonPath, json)
writeFileAtomic(
actionManifestJsPath,
`self.__RSC_SERVER_MANIFEST=${JSON.stringify(json)}`
)
}
async loadAppBuildManifest(pageName: string): Promise<void> {
loadAppBuildManifest(pageName: string): void {
this.appBuildManifests.set(
getEntryKey('app', 'server', pageName),
await readPartialManifest(
this.distDir,
APP_BUILD_MANIFEST,
pageName,
'app'
)
readPartialManifest(this.distDir, APP_BUILD_MANIFEST, pageName, 'app')
)
}
......@@ -275,31 +270,26 @@ export class TurbopackManifestLoader {
return manifest
}
private async writeAppBuildManifest(): Promise<void> {
private writeAppBuildManifest(): void {
const appBuildManifest = this.mergeAppBuildManifests(
this.appBuildManifests.values()
)
const appBuildManifestPath = join(this.distDir, APP_BUILD_MANIFEST)
deleteCache(appBuildManifestPath)
await writeFileAtomic(
writeFileAtomic(
appBuildManifestPath,
JSON.stringify(appBuildManifest, null, 2)
)
}
async loadAppPathsManifest(pageName: string): Promise<void> {
loadAppPathsManifest(pageName: string): void {
this.appPathsManifests.set(
getEntryKey('app', 'server', pageName),
await readPartialManifest(
this.distDir,
APP_PATHS_MANIFEST,
pageName,
'app'
)
readPartialManifest(this.distDir, APP_PATHS_MANIFEST, pageName, 'app')
)
}
private async writeAppPathsManifest(): Promise<void> {
private writeAppPathsManifest(): void {
const appPathsManifest = this.mergePagesManifests(
this.appPathsManifests.values()
)
......@@ -309,36 +299,33 @@ export class TurbopackManifestLoader {
APP_PATHS_MANIFEST
)
deleteCache(appPathsManifestPath)
await writeFileAtomic(
writeFileAtomic(
appPathsManifestPath,
JSON.stringify(appPathsManifest, null, 2)
)
}
private async writeWebpackStats(): Promise<void> {
private writeWebpackStats(): void {
const webpackStats = this.mergeWebpackStats(this.webpackStats.values())
const path = join(this.distDir, 'server', WEBPACK_STATS)
deleteCache(path)
await writeFileAtomic(path, JSON.stringify(webpackStats, null, 2))
writeFileAtomic(path, JSON.stringify(webpackStats, null, 2))
}
async loadBuildManifest(
pageName: string,
type: 'app' | 'pages' = 'pages'
): Promise<void> {
loadBuildManifest(pageName: string, type: 'app' | 'pages' = 'pages'): void {
this.buildManifests.set(
getEntryKey(type, 'server', pageName),
await readPartialManifest(this.distDir, BUILD_MANIFEST, pageName, type)
readPartialManifest(this.distDir, BUILD_MANIFEST, pageName, type)
)
}
async loadClientBuildManifest(
loadClientBuildManifest(
pageName: string,
type: 'app' | 'pages' = 'pages'
): Promise<void> {
): void {
this.clientBuildManifests.set(
getEntryKey(type, 'server', pageName),
await readPartialManifest(
readPartialManifest(
this.distDir,
TURBOPACK_CLIENT_BUILD_MANIFEST,
pageName,
......@@ -347,13 +334,10 @@ export class TurbopackManifestLoader {
)
}
async loadWebpackStats(
pageName: string,
type: 'app' | 'pages' = 'pages'
): Promise<void> {
loadWebpackStats(pageName: string, type: 'app' | 'pages' = 'pages'): void {
this.webpackStats.set(
getEntryKey(type, 'client', pageName),
await readPartialManifest(this.distDir, WEBPACK_STATS, pageName, type)
readPartialManifest(this.distDir, WEBPACK_STATS, pageName, type)
)
}
......@@ -458,11 +442,11 @@ export class TurbopackManifestLoader {
return sortObjectByKey(manifest)
}
private async writeBuildManifest(
private writeBuildManifest(
entrypoints: Entrypoints,
devRewrites: SetupOpts['fsChecker']['rewrites'] | undefined,
productionRewrites: CustomRoutes['rewrites'] | undefined
): Promise<void> {
): void {
const rewrites = productionRewrites ?? {
...devRewrites,
beforeFiles: (devRewrites?.beforeFiles ?? []).map(processRoute),
......@@ -484,11 +468,8 @@ export class TurbopackManifestLoader {
deleteCache(buildManifestPath)
deleteCache(middlewareBuildManifestPath)
deleteCache(interceptionRewriteManifestPath)
await writeFileAtomic(
buildManifestPath,
JSON.stringify(buildManifest, null, 2)
)
await writeFileAtomic(
writeFileAtomic(buildManifestPath, JSON.stringify(buildManifest, null, 2))
writeFileAtomic(
middlewareBuildManifestPath,
// we use globalThis here because middleware can be node
// which doesn't have "self"
......@@ -499,7 +480,7 @@ export class TurbopackManifestLoader {
rewrites.beforeFiles.filter(isInterceptionRouteRewrite)
)
await writeFileAtomic(
writeFileAtomic(
interceptionRewriteManifestPath,
`self.__INTERCEPTION_ROUTE_REWRITE_MANIFEST=${JSON.stringify(
interceptionRewrites
......@@ -525,17 +506,17 @@ export class TurbopackManifestLoader {
null,
2
)};self.__BUILD_MANIFEST_CB && self.__BUILD_MANIFEST_CB()`
await writeFileAtomic(
writeFileAtomic(
join(this.distDir, 'static', this.buildId, '_buildManifest.js'),
clientBuildManifestJs
)
await writeFileAtomic(
writeFileAtomic(
join(this.distDir, 'static', this.buildId, '_ssgManifest.js'),
srcEmptySsgManifest
)
}
private async writeClientMiddlewareManifest(): Promise<void> {
private writeClientMiddlewareManifest(): void {
const middlewareManifest = this.mergeMiddlewareManifests(
this.middlewareManifests.values()
)
......@@ -549,7 +530,7 @@ export class TurbopackManifestLoader {
`${TURBOPACK_CLIENT_MIDDLEWARE_MANIFEST}`
)
deleteCache(clientMiddlewareManifestPath)
await writeFileAtomic(
writeFileAtomic(
clientMiddlewareManifestPath,
JSON.stringify(matchers, null, 2)
)
......@@ -567,19 +548,16 @@ export class TurbopackManifestLoader {
`fallback-${BUILD_MANIFEST}`
)
deleteCache(fallbackBuildManifestPath)
await writeFileAtomic(
writeFileAtomic(
fallbackBuildManifestPath,
JSON.stringify(fallbackBuildManifest, null, 2)
)
}
async loadFontManifest(
pageName: string,
type: 'app' | 'pages' = 'pages'
): Promise<void> {
loadFontManifest(pageName: string, type: 'app' | 'pages' = 'pages'): void {
this.fontManifests.set(
getEntryKey(type, 'server', pageName),
await readPartialManifest(
readPartialManifest(
this.distDir,
`${NEXT_FONT_MANIFEST}.json`,
pageName,
......@@ -625,8 +603,8 @@ export class TurbopackManifestLoader {
)
deleteCache(fontManifestJsonPath)
deleteCache(fontManifestJsPath)
await writeFileAtomic(fontManifestJsonPath, json)
await writeFileAtomic(
writeFileAtomic(fontManifestJsonPath, json)
writeFileAtomic(
fontManifestJsPath,
`self.__NEXT_FONT_MANIFEST=${JSON.stringify(json)}`
)
......@@ -635,10 +613,10 @@ export class TurbopackManifestLoader {
/**
* @returns If the manifest was written or not
*/
async loadMiddlewareManifest(
loadMiddlewareManifest(
pageName: string,
type: 'pages' | 'app' | 'middleware' | 'instrumentation'
): Promise<boolean> {
): boolean {
const middlewareManifestPath = getManifestPath(
pageName,
this.distDir,
......@@ -658,12 +636,7 @@ export class TurbopackManifestLoader {
'server',
pageName
),
await readPartialManifest(
this.distDir,
MIDDLEWARE_MANIFEST,
pageName,
type
)
readPartialManifest(this.distDir, MIDDLEWARE_MANIFEST, pageName, type)
)
return true
......@@ -730,7 +703,7 @@ export class TurbopackManifestLoader {
return manifest
}
private async writeMiddlewareManifest(): Promise<void> {
private writeMiddlewareManifest(): void {
const middlewareManifest = this.mergeMiddlewareManifests(
this.middlewareManifests.values()
)
......@@ -754,16 +727,16 @@ export class TurbopackManifestLoader {
MIDDLEWARE_MANIFEST
)
deleteCache(middlewareManifestPath)
await writeFileAtomic(
writeFileAtomic(
middlewareManifestPath,
JSON.stringify(middlewareManifest, null, 2)
)
}
async loadPagesManifest(pageName: string): Promise<void> {
loadPagesManifest(pageName: string): void {
this.pagesManifests.set(
getEntryKey('pages', 'server', pageName),
await readPartialManifest(this.distDir, PAGES_MANIFEST, pageName)
readPartialManifest(this.distDir, PAGES_MANIFEST, pageName)
)
}
......@@ -775,17 +748,14 @@ export class TurbopackManifestLoader {
return sortObjectByKey(manifest)
}
private async writePagesManifest(): Promise<void> {
private writePagesManifest(): void {
const pagesManifest = this.mergePagesManifests(this.pagesManifests.values())
const pagesManifestPath = join(this.distDir, 'server', PAGES_MANIFEST)
deleteCache(pagesManifestPath)
await writeFileAtomic(
pagesManifestPath,
JSON.stringify(pagesManifest, null, 2)
)
writeFileAtomic(pagesManifestPath, JSON.stringify(pagesManifest, null, 2))
}
async writeManifests({
writeManifests({
devRewrites,
productionRewrites,
entrypoints,
......@@ -793,19 +763,19 @@ export class TurbopackManifestLoader {
devRewrites: SetupOpts['fsChecker']['rewrites'] | undefined
productionRewrites: CustomRoutes['rewrites'] | undefined
entrypoints: Entrypoints
}) {
await this.writeActionManifest()
await this.writeAppBuildManifest()
await this.writeAppPathsManifest()
await this.writeBuildManifest(entrypoints, devRewrites, productionRewrites)
await this.writeFallbackBuildManifest()
await this.writeMiddlewareManifest()
await this.writeClientMiddlewareManifest()
await this.writeNextFontManifest()
await this.writePagesManifest()
}): void {
this.writeActionManifest()
this.writeAppBuildManifest()
this.writeAppPathsManifest()
this.writeBuildManifest(entrypoints, devRewrites, productionRewrites)
this.writeFallbackBuildManifest()
this.writeMiddlewareManifest()
this.writeClientMiddlewareManifest()
this.writeNextFontManifest()
this.writePagesManifest()
if (process.env.TURBOPACK_STATS != null) {
await this.writeWebpackStats()
this.writeWebpackStats()
}
}
}
......
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