1use std::sync::Arc;
4
5use adk_artifact::{ArtifactService, LoadRequest, SaveRequest, VersionsRequest};
6use adk_core::{ErrorCategory, Part};
7use serde::{Deserialize, Serialize};
8
9use super::{
10 ArtifactLocator, DecodeLimits, DecodedImage, ImageRef, Provenance, SourceImage, artifact_uri,
11};
12use crate::digest::Digest;
13use crate::error::{Result, VisionError};
14
15#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
17#[serde(rename_all = "camelCase")]
18pub struct MediaScope {
19 pub app_name: String,
21 pub user_id: String,
23 pub session_id: String,
25}
26
27impl MediaScope {
28 pub fn new(
30 app_name: impl Into<String>,
31 user_id: impl Into<String>,
32 session_id: impl Into<String>,
33 ) -> Self {
34 Self { app_name: app_name.into(), user_id: user_id.into(), session_id: session_id.into() }
35 }
36}
37
38#[derive(Clone)]
63pub struct MediaStore {
64 artifacts: Arc<dyn ArtifactService>,
65 limits: DecodeLimits,
66}
67
68impl std::fmt::Debug for MediaStore {
69 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
70 f.debug_struct("MediaStore").field("limits", &self.limits).finish_non_exhaustive()
71 }
72}
73
74impl MediaStore {
75 pub fn new(artifacts: Arc<dyn ArtifactService>) -> Self {
77 Self { artifacts, limits: DecodeLimits::default() }
78 }
79
80 pub fn with_limits(mut self, limits: DecodeLimits) -> Self {
82 self.limits = limits;
83 self
84 }
85
86 pub fn limits(&self) -> &DecodeLimits {
88 &self.limits
89 }
90
91 pub async fn put_image(
98 &self,
99 scope: &MediaScope,
100 bytes: Vec<u8>,
101 provenance: Provenance,
102 ) -> Result<(ImageRef, SourceImage)> {
103 let (pixels, mime) = DecodedImage::decode(&bytes, &self.limits)?;
104 let digest = Digest::of(&bytes);
105 let source = SourceImage::from_parts(digest, mime.to_string(), Arc::new(pixels));
106 let image = self.save(scope, bytes, digest, mime, source.size(), provenance).await?;
107 Ok((image, source))
108 }
109
110 pub async fn put_pixels(
116 &self,
117 scope: &MediaScope,
118 pixels: DecodedImage,
119 provenance: Provenance,
120 ) -> Result<(ImageRef, SourceImage)> {
121 let png = pixels.encode_png()?;
122 let digest = Digest::of(&png);
123 let size = pixels.size();
124 let source = SourceImage::from_parts(digest, "image/png".into(), Arc::new(pixels));
125 let image = self.save(scope, png, digest, "image/png", size, provenance).await?;
126 Ok((image, source))
127 }
128
129 async fn save(
130 &self,
131 scope: &MediaScope,
132 bytes: Vec<u8>,
133 digest: Digest,
134 mime: &str,
135 (width, height): (u32, u32),
136 provenance: Provenance,
137 ) -> Result<ImageRef> {
138 let extension = mime.strip_prefix("image/").unwrap_or("bin");
139 let file_name = format!("vision-{}.{extension}", digest.hex());
140 let existing = self
141 .artifacts
142 .versions(VersionsRequest {
143 app_name: scope.app_name.clone(),
144 user_id: scope.user_id.clone(),
145 session_id: scope.session_id.clone(),
146 file_name: file_name.clone(),
147 })
148 .await;
149 let version = match existing {
150 Ok(found) if !found.versions.is_empty() => found.versions.iter().copied().max(),
151 Ok(_) => None,
152 Err(err) if err.category == ErrorCategory::NotFound => None,
153 Err(err) => return Err(err.into()),
154 };
155 let version = match version {
156 Some(version) => version,
157 None => {
158 let part = Part::InlineData {
159 mime_type: mime.to_string(),
160 data: bytes,
161 uri: None,
162 annotations: Some(serde_json::json!({ "adkVision": { "digest": digest } })),
163 };
164 self.artifacts
165 .save(SaveRequest {
166 app_name: scope.app_name.clone(),
167 user_id: scope.user_id.clone(),
168 session_id: scope.session_id.clone(),
169 file_name: file_name.clone(),
170 part,
171 version: None,
172 })
173 .await?
174 .version
175 }
176 };
177 tracing::debug!(image.digest = %digest, artifact.version = version, "image stored");
178 Ok(ImageRef {
179 artifact: ArtifactLocator::new(
180 scope.app_name.clone(),
181 scope.user_id.clone(),
182 scope.session_id.clone(),
183 file_name,
184 version,
185 ),
186 digest,
187 mime_type: mime.to_string(),
188 width,
189 height,
190 provenance,
191 })
192 }
193
194 pub async fn load_bytes(&self, image: &ImageRef) -> Result<Vec<u8>> {
201 let at = &image.artifact;
202 let loaded = self
203 .artifacts
204 .load(LoadRequest {
205 app_name: at.app_name.clone(),
206 user_id: at.user_id.clone(),
207 session_id: at.session_id.clone(),
208 file_name: at.file_name.clone(),
209 version: Some(at.version),
210 })
211 .await?;
212 let Part::InlineData { data, .. } = loaded.part else {
213 return Err(VisionError::InvalidInput(format!(
214 "artifact {} does not hold inline image data",
215 artifact_uri(at)
216 )));
217 };
218 let actual = Digest::of(&data);
219 if actual != image.digest {
220 return Err(VisionError::DigestMismatch {
221 path: artifact_uri(at).into(),
222 expected: image.digest,
223 actual,
224 });
225 }
226 Ok(data)
227 }
228
229 pub async fn load(&self, image: &ImageRef) -> Result<SourceImage> {
235 let bytes = self.load_bytes(image).await?;
236 SourceImage::decode(&bytes, &self.limits)
237 }
238}