Skip to main content

schedr_proto/
convert.rs

1//! Conversions between protocol enums and `schedr-model`, and the master's reaction to each
2//! rejection reason.
3
4use schedr_model::runner::{ErrorSummary, ParsedFile};
5use schedr_model::{AttemptStatus, CleanupResult, RunKind};
6
7use crate::pb;
8
9#[cfg(test)]
10mod tests;
11
12/// A protocol value that has no `schedr-model` equivalent.
13#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
14pub enum ConversionError {
15    /// An enum value that is unspecified (0) or unknown to this version.
16    #[error("{field}: unspecified or unknown value {value}")]
17    UnknownEnumValue {
18        /// The field, e.g. `Finished.status`.
19        field: &'static str,
20        /// The raw value received.
21        value: i32,
22    },
23    /// A run kind name that isn't a `RunKind`.
24    #[error("RunInfo.kind: unknown run kind `{0}`")]
25    UnknownRunKind(String),
26    /// A parse upload's messages out of order (see [`ParseUpload`]).
27    #[error("{0}")]
28    BadUpload(String),
29    /// A DAG in a parsed file that isn't valid DAG JSON.
30    #[error("ParsedFile `{path}`: DAG {index} isn't valid DAG JSON: {reason}")]
31    InvalidDagJson {
32        /// The file.
33        path: String,
34        /// The DAG's position in the file's list.
35        index: usize,
36        /// Why it doesn't parse.
37        reason: String,
38    },
39    /// A connection in a parsed file that isn't valid connection JSON.
40    #[error("ParsedFile `{path}`: connection {index} isn't valid: {reason}")]
41    InvalidConnectionJson {
42        /// The file.
43        path: String,
44        /// The connection's position in the file's list.
45        index: usize,
46        /// Why it doesn't parse.
47        reason: String,
48    },
49}
50
51/// The protocol's form of a parsed file: each DAG as DAG JSON bytes, each connection as its
52/// JSON.
53///
54/// # Panics
55///
56/// Never: model DAGs always serialize (their maps have string keys).
57#[must_use]
58pub fn parsed_file_to_proto(file: &ParsedFile) -> pb::ParsedFile {
59    pb::ParsedFile {
60        path: file.path.clone(),
61        dag_json: file
62            .dags
63            .iter()
64            .map(|dag| serde_json::to_vec(dag).expect("a DAG always serializes"))
65            .collect(),
66        import_error: file.error.as_ref().map(|e| pb::ImportError {
67            exception: e.exception.clone(),
68            message: e.message.clone(),
69            traceback: e.traceback.clone(),
70        }),
71        connection_json: file
72            .connections
73            .iter()
74            .map(|c| serde_json::to_vec(c).expect("a connection always serializes"))
75            .collect(),
76        script_roots: file.script_roots.clone(),
77    }
78}
79
80/// A parse result as an upload's messages: the header (without files), then each file in
81/// a message of its own (B35).
82#[must_use]
83pub fn parse_upload_parts(mut result: pb::ParseResult) -> Vec<pb::ParseResultPart> {
84    let files = std::mem::take(&mut result.files);
85    let mut parts = Vec::with_capacity(files.len() + 1);
86    parts.push(pb::ParseResultPart {
87        part: Some(pb::parse_result_part::Part::Header(result)),
88    });
89    parts.extend(files.into_iter().map(|file| pb::ParseResultPart {
90        part: Some(pb::parse_result_part::Part::File(file)),
91    }));
92    parts
93}
94
95/// Collects an upload's messages back into one parse result, as they arrive.
96#[derive(Debug, Default)]
97pub struct ParseUpload {
98    result: Option<pb::ParseResult>,
99}
100
101impl ParseUpload {
102    /// Takes the next message.
103    ///
104    /// # Errors
105    ///
106    /// [`ConversionError::BadUpload`] when the first message isn't the header, a later one is,
107    /// or one is empty.
108    pub fn add(&mut self, part: pb::ParseResultPart) -> Result<(), ConversionError> {
109        match (part.part, &mut self.result) {
110            (Some(pb::parse_result_part::Part::Header(header)), None) => {
111                self.result = Some(header);
112                Ok(())
113            }
114            (Some(pb::parse_result_part::Part::File(file)), Some(result)) => {
115                result.files.push(file);
116                Ok(())
117            }
118            (Some(pb::parse_result_part::Part::Header(_)), Some(_)) => Err(
119                ConversionError::BadUpload("a second header in one parse upload".to_owned()),
120            ),
121            (Some(pb::parse_result_part::Part::File(_)), None) => Err(ConversionError::BadUpload(
122                "a parse upload must start with its header".to_owned(),
123            )),
124            (None, _) => Err(ConversionError::BadUpload(
125                "an empty message in a parse upload".to_owned(),
126            )),
127        }
128    }
129
130    /// The whole parse result.
131    ///
132    /// # Errors
133    ///
134    /// [`ConversionError::BadUpload`] when no header arrived.
135    pub fn finish(self) -> Result<pb::ParseResult, ConversionError> {
136        self.result.ok_or_else(|| {
137            ConversionError::BadUpload("a parse upload without its header".to_owned())
138        })
139    }
140}
141
142/// A parsed file from its protocol form (without its warnings, which the protocol doesn't
143/// carry).
144///
145/// # Errors
146///
147/// Returns [`ConversionError::InvalidDagJson`] for a DAG that doesn't parse as DAG JSON (the
148/// master's validation then reports the problems of DAGs that do).
149pub fn parsed_file_from_proto(file: pb::ParsedFile) -> Result<ParsedFile, ConversionError> {
150    let dags = file
151        .dag_json
152        .iter()
153        .enumerate()
154        .map(|(index, bytes)| {
155            serde_json::from_slice(bytes).map_err(|e| ConversionError::InvalidDagJson {
156                path: file.path.clone(),
157                index,
158                reason: e.to_string(),
159            })
160        })
161        .collect::<Result<_, _>>()?;
162    let connections = file
163        .connection_json
164        .iter()
165        .enumerate()
166        .map(|(index, bytes)| {
167            serde_json::from_slice(bytes).map_err(|e| ConversionError::InvalidConnectionJson {
168                path: file.path.clone(),
169                index,
170                reason: e.to_string(),
171            })
172        })
173        .collect::<Result<_, _>>()?;
174    Ok(ParsedFile {
175        script_roots: file.script_roots,
176        dags,
177        connections,
178        error: file.import_error.map(|e| ErrorSummary {
179            exception: e.exception,
180            message: e.message,
181            traceback: e.traceback,
182        }),
183        path: file.path,
184        // Not in the protocol: only `schedr dags check` shows them.
185        warnings: Vec::new(),
186    })
187}
188
189/// The protocol's attempt status for a model status.
190#[must_use]
191pub const fn attempt_status_to_proto(status: AttemptStatus) -> pb::AttemptStatus {
192    match status {
193        AttemptStatus::Success => pb::AttemptStatus::Success,
194        AttemptStatus::Failed => pb::AttemptStatus::Failed,
195        AttemptStatus::TimedOut => pb::AttemptStatus::TimedOut,
196        AttemptStatus::OomKilled => pb::AttemptStatus::OomKilled,
197        AttemptStatus::Cancelled => pb::AttemptStatus::Cancelled,
198        AttemptStatus::Interrupted => pb::AttemptStatus::Interrupted,
199        AttemptStatus::Lost => pb::AttemptStatus::Lost,
200        AttemptStatus::AssignmentExpired => pb::AttemptStatus::AssignmentExpired,
201    }
202}
203
204/// The model result for a raw protocol value (as found in `CleanupResult.status`).
205///
206/// # Errors
207///
208/// Returns [`ConversionError::UnknownEnumValue`] for `UNSPECIFIED` or an unknown value.
209pub fn cleanup_result_from_proto(value: i32) -> Result<CleanupResult, ConversionError> {
210    let unknown = ConversionError::UnknownEnumValue {
211        field: "CleanupResult.status",
212        value,
213    };
214    Ok(
215        match pb::CleanupStatus::try_from(value).map_err(|_| unknown.clone())? {
216            pb::CleanupStatus::Unspecified => return Err(unknown),
217            pb::CleanupStatus::Ok => CleanupResult::Ok,
218            pb::CleanupStatus::Failed => CleanupResult::Failed,
219            pb::CleanupStatus::NotNeeded => CleanupResult::NotNeeded,
220        },
221    )
222}
223
224/// The model status for a raw protocol value (as found in `Finished.status`).
225///
226/// # Errors
227///
228/// Returns [`ConversionError::UnknownEnumValue`] for `UNSPECIFIED` or an unknown value.
229pub fn attempt_status_from_proto(value: i32) -> Result<AttemptStatus, ConversionError> {
230    let unknown = ConversionError::UnknownEnumValue {
231        field: "Finished.status",
232        value,
233    };
234    Ok(
235        match pb::AttemptStatus::try_from(value).map_err(|_| unknown.clone())? {
236            pb::AttemptStatus::Unspecified => return Err(unknown),
237            pb::AttemptStatus::Success => AttemptStatus::Success,
238            pb::AttemptStatus::Failed => AttemptStatus::Failed,
239            pb::AttemptStatus::TimedOut => AttemptStatus::TimedOut,
240            pb::AttemptStatus::OomKilled => AttemptStatus::OomKilled,
241            pb::AttemptStatus::Cancelled => AttemptStatus::Cancelled,
242            pb::AttemptStatus::Interrupted => AttemptStatus::Interrupted,
243            pb::AttemptStatus::Lost => AttemptStatus::Lost,
244            pb::AttemptStatus::AssignmentExpired => AttemptStatus::AssignmentExpired,
245        },
246    )
247}
248
249/// The name a run kind travels as in `RunInfo.kind`.
250#[must_use]
251pub fn run_kind_to_proto(kind: RunKind) -> String {
252    kind.to_string()
253}
254
255/// The run kind for a `RunInfo.kind` name.
256///
257/// # Errors
258///
259/// Returns [`ConversionError::UnknownRunKind`] for a name that isn't a `RunKind`.
260pub fn run_kind_from_proto(name: &str) -> Result<RunKind, ConversionError> {
261    match name {
262        "scheduled" => Ok(RunKind::Scheduled),
263        "manual" => Ok(RunKind::Manual),
264        "backfill" => Ok(RunKind::Backfill),
265        "chained" => Ok(RunKind::Chained),
266        "event" => Ok(RunKind::Event),
267        other => Err(ConversionError::UnknownRunKind(other.to_owned())),
268    }
269}
270
271/// How the master reacts to a rejection (see archive/PROJECT.md, Task rejections). A rejection
272/// never uses up a retry.
273#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
274pub enum RejectReaction {
275    /// A momentary condition: requeue at once, any worker.
276    Temporary,
277    /// This worker can't run it: don't offer this attempt to it again; when every eligible
278    /// worker rejected it, the task is `unschedulable`.
279    WorkerSpecific,
280    /// The code isn't on the worker yet (git-sync lagging): retry after roughly the sync
281    /// interval plus settle time, any worker.
282    CodeNotThereYet,
283}
284
285/// The master's reaction to a raw `Rejected.reason`.
286///
287/// # Errors
288///
289/// Returns [`ConversionError::UnknownEnumValue`] for `UNSPECIFIED` or an unknown value.
290pub fn reject_reaction(reason: i32) -> Result<RejectReaction, ConversionError> {
291    use pb::RejectReason as R;
292    let unknown = ConversionError::UnknownEnumValue {
293        field: "Rejected.reason",
294        value: reason,
295    };
296    Ok(match R::try_from(reason).map_err(|_| unknown.clone())? {
297        R::Unspecified => return Err(unknown),
298        R::NoFreeSlot | R::Draining => RejectReaction::Temporary,
299        R::ScriptReferenceNotFound | R::DagFileMissing | R::CodeMismatch => {
300            RejectReaction::CodeNotThereYet
301        }
302        R::InterpreterUndefined
303        | R::ScriptRootUnknown
304        | R::MemoryBudgetTooLarge
305        | R::DiskNotWritable
306        | R::InvalidSpecification => RejectReaction::WorkerSpecific,
307    })
308}