pub struct AppSpindown;
Expand description
A facade for interacting with the application’s global spindown registry.
Allows registering arbitrary workloads and later waiting for all registered workloads to signal their graceful completion (within a configurable timeout).
§Problem statement
Every application may choose to run asynchronous background tasks that hold some kind of resource. An example here would be a pool of database connections that is owned by a background task that lends access to the pool to any task that requests it. However, when the application is shut down, all background tasks are unceremoniously killed, which prevents proper clean-up, such as closing the database connections.
§Spindown
To solve the problem, this crate enables the following flow.
§Main thread
The main thread:
- spawns background tasks,
- waits until the global context is
terminated(e.g., in a
select
block, while also waiting for the main logic to finish), - waits for all background tasks to signal completion,
- returns from the
main
function.
§Background tasks
Meanwhile, each spawned background task:
- registers with the global spindown registry,
- also waits until the global context is
terminated (e.g., in a
select
block, while also doing other work), - performs clean-up procedures (e.g., closes connections, etc.),
- punches out the spindown token to signal completion.
Implementations§
Source§impl AppSpindown
impl AppSpindown
Sourcepub fn register(name: impl AsRef<str>) -> AppSpindownToken
pub fn register(name: impl AsRef<str>) -> AppSpindownToken
Informs the application’s global spindown registry that a workload with the given name (an arbitrary human-readable string) will need to be awaited during the application spindown, giving it some time to perform clean-up.
The returned AppSpindownToken
must be used by the registering
workload to signal back to the registry once it has gracefully completed.
Sourcepub fn set_timeout_secs(timeout_secs: impl Into<u64>)
pub fn set_timeout_secs(timeout_secs: impl Into<u64>)
Allows customizing the spindown timeout for the global singleton registry. Importantly, this method must be called early on, before any interaction with the global spindown registry, such as registering a workload. If called later, this method will have no effect.
Sourcepub async fn completed()
pub async fn completed()
Collects all previously registered workloads, and then waits (within a timeout) for them to signal completion.
This function is destructive, as it consumes the internally stored list of workloads.
The spindown is performed in repeated cycles (within a single shared timeout). If new workloads are registered while previous ones are being spun down, a new cycle is initiated to wait for the next batch. This is repeated until no more registered workloads are found.
Importantly, this function does not signal to the workloads to begin
their spindown. This is the job of the global
AppContext
.