1use std::collections::BTreeMap;
4use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
5
6use adk_core::audit_log::{AuditRecordDraft, AuditRecordKind, AuditRecordOutcome};
7use chrono::{DateTime, Utc};
8use futures::FutureExt;
9use serde::{Deserialize, Serialize};
10use serde_json::json;
11use tokio::task::JoinHandle;
12use tokio_util::sync::CancellationToken;
13
14use super::FrameSource;
15use super::governor::FrameBudget;
16use super::pipeline::{ObservationSink, StopCause, StreamPipeline, StreamSummary};
17use super::privacy::{NoRedaction, PrivacyHook};
18use super::retention::FrameKeeper;
19use super::watching::StreamWatch;
20use crate::audit::VISION_AUDIT_KIND;
21use crate::cx::VisionCx;
22use crate::error::{Result, VisionError};
23use crate::media::FrameSourceId;
24use crate::runtime::VisionRuntime;
25use crate::traits::{DetectQuery, Sampling, Tracker};
26use crate::watch::{
27 VISION_WATCH_STOPPED, WatchCondition, WatchEvaluator, WatchSink, watch_registered_draft,
28};
29
30pub type TrackerFactory = Arc<dyn Fn() -> Box<dyn Tracker> + Send + Sync>;
33
34#[must_use]
63pub struct SourceSpec {
64 source: Arc<dyn FrameSource>,
65 privacy: Arc<dyn PrivacyHook>,
66 keeper: Arc<FrameKeeper>,
67 wakes: Arc<dyn WatchSink>,
68 description: Option<String>,
69 detection: Option<(Arc<VisionRuntime>, DetectQuery)>,
70 tracker: Option<TrackerFactory>,
71 sampling: Option<Sampling>,
72 budget: Option<FrameBudget>,
73 observer: Option<Arc<dyn ObservationSink>>,
74}
75
76impl std::fmt::Debug for SourceSpec {
77 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
78 f.debug_struct("SourceSpec")
79 .field("source", self.source.id())
80 .field("description", &self.description)
81 .field("sampling", &self.sampling)
82 .field("budget", &self.budget)
83 .finish_non_exhaustive()
84 }
85}
86
87impl SourceSpec {
88 pub fn new(
91 source: Arc<dyn FrameSource>,
92 keeper: Arc<FrameKeeper>,
93 wakes: Arc<dyn WatchSink>,
94 ) -> Self {
95 Self {
96 source,
97 privacy: Arc::new(NoRedaction),
98 keeper,
99 wakes,
100 description: None,
101 detection: None,
102 tracker: None,
103 sampling: None,
104 budget: None,
105 observer: None,
106 }
107 }
108
109 pub fn with_privacy(mut self, hook: Arc<dyn PrivacyHook>) -> Self {
112 self.privacy = hook;
113 self
114 }
115
116 pub fn describe(mut self, description: impl Into<String>) -> Self {
118 self.description = Some(description.into());
119 self
120 }
121
122 pub fn detector(mut self, runtime: Arc<VisionRuntime>, query: DetectQuery) -> Self {
125 self.detection = Some((runtime, query));
126 self
127 }
128
129 pub fn tracker(mut self, factory: TrackerFactory) -> Self {
131 self.tracker = Some(factory);
132 self
133 }
134
135 pub fn sampling(mut self, sampling: Sampling) -> Self {
137 self.sampling = Some(sampling);
138 self
139 }
140
141 pub fn budget(mut self, budget: FrameBudget) -> Self {
143 self.budget = Some(budget);
144 self
145 }
146
147 pub fn observer(mut self, observer: Arc<dyn ObservationSink>) -> Self {
149 self.observer = Some(observer);
150 self
151 }
152
153 fn labels(&self) -> Vec<String> {
154 match &self.detection {
155 Some((_, DetectQuery::Classes(labels) | DetectQuery::Concepts(labels))) => {
156 labels.clone()
157 }
158 None => Vec::new(),
159 }
160 }
161
162 fn check(&self, condition: &WatchCondition) -> Result<()> {
164 condition.validate()?;
165 let id = &self.source.id().0;
166 if self.detection.is_none() {
167 return Err(VisionError::InvalidInput(format!(
168 "source `{id}` has no detector, so no watch condition can fire on it"
169 )));
170 }
171 let labels = self.labels();
172 let unknown: Vec<&String> = condition
173 .labels
174 .iter()
175 .filter(|wanted| !labels.iter().any(|label| label.eq_ignore_ascii_case(wanted)))
176 .collect();
177 if !unknown.is_empty() {
178 return Err(VisionError::InvalidInput(format!(
179 "source `{id}` detects {labels:?}; the watch condition `{}` names {unknown:?}, \
180 which it never reports",
181 condition.name
182 )));
183 }
184 Ok(())
185 }
186
187 fn pipeline(&self, watch: Arc<StreamWatch>) -> Result<StreamPipeline> {
188 let mut builder =
189 StreamPipeline::builder(self.source.clone()).with_privacy(self.privacy.clone());
190 if let Some(sampling) = self.sampling {
191 builder = builder.sampling(sampling);
192 }
193 if let Some((runtime, query)) = &self.detection {
194 builder = builder.detector(runtime.clone(), query.clone());
195 }
196 if let Some(factory) = &self.tracker {
197 builder = builder.tracker(factory());
198 }
199 if let Some(budget) = &self.budget {
200 builder = builder.budget(budget.clone());
201 }
202 builder.sink(watch).build()
203 }
204}
205
206#[non_exhaustive]
208#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
209#[serde(rename_all = "camelCase")]
210pub enum WatchChange {
211 Registered,
213 Unchanged,
215 Removed,
217 NotWatched,
219}
220
221#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
223#[serde(rename_all = "camelCase")]
224pub struct StreamEnd {
225 pub cause: StopCause,
227 pub summary: StreamSummary,
229 pub ended_at: DateTime<Utc>,
231}
232
233#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
235#[serde(rename_all = "camelCase")]
236pub struct SourceStatus {
237 pub source: FrameSourceId,
239 #[serde(default, skip_serializing_if = "Option::is_none")]
241 pub description: Option<String>,
242 pub labels: Vec<String>,
244 pub streaming: bool,
246 pub conditions: Vec<WatchCondition>,
248 pub fired: u64,
250 #[serde(default, skip_serializing_if = "Option::is_none")]
252 pub last_end: Option<StreamEnd>,
253}
254
255#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
257#[serde(rename_all = "camelCase")]
258pub struct WatchOutcome {
259 pub change: WatchChange,
261 pub status: SourceStatus,
263}
264
265struct Running {
266 watch: Arc<StreamWatch>,
267 cancel: CancellationToken,
268 task: JoinHandle<Result<StreamSummary>>,
269}
270
271struct Entry {
272 spec: Arc<SourceSpec>,
273 conditions: Vec<WatchCondition>,
274 running: Option<Running>,
275 last_end: Option<StreamEnd>,
276}
277
278impl Entry {
279 fn reap(&mut self) {
281 let finished = self.running.as_ref().is_some_and(|running| running.task.is_finished());
282 if !finished {
283 return;
284 }
285 if let Some(running) = self.running.take() {
286 let outcome = running.task.now_or_never();
287 self.last_end = Some(end_of(outcome, false));
288 }
289 }
290
291 fn status(&self) -> SourceStatus {
292 SourceStatus {
293 source: self.spec.source.id().clone(),
294 description: self.spec.description.clone(),
295 labels: self.spec.labels(),
296 streaming: self.running.is_some(),
297 conditions: self.conditions.clone(),
298 fired: self.running.as_ref().map_or(0, |running| running.watch.fired()),
299 last_end: self.last_end.clone(),
300 }
301 }
302}
303
304type Joined = std::result::Result<Result<StreamSummary>, tokio::task::JoinError>;
305
306fn end_of(outcome: Option<Joined>, cancelled: bool) -> StreamEnd {
307 let (cause, summary) = match outcome {
308 Some(Ok(Ok(summary))) if cancelled => (StopCause::Cancelled, summary),
309 Some(Ok(Ok(summary))) => (StopCause::Ended, summary),
310 Some(Ok(Err(err))) => (
311 StopCause::Failed { code: err.code().to_string(), message: err.to_string() },
312 StreamSummary::default(),
313 ),
314 Some(Err(err)) => (
315 StopCause::Failed { code: "vision.stream.panicked".into(), message: err.to_string() },
316 StreamSummary::default(),
317 ),
318 None => (StopCause::Cancelled, StreamSummary::default()),
319 };
320 StreamEnd { cause, summary, ended_at: Utc::now() }
321}
322
323#[derive(Clone)]
351pub struct FrameSources {
352 inner: Arc<Inner>,
353}
354
355struct Inner {
356 cx: VisionCx,
357 entries: Mutex<BTreeMap<FrameSourceId, Entry>>,
358}
359
360impl std::fmt::Debug for FrameSources {
361 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
362 f.debug_struct("FrameSources").field("sources", &self.names()).finish_non_exhaustive()
363 }
364}
365
366impl FrameSources {
367 pub fn new(cx: VisionCx) -> Self {
370 Self { inner: Arc::new(Inner { cx, entries: Mutex::new(BTreeMap::new()) }) }
371 }
372
373 fn entries(&self) -> MutexGuard<'_, BTreeMap<FrameSourceId, Entry>> {
374 self.inner.entries.lock().unwrap_or_else(PoisonError::into_inner)
375 }
376
377 pub fn register(&self, spec: SourceSpec) -> Result<()> {
383 let id = spec.source.id().clone();
384 let mut entries = self.entries();
385 if entries.contains_key(&id) {
386 return Err(VisionError::InvalidInput(format!(
387 "a frame source named `{}` is already registered",
388 id.0
389 )));
390 }
391 entries.insert(
392 id,
393 Entry { spec: Arc::new(spec), conditions: Vec::new(), running: None, last_end: None },
394 );
395 Ok(())
396 }
397
398 pub fn names(&self) -> Vec<FrameSourceId> {
400 self.entries().keys().cloned().collect()
401 }
402
403 pub fn statuses(&self) -> Vec<SourceStatus> {
405 self.entries()
406 .values_mut()
407 .map(|entry| {
408 entry.reap();
409 entry.status()
410 })
411 .collect()
412 }
413
414 pub fn status(&self, source: &FrameSourceId) -> Result<SourceStatus> {
420 let mut entries = self.entries();
421 let entry = entries.get_mut(source).ok_or_else(|| unknown(source))?;
422 entry.reap();
423 Ok(entry.status())
424 }
425
426 async fn audit(&self, cx: &VisionCx, draft: AuditRecordDraft) -> Result<()> {
427 if cx.audit_trail().is_some() {
428 cx.audit(draft).await
429 } else {
430 self.inner.cx.audit(draft).await
431 }
432 }
433
434 pub async fn start_watch(
444 &self,
445 cx: &VisionCx,
446 source: &FrameSourceId,
447 condition: WatchCondition,
448 ) -> Result<WatchOutcome> {
449 cx.check()?;
450 let change = {
451 let mut entries = self.entries();
452 let entry = entries.get_mut(source).ok_or_else(|| unknown(source))?;
453 entry.reap();
454 entry.spec.check(&condition)?;
455 let change = match entry.conditions.iter().find(|c| c.name == condition.name) {
456 Some(existing) if *existing == condition => WatchChange::Unchanged,
457 Some(_) => {
458 return Err(VisionError::InvalidInput(format!(
459 "a watch named `{}` is already registered on `{}` with other settings; \
460 stop it first",
461 condition.name, source.0
462 )));
463 }
464 None => {
465 entry.conditions.push(condition.clone());
466 WatchChange::Registered
467 }
468 };
469 match &entry.running {
470 Some(running) => {
471 if change == WatchChange::Registered {
472 running.watch.add_condition(condition.clone())?;
473 }
474 }
475 None => {
476 if let Err(err) = self.spawn(entry) {
477 if change == WatchChange::Registered {
478 entry.conditions.retain(|c| c.name != condition.name);
479 }
480 return Err(err);
481 }
482 }
483 }
484 change
485 };
486 if change == WatchChange::Registered {
487 self.audit(cx, watch_registered_draft(source, &condition)).await?;
488 tracing::info!(vision.source = %source.0, vision.condition = %condition.name, "watch registered");
489 }
490 Ok(WatchOutcome { change, status: self.status(source)? })
491 }
492
493 fn spawn(&self, entry: &mut Entry) -> Result<()> {
495 let evaluator = WatchEvaluator::new(entry.conditions.clone())?;
496 let mut watch =
497 StreamWatch::new(evaluator, entry.spec.keeper.clone(), entry.spec.wakes.clone());
498 if let Some(observer) = &entry.spec.observer {
499 watch = watch.with_observer(observer.clone());
500 }
501 let watch = Arc::new(watch);
502 let pipeline = entry.spec.pipeline(watch.clone())?;
503 let cancel = self.inner.cx.cancellation().child_token();
504 let cx = self.inner.cx.clone().with_cancellation(cancel.clone());
505 let task = tokio::spawn(async move { pipeline.run(&cx).await });
506 entry.running = Some(Running { watch, cancel, task });
507 Ok(())
508 }
509
510 pub async fn stop_watch(
518 &self,
519 cx: &VisionCx,
520 source: &FrameSourceId,
521 name: &str,
522 ) -> Result<WatchOutcome> {
523 let (removed, stopping) = {
524 let mut entries = self.entries();
525 let entry = entries.get_mut(source).ok_or_else(|| unknown(source))?;
526 entry.reap();
527 let removed = entry
528 .conditions
529 .iter()
530 .position(|c| c.name == name)
531 .map(|index| entry.conditions.remove(index));
532 if removed.is_some()
533 && let Some(running) = &entry.running
534 {
535 running.watch.remove_condition(name);
536 }
537 let stopping = if entry.conditions.is_empty() { entry.running.take() } else { None };
538 (removed, stopping)
539 };
540 if let Some(running) = stopping {
541 running.cancel.cancel();
542 let outcome = running.task.await;
543 let end = end_of(Some(outcome), true);
544 if let Some(entry) = self.entries().get_mut(source) {
545 entry.last_end = Some(end);
546 }
547 }
548 let change = match &removed {
549 Some(condition) => {
550 self.audit(cx, watch_stopped_draft(source, condition)).await?;
551 tracing::info!(vision.source = %source.0, vision.condition = %name, "watch stopped");
552 WatchChange::Removed
553 }
554 None => WatchChange::NotWatched,
555 };
556 Ok(WatchOutcome { change, status: self.status(source)? })
557 }
558
559 pub async fn shutdown(&self) {
561 let running: Vec<(FrameSourceId, Running)> = self
562 .entries()
563 .iter_mut()
564 .filter_map(|(id, entry)| entry.running.take().map(|running| (id.clone(), running)))
565 .collect();
566 for (id, running) in running {
567 running.cancel.cancel();
568 let end = end_of(Some(running.task.await), true);
569 if let Some(entry) = self.entries().get_mut(&id) {
570 entry.last_end = Some(end);
571 }
572 }
573 }
574}
575
576fn unknown(source: &FrameSourceId) -> VisionError {
577 VisionError::InvalidInput(format!(
578 "no frame source is registered as `{}`; list the sources with the `list` action",
579 source.0
580 ))
581}
582
583pub(crate) fn watch_stopped_draft(
585 source: &FrameSourceId,
586 condition: &WatchCondition,
587) -> AuditRecordDraft {
588 AuditRecordDraft::new(
589 AuditRecordKind::Other(VISION_AUDIT_KIND.to_string()),
590 VISION_WATCH_STOPPED,
591 )
592 .outcome(AuditRecordOutcome::Succeeded)
593 .payload_ref(condition.digest().to_string())
594 .ext("source", json!(source))
595 .ext("condition", json!(condition.name))
596 .ext("conditionDigest", json!(condition.digest()))
597}