Skip to content

Commit

Permalink
fix: unhandled promise rejection when finding gateway
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 committed Dec 10, 2024
1 parent e7133ee commit a84bf82
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()

Check warning on line 82 in packages/upnp-nat/src/check-external-address.ts

View check run for this annotation

Codecov / codecov/patch

packages/upnp-nat/src/check-external-address.ts#L80-L82

Added lines #L80 - L82 were not covered by tests
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)

Check warning on line 110 in packages/upnp-nat/src/check-external-address.ts

View check run for this annotation

Codecov / codecov/patch

packages/upnp-nat/src/check-external-address.ts#L110

Added line #L110 was not covered by tests
}
}
}
Expand Down

0 comments on commit a84bf82

Please sign in to comment.