Skip to main content

scientific_workflow/state/
schema.rs

1//! Immutable state schemas loaded from JSON templates.
2//!
3//! A scientific program establishes its SystemState layout before constructing
4//! states. This module loads that layout, validates field declarations, assigns
5//! compact deterministic field indices, and shares the resulting metadata
6//! among all derived states.
7//!
8//! # Template format
9//!
10//! The accepted JSON document has one ordered `fields` array:
11//!
12//! ```json
13//! {
14//!   "fields": [
15//!     {
16//!       "name": "population",
17//!       "description": "Population count for each simulated region"
18//!     },
19//!     {"name": "space"}
20//!   ]
21//! }
22//! ```
23//!
24//! Array order is significant. It assigns each field a zero-based index used
25//! by the compact payload-slot vector in `SystemState`. Names and present
26//! descriptions are trimmed. Missing, null, empty, and whitespace-only
27//! descriptions all normalize to no description. Unknown JSON properties are
28//! rejected so misspelled template configuration cannot be silently ignored.
29//! Payload types and storage encodings deliberately do not belong here.
30//!
31//! # Sharing and performance
32//!
33//! `SystemStateSchema` is a small cloneable handle around an immutable, reference-
34//! counted layout. Cloning it never duplicates field names or lookup tables.
35//! Field lookup uses a hash map, while iteration preserves JSON declaration
36//! order through the field slice.
37//!
38//! # Construction boundary
39//!
40//! Public callers load the first specification from a JSON template path using
41//! [`SystemStateSchema::load_json_template`]. Crate-private peer functions apply
42//! the same semantic validation to Config's already-parsed JSON values and to
43//! Persistence's already-decoded ordered field metadata. Those peers never
44//! reread a project document or serialize metadata merely to parse it again.
45
46use std::collections::HashMap;
47use std::fs;
48use std::path::{Path, PathBuf};
49use std::sync::Arc;
50
51use serde::{Deserialize, Serialize};
52
53use super::error::StateError;
54use super::field::StateFieldSchema;
55use super::state::SystemState;
56use super::time::StateTime;
57
58/// A validated, shareable SystemState layout.
59///
60/// `SystemStateSchema` owns an [`Arc`] to immutable metadata, making `Clone` a cheap
61/// reference-count increment. Every state derived from a specification shares
62/// the exact field order and name lookup table.
63#[derive(Clone, Debug)]
64pub struct SystemStateSchema {
65    inner: Arc<StateLayout>,
66}
67
68/// One reusable static state-schema document supplied by an upstream crate.
69///
70/// An execution unit may return this descriptor from
71/// [`ExecutionUnit::standard_state_schema`](crate::task::ExecutionUnit::standard_state_schema)
72/// when its ordinary state layout is fixed by a linked dependency. Study
73/// validates and caches the borrowed document during preflight. The provider
74/// performs no filesystem IO and retains no project or runtime state.
75#[derive(Clone, Copy, Debug)]
76pub struct StateSchemaProvider {
77    id: &'static str,
78    document: &'static [u8],
79}
80
81impl StateSchemaProvider {
82    /// Declares one stable provider identity and its complete JSON template.
83    ///
84    /// Validation is intentionally deferred to Study or [`Self::resolve`] so
85    /// this constructor can remain `const` and providers can expose ordinary
86    /// static descriptors.
87    pub const fn new(id: &'static str, document: &'static [u8]) -> Self {
88        Self { id, document }
89    }
90
91    /// Returns the stable, versionable provider identity retained as provenance.
92    pub const fn id(self) -> &'static str {
93        self.id
94    }
95
96    /// Returns the borrowed static JSON schema document.
97    pub const fn document(self) -> &'static [u8] {
98        self.document
99    }
100
101    /// Validates this embedded document and returns its immutable state schema.
102    ///
103    /// This is the direct-integration counterpart to Study's automatic
104    /// provider resolution. It performs no filesystem IO. Each call creates a
105    /// new schema allocation; composed Workflow studies resolve and cache one
106    /// allocation per provider identity during preflight.
107    pub fn resolve(self) -> Result<SystemStateSchema, StateError> {
108        let source = PathBuf::from(format!("<state-schema-provider:{}>", self.id));
109        SystemStateSchema::parse(source, self.document)
110    }
111}
112
113impl SystemStateSchema {
114    /// Loads and validates a state specification from a JSON template.
115    ///
116    /// The file is read as bytes and parsed directly, avoiding an intermediate
117    /// UTF-8 `String` allocation. The returned specification retains the input
118    /// path for diagnostics and provenance but does not canonicalize it or keep
119    /// the file open.
120    ///
121    /// # Errors
122    ///
123    /// Returns:
124    ///
125    /// - [`StateError::TemplateRead`] when the file cannot be read;
126    /// - [`StateError::TemplateParse`] when JSON syntax or structure is invalid;
127    /// - [`StateError::EmptyFieldName`] for an empty normalized field name;
128    /// - [`StateError::DuplicateField`] for repeated normalized names.
129    pub fn load_json_template(path: &Path) -> Result<Self, StateError> {
130        let source = path.to_path_buf();
131        let bytes = fs::read(&source).map_err(|error| StateError::TemplateRead {
132            path: source.clone(),
133            source: error,
134        })?;
135
136        Self::parse(source, &bytes)
137    }
138
139    /// Parses the standalone public template loaded from disk.
140    ///
141    /// # Errors
142    ///
143    /// Returns [`StateError::TemplateParse`] for invalid JSON structure or
144    /// syntax and the same semantic template variants documented by
145    /// [`SystemStateSchema::load_json_template`]. The input bytes are borrowed
146    /// only for this call.
147    fn parse(source: PathBuf, bytes: &[u8]) -> Result<Self, StateError> {
148        let template: StateTemplate =
149            serde_json::from_slice(bytes).map_err(|error| StateError::TemplateParse {
150                path: source.clone(),
151                source: error,
152            })?;
153
154        Self::from_template(source, template)
155    }
156
157    /// Validates a centrally parsed JSON value without a second file read.
158    fn from_json_template_value(
159        source_path: &Path,
160        document: &serde_json::Value,
161    ) -> Result<Self, StateError> {
162        let template =
163            StateTemplate::deserialize(document).map_err(|source| StateError::TemplateParse {
164                path: source_path.to_path_buf(),
165                source,
166            })?;
167        Self::from_template(source_path.to_path_buf(), template)
168    }
169
170    /// Creates an empty SystemState that shares this specification.
171    ///
172    /// Every declared field exists in the returned state's layout, while every
173    /// payload slot starts empty. Cloning the specification is constant-time
174    /// and does not duplicate layout data.
175    pub fn create_empty_state(&self, time: StateTime) -> SystemState {
176        SystemState::new(self.clone(), time)
177    }
178
179    /// Resolves a declared field name to its payload-slot index.
180    ///
181    /// This is crate-private because compact indices are an implementation
182    /// detail. Public callers address fields by name or inspect [`StateFieldSchema`].
183    pub(crate) fn index_of(&self, name: &str) -> Result<usize, StateError> {
184        self.inner
185            .by_name
186            .get(name)
187            .copied()
188            .ok_or_else(|| StateError::UnknownField {
189                field: name.to_owned(),
190            })
191    }
192
193    /// Validates a parsed template and constructs its shared lookup layout.
194    fn from_template(source: PathBuf, template: StateTemplate) -> Result<Self, StateError> {
195        let mut fields = Vec::with_capacity(template.fields.len());
196        let mut by_name = HashMap::with_capacity(template.fields.len());
197
198        for (index, declaration) in template.fields.into_iter().enumerate() {
199            let name = declaration.name.trim();
200            if name.is_empty() {
201                return Err(StateError::EmptyFieldName { index });
202            }
203
204            if by_name.contains_key(name) {
205                return Err(StateError::DuplicateField {
206                    field: name.to_owned(),
207                });
208            }
209
210            let field = StateFieldSchema::new(index, name, declaration.description.as_deref());
211            by_name.insert(field.owned_name(), index);
212            fields.push(field);
213        }
214
215        Ok(Self {
216            inner: Arc::new(StateLayout {
217                source,
218                fields,
219                by_name,
220            }),
221        })
222    }
223}
224
225/// Validates one centrally parsed state-schema value without reading a file.
226pub(crate) fn schema_from_json_value(
227    source_path: &Path,
228    document: &serde_json::Value,
229) -> Result<SystemStateSchema, StateError> {
230    SystemStateSchema::from_json_template_value(source_path, document)
231}
232
233/// Reconstructs a schema directly from already-decoded ordered field metadata.
234pub(crate) fn schema_from_fields<'a>(
235    source_path: &Path,
236    fields: impl IntoIterator<Item = (&'a str, Option<&'a str>)>,
237) -> Result<SystemStateSchema, StateError> {
238    let template = StateTemplate {
239        fields: fields
240            .into_iter()
241            .map(|(name, description)| FieldDeclaration {
242                name: name.to_owned(),
243                description: description.map(str::to_owned),
244            })
245            .collect(),
246    };
247    SystemStateSchema::from_template(source_path.to_path_buf(), template)
248}
249
250impl SystemStateSchema {
251    /// Reports whether two schema handles share one immutable allocation.
252    ///
253    /// This is an identity comparison, not structural equality. Independently
254    /// loaded but textually identical schemas do not share an instance.
255    pub fn shares_schema_instance(&self, other: &SystemStateSchema) -> bool {
256        Arc::ptr_eq(&self.inner, &other.inner)
257    }
258
259    /// Returns the path from which this schema was loaded.
260    pub fn template_path(&self) -> &Path {
261        &self.inner.source
262    }
263
264    /// Returns field descriptions in deterministic template order.
265    pub fn field_schemas(&self) -> &[StateFieldSchema] {
266        &self.inner.fields
267    }
268
269    /// Looks up one field description by normalized name.
270    pub fn field_schema(&self, name: &str) -> Option<&StateFieldSchema> {
271        let index = self.inner.by_name.get(name)?;
272        self.inner.fields.get(*index)
273    }
274
275    /// Reports whether the schema declares `name`.
276    pub fn contains_field(&self, name: &str) -> bool {
277        self.inner.by_name.contains_key(name)
278    }
279
280    /// Returns the number of declared fields.
281    pub fn len(&self) -> usize {
282        self.inner.fields.len()
283    }
284
285    /// Reports whether the schema declares no fields.
286    pub fn is_empty(&self) -> bool {
287        self.inner.fields.is_empty()
288    }
289
290    /// Converts this schema to the strict, pretty-printed JSON template format.
291    pub fn to_json_template(&self) -> Result<String, serde_json::Error> {
292        serde_json::to_string_pretty(&StateTemplateRef {
293            fields: self.field_schemas(),
294        })
295    }
296}
297
298/// Immutable metadata shared by every clone of a [`SystemStateSchema`].
299#[derive(Debug)]
300struct StateLayout {
301    /// Original template path retained for provenance and diagnostics.
302    source: PathBuf,
303    /// Validated fields in deterministic template order.
304    fields: Vec<StateFieldSchema>,
305    /// Normalized field name to compact payload-slot index.
306    by_name: HashMap<Box<str>, usize>,
307}
308
309/// Serde-only representation of the top-level JSON template.
310#[derive(Debug, Deserialize)]
311#[serde(deny_unknown_fields)]
312struct StateTemplate {
313    /// Ordered field declarations.
314    fields: Vec<FieldDeclaration>,
315}
316
317/// Serde-only representation of one JSON field declaration.
318#[derive(Debug, Deserialize)]
319#[serde(deny_unknown_fields)]
320struct FieldDeclaration {
321    /// Human-facing dictionary key.
322    name: String,
323    /// Optional human-facing payload documentation.
324    #[serde(default)]
325    description: Option<String>,
326}
327
328/// Borrowed serialization view of a validated state specification.
329///
330/// Keeping this separate from [`StateTemplate`] prevents deserialization-only
331/// owned strings from being allocated when converting an existing
332/// specification back to JSON.
333#[derive(Serialize)]
334struct StateTemplateRef<'a> {
335    /// Fields borrowed in deterministic template order.
336    fields: &'a [StateFieldSchema],
337}