Skip to content

Commit

Permalink
fix: unhandled promise rejection when finding gateway (#2884)
Browse files Browse the repository at this point in the history
Defer creating the last public ip promise until it's guaranteed to
have a a listener for promise rejections.

Fixes ipfs/helia#702
  • Loading branch information
achingbrain authored Dec 10, 2024
1 parent e7133ee commit 127abe2
Showing 1 changed file with 10 additions and 6 deletions.
16 changes: 10 additions & 6 deletions packages/upnp-nat/src/check-external-address.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ class ExternalAddressChecker implements ExternalAddress, Startable {
private readonly addressManager: AddressManager
private started: boolean
private lastPublicIp?: string
private readonly lastPublicIpPromise: DeferredPromise<string>
private lastPublicIpPromise?: DeferredPromise<string>
private readonly check: RepeatingTask
private readonly onExternalAddressChange?: (newExternalAddress: string) => void

Expand All @@ -46,8 +46,6 @@ class ExternalAddressChecker implements ExternalAddress, Startable {

this.checkExternalAddress = this.checkExternalAddress.bind(this)

this.lastPublicIpPromise = pDefer()

this.check = repeatingTask(this.checkExternalAddress, init.interval ?? 30000, {
timeout: init.timeout ?? 10000,
runImmediately: true
Expand Down Expand Up @@ -76,7 +74,13 @@ class ExternalAddressChecker implements ExternalAddress, Startable {
throw new NotStartedError('Not started yet')
}

return this.lastPublicIp ?? raceSignal(this.lastPublicIpPromise.promise, options?.signal, {
if (this.lastPublicIp != null) {
return this.lastPublicIp
}

this.lastPublicIpPromise = pDefer()

return raceSignal(this.lastPublicIpPromise.promise, options?.signal, {
errorMessage: 'Requesting the public IP from the network gateway timed out - UPnP may not be enabled'
})
}
Expand All @@ -94,7 +98,7 @@ class ExternalAddressChecker implements ExternalAddress, Startable {
}

this.lastPublicIp = externalAddress
this.lastPublicIpPromise.resolve(externalAddress)
this.lastPublicIpPromise?.resolve(externalAddress)
} catch (err: any) {
this.log.error('could not resolve external address - %e', err)

Expand All @@ -103,7 +107,7 @@ class ExternalAddressChecker implements ExternalAddress, Startable {
return
}

this.lastPublicIpPromise.reject(err)
this.lastPublicIpPromise?.reject(err)
}
}
}
Expand Down

0 comments on commit 127abe2

Please sign in to comment.