Fix memory leak in dev server

This commit is contained in:
2026-10-16 14:25:18 +01:00
parent 3d0771f2d0
commit 5dc783fe97
36 changed files with 642 additions and 406 deletions
+6
View File
@@ -0,0 +1,6 @@
/**
* Disposes the hydration and SSR esbuild contexts, releasing the incremental
* build state esbuild keeps in memory for them. The bundlers re-create the
* contexts on their next run.
*/
export default function disposeBundlerContexts(): Promise<void>;
+17
View File
@@ -0,0 +1,17 @@
/**
* Disposes the hydration and SSR esbuild contexts, releasing the incremental
* build state esbuild keeps in memory for them. The bundlers re-create the
* contexts on their next run.
*/
export default async function disposeBundlerContexts() {
try {
await global.BUNEXT_BUNDLER_CTX?.dispose();
}
catch (error) { }
global.BUNEXT_BUNDLER_CTX = undefined;
try {
await global.BUNEXT_SSR_BUNDLER_CTX?.dispose();
}
catch (error) { }
global.BUNEXT_SSR_BUNDLER_CTX = undefined;
}
+4
View File
@@ -8,6 +8,7 @@ import grabRootFilePath from "../server/web-pages/grab-root-file-path";
import ssrVirtualFilesPlugin from "./plugins/ssr-virtual-files-plugin";
import ssrCTXArtifactTracker from "./plugins/ssr-ctx-artifact-tracker";
import cleanupArtifacts from "../server/cleanup-artifacts";
import { evictDeletedModules } from "../../utils/import-fresh";
import { writeFileSync } from "fs";
import path from "path";
import { log } from "../../utils/log";
@@ -165,6 +166,9 @@ async function doSSRRebuild(params) {
global.BUNEXT_SSR_BUNDLER_CTX_DISPOSED = false;
global.BUNEXT_BUILD_FAILED = false;
await cleanupArtifacts({ paradigm: "ssr" });
// esbuild has now replaced superseded outputs on disk; release the
// ones the server already imported.
evictDeletedModules(BUNX_CWD_MODULE_CACHE_DIR);
}
catch (error) {
global.BUNEXT_SSR_BUNDLER_CTX_DISPOSED = true;
+4
View File
@@ -8,6 +8,7 @@ import serverPostBuildFn from "./server/server-post-build-fn";
import reactModulesBundler from "./bundler/react-modules-bundler";
import grabConstants from "../utils/grab-constants";
import watcherEsbuildCTX from "./server/watcher-esbuild-ctx";
import disposeBundlerContexts from "./bundler/dispose-bundler-contexts";
import { readFileSync } from "fs";
const dirNames = grabDirNames();
const { PAGES_DIR, BUNDLER_CTX_MAP_JSON, SSR_BUNDLER_CTX_MAP_JSON } = dirNames;
@@ -86,6 +87,9 @@ export default async function bunextInit(params) {
else {
log.build(`Building Modules ...`);
await allPagesESBuildContextBundler({ start: true });
// The server only needs the artifact maps; don't keep
// esbuild's build state alive for the rest of the process.
await disposeBundlerContexts();
}
cron();
}
+7 -3
View File
@@ -16,15 +16,19 @@ const HMR_RETRY_COOLDOWN_MS = 5000;
let lastHmrRetryTime = 0;
export default async function bunextRequestHandler({ req: initial_req, server, }) {
const is_dev = isDevelopment();
let req = initial_req.clone();
const middleware = global.BUNEXT_CONSTANTS.config?.middleware;
// Middleware may consume `initial_req`'s body, so it gets its own copy.
// Cloning tees the body stream and buffers whatever one side doesn't
// read, so only pay for it when middleware is configured.
let req = middleware ? initial_req.clone() : initial_req;
try {
let url = new URL(req.url);
if (checkExcludedPatterns({ path: url.pathname })) {
return Response.json({ success: false, msg: `Invalid Path` }, { status: 404 });
}
let response = undefined;
if (global.BUNEXT_CONSTANTS.config?.middleware) {
const middleware_res = await global.BUNEXT_CONSTANTS.config.middleware({
if (middleware) {
const middleware_res = await middleware({
req: initial_req,
url,
});
+8 -7
View File
@@ -3,6 +3,8 @@ import allPagesESBuildContextBundler from "../bundler/all-pages-esbuild-context-
import serverPostBuildFn from "./server-post-build-fn";
import { restartWatcher } from "./watcher-esbuild-ctx";
import { logBuildErrorsOnce } from "../../utils/build-error-log";
import disposeBundlerContexts from "../bundler/dispose-bundler-contexts";
import isDevelopment from "../../utils/is-development";
// Single-flight: error recovery paths (grab-page-component retries, the
// watcher, post-build HMR pushes) all call fullRebuild, and each rebuild
// triggers serverPostBuildFn which can re-enter error handling. Without this
@@ -33,18 +35,17 @@ async function doFullRebuild(params) {
log.watch(msg);
}
global.BUNEXT_ROUTER.reload();
try {
await global.BUNEXT_BUNDLER_CTX?.dispose();
global.BUNEXT_BUNDLER_CTX = undefined;
await global.BUNEXT_SSR_BUNDLER_CTX?.dispose();
global.BUNEXT_SSR_BUNDLER_CTX = undefined;
}
catch (error) { }
await disposeBundlerContexts();
await allPagesESBuildContextBundler({
post_build_fn: async (params) => {
await serverPostBuildFn(params);
},
});
// Production never rebuilds incrementally; don't keep esbuild's
// build state alive for the rest of the process.
if (!isDevelopment()) {
await disposeBundlerContexts();
}
}
catch (error) {
logBuildErrorsOnce([{ text: error?.message || String(error) }], (line) => log.error(line));
+3 -6
View File
@@ -8,6 +8,7 @@ import path from "path";
import grabDirNames from "../../utils/grab-dir-names";
import grabRelativePath from "../../utils/grab-relative-path";
import { RequestBodyTooLargeError } from "../../utils/read-request-body";
import importFresh from "../../utils/import-fresh";
const { ROOT_DIR } = grabDirNames();
export default async function ({ req }) {
try {
@@ -29,18 +30,14 @@ export default async function ({ req }) {
});
}
let module;
const now = Date.now();
const relative_match_path = grabRelativePath(match.filePath);
if (is_dev &&
global.BUNEXT_SSR_BUNDLER_CTX_MAP?.[relative_match_path]?.path) {
const target_import = path.join(ROOT_DIR, global.BUNEXT_SSR_BUNDLER_CTX_MAP[relative_match_path].path);
module = await import(`${target_import}?t=${now}`);
module = await importFresh(target_import);
}
else {
const import_path = is_dev
? `${match.filePath}?t=${now}`
: match.filePath;
module = await import(import_path);
module = await importFresh(match.filePath);
}
const config = module.config;
const maxBodyBytes = config?.max_request_body_mb
+4 -10
View File
@@ -2,7 +2,7 @@ import _ from "lodash";
import { log } from "../../utils/log";
import serverParamsGen from "./server-params-gen";
import isDevelopment from "../../utils/is-development";
import { restartWatcher, watcherRestartAvailable, } from "./watcher-esbuild-ctx";
import { watcherWatchdogTick } from "./watcher-esbuild-ctx";
export default async function startServer() {
const serverParams = await serverParamsGen();
const server = Bun.serve(serverParams);
@@ -10,15 +10,9 @@ export default async function startServer() {
global.BUNEXT_SERVER = server;
log.server(`http://${server.hostname}:${server.port}`);
if (is_dev) {
// Watchdog: periodically re-create the FS watcher in case it went
// stale and stopped receiving events. Skipped while a recent restart
// (e.g. by fullRebuild) is still fresh so the watcher isn't churned
// twice in a row.
setInterval(() => {
if (watcherRestartAvailable()) {
restartWatcher();
}
}, 5000);
// Watchdog: re-create the FS watcher if it went stale and stopped
// receiving events.
setInterval(watcherWatchdogTick, 5000);
}
return server;
}
+5 -3
View File
@@ -5,10 +5,12 @@
*/
export declare function restartWatcher(): void;
/**
* True when the watcher was last (re)created long enough ago that the
* watchdog should consider re-creating it again.
* Called periodically by the dev server. Re-creates the watcher only when it
* failed to report the probe written on the previous tick, i.e. when it went
* stale. A healthy watcher is left alone: re-creating it rescans the whole
* project tree.
*/
export declare function watcherRestartAvailable(): boolean;
export declare function watcherWatchdogTick(): void;
export default function watcherEsbuildCTX(params?: {
pages_snapshot?: string;
}): Promise<void>;
+58 -19
View File
@@ -1,6 +1,6 @@
import chokidar from "chokidar";
import path from "path";
import { existsSync } from "fs";
import { existsSync, mkdirSync, writeFileSync } from "fs";
import grabDirNames from "../../utils/grab-dir-names";
import fullRebuild from "./full-rebuild";
import { AppData } from "../../data/app-data";
@@ -10,10 +10,18 @@ import grabAllPages from "../../utils/grab-all-pages";
import serverPostBuildFn from "./server-post-build-fn";
import { log } from "../../utils/log";
import { logBuildErrorsOnce } from "../../utils/build-error-log";
const { ROOT_DIR, BUNX_BUNDLER_ERROR_EXIT_FILE } = grabDirNames();
// Tracks the last watcher re-creation so the 5s watchdog in start-server
// doesn't fight fullRebuild (which also restarts the watcher after a rebuild).
const { ROOT_DIR, BUNX_CWD_DIR, BUNX_BUNDLER_ERROR_EXIT_FILE } = grabDirNames();
// The watchdog writes this file and expects the watcher to report it. It
// sits under `.bunext` (otherwise ignored), so only this path is watched.
const WATCH_PROBE_DIR = path.join(BUNX_CWD_DIR, "watch-probe");
const WATCH_PROBE_FILE = path.join(WATCH_PROBE_DIR, "probe");
// Dedupes near-simultaneous restarts (fullRebuild, watchdog).
let last_watcher_restart = 0;
// The current watcher finished its initial scan; probes written before
// that may not produce events.
let watcher_ready = false;
// A probe was written and the watcher hasn't reported it yet.
let probe_pending = false;
/**
* Closes and re-creates the FS watcher. Deduped: callers that restart the
* watcher around the same time (fullRebuild, reloadWatcher, watchdog) only
@@ -48,11 +56,27 @@ function grabPagesSnapshot() {
}
}
/**
* True when the watcher was last (re)created long enough ago that the
* watchdog should consider re-creating it again.
* Called periodically by the dev server. Re-creates the watcher only when it
* failed to report the probe written on the previous tick, i.e. when it went
* stale. A healthy watcher is left alone: re-creating it rescans the whole
* project tree.
*/
export function watcherRestartAvailable() {
return Date.now() - last_watcher_restart > 6000;
export function watcherWatchdogTick() {
if (!global.BUNEXT_PAGES_SRC_WATCHER || !watcher_ready)
return;
if (probe_pending) {
restartWatcher();
return;
}
try {
mkdirSync(WATCH_PROBE_DIR, { recursive: true });
writeFileSync(WATCH_PROBE_FILE, String(Date.now()));
probe_pending = true;
}
catch (error) { }
}
function isWatchProbePath(p) {
return (p === WATCH_PROBE_FILE || p === WATCH_PROBE_DIR || p === BUNX_CWD_DIR);
}
const TARGET_FILES_MATCH = /\.(tsx?|jsx?|css)$/;
// Rebuild coalescing: editors emit bursts of events per save (change +
@@ -170,10 +194,10 @@ function isPathExcluded(filename, full_file_path) {
// install watches (and deliver events) for trees the bundler never reads.
function buildIgnoredPatterns() {
const ignored = [
/(^|[\/\\])\../,
(p) => !isWatchProbePath(p) && /(^|[\/\\])\../.test(p),
/(^|[\/\\])node_modules([\/\\]|$)/,
/(^|[\/\\])public([\/\\]|$)/,
/(^|[\/\\])\.bunext([\/\\]|$)/,
(p) => !isWatchProbePath(p) && /(^|[\/\\])\.bunext([\/\\]|$)/.test(p),
/(^|[\/\\])\.git([\/\\]|$)/,
/(^|[\/\\])dist([\/\\]|$)/,
/bun\.lockb$/,
@@ -195,6 +219,12 @@ function buildIgnoredPatterns() {
return ignored;
}
export default async function watcherEsbuildCTX(params) {
try {
mkdirSync(WATCH_PROBE_DIR, { recursive: true });
}
catch (error) { }
watcher_ready = false;
probe_pending = false;
const pages_src_watcher = chokidar.watch(ROOT_DIR, {
ignored: buildIgnoredPatterns(),
persistent: true,
@@ -202,18 +232,27 @@ export default async function watcherEsbuildCTX(params) {
});
watcherHandlers(pages_src_watcher, (event, filePath) => handleEvent(event, filePath));
const pages_snapshot = params?.pages_snapshot;
if (pages_snapshot !== undefined) {
pages_src_watcher.on("ready", () => {
const current = grabPagesSnapshot();
if (current !== undefined && current !== pages_snapshot) {
pending_structural = true;
scheduleRebuild();
}
});
}
pages_src_watcher.on("ready", () => {
if (global.BUNEXT_PAGES_SRC_WATCHER === pages_src_watcher) {
watcher_ready = true;
}
if (pages_snapshot === undefined)
return;
const current = grabPagesSnapshot();
if (current !== undefined && current !== pages_snapshot) {
pending_structural = true;
scheduleRebuild();
}
});
global.BUNEXT_PAGES_SRC_WATCHER = pages_src_watcher;
}
function handleEvent(event, filePath) {
if (isWatchProbePath(filePath)) {
if (filePath === WATCH_PROBE_FILE) {
probe_pending = false;
}
return;
}
try {
const filename = path.relative(ROOT_DIR, filePath);
const full_file_path = filePath;
+15 -1
View File
@@ -77,8 +77,16 @@ export default async function genWebHTML({ component: Main, pageProps, bundledMa
let htmlBody;
let render_error;
let has_render_error = false;
const render_timeout_ms = global.BUNEXT_CONFIG.ssr_render_timeout_ms ||
AppData["DefaultSSRRenderTimeoutMs"];
// Without a deadline, a Suspense boundary that never settles keeps the
// request (and its whole render tree) alive forever. The timer is
// cleared once the render ends so finished requests don't linger.
const render_abort = new AbortController();
const render_timeout = setTimeout(() => render_abort.abort(new RenderTimeoutError(`Page render timed out after ${render_timeout_ms}ms`)), render_timeout_ms);
try {
const stream = await renderToReadableStream(final_component, {
signal: render_abort.signal,
onError(error) {
if (error?.message?.includes('unique "key" prop'))
return;
@@ -86,12 +94,16 @@ export default async function genWebHTML({ component: Main, pageProps, bundledMa
has_render_error = true;
render_error = error;
}
original_console.error(error);
// A timeout has no useful stack; it's logged upstream.
if (!(error instanceof RenderTimeoutError)) {
original_console.error(error);
}
},
});
htmlBody = await new Response(stream).text();
}
finally {
clearTimeout(render_timeout);
restoreConsole();
}
// A component crash during SSR must surface as a proper error (handled
@@ -103,6 +115,8 @@ export default async function genWebHTML({ component: Main, pageProps, bundledMa
html += htmlBody;
return html;
}
class RenderTimeoutError extends Error {
}
let original_console = console;
let silenced_renders = 0;
/**
@@ -1,6 +0,0 @@
type Params = {
file_path: string;
out_file?: string;
};
export default function grabFilePathModule<T extends any = any>({ file_path, out_file, }: Params): Promise<T>;
export {};
@@ -1,30 +0,0 @@
import isDevelopment from "../../../utils/is-development";
import * as esbuild from "esbuild";
import grabDirNames from "../../../utils/grab-dir-names";
import path from "path";
import tailwindEsbuildPlugin from "./tailwind-esbuild-plugin";
export default async function grabFilePathModule({ file_path, out_file, }) {
const dev = isDevelopment();
const { BUNX_CWD_MODULE_CACHE_DIR } = grabDirNames();
const target_cache_file_path = out_file ||
path.join(BUNX_CWD_MODULE_CACHE_DIR, `${path.basename(file_path)}.js`);
await esbuild.build({
entryPoints: [file_path],
bundle: true,
format: "esm",
target: "es2020",
platform: "node",
// external: ["react", "react-dom"],
minify: true,
define: {
"process.env.NODE_ENV": JSON.stringify(dev ? "development" : "production"),
},
metafile: true,
plugins: [tailwindEsbuildPlugin],
jsx: "automatic",
outfile: target_cache_file_path,
});
// Loader.registry.delete(target_cache_file_path);
const module = await import(`${target_cache_file_path}?t=${Date.now()}`);
return module;
}