Skip to main content

aurelin_framework/storage/
path.rs

1use std::{fmt, str::FromStr};
2
3use object_store::path::Path;
4
5use super::{StorageError, StorageResult};
6
7/// A validated, non-empty path relative to a disk root.
8#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
9pub struct StoragePath(Path);
10
11impl StoragePath {
12    /// Validates an application path without silently changing it.
13    pub fn parse(value: impl AsRef<str>) -> StorageResult<Self> {
14        let value = value.as_ref();
15        validate_shape(value)?;
16        let path = Path::parse(value)
17            .map_err(|error| StorageError::InvalidPath { path: value.to_owned(), reason: error.to_string() })?;
18        if path.is_root() {
19            return Err(invalid(value, "a file path cannot be empty"));
20        }
21        Ok(Self(path))
22    }
23
24    pub(crate) fn object_path(&self) -> &Path {
25        &self.0
26    }
27
28    pub(crate) fn from_object_path(path: Path) -> Self {
29        Self(path)
30    }
31
32    /// Returns the validated relative path.
33    pub fn as_str(&self) -> &str {
34        self.0.as_ref()
35    }
36
37    /// Returns the individual path segments.
38    pub fn segments(&self) -> impl Iterator<Item = &str> {
39        self.as_str().split('/')
40    }
41}
42
43fn validate_shape(value: &str) -> StorageResult<()> {
44    if value.starts_with('/') {
45        return Err(invalid(value, "absolute paths are not allowed"));
46    }
47    if value.ends_with('/') {
48        return Err(invalid(value, "trailing separators are not allowed"));
49    }
50    if value.contains('\\') {
51        return Err(invalid(value, "backslash separators are not allowed"));
52    }
53    if value.as_bytes().get(1) == Some(&b':') && value.as_bytes().first().is_some_and(u8::is_ascii_alphabetic) {
54        return Err(invalid(value, "Windows absolute paths are not allowed"));
55    }
56    if value.split('/').any(|segment| segment.is_empty()) {
57        return Err(invalid(value, "empty path segments are not allowed"));
58    }
59    Ok(())
60}
61
62fn invalid(path: &str, reason: &str) -> StorageError {
63    StorageError::InvalidPath { path: path.to_owned(), reason: reason.to_owned() }
64}
65
66impl AsRef<str> for StoragePath {
67    fn as_ref(&self) -> &str {
68        self.as_str()
69    }
70}
71
72impl fmt::Display for StoragePath {
73    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
74        formatter.write_str(self.as_str())
75    }
76}
77
78impl FromStr for StoragePath {
79    type Err = StorageError;
80
81    fn from_str(value: &str) -> Result<Self, Self::Err> {
82        Self::parse(value)
83    }
84}
85
86impl TryFrom<&str> for StoragePath {
87    type Error = StorageError;
88
89    fn try_from(value: &str) -> Result<Self, Self::Error> {
90        Self::parse(value)
91    }
92}