Skip to main content

schedr_agent/
resource.rs

1//! A command's resource value (M4.8d): what a `CommandResource` setup reports with `schedr
2//! task-ctx resource set`, and what a resource's `cleanup_command` reads with `resource get`.
3//!
4//! The value stays in memory: a setup's attempt is stopped when its agent restarts (and runs
5//! again), and once it ends its value is its output, journaled with its result. It is masked
6//! then, with every secret the attempt read by its end.
7
8/// The most a value may take as stored JSON: what `resource get` can answer in one message of
9/// the context channel, less room for what wraps it.
10pub const MAX_VALUE_SIZE: usize = MAX_CTX_MESSAGE_SIZE as usize - 1024;
11
12use std::collections::BTreeMap;
13use std::sync::{Arc, Mutex, PoisonError};
14
15use schedr_model::ctx::MAX_CTX_MESSAGE_SIZE;
16use schedr_model::params::to_reported;
17use schedr_model::{ResourceRole, Task, TaskKind, TypeDesc};
18use serde_json::Value;
19
20use crate::mask::MaskSet;
21
22#[cfg(test)]
23mod tests;
24
25/// Why the value can't be reported or read.
26#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
27pub enum ResourceError {
28    /// `resource set` outside a `CommandResource` setup.
29    #[error("`resource set` works only in a `CommandResource`'s or `ScriptResource`'s setup")]
30    NotSetup,
31    /// `resource get` outside a resource's command cleanup.
32    #[error("`resource get` works only in a resource's `cleanup_command` or `cleanup_script`")]
33    NotCleanup,
34    /// The resource has no value (declared without `value=`).
35    #[error("the resource has no value: it was declared without one")]
36    NoValue,
37    /// Over [`MAX_VALUE_SIZE`] as stored.
38    #[error(
39        "the value would take {0} bytes, over the limit of {MAX_VALUE_SIZE}: keep what is large \
40         somewhere else and report where it is"
41    )]
42    TooLarge(usize),
43    /// Reported twice.
44    #[error("the resource's value is reported already; it is reported once")]
45    Again,
46    /// Not of the declared type; `why` never quotes the value.
47    #[error("the value doesn't fit the resource's type: {0}")]
48    Misfit(String),
49    /// The setup's value didn't reach the cleanup.
50    #[error("the setup's value didn't reach the cleanup")]
51    Missing,
52}
53
54#[derive(Debug)]
55enum Part {
56    /// A setup: what it reports, of `ty`, masked.
57    Setup {
58        ty: TypeDesc,
59        mask: Arc<MaskSet>,
60        reported: Mutex<Option<Value>>,
61    },
62    /// A cleanup: its setup's value, if it reached it.
63    Cleanup(Option<Value>),
64}
65
66/// An attempt's resource value.
67#[derive(Debug)]
68pub struct AttemptResource(Part);
69
70impl AttemptResource {
71    /// The resource part of an attempt of `task`, with its `inputs` (by task ID); `None` for a
72    /// task that is neither a command setup nor a command cleanup.
73    #[must_use]
74    pub fn of(task: &Task, inputs: &BTreeMap<String, Value>, mask: Arc<MaskSet>) -> Option<Self> {
75        let (TaskKind::Command {
76            resource: Some(role),
77            ..
78        }
79        | TaskKind::Script {
80            resource: Some(role),
81            ..
82        }) = &task.kind
83        else {
84            return None;
85        };
86        Some(Self(match role {
87            ResourceRole::Setup => Part::Setup {
88                ty: task.output_type.clone(),
89                mask,
90                reported: Mutex::new(None),
91            },
92            ResourceRole::Cleanup { setup } => Part::Cleanup(inputs.get(setup.as_str()).cloned()),
93        }))
94    }
95
96    /// Reports the value: checked against the type, stored tagged and masked.
97    ///
98    /// # Errors
99    ///
100    /// [`ResourceError`] outside a setup, for a resource without a value, a second report or
101    /// a value of another type.
102    pub fn set(&self, value: &Value) -> Result<(), ResourceError> {
103        let Part::Setup { ty, reported, .. } = &self.0 else {
104            return Err(ResourceError::NotSetup);
105        };
106        if *ty == TypeDesc::None {
107            return Err(ResourceError::NoValue);
108        }
109        let stored = to_reported(value, ty).map_err(|m| ResourceError::Misfit(m.to_string()))?;
110        let size = serde_json::to_string(&stored).map_or(usize::MAX, |json| json.len());
111        if size > MAX_VALUE_SIZE {
112            return Err(ResourceError::TooLarge(size));
113        }
114        let mut reported = reported.lock().unwrap_or_else(PoisonError::into_inner);
115        if reported.is_some() {
116            return Err(ResourceError::Again);
117        }
118        // Masked when the attempt ends: a secret read after the report is masked too.
119        *reported = Some(stored);
120        Ok(())
121    }
122
123    /// The setup's value, as stored; `null` for a resource without one (or one that reported
124    /// `null`, of an optional type).
125    ///
126    /// # Errors
127    ///
128    /// [`ResourceError`] outside a cleanup.
129    pub fn get(&self) -> Result<Value, ResourceError> {
130        match &self.0 {
131            Part::Setup { .. } => Err(ResourceError::NotCleanup),
132            Part::Cleanup(None) => Err(ResourceError::Missing),
133            Part::Cleanup(Some(value)) => Ok(value.clone()),
134        }
135    }
136
137    /// What a setup's attempt ends with: `Ok(value)` (null for a resource without one), or
138    /// `Err` when it has a value and reported none; `None` for a cleanup.
139    #[must_use]
140    pub fn outcome(&self) -> Option<Result<Value, ()>> {
141        let Part::Setup { ty, mask, reported } = &self.0 else {
142            return None;
143        };
144        let reported = reported.lock().unwrap_or_else(PoisonError::into_inner);
145        Some(match (&*reported, ty) {
146            (_, TypeDesc::None) => Ok(Value::Null),
147            (Some(value), _) => Ok(mask.mask_json(value)),
148            (None, _) => Err(()),
149        })
150    }
151}