holepunchto / hyperdht

The DHT powering Hyperswarm
https://docs.holepunch.to
MIT License
323 stars 46 forks source link

Bugfix: server lifecycle when closing during listen #155

Closed HDegroote closed 9 months ago

HDegroote commented 9 months ago

This fixes a catastrophic bug when destroying a server while listen() is being called, but before the server added itself to the DHT's server-set. This resulted in the _background https://github.com/holepunchto/hyperdht/blob/55536eb95e5dfbef13bbe68f00adb1f6b1a9557a/lib/announcer.js#L96 function of the announcer entering an infinite loop hogging the event loop due to continuously throwing and catching DHT_CLOSED errors. To reproduce, you can run the newly added test on the original code.

The fix is to add the server to the DHT's server-set as soon as listen() is called, ensuring its close function is always called when the DHT gets destroyed.

If there originally was a reason not to do immediately add a new server to the DHT's server-set, I can instead look into reworking the lifecycle a bit more in depth.