Skip to main content

adk_artifact/
file.rs

1use crate::service::*;
2use adk_core::{AdkError, ErrorCategory, ErrorComponent, Part, Result};
3use async_trait::async_trait;
4use std::collections::BTreeSet;
5use std::fmt::Write as _;
6use std::io::ErrorKind;
7use std::path::{Path, PathBuf};
8use std::sync::atomic::{AtomicU64, Ordering};
9use std::time::{SystemTime, UNIX_EPOCH};
10use tokio::fs;
11use tokio::io::AsyncWriteExt;
12
13/// Directory of user-scoped artifacts. It shares the reserved session id's name, so no
14/// session directory can collide with it.
15const USER_SCOPE_DIR: &str = USER_SCOPE_SESSION_ID;
16
17/// Directory earlier releases kept user-scoped artifacts in, still read so they stay loadable.
18const LEGACY_USER_SCOPE_DIR: &str = "_user_scoped_";
19
20/// Prefix of a save's temporary file, which never parses as a version file.
21const TEMP_PREFIX: &str = ".save-";
22
23/// How many versions taken by concurrent saves one save steps past before it gives up.
24const MAX_SAVE_ATTEMPTS: usize = 1024;
25
26static TEMP_COUNTER: AtomicU64 = AtomicU64::new(0);
27
28/// The error for an artifact whose resolved path leaves the base directory.
29fn path_escapes() -> AdkError {
30    AdkError::new(
31        ErrorComponent::Artifact,
32        ErrorCategory::InvalidInput,
33        "artifact.path_escapes",
34        "the artifact path resolves outside the configured base directory",
35    )
36}
37
38/// A filesystem failure under the base directory; `operation` names what failed.
39fn io_error(operation: &str, error: impl std::fmt::Display) -> AdkError {
40    AdkError::internal(
41        ErrorComponent::Artifact,
42        "artifact.file.io",
43        format!("{operation}: {error}"),
44    )
45}
46
47/// Encodes an artifact name as one directory name.
48///
49/// `%`, and the characters Windows forbids in file names (`<>:"|?*` and ASCII control
50/// characters), become `%XX` escapes. So does the second `_` of every `__`, so no encoded
51/// name contains `__`, the marker of the encoding earlier releases used (`:` as `__`).
52/// Distinct names therefore always get distinct directories.
53fn encode_name(name: &str) -> String {
54    let mut encoded = String::with_capacity(name.len());
55    let mut after_underscore = false;
56    for c in name.chars() {
57        let escape = match c {
58            '%' | '<' | '>' | ':' | '"' | '|' | '?' | '*' => true,
59            '_' => after_underscore,
60            other => other.is_ascii_control(),
61        };
62        if escape {
63            // Every escaped character is ASCII, so it fits in two hex digits.
64            let _ = write!(encoded, "%{:02X}", u32::from(c));
65            after_underscore = false;
66        } else {
67            encoded.push(c);
68            after_underscore = c == '_';
69        }
70    }
71    encoded
72}
73
74/// The directory name earlier releases stored `name` under.
75fn legacy_encode_name(name: &str) -> String {
76    name.replace(':', "__")
77}
78
79/// Recovers the artifact name from a directory written by this or an earlier release.
80fn decode_name(dir_name: &str) -> String {
81    if dir_name.contains("__") {
82        // Only the earlier encoding produces `__`; it stored `:` that way.
83        return dir_name.replace("__", ":");
84    }
85    percent_decode(dir_name).unwrap_or_else(|| dir_name.to_string())
86}
87
88fn percent_decode(encoded: &str) -> Option<String> {
89    let bytes = encoded.as_bytes();
90    let mut decoded = Vec::with_capacity(bytes.len());
91    let mut index = 0;
92    while index < bytes.len() {
93        if bytes[index] == b'%' {
94            let hex = bytes.get(index + 1..index + 3)?;
95            if !hex.iter().all(u8::is_ascii_hexdigit) {
96                return None;
97            }
98            decoded.push(u8::from_str_radix(std::str::from_utf8(hex).ok()?, 16).ok()?);
99            index += 3;
100        } else {
101            decoded.push(bytes[index]);
102            index += 1;
103        }
104    }
105    String::from_utf8(decoded).ok()
106}
107
108fn version_file_name(version: i64) -> String {
109    format!("v{version}.json")
110}
111
112/// The directories one artifact's versions live in.
113struct ArtifactDirs {
114    /// Where saves write.
115    primary: PathBuf,
116    /// Where an earlier release stored the same artifact, when that differs.
117    legacy: Option<PathBuf>,
118}
119
120impl ArtifactDirs {
121    fn all(&self) -> impl Iterator<Item = &PathBuf> {
122        std::iter::once(&self.primary).chain(self.legacy.as_ref())
123    }
124}
125
126/// Persist artifacts on the local filesystem.
127///
128/// The base directory is created and canonicalized at construction time. Each version is
129/// one JSON file:
130///
131/// - Session-scoped: `{app_name}/{user_id}/{session_id}/{name}/v{version}.json`
132/// - User-scoped (`user:` names): `{app_name}/{user_id}/user/{name}/v{version}.json`
133///
134/// `{name}` is the artifact name with `%`, `:`, the other characters Windows forbids in file
135/// names, and the second `_` of every `__` written as `%XX` escapes, so distinct names never
136/// share a directory.
137///
138/// A save writes the version to a temporary file, flushes it to disk, and links it into
139/// place without replacing an existing file. A crash mid-save leaves the earlier versions
140/// intact, and concurrent saves each claim their own version. On filesystems without hard
141/// links (FAT, exFAT) the version file is created exclusively and written in place instead.
142///
143/// Artifacts stored by earlier releases, which wrote `:` as `__` and kept user-scoped
144/// artifacts under `_user_scoped_`, are still loaded, listed, versioned, and deleted; new
145/// versions of them are written to the current layout.
146///
147/// # Example
148///
149/// ```rust,no_run
150/// use adk_artifact::{ArtifactService, FileArtifactService, SaveRequest};
151/// use adk_core::Part;
152///
153/// # async fn example() -> adk_core::Result<()> {
154/// let service = FileArtifactService::new("./artifacts")?;
155/// let saved = service
156///     .save(SaveRequest {
157///         app_name: "my_app".to_string(),
158///         user_id: "user_123".to_string(),
159///         session_id: "session_456".to_string(),
160///         file_name: "report:q1".to_string(),
161///         part: Part::Text { text: "quarterly numbers".to_string() },
162///         version: None,
163///     })
164///     .await?;
165/// assert_eq!(saved.version, 1);
166/// # Ok(())
167/// # }
168/// ```
169pub struct FileArtifactService {
170    /// Canonical (absolute, resolved) base directory. Set once at construction.
171    base_dir: PathBuf,
172}
173
174impl FileArtifactService {
175    /// Create a new filesystem-backed artifact service rooted at `base_dir`.
176    ///
177    /// Creates the directory if it doesn't exist and stores the canonical path.
178    ///
179    /// # Errors
180    ///
181    /// Returns an error if the directory cannot be created or canonicalized.
182    pub fn new(base_dir: impl Into<PathBuf>) -> Result<Self> {
183        let raw = base_dir.into();
184        std::fs::create_dir_all(&raw).map_err(|e| io_error("create base dir failed", e))?;
185        let canonical =
186            raw.canonicalize().map_err(|e| io_error("canonicalize base dir failed", e))?;
187        Ok(Self { base_dir: canonical })
188    }
189
190    fn validate_file_name(file_name: &str) -> Result<()> {
191        if file_name.is_empty() {
192            return Err(invalid_file_name(file_name, "the name is empty"));
193        }
194
195        if file_name.contains('/')
196            || file_name.contains('\\')
197            || file_name == "."
198            || file_name == ".."
199            || file_name.contains("..")
200        {
201            return Err(invalid_file_name(
202                file_name,
203                "path separators and traversal patterns are not allowed",
204            ));
205        }
206
207        Ok(())
208    }
209
210    /// Validates a path component (app_name, user_id, session_id) used to build artifact paths.
211    ///
212    /// Rejects empty values, directory separators, and traversal patterns.
213    fn validate_path_component(component: &str, field: &str) -> Result<()> {
214        if component.is_empty() {
215            return Err(invalid_identifier(field, component, "the value is empty"));
216        }
217
218        if component.contains('/')
219            || component.contains('\\')
220            || component == "."
221            || component == ".."
222            || component.contains("..")
223        {
224            return Err(invalid_identifier(
225                field,
226                component,
227                "path separators and traversal patterns are not allowed",
228            ));
229        }
230
231        Ok(())
232    }
233
234    /// Validates the app, user, and session components and returns the user's directory.
235    fn user_root(&self, app_name: &str, user_id: &str, session_id: &str) -> Result<PathBuf> {
236        Self::validate_path_component(app_name, "app name")?;
237        Self::validate_path_component(user_id, "user id")?;
238        Self::validate_path_component(session_id, "session id")?;
239        check_session_id(session_id)?;
240        Ok(self.base_dir.join(app_name).join(user_id))
241    }
242
243    /// Ensures the given path stays within the configured base directory.
244    fn ensure_within_base_dir(&self, path: &Path) -> Result<()> {
245        let canonical_base = self
246            .base_dir
247            .canonicalize()
248            .map_err(|e| io_error("canonicalize base dir failed", e))?;
249
250        // For paths that may not exist yet, resolve relative to canonical base
251        let canonical_path = match path.canonicalize() {
252            Ok(canonical) => canonical,
253            Err(_) => {
254                let relative = path.strip_prefix(&self.base_dir).unwrap_or(path);
255                canonical_base.join(relative)
256            }
257        };
258
259        if !canonical_path.starts_with(&canonical_base) {
260            return Err(path_escapes());
261        }
262
263        Ok(())
264    }
265
266    fn is_user_scoped(file_name: &str) -> bool {
267        file_name.starts_with("user:")
268    }
269
270    /// Builds the directories of one artifact from validated components.
271    ///
272    /// Both returned paths are verified to be under `self.base_dir`.
273    fn artifact_dirs(
274        &self,
275        app_name: &str,
276        user_id: &str,
277        session_id: &str,
278        file_name: &str,
279    ) -> Result<ArtifactDirs> {
280        let user_root = self.user_root(app_name, user_id, session_id)?;
281        Self::validate_file_name(file_name)?;
282
283        let (scope, legacy_scope) = if Self::is_user_scoped(file_name) {
284            (USER_SCOPE_DIR, LEGACY_USER_SCOPE_DIR)
285        } else {
286            (session_id, session_id)
287        };
288        let primary = user_root.join(scope).join(encode_name(file_name));
289        let legacy = user_root.join(legacy_scope).join(legacy_encode_name(file_name));
290        let dirs = ArtifactDirs { legacy: (legacy != primary).then_some(legacy), primary };
291        for dir in dirs.all() {
292            self.ensure_within_base_dir(dir)?;
293        }
294        Ok(dirs)
295    }
296
297    async fn versions_in(dir: &Path) -> Result<Vec<i64>> {
298        let mut entries = match fs::read_dir(dir).await {
299            Ok(entries) => entries,
300            Err(error) if error.kind() == ErrorKind::NotFound => return Ok(Vec::new()),
301            Err(error) => {
302                return Err(io_error("read dir failed", error));
303            }
304        };
305
306        let mut versions = Vec::new();
307        while let Some(entry) =
308            entries.next_entry().await.map_err(|e| io_error("read dir entry failed", e))?
309        {
310            let Some(file_name) = entry.file_name().to_str().map(ToString::to_string) else {
311                continue;
312            };
313            let Some(raw) =
314                file_name.strip_prefix('v').and_then(|value| value.strip_suffix(".json"))
315            else {
316                continue;
317            };
318            if let Ok(version) = raw.parse::<i64>() {
319                versions.push(version);
320            }
321        }
322        Ok(versions)
323    }
324
325    /// Every stored version of an artifact, across the current and the legacy layout.
326    async fn stored_versions(dirs: &ArtifactDirs) -> Result<BTreeSet<i64>> {
327        let mut versions = BTreeSet::new();
328        for dir in dirs.all() {
329            versions.extend(Self::versions_in(dir).await?);
330        }
331        Ok(versions)
332    }
333
334    /// The file holding `version`, preferring the current layout.
335    async fn version_path(dirs: &ArtifactDirs, version: i64) -> Option<PathBuf> {
336        for dir in dirs.all() {
337            let path = dir.join(version_file_name(version));
338            if fs::try_exists(&path).await.unwrap_or(false) {
339                return Some(path);
340            }
341        }
342        None
343    }
344
345    /// Lists the artifact names stored in a scope directory that satisfy `keep`.
346    async fn list_scope_dir(path: &Path, keep: fn(&str) -> bool) -> Result<BTreeSet<String>> {
347        let mut names = BTreeSet::new();
348        let mut entries = match fs::read_dir(path).await {
349            Ok(entries) => entries,
350            Err(error) if error.kind() == ErrorKind::NotFound => return Ok(names),
351            Err(error) => {
352                return Err(io_error("read dir failed", error));
353            }
354        };
355
356        while let Some(entry) =
357            entries.next_entry().await.map_err(|e| io_error("read dir entry failed", e))?
358        {
359            if entry.file_type().await.map_err(|e| io_error("file type check failed", e))?.is_dir()
360                && let Some(dir_name) = entry.file_name().to_str()
361            {
362                let name = decode_name(dir_name);
363                if keep(&name) {
364                    names.insert(name);
365                }
366            }
367        }
368
369        Ok(names)
370    }
371
372    /// Every version file of a user: its session (`None` for the `user:` scope), artifact
373    /// name, version, and path. An empty list when the user has no directory.
374    async fn user_version_files(
375        &self,
376        app_name: &str,
377        user_id: &str,
378    ) -> Result<Vec<(Option<String>, String, i64, PathBuf)>> {
379        Self::validate_path_component(app_name, "app name")?;
380        Self::validate_path_component(user_id, "user id")?;
381        let user_root = self.base_dir.join(app_name).join(user_id);
382        self.ensure_within_base_dir(&user_root)?;
383        let mut found = Vec::new();
384        for scope in Self::subdirectories(&user_root).await? {
385            let scope_dir = user_root.join(&scope);
386            for dir_name in Self::subdirectories(&scope_dir).await? {
387                let name = decode_name(&dir_name);
388                let session = match scope.as_str() {
389                    USER_SCOPE_DIR => None,
390                    LEGACY_USER_SCOPE_DIR if Self::is_user_scoped(&name) => None,
391                    _ => Some(scope.clone()),
392                };
393                let artifact_dir = scope_dir.join(&dir_name);
394                let mut versions = Self::versions_in(&artifact_dir).await?;
395                versions.sort_unstable();
396                for version in versions {
397                    let path = artifact_dir.join(version_file_name(version));
398                    found.push((session.clone(), name.clone(), version, path));
399                }
400            }
401        }
402        found.sort_by(|a, b| (&a.0, &a.1, a.2).cmp(&(&b.0, &b.1, b.2)));
403        Ok(found)
404    }
405
406    /// The names of the directories in `dir`; empty when `dir` does not exist.
407    async fn subdirectories(dir: &Path) -> Result<Vec<String>> {
408        let mut entries = match fs::read_dir(dir).await {
409            Ok(entries) => entries,
410            Err(error) if error.kind() == ErrorKind::NotFound => return Ok(Vec::new()),
411            Err(error) => return Err(io_error("read dir failed", error)),
412        };
413        let mut names = Vec::new();
414        while let Some(entry) =
415            entries.next_entry().await.map_err(|e| io_error("read dir entry failed", e))?
416        {
417            if entry.file_type().await.map_err(|e| io_error("file type check failed", e))?.is_dir()
418                && let Some(name) = entry.file_name().to_str()
419            {
420                names.push(name.to_string());
421            }
422        }
423        Ok(names)
424    }
425
426    /// Writes `payload` to a new file and flushes it to disk.
427    async fn write_synced(path: &Path, payload: &[u8]) -> std::io::Result<()> {
428        let mut file = fs::OpenOptions::new().write(true).create_new(true).open(path).await?;
429        file.write_all(payload).await?;
430        file.sync_all().await
431    }
432
433    /// Publishes the fully written `temp` file as `target` unless `target` already exists.
434    ///
435    /// Returns `false` when `target` exists.
436    async fn publish(temp: &Path, target: &Path, payload: &[u8]) -> std::io::Result<bool> {
437        match fs::hard_link(temp, target).await {
438            Ok(()) => Ok(true),
439            Err(error) if error.kind() == ErrorKind::AlreadyExists => Ok(false),
440            // Filesystems without hard links: claim the name exclusively, then write in place.
441            Err(_) => match Self::write_synced(target, payload).await {
442                Ok(()) => Ok(true),
443                Err(error) if error.kind() == ErrorKind::AlreadyExists => Ok(false),
444                Err(error) => Err(error),
445            },
446        }
447    }
448
449    /// Links the temporary file to the first free version, starting at the requested one.
450    async fn claim_version(
451        dirs: &ArtifactDirs,
452        dir: &Path,
453        temp: &Path,
454        payload: &[u8],
455        req: &SaveRequest,
456    ) -> Result<i64> {
457        let mut version = match req.version {
458            Some(version) => {
459                if let Some(legacy) = &dirs.legacy
460                    && fs::try_exists(legacy.join(version_file_name(version)))
461                        .await
462                        .unwrap_or(false)
463                {
464                    return Err(version_exists(&req.file_name, version));
465                }
466                version
467            }
468            None => Self::stored_versions(dirs).await?.last().map_or(1, |latest| latest + 1),
469        };
470        for _ in 0..MAX_SAVE_ATTEMPTS {
471            let target = dir.join(version_file_name(version));
472            let published = Self::publish(temp, &target, payload)
473                .await
474                .map_err(|e| io_error("write failed", e))?;
475            if published {
476                return Ok(version);
477            }
478            if req.version.is_some() {
479                return Err(version_exists(&req.file_name, version));
480            }
481            version += 1;
482        }
483        Err(AdkError::new(
484            ErrorComponent::Artifact,
485            ErrorCategory::Conflict,
486            "artifact.save_contended",
487            format!(
488                "artifact '{}' gained {MAX_SAVE_ATTEMPTS} versions while this save ran; retry the save",
489                req.file_name
490            ),
491        ))
492    }
493}
494
495/// Flushes a directory entry change to disk where the platform supports it.
496async fn sync_dir(dir: &Path) {
497    #[cfg(unix)]
498    if let Ok(handle) = fs::File::open(dir).await {
499        // Best effort: the version is already visible, so a failed flush does not fail the save.
500        let _ = handle.sync_all().await;
501    }
502    #[cfg(not(unix))]
503    let _ = dir;
504}
505
506#[async_trait]
507impl ArtifactService for FileArtifactService {
508    async fn list_user(&self, app_name: &str, user_id: &str) -> Result<Vec<UserArtifact>> {
509        let mut artifacts = Vec::new();
510        for (session_id, file_name, version, path) in
511            self.user_version_files(app_name, user_id).await?
512        {
513            let bytes = fs::read(&path).await.map_err(|e| io_error("read failed", e))?;
514            let part: Part = serde_json::from_slice(&bytes)
515                .map_err(|error| io_error("decode artifact failed", error))?;
516            let (mime_type, size) = part_summary(&part);
517            artifacts.push(UserArtifact { session_id, file_name, version, mime_type, size });
518        }
519        Ok(artifacts)
520    }
521
522    async fn delete_user(&self, app_name: &str, user_id: &str) -> Result<u64> {
523        let versions = self.user_version_files(app_name, user_id).await?.len() as u64;
524        match fs::remove_dir_all(self.base_dir.join(app_name).join(user_id)).await {
525            Ok(()) => Ok(versions),
526            Err(error) if error.kind() == ErrorKind::NotFound => Ok(0),
527            Err(error) => Err(io_error("delete user dir failed", error)),
528        }
529    }
530
531    async fn save(&self, req: SaveRequest) -> Result<SaveResponse> {
532        let dirs =
533            self.artifact_dirs(&req.app_name, &req.user_id, &req.session_id, &req.file_name)?;
534        let payload = serde_json::to_vec(&req.part)
535            .map_err(|error| io_error("encode artifact failed", error))?;
536
537        fs::create_dir_all(&dirs.primary).await.map_err(|e| io_error("create dir failed", e))?;
538
539        // Final canonicalization check after directory exists
540        let verified_dir = dirs
541            .primary
542            .canonicalize()
543            .map_err(|e| io_error("canonicalize artifact dir failed", e))?;
544        if !verified_dir.starts_with(&self.base_dir) {
545            return Err(path_escapes());
546        }
547
548        let nonce = SystemTime::now().duration_since(UNIX_EPOCH).unwrap_or_default().as_nanos();
549        let temp = verified_dir.join(format!(
550            "{TEMP_PREFIX}{}-{nonce}-{}.tmp",
551            std::process::id(),
552            TEMP_COUNTER.fetch_add(1, Ordering::Relaxed)
553        ));
554        if let Err(error) = Self::write_synced(&temp, &payload).await {
555            let _ = fs::remove_file(&temp).await;
556            return Err(io_error("write failed", error));
557        }
558        let claimed = Self::claim_version(&dirs, &verified_dir, &temp, &payload, &req).await;
559        let _ = fs::remove_file(&temp).await;
560        let version = claimed?;
561        sync_dir(&verified_dir).await;
562
563        Ok(SaveResponse { version })
564    }
565
566    async fn load(&self, req: LoadRequest) -> Result<LoadResponse> {
567        let dirs =
568            self.artifact_dirs(&req.app_name, &req.user_id, &req.session_id, &req.file_name)?;
569        let version = match req.version {
570            Some(version) => version,
571            None => *Self::stored_versions(&dirs)
572                .await?
573                .last()
574                .ok_or_else(|| artifact_not_found(&req.file_name, None))?,
575        };
576
577        let path = Self::version_path(&dirs, version)
578            .await
579            .ok_or_else(|| artifact_not_found(&req.file_name, req.version))?;
580        let payload = fs::read(&path).await.map_err(|error| {
581            if error.kind() == ErrorKind::NotFound {
582                artifact_not_found(&req.file_name, req.version)
583            } else {
584                io_error("read failed", error)
585            }
586        })?;
587
588        let part = serde_json::from_slice::<Part>(&payload).map_err(|error| {
589            AdkError::internal(
590                ErrorComponent::Artifact,
591                "artifact.file.corrupt",
592                format!(
593                    "artifact '{}' version {version} is not a stored artifact: {error}",
594                    req.file_name
595                ),
596            )
597        })?;
598
599        Ok(LoadResponse { part })
600    }
601
602    async fn delete(&self, req: DeleteRequest) -> Result<()> {
603        let dirs =
604            self.artifact_dirs(&req.app_name, &req.user_id, &req.session_id, &req.file_name)?;
605        for dir in dirs.all() {
606            let removed = match req.version {
607                Some(version) => fs::remove_file(dir.join(version_file_name(version))).await,
608                None => fs::remove_dir_all(dir).await,
609            };
610            match removed {
611                Ok(()) => {}
612                Err(error) if error.kind() == ErrorKind::NotFound => {}
613                Err(error) => {
614                    return Err(io_error("delete failed", error));
615                }
616            }
617        }
618
619        Ok(())
620    }
621
622    async fn list(&self, req: ListRequest) -> Result<ListResponse> {
623        let user_root = self.user_root(&req.app_name, &req.user_id, &req.session_id)?;
624        let session_dir = user_root.join(&req.session_id);
625        self.ensure_within_base_dir(&session_dir)?;
626
627        // A session directory holds only session-scoped names; the user scope directories
628        // only `user:` names.
629        let mut names =
630            Self::list_scope_dir(&session_dir, |name| !Self::is_user_scoped(name)).await?;
631        for scope in [USER_SCOPE_DIR, LEGACY_USER_SCOPE_DIR] {
632            let user_dir = user_root.join(scope);
633            self.ensure_within_base_dir(&user_dir)?;
634            names.extend(Self::list_scope_dir(&user_dir, Self::is_user_scoped).await?);
635        }
636
637        Ok(ListResponse { file_names: names.into_iter().collect() })
638    }
639
640    async fn versions(&self, req: VersionsRequest) -> Result<VersionsResponse> {
641        let dirs =
642            self.artifact_dirs(&req.app_name, &req.user_id, &req.session_id, &req.file_name)?;
643        let versions: Vec<i64> = Self::stored_versions(&dirs).await?.into_iter().rev().collect();
644        if versions.is_empty() {
645            return Err(artifact_not_found(&req.file_name, None));
646        }
647        Ok(VersionsResponse { versions })
648    }
649
650    async fn health_check(&self) -> Result<()> {
651        fs::create_dir_all(&self.base_dir).await.map_err(|e| io_error("health check failed", e))?;
652        let nonce = SystemTime::now().duration_since(UNIX_EPOCH).unwrap_or_default().as_nanos();
653        let path = self.base_dir.join(format!(".healthcheck-{nonce}"));
654        fs::write(&path, b"ok").await.map_err(|e| io_error("health check failed", e))?;
655        fs::remove_file(path).await.map_err(|e| io_error("health check failed", e))?;
656        Ok(())
657    }
658}
659
660#[cfg(test)]
661mod tests {
662    use super::*;
663
664    #[tokio::test]
665    async fn user_scoped_artifacts_are_visible_across_sessions() {
666        let tempdir = tempfile::tempdir().unwrap();
667        let service = FileArtifactService::new(tempdir.path()).unwrap();
668
669        service
670            .save(SaveRequest {
671                app_name: "app".into(),
672                user_id: "user".into(),
673                session_id: "s1".into(),
674                file_name: "user:shared.txt".into(),
675                part: Part::Text { text: "hello".into() },
676                version: None,
677            })
678            .await
679            .unwrap();
680
681        let list = service
682            .list(ListRequest {
683                app_name: "app".into(),
684                user_id: "user".into(),
685                session_id: "s2".into(),
686            })
687            .await
688            .unwrap();
689
690        assert_eq!(list.file_names, vec!["user:shared.txt".to_string()]);
691    }
692
693    #[test]
694    fn name_encoding_is_injective_and_round_trips() {
695        let names = [
696            "a:b",
697            "a__b",
698            "a_b",
699            "a%3Ab",
700            "a___b",
701            "_",
702            "__",
703            "___",
704            "a_:b",
705            "50%.txt",
706            "what?.txt",
707            "q<1>|\"*\"",
708            "tab\tname",
709            "user:prefs",
710            "plain.txt",
711            "日本:語",
712        ];
713        let encoded: BTreeSet<String> = names.iter().map(|name| encode_name(name)).collect();
714        assert_eq!(encoded.len(), names.len(), "{encoded:?}");
715        for name in names {
716            let dir = encode_name(name);
717            assert!(!dir.contains("__"), "{name} encoded as {dir}");
718            assert!(!dir.contains(['<', '>', ':', '"', '|', '?', '*', '\t']), "{dir}");
719            assert_eq!(decode_name(&dir), name);
720        }
721    }
722
723    #[test]
724    fn legacy_directory_names_decode_as_before() {
725        assert_eq!(decode_name("user__prefs"), "user:prefs");
726        assert_eq!(decode_name("report__q1"), "report:q1");
727        assert_eq!(decode_name("plain.txt"), "plain.txt");
728        // A literal `%` that is not an escape stays as written.
729        assert_eq!(decode_name("50%off"), "50%off");
730    }
731}