Skip to main content

schedr_agent/
handles.rs

1//! The cleanup handles an attempt registers: what its cleanup needs that only existed in the
2//! attempt (see archive/PROJECT.md, Per-task cleanup). Masked as outputs are (decision 222), at
3//! most [`MAX_HANDLES_SIZE`] in all (decision 228).
4
5use std::sync::{Arc, Mutex, PoisonError};
6
7use schedr_model::ctx::MAX_CTX_MESSAGE_SIZE;
8use schedr_model::runner::CleanupHandle;
9use schedr_model::task::TaskCleanup;
10
11use crate::journal::Journal;
12use crate::mask::MaskSet;
13
14#[cfg(test)]
15mod tests;
16
17/// The most an attempt's handles may take as JSON, in bytes: 1 MiB, less room for what wraps
18/// them, so that `schedr task-ctx cleanup list` can read back all that was accepted, in one
19/// message of the context channel. They also travel with an assignment (`cleanup_anywhere`),
20/// within a worker's 4 MiB message.
21pub const MAX_HANDLES_SIZE: usize = MAX_CTX_MESSAGE_SIZE as usize - 1024;
22
23/// Why a handle isn't registered.
24#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
25pub enum HandleError {
26    /// The task has no cleanup to give it to.
27    #[error("the task has no cleanup: give it one (`cleanup=`), or don't register handles")]
28    NoCleanup,
29    /// Registered from the cleanup itself: nothing would clean up after it.
30    #[error("a cleanup can't register handles")]
31    InCleanup,
32    /// The cleanup takes none: it would never see them.
33    #[error(
34        "the task's cleanup takes no handles: give it a `handles` parameter, or don't register \
35         them"
36    )]
37    NoneTaken,
38    /// A type the cleanup doesn't take.
39    #[error("handle type `{given}` isn't one its cleanup takes ({taken})")]
40    OtherType {
41        /// The type given.
42        given: String,
43        /// The types it takes.
44        taken: String,
45    },
46    /// It can't be journaled: a restart would lose it.
47    #[error("the handle can't be written to the journal: {0}")]
48    NotJournaled(String),
49    /// Over [`MAX_HANDLES_SIZE`].
50    #[error(
51        "the attempt's handles would take {size} bytes, over the limit of {MAX_HANDLES_SIZE}: \
52         keep what is large somewhere else and register where it is"
53    )]
54    TooLarge {
55        /// What they would take.
56        size: usize,
57    },
58}
59
60/// Told each handle once it is journaled, with its place, to send it on to the master.
61#[derive(Clone)]
62pub struct HandleSink(pub Arc<SendHandle>);
63
64/// How a [`HandleSink`] sends a handle on.
65pub type SendHandle = dyn Fn(u32, &CleanupHandle) + Send + Sync;
66
67impl std::fmt::Debug for HandleSink {
68    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
69        f.write_str("HandleSink")
70    }
71}
72
73impl PartialEq for HandleSink {
74    fn eq(&self, other: &Self) -> bool {
75        Arc::ptr_eq(&self.0, &other.0)
76    }
77}
78
79/// What an attempt may register.
80#[derive(Debug)]
81enum Taken {
82    /// Nothing: its task has no cleanup.
83    NoCleanup,
84    /// Any type.
85    Any,
86    /// These types; none listed, none.
87    Only(Vec<String>),
88}
89
90#[derive(Debug, Default)]
91struct Registered {
92    handles: Vec<CleanupHandle>,
93    size: usize,
94    closed: bool,
95}
96
97/// An attempt's handles, in registration order.
98#[derive(Debug)]
99pub struct AttemptHandles {
100    /// The types its cleanup takes (empty: any); `None`: the task has no cleanup.
101    taken: Taken,
102    mask: Arc<MaskSet>,
103    /// Where each is on disk before the task hears it is registered, and under which attempt.
104    journal: Option<(Journal, String)>,
105    /// Told each handle, after the journal.
106    sink: Option<HandleSink>,
107    /// Held from a handle's place in the list to its line in the journal: one order in both.
108    adding: tokio::sync::Mutex<()>,
109    registered: Mutex<Registered>,
110}
111
112impl AttemptHandles {
113    /// The handles of an attempt of a task with `cleanup`, masked with `mask`.
114    #[must_use]
115    pub fn new(cleanup: Option<&TaskCleanup>, mask: Arc<MaskSet>) -> Self {
116        Self {
117            taken: match cleanup {
118                None => Taken::NoCleanup,
119                Some(TaskCleanup { handles: None, .. }) => Taken::Any,
120                Some(TaskCleanup {
121                    handles: Some(types),
122                    ..
123                }) => Taken::Only(types.clone()),
124            },
125            mask,
126            journal: None,
127            sink: None,
128            adding: tokio::sync::Mutex::new(()),
129            registered: Mutex::default(),
130        }
131    }
132
133    /// These handles journaled, as `attempt_id`'s.
134    #[must_use]
135    pub fn journaled(mut self, journal: Journal, attempt_id: String) -> Self {
136        self.journal = Some((journal, attempt_id));
137        self
138    }
139
140    /// These handles told to `sink`, once journaled.
141    #[must_use]
142    pub fn forwarded(mut self, sink: HandleSink) -> Self {
143        self.sink = Some(sink);
144        self
145    }
146
147    /// The handles read back from the journal, for a cleanup after a restart: closed.
148    #[must_use]
149    pub fn restored(handles: Vec<CleanupHandle>, mask: Arc<MaskSet>) -> Self {
150        Self {
151            taken: Taken::Any,
152            mask,
153            journal: None,
154            sink: None,
155            adding: tokio::sync::Mutex::new(()),
156            registered: Mutex::new(Registered {
157                handles,
158                size: 0,
159                closed: true,
160            }),
161        }
162    }
163
164    /// Registers a handle; journaled, if the attempt's handles are, when this returns.
165    ///
166    /// # Errors
167    ///
168    /// [`HandleError`] if it can't be: the attempt then fails where it registered it.
169    pub async fn add(&self, handle: CleanupHandle) -> Result<(), HandleError> {
170        match &self.taken {
171            Taken::NoCleanup => return Err(HandleError::NoCleanup),
172            Taken::Only(types) if types.is_empty() => return Err(HandleError::NoneTaken),
173            Taken::Only(types) if !types.contains(&handle.handle_type) => {
174                return Err(HandleError::OtherType {
175                    given: handle.handle_type,
176                    taken: types.join(", "),
177                });
178            }
179            Taken::Any | Taken::Only(_) => {}
180        }
181        let handle = CleanupHandle {
182            value: self.mask.mask_json(&handle.value),
183            ..handle
184        };
185        // As listed: the whole handle and a comma.
186        let added = serde_json::to_string(&handle).map_or(usize::MAX, |json| json.len() + 1);
187        let _adding = self.adding.lock().await;
188        let position = {
189            let mut registered = self
190                .registered
191                .lock()
192                .unwrap_or_else(PoisonError::into_inner);
193            if registered.closed {
194                return Err(HandleError::InCleanup);
195            }
196            let size = registered.size.saturating_add(added);
197            if size > MAX_HANDLES_SIZE {
198                return Err(HandleError::TooLarge { size });
199            }
200            registered.size = size;
201            registered.handles.push(handle.clone());
202            u32::try_from(registered.handles.len() - 1).unwrap_or(u32::MAX)
203        };
204        if let Some((journal, attempt_id)) = &self.journal {
205            let (journal, attempt_id) = (journal.clone(), attempt_id.clone());
206            let line = handle.clone();
207            tokio::task::spawn_blocking(move || journal.add_handle(&attempt_id, &line))
208                .await
209                .map_err(std::io::Error::other)
210                .and_then(|written| written)
211                .map_err(|error| HandleError::NotJournaled(error.to_string()))?;
212        }
213        if let Some(sink) = &self.sink {
214            (sink.0)(position, &handle);
215        }
216        Ok(())
217    }
218
219    /// Whether the cleanup has started.
220    #[must_use]
221    pub fn in_cleanup(&self) -> bool {
222        self.registered
223            .lock()
224            .unwrap_or_else(PoisonError::into_inner)
225            .closed
226    }
227
228    /// The handles so far, in registration order.
229    #[must_use]
230    pub fn list(&self) -> Vec<CleanupHandle> {
231        self.registered
232            .lock()
233            .unwrap_or_else(PoisonError::into_inner)
234            .handles
235            .clone()
236    }
237
238    /// Leaves out the first `count` handles: a cleanup that moved had them, this one runs on
239    /// the rest (B169).
240    pub fn skip(&self, count: usize) {
241        let mut registered = self
242            .registered
243            .lock()
244            .unwrap_or_else(PoisonError::into_inner);
245        let count = count.min(registered.handles.len());
246        registered.handles.drain(..count);
247    }
248
249    /// Stops taking handles: the cleanup starts.
250    pub fn close(&self) {
251        self.registered
252            .lock()
253            .unwrap_or_else(PoisonError::into_inner)
254            .closed = true;
255    }
256}