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::advanced::{StateFieldSchema, StateSchemaAccess, 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    pub fn all_fields(name: impl Into<String>) -> Result<Self, ObservationError> {
28        Ok(Self {
29            name: normalize_stream_name(name)?,
30            fields: FieldSelection::All,
31            sampling: IterationSampling::EVERY,
32        })
33    }
34
35    /// Defines a named stream containing the selected state fields.
36    pub fn fields<I, S>(name: impl Into<String>, fields: I) -> Result<Self, ObservationError>
37    where
38        I: IntoIterator<Item = S>,
39        S: Into<String>,
40    {
41        let name = normalize_stream_name(name)?;
42        let mut normalized = Vec::new();
43        let mut unique = HashSet::new();
44        for field in fields {
45            let field = field.into();
46            let field = field.trim();
47            if field.is_empty() {
48                return Err(ObservationError::EmptyFieldName {
49                    stream: name.to_string(),
50                });
51            }
52            if !unique.insert(field.to_owned()) {
53                return Err(ObservationError::DuplicateField {
54                    stream: name.to_string(),
55                    field: field.to_owned(),
56                });
57            }
58            normalized.push(Box::<str>::from(field));
59        }
60        if normalized.is_empty() {
61            return Err(ObservationError::EmptyFieldSelection {
62                stream: name.to_string(),
63            });
64        }
65        Ok(Self {
66            name,
67            fields: FieldSelection::Selected(normalized.into_boxed_slice()),
68            sampling: IterationSampling::EVERY,
69        })
70    }
71
72    /// Changes this stream's cadence from every iteration to every `iterations`.
73    pub fn every_iterations(mut self, iterations: u64) -> Result<Self, ObservationError> {
74        let Some(iterations) = NonZeroU64::new(iterations) else {
75            return Err(ObservationError::InvalidSamplingInterval {
76                stream: self.name.to_string(),
77            });
78        };
79        self.sampling = IterationSampling::new(iterations);
80        Ok(self)
81    }
82
83    pub(super) fn name(&self) -> &str {
84        &self.name
85    }
86
87    pub(super) fn bind(
88        self,
89        schema: &SystemStateSchema,
90    ) -> Result<BoundObservationStream, ObservationError> {
91        let fields = match self.fields {
92            FieldSelection::All => schema.field_schemas().to_vec(),
93            FieldSelection::Selected(selected) => {
94                let mut positions = HashSet::with_capacity(selected.len());
95                for field in &selected {
96                    let declaration = schema.field_schema(field).ok_or_else(|| {
97                        ObservationError::UnknownField {
98                            stream: self.name.to_string(),
99                            field: field.to_string(),
100                        }
101                    })?;
102                    positions.insert(declaration.position());
103                }
104                schema
105                    .field_schemas()
106                    .iter()
107                    .filter(|field| positions.contains(&field.position()))
108                    .cloned()
109                    .collect()
110            }
111        };
112        if fields.is_empty() {
113            return Err(ObservationError::EmptyFieldSelection {
114                stream: self.name.to_string(),
115            });
116        }
117        Ok(BoundObservationStream {
118            name: self.name,
119            fields: fields.into_boxed_slice(),
120            sampling: self.sampling,
121        })
122    }
123}
124
125fn normalize_stream_name(name: impl Into<String>) -> Result<Box<str>, ObservationError> {
126    let name = name.into();
127    let name = name.trim();
128    if name.is_empty() {
129        return Err(ObservationError::EmptyStreamName);
130    }
131    Ok(name.into())
132}
133
134/// One stream validated and ordered against a concrete state schema.
135#[derive(Clone, Debug, Eq, PartialEq)]
136pub(crate) struct BoundObservationStream {
137    name: Box<str>,
138    fields: Box<[StateFieldSchema]>,
139    sampling: IterationSampling,
140}
141
142impl BoundObservationStream {
143    /// Returns the normalized scientific stream name.
144    pub(crate) fn name(&self) -> &str {
145        &self.name
146    }
147
148    /// Returns selected fields in canonical state-schema order.
149    pub(crate) fn fields(&self) -> &[StateFieldSchema] {
150        &self.fields
151    }
152
153    /// Returns the positive iteration sampling cadence.
154    pub(crate) fn every_iterations(&self) -> u64 {
155        self.sampling.get()
156    }
157
158    pub(crate) fn includes(&self, iteration: u64) -> bool {
159        self.sampling.includes(iteration)
160    }
161}