1use 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#[derive(Clone, Debug)]
37#[non_exhaustive]
38pub struct ClipReleaseRequest<'a> {
39 pub clip: &'a SourceClip,
41 pub backend: &'a BackendDescriptor,
43 pub data_class: DataClass,
45 pub approved: Vec<Digest>,
47 pub estimated_cost_micro_usd: Option<u64>,
50}
51
52impl<'a> ClipReleaseRequest<'a> {
53 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 pub fn approved(mut self, digest: Digest) -> Self {
66 self.approved.push(digest);
67 self
68 }
69
70 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#[derive(Clone, Debug)]
87pub struct ReleasedClip {
88 clip: SourceClip,
89 receipt: EgressReceipt,
90}
91
92impl ReleasedClip {
93 pub fn bytes(&self) -> &[u8] {
95 self.clip.bytes()
96 }
97
98 pub fn clip(&self) -> &SourceClip {
100 &self.clip
101 }
102
103 pub fn info(&self) -> &ClipInfo {
105 self.clip.info()
106 }
107
108 pub fn mime_type(&self) -> &str {
110 &self.clip.info().mime_type
111 }
112
113 pub fn receipt(&self) -> &EgressReceipt {
115 &self.receipt
116 }
117
118 pub fn is_for(&self, backend: &BackendId) -> bool {
120 &self.receipt.backend == backend
121 }
122}
123
124impl EgressGate {
125 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}