threefoldtech/mycelium

Keep track of background tasks and clean them up when the spawning struct is dropped

Opened this issue · 0 comments

We are spawning a bunch of (background) tasks in the code (router and peer manager mostly) which essentially run forever (some could exit if the channel they reach from gets closed, but that generally won't happen as we keep the channels on the same struct). These tasks also keep a copy of the containing struct locally to access it, either through an Arc or a deep copy.

We'll need a way to track these background tasks and abort them when required. Keeping track can be done by shoving them in an Arc<Mutex<Vec>> (since this is strictly for cancelling the tasks, we track the aborthandle instead of the joinhandle as that more clearly describes the intention and there is no need for the result). For cancelling them, using the Drop trait will probably not work due to the amount of Arc's and Clones which are kept. This can be exposed as a terminate method of sorts which aborts all tasks. Using a cancellation token and injecting that into tasks is technically also possible, but also requires a way to cancel the token (so still a terminate method), while requiring tasks to be rewritten to check the token periodically.

On top of this, things like the source table, routing table, seqno cache, which spawn timers should also cancel the timers when they get dropped.

When the PeerManagerInner actually gets dropped, it should likely also cancel all peers it knows about.