adk_artifact/service.rs
1use adk_core::{AdkError, ErrorCategory, ErrorComponent, Part, Result};
2use async_trait::async_trait;
3
4/// The session segment that user-scoped (`user:`) artifacts are stored under.
5///
6/// Every backend rejects it as a session id, so a session's artifacts never mix with the
7/// artifacts every session of the user shares.
8pub const USER_SCOPE_SESSION_ID: &str = "user";
9
10/// Rejects the session id reserved for the user scope.
11pub(crate) fn check_session_id(session_id: &str) -> Result<()> {
12 if session_id == USER_SCOPE_SESSION_ID {
13 return Err(AdkError::new(
14 ErrorComponent::Artifact,
15 ErrorCategory::InvalidInput,
16 "artifact.reserved_session_id",
17 format!(
18 "invalid artifact session id '{USER_SCOPE_SESSION_ID}': it names the scope that \
19 `user:` artifacts share across sessions; use another session id"
20 ),
21 ));
22 }
23 Ok(())
24}
25
26/// The error for a load or version listing of an artifact, or a version of one, that is
27/// not stored. Every backend returns it, so `AdkError::is_not_found` holds for each.
28pub(crate) fn artifact_not_found(file_name: &str, version: Option<i64>) -> AdkError {
29 let message = match version {
30 Some(version) => format!(
31 "artifact '{file_name}' has no version {version}; list its versions to see which exist"
32 ),
33 None => format!("artifact '{file_name}' was not found; save it before loading it"),
34 };
35 AdkError::not_found(ErrorComponent::Artifact, "artifact.not_found", message)
36}
37
38/// The error for an artifact file name the backend cannot store, such as one with a path
39/// separator or a `..` traversal.
40pub(crate) fn invalid_file_name(file_name: &str, rule: &str) -> AdkError {
41 AdkError::new(
42 ErrorComponent::Artifact,
43 ErrorCategory::InvalidInput,
44 "artifact.invalid_name",
45 format!("invalid artifact file name '{file_name}': {rule}"),
46 )
47}
48
49/// The error for an app name, user ID, or session ID that cannot address artifact storage.
50pub(crate) fn invalid_identifier(field: &str, value: &str, rule: &str) -> AdkError {
51 AdkError::new(
52 ErrorComponent::Artifact,
53 ErrorCategory::InvalidInput,
54 "artifact.invalid_identifier",
55 format!("invalid artifact {field} '{value}': {rule}"),
56 )
57}
58
59/// The error for a save naming a version that already exists.
60pub(crate) fn version_exists(file_name: &str, version: i64) -> AdkError {
61 AdkError::new(
62 ErrorComponent::Artifact,
63 ErrorCategory::Conflict,
64 "artifact.version_exists",
65 format!(
66 "artifact '{file_name}' already has version {version}; versions are never \
67 replaced, so save without a version to append a new one"
68 ),
69 )
70}
71
72/// Request to save a binary artifact.
73#[derive(Debug, Clone)]
74pub struct SaveRequest {
75 /// Application namespace.
76 pub app_name: String,
77 /// Owning user.
78 pub user_id: String,
79 /// Session the artifact belongs to.
80 pub session_id: String,
81 /// Artifact filename (validated against path traversal).
82 pub file_name: String,
83 /// The binary content to store.
84 pub part: Part,
85 /// Explicit version to write, or `None` to append the next version.
86 ///
87 /// A version that already exists is never replaced: the save fails with
88 /// [`ErrorCategory::Conflict`].
89 pub version: Option<i64>,
90}
91
92/// Response from a successful save operation.
93#[derive(Debug, Clone)]
94pub struct SaveResponse {
95 /// The version number that was written.
96 pub version: i64,
97}
98
99/// Request to load an artifact.
100#[derive(Debug, Clone)]
101pub struct LoadRequest {
102 /// Application namespace.
103 pub app_name: String,
104 /// Owning user.
105 pub user_id: String,
106 /// Session the artifact belongs to.
107 pub session_id: String,
108 /// Artifact filename.
109 pub file_name: String,
110 /// Specific version to load, or `None` for the latest.
111 pub version: Option<i64>,
112}
113
114/// Response from a successful load operation.
115#[derive(Debug, Clone)]
116pub struct LoadResponse {
117 /// The binary content that was stored.
118 pub part: Part,
119}
120
121/// Request to delete an artifact.
122#[derive(Debug, Clone)]
123pub struct DeleteRequest {
124 /// Application namespace.
125 pub app_name: String,
126 /// Owning user.
127 pub user_id: String,
128 /// Session the artifact belongs to.
129 pub session_id: String,
130 /// Artifact filename.
131 pub file_name: String,
132 /// Specific version to delete, or `None` to delete all versions.
133 pub version: Option<i64>,
134}
135
136/// Request to list artifacts in a session.
137#[derive(Debug, Clone)]
138pub struct ListRequest {
139 /// Application namespace.
140 pub app_name: String,
141 /// Owning user.
142 pub user_id: String,
143 /// Session to list artifacts from.
144 pub session_id: String,
145}
146
147/// Response containing artifact filenames.
148#[derive(Debug, Clone)]
149pub struct ListResponse {
150 /// Filenames of all artifacts in the session.
151 pub file_names: Vec<String>,
152}
153
154/// Request to list versions of a specific artifact.
155#[derive(Debug, Clone)]
156pub struct VersionsRequest {
157 /// Application namespace.
158 pub app_name: String,
159 /// Owning user.
160 pub user_id: String,
161 /// Session the artifact belongs to.
162 pub session_id: String,
163 /// Artifact filename.
164 pub file_name: String,
165}
166
167/// Response containing available version numbers.
168#[derive(Debug, Clone)]
169pub struct VersionsResponse {
170 /// Version numbers in ascending order.
171 pub versions: Vec<i64>,
172}
173
174/// One stored version of one of a user's artifacts, as
175/// [`ArtifactService::list_user`] returns it.
176///
177/// # Example
178///
179/// ```rust
180/// use adk_artifact::UserArtifact;
181///
182/// let shared = UserArtifact {
183/// session_id: None,
184/// file_name: "user:avatar.png".to_string(),
185/// version: 1,
186/// mime_type: Some("image/png".to_string()),
187/// size: 2048,
188/// };
189/// assert!(shared.session_id.is_none(), "user: artifacts belong to no session");
190/// ```
191#[derive(Debug, Clone, PartialEq, Eq)]
192pub struct UserArtifact {
193 /// The session the artifact belongs to; `None` for a `user:` artifact every session
194 /// of the user shares.
195 pub session_id: Option<String>,
196 /// The artifact's file name.
197 pub file_name: String,
198 /// The version.
199 pub version: i64,
200 /// The stored part's MIME type: `text/plain` for text, the declared type for inline
201 /// data and file references, `None` for any other part.
202 pub mime_type: Option<String>,
203 /// The stored content's size in bytes: the text or inline data, 0 for a file
204 /// reference, and the JSON form for any other part.
205 pub size: u64,
206}
207
208/// The MIME type and byte size [`UserArtifact`] reports for a stored part.
209pub(crate) fn part_summary(part: &Part) -> (Option<String>, u64) {
210 match part {
211 Part::Text { text } => (Some("text/plain".to_string()), text.len() as u64),
212 Part::InlineData { mime_type, data, .. } => (Some(mime_type.clone()), data.len() as u64),
213 Part::FileData { mime_type, .. } => (Some(mime_type.clone()), 0),
214 Part::Thinking { .. }
215 | Part::FunctionCall { .. }
216 | Part::FunctionResponse { .. }
217 | Part::ServerToolCall { .. }
218 | Part::ServerToolResponse { .. }
219 | Part::EmbeddedResource { .. } => {
220 (None, serde_json::to_vec(part).map_or(0, |json| json.len() as u64))
221 }
222 }
223}
224
225/// Trait for artifact storage backends.
226///
227/// Implementations must be thread-safe (`Send + Sync`) and support
228/// versioned binary storage scoped by app, user, and session. Every backend in
229/// this crate keeps the same contract:
230///
231/// - **Versions are immutable.** A save never replaces a stored version.
232/// - **Concurrent saves each get their own version.** Saves of one artifact without
233/// an explicit version that run at the same time return distinct versions, and
234/// every one of them is stored.
235/// - **Distinct names are distinct artifacts.** No two file names share storage.
236/// - **The session id [`USER_SCOPE_SESSION_ID`] is reserved.** Every operation
237/// rejects it with [`ErrorCategory::InvalidInput`].
238#[async_trait]
239pub trait ArtifactService: Send + Sync {
240 /// Store a binary artifact, returning the version that was written.
241 ///
242 /// # Errors
243 ///
244 /// Returns a [`Conflict`](ErrorCategory::Conflict) error when
245 /// `req.version` names a version that already exists, and an
246 /// [`InvalidInput`](ErrorCategory::InvalidInput) error for an invalid
247 /// name or the reserved session id.
248 async fn save(&self, req: SaveRequest) -> Result<SaveResponse>;
249 /// Retrieve a stored artifact by filename and optional version.
250 async fn load(&self, req: LoadRequest) -> Result<LoadResponse>;
251 /// Delete an artifact (specific version or all versions).
252 async fn delete(&self, req: DeleteRequest) -> Result<()>;
253 /// List all artifact filenames in a session.
254 async fn list(&self, req: ListRequest) -> Result<ListResponse>;
255 /// List all available versions of a specific artifact.
256 async fn versions(&self, req: VersionsRequest) -> Result<VersionsResponse>;
257
258 /// Lists every stored version of every artifact of `user_id` in `app_name` — in
259 /// every session and in the `user:` scope — ordered by session, name, and version.
260 ///
261 /// [`ArtifactSubjectData`](crate::ArtifactSubjectData) exports a data subject's
262 /// artifacts through it.
263 ///
264 /// # Errors
265 ///
266 /// The default returns `subject.unsupported`
267 /// ([`SUBJECT_UNSUPPORTED_CODE`](adk_core::subject::SUBJECT_UNSUPPORTED_CODE)).
268 async fn list_user(&self, app_name: &str, user_id: &str) -> Result<Vec<UserArtifact>> {
269 let _ = (app_name, user_id);
270 Err(adk_core::subject::unsupported_error("artifacts", "list"))
271 }
272
273 /// Deletes every version of every artifact of `user_id` in `app_name`, in every
274 /// session and in the `user:` scope, and returns how many versions it deleted.
275 ///
276 /// # Errors
277 ///
278 /// The default returns `subject.unsupported`
279 /// ([`SUBJECT_UNSUPPORTED_CODE`](adk_core::subject::SUBJECT_UNSUPPORTED_CODE)).
280 async fn delete_user(&self, app_name: &str, user_id: &str) -> Result<u64> {
281 let _ = (app_name, user_id);
282 Err(adk_core::subject::unsupported_error("artifacts", "delete"))
283 }
284
285 /// Verify backend connectivity.
286 ///
287 /// The default implementation succeeds, which is appropriate for
288 /// in-memory backends.
289 async fn health_check(&self) -> Result<()> {
290 Ok(())
291 }
292}