Skip to main content

schedr_agent/
parse.rs

1//! Parse jobs on the worker: the runner in `parse` mode over a root's files, with a per-file
2//! timeout.
3//!
4//! Each file of a parse job gets a runner process of its own, a few at once (`[dags]
5//! parse_concurrency`). If a file doesn't finish within the per-file timeout, or its runner dies
6//! while importing it, the agent stops the runner and records an import error for that file
7//! (see archive/PROJECT.md, Rust/Python integration: parsing granularity).
8
9use std::collections::{BTreeMap, BTreeSet};
10use std::time::Duration;
11
12use futures_util::StreamExt as _;
13use futures_util::stream::FuturesUnordered;
14use schedr_model::runner::{AgentMessage, ErrorSummary, ParseRequest, ParsedFile, RunnerMessage};
15
16use crate::channel::ChannelError;
17use crate::jobs::ScriptRoot;
18
19#[cfg(test)]
20mod tests;
21
22/// The exception name of the import error recorded for a file that timed out.
23pub const TIMEOUT_EXCEPTION: &str = schedr_model::runner::PARSE_TIMEOUT_EXCEPTION;
24
25/// The exception name of the import error recorded for a file whose runner died.
26pub const RUNNER_DIED_EXCEPTION: &str = schedr_model::runner::RUNNER_DIED_EXCEPTION;
27
28/// Why a parse job couldn't be finished.
29#[derive(Debug, thiserror::Error)]
30pub enum ParseError {
31    /// Talking to the runner failed outside a file (starting, the handshake, between files).
32    #[error("parse runner: {0}")]
33    Channel(#[from] ChannelError),
34    /// The runner said nothing for the per-file timeout outside a file (e.g. while starting).
35    #[error("the parse runner didn't respond within {0:?}")]
36    Unresponsive(Duration),
37}
38
39/// A started runner in parse mode, after the handshake and the `parse` request.
40pub trait ParseSession: Send {
41    /// The runner's next message.
42    fn next(&mut self) -> impl Future<Output = Result<RunnerMessage, ChannelError>> + Send;
43
44    /// Answers the runner (a `ScriptOperator`'s declaration, decision 293).
45    fn send(
46        &mut self,
47        message: AgentMessage,
48    ) -> impl Future<Output = Result<(), ChannelError>> + Send;
49
50    /// Stops the runner (its whole process group) and waits for it.
51    fn stop(self) -> impl Future<Output = ()> + Send;
52}
53
54/// Starts runners in parse mode.
55pub trait ParseRunner: Sync {
56    /// The started runner.
57    type Session: ParseSession;
58
59    /// Starts a runner, completes the handshake and sends it the request. Called for several
60    /// files at once.
61    fn start(
62        &self,
63        request: ParseRequest,
64    ) -> impl Future<Output = Result<Self::Session, ChannelError>> + Send;
65}
66
67/// How a parse job runs.
68#[derive(Debug, Clone, Copy, PartialEq, Eq)]
69pub struct ParseLimits {
70    /// How long one file may take to import.
71    pub per_file: Duration,
72    /// How many files are parsed at once.
73    pub concurrency: usize,
74}
75
76impl ParseLimits {
77    /// One file at a time.
78    #[must_use]
79    pub const fn one_at_a_time(per_file: Duration) -> Self {
80        Self {
81            per_file,
82            concurrency: 1,
83        }
84    }
85
86    /// `[dags] parse_file_timeout` and `parse_concurrency`, the latter capped at the cores this
87    /// process may use: more would only make the files' timeouts tighter.
88    #[must_use]
89    pub fn configured(per_file: Duration, concurrency: u32) -> Self {
90        let cores = std::thread::available_parallelism().map_or(1, std::num::NonZero::get);
91        Self {
92            per_file,
93            concurrency: capped(concurrency, cores),
94        }
95    }
96}
97
98fn capped(concurrency: u32, cores: usize) -> usize {
99    usize::try_from(concurrency)
100        .unwrap_or(usize::MAX)
101        .min(cores)
102        .max(1)
103}
104
105/// Parses the files of `request`, one at a time, each in a runner of its own: one file's imports
106/// and what they change can't reach another's, as they can't reach a task's (decision 326).
107///
108/// # Errors
109///
110/// [`ParseError`] if a runner can't be started or talked to outside a file; errors inside a
111/// file become that file's import error.
112pub async fn parse_files<R: ParseRunner>(
113    runner: &R,
114    request: ParseRequest,
115    per_file: Duration,
116) -> Result<Vec<ParsedFile>, ParseError> {
117    parse_files_with(
118        runner,
119        request,
120        ParseLimits::one_at_a_time(per_file),
121        &BTreeMap::new(),
122    )
123    .await
124}
125
126/// As [`parse_files`], `limits.concurrency` files at once, with the files in the order of the
127/// request, answering a `ScriptOperator`'s questions from the script roots `scripts` (their
128/// copies, decision 293) and recording in each file the script roots it asked about (decision
129/// 304).
130///
131/// After a failure no new file starts, and those being parsed are finished: their runners end
132/// as usual, not by being dropped.
133///
134/// # Errors
135///
136/// As [`parse_files`], the first failure.
137pub async fn parse_files_with<R: ParseRunner>(
138    runner: &R,
139    mut request: ParseRequest,
140    limits: ParseLimits,
141    scripts: &BTreeMap<String, ScriptRoot>,
142) -> Result<Vec<ParsedFile>, ParseError> {
143    let files = std::mem::take(&mut request.files);
144    let request = &request;
145    let mut parsed: Vec<Option<ParsedFile>> = files.iter().map(|_| None).collect();
146    let mut waiting = files.into_iter().enumerate();
147    let mut parsing = FuturesUnordered::new();
148    let mut failure = None;
149    loop {
150        while failure.is_none() && parsing.len() < limits.concurrency.max(1) {
151            let Some((index, file)) = waiting.next() else {
152                break;
153            };
154            parsing.push(parse_file(
155                runner,
156                request,
157                index,
158                file,
159                limits.per_file,
160                scripts,
161            ));
162        }
163        match parsing.next().await {
164            Some(Ok((index, file))) => parsed[index] = Some(file),
165            Some(Err(error)) => failure = failure.or(Some(error)),
166            None => break,
167        }
168    }
169    match failure {
170        Some(error) => Err(error),
171        None => Ok(parsed.into_iter().flatten().collect()),
172    }
173}
174
175/// One file, in a runner of its own.
176async fn parse_file<R: ParseRunner>(
177    runner: &R,
178    request: &ParseRequest,
179    index: usize,
180    file: String,
181    per_file: Duration,
182    scripts: &BTreeMap<String, ScriptRoot>,
183) -> Result<(usize, ParsedFile), ParseError> {
184    let mut session = runner
185        .start(ParseRequest {
186            files: vec![file.clone()],
187            ..request.clone()
188        })
189        .await?;
190    let mut asked = BTreeSet::new();
191    let step = run_session(&mut session, &file, per_file, (scripts, &mut asked)).await;
192    session.stop().await;
193    match step {
194        Ok(parsed) => Ok((index, parsed)),
195        Err(SessionEnd::Lost(error)) => Ok((
196            index,
197            ParsedFile {
198                // What it asked before it was lost still counts (decision 304).
199                script_roots: asked.into_iter().collect(),
200                path: file,
201                dags: Vec::new(),
202                connections: Vec::new(),
203                error: Some(error),
204                warnings: Vec::new(),
205            },
206        )),
207        Err(SessionEnd::Failed(error)) => Err(error),
208    }
209}
210
211/// How a session ended early.
212enum SessionEnd {
213    /// The file being imported timed out or killed the runner.
214    Lost(ErrorSummary),
215    /// Nothing can be blamed on the file.
216    Failed(ParseError),
217}
218
219async fn run_session<S: ParseSession>(
220    session: &mut S,
221    file: &str,
222    per_file: Duration,
223    (scripts, asked): (&BTreeMap<String, ScriptRoot>, &mut BTreeSet<String>),
224) -> Result<ParsedFile, SessionEnd> {
225    let mut started = false;
226    let mut done = None;
227    // A file's whole import has `per_file`, its `ScriptOperator`s' questions included.
228    let mut deadline = tokio::time::Instant::now() + per_file;
229    loop {
230        // A runner still to say it started has `per_file` from now on.
231        if !started {
232            deadline = tokio::time::Instant::now() + per_file;
233        }
234        let message = match tokio::time::timeout_at(deadline, session.next()).await {
235            Ok(Ok(message)) => message,
236            Ok(Err(error)) => {
237                return Err(if started && done.is_none() {
238                    SessionEnd::Lost(died(&error))
239                } else {
240                    SessionEnd::Failed(error.into())
241                });
242            }
243            Err(_) => {
244                return Err(if started && done.is_none() {
245                    SessionEnd::Lost(timed_out(per_file))
246                } else {
247                    SessionEnd::Failed(ParseError::Unresponsive(per_file))
248                });
249            }
250        };
251        let importing = started && done.is_none();
252        match message {
253            RunnerMessage::FileStarted { path } if !started && path == file => {
254                started = true;
255                // Its import starts now.
256                deadline = tokio::time::Instant::now() + per_file;
257            }
258            RunnerMessage::ScriptDeclaration { reference } if importing => {
259                let (root, found) = crate::jobs::lookup(&reference, scripts);
260                asked.extend(root);
261                let answer = match found {
262                    Ok(declaration) => AgentMessage::ScriptDeclaration(Box::new(declaration)),
263                    Err(message) => AgentMessage::ScriptNotFound { message },
264                };
265                match tokio::time::timeout_at(deadline, session.send(answer)).await {
266                    Ok(Ok(())) => {}
267                    Ok(Err(error)) => return Err(SessionEnd::Lost(died(&error))),
268                    Err(_) => return Err(SessionEnd::Lost(timed_out(per_file))),
269                }
270            }
271            RunnerMessage::FileParsed {
272                path,
273                dags,
274                connections,
275                error,
276                warnings,
277            } if importing && path == file => {
278                done = Some(ParsedFile {
279                    script_roots: std::mem::take(asked).into_iter().collect(),
280                    path,
281                    dags,
282                    connections,
283                    error,
284                    warnings,
285                });
286                // The wait for its end is a wait of its own.
287                deadline = tokio::time::Instant::now() + per_file;
288            }
289            RunnerMessage::ParseFinished if done.is_some() => {
290                return done.ok_or(SessionEnd::Failed(ParseError::Unresponsive(per_file)));
291            }
292            other => {
293                let expected = match (started, done.is_some()) {
294                    (true, false) => "file_parsed for the file started",
295                    (false, _) => "file_started for its file",
296                    (true, true) => "parse_finished",
297                };
298                return Err(SessionEnd::Failed(ParseError::Channel(
299                    ChannelError::Unexpected {
300                        expected,
301                        got: crate::channel::describe(&other),
302                    },
303                )));
304            }
305        }
306    }
307}
308
309fn timed_out(per_file: Duration) -> ErrorSummary {
310    ErrorSummary {
311        exception: TIMEOUT_EXCEPTION.to_owned(),
312        message: format!(
313            "importing the file took longer than the parse timeout of {} s",
314            per_file.as_secs_f64()
315        ),
316        traceback: String::new(),
317    }
318}
319
320fn died(error: &ChannelError) -> ErrorSummary {
321    ErrorSummary {
322        exception: RUNNER_DIED_EXCEPTION.to_owned(),
323        message: format!("the runner stopped while importing the file ({error})"),
324        traceback: String::new(),
325    }
326}