scientific_workflow/observation/
stream.rs1use std::collections::HashSet;
4use std::num::NonZeroU64;
5
6use crate::state::{StateFieldSchema, SystemStateSchema};
7
8use super::error::ObservationError;
9use super::sampling::IterationSampling;
10
11#[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 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 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 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 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#[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 pub(crate) fn name(&self) -> &str {
183 &self.name
184 }
185
186 pub(crate) fn fields(&self) -> &[StateFieldSchema] {
188 &self.fields
189 }
190
191 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}