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