rsnext/packages/next/build/webpack/plugins/nextjs-require-cache-hot-reloader.ts
Jimmy Lai 589f090d0b
memory: fix 2 memory leaks in next-dev (#43859)
This PR fixes two memory leaks I found debugging with @sokra.

## 1) Leak in `next-server.ts`

The first leak was caused by the fact that the `require.cache` associated to the `next-server` module was not being cleared up properly, so we leaked context from modules required in that page, like API routes.

## 2)  Leak with React Fetch

When evaluating a route, we also evaluated the `react.shared-subset.development.js` module where React patches the `fetch` function. The problem is that when re-evaluating a route as part of hot reloading, we were patching over the previously patched `fetch` function. 
The result of this operation meant that we were keeping a reference to the context of the previous `fetch` and thus to the previous route context, thus creating a memory leak, since we only needed the new context.

## Test plan

Checked manually the heap snapshots of a test app.

## Bug

- [ ] Related issues linked using `fixes #number`
- [ ] Integration tests added
- [ ] Errors have a helpful link attached, see [`contributing.md`](https://github.com/vercel/next.js/blob/canary/contributing.md)

## Feature

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

## Documentation / Examples

- [ ] Make sure the linting passes by running `pnpm build && pnpm lint`
- [ ] The "examples guidelines" are followed from [our contributing doc](https://github.com/vercel/next.js/blob/canary/contributing/examples/adding-examples.md)
2022-12-08 19:50:46 +00:00

110 lines
3.4 KiB
TypeScript

import type { webpack } from 'next/dist/compiled/webpack/webpack'
import { clearModuleContext } from '../../../server/web/sandbox'
import { realpathSync } from 'fs'
import path from 'path'
import isError from '../../../lib/is-error'
type Compiler = webpack.Compiler
type WebpackPluginInstance = webpack.WebpackPluginInstance
const originModules = [
require.resolve('../../../server/require'),
require.resolve('../../../server/load-components'),
require.resolve('../../../server/next-server'),
require.resolve('../../../compiled/react-server-dom-webpack/client'),
]
const RUNTIME_NAMES = ['webpack-runtime', 'webpack-api-runtime']
function deleteCache(filePath: string) {
try {
filePath = realpathSync(filePath)
} catch (e) {
if (isError(e) && e.code !== 'ENOENT') throw e
}
const mod = require.cache[filePath]
if (mod) {
// remove the child reference from the originModules
for (const originModule of originModules) {
const parent = require.cache[originModule]
if (parent) {
const idx = parent.children.indexOf(mod)
if (idx >= 0) parent.children.splice(idx, 1)
}
}
// remove parent references from external modules
for (const child of mod.children) {
child.parent = null
}
delete require.cache[filePath]
return true
}
return false
}
const PLUGIN_NAME = 'NextJsRequireCacheHotReloader'
// This plugin flushes require.cache after emitting the files. Providing 'hot reloading' of server files.
export class NextJsRequireCacheHotReloader implements WebpackPluginInstance {
prevAssets: any = null
hasServerComponents: boolean
constructor(opts: { hasServerComponents: boolean }) {
this.hasServerComponents = opts.hasServerComponents
}
apply(compiler: Compiler) {
compiler.hooks.assetEmitted.tap(
PLUGIN_NAME,
(_file, { targetPath, content }) => {
deleteCache(targetPath)
clearModuleContext(targetPath, content.toString('utf-8'))
}
)
compiler.hooks.afterEmit.tap(PLUGIN_NAME, (compilation) => {
RUNTIME_NAMES.forEach((name) => {
const runtimeChunkPath = path.join(
compilation.outputOptions.path!,
`${name}.js`
)
deleteCache(runtimeChunkPath)
})
let hasAppPath = false
// we need to make sure to clear all server entries from cache
// since they can have a stale webpack-runtime cache
// which needs to always be in-sync
const entries = [...compilation.entries.keys()].filter((entry) => {
const isAppPath = entry.toString().startsWith('app/')
hasAppPath = hasAppPath || isAppPath
return entry.toString().startsWith('pages/') || isAppPath
})
if (hasAppPath) {
// ensure we reset the cache for sc_server components
// loaded via react-server-dom-webpack
const reactServerDomModId = require.resolve(
'next/dist/compiled/react-server-dom-webpack/client'
)
const reactServerDomMod = require.cache[reactServerDomModId]
if (reactServerDomMod) {
for (const child of reactServerDomMod.children) {
child.parent = null
delete require.cache[child.id]
}
}
delete require.cache[reactServerDomModId]
}
entries.forEach((page) => {
const outputPath = path.join(
compilation.outputOptions.path!,
page + '.js'
)
deleteCache(outputPath)
})
})
}
}