Skip to content

Commit

Permalink
fix(net) signal should destroy the connection and propagate the error…
Browse files Browse the repository at this point in the history
… properly (#15624)
  • Loading branch information
cirospaciari authored Dec 7, 2024
1 parent fcca2cc commit c1eba58
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 2 deletions.
16 changes: 14 additions & 2 deletions src/js/node/net.ts
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,15 @@ function finishSocket(hasError) {
detachSocket(this);
this.emit("close", hasError);
}

function destroyNT(self, err) {
self.destroy(err);
}
function destroyWhenAborted(err) {
if (!this.destroyed) {
this.destroy(err.target.reason);
}
}
// Provide a better error message when we call end() as a result
// of the other side sending a FIN. The standard 'write after end'
// is overly vague, and makes it seem like the user's code is to blame.
Expand Down Expand Up @@ -479,9 +488,12 @@ const Socket = (function (InternalSocket) {
},
};
}

if (signal) {
signal.addEventListener("abort", () => this.destroy());
if (signal.aborted) {
process.nextTick(destroyNT, this, signal.reason);
} else {
signal.addEventListener("abort", destroyWhenAborted.bind(this));
}
}
}

Expand Down
33 changes: 33 additions & 0 deletions test/js/node/net/node-net.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -563,6 +563,39 @@ it("should not hang after destroy", async () => {
}
});

it("should trigger error when aborted even if connection failed #13126", async () => {
const signal = AbortSignal.timeout(100);
const socket = createConnection({
host: "example.com",
port: 999,
signal: signal,
});
const { promise, resolve, reject } = Promise.withResolvers();

socket.on("connect", reject);
socket.on("error", resolve);

const err = (await promise) as Error;
expect(err.name).toBe("TimeoutError");
});

it("should trigger error when aborted even if connection failed, and the signal is already aborted #13126", async () => {
const signal = AbortSignal.timeout(1);
await Bun.sleep(10);
const socket = createConnection({
host: "example.com",
port: 999,
signal: signal,
});
const { promise, resolve, reject } = Promise.withResolvers();

socket.on("connect", reject);
socket.on("error", resolve);

const err = (await promise) as Error;
expect(err.name).toBe("TimeoutError");
});

it.if(isWindows)(
"should work with named pipes",
async () => {
Expand Down

0 comments on commit c1eba58

Please sign in to comment.