scientific_workflow/observation/
stream.rs1use 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#[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 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 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 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 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#[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 pub(crate) fn name(&self) -> &str {
210 &self.name
211 }
212
213 pub(crate) fn fields(&self) -> &[StateFieldSchema] {
215 &self.fields
216 }
217
218 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}