From 48c31b4825797df5e8840ee699c5b96b280aec14 Mon Sep 17 00:00:00 2001 From: Hornwitser Date: Mon, 5 Feb 2024 23:36:43 +0100 Subject: [PATCH] Fix unhandled rejection on disconnect (#582) If a link is closed while the prepareDisconnect action is in progress the link will still try to signal the disconnect ready over the socket when the prepareDisconnect action completes, which throws due to the socket no longer being present. This error is not caught due to the catch happening before the finally on the promise and triggers an unhandled rejection. Fix by rearranging the finally to come before the catch on the promise so that errors are always handled, and checking that the link still has a session before attempting to send the disconnect ready signal. --- CHANGELOG.md | 1 + packages/lib/src/link/link.ts | 17 ++++++++--------- test/mock.js | 1 + 3 files changed, 10 insertions(+), 9 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4275137c..68e772fe 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,7 @@ ## Changes - Fixed an unhandled error in Subspace Storage crashing the host. +- Fixed an unhandled rejection in disconnect logic crashing the host. ## Version 2.0.0-alpha.16 diff --git a/packages/lib/src/link/link.ts b/packages/lib/src/link/link.ts index e3a746c0..0f8f2d32 100644 --- a/packages/lib/src/link/link.ts +++ b/packages/lib/src/link/link.ts @@ -126,16 +126,15 @@ export class Link { }); connector.on("disconnectPrepare", () => { - this.prepareDisconnect().catch( - err => { - logger.error(`Unexpected error preparing disconnect:\n${err.stack}`); + this.prepareDisconnect().finally(() => { + // Only WebSocket connectors issue disconnection events. + const webSocketConnector = this.connector as WebSocketBaseConnector; + if (webSocketConnector.hasSession) { + webSocketConnector.sendDisconnectReady(); } - ).finally( - () => { - // Only WebSocket connectors issue disconnection events. - (this.connector as WebSocketBaseConnector).sendDisconnectReady(); - }, - ); + }).catch(err => { + logger.error(`Unexpected error preparing disconnect:\n${err.stack}`); + }); }); connector.on("invalidate", () => { diff --git a/test/mock.js b/test/mock.js index 171c5923..4d2a8564 100644 --- a/test/mock.js +++ b/test/mock.js @@ -73,6 +73,7 @@ class MockConnector extends lib.BaseConnector { super(src, dst); this.connected = true; + this.hasSession = true; this.sentMessages = []; }