Skip to main content

adk_vision/media/
store.rs

1//! [`MediaStore`]: images kept as artifacts, by digest.
2
3use 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/// The app, user and session an image is stored under.
16#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
17#[serde(rename_all = "camelCase")]
18pub struct MediaScope {
19    /// Application namespace.
20    pub app_name: String,
21    /// Owning user.
22    pub user_id: String,
23    /// Session.
24    pub session_id: String,
25}
26
27impl MediaScope {
28    /// A scope.
29    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/// Images kept as versioned artifacts, named by digest.
39///
40/// [`put_image`](Self::put_image) decodes once under the decode limits, computes the
41/// digest, and saves a `Part::InlineData`; identical bytes in one scope are one artifact.
42/// [`load`](Self::load) checks the digest of what it reads back.
43///
44/// # Example
45///
46/// ```
47/// use std::sync::Arc;
48/// use adk_artifact::InMemoryArtifactService;
49/// use adk_vision::{DecodedImage, MediaScope, MediaStore, Provenance};
50///
51/// # async fn demo() -> adk_vision::Result<()> {
52/// let store = MediaStore::new(Arc::new(InMemoryArtifactService::new()));
53/// let scope = MediaScope::new("desk", "u1", "s1");
54/// let png = DecodedImage::filled(8, 8, [255, 0, 0, 255]).encode_png()?;
55/// let (image, source) = store.put_image(&scope, png.clone(), Provenance::Upload).await?;
56/// let (again, _) = store.put_image(&scope, png, Provenance::Upload).await?;
57/// assert_eq!(again.artifact, image.artifact);
58/// assert_eq!(store.load(&image).await?.digest(), source.digest());
59/// # Ok(())
60/// # }
61/// ```
62#[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    /// A store over an artifact service, with the default decode limits.
76    pub fn new(artifacts: Arc<dyn ArtifactService>) -> Self {
77        Self { artifacts, limits: DecodeLimits::default() }
78    }
79
80    /// Sets the decode limits.
81    pub fn with_limits(mut self, limits: DecodeLimits) -> Self {
82        self.limits = limits;
83        self
84    }
85
86    /// The decode limits.
87    pub fn limits(&self) -> &DecodeLimits {
88        &self.limits
89    }
90
91    /// Decodes, checks and stores encoded image bytes.
92    ///
93    /// # Errors
94    ///
95    /// A decode refusal ([`DecodedImage::decode`]) before anything is stored, or the
96    /// artifact service's error.
97    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    /// Encodes pixels as PNG and stores them.
111    ///
112    /// # Errors
113    ///
114    /// The encoder's or the artifact service's error.
115    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    /// Loads an image's encoded bytes, checking them against its digest.
195    ///
196    /// # Errors
197    ///
198    /// The artifact service's error, [`VisionError::InvalidInput`] when the artifact is not
199    /// inline image data, or [`VisionError::DigestMismatch`] when the bytes changed.
200    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    /// Loads and decodes an image.
230    ///
231    /// # Errors
232    ///
233    /// As [`load_bytes`](Self::load_bytes), and the decode refusals.
234    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}