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`]. A crate-private byte parser applies the identical
42//! validation path for persistence readers that recover an embedded template
43//! from the sole dataset metadata file. Keeping that parser crate-private
44//! preserves the public file-template initialization contract.
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
68impl SystemStateSchema {
69    /// Loads and validates a state specification from a JSON template.
70    ///
71    /// The file is read as bytes and parsed directly, avoiding an intermediate
72    /// UTF-8 `String` allocation. The returned specification retains the input
73    /// path for diagnostics and provenance but does not canonicalize it or keep
74    /// the file open.
75    ///
76    /// # Errors
77    ///
78    /// Returns:
79    ///
80    /// - [`StateError::TemplateRead`] when the file cannot be read;
81    /// - [`StateError::TemplateParse`] when JSON syntax or structure is invalid;
82    /// - [`StateError::EmptyFieldName`] for an empty normalized field name;
83    /// - [`StateError::DuplicateField`] for repeated normalized names.
84    pub fn load_json_template(path: &Path) -> Result<Self, StateError> {
85        let source = path.to_path_buf();
86        let bytes = fs::read(&source).map_err(|error| StateError::TemplateRead {
87            path: source.clone(),
88            source: error,
89        })?;
90
91        Self::parse(source, &bytes)
92    }
93
94    /// Parses and validates a specification from an in-memory JSON document.
95    ///
96    /// This is the internal reconstruction boundary for a future persistence
97    /// reader. `source` identifies the containing metadata file for provenance
98    /// and errors; it need not be a standalone state-template path. Parsing
99    /// uses the same strict Serde representation and semantic validation as
100    /// [`SystemStateSchema::load_json_template`].
101    ///
102    /// The method is crate-private so application code cannot bypass the
103    /// required public initialization from a JSON template file.
104    ///
105    /// # Errors
106    ///
107    /// Returns [`StateError::TemplateParse`] for invalid JSON structure or
108    /// syntax and the same semantic template variants documented by
109    /// [`SystemStateSchema::load_json_template`]. The input bytes are borrowed only for this call.
110    pub(crate) fn parse(source: PathBuf, bytes: &[u8]) -> Result<Self, StateError> {
111        let template: StateTemplate =
112            serde_json::from_slice(bytes).map_err(|error| StateError::TemplateParse {
113                path: source.clone(),
114                source: error,
115            })?;
116
117        Self::from_template(source, template)
118    }
119
120    /// Validates a centrally parsed JSON value without a second file read.
121    pub(crate) fn from_json_template_value(
122        source_path: &Path,
123        document: &serde_json::Value,
124    ) -> Result<Self, StateError> {
125        let template =
126            StateTemplate::deserialize(document).map_err(|source| StateError::TemplateParse {
127                path: source_path.to_path_buf(),
128                source,
129            })?;
130        Self::from_template(source_path.to_path_buf(), template)
131    }
132
133    /// Creates an empty SystemState that shares this specification.
134    ///
135    /// Every declared field exists in the returned state's layout, while every
136    /// payload slot starts empty. Cloning the specification is constant-time
137    /// and does not duplicate layout data.
138    pub fn create_empty_state(&self, time: StateTime) -> SystemState {
139        SystemState::new(self.clone(), time)
140    }
141
142    /// Resolves a declared field name to its payload-slot index.
143    ///
144    /// This is crate-private because compact indices are an implementation
145    /// detail. Public callers address fields by name or inspect [`StateFieldSchema`].
146    pub(crate) fn index_of(&self, name: &str) -> Result<usize, StateError> {
147        self.inner
148            .by_name
149            .get(name)
150            .copied()
151            .ok_or_else(|| StateError::UnknownField {
152                field: name.to_owned(),
153            })
154    }
155
156    /// Validates a parsed template and constructs its shared lookup layout.
157    fn from_template(source: PathBuf, template: StateTemplate) -> Result<Self, StateError> {
158        let mut fields = Vec::with_capacity(template.fields.len());
159        let mut by_name = HashMap::with_capacity(template.fields.len());
160
161        for (index, declaration) in template.fields.into_iter().enumerate() {
162            let name = declaration.name.trim();
163            if name.is_empty() {
164                return Err(StateError::EmptyFieldName { index });
165            }
166
167            if by_name.contains_key(name) {
168                return Err(StateError::DuplicateField {
169                    field: name.to_owned(),
170                });
171            }
172
173            let field = StateFieldSchema::new(index, name, declaration.description.as_deref());
174            by_name.insert(field.owned_name(), index);
175            fields.push(field);
176        }
177
178        Ok(Self {
179            inner: Arc::new(StateLayout {
180                source,
181                fields,
182                by_name,
183            }),
184        })
185    }
186}
187
188/// Advanced inspection and tooling operations for a validated state schema.
189///
190/// Import this trait from [`crate::state::advanced`] when schema metadata is
191/// needed. Ordinary state construction requires only the inherent basic API.
192pub trait StateSchemaAccess {
193    /// Reports whether two schema handles share one immutable allocation.
194    ///
195    /// This is an identity comparison, not structural equality. Independently
196    /// loaded but textually identical schemas do not share an instance.
197    fn shares_schema_instance(&self, other: &SystemStateSchema) -> bool;
198
199    /// Returns the path from which this schema was loaded.
200    fn template_path(&self) -> &Path;
201
202    /// Returns field descriptions in deterministic template order.
203    fn field_schemas(&self) -> &[StateFieldSchema];
204
205    /// Looks up one field description by normalized name.
206    fn field_schema(&self, name: &str) -> Option<&StateFieldSchema>;
207
208    /// Reports whether the schema declares `name`.
209    fn contains_field(&self, name: &str) -> bool;
210
211    /// Returns the number of declared fields.
212    fn len(&self) -> usize;
213
214    /// Reports whether the schema declares no fields.
215    fn is_empty(&self) -> bool;
216
217    /// Converts this schema to the strict, pretty-printed JSON template format.
218    fn to_json_template(&self) -> Result<String, serde_json::Error>;
219}
220
221impl StateSchemaAccess for SystemStateSchema {
222    fn shares_schema_instance(&self, other: &SystemStateSchema) -> bool {
223        Arc::ptr_eq(&self.inner, &other.inner)
224    }
225
226    fn template_path(&self) -> &Path {
227        &self.inner.source
228    }
229
230    fn field_schemas(&self) -> &[StateFieldSchema] {
231        &self.inner.fields
232    }
233
234    fn field_schema(&self, name: &str) -> Option<&StateFieldSchema> {
235        let index = self.inner.by_name.get(name)?;
236        self.inner.fields.get(*index)
237    }
238
239    fn contains_field(&self, name: &str) -> bool {
240        self.inner.by_name.contains_key(name)
241    }
242
243    fn len(&self) -> usize {
244        self.inner.fields.len()
245    }
246
247    fn is_empty(&self) -> bool {
248        self.inner.fields.is_empty()
249    }
250
251    fn to_json_template(&self) -> Result<String, serde_json::Error> {
252        serde_json::to_string_pretty(&StateTemplateRef {
253            fields: self.field_schemas(),
254        })
255    }
256}
257
258/// Immutable metadata shared by every clone of a [`SystemStateSchema`].
259#[derive(Debug)]
260struct StateLayout {
261    /// Original template path retained for provenance and diagnostics.
262    source: PathBuf,
263    /// Validated fields in deterministic template order.
264    fields: Vec<StateFieldSchema>,
265    /// Normalized field name to compact payload-slot index.
266    by_name: HashMap<Box<str>, usize>,
267}
268
269/// Serde-only representation of the top-level JSON template.
270#[derive(Debug, Deserialize)]
271#[serde(deny_unknown_fields)]
272struct StateTemplate {
273    /// Ordered field declarations.
274    fields: Vec<FieldDeclaration>,
275}
276
277/// Serde-only representation of one JSON field declaration.
278#[derive(Debug, Deserialize)]
279#[serde(deny_unknown_fields)]
280struct FieldDeclaration {
281    /// Human-facing dictionary key.
282    name: String,
283    /// Optional human-facing payload documentation.
284    #[serde(default)]
285    description: Option<String>,
286}
287
288/// Borrowed serialization view of a validated state specification.
289///
290/// Keeping this separate from [`StateTemplate`] prevents deserialization-only
291/// owned strings from being allocated when converting an existing
292/// specification back to JSON.
293#[derive(Serialize)]
294struct StateTemplateRef<'a> {
295    /// Fields borrowed in deterministic template order.
296    fields: &'a [StateFieldSchema],
297}