Skip to main content

fluxpro_engine/models/context_map/
context_map.rs

1//! Typed process context with JSON serialization and exact-type accessors.
2
3use crate::models::context_map::context_patcher::{ContextPatcher, ContextPatcherOp};
4use crate::models::id_field::IdField;
5use chrono::{DateTime, NaiveDate, Utc};
6use serde::{Deserialize, Serialize};
7use serde_json::Value;
8use std::collections::HashMap;
9
10/// Typed values keyed by validated identifiers.
11///
12/// Wire values retain their type wrapper, for example
13/// `{"amount":{"number":100},"approved":{"boolean":true}}`.
14///
15/// # Examples
16///
17/// ```
18/// use fluxpro_engine::models::context_map::context_map::{ContextMap, ContextMapBuilder, ContextValue};
19/// use fluxpro_engine::models::id_field::IdField;
20///
21/// let amount = IdField::new("amount").unwrap();
22/// let context = ContextMapBuilder::new()
23///     .set(amount.clone(), ContextValue::number(100))
24///     .build();
25/// assert_eq!(context.as_number(&amount), Some(100));
26/// assert_eq!(context.as_string(&amount), None);
27/// let json = serde_json::to_value(&context).unwrap();
28/// assert_eq!(json["amount"]["number"], 100);
29/// let decoded: ContextMap = serde_json::from_value(json).unwrap();
30/// assert_eq!(decoded, context);
31/// ```
32#[derive(Debug, Clone, Deserialize, Serialize, Default, PartialEq)]
33pub struct ContextMap(pub HashMap<IdField, ContextValue>);
34
35impl ContextMap {
36    /// Borrows a value by its exact context key.
37    pub fn get(&self, key: &IdField) -> Option<&ContextValue> {
38        self.0.get(key)
39    }
40}
41
42/// A typed context value serialized as a single-key object.
43///
44/// For example, a string is `{ "string": "approved" }`, not a bare string.
45/// The runtime unwraps primitive values when exposing context to Rhai.
46#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]
47#[serde(untagged)]
48#[serde(rename_all = "lowercase")]
49pub enum ContextValue {
50    /// A wrapped UTF-8 string.
51    String {
52        /// UTF-8 string value.
53        string: String,
54    },
55    /// A wrapped validated identifier.
56    IdField {
57        /// Validated identifier value.
58        #[serde(alias = "id_field")]
59        id_field: IdField,
60    },
61    /// A wrapped signed integer.
62    Number {
63        /// Signed 64-bit integer value.
64        number: i64,
65    },
66    /// A wrapped floating-point number.
67    Float {
68        /// Double-precision floating-point value.
69        float: f64,
70    },
71    /// A wrapped calendar date.
72    Date {
73        /// Calendar date without a time zone.
74        date: NaiveDate,
75    },
76    /// A sequence of typed values.
77    Array {
78        /// Ordered sequence of typed context values.
79        array: Vec<ContextValue>,
80    },
81    /// A wrapped UTC timestamp.
82    DateTime {
83        /// UTC timestamp value.
84        #[serde(alias = "date_time")]
85        datetime: DateTime<Utc>,
86    },
87    /// A wrapped boolean.
88    Boolean {
89        /// Boolean value.
90        boolean: bool,
91    },
92    /// A wrapped arbitrary JSON value.
93    Object {
94        /// Arbitrary JSON value stored under the object wrapper.
95        object: Value,
96    },
97}
98
99impl ContextValue {
100    /// Wraps a string value for typed context serialization.
101    pub fn string(value: String) -> Self {
102        Self::String { string: value }
103    }
104
105    /// Wraps a id field value for typed context serialization.
106    pub fn id_field(value: IdField) -> Self {
107        Self::IdField { id_field: value }
108    }
109
110    /// Wraps a number value for typed context serialization.
111    pub fn number(value: i64) -> Self {
112        Self::Number { number: value }
113    }
114
115    /// Wraps a float value for typed context serialization.
116    pub fn float(value: f64) -> Self {
117        Self::Float { float: value }
118    }
119
120    /// Wraps a date value for typed context serialization.
121    pub fn date(value: NaiveDate) -> Self {
122        Self::Date { date: value }
123    }
124
125    /// Wraps a array value for typed context serialization.
126    pub fn array(value: Vec<ContextValue>) -> Self {
127        Self::Array { array: value }
128    }
129
130    /// Wraps a date time value for typed context serialization.
131    pub fn date_time(value: DateTime<Utc>) -> Self {
132        Self::DateTime { datetime: value }
133    }
134
135    /// Wraps a boolean value for typed context serialization.
136    pub fn boolean(value: bool) -> Self {
137        Self::Boolean { boolean: value }
138    }
139
140    /// Wraps a object value for typed context serialization.
141    pub fn object(value: Value) -> Self {
142        Self::Object { object: value }
143    }
144}
145
146impl ContextMap {
147    /// Applies patch operations in order to this in-memory context.
148    pub fn apply_patcher(&mut self, patcher: &ContextPatcher) {
149        patcher.ops().iter().for_each(|op| match op {
150            ContextPatcherOp::Set { key, value } => {
151                if self.0.contains_key(&key) {
152                    self.0.remove(&key);
153                }
154                self.0.insert(key.clone(), value.clone());
155            }
156            ContextPatcherOp::Remove { key } => {
157                self.0.remove(&key);
158            }
159        })
160    }
161
162    /// Returns the string value, or `None` for an absent key or different type.
163    pub fn as_string(&self, key: &IdField) -> Option<String> {
164        self.0.get(key).and_then(|v| match v {
165            ContextValue::String { string } => Some(string.clone()),
166            _ => None,
167        })
168    }
169
170    /// Returns the number value, or `None` for an absent key or different type.
171    pub fn as_number(&self, key: &IdField) -> Option<i64> {
172        self.0.get(key).and_then(|v| match v {
173            ContextValue::Number { number } => Some(number.clone()),
174            _ => None,
175        })
176    }
177
178    /// Returns the id field value, or `None` for an absent key or different type.
179    pub fn as_id_field(&self, key: &IdField) -> Option<IdField> {
180        self.0.get(key).and_then(|v| match v {
181            ContextValue::IdField { id_field } => Some(id_field.clone()),
182            _ => None,
183        })
184    }
185
186    /// Returns the float value, or `None` for an absent key or different type.
187    pub fn as_float(&self, key: &IdField) -> Option<f64> {
188        self.0.get(key).and_then(|v| match v {
189            ContextValue::Float { float } => Some(float.clone()),
190            _ => None,
191        })
192    }
193
194    /// Returns the date value, or `None` for an absent key or different type.
195    pub fn as_date(&self, key: &IdField) -> Option<NaiveDate> {
196        self.0.get(key).and_then(|v| match v {
197            ContextValue::Date { date } => Some(date.clone()),
198            _ => None,
199        })
200    }
201
202    /// Returns the date time value, or `None` for an absent key or different type.
203    pub fn as_date_time(&self, key: &IdField) -> Option<DateTime<Utc>> {
204        self.0.get(key).and_then(|v| match v {
205            ContextValue::DateTime { datetime } => Some(datetime.clone()),
206            _ => None,
207        })
208    }
209
210    /// Returns the bool value, or `None` for an absent key or different type.
211    pub fn as_bool(&self, key: &IdField) -> Option<bool> {
212        self.0.get(key).and_then(|v| match v {
213            ContextValue::Boolean { boolean } => Some(boolean.clone()),
214            _ => None,
215        })
216    }
217
218    /// Returns the object value, or `None` for an absent key or different type.
219    pub fn as_object(&self, key: &IdField) -> Option<Value> {
220        self.0.get(key).and_then(|v| match v {
221            ContextValue::Object { object } => Some(object.clone()),
222            _ => None,
223        })
224    }
225
226    /// Returns the array value, or `None` for an absent key or different type.
227    pub fn as_array(&self, key: &IdField) -> Option<Vec<ContextValue>> {
228        self.0.get(key).and_then(|v| match v {
229            ContextValue::Array { array } => Some(array.clone()),
230            _ => None,
231        })
232    }
233}
234
235/// Fluent builder that inserts or replaces typed context values.
236pub struct ContextMapBuilder {
237    context_map: ContextMap,
238}
239
240impl ContextMapBuilder {
241    /// Creates an empty context builder.
242    pub fn new() -> Self {
243        Self {
244            context_map: ContextMap::default(),
245        }
246    }
247
248    /// Starts a builder from an existing context map.
249    pub fn from(context_map: ContextMap) -> Self {
250        Self { context_map }
251    }
252
253    /// Adds a typed value assignment; a later assignment to the same key wins.
254    pub fn set(mut self, key: IdField, value: ContextValue) -> Self {
255        self.context_map.0.insert(key, value);
256        self
257    }
258
259    /// Consumes the builder and returns its accumulated value.
260    pub fn build(self) -> ContextMap {
261        self.context_map
262    }
263}