1pub mod queued;
46pub mod source;
47pub mod stream;
48
49use astrs_wire::messages::control::types::ParamScope;
50use astrs_wire::metadata::Parameter;
51use astrs_wire::{
52 DataId, ExtensionKey, Metadata, NodeExitCause, NodeId, OperatorId, ParamKey, PortRef,
53 RouteCloseReason, StopCause,
54};
55
56use crate::payload::Payload;
57
58pub use queued::QueuedEvent;
59pub use source::EventSource;
60pub use stream::{EventStream, Stream};
61
62#[derive(Debug)]
70#[non_exhaustive]
71pub enum Event {
72 Input {
74 id: DataId,
76 meta: Metadata,
79 data: Payload,
82 },
83 InputClosed {
85 id: DataId,
87 source: PortRef,
89 reason: RouteCloseReason,
91 },
92 InputRecovered {
94 id: DataId,
96 source: PortRef,
98 generation: u64,
100 },
101 Stop(StopCause),
103 Reload {
105 operator: Option<OperatorId>,
107 path: Option<String>,
109 },
110 AllInputsClosed,
112 ParamUpdate {
114 scope: ParamScope,
116 key: ParamKey,
118 value: Parameter,
120 },
121 ParamDeleted {
123 scope: ParamScope,
125 key: ParamKey,
127 },
128 NodeFailed {
130 peer: NodeId,
132 cause: NodeExitCause,
134 },
135 Restarted {
137 peer: NodeId,
139 generation: u64,
141 },
142 ExtDropped {
144 key: ExtensionKey,
146 reason: String,
148 },
149 Error(String),
153}
154
155impl Event {
156 #[must_use]
158 pub const fn input(&self) -> Option<&DataId> {
159 match self {
160 Self::Input { id, .. }
161 | Self::InputClosed { id, .. }
162 | Self::InputRecovered { id, .. } => Some(id),
163 _ => None,
164 }
165 }
166
167 #[must_use]
169 pub const fn is_input(&self) -> bool {
170 matches!(self, Self::Input { .. })
171 }
172
173 #[must_use]
175 pub const fn is_stop(&self) -> bool {
176 matches!(self, Self::Stop(_))
177 }
178
179 #[must_use]
181 pub const fn is_control(&self) -> bool {
182 !matches!(
183 self,
184 Self::Input { .. } | Self::InputClosed { .. } | Self::InputRecovered { .. }
185 )
186 }
187
188 #[must_use]
190 pub fn is_fault(&self) -> bool {
191 match self {
192 Self::NodeFailed { .. } | Self::Error(_) => true,
193 Self::InputClosed { reason, .. } => !reason.is_expected(),
194 _ => false,
195 }
196 }
197
198 #[must_use]
200 pub const fn metadata(&self) -> Option<&Metadata> {
201 match self {
202 Self::Input { meta, .. } => Some(meta),
203 _ => None,
204 }
205 }
206
207 #[must_use]
209 pub const fn payload(&self) -> Option<&Payload> {
210 match self {
211 Self::Input { data, .. } => Some(data),
212 _ => None,
213 }
214 }
215
216 #[must_use]
219 pub fn into_input(self) -> Option<(DataId, Metadata, Payload)> {
220 match self {
221 Self::Input { id, meta, data } => Some((id, meta, data)),
222 _ => None,
223 }
224 }
225
226 #[must_use]
228 pub const fn kind_name(&self) -> &'static str {
229 match self {
230 Self::Input { .. } => "input",
231 Self::InputClosed { .. } => "input_closed",
232 Self::InputRecovered { .. } => "input_recovered",
233 Self::Stop(_) => "stop",
234 Self::Reload { .. } => "reload",
235 Self::AllInputsClosed => "all_inputs_closed",
236 Self::ParamUpdate { .. } => "param_update",
237 Self::ParamDeleted { .. } => "param_deleted",
238 Self::NodeFailed { .. } => "node_failed",
239 Self::Restarted { .. } => "restarted",
240 Self::ExtDropped { .. } => "ext_dropped",
241 Self::Error(_) => "error",
242 }
243 }
244}
245
246impl core::fmt::Display for Event {
247 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
248 match self {
249 Self::Input { id, data, .. } => write!(f, "input {id} ({data})"),
250 Self::InputClosed { id, reason, .. } => write!(f, "input {id} closed: {reason}"),
251 Self::InputRecovered { id, generation, .. } => {
252 write!(f, "input {id} recovered at generation {generation}")
253 }
254 Self::Stop(cause) => write!(f, "stop: {cause}"),
255 Self::Reload { operator, .. } => match operator {
256 Some(operator) => write!(f, "reload operator {operator}"),
257 None => f.write_str("reload node"),
258 },
259 Self::AllInputsClosed => f.write_str("all inputs closed"),
260 Self::ParamUpdate { scope, key, value } => write!(f, "{scope}: {key} = {value}"),
261 Self::ParamDeleted { scope, key } => write!(f, "{scope}: {key} deleted"),
262 Self::NodeFailed { peer, cause } => write!(f, "peer {peer} failed: {cause}"),
263 Self::Restarted { peer, generation } => {
264 write!(f, "peer {peer} restarted as generation {generation}")
265 }
266 Self::ExtDropped { key, reason } => write!(f, "extension {key} dropped: {reason}"),
267 Self::Error(message) => write!(f, "error: {message}"),
268 }
269 }
270}
271
272#[cfg(test)]
273mod tests {
274 #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
275
276 use super::*;
277 use astrs_time::HlcTimestamp;
278
279 fn input() -> Event {
280 Event::Input {
281 id: DataId::new("frames").unwrap(),
282 meta: Metadata::new(HlcTimestamp::new(1, 0)),
283 data: Payload::inline(vec![1, 2, 3]),
284 }
285 }
286
287 fn every_variant() -> Vec<Event> {
288 vec![
289 input(),
290 Event::InputClosed {
291 id: DataId::new("frames").unwrap(),
292 source: PortRef::from_parts("camera", "image").unwrap(),
293 reason: RouteCloseReason::ProducerFinished,
294 },
295 Event::InputRecovered {
296 id: DataId::new("frames").unwrap(),
297 source: PortRef::from_parts("camera", "image").unwrap(),
298 generation: 2,
299 },
300 Event::Stop(StopCause::Requested),
301 Event::Reload {
302 operator: None,
303 path: None,
304 },
305 Event::AllInputsClosed,
306 Event::ParamUpdate {
307 scope: ParamScope::Global,
308 key: ParamKey::new("gain").unwrap(),
309 value: Parameter::from(2.0),
310 },
311 Event::ParamDeleted {
312 scope: ParamScope::Global,
313 key: ParamKey::new("gain").unwrap(),
314 },
315 Event::NodeFailed {
316 peer: NodeId::new("camera").unwrap(),
317 cause: NodeExitCause::Success,
318 },
319 Event::Restarted {
320 peer: NodeId::new("camera").unwrap(),
321 generation: 1,
322 },
323 Event::ExtDropped {
324 key: ExtensionKey::user("calibration").unwrap(),
325 reason: "ttl".to_owned(),
326 },
327 Event::Error("queue overflow".to_owned()),
328 ]
329 }
330
331 #[test]
332 fn every_variant_renders_and_classifies() {
333 for event in every_variant() {
334 assert!(!event.to_string().is_empty(), "{event:?}");
335 assert!(!event.kind_name().is_empty());
336 }
337 }
338
339 #[test]
340 fn kind_names_are_unique() {
341 let mut names: Vec<&str> = every_variant().iter().map(Event::kind_name).collect();
342 let total = names.len();
343 names.sort_unstable();
344 names.dedup();
345 assert_eq!(names.len(), total);
346 }
347
348 #[test]
349 fn the_control_lane_is_everything_that_is_not_an_input() {
350 for event in every_variant() {
351 let data_lane = matches!(
352 event,
353 Event::Input { .. } | Event::InputClosed { .. } | Event::InputRecovered { .. }
354 );
355 assert_eq!(event.is_control(), !data_lane, "{event}");
356 }
357 }
358
359 #[test]
360 fn inputs_expose_their_parts() {
361 let event = input();
362 assert!(event.is_input());
363 assert!(!event.is_stop());
364 assert_eq!(event.input().map(DataId::as_str), Some("frames"));
365 assert!(event.metadata().is_some());
366 assert_eq!(event.payload().map(Payload::len), Some(3));
367
368 let (id, meta, data) = input().into_input().unwrap();
369 assert_eq!(id.as_str(), "frames");
370 assert_eq!(meta.timestamp, HlcTimestamp::new(1, 0));
371 assert_eq!(data.len(), 3);
372 assert!(Event::AllInputsClosed.into_input().is_none());
373 }
374
375 #[test]
376 fn stop_is_the_only_fusing_event() {
377 for event in every_variant() {
378 assert_eq!(event.is_stop(), matches!(event, Event::Stop(_)));
379 }
380 }
381
382 #[test]
383 fn faults_are_reported_as_faults() {
384 assert!(Event::Error(String::new()).is_fault());
385 assert!(
386 Event::NodeFailed {
387 peer: NodeId::new("x").unwrap(),
388 cause: NodeExitCause::Success
389 }
390 .is_fault()
391 );
392 assert!(!input().is_fault());
393 assert!(
394 !Event::InputClosed {
395 id: DataId::new("a").unwrap(),
396 source: PortRef::from_parts("b", "c").unwrap(),
397 reason: RouteCloseReason::ProducerFinished,
398 }
399 .is_fault(),
400 "a producer finishing is not a fault"
401 );
402 }
403}