Skip to main content

adk_vision/egress/
clip.rs

1//! Releasing a video clip to a remote backend: [`ReleasedClip`] and
2//! [`EgressGate::release_clip`].
3
4use std::collections::BTreeMap;
5
6use adk_core::egress::EgressTarget;
7use chrono::Utc;
8
9use super::gate::{deny_reason, on_device_reason, remote_hosts, split_host_port};
10use super::{
11    DataClass, EgressAction, EgressDecision, EgressGate, EgressReceipt, EgressRecord, EgressRefusal,
12};
13use crate::backend::{BackendDescriptor, BackendId};
14use crate::cx::VisionCx;
15use crate::digest::Digest;
16use crate::error::{Result, VisionError};
17use crate::geometry::TransformChain;
18use crate::video::{ClipInfo, SourceClip};
19
20/// One request to release a clip to a remote backend.
21///
22/// # Example
23///
24/// ```no_run
25/// use adk_vision::{BackendDescriptor, ClipReleaseRequest, CoordFrame, DataClass, Locality, SourceClip};
26///
27/// let clip = SourceClip::decode(std::fs::read("aisle.mp4").unwrap()).unwrap();
28/// let gemini = BackendDescriptor::new(
29///     "gemini-3.8-flash",
30///     Locality::Remote { hosts: vec!["generativelanguage.googleapis.com".into()] },
31///     CoordFrame::SentPixels,
32/// );
33/// let request = ClipReleaseRequest::new(&clip, &gemini, DataClass::new("video"));
34/// assert!(request.approved.is_empty());
35/// ```
36#[derive(Clone, Debug)]
37#[non_exhaustive]
38pub struct ClipReleaseRequest<'a> {
39    /// The clip.
40    pub clip: &'a SourceClip,
41    /// The backend the clip is for.
42    pub backend: &'a BackendDescriptor,
43    /// The data class the egress rules are written per.
44    pub data_class: DataClass,
45    /// Clip digests a person approved, for a rule that asks.
46    pub approved: Vec<Digest>,
47    /// The call's estimated cost for the receipt: by default the backend's per-unit price
48    /// for every frame of the clip in one request.
49    pub estimated_cost_micro_usd: Option<u64>,
50}
51
52impl<'a> ClipReleaseRequest<'a> {
53    /// A request to release `clip` to `backend` as `data_class`.
54    pub fn new(
55        clip: &'a SourceClip,
56        backend: &'a BackendDescriptor,
57        data_class: DataClass,
58    ) -> Self {
59        let estimated_cost_micro_usd =
60            backend.price.as_ref().and_then(|p| p.request_cost(clip.info().frames));
61        Self { clip, backend, data_class, approved: Vec::new(), estimated_cost_micro_usd }
62    }
63
64    /// Releases the clip if its digest is one a person approved.
65    pub fn approved(mut self, digest: Digest) -> Self {
66        self.approved.push(digest);
67        self
68    }
69
70    /// Records `micro_usd` as the call's estimated cost.
71    pub fn with_estimated_cost(mut self, micro_usd: Option<u64>) -> Self {
72        self.estimated_cost_micro_usd = micro_usd;
73        self
74    }
75}
76
77/// A clip the egress gate released to one backend: the exact bytes sent and the receipt
78/// the gate recorded. The only clip a remote video backend accepts; only [`EgressGate`]
79/// constructs one:
80///
81/// ```compile_fail,E0599
82/// use adk_vision::ReleasedClip;
83///
84/// let forged = ReleasedClip::new();
85/// ```
86#[derive(Clone, Debug)]
87pub struct ReleasedClip {
88    clip: SourceClip,
89    receipt: EgressReceipt,
90}
91
92impl ReleasedClip {
93    /// The exact bytes released; their digest is the receipt's `egress`.
94    pub fn bytes(&self) -> &[u8] {
95        self.clip.bytes()
96    }
97
98    /// The released clip.
99    pub fn clip(&self) -> &SourceClip {
100        &self.clip
101    }
102
103    /// What the container states.
104    pub fn info(&self) -> &ClipInfo {
105        self.clip.info()
106    }
107
108    /// `video/mp4` or `video/quicktime`.
109    pub fn mime_type(&self) -> &str {
110        &self.clip.info().mime_type
111    }
112
113    /// The receipt the gate recorded.
114    pub fn receipt(&self) -> &EgressReceipt {
115        &self.receipt
116    }
117
118    /// `true` when this clip was released to `backend`.
119    pub fn is_for(&self, backend: &BackendId) -> bool {
120        &self.receipt.backend == backend
121    }
122}
123
124impl EgressGate {
125    /// Releases a video clip to a remote backend, or refuses, in the steps of
126    /// [`release`](Self::release):
127    ///
128    /// 1. **Destination.** The on-device profile refuses every host; otherwise the adk-core
129    ///    egress policy decides each of the backend's hosts.
130    /// 2. **Minimise and redact.** A clip is not re-encoded on the device, so a
131    ///    configuration that requires any redaction class refuses every clip (V-I2): send
132    ///    sampled frames instead, which the gate redacts one by one.
133    /// 3. **Decide.** The rule for the host and data class says `deny`, `ask` or `allow`;
134    ///    `ask` holds the clip unless a person approved its digest.
135    /// 4. **Record and release.** The receipt, with the clip's digest as both source and
136    ///    egress digest, goes to the recorder and the audit log before the clip is returned.
137    ///
138    /// # Errors
139    ///
140    /// [`VisionError::EgressRefused`] at the destination, redact or decide step,
141    /// [`VisionError::EgressHeld`] for a rule that asks, [`VisionError::Cancelled`] or the
142    /// kill switch's error, and the recorder's error.
143    pub async fn release_clip(
144        &self,
145        cx: &VisionCx,
146        request: ClipReleaseRequest<'_>,
147    ) -> Result<ReleasedClip> {
148        let hosts = remote_hosts(request.backend)?;
149        let digest = request.clip.digest();
150        if let Err(err) = cx.check() {
151            self.refuse_clip(cx, &request, &hosts, None, "destination", &err.to_string()).await?;
152            return Err(err);
153        }
154        if self.config.on_device {
155            let reason = on_device_reason(&hosts);
156            self.refuse_clip(cx, &request, &hosts, None, "destination", &reason).await?;
157            return Err(VisionError::EgressRefused { host: hosts.join(", "), reason });
158        }
159        let policy = self.destination_policy();
160        for host in &hosts {
161            let (name, port) = split_host_port(host);
162            if let Err(denial) = policy.decide(&EgressTarget::Name { host: name, port }) {
163                let reason = denial.to_string();
164                self.refuse_clip(cx, &request, &hosts, None, "destination", &reason).await?;
165                return Err(VisionError::EgressRefused { host: host.clone(), reason });
166            }
167        }
168        if let Some(class) = self.config.redact.first() {
169            let reason = format!(
170                "the egress rules require `{class}` redaction, and a clip cannot be redacted on \
171                 the device; analyse sampled frames instead, which the gate redacts one by one"
172            );
173            self.refuse_clip(cx, &request, &hosts, Some(digest), "redact", &reason).await?;
174            return Err(VisionError::EgressRefused { host: hosts.join(", "), reason });
175        }
176        let (action, rule) = self.decide(request.backend, &request.data_class);
177        let decision = match action {
178            EgressAction::Allow => EgressDecision::Allowed { rule },
179            EgressAction::Ask if request.approved.contains(&digest) => {
180                EgressDecision::Approved { rule }
181            }
182            EgressAction::Ask => {
183                let reason = format!("held for a person's approval of {digest}");
184                self.refuse_clip(cx, &request, &hosts, Some(digest), "decide", &reason).await?;
185                return Err(VisionError::EgressHeld {
186                    host: hosts.join(", "),
187                    data_class: request.data_class.to_string(),
188                    egress: digest,
189                });
190            }
191            EgressAction::Deny => {
192                let reason = deny_reason(rule, &request.data_class);
193                self.refuse_clip(cx, &request, &hosts, Some(digest), "decide", &reason).await?;
194                return Err(VisionError::EgressRefused { host: hosts.join(", "), reason });
195            }
196        };
197        if let Err(err) = cx.check() {
198            self.refuse_clip(cx, &request, &hosts, Some(digest), "release", &err.to_string())
199                .await?;
200            return Err(err);
201        }
202        let (width, height) = request.clip.size();
203        let receipt = EgressReceipt {
204            id: uuid::Uuid::new_v4().to_string(),
205            source: digest,
206            egress: digest,
207            backend: request.backend.id.clone(),
208            hosts,
209            data_class: request.data_class.clone(),
210            chain: TransformChain::new(width, height),
211            redactions: BTreeMap::new(),
212            decision,
213            estimated_cost_micro_usd: request.estimated_cost_micro_usd,
214            artifact: request.clip.artifact().cloned(),
215            released_at: Utc::now(),
216        };
217        let record = EgressRecord::Released(receipt.clone());
218        self.recorder.record(record.clone()).await?;
219        cx.audit(crate::audit::egress_draft(&record)).await?;
220        self.released.lock().unwrap_or_else(|e| e.into_inner()).insert(digest);
221        tracing::info!(
222            egress.backend = %receipt.backend,
223            egress.digest = %digest,
224            egress.data_class = %receipt.data_class,
225            clip.bytes = request.clip.bytes().len(),
226            "clip released"
227        );
228        Ok(ReleasedClip { clip: request.clip.clone(), receipt })
229    }
230
231    async fn refuse_clip(
232        &self,
233        cx: &VisionCx,
234        request: &ClipReleaseRequest<'_>,
235        hosts: &[String],
236        egress: Option<Digest>,
237        step: &str,
238        reason: &str,
239    ) -> Result<()> {
240        tracing::warn!(
241            egress.backend = %request.backend.id,
242            egress.step = step,
243            egress.reason = reason,
244            "clip not released"
245        );
246        let record = EgressRecord::Refused(EgressRefusal {
247            source: request.clip.digest(),
248            egress,
249            backend: request.backend.id.clone(),
250            hosts: hosts.to_vec(),
251            data_class: request.data_class.clone(),
252            step: step.to_string(),
253            reason: reason.to_string(),
254            refused_at: Utc::now(),
255        });
256        self.recorder.record(record.clone()).await?;
257        cx.audit(crate::audit::egress_draft(&record)).await
258    }
259}