Skip to main content

schedr_model/
runner.rs

1//! Messages between the worker agent and the Python runner (`python -m schedr.runner`).
2//!
3//! They travel over the runner's inherited socket (`SCHEDR_AGENT_FD`), each one as a 4-byte
4//! big-endian length followed by that many bytes of UTF-8 JSON (see archive/PROJECT.md, Rust/Python
5//! integration: the agent <-> runner channel). Every message is an object tagged by `type`.
6
7use schemars::JsonSchema;
8use serde::{Deserialize, Serialize};
9
10use crate::dag::Dag;
11
12#[cfg(test)]
13mod tests;
14
15/// The largest message either side accepts, in bytes (the cap on inputs per task, 64 MiB).
16pub const MAX_MESSAGE_SIZE: u32 = 64 * 1024 * 1024;
17
18/// The error kind of a task its DAG file no longer defines (the runner's
19/// `task_not_found`).
20pub const TASK_NOT_FOUND: &str = "task_not_found";
21
22/// The error kind of a connection a task opens that its root's registry doesn't have
23/// (decision 174): not defined in the DAG folder, defined twice, or invalid.
24pub const CONNECTION_NOT_FOUND: &str = "connection_not_found";
25
26/// The error kind of a connection a task opens without declaring it in `connections=`
27/// (decision 179).
28pub const CONNECTION_DENIED: &str = "connection_denied";
29
30/// The error kind of an attempt whose DAG file is missing although the worker has the root at
31/// the hash the master expects (the newest code): the file is gone, not on its way.
32pub const DAG_FILE_MISSING: &str = "dag_file_missing";
33
34/// The error kind of a wait step that held its host's event loop past `[watchers] block_limit`.
35pub const BLOCKED_EVENT_LOOP: &str = "blocked_event_loop";
36
37/// The error kind of a wait step switched off for getting its host killed (decision 338).
38pub const SWITCHED_OFF: &str = "switched_off";
39
40/// The error kind of a wait step whose host ended with no wait step to blame.
41pub const WATCHER_HOST_LOST: &str = "watcher_host_lost";
42
43/// What the runner was started to do.
44#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
45#[serde(rename_all = "snake_case")]
46pub enum RunnerMode {
47    /// Import DAG files and report the DAGs they define.
48    Parse,
49    /// Run one task attempt.
50    Task,
51    /// Preload libraries, then fork a process per request (Linux only).
52    ForkServer,
53    /// Run the wait steps of one code set as coroutines, long-lived (decision 320).
54    Watchers,
55}
56
57/// A structured error summary: why a DAG file couldn't be imported, or why a task failed.
58#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
59#[serde(deny_unknown_fields)]
60pub struct ErrorSummary {
61    /// The exception's class name, e.g. `ModuleNotFoundError`; `ParseTimeout` or
62    /// `RunnerDied` when the agent stopped a file that took too long or lost its runner.
63    pub exception: String,
64    /// The exception's message.
65    pub message: String,
66    /// The last lines of the traceback (empty for a timeout).
67    pub traceback: String,
68}
69
70/// A declaration's `[cleanup]`: what its script runs, and only the settings its `schedr.toml`
71/// gives.
72#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
73#[serde(deny_unknown_fields)]
74pub struct ScriptCleanupDeclaration {
75    /// The script, relative to the script root.
76    pub script: String,
77    /// The interpreter's name.
78    pub interpreter: String,
79    /// Its arguments (templates).
80    #[serde(default, skip_serializing_if = "Vec::is_empty")]
81    pub args: Vec<crate::value::Template>,
82    /// `timeout`, if given.
83    #[serde(default, skip_serializing_if = "Option::is_none")]
84    pub timeout_ms: Option<u64>,
85    /// `retries`, if given.
86    #[serde(default, skip_serializing_if = "Option::is_none")]
87    pub retries: Option<u32>,
88    /// `retry_delay`, if given.
89    #[serde(default, skip_serializing_if = "Option::is_none")]
90    pub retry_delay_ms: Option<u64>,
91    /// `anywhere`, if given.
92    #[serde(default, skip_serializing_if = "Option::is_none")]
93    pub anywhere: Option<bool>,
94    /// The job's `cleanup_handles`, if given.
95    #[serde(default, skip_serializing_if = "Option::is_none")]
96    pub handles: Option<Vec<String>>,
97}
98
99/// A declared script, as the agent answers a `ScriptOperator` (decision 293): what its task
100/// runs, and only the settings its `schedr.toml` gives (the DAG's defaults apply to the
101/// others).
102#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
103#[serde(deny_unknown_fields)]
104pub struct ScriptDeclaration {
105    /// Its reference, `<root>:<path>#<name>` (an absolute one resolved to its root).
106    pub job: String,
107    /// The script, relative to the script root.
108    pub script: String,
109    /// The interpreter's name.
110    pub interpreter: String,
111    /// Its arguments, as the task carries them (templates).
112    #[serde(default, skip_serializing_if = "Vec::is_empty")]
113    pub args: Vec<crate::value::Template>,
114    /// Its environment variables, as the task carries them (templates).
115    #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
116    pub env: std::collections::BTreeMap<String, crate::value::Template>,
117    /// The secrets it declares.
118    #[serde(default, skip_serializing_if = "Vec::is_empty")]
119    pub secrets: Vec<crate::secret::SecretDecl>,
120    /// Where it runs, relative to the script root.
121    pub working_dir: String,
122    /// `retries`, if given.
123    #[serde(default, skip_serializing_if = "Option::is_none")]
124    pub retries: Option<u32>,
125    /// `retry_delay`, if given.
126    #[serde(default, skip_serializing_if = "Option::is_none")]
127    pub retry_delay_ms: Option<u64>,
128    /// `timeout`, if given.
129    #[serde(default, skip_serializing_if = "Option::is_none")]
130    pub timeout_ms: Option<u64>,
131    /// `queue`, if given.
132    #[serde(default, skip_serializing_if = "Option::is_none")]
133    pub queue: Option<String>,
134    /// `max_output_size`, if given.
135    #[serde(default, skip_serializing_if = "Option::is_none")]
136    pub max_output_size: Option<u64>,
137    /// `[outcomes]`, if given: each name with its exit code.
138    #[serde(default, skip_serializing_if = "Vec::is_empty")]
139    pub outcomes: Vec<crate::task::OutcomeDecl>,
140    /// `[cleanup]`, if given.
141    #[serde(default, skip_serializing_if = "Option::is_none")]
142    pub cleanup: Option<ScriptCleanupDeclaration>,
143}
144
145/// The exception name of the import error the agent records for a file that took longer than
146/// the parse timeout.
147pub const PARSE_TIMEOUT_EXCEPTION: &str = "ParseTimeout";
148
149/// The exception name of the import error the agent records for a file whose runner died.
150pub const RUNNER_DIED_EXCEPTION: &str = "RunnerDied";
151
152/// The exception name of the import error the agent records for a file whose parse result
153/// (all its DAGs' JSON together) is larger than the master accepts (B35).
154pub const PARSE_RESULT_TOO_LARGE_EXCEPTION: &str = "ParseResultTooLarge";
155
156/// The exception name of the import error the master records for a file that imported but
157/// defines a DAG its checks refuse.
158pub const INVALID_DAG_EXCEPTION: &str = "InvalidDag";
159
160/// The exception name of the import error the master records for a file whose path isn't
161/// inside its root.
162pub const INVALID_PATH_EXCEPTION: &str = "InvalidPath";
163
164impl ErrorSummary {
165    /// Whether it is a **transient** import error (decision 72.2): the agent stopped the file
166    /// (a timeout, a runner that died), so the code itself may be fine. Such a file is parsed
167    /// again, and doesn't hold its DAGs.
168    #[must_use]
169    pub fn is_transient(&self) -> bool {
170        self.exception == PARSE_TIMEOUT_EXCEPTION || self.exception == RUNNER_DIED_EXCEPTION
171    }
172
173    /// The JSON text of a summary schedr itself wrote (no traceback), e.g. when the agent
174    /// lost the runner or the master lost the worker.
175    #[must_use]
176    pub fn json(exception: &str, message: &str) -> String {
177        let summary = Self {
178            exception: exception.to_owned(),
179            message: message.to_owned(),
180            traceback: String::new(),
181        };
182        serde_json::to_string(&summary).unwrap_or_default()
183    }
184}
185
186/// One file of a parse job: the DAGs it defines, or why it couldn't be imported. The agent
187/// builds it from `file_parsed`, uploads it to the master, which stores it as is.
188#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
189#[serde(deny_unknown_fields)]
190pub struct ParsedFile {
191    /// The path relative to the root.
192    pub path: String,
193    /// The DAGs it defines (none for a helper module or a failed import).
194    pub dags: Vec<Dag>,
195    /// The connections it defines itself (decision 174: the root's registry).
196    #[serde(default, skip_serializing_if = "Vec::is_empty")]
197    pub connections: Vec<crate::connection::ConnectionDef>,
198    /// Why importing it failed, if it did.
199    pub error: Option<ErrorSummary>,
200    /// The Python warnings importing it raised (`Category: message`), for `schedr dags
201    /// check`; neither uploaded to the master nor stored.
202    #[serde(default, skip_serializing_if = "Vec::is_empty")]
203    pub warnings: Vec<String>,
204    /// The script roots its `ScriptOperator`s asked the agent about while it was imported,
205    /// found or not (decision 304): the master tells every worker which script roots each DAG
206    /// root uses, from its current parse.
207    #[serde(default, skip_serializing_if = "Vec::is_empty")]
208    pub script_roots: Vec<String>,
209}
210
211/// A process's output stream.
212#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
213#[serde(rename_all = "snake_case")]
214pub enum OutputStream {
215    /// Standard output.
216    Stdout,
217    /// Standard error.
218    Stderr,
219}
220
221/// A message from the runner to the agent.
222#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
223#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)]
224pub enum RunnerMessage {
225    /// The first message: who is speaking and what for.
226    Hello {
227        /// The installed `schedr` package version; it must equal the agent's.
228        schedr_version: String,
229        /// The mode the runner was started in.
230        mode: RunnerMode,
231    },
232    /// The runner starts importing a file (the agent times each file).
233    FileStarted {
234        /// The file's path relative to the root.
235        path: String,
236    },
237    /// A file was imported, or failed to import.
238    FileParsed {
239        /// The file's path relative to the root.
240        path: String,
241        /// The DAGs it defines (none for a helper module).
242        dags: Vec<Dag>,
243        /// The connections it defines itself (not those of modules it imports).
244        #[serde(default, skip_serializing_if = "Vec::is_empty")]
245        connections: Vec<crate::connection::ConnectionDef>,
246        /// Why importing it failed, if it did; then `dags` is empty.
247        error: Option<ErrorSummary>,
248        /// The Python warnings importing it raised (`Category: message`), e.g. a
249        /// `TypingHint`.
250        #[serde(default, skip_serializing_if = "Vec::is_empty")]
251        warnings: Vec<String>,
252    },
253    /// Every requested file was handled.
254    ParseFinished,
255    /// The task's DAG file is imported and its arguments built; its function is called next
256    /// (the agent times the start from it). Not sent when that fails.
257    TaskImported,
258    /// The task's function returned; its output is encoded and within the size limit.
259    TaskSucceeded {
260        /// The output as stored JSON (tagged extra types).
261        output: serde_json::Value,
262        /// The outcome's name: `SUCCESS`, an outcome union member's class name, or an `Outcome` member's name.
263        outcome: String,
264    },
265    /// A running task reads a secret it didn't get with the request: one under a declared
266    /// prefix (`task_ctx.secret(...)`); the agent answers [`AgentMessage::Secret`] or
267    /// [`AgentMessage::SecretFailed`].
268    SecretGet {
269        /// Which secret.
270        secret: crate::secret::SecretName,
271    },
272    /// A DAG file being parsed has a `ScriptOperator` (decision 293): the declaration it
273    /// refers to, `<root>:<path>#<name>` or `/abs/path/schedr.toml#<name>`; the agent answers
274    /// [`AgentMessage::ScriptDeclaration`] or [`AgentMessage::ScriptNotFound`].
275    ScriptDeclaration {
276        /// The reference as written.
277        reference: String,
278    },
279    /// A running task opens a connection it didn't get with the request
280    /// (`with name():`); the agent answers [`AgentMessage::Connection`] or
281    /// [`AgentMessage::ConnectionFailed`].
282    ConnectionGet {
283        /// The connection's name.
284        name: String,
285    },
286    /// A request to schedr's REST API (`schedr.api`, M4.11h): the agent has the master run it as
287    /// the task; it answers [`AgentMessage::ApiAnswer`].
288    ApiCall {
289        /// `GET`, `POST`, ...
290        method: String,
291        /// The path and its query, e.g. `/api/v1/events?name=paid`.
292        path: String,
293        /// The body, JSON; `None` for none.
294        #[serde(default, skip_serializing_if = "Option::is_none")]
295        body: Option<serde_json::Value>,
296        /// Its `Idempotency-Key`.
297        #[serde(default, skip_serializing_if = "Option::is_none")]
298        idempotency_key: Option<String>,
299    },
300    /// A running task registers a cleanup handle (`cleanup_handle(x)`); the agent answers
301    /// [`AgentMessage::HandleAdded`] or [`AgentMessage::HandleRefused`].
302    HandleAdd {
303        /// The handle.
304        handle: CleanupHandle,
305    },
306    /// The task failed: an exception, or an output that can't be stored.
307    TaskFailed {
308        /// What went wrong.
309        error: ErrorSummary,
310        /// A failure schedr recognises, e.g. `output_not_serializable`; `None` for an
311        /// exception from the task's own code.
312        kind: Option<String>,
313    },
314    /// A watcher host's event loop has been held past its limit: it can only be killed.
315    LoopBlocked {
316        /// The watcher holding it; `None` if no watcher is to blame.
317        watcher: Option<u64>,
318        /// Where the loop's thread is.
319        stack: String,
320    },
321    /// What a trigger found (inside a [`Self::WatcherMessage`]); it goes on when told
322    /// [`AgentMessage::EventStored`].
323    TriggerEvent {
324        /// Its key, unique in its DAG.
325        key: String,
326        /// Its data, encoded as an output is.
327        #[schemars(with = "serde_json::Value")]
328        data: serde_json::Value,
329        /// When it happened, if it said.
330        #[serde(default, skip_serializing_if = "Option::is_none")]
331        at: Option<jiff::Timestamp>,
332    },
333    /// A poke trigger's call ended; `error` is why it failed. Nothing answers it.
334    TriggerPoked {
335        /// Why the call failed.
336        #[serde(default, skip_serializing_if = "Option::is_none")]
337        error: Option<String>,
338    },
339    /// A watcher host is there, its event loop held or not, and how it is doing.
340    HostAlive {
341        /// Its process's threads.
342        threads: u32,
343        /// Those a wait step is tied to: running its `to_thread` calls, or started by it.
344        tied_threads: u32,
345        /// `to_thread` calls it stopped so far, each of which may have left shared state half
346        /// updated.
347        thread_stops: u64,
348        /// How long its event loop last took to get to a call, in milliseconds.
349        loop_lag_ms: u64,
350    },
351    /// A thread of this watcher didn't stop in its grace time: its host ends after its result
352    /// (inside a [`Self::WatcherMessage`]).
353    WatcherStuck,
354    /// Of one watcher, in a watcher host: what a task's runner would send.
355    WatcherMessage {
356        /// The watcher's ID.
357        watcher: u64,
358        /// The message: never a `watcher_message`.
359        message: Box<RunnerMessage>,
360    },
361    /// What a watcher printed: its attempt's log (inside a [`Self::WatcherMessage`]).
362    WatcherLog {
363        /// Which of its streams.
364        stream: OutputStream,
365        /// The text.
366        text: String,
367    },
368    /// A watcher ended by its cancel (inside a [`Self::WatcherMessage`]).
369    WatcherCancelled,
370    /// A poke stopped between calls, as asked: its next one is on new code (decision 335).
371    WatcherMoved,
372    /// The fork server preloaded its libraries and is single-threaded: it takes `fork`
373    /// requests.
374    ForkServerReady,
375    /// The fork server can't be used: tasks fall back (to the bare fork server, then to
376    /// spawn). It answers every later `fork` with `fork_failed` until the agent closes the
377    /// channel (exiting with a request unread would reset the connection and could lose this
378    /// message). Also the answer to a `fork` when a thread appeared since the check.
379    ForkServerDisabled {
380        /// Why, e.g. a failing preload or a second thread.
381        reason: String,
382        /// The names of the threads besides the main one (`/proc/self/task/*/comm`).
383        threads: Vec<String>,
384    },
385    /// A `fork` request was carried out: the shim runs, and reports on the status socket.
386    Forked {
387        /// The request's ID.
388        id: u64,
389    },
390    /// A `fork` request failed; the task falls back.
391    ForkFailed {
392        /// The request's ID.
393        id: u64,
394        /// Why.
395        reason: String,
396    },
397    /// From the shim, on the status socket: the forked process runs in its own process group
398    /// (its ID is the PID), so the agent may signal and watch the group.
399    ProcessStarted {
400        /// The process's PID, which is also its process group's ID.
401        pid: i32,
402    },
403    /// From the shim, on the status socket: the forked process ended. The shim reaps it when
404    /// the agent closes its end, so the PID isn't reused before.
405    ProcessExited {
406        /// The exit code, if it exited.
407        code: Option<i32>,
408        /// The signal that ended it, if one did.
409        signal: Option<i32>,
410        /// Whether it dumped core (ended by a signal).
411        core_dumped: bool,
412        /// What it used, with the children it reaped; `None` if the shim couldn't read it.
413        usage: Option<ProcessUsage>,
414    },
415}
416
417/// What a process used, with the children it reaped: its parent's view at its exit (`rusage`).
418#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
419#[serde(deny_unknown_fields)]
420pub struct ProcessUsage {
421    /// CPU time in user mode, in microseconds.
422    pub user_cpu_micros: u64,
423    /// CPU time in the kernel, in microseconds.
424    pub system_cpu_micros: u64,
425    /// The peak resident set size, in bytes. For a forked process it includes the pages it
426    /// shares with the fork server (the watchdog's PSS doesn't); `None` for a spawned process
427    /// (its memory is gone before the agent reads its zombie).
428    pub peak_rss_bytes: Option<u64>,
429    /// Page faults that needed I/O.
430    pub major_faults: u64,
431    /// Times it gave up the CPU (waiting for I/O or a lock), with its threads and reaped
432    /// children; `None` for a spawned process (its zombie's `/proc` has the leader thread's
433    /// only).
434    pub voluntary_context_switches: Option<u64>,
435    /// Times it was preempted; `None` as for `voluntary_context_switches`.
436    pub involuntary_context_switches: Option<u64>,
437}
438
439/// A parse job: the files of one root to import.
440#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
441#[serde(deny_unknown_fields)]
442pub struct ParseRequest {
443    /// The root's name, e.g. `etl-repo`.
444    pub root: String,
445    /// The root's directory.
446    pub root_dir: String,
447    /// The files to import, relative to the root, in order.
448    pub files: Vec<String>,
449    /// Directories put first on `sys.path` (every DAG root).
450    pub sys_path: Vec<String>,
451}
452
453/// Where a DAG file is.
454#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
455#[serde(deny_unknown_fields)]
456pub struct DagFile {
457    /// The DAG root's name.
458    pub root: String,
459    /// The root's directory on this worker.
460    pub root_dir: String,
461    /// The file's path relative to the root.
462    pub path: String,
463}
464
465/// The run information a task gets (`dag_ctx` and the `SCHEDR_*` variables).
466#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
467#[serde(deny_unknown_fields)]
468pub struct RunInfo {
469    /// The DAG's ID.
470    pub dag_id: String,
471    /// The run's ID (a `UUIDv7`).
472    pub run_id: String,
473    /// The run's kind.
474    pub kind: crate::states::RunKind,
475    /// The moment the run is for.
476    pub planned_for: jiff::Timestamp,
477    /// The start of the run's window.
478    pub since: jiff::Timestamp,
479    /// The attempt's try number, from 1.
480    pub try_number: u32,
481    /// The instance of a mapped task.
482    pub map_index: Option<u32>,
483    /// The run's parameters, as stored JSON (decision 138); `{}` when the DAG takes none.
484    #[serde(default = "no_params")]
485    #[schemars(with = "serde_json::Map<String, serde_json::Value>")]
486    pub params: serde_json::Value,
487    /// The event that started it, for a run of an event-triggered DAG.
488    #[serde(default, skip_serializing_if = "Option::is_none")]
489    pub event: Option<crate::trigger::RunEvent>,
490    /// When a wait step's first try started, for one tried again (`delay` counts from it);
491    /// `None` on its first try, and for other tasks.
492    #[serde(default, skip_serializing_if = "Option::is_none")]
493    pub first_started: Option<jiff::Timestamp>,
494}
495
496/// A run of a DAG without parameters.
497fn no_params() -> serde_json::Value {
498    serde_json::Value::Object(serde_json::Map::new())
499}
500
501/// One task attempt for the runner to run.
502#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
503#[serde(deny_unknown_fields)]
504pub struct TaskRequest {
505    /// The DAG file to import.
506    pub dag_file: DagFile,
507    /// The DAG's ID (the file may define several DAGs).
508    pub dag_id: String,
509    /// The task as stored in DAG JSON (its arguments and settings).
510    pub task: crate::task::Task,
511    /// The upstream outputs the task uses, by task ID, as stored JSON.
512    pub inputs: std::collections::BTreeMap<String, serde_json::Value>,
513    /// The upstream tasks' outcomes, by task ID: a name, or `null` for a skipped one (its
514    /// references stand for `None`).
515    #[serde(default)]
516    pub outcomes: std::collections::BTreeMap<String, serde_json::Value>,
517    /// The run information.
518    pub run: RunInfo,
519    /// Directories put first on `sys.path` (every DAG root).
520    pub sys_path: Vec<String>,
521    /// The secrets fetched for the attempt (those its arguments name and those it declares,
522    /// prefixes aside): filled into its arguments and read by `task_ctx.secret(...)`.
523    #[serde(default, skip_serializing_if = "Vec::is_empty")]
524    pub secrets: Vec<SecretValue>,
525    /// Set for `schedr connections test` (decision 174): no task is run; the file is
526    /// imported, and this connection opened and checked (decision 198).
527    #[serde(default, skip_serializing_if = "Option::is_none")]
528    pub connection_test: Option<String>,
529    /// Set for a cleanup: the task's cleanup function is called with the task's inputs and
530    /// these handles, in registration order, instead of the task.
531    #[serde(default, skip_serializing_if = "Option::is_none")]
532    pub cleanup: Option<Vec<CleanupHandle>>,
533    /// Set for a trigger: `task` is its function, which yields events until it is stopped.
534    #[serde(default, skip_serializing_if = "Option::is_none")]
535    pub trigger: Option<TriggerStart>,
536}
537
538/// How a trigger starts.
539#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
540#[serde(deny_unknown_fields)]
541pub struct TriggerStart {
542    /// The last key acted on: what its function gets as `after`.
543    pub after: Option<String>,
544}
545
546/// A handle registered by an attempt: what its cleanup needs that only existed in it.
547#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
548#[serde(deny_unknown_fields)]
549pub struct CleanupHandle {
550    /// Its type's name (a dataclass's name, or `schedr task-ctx cleanup add`'s first argument).
551    pub handle_type: String,
552    /// Its fields, as stored JSON.
553    pub value: serde_json::Value,
554}
555
556/// A secret's value, fetched by the agent for an attempt.
557#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
558#[serde(deny_unknown_fields)]
559pub struct SecretValue {
560    /// Which secret.
561    pub name: crate::secret::SecretName,
562    /// A key's value as a string; a whole secret as an object of key to value.
563    pub value: serde_json::Value,
564}
565
566/// What the fork server preloads.
567#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
568#[serde(deny_unknown_fields)]
569pub struct ForkServerRequest {
570    /// The modules to import, in order (none for the bare fork server).
571    pub preload: Vec<String>,
572}
573
574/// A request to the fork server: start a runner process.
575///
576/// Four descriptors come with it (`SCM_RIGHTS`, on the message's first bytes), in order: the
577/// process's end of its channel, its stdout, its stderr, and the shim's end of the status
578/// socket.
579#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
580#[serde(deny_unknown_fields)]
581pub struct ForkRequest {
582    /// The request's ID, repeated in the answer.
583    pub id: u64,
584    /// What the process runs (`parse` or `task`); it shakes hands on its channel as a spawned
585    /// runner does.
586    pub mode: RunnerMode,
587    /// The process's whole environment.
588    pub env: std::collections::BTreeMap<String, String>,
589    /// The process's working directory.
590    pub cwd: String,
591}
592
593/// A watcher host's request: what it holds for its whole life (decision 320).
594#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
595#[serde(deny_unknown_fields)]
596pub struct WatchersRequest {
597    /// Directories put first on `sys.path` (every DAG root's copy).
598    pub sys_path: Vec<String>,
599    /// How long a watcher may hold the event loop (`[watchers] block_limit`).
600    pub block_limit_ms: u64,
601    /// How long importing a DAG file may hold it (`[dags] parse_file_timeout`).
602    pub import_limit_ms: u64,
603    /// After how many calls in a row past its `every` a sensor's poke fails (`[watchers]
604    /// poke_overruns`).
605    pub poke_overruns: u32,
606}
607
608/// A message from the agent to the runner.
609#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
610#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)]
611pub enum AgentMessage {
612    /// The handshake succeeded.
613    Welcome,
614    /// The handshake failed; the runner exits.
615    Refused {
616        /// Why, e.g. a version mismatch.
617        reason: String,
618    },
619    /// A parse job.
620    Parse(ParseRequest),
621    /// A task attempt.
622    Task(Box<TaskRequest>),
623    /// The fork server's preload list (its mode's request).
624    ForkServer(ForkServerRequest),
625    /// A watcher host's code set (its mode's request).
626    Watchers(WatchersRequest),
627    /// Start a wait step in a watcher host.
628    StartWatcher {
629        /// The watcher's ID, unique in the host.
630        watcher: u64,
631        /// What to run.
632        task: Box<TaskRequest>,
633        /// How long a thread it left running has to end before the host does (decision 337).
634        cancel_grace_ms: u64,
635        /// A poke moving here from older code (decision 335): it says `task_imported` when it
636        /// could start, or `task_failed`, and makes no call until a [`Self::GoWatcher`].
637        #[serde(default, skip_serializing_if = "std::ops::Not::not")]
638        moved_in: bool,
639    },
640    /// Stop a poke between its calls: `watcher_moved`, unless it ended first.
641    MoveWatcher {
642        /// The watcher's ID.
643        watcher: u64,
644    },
645    /// Let a poke that moved here make its first call.
646    GoWatcher {
647        /// The watcher's ID.
648        watcher: u64,
649        /// What is left of its `max_wait`.
650        max_wait_ms: Option<u64>,
651    },
652    /// Cancel a watcher: `CancelledError` at its next `await`.
653    CancelWatcher {
654        /// The watcher's ID.
655        watcher: u64,
656    },
657    /// An answer to one watcher, in a watcher host.
658    ToWatcher {
659        /// The watcher's ID.
660        watcher: u64,
661        /// What a task's runner would get.
662        message: Box<AgentMessage>,
663    },
664    /// The master has what a trigger found: on to the next.
665    EventStored,
666    /// Start a runner process (to the fork server).
667    Fork(ForkRequest),
668    /// The declaration a [`RunnerMessage::ScriptDeclaration`] asked for, checked.
669    ScriptDeclaration(Box<ScriptDeclaration>),
670    /// Why the declaration a [`RunnerMessage::ScriptDeclaration`] asked for can't be used:
671    /// its script root isn't on this worker (decision 295), its file or job isn't there, or
672    /// the file has problems; the DAG file's import error.
673    ScriptNotFound {
674        /// What is wrong.
675        message: String,
676    },
677    /// The value of the secret a [`RunnerMessage::SecretGet`] asked for.
678    Secret {
679        /// A key's value as a string; a whole secret as an object of key to value.
680        value: serde_json::Value,
681    },
682    /// What the API answered a [`RunnerMessage::ApiCall`].
683    ApiAnswer {
684        /// The HTTP status.
685        status: u16,
686        /// The body, JSON (`{"error": ...}` for a refusal).
687        body: serde_json::Value,
688        /// What the task is told of its request: a secret in it masked. Printed to its log.
689        #[serde(default, skip_serializing_if = "Option::is_none")]
690        note: Option<String>,
691    },
692    /// The handle of a [`RunnerMessage::HandleAdd`] is registered.
693    HandleAdded,
694    /// Why the handle of a [`RunnerMessage::HandleAdd`] isn't registered.
695    HandleRefused {
696        /// What went wrong.
697        message: String,
698    },
699    /// Why the secret a [`RunnerMessage::SecretGet`] asked for can't be read.
700    SecretFailed {
701        /// The error kind (`secret_unavailable`, `secret_denied`, `secret_not_found`).
702        kind: String,
703        /// What went wrong, naming the secret (never a value).
704        message: String,
705    },
706    /// The values of the connection a [`RunnerMessage::ConnectionGet`] asked for, rendered.
707    Connection {
708        /// Each parameter's value, as stored JSON.
709        values: std::collections::BTreeMap<String, serde_json::Value>,
710    },
711    /// Why the connection a [`RunnerMessage::ConnectionGet`] asked for can't be opened.
712    ConnectionFailed {
713        /// The error kind (`connection_not_found`, or a secret's).
714        kind: String,
715        /// What went wrong, naming the connection (never a value).
716        message: String,
717    },
718}
719
720/// Whether the agent accepts a runner: the versions must be equal (the binary and the
721/// Python package are released together, see archive/PROJECT.md, Packaging and releases). The
722/// agent's Cargo version is compared as the Python package writes it: a release candidate
723/// `0.1.0-rc1` is the package's `0.1.0rc1` (decision 163).
724///
725/// # Errors
726///
727/// Returns the reason to send in [`AgentMessage::Refused`].
728pub fn check_runner_version(agent_version: &str, runner_version: &str) -> Result<(), String> {
729    let agent_version = python_version(agent_version);
730    if agent_version == runner_version {
731        Ok(())
732    } else {
733        Err(format!(
734            "the runner's schedr package is {runner_version}, the agent is {agent_version}: \
735             install schedr=={agent_version} in the interpreter's environment"
736        ))
737    }
738}
739
740/// A Cargo version as the Python package's metadata writes it (PEP 440, as maturin
741/// normalizes it): `X.Y.Z-rcN` is `X.Y.ZrcN`; a release is unchanged. The release workflow
742/// allows no other pre-release form (`scripts/release.py`).
743#[must_use]
744pub fn python_version(cargo_version: &str) -> String {
745    match cargo_version.split_once("-rc") {
746        Some((release, number))
747            if !number.is_empty() && number.bytes().all(|b| b.is_ascii_digit()) =>
748        {
749            format!("{release}rc{number}")
750        }
751        _ => cargo_version.to_owned(),
752    }
753}