Skip to main content

schedr_bin/
ctx.rs

1//! `schedr dag-ctx`: a command task's processes reading the run's parameters and information
2//! from the agent, over the task's context channel (decisions 143-147, see
3//! `schedr_model::ctx`).
4//!
5//! Blocking and without the configuration: it runs inside a task, which may have none, and
6//! is one request and one answer.
7
8use std::collections::BTreeMap;
9use std::fmt::Write as _;
10use std::io::{self, IoSlice, Read, Write};
11use std::mem::MaybeUninit;
12use std::os::fd::{AsFd, OwnedFd};
13use std::os::unix::net::UnixStream;
14use std::time::{Duration, Instant};
15
16use rustix::event::{PollFd, PollFlags};
17use rustix::net::{SendAncillaryBuffer, SendAncillaryMessage, SendFlags};
18use schedr_fd::{Inherited, inherited_datagram};
19use schedr_model::ctx::{CTX_FD_ENV, CTX_PROTOCOL, CtxAnswer, CtxRequest, MAX_CTX_MESSAGE_SIZE};
20use serde_json::Value;
21
22use schedr_model::SecretName;
23use schedr_model::runner::CleanupHandle;
24
25use crate::cli::{
26    CleanupCommand, ConnectionArgs, DagCtxCommand, GetCommand, ResourceCommand, SecretCommand,
27    TaskCtxCommand, TaskEventsCommand,
28};
29
30#[cfg(test)]
31mod tests;
32
33/// How long the agent has to answer.
34const ANSWER_TIMEOUT: Duration = Duration::from_secs(30);
35
36/// Runs a `schedr dag-ctx` command; the error is the message for stderr.
37///
38/// # Errors
39///
40/// Outside a task, when the channel is gone, or when the agent refuses the call or the field
41/// asked for isn't there.
42pub fn run_dag_ctx(
43    command: &DagCtxCommand,
44    env: &BTreeMap<String, String>,
45    version: &str,
46    out: &mut impl Write,
47) -> Result<(), String> {
48    let (request, GetCommand::Get { field }) = match command {
49        DagCtxCommand::Params { command } => (CtxRequest::ParamsGet, command),
50        DagCtxCommand::Run { command } => (CtxRequest::RunGet, command),
51    };
52    let mut stream = connect(env, Ctx::Dag)?;
53    let answer = call(&mut stream, version, &request)?;
54    let values = values(answer)?;
55    let text = printed(&values, field.field.as_deref())?;
56    out.write_all(text.as_bytes())
57        .map_err(|e| format!("can't write output: {e}"))
58}
59
60/// Runs a `schedr task-ctx` command; the error is the message for stderr.
61///
62/// # Errors
63///
64/// As the command's own (`run_task_ctx_*`).
65pub fn run_task_ctx(
66    command: &TaskCtxCommand,
67    env: &BTreeMap<String, String>,
68    version: &str,
69    (out, err): (&mut impl Write, &mut impl Write),
70) -> Result<(), String> {
71    match command {
72        TaskCtxCommand::Secret { command } => run_task_ctx_secret(command, env, version, out),
73        TaskCtxCommand::Connection(command) => run_task_ctx_connection(command, env, version, out),
74        TaskCtxCommand::Cleanup { command } => run_task_ctx_cleanup(command, env, version, out),
75        TaskCtxCommand::Resource { command } => run_task_ctx_resource(command, env, version, out),
76        TaskCtxCommand::Api {
77            method,
78            path,
79            data,
80            idempotency_key,
81        } => {
82            let request = (
83                method.as_str(),
84                path.as_str(),
85                data.as_deref(),
86                idempotency_key.as_deref(),
87            );
88            run_task_ctx_api(request, env, version, (out, err))
89        }
90        TaskCtxCommand::Events { command } => {
91            run_task_ctx_events(command, env, version, (out, err))
92        }
93        TaskCtxCommand::Notify {
94            channel,
95            text,
96            data,
97        } => {
98            let data = crate::user::given_event_data(data.as_deref())
99                .map_err(|why| why.replace("--event-data", "--data"))?;
100            let request = CtxRequest::ApiCall {
101                method: "POST".to_owned(),
102                path: "/api/v1/notifications".to_owned(),
103                body: Some(serde_json::json!({
104                    "channel": channel,
105                    "text": text,
106                    "data": data.unwrap_or_default(),
107                })),
108                idempotency_key: None,
109            };
110            api_call(env, version, &request, err).map(|_| ())
111        }
112    }
113}
114
115/// Which command connects, for the message outside a task.
116#[derive(Debug, Clone, Copy)]
117enum Ctx {
118    Dag,
119    Task,
120}
121
122/// Runs `schedr task-ctx secret get`: prints a secret the task declares (a key's value as
123/// it is, with no newline; a whole secret as one line of JSON); the error is the message for
124/// stderr, with the error kind.
125///
126/// # Errors
127///
128/// Outside a task, when the channel is gone, or when the secret can't be read (not declared,
129/// not found, its storage down).
130pub fn run_task_ctx_secret(
131    command: &SecretCommand,
132    env: &BTreeMap<String, String>,
133    version: &str,
134    out: &mut impl Write,
135) -> Result<(), String> {
136    let SecretCommand::Get { secret, storage } = command;
137    let (path, key) = match secret.split_once('#') {
138        Some((path, key)) => (path, Some(key)),
139        None => (secret.as_str(), None),
140    };
141    let name = SecretName {
142        storage: storage.clone(),
143        path: path.to_owned(),
144        key: key.map(str::to_owned),
145        default: None,
146    };
147    name.check()?;
148    let mut stream = connect(env, Ctx::Task)?;
149    let request = CtxRequest::SecretGet { secret: name };
150    let text = match call(&mut stream, version, &request)? {
151        CtxAnswer::Secret {
152            value: Value::String(text),
153        } => text,
154        CtxAnswer::Secret { value } => value.to_string(),
155        CtxAnswer::SecretFailed { kind, reason } => return Err(format!("{reason} ({kind})")),
156        CtxAnswer::Error { reason } | CtxAnswer::Refused { reason } => return Err(reason),
157        _ => return Err("the agent answered with something else than the secret".to_owned()),
158    };
159    out.write_all(text.as_bytes())
160        .map_err(|e| format!("can't write output: {e}"))
161}
162
163/// Runs `schedr task-ctx connection NAME`: prints a connection's values, its secrets filled
164/// in (decision 174), as one line of JSON in the form `--params` takes, or with `--env
165/// PREFIX` as `export PREFIX_PARAM='value'` lines for `eval` (each value quoted for the
166/// shell, so nothing in one runs); the error is the message for stderr, with the error kind.
167///
168/// # Errors
169///
170/// Outside a task, when the channel is gone, when the prefix isn't a variable name's start,
171/// or when the connection can't be opened (not declared, not in the DAG folder, a secret it
172/// names unreadable).
173pub fn run_task_ctx_connection(
174    command: &ConnectionArgs,
175    env: &BTreeMap<String, String>,
176    version: &str,
177    out: &mut impl Write,
178) -> Result<(), String> {
179    let ConnectionArgs {
180        name, env: prefix, ..
181    } = command;
182    if let Some(prefix) = prefix {
183        schedr_model::connection::check_prefix(prefix).map_err(|e| format!("--env {e}"))?;
184    }
185    let mut stream = connect(env, Ctx::Task)?;
186    let request = match prefix {
187        None => CtxRequest::ConnectionGet { name: name.clone() },
188        Some(prefix) => CtxRequest::ConnectionEnvGet {
189            name: name.clone(),
190            prefix: prefix.clone(),
191        },
192    };
193    let text = match call(&mut stream, version, &request)? {
194        CtxAnswer::Connection { values } => {
195            let shown = schedr_model::params::shown(&Value::Object(values.into_iter().collect()));
196            format!("{shown}\n")
197        }
198        CtxAnswer::ConnectionEnv { variables } => exports(&variables),
199        CtxAnswer::ConnectionFailed { kind, reason } => return Err(format!("{reason} ({kind})")),
200        CtxAnswer::Error { reason } | CtxAnswer::Refused { reason } => return Err(reason),
201        _ => return Err("the agent answered with something else than the connection".to_owned()),
202    };
203    out.write_all(text.as_bytes())
204        .map_err(|e| format!("can't write output: {e}"))
205}
206
207/// Runs `schedr task-ctx cleanup add|list`: registers a handle before the work it cleans up
208/// after, or, in a cleanup, prints the attempt's handles in registration order: one line of
209/// JSON each, or with `--field` one field's raw value each; the error is the message for
210/// stderr.
211///
212/// # Errors
213///
214/// Outside a task, when the channel is gone, when a field or `--json` can't be read, when the
215/// agent refuses the handle (no cleanup declared, a type not declared, too large, already in
216/// the cleanup) or the list (not in a cleanup), or when a handle lacks the field asked for.
217pub fn run_task_ctx_cleanup(
218    command: &CleanupCommand,
219    env: &BTreeMap<String, String>,
220    version: &str,
221    out: &mut impl Write,
222) -> Result<(), String> {
223    match command {
224        CleanupCommand::Add {
225            handle_type,
226            fields,
227            json,
228        } => {
229            let value = handle_value(fields, json.as_deref())?;
230            let mut stream = connect(env, Ctx::Task)?;
231            let request = CtxRequest::HandleAdd {
232                handle: CleanupHandle {
233                    handle_type: handle_type.clone(),
234                    value,
235                },
236            };
237            match call(&mut stream, version, &request)? {
238                CtxAnswer::HandleAdded => Ok(()),
239                CtxAnswer::HandleRefused { reason }
240                | CtxAnswer::Error { reason }
241                | CtxAnswer::Refused { reason } => Err(reason),
242                _ => Err("the agent answered with something else than the handle".to_owned()),
243            }
244        }
245        CleanupCommand::List { handle_type, field } => {
246            let mut stream = connect(env, Ctx::Task)?;
247            let handles = match call(&mut stream, version, &CtxRequest::HandleList)? {
248                CtxAnswer::Handles { handles } => handles,
249                CtxAnswer::Error { reason } | CtxAnswer::Refused { reason } => return Err(reason),
250                _ => return Err("the agent answered with something else than handles".to_owned()),
251            };
252            let text = listed(&handles, handle_type.as_deref(), field.field.as_deref())?;
253            out.write_all(text.as_bytes())
254                .map_err(|e| format!("can't write output: {e}"))
255        }
256    }
257}
258
259/// `schedr task-ctx resource set|get`: reports the value of the resource a `CommandResource`
260/// setup creates (checked against its type at once), or prints the value a resource's
261/// `cleanup_command` cleans up (as `--params` takes it: dates as text, tuples as lists).
262///
263/// # Errors
264///
265/// Outside a task, when the channel is gone, when a field or `--json` can't be read, or when
266/// the agent refuses: `set` outside a setup, twice, or with a value of another type; `get`
267/// outside a cleanup; a missing `--field`.
268pub fn run_task_ctx_resource(
269    command: &ResourceCommand,
270    env: &BTreeMap<String, String>,
271    version: &str,
272    out: &mut impl Write,
273) -> Result<(), String> {
274    match command {
275        ResourceCommand::Set { fields, json } => {
276            let value = resource_value(fields, json.as_deref())?;
277            let mut stream = connect(env, Ctx::Task)?;
278            match call(&mut stream, version, &CtxRequest::ResourceSet { value })? {
279                CtxAnswer::ResourceReported => Ok(()),
280                CtxAnswer::ResourceRefused { reason }
281                | CtxAnswer::Error { reason }
282                | CtxAnswer::Refused { reason } => Err(reason),
283                _ => Err("the agent answered with something else than the resource".to_owned()),
284            }
285        }
286        ResourceCommand::Get { field } => {
287            let mut stream = connect(env, Ctx::Task)?;
288            let value = match call(&mut stream, version, &CtxRequest::ResourceGet)? {
289                CtxAnswer::Resource { value } => schedr_model::params::shown(&value),
290                CtxAnswer::ResourceRefused { reason }
291                | CtxAnswer::Error { reason }
292                | CtxAnswer::Refused { reason } => return Err(reason),
293                _ => {
294                    return Err(
295                        "the agent answered with something else than the resource".to_owned()
296                    );
297                }
298            };
299            let text = printed(&value, field.field.as_deref())?;
300            out.write_all(text.as_bytes())
301                .map_err(|e| format!("can't write output: {e}"))
302        }
303    }
304}
305
306/// Runs `schedr task-ctx api`: prints the answer's body as one line of JSON.
307///
308/// # Errors
309///
310/// Outside a task, when `--data` isn't JSON, when the channel is gone, or when the API answers
311/// an error status (its message).
312pub fn run_task_ctx_api(
313    (method, path, data, idempotency_key): (&str, &str, Option<&str>, Option<&str>),
314    env: &BTreeMap<String, String>,
315    version: &str,
316    (out, err): (&mut impl Write, &mut impl Write),
317) -> Result<(), String> {
318    let body = data
319        .map(|text| serde_json::from_str(text).map_err(|e| format!("--data isn't JSON: {e}")))
320        .transpose()?;
321    let request = CtxRequest::ApiCall {
322        method: method.to_owned(),
323        path: path.to_owned(),
324        body,
325        idempotency_key: idempotency_key.map(str::to_owned),
326    };
327    let answer = api_call(env, version, &request, err)?;
328    out.write_all(format!("{answer}\n").as_bytes())
329        .map_err(|e| format!("can't write output: {e}"))
330}
331
332/// Runs `schedr task-ctx events`: the event posted, or those listed, one line of JSON each.
333///
334/// # Errors
335///
336/// Outside a task, when `--data` or `--at` doesn't read, when the channel is gone, or when
337/// the API refuses (its message).
338pub fn run_task_ctx_events(
339    command: &TaskEventsCommand,
340    env: &BTreeMap<String, String>,
341    version: &str,
342    (out, err): (&mut impl Write, &mut impl Write),
343) -> Result<(), String> {
344    let request = match command {
345        TaskEventsCommand::Post {
346            name,
347            key,
348            data,
349            at,
350            idempotency_key,
351        } => {
352            let data = crate::user::given_event_data(data.as_deref())
353                .map_err(|why| why.replace("--event-data", "--data"))?;
354            let mut body = serde_json::json!({
355                "name": name,
356                "key": key,
357                "data": data.unwrap_or_default(),
358            });
359            if let Some(text) = at {
360                let parsed = crate::times::parse_for(text).map_err(|why| format!("--at: {why}"))?;
361                if let Some(warning) = parsed.warning {
362                    let _ = writeln!(err, "{warning}");
363                }
364                body["at"] = Value::String(parsed.at.to_string());
365            }
366            CtxRequest::ApiCall {
367                method: "POST".to_owned(),
368                path: "/api/v1/events".to_owned(),
369                body: Some(body),
370                idempotency_key: idempotency_key.clone(),
371            }
372        }
373        TaskEventsCommand::List { name, limit } => {
374            let mut path = format!("/api/v1/events?limit={limit}");
375            if let Some(name) = name {
376                let name =
377                    schedr_model::EventName::new(name).map_err(|e| format!("--name: {e}"))?;
378                // Encoded: a name may hold `#` or `/` (Grok's review: `#` cut the query).
379                let _ = write!(path, "&name={}", query_value(name.as_str()));
380            }
381            CtxRequest::ApiCall {
382                method: "GET".to_owned(),
383                path,
384                body: None,
385                idempotency_key: None,
386            }
387        }
388    };
389    let answer = api_call(env, version, &request, err)?;
390    let text = match answer.get("events").and_then(Value::as_array) {
391        Some(events) if matches!(command, TaskEventsCommand::List { .. }) => {
392            events.iter().fold(String::new(), |mut text, event| {
393                let _ = writeln!(text, "{event}");
394                text
395            })
396        }
397        _ => format!("{answer}\n"),
398    };
399    out.write_all(text.as_bytes())
400        .map_err(|e| format!("can't write output: {e}"))
401}
402
403/// `text` as a query's value: all but unreserved characters percent-encoded.
404fn query_value(text: &str) -> String {
405    text.bytes().fold(String::new(), |mut encoded, byte| {
406        if byte.is_ascii_alphanumeric() || b"-._~".contains(&byte) {
407            encoded.push(char::from(byte));
408        } else {
409            let _ = write!(encoded, "%{byte:02X}");
410        }
411        encoded
412    })
413}
414
415/// An API call through the task's agent: the answer's body, or its error as the message.
416fn api_call(
417    env: &BTreeMap<String, String>,
418    version: &str,
419    request: &CtxRequest,
420    err: &mut impl Write,
421) -> Result<Value, String> {
422    let mut stream = connect(env, Ctx::Task)?;
423    // The agent waits for the master up to its limit, over reconnects: the answer comes then.
424    stream
425        .set_read_timeout(Some(
426            schedr_agent::api::API_CALL_LIMIT.saturating_add(ANSWER_TIMEOUT),
427        ))
428        .map_err(|e| format!("can't set up the connection: {e}"))?;
429    let answer = call(&mut stream, version, request)?;
430    if let CtxAnswer::ApiAnswer {
431        note: Some(note), ..
432    } = &answer
433    {
434        let _ = writeln!(err, "{note}");
435    }
436    match answer {
437        CtxAnswer::ApiAnswer { status, body, .. } if status < 400 => Ok(body),
438        CtxAnswer::ApiAnswer { status, body, .. } => {
439            let why = body
440                .get("error")
441                .and_then(Value::as_str)
442                .map_or_else(|| body.to_string(), str::to_owned);
443            Err(format!("the API answered {status}: {why}"))
444        }
445        CtxAnswer::Error { reason } | CtxAnswer::Refused { reason } => Err(reason),
446        _ => Err("the agent answered with something else than the API's answer".to_owned()),
447    }
448}
449
450/// A resource's value: an object from `key=value` and `key:=json` fields, or any JSON from
451/// `--json` (`--json 7` for `value=int`).
452fn resource_value(fields: &[String], json: Option<&str>) -> Result<Value, String> {
453    match json {
454        Some(text) if fields.is_empty() => {
455            serde_json::from_str(text).map_err(|e| format!("--json isn't JSON: {e}"))
456        }
457        Some(_) => Err("give the value as fields or as --json, not both".to_owned()),
458        None => handle_value(fields, None),
459    }
460}
461
462/// A handle's value from `key=value` and `key:=json` fields, or from `--json`.
463fn handle_value(fields: &[String], json: Option<&str>) -> Result<Value, String> {
464    if let Some(text) = json {
465        if !fields.is_empty() {
466            return Err("give the handle as fields or as --json, not both".to_owned());
467        }
468        let value: Value =
469            serde_json::from_str(text).map_err(|e| format!("--json isn't JSON: {e}"))?;
470        if !value.is_object() {
471            return Err("--json must be one JSON object".to_owned());
472        }
473        return Ok(value);
474    }
475    let mut object = serde_json::Map::new();
476    for field in fields {
477        // A field is never quoted back: it may be a secret (B210).
478        let Some((name, text)) = field.split_once('=') else {
479            return Err("a field isn't `key=value` or `key:=json`".to_owned());
480        };
481        let (name, value) = match name.strip_suffix(':') {
482            Some(name) => {
483                let value = serde_json::from_str(text)
484                    .map_err(|e| format!("the value of `{name}` isn't JSON: {e}"))?;
485                (name, value)
486            }
487            None => (name, Value::String(text.to_owned())),
488        };
489        if name.is_empty() {
490            return Err("a field has no key (`=value`)".to_owned());
491        }
492        if object.insert(name.to_owned(), value).is_some() {
493            return Err(format!("the field `{name}` is given twice"));
494        }
495    }
496    Ok(Value::Object(object))
497}
498
499/// The handles as printed, of one type if asked: each as a line of JSON, or its field's raw
500/// value.
501fn listed(
502    handles: &[CleanupHandle],
503    handle_type: Option<&str>,
504    field: Option<&str>,
505) -> Result<String, String> {
506    let mut text = String::new();
507    let wanted = handles
508        .iter()
509        .filter(|handle| handle_type.is_none_or(|name| name == handle.handle_type));
510    for handle in wanted {
511        if field.is_some() {
512            text.push_str(&printed(&handle.value, field)?);
513        } else {
514            let line = serde_json::to_string(handle).map_err(|e| e.to_string())?;
515            let _ = writeln!(text, "{line}");
516        }
517    }
518    Ok(text)
519}
520
521/// `export NAME='value'` lines, one per variable, in order, single-quoted for the shell (a
522/// `'` written `'\''`): the agent named them, its files written already.
523fn exports(variables: &BTreeMap<String, String>) -> String {
524    let mut lines = String::new();
525    for (variable, text) in variables {
526        let quoted = text.replace('\'', "'\\''");
527        let _ = writeln!(lines, "export {variable}='{quoted}'");
528    }
529    lines
530}
531
532/// The values an answer holds, as printed: params in the JSON form `--params` takes.
533fn values(answer: CtxAnswer) -> Result<Value, String> {
534    match answer {
535        CtxAnswer::Params { params } => Ok(schedr_model::params::shown(&params)),
536        CtxAnswer::Run(run) => serde_json::to_value(run).map_err(|e| e.to_string()),
537        CtxAnswer::Error { reason } | CtxAnswer::Refused { reason } => Err(reason),
538        CtxAnswer::Welcome => Err("the agent answered `welcome` to a request".to_owned()),
539        CtxAnswer::ApiAnswer { .. } => {
540            Err("the agent answered with the API's answer to another request".to_owned())
541        }
542        CtxAnswer::HandleAdded | CtxAnswer::HandleRefused { .. } | CtxAnswer::Handles { .. } => {
543            Err("the agent answered with a cleanup handle to another request".to_owned())
544        }
545        CtxAnswer::ResourceReported
546        | CtxAnswer::Resource { .. }
547        | CtxAnswer::ResourceRefused { .. } => {
548            Err("the agent answered with a resource to another request".to_owned())
549        }
550        // Never printed in a message: it may hold a value.
551        CtxAnswer::Secret { .. }
552        | CtxAnswer::SecretFailed { .. }
553        | CtxAnswer::Connection { .. }
554        | CtxAnswer::ConnectionEnv { .. }
555        | CtxAnswer::ConnectionFailed { .. } => {
556            Err("the agent answered with a secret to another request".to_owned())
557        }
558    }
559}
560
561/// The output: the values as one line of JSON, or one field's raw value (text as it is,
562/// anything else as JSON), each with a newline.
563fn printed(values: &Value, field: Option<&str>) -> Result<String, String> {
564    let Some(name) = field else {
565        return Ok(format!("{values}\n"));
566    };
567    match values.get(name) {
568        Some(Value::String(text)) => Ok(format!("{text}\n")),
569        Some(value) => Ok(format!("{value}\n")),
570        None => Err(format!("there is no field `{name}`")),
571    }
572}
573
574/// A connection of this call's own: a fresh stream pair, one end sent to the agent over the
575/// task's channel.
576fn connect(env: &BTreeMap<String, String>, what: Ctx) -> Result<UnixStream, String> {
577    let Some(text) = env.get(CTX_FD_ENV) else {
578        let (command, python) = match what {
579            Ctx::Dag => ("dag-ctx", "reads `dag_ctx`"),
580            Ctx::Task => ("task-ctx", "reads `task_ctx`"),
581        };
582        return Err(format!(
583            "`schedr {command}` must be run inside a schedr task: a command task's processes \
584             can use it ({CTX_FD_ENV} isn't set here); a Python task {python}"
585        ));
586    };
587    let fd: i32 = text
588        .parse()
589        .map_err(|_| format!("{CTX_FD_ENV}=`{text}` isn't a descriptor number"))?;
590    let channel = inherited_datagram(fd).map_err(|e| channel_lost(fd, e))?;
591    let (mine, theirs) = UnixStream::pair().map_err(|e| format!("can't make a connection: {e}"))?;
592    send_end(&channel, &OwnedFd::from(theirs), ANSWER_TIMEOUT).map_err(|e| {
593        match e.raw_os_error() {
594            _ if e.kind() == io::ErrorKind::TimedOut => format!(
595                "the task's agent didn't take the call within {}s",
596                ANSWER_TIMEOUT.as_secs()
597            ),
598            Some(code) if code == rustix::io::Errno::CONNREFUSED.raw_os_error() => {
599                "the task's agent no longer serves its context: the task has ended (a process it \
600             left running can't read it)"
601                    .to_owned()
602            }
603            _ => format!("can't reach the task's agent: {e}"),
604        }
605    })?;
606    mine.set_read_timeout(Some(ANSWER_TIMEOUT))
607        .and_then(|()| mine.set_write_timeout(Some(ANSWER_TIMEOUT)))
608        .map_err(|e| format!("can't set up the connection: {e}"))?;
609    Ok(mine)
610}
611
612/// Why the inherited channel can't be used, for the message.
613fn channel_lost(fd: i32, error: Inherited) -> String {
614    let closed = format!(
615        "a parent process closed it (Python's `subprocess` closes inherited descriptors unless \
616         given `pass_fds=[{fd}]`; in a Python script, `from schedr.script import dag_ctx` reads \
617         the same values)"
618    );
619    match error {
620        Inherited::Closed(_) => {
621            format!("the task's context channel ({CTX_FD_ENV}={fd}) isn't open here: {closed}")
622        }
623        Inherited::NotChannel(_) => format!(
624            "descriptor {fd} ({CTX_FD_ENV}) isn't the task's context channel any more: {closed}, \
625             and the number was reused"
626        ),
627        other => format!("the task's context channel ({CTX_FD_ENV}={fd}): {other}"),
628    }
629}
630
631/// Sends `end` over the channel in one datagram (`SCM_RIGHTS`), waiting for room in it until
632/// `wait` ([`ANSWER_TIMEOUT`]): never blocking on the send itself (the inherited socket is shared with
633/// every process of the task, and may block).
634fn send_end(channel: &OwnedFd, end: &OwnedFd, wait: Duration) -> io::Result<()> {
635    let deadline = Instant::now() + wait;
636    let ends = [end.as_fd()];
637    loop {
638        let mut space = [MaybeUninit::uninit(); rustix::cmsg_space!(ScmRights(1))];
639        let mut control = SendAncillaryBuffer::new(&mut space);
640        if !control.push(SendAncillaryMessage::ScmRights(&ends)) {
641            return Err(io::Error::other("no room for the descriptor"));
642        }
643        match rustix::net::sendmsg(channel, &[IoSlice::new(b"c")], &mut control, SEND_FLAGS) {
644            Ok(_) => return Ok(()),
645            Err(rustix::io::Errno::AGAIN | rustix::io::Errno::INTR) => {}
646            Err(errno) => return Err(errno.into()),
647        }
648        let left = deadline.saturating_duration_since(Instant::now());
649        if left.is_zero() {
650            return Err(io::ErrorKind::TimedOut.into());
651        }
652        let left = rustix::event::Timespec::try_from(left).map_err(io::Error::other)?;
653        let mut room = [PollFd::new(channel, PollFlags::OUT)];
654        match rustix::event::poll(&mut room, Some(&left)) {
655            Ok(_) | Err(rustix::io::Errno::INTR) => {}
656            Err(errno) => return Err(errno.into()),
657        }
658    }
659}
660
661/// The send doesn't wait (`MSG_DONTWAIT`), nor raise `SIGPIPE` (Linux's flag; elsewhere
662/// Rust's runtime ignores it already).
663#[cfg(target_os = "linux")]
664const SEND_FLAGS: SendFlags = SendFlags::DONTWAIT.union(SendFlags::NOSIGNAL);
665#[cfg(not(target_os = "linux"))]
666const SEND_FLAGS: SendFlags = SendFlags::DONTWAIT;
667
668/// The handshake, then `request`'s answer.
669fn call(
670    stream: &mut (impl Read + Write),
671    version: &str,
672    request: &CtxRequest,
673) -> Result<CtxAnswer, String> {
674    let hello = CtxRequest::Hello {
675        protocol: CTX_PROTOCOL,
676        schedr_version: version.to_owned(),
677    };
678    // An agent refusing the connection (too many open) says why before closing it, maybe
679    // before the hello arrives: its answer is read even when the hello can't be written.
680    let said = write_message(stream, &hello);
681    let answer = match (read_answer(stream), said) {
682        (Ok(answer), _) => answer,
683        (Err(_), Err(not_said)) => return Err(not_said),
684        (Err(not_read), Ok(())) => return Err(not_read),
685    };
686    match answer {
687        CtxAnswer::Welcome => {}
688        CtxAnswer::Refused { reason } | CtxAnswer::Error { reason } => return Err(reason),
689        CtxAnswer::Secret { .. }
690        | CtxAnswer::Connection { .. }
691        | CtxAnswer::ConnectionEnv { .. } => {
692            return Err("the agent answered hello with a secret".to_owned());
693        }
694        other => return Err(format!("the agent answered hello with {other:?}")),
695    }
696    write_message(stream, request)?;
697    read_answer(stream)
698}
699
700fn lost(e: &io::Error) -> String {
701    match e.kind() {
702        io::ErrorKind::WouldBlock | io::ErrorKind::TimedOut => format!(
703            "the task's agent didn't answer within {}s",
704            ANSWER_TIMEOUT.as_secs()
705        ),
706        io::ErrorKind::UnexpectedEof
707        | io::ErrorKind::ConnectionReset
708        | io::ErrorKind::BrokenPipe => {
709            "the task's agent closed the connection without an answer (the task may have ended)"
710                .to_owned()
711        }
712        _ => format!("talking to the task's agent: {e}"),
713    }
714}
715
716fn write_message(stream: &mut impl Write, request: &CtxRequest) -> Result<(), String> {
717    let body = serde_json::to_vec(request).map_err(|e| e.to_string())?;
718    let size = u32::try_from(body.len()).map_err(|e| e.to_string())?;
719    stream
720        .write_all(&size.to_be_bytes())
721        .and_then(|()| stream.write_all(&body))
722        .map_err(|e| lost(&e))
723}
724
725fn read_answer(stream: &mut impl Read) -> Result<CtxAnswer, String> {
726    let mut header = [0; 4];
727    stream.read_exact(&mut header).map_err(|e| lost(&e))?;
728    let size = u32::from_be_bytes(header);
729    if size > MAX_CTX_MESSAGE_SIZE {
730        return Err(format!(
731            "the agent's answer of {size} bytes is over the limit of {MAX_CTX_MESSAGE_SIZE}"
732        ));
733    }
734    let mut body = vec![0; size as usize];
735    stream.read_exact(&mut body).map_err(|e| lost(&e))?;
736    serde_json::from_slice(&body).map_err(|e| format!("the agent's answer doesn't read: {e}"))
737}