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