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    pub(super) fn name(&self) -> &str {
112        &self.name
113    }
114
115    pub(super) fn bind(
116        self,
117        schema: &SystemStateSchema,
118    ) -> Result<BoundObservationStream, ObservationError> {
119        let fields = match self.fields {
120            FieldSelection::All => schema.field_schemas().to_vec(),
121            FieldSelection::Selected(selected) => {
122                let mut positions = HashSet::with_capacity(selected.len());
123                for field in &selected {
124                    let declaration = schema.field_schema(field).ok_or_else(|| {
125                        ObservationError::UnknownField {
126                            stream: self.name.to_string(),
127                            field: field.to_string(),
128                        }
129                    })?;
130                    positions.insert(declaration.position());
131                }
132                schema
133                    .field_schemas()
134                    .iter()
135                    .filter(|field| positions.contains(&field.position()))
136                    .cloned()
137                    .collect()
138            }
139        };
140        if fields.is_empty() {
141            return Err(ObservationError::EmptyFieldSelection {
142                stream: self.name.to_string(),
143            });
144        }
145        Ok(BoundObservationStream {
146            name: self.name,
147            fields: fields.into_boxed_slice(),
148            sampling: self.sampling,
149        })
150    }
151}
152
153fn normalize_stream_name(name: impl Into<String>) -> Result<Box<str>, ObservationError> {
154    let name = name.into();
155    let name = name.trim();
156    if name.is_empty() {
157        return Err(ObservationError::EmptyStreamName);
158    }
159    Ok(name.into())
160}
161
162/// One stream validated and ordered against a concrete state schema.
163#[derive(Clone, Debug, Eq, PartialEq)]
164pub(crate) struct BoundObservationStream {
165    name: Box<str>,
166    fields: Box<[StateFieldSchema]>,
167    sampling: IterationSampling,
168}
169
170impl BoundObservationStream {
171    /// Returns the normalized scientific stream name.
172    pub(crate) fn name(&self) -> &str {
173        &self.name
174    }
175
176    /// Returns selected fields in canonical state-schema order.
177    pub(crate) fn fields(&self) -> &[StateFieldSchema] {
178        &self.fields
179    }
180
181    /// Returns the positive iteration sampling cadence.
182    pub(crate) fn every_iterations(&self) -> u64 {
183        self.sampling.get()
184    }
185
186    pub(crate) fn includes(&self, iteration: u64) -> bool {
187        self.sampling.includes(iteration)
188    }
189}