From ae75570c852fa9bfe00910dca1c219fa585dcb83 Mon Sep 17 00:00:00 2001 From: Alex Potsides Date: Mon, 6 Jan 2025 16:52:00 +0100 Subject: [PATCH] fix: return empty address list during listen operation (#2904) If `getAddrs` is called on a WS listener after `.listen` has been called but before any socket(s) have opened, return an empty list instead of throwing. Fixes #2902 --- packages/transport-websockets/src/listener.ts | 10 +++++----- packages/transport-websockets/test/node.ts | 16 ++++++++++++++++ 2 files changed, 21 insertions(+), 5 deletions(-) diff --git a/packages/transport-websockets/src/listener.ts b/packages/transport-websockets/src/listener.ts index 25d18835b3..cbb4913a91 100644 --- a/packages/transport-websockets/src/listener.ts +++ b/packages/transport-websockets/src/listener.ts @@ -341,20 +341,20 @@ export class WebSocketListener extends TypedEventEmitter impleme } getAddrs (): Multiaddr[] { + if (this.listeningMultiaddr == null) { + throw new Error('Listener is not ready yet') + } + const address = this.server.address() if (address == null) { - throw new Error('Listener is not ready yet') + return [] } if (typeof address === 'string') { throw new Error('Wrong address type received - expected AddressInfo, got string - are you trying to listen on a unix socket?') } - if (this.listeningMultiaddr == null) { - throw new Error('Listener is not ready yet') - } - const options = this.listeningMultiaddr.toOptions() const multiaddrs: Multiaddr[] = [] diff --git a/packages/transport-websockets/test/node.ts b/packages/transport-websockets/test/node.ts index 6baae5a67d..82b255e2cc 100644 --- a/packages/transport-websockets/test/node.ts +++ b/packages/transport-websockets/test/node.ts @@ -73,6 +73,22 @@ describe('listen', () => { void listener.listen(ma) }) + it('should return an empty address list when `getAddrs` called before listening has finished', async () => { + listener = ws.createListener({ upgrader }) + + void listener.listen(ma) + + // call getAddrs before sockets have opened + expect(listener.getAddrs()).to.be.empty() + }) + + it('should throw when `.getAddrs` called before `.listen`', async () => { + listener = ws.createListener({ upgrader }) + + // call getAddrs before sockets have opened + expect(() => listener.getAddrs()).to.throw(/not ready/) + }) + it('should error on starting two listeners on same address', async () => { listener = ws.createListener({ upgrader }) const dumbServer = http.createServer()