Skip to main content

adk_vision/stream/
retention.rs

1//! Frame retention (spec 3.7 §7.13, Q13): frames are ephemeral unless they become a wake
2//! payload, evidence on a card, or a sample a person kept.
3
4use std::sync::Arc;
5use std::time::Duration;
6
7use adk_artifact::{ArtifactService, DeleteRequest, LoadRequest, SaveRequest, VersionsRequest};
8use adk_core::{ErrorCategory, Part};
9use chrono::{DateTime, Utc};
10use serde::{Deserialize, Serialize};
11use serde_json::json;
12
13use super::privacy::RedactedFrame;
14use super::records::{VISION_EVIDENCE_KEPT, VISION_EVIDENCE_PURGED, evidence_draft};
15use crate::cx::VisionCx;
16use crate::digest::Digest;
17use crate::error::{Result, VisionError};
18use crate::media::{FrameSourceId, ImageRef, MediaScope, MediaStore, Provenance};
19
20/// How long an evidence frame is kept by default: 30 days (spec 3.7 Q13).
21pub const EVIDENCE_RETENTION: Duration = Duration::from_secs(30 * 24 * 60 * 60);
22
23/// Why a frame is kept.
24#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
25#[serde(rename_all = "camelCase")]
26pub enum KeepReason {
27    /// It is the frame a wake payload names.
28    WakePayload,
29    /// It is evidence on a card: an approval, a stopped line.
30    CardEvidence,
31    /// A person asked to keep it.
32    PersonKept,
33}
34
35/// How long a source's kept frames live, per [`KeepReason`]: 30 days for each by default
36/// (spec 3.7 Q13).
37///
38/// # Example
39///
40/// ```
41/// use std::time::Duration;
42/// use adk_vision::stream::{EVIDENCE_RETENTION, KeepReason, RetentionPolicy};
43///
44/// let policy = RetentionPolicy::default()
45///     .with_reason(KeepReason::PersonKept, Duration::from_secs(90 * 86_400));
46/// assert_eq!(policy.for_reason(KeepReason::CardEvidence), EVIDENCE_RETENTION);
47/// assert_eq!(policy.for_reason(KeepReason::PersonKept).as_secs(), 90 * 86_400);
48/// ```
49#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
50#[serde(rename_all = "camelCase")]
51pub struct RetentionPolicy {
52    /// Frames a wake payload names.
53    pub wake_payload: Duration,
54    /// Frames on cards.
55    pub card_evidence: Duration,
56    /// Frames a person kept.
57    pub person_kept: Duration,
58}
59
60impl Default for RetentionPolicy {
61    fn default() -> Self {
62        Self::evidence(EVIDENCE_RETENTION)
63    }
64}
65
66impl RetentionPolicy {
67    /// The same retention for every reason.
68    pub fn evidence(retention: Duration) -> Self {
69        Self { wake_payload: retention, card_evidence: retention, person_kept: retention }
70    }
71
72    /// Sets the retention of one reason.
73    pub fn with_reason(mut self, reason: KeepReason, retention: Duration) -> Self {
74        match reason {
75            KeepReason::WakePayload => self.wake_payload = retention,
76            KeepReason::CardEvidence => self.card_evidence = retention,
77            KeepReason::PersonKept => self.person_kept = retention,
78        }
79        self
80    }
81
82    /// The retention of `reason`.
83    pub fn for_reason(&self, reason: KeepReason) -> Duration {
84        match reason {
85            KeepReason::WakePayload => self.wake_payload,
86            KeepReason::CardEvidence => self.card_evidence,
87            KeepReason::PersonKept => self.person_kept,
88        }
89    }
90}
91
92/// One kept frame.
93#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
94#[serde(rename_all = "camelCase")]
95pub struct RetentionEntry {
96    /// The stored image.
97    pub image: ImageRef,
98    /// Why it is kept; a frame kept twice lists both reasons.
99    pub reasons: Vec<KeepReason>,
100    /// The frame's index in its stream.
101    pub frame_index: u64,
102    /// When it was first kept.
103    pub kept_at: DateTime<Utc>,
104    /// When it is purged: the latest expiry of its reasons.
105    pub expires_at: DateTime<Utc>,
106    /// The privacy hook the frame passed before its write.
107    pub privacy: String,
108    /// How many boxes the hook redacted.
109    pub redacted: usize,
110}
111
112/// Why a kept frame was deleted.
113#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
114#[serde(rename_all = "camelCase")]
115pub enum PurgeCause {
116    /// Its retention ran out.
117    Expired,
118    /// Its source's frames were erased.
119    Erased,
120}
121
122/// A deleted frame.
123#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
124#[serde(rename_all = "camelCase")]
125pub struct PurgedFrame {
126    /// What was kept.
127    pub entry: RetentionEntry,
128    /// Why it went.
129    pub cause: PurgeCause,
130}
131
132/// Stores the frames of one source that a wake, a card or a person keeps, and deletes them
133/// when their retention runs out (spec 3.7 §7.13, Q13).
134///
135/// Only a [`RedactedFrame`] can be kept, so every stored frame passed its privacy hook
136/// before the write (V-I9, S18). Frames go to the media store as PNG, by digest, so a frame
137/// kept for a wake and again for a card is one artifact with both reasons. The keeper's
138/// index is itself an artifact in the scope, `vision-retention-<source>-<hash>.json`, so a
139/// restarted process still purges what an earlier one kept. Every keep writes
140/// `vision.evidence.kept`, and every deletion `vision.evidence.purged`, with the frame's
141/// digest, never its pixels.
142///
143/// # Example
144///
145/// ```
146/// use std::sync::Arc;
147/// use std::time::Duration;
148/// use adk_artifact::InMemoryArtifactService;
149/// use adk_vision::stream::{FrameKeeper, FramePrivacy, KeepReason, NoRedaction};
150/// use adk_vision::{DecodedImage, Frame, FramePixels, FrameSourceId, MediaScope, VisionCx};
151///
152/// # tokio::runtime::Runtime::new().unwrap().block_on(async {
153/// let source = FrameSourceId("line-1".into());
154/// let keeper = FrameKeeper::new(
155///     Arc::new(InMemoryArtifactService::new()),
156///     MediaScope::new("inspector", "u1", "s1"),
157///     source.clone(),
158/// );
159/// let frame = Frame {
160///     source,
161///     index: 7,
162///     pts: Duration::from_millis(700),
163///     captured_at: chrono::Utc::now(),
164///     pixels: FramePixels::Ephemeral(Arc::new(DecodedImage::filled(8, 8, [40; 4]))),
165/// };
166/// let cx = VisionCx::new();
167/// let redacted = FramePrivacy::new(Arc::new(NoRedaction)).apply(&cx, frame).await.unwrap();
168/// let kept = keeper.keep(&cx, &redacted, KeepReason::WakePayload).await.unwrap();
169/// assert_eq!(kept.reasons, vec![KeepReason::WakePayload]);
170/// // Thirty days on, it is gone.
171/// let later = kept.kept_at + chrono::TimeDelta::days(31);
172/// assert_eq!(keeper.purge_expired(&cx, later).await.unwrap().len(), 1);
173/// # });
174/// ```
175pub struct FrameKeeper {
176    artifacts: Arc<dyn ArtifactService>,
177    store: MediaStore,
178    scope: MediaScope,
179    source: FrameSourceId,
180    policy: RetentionPolicy,
181    provenance: Provenance,
182    index_file: String,
183    // Serialises read-modify-write of the index artifact.
184    index: tokio::sync::Mutex<()>,
185}
186
187impl std::fmt::Debug for FrameKeeper {
188    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
189        f.debug_struct("FrameKeeper")
190            .field("scope", &self.scope)
191            .field("source", &self.source)
192            .field("policy", &self.policy)
193            .finish_non_exhaustive()
194    }
195}
196
197impl FrameKeeper {
198    /// A keeper of `source`'s frames in `scope`, with the default 30-day policy and camera
199    /// provenance.
200    pub fn new(
201        artifacts: Arc<dyn ArtifactService>,
202        scope: MediaScope,
203        source: FrameSourceId,
204    ) -> Self {
205        let safe: String = source
206            .0
207            .chars()
208            .map(|c| if c.is_ascii_alphanumeric() || c == '-' || c == '_' { c } else { '_' })
209            .take(48)
210            .collect();
211        let tag = &Digest::of(source.0.as_bytes()).hex()[..8];
212        Self {
213            store: MediaStore::new(Arc::clone(&artifacts)),
214            artifacts,
215            scope,
216            provenance: Provenance::Camera { source: source.clone() },
217            index_file: format!("vision-retention-{safe}-{tag}.json"),
218            source,
219            policy: RetentionPolicy::default(),
220            index: tokio::sync::Mutex::new(()),
221        }
222    }
223
224    /// Sets the retention policy.
225    pub fn with_policy(mut self, policy: RetentionPolicy) -> Self {
226        self.policy = policy;
227        self
228    }
229
230    /// Sets the provenance kept frames record: [`Provenance::Screen`] or
231    /// [`Provenance::Browser`] for those sources.
232    pub fn with_provenance(mut self, provenance: Provenance) -> Self {
233        self.provenance = provenance;
234        self
235    }
236
237    /// The retention policy.
238    pub fn policy(&self) -> &RetentionPolicy {
239        &self.policy
240    }
241
242    /// Keeps `frame` for `reason`, now.
243    ///
244    /// # Errors
245    ///
246    /// As [`keep_at`](Self::keep_at).
247    pub async fn keep(
248        &self,
249        cx: &VisionCx,
250        frame: &RedactedFrame,
251        reason: KeepReason,
252    ) -> Result<RetentionEntry> {
253        self.keep_at(cx, frame, reason, Utc::now()).await
254    }
255
256    /// Keeps `frame` for `reason` as of `at`: stores it, records it in the index, and writes
257    /// `vision.evidence.kept`.
258    ///
259    /// # Errors
260    ///
261    /// [`VisionError::InvalidInput`] for a frame of another source, the encoder's or the
262    /// artifact service's error, or the audit trail's when it fails closed.
263    pub async fn keep_at(
264        &self,
265        cx: &VisionCx,
266        frame: &RedactedFrame,
267        reason: KeepReason,
268        at: DateTime<Utc>,
269    ) -> Result<RetentionEntry> {
270        if frame.meta().source != self.source {
271            return Err(VisionError::InvalidInput(format!(
272                "frame of `{}` handed to the keeper of `{}`",
273                frame.meta().source.0,
274                self.source.0
275            )));
276        }
277        let _guard = self.index.lock().await;
278        let (image, _) = self
279            .store
280            .put_pixels(&self.scope, frame.pixels().clone(), self.provenance.clone())
281            .await?;
282        let retention = self.policy.for_reason(reason);
283        let expires_at =
284            at + chrono::TimeDelta::from_std(retention).unwrap_or(chrono::TimeDelta::MAX);
285        let mut entries = self.load_index().await?;
286        let entry = match entries.iter_mut().find(|e| e.image.digest == image.digest) {
287            Some(existing) => {
288                if !existing.reasons.contains(&reason) {
289                    existing.reasons.push(reason);
290                    existing.reasons.sort();
291                }
292                existing.expires_at = existing.expires_at.max(expires_at);
293                existing.clone()
294            }
295            None => {
296                let entry = RetentionEntry {
297                    image,
298                    reasons: vec![reason],
299                    frame_index: frame.meta().index,
300                    kept_at: at,
301                    expires_at,
302                    privacy: frame.hook().to_string(),
303                    redacted: frame.redacted().len(),
304                };
305                entries.push(entry.clone());
306                entry
307            }
308        };
309        self.save_index(&entries).await?;
310        tracing::debug!(
311            frame.source = %self.source.0,
312            frame.index = entry.frame_index,
313            image.digest = %entry.image.digest,
314            "frame kept"
315        );
316        cx.audit(evidence_draft(
317            VISION_EVIDENCE_KEPT,
318            &entry.image.digest.to_string(),
319            json!({
320                "source": self.source.0,
321                "reason": reason,
322                "reasons": entry.reasons,
323                "retentionSecs": retention.as_secs(),
324                "expiresAt": entry.expires_at,
325                "scope": self.scope,
326                "artifact": entry.image.artifact,
327                "frameIndex": entry.frame_index,
328                "privacy": entry.privacy,
329                "redacted": entry.redacted,
330            }),
331        ))
332        .await?;
333        Ok(entry)
334    }
335
336    /// Every frame kept and not yet purged.
337    ///
338    /// # Errors
339    ///
340    /// The artifact service's error, or [`VisionError::Parse`] for an index that does not
341    /// parse.
342    pub async fn kept(&self) -> Result<Vec<RetentionEntry>> {
343        let _guard = self.index.lock().await;
344        self.load_index().await
345    }
346
347    /// Deletes every frame whose retention ran out by `now`.
348    ///
349    /// # Errors
350    ///
351    /// As [`erase`](Self::erase).
352    pub async fn purge_expired(
353        &self,
354        cx: &VisionCx,
355        now: DateTime<Utc>,
356    ) -> Result<Vec<PurgedFrame>> {
357        self.purge(cx, PurgeCause::Expired, |entry| entry.expires_at <= now).await
358    }
359
360    /// Deletes every frame of the source in the scope: erasure by scope.
361    ///
362    /// # Errors
363    ///
364    /// The artifact service's error, or the audit trail's when it fails closed. Frames
365    /// deleted before an error stay deleted and out of the index.
366    pub async fn erase(&self, cx: &VisionCx) -> Result<Vec<PurgedFrame>> {
367        self.purge(cx, PurgeCause::Erased, |_| true).await
368    }
369
370    async fn purge(
371        &self,
372        cx: &VisionCx,
373        cause: PurgeCause,
374        due: impl Fn(&RetentionEntry) -> bool,
375    ) -> Result<Vec<PurgedFrame>> {
376        let _guard = self.index.lock().await;
377        let entries = self.load_index().await?;
378        let (gone, mut keep): (Vec<_>, Vec<_>) = entries.into_iter().partition(|e| due(e));
379        let mut purged = Vec::with_capacity(gone.len());
380        let mut failure = None;
381        let mut gone = gone.into_iter();
382        for entry in gone.by_ref() {
383            let at = &entry.image.artifact;
384            let deleted = self
385                .artifacts
386                .delete(DeleteRequest {
387                    app_name: at.app_name.clone(),
388                    user_id: at.user_id.clone(),
389                    session_id: at.session_id.clone(),
390                    file_name: at.file_name.clone(),
391                    version: None,
392                })
393                .await;
394            match deleted {
395                Ok(()) => {}
396                Err(err) if err.category == ErrorCategory::NotFound => {}
397                Err(err) => {
398                    keep.push(entry);
399                    failure = Some(VisionError::from(err));
400                    break;
401                }
402            }
403            purged.push(PurgedFrame { entry, cause });
404        }
405        keep.extend(gone);
406        self.save_index(&keep).await?;
407        for frame in &purged {
408            cx.audit(evidence_draft(
409                VISION_EVIDENCE_PURGED,
410                &frame.entry.image.digest.to_string(),
411                json!({
412                    "source": self.source.0,
413                    "cause": cause,
414                    "reasons": frame.entry.reasons,
415                    "keptAt": frame.entry.kept_at,
416                    "expiresAt": frame.entry.expires_at,
417                    "scope": self.scope,
418                    "artifact": frame.entry.image.artifact,
419                }),
420            ))
421            .await?;
422        }
423        match failure {
424            Some(err) => Err(err),
425            None => Ok(purged),
426        }
427    }
428
429    async fn load_index(&self) -> Result<Vec<RetentionEntry>> {
430        let loaded = self
431            .artifacts
432            .load(LoadRequest {
433                app_name: self.scope.app_name.clone(),
434                user_id: self.scope.user_id.clone(),
435                session_id: self.scope.session_id.clone(),
436                file_name: self.index_file.clone(),
437                version: None,
438            })
439            .await;
440        let part = match loaded {
441            Ok(loaded) => loaded.part,
442            Err(err) if err.category == ErrorCategory::NotFound => return Ok(Vec::new()),
443            Err(err) => return Err(err.into()),
444        };
445        let bytes = match part {
446            Part::InlineData { data, .. } => data,
447            Part::Text { text } => text.into_bytes(),
448            _ => {
449                return Err(VisionError::Parse {
450                    backend: "frame-keeper".into(),
451                    message: format!("retention index {} is not JSON data", self.index_file),
452                });
453            }
454        };
455        serde_json::from_slice(&bytes).map_err(|err| VisionError::Parse {
456            backend: "frame-keeper".into(),
457            message: format!("retention index {}: {err}", self.index_file),
458        })
459    }
460
461    /// Saves the index as a new version, then deletes the older ones, so a failure between
462    /// the two leaves an index that still lists every stored frame.
463    async fn save_index(&self, entries: &[RetentionEntry]) -> Result<()> {
464        let data = serde_json::to_vec(entries).map_err(|err| VisionError::Parse {
465            backend: "frame-keeper".into(),
466            message: err.to_string(),
467        })?;
468        let saved = self
469            .artifacts
470            .save(SaveRequest {
471                app_name: self.scope.app_name.clone(),
472                user_id: self.scope.user_id.clone(),
473                session_id: self.scope.session_id.clone(),
474                file_name: self.index_file.clone(),
475                part: Part::InlineData {
476                    mime_type: "application/json".into(),
477                    data,
478                    uri: None,
479                    annotations: None,
480                },
481                version: None,
482            })
483            .await?;
484        let versions = self
485            .artifacts
486            .versions(VersionsRequest {
487                app_name: self.scope.app_name.clone(),
488                user_id: self.scope.user_id.clone(),
489                session_id: self.scope.session_id.clone(),
490                file_name: self.index_file.clone(),
491            })
492            .await?;
493        for version in versions.versions.into_iter().filter(|v| *v != saved.version) {
494            self.artifacts
495                .delete(DeleteRequest {
496                    app_name: self.scope.app_name.clone(),
497                    user_id: self.scope.user_id.clone(),
498                    session_id: self.scope.session_id.clone(),
499                    file_name: self.index_file.clone(),
500                    version: Some(version),
501                })
502                .await?;
503        }
504        Ok(())
505    }
506}