Skip to content

Commit

Permalink
fix: return empty address list during listen operation (#2904)
Browse files Browse the repository at this point in the history
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
  • Loading branch information
achingbrain authored Jan 6, 2025
1 parent 7caee9f commit ae75570
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 5 deletions.
10 changes: 5 additions & 5 deletions packages/transport-websockets/src/listener.ts
Original file line number Diff line number Diff line change
Expand Up @@ -341,20 +341,20 @@ export class WebSocketListener extends TypedEventEmitter<ListenerEvents> 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[] = []

Expand Down
16 changes: 16 additions & 0 deletions packages/transport-websockets/test/node.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down

0 comments on commit ae75570

Please sign in to comment.