Skip to main content

fasm_storage/
key.rs

1//! Directory-key validation and the owned key form.
2
3use core::str;
4
5use thiserror::Error;
6
7use crate::error::RetryableStorageError;
8
9/// The owned `(dir, key)` form, for callers that hold a key across async
10/// boundaries, in contrast to the borrowed forms the store operations
11/// take. `dir` must pass [`validate_dir`](crate::validate_dir); `key` is
12/// arbitrary bytes.
13#[derive(Debug, Clone, PartialEq, Eq)]
14pub struct Key {
15    /// The directory path (UTF-8 segments).
16    pub dir: Vec<Vec<u8>>,
17    /// The key within the directory (arbitrary bytes).
18    pub key: Vec<u8>,
19}
20
21/// A directory path failed validation.
22///
23/// Both variants are input errors: the operation is just as wrong on a
24/// rerun, so neither is retryable.
25#[derive(Debug, Error, PartialEq, Eq)]
26pub enum KeyError {
27    /// Segment `segment` is not valid UTF-8.
28    ///
29    /// Directory segments are the trait-level UTF-8 contract (FDB's layer
30    /// takes `&[String]` paths; the flat backends enforce the same for
31    /// uniformity). Keys are not subject to it.
32    #[error("directory segment {segment} is not valid UTF-8")]
33    DirSegmentNotUtf8 {
34        /// The 0-based index of the offending segment.
35        segment: usize,
36    },
37    /// A directory-removal operation was applied to the root `[]`.
38    #[error("the root directory cannot be removed")]
39    RootNotRemovable,
40}
41
42impl RetryableStorageError for KeyError {
43    fn is_retryable(&self) -> bool {
44        false
45    }
46}
47
48/// Validate a directory path: every segment must be valid UTF-8.
49///
50/// Every backend calls this before touching its engine, so an invalid path
51/// fails with one answer on every backend. An empty segment is valid (the
52/// empty string is valid UTF-8), and the empty path (the root) is valid.
53pub fn validate_dir(dir: &[&[u8]]) -> Result<(), KeyError> {
54    for (i, seg) in dir.iter().enumerate() {
55        if str::from_utf8(seg).is_err() {
56            return Err(KeyError::DirSegmentNotUtf8 { segment: i });
57        }
58    }
59    Ok(())
60}
61
62#[cfg(test)]
63mod tests {
64    use super::*;
65
66    // `proptest` reaches `wait-timeout`, which does not support browser wasm.
67    #[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
68    use proptest::prelude::*;
69
70    #[test]
71    fn validate_dir_accepts_utf8_and_empty() {
72        assert!(validate_dir(&[]).is_ok());
73        assert!(validate_dir(&[b"", b"asset", b"btc"]).is_ok());
74        // UTF-8 multi-byte content is legal.
75        assert!(validate_dir(&["€".as_bytes()]).is_ok());
76    }
77
78    #[test]
79    fn validate_dir_rejects_non_utf8_with_index() {
80        assert_eq!(
81            validate_dir(&[b"ok", b"\xFF\xFE"]),
82            Err(KeyError::DirSegmentNotUtf8 { segment: 1 })
83        );
84        assert_eq!(
85            validate_dir(&[b"\x00\xFF"]),
86            Err(KeyError::DirSegmentNotUtf8 { segment: 0 })
87        );
88    }
89
90    #[test]
91    fn key_error_is_not_retryable() {
92        assert!(!KeyError::RootNotRemovable.is_retryable());
93        assert!(!KeyError::DirSegmentNotUtf8 { segment: 0 }.is_retryable());
94    }
95
96    #[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
97    proptest! {
98        #[test]
99        fn prop_validate_dir_matches_str_from_utf8(
100            dir in proptest::collection::vec(proptest::collection::vec(any::<u8>(), 0..8), 0..4),
101        ) {
102            let slices: Vec<&[u8]> = dir.iter().map(|v| v.as_slice()).collect();
103            let expected: Option<usize> =
104                dir.iter().position(|seg| str::from_utf8(seg).is_err());
105            match (validate_dir(&slices), expected) {
106                (Ok(()), None) => {}
107                (Err(KeyError::DirSegmentNotUtf8 { segment }), Some(i)) => {
108                    prop_assert_eq!(segment, i);
109                }
110                (other, _) => prop_assert!(false, "unexpected answer: {other:?}"),
111            }
112        }
113    }
114}