adk_vision/stream/watching.rs
1//! [`StreamWatch`]: the watch stage of a stream — conditions, the kept frame, the wake.
2
3use std::sync::atomic::{AtomicU64, Ordering};
4use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
5
6use async_trait::async_trait;
7
8use super::pipeline::{Observation, ObservationSink, SourceEvent};
9use super::retention::{FrameKeeper, KeepReason};
10use crate::cx::VisionCx;
11use crate::error::Result;
12use crate::watch::{WatchCondition, WatchEvaluator, WatchSink};
13
14/// The watch stage of a stream (spec 3.7 §7.10): an [`ObservationSink`] that holds watch
15/// conditions against every observation and, for each event that passes,
16///
17/// 1. keeps the frame through its [`FrameKeeper`] as [`KeepReason::WakePayload`] — the frame
18/// is stored redacted, once however many events it carries;
19/// 2. names the kept artifact in the event ([`WatchEvent::with_frame_artifact`]);
20/// 3. writes the `vision.watch.fired` audit record, by digest only (V-I15);
21/// 4. delivers the event to its [`WatchSink`], such as the kernel's `VisionWakeSource`.
22///
23/// Conditions can be added and removed while the stream runs; the others keep their
24/// streaks. A second sink, such as the live camera surface, can see every observation and
25/// source event after the watch ([`with_observer`](Self::with_observer)).
26///
27/// # Example
28///
29/// ```
30/// use std::sync::{Arc, Mutex};
31/// use adk_artifact::InMemoryArtifactService;
32/// use adk_vision::stream::{FrameKeeper, StreamWatch};
33/// use adk_vision::{FrameSourceId, MediaScope, WatchCondition, WatchEvaluator, WatchEvent, WatchSink};
34///
35/// #[derive(Default)]
36/// struct Wakes(Mutex<Vec<String>>);
37///
38/// #[async_trait::async_trait]
39/// impl WatchSink for Wakes {
40/// async fn deliver(&self, event: &WatchEvent) -> adk_vision::Result<()> {
41/// self.0.lock().unwrap().push(event.key());
42/// Ok(())
43/// }
44/// }
45///
46/// let source = FrameSourceId("conveyor-1".into());
47/// let keeper = FrameKeeper::new(
48/// Arc::new(InMemoryArtifactService::new()),
49/// MediaScope::new("inspector", "line-1", "shift-1"),
50/// source,
51/// );
52/// let watch = StreamWatch::new(WatchEvaluator::new(Vec::new()).unwrap(), Arc::new(keeper), Arc::new(Wakes::default()));
53/// watch.add_condition(WatchCondition::new("torn-seal", ["torn seal"])).unwrap();
54/// assert_eq!(watch.conditions().len(), 1);
55/// ```
56///
57/// [`WatchEvent::with_frame_artifact`]: crate::WatchEvent::with_frame_artifact
58pub struct StreamWatch {
59 // Locked only between awaits: `observe` takes the events out before it keeps or wakes.
60 evaluator: Mutex<WatchEvaluator>,
61 keeper: Arc<FrameKeeper>,
62 wakes: Arc<dyn WatchSink>,
63 observer: Option<Arc<dyn ObservationSink>>,
64 fired: AtomicU64,
65}
66
67impl std::fmt::Debug for StreamWatch {
68 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
69 f.debug_struct("StreamWatch")
70 .field("conditions", &self.conditions().len())
71 .field("keeper", &self.keeper)
72 .field("fired", &self.fired())
73 .finish_non_exhaustive()
74 }
75}
76
77impl StreamWatch {
78 /// A watch holding `evaluator`'s conditions, keeping each event's frame with `keeper`
79 /// and delivering the event to `wakes`.
80 pub fn new(
81 evaluator: WatchEvaluator,
82 keeper: Arc<FrameKeeper>,
83 wakes: Arc<dyn WatchSink>,
84 ) -> Self {
85 Self {
86 evaluator: Mutex::new(evaluator),
87 keeper,
88 wakes,
89 observer: None,
90 fired: AtomicU64::new(0),
91 }
92 }
93
94 /// Hands every observation and source event on to `observer` after the watch has seen it.
95 #[must_use]
96 pub fn with_observer(mut self, observer: Arc<dyn ObservationSink>) -> Self {
97 self.observer = Some(observer);
98 self
99 }
100
101 fn evaluator(&self) -> MutexGuard<'_, WatchEvaluator> {
102 self.evaluator.lock().unwrap_or_else(PoisonError::into_inner)
103 }
104
105 /// The conditions now held.
106 pub fn conditions(&self) -> Vec<WatchCondition> {
107 self.evaluator().conditions().to_vec()
108 }
109
110 /// Adds a condition while the stream runs.
111 ///
112 /// # Errors
113 ///
114 /// As [`WatchEvaluator::add`].
115 pub fn add_condition(&self, condition: WatchCondition) -> Result<()> {
116 self.evaluator().add(condition)
117 }
118
119 /// Removes the condition named `name`.
120 pub fn remove_condition(&self, name: &str) -> Option<WatchCondition> {
121 self.evaluator().remove(name)
122 }
123
124 /// How many events the watch has delivered.
125 pub fn fired(&self) -> u64 {
126 self.fired.load(Ordering::Relaxed)
127 }
128}
129
130#[async_trait]
131impl ObservationSink for StreamWatch {
132 async fn observe(&self, cx: &VisionCx, observation: Observation) -> Result<()> {
133 let fired: Vec<_> = {
134 let mut evaluator = self.evaluator();
135 let events = evaluator.observe(&observation.tracked());
136 events
137 .into_iter()
138 .map(|event| {
139 let digest = evaluator.condition(&event.condition).map(WatchCondition::digest);
140 (event, digest)
141 })
142 .collect()
143 };
144 if !fired.is_empty() {
145 let kept = self.keeper.keep(cx, &observation.image, KeepReason::WakePayload).await?;
146 for (event, condition) in fired {
147 let event = event.with_frame_artifact(kept.image.artifact.clone());
148 if let Some(condition) = condition {
149 cx.audit(event.audit_draft(condition)).await?;
150 }
151 tracing::info!(
152 vision.source = %event.source.0,
153 vision.condition = %event.condition,
154 vision.track = event.track.0,
155 vision.frame = event.frame.index,
156 "watch condition fired"
157 );
158 self.wakes.deliver(&event).await?;
159 self.fired.fetch_add(1, Ordering::Relaxed);
160 }
161 }
162 match &self.observer {
163 Some(observer) => observer.observe(cx, observation).await,
164 None => Ok(()),
165 }
166 }
167
168 async fn source_event(&self, cx: &VisionCx, event: &SourceEvent) -> Result<()> {
169 match &self.observer {
170 Some(observer) => observer.source_event(cx, event).await,
171 None => Ok(()),
172 }
173 }
174}