fix(net) signal should destroy the connection and propagate the error properly (#15624)

This commit is contained in:
Ciro Spaciari
2024-12-06 16:10:33 -08:00
committed by GitHub
parent fcca2cc398
commit c1eba5886f
2 changed files with 47 additions and 2 deletions

View File

@@ -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.
@@ -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));
}
}
}

View File

@@ -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 () => {