1pub 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#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
27pub enum ResourceError {
28 #[error("`resource set` works only in a `CommandResource`'s or `ScriptResource`'s setup")]
30 NotSetup,
31 #[error("`resource get` works only in a resource's `cleanup_command` or `cleanup_script`")]
33 NotCleanup,
34 #[error("the resource has no value: it was declared without one")]
36 NoValue,
37 #[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 #[error("the resource's value is reported already; it is reported once")]
45 Again,
46 #[error("the value doesn't fit the resource's type: {0}")]
48 Misfit(String),
49 #[error("the setup's value didn't reach the cleanup")]
51 Missing,
52}
53
54#[derive(Debug)]
55enum Part {
56 Setup {
58 ty: TypeDesc,
59 mask: Arc<MaskSet>,
60 reported: Mutex<Option<Value>>,
61 },
62 Cleanup(Option<Value>),
64}
65
66#[derive(Debug)]
68pub struct AttemptResource(Part);
69
70impl AttemptResource {
71 #[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 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 *reported = Some(stored);
120 Ok(())
121 }
122
123 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 #[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}