Skip to main content

scientific_workflow/observation/
stream.rs

1//! Scientific observation-stream definitions and bound streams.
2
3use std::collections::HashSet;
4use std::num::NonZeroU64;
5
6use crate::state::{StateFieldSchema, SystemStateSchema};
7
8use super::error::ObservationError;
9
10#[derive(Clone, Copy, Debug, Eq, PartialEq)]
11enum IterationSampling {
12    Iterations(NonZeroU64),
13    InitialAndFinal,
14}
15
16impl IterationSampling {
17    const EVERY: Self = Self::Iterations(NonZeroU64::MIN);
18
19    const fn new(iterations: NonZeroU64) -> Self {
20        Self::Iterations(iterations)
21    }
22
23    const fn get(self) -> Option<u64> {
24        match self {
25            Self::Iterations(iterations) => Some(iterations.get()),
26            Self::InitialAndFinal => None,
27        }
28    }
29
30    const fn includes(self, iteration: u64) -> bool {
31        match self {
32            Self::Iterations(interval) => iteration.is_multiple_of(interval.get()),
33            Self::InitialAndFinal => false,
34        }
35    }
36}
37
38/// One application-defined scientific observation stream.
39#[derive(Clone, Debug, Eq, PartialEq)]
40pub struct ObservationStream {
41    name: Box<str>,
42    fields: FieldSelection,
43    sampling: IterationSampling,
44}
45
46#[derive(Clone, Debug, Eq, PartialEq)]
47enum FieldSelection {
48    All,
49    Selected(Box<[Box<str>]>),
50}
51
52impl ObservationStream {
53    /// Defines a named stream containing every field in its bound state schema.
54    ///
55    /// The name is trimmed and remains a scientific identifier rather than a
56    /// filesystem path.
57    ///
58    /// # Errors
59    ///
60    /// Returns [`ObservationError::EmptyStreamName`] when the normalized name
61    /// is empty.
62    pub fn all_fields(name: impl Into<String>) -> Result<Self, ObservationError> {
63        Ok(Self {
64            name: normalize_stream_name(name)?,
65            fields: FieldSelection::All,
66            sampling: IterationSampling::EVERY,
67        })
68    }
69
70    /// Defines a named stream containing the selected state fields.
71    ///
72    /// Stream and field names are trimmed. Selection order is accepted as
73    /// application input but schema binding later restores canonical schema
74    /// order.
75    ///
76    /// # Errors
77    ///
78    /// Returns [`ObservationError::EmptyStreamName`],
79    /// [`ObservationError::EmptyFieldName`],
80    /// [`ObservationError::EmptyFieldSelection`], or
81    /// [`ObservationError::DuplicateField`] for an invalid declaration.
82    pub fn fields<I, S>(name: impl Into<String>, fields: I) -> Result<Self, ObservationError>
83    where
84        I: IntoIterator<Item = S>,
85        S: Into<String>,
86    {
87        let name = normalize_stream_name(name)?;
88        let mut normalized = Vec::new();
89        let mut unique = HashSet::new();
90        for field in fields {
91            let field = field.into();
92            let field = field.trim();
93            if field.is_empty() {
94                return Err(ObservationError::EmptyFieldName {
95                    stream: name.to_string(),
96                });
97            }
98            if !unique.insert(field.to_owned()) {
99                return Err(ObservationError::DuplicateField {
100                    stream: name.to_string(),
101                    field: field.to_owned(),
102                });
103            }
104            normalized.push(Box::<str>::from(field));
105        }
106        if normalized.is_empty() {
107            return Err(ObservationError::EmptyFieldSelection {
108                stream: name.to_string(),
109            });
110        }
111        Ok(Self {
112            name,
113            fields: FieldSelection::Selected(normalized.into_boxed_slice()),
114            sampling: IterationSampling::EVERY,
115        })
116    }
117
118    /// Changes this stream's cadence from every iteration to every `iterations`.
119    ///
120    /// Iteration zero and every iteration divisible by this positive interval
121    /// are selected. The terminal state is handled independently by the
122    /// private observation session.
123    ///
124    /// # Errors
125    ///
126    /// Returns [`ObservationError::InvalidSamplingInterval`] when `iterations`
127    /// is zero.
128    pub fn every_iterations(mut self, iterations: u64) -> Result<Self, ObservationError> {
129        let Some(iterations) = NonZeroU64::new(iterations) else {
130            return Err(ObservationError::InvalidSamplingInterval {
131                stream: self.name.to_string(),
132            });
133        };
134        self.sampling = IterationSampling::new(iterations);
135        Ok(self)
136    }
137
138    /// Records the initial state and successful final state, with no intermediate records.
139    ///
140    /// An already-complete initial state is recorded once. This replaces any
141    /// previously selected interval; a later `every_iterations` replaces it.
142    /// Boundary-only metadata requires recording format 8.
143    pub fn initial_and_final(mut self) -> Self {
144        self.sampling = IterationSampling::InitialAndFinal;
145        self
146    }
147
148    pub(super) fn name(&self) -> &str {
149        &self.name
150    }
151
152    pub(super) fn bind(
153        self,
154        schema: &SystemStateSchema,
155    ) -> Result<BoundObservationStream, ObservationError> {
156        let fields = match self.fields {
157            FieldSelection::All => schema.field_schemas().to_vec(),
158            FieldSelection::Selected(selected) => {
159                let mut positions = HashSet::with_capacity(selected.len());
160                for field in &selected {
161                    let declaration = schema.field_schema(field).ok_or_else(|| {
162                        ObservationError::UnknownField {
163                            stream: self.name.to_string(),
164                            field: field.to_string(),
165                        }
166                    })?;
167                    positions.insert(declaration.position());
168                }
169                schema
170                    .field_schemas()
171                    .iter()
172                    .filter(|field| positions.contains(&field.position()))
173                    .cloned()
174                    .collect()
175            }
176        };
177        if fields.is_empty() {
178            return Err(ObservationError::EmptyFieldSelection {
179                stream: self.name.to_string(),
180            });
181        }
182        Ok(BoundObservationStream {
183            name: self.name,
184            fields: fields.into_boxed_slice(),
185            sampling: self.sampling,
186        })
187    }
188}
189
190fn normalize_stream_name(name: impl Into<String>) -> Result<Box<str>, ObservationError> {
191    let name = name.into();
192    let name = name.trim();
193    if name.is_empty() {
194        return Err(ObservationError::EmptyStreamName);
195    }
196    Ok(name.into())
197}
198
199/// One stream validated and ordered against a concrete state schema.
200#[derive(Clone, Debug, Eq, PartialEq)]
201pub(crate) struct BoundObservationStream {
202    name: Box<str>,
203    fields: Box<[StateFieldSchema]>,
204    sampling: IterationSampling,
205}
206
207impl BoundObservationStream {
208    /// Returns the normalized scientific stream name.
209    pub(crate) fn name(&self) -> &str {
210        &self.name
211    }
212
213    /// Returns selected fields in canonical state-schema order.
214    pub(crate) fn fields(&self) -> &[StateFieldSchema] {
215        &self.fields
216    }
217
218    /// Returns the positive iteration sampling cadence.
219    pub(crate) fn every_iterations(&self) -> Option<u64> {
220        self.sampling.get()
221    }
222
223    pub(crate) fn includes(&self, iteration: u64) -> bool {
224        self.sampling.includes(iteration)
225    }
226}