Skip to main content

toolkit/runtime/
client_cleanup.rs

1use std::{fmt, future::Future, pin::Pin};
2
3use tokio_util::sync::CancellationToken;
4
5/// The completion operation owned by [`ClientCleanup`].
6pub type ClientCleanupFuture = Pin<Box<dyn Future<Output = Result<(), ClientCleanupError>> + Send>>;
7
8/// A failure during client cleanup.
9#[derive(Debug, PartialEq, Eq, thiserror::Error)]
10pub enum ClientCleanupError {
11    /// A client worker fails during cleanup.
12    #[error("client cleanup worker failed")]
13    WorkerFailed,
14    /// The completion operation reports a deadline, or the `OoP` bootstrap times out while waiting
15    /// for cleanup. When the bootstrap times out, it requests cancellation. Workers may still be
16    /// running when the call returns.
17    #[error("client cleanup deadline exceeded")]
18    DeadlineExceeded,
19}
20
21/// Owns one asynchronous client completion operation.
22///
23/// Await [`finish`](Self::finish) to observe completion. Dropping an unfinished
24/// owner requests cancellation through its abort token; it does not join workers.
25pub struct ClientCleanup {
26    completion: ClientCleanupFuture,
27    abort: CancellationToken,
28    armed: bool,
29}
30
31impl ClientCleanup {
32    /// Stores the completion operation without polling it or spawning work.
33    #[must_use]
34    pub fn new(completion: ClientCleanupFuture, abort: CancellationToken) -> Self {
35        Self {
36            completion,
37            abort,
38            armed: true,
39        }
40    }
41
42    /// Creates an owner whose completion succeeds immediately.
43    #[must_use]
44    pub fn empty() -> Self {
45        Self::new(Box::pin(async { Ok(()) }), CancellationToken::new())
46    }
47
48    /// Drives the supplied operation to completion, then disarms abort cancellation.
49    ///
50    /// # Cancellation safety
51    ///
52    /// Dropping this future before completion, even before its first poll, cancels
53    /// the abort token and drops the completion operation. Cancellation requests
54    /// termination; it does not prove that workers have joined.
55    ///
56    /// # Errors
57    ///
58    /// Returns the supplied completion error unchanged. An error also disarms abort.
59    pub async fn finish(mut self) -> Result<(), ClientCleanupError> {
60        let result = self.completion.as_mut().await;
61        self.armed = false;
62        result
63    }
64}
65
66impl fmt::Debug for ClientCleanup {
67    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
68        f.debug_struct("ClientCleanup")
69            .field("armed", &self.armed)
70            .finish_non_exhaustive()
71    }
72}
73
74impl Drop for ClientCleanup {
75    fn drop(&mut self) {
76        if self.armed {
77            self.abort.cancel();
78        }
79    }
80}