Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions src/runtime/server/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -220,6 +220,7 @@ bitflags::bitflags! {
const DEINIT_SCHEDULED = 1 << 0;
const TERMINATED = 1 << 1;
const HAS_HANDLED_ALL_CLOSED_PROMISE = 1 << 2;
const HANDLERS_RELEASED = 1 << 3;
}
}

Expand Down Expand Up @@ -1667,6 +1668,24 @@ impl<const SSL: bool, const DEBUG: bool> NewServer<SSL, DEBUG> {
if let Some(ws) = self.config.websocket.as_mut() {
ws.handler.app = None;
}
// No request or upgrade can reach the user's handler callbacks once
// the listener is gone, the in-flight count is zero, and there are
// no live websockets. Release their `Strong` handles now: a handler
// defined in a scope that closes over the JS `Server` value
// otherwise forms a native↔JS cycle (box → Strong(handler) →
// lexical environment → Server wrapper → m_ctx → box) that the GC
// cannot see through, so the wrapper never finalizes and the box is
// never freed.
if !self.flags.contains(ServerFlags::HANDLERS_RELEASED) {
self.flags.insert(ServerFlags::HANDLERS_RELEASED);
self.config.on_request = None;
self.config.on_node_http_request = None;
self.config.on_error = None;
self.on_clienterror.deinit();
if let Some(ws) = self.config.websocket.as_mut() {
Comment thread
robobun marked this conversation as resolved.
Outdated
ws.handler.unprotect();
Comment thread
robobun marked this conversation as resolved.
Comment thread
robobun marked this conversation as resolved.
}
}
self.unref();

// Detach DevServer. This is needed because there are aggressive
Expand Down
45 changes: 43 additions & 2 deletions test/bake/fixtures/deinitialization/test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { getDevServerDeinitCount } from "bun:internal-for-testing";
import html from "./index.html";
import { expect, test } from "bun:test";
import { fullGC } from "bun:jsc";
import { afterAll, expect, test } from "bun:test";
import { fullGC, heapStats } from "bun:jsc";

expect(process.cwd()).toBe(import.meta.dir);

Expand Down Expand Up @@ -72,6 +72,11 @@ async function run({ closeActiveConnections = false, sendAnyRequests = true, web
}

await main();
// The closure assigned to `globalThis.callback` inside `main()` captures
// `server`; left in place it roots the JS Server wrapper through every GC
// below, so the wrapper never finalizes and the native NewServer box (and
// everything its config owns) is still live at process exit.
globalThis.callback = undefined;
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Outdated

if (closeActiveConnections) {
await promise;
Expand Down Expand Up @@ -109,6 +114,42 @@ const cases = [
{ closeActiveConnections: true, sendAnyRequests: false, websocket: 8 },
];

function liveServerWrappers() {
const c = heapStats().objectTypeCounts;
return (c.HTTPServer ?? 0) + (c.DebugHTTPServer ?? 0) + (c.HTTPSServer ?? 0) + (c.DebugHTTPSServer ?? 0);
}
// `objectTypeCounts` includes the (lazily created) prototype object once the
// first server has been constructed. Create-and-stop one trivial server here
// so the prototype is materialized but the instance is freed; the afterAll
// check then asserts every dev-server case returns to this baseline (i.e. zero
// live wrapper instances and the native boxes were actually freed).
let serverWrapperBaseline: number;
test("baseline: stopped server wrapper collects", async () => {
await (async () => {
const server = Bun.serve({ port: 0, fetch: () => new Response("ok") });
server.stop(true);
})();
for (let i = 0; i < 10 && liveServerWrappers() > 1; i++) {
Comment thread
robobun marked this conversation as resolved.
Outdated
Bun.gc(true);
fullGC();
await new Promise(resolve => setTimeout(resolve, 100));
}
serverWrapperBaseline = liveServerWrappers();
expect(serverWrapperBaseline).toBeLessThanOrEqual(1);
});

afterAll(async () => {
// Drain any deferred deinit task scheduled during the final case's GC, then
// assert every JS Server wrapper has actually been collected — i.e. the
// native NewServer boxes are freed, not just the embedded dev servers.
for (let i = 0; i < 10 && liveServerWrappers() > serverWrapperBaseline; i++) {
Comment thread
robobun marked this conversation as resolved.
Outdated
Bun.gc(true);
fullGC();
await new Promise(resolve => setTimeout(resolve, 100));
}
expect(liveServerWrappers()).toBe(serverWrapperBaseline);
});

for (const { closeActiveConnections, sendAnyRequests, websocket } of cases) {
test(
"flags: " +
Expand Down
Loading