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