Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(ext/node): delay accept() call 2 ticks in net.Server#listen #25481

Merged
merged 2 commits into from
Sep 8, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
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
10 changes: 9 additions & 1 deletion ext/node/polyfills/internal_binding/tcp_wrap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ import {
INITIAL_ACCEPT_BACKOFF_DELAY,
MAX_ACCEPT_BACKOFF_DELAY,
} from "ext:deno_node/internal_binding/_listen.ts";
import { nextTick } from "ext:deno_node/_next_tick.ts";

/** The type of TCP socket. */
enum socketType {
Expand Down Expand Up @@ -228,7 +229,14 @@ export class TCP extends ConnectionWrap {
this.#port = address.port;

this.#listener = listener;
this.#accept();

// TODO(kt3k): Delays the accept() call 2 ticks. Deno.Listener can't be closed
// synchronously when accept() is called. By delaying the accept() call,
// the user can close the server synchronously in the callback of listen().
// This workaround enables `npm:detect-port` to work correctly.
// Remove these nextTick calls when the below issue resolved:
// https://github.com/denoland/deno/issues/25480
nextTick(nextTick, () => this.#accept());

return 0;
}
Expand Down
19 changes: 19 additions & 0 deletions tests/unit_node/net_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -228,3 +228,22 @@ Deno.test("[node/net] BlockList doesn't leak resources", () => {
blockList.addAddress("1.1.1.1");
assert(blockList.check("1.1.1.1"));
});

Deno.test("[node/net] net.Server can listen on the same port immediately after it's closed", async () => {
const serverClosed = Promise.withResolvers<void>();
const server = net.createServer();
server.on("error", (e) => {
console.error(e);
});
server.listen(0, () => {
// deno-lint-ignore no-explicit-any
const { port } = server.address() as any;
server.close();
server.listen(port, () => {
server.close(() => {
serverClosed.resolve();
});
});
});
await serverClosed.promise;
});