Skip to main content

engine/core/
metadata.rs

1//! Object metadata.
2//!
3//! Metadata is generic: names, timestamps, a reference to an owning
4//! principal, opaque authorization data, and an extensible key/value store.
5//! The Engine stores extension values without understanding their meaning;
6//! the OS assigns semantics.
7
8use std::collections::BTreeMap;
9use std::fmt;
10
11use crate::error::Error;
12use crate::filesystem::path::SEPARATOR;
13use crate::security::authorization::{ActorId, AuthorizationData};
14
15use super::timestamp::Timestamp;
16
17/// The name of the filesystem root.
18///
19/// The root is the only object whose name is not a path component.
20pub const ROOT_NAME: &str = "/";
21
22/// The name of an object, as stored in its metadata.
23///
24/// Valid names are non-empty, contain no path separator and no NUL byte, and
25/// are neither `.` nor `..`.
26#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
27pub struct Name(String);
28
29impl Name {
30    /// Validates and constructs a name.
31    pub fn new(name: &str) -> Result<Self, Error> {
32        if name.is_empty() {
33            return Err(Error::InvalidName(name.to_owned()));
34        }
35        if name.contains(SEPARATOR) {
36            return Err(Error::InvalidName(name.to_owned()));
37        }
38        if name.contains('\0') {
39            return Err(Error::InvalidName(name.to_owned()));
40        }
41        if name == "." || name == ".." {
42            return Err(Error::InvalidName(name.to_owned()));
43        }
44        Ok(Self(name.to_owned()))
45    }
46
47    /// The name of the filesystem root.
48    pub fn root() -> Self {
49        Self(ROOT_NAME.to_owned())
50    }
51
52    /// Returns the name as a string slice.
53    pub fn as_str(&self) -> &str {
54        &self.0
55    }
56
57    /// Returns `true` for the root name.
58    pub fn is_root(&self) -> bool {
59        self.0 == ROOT_NAME
60    }
61}
62
63impl fmt::Display for Name {
64    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
65        self.0.fmt(f)
66    }
67}
68
69/// A generic metadata value for the extensible key/value store.
70///
71/// Used both for metadata extensions and for event payloads. The Engine does
72/// not interpret these values.
73#[derive(Clone, PartialEq, Debug)]
74pub enum MetadataValue {
75    /// A string value.
76    String(String),
77    /// A signed integer value.
78    Integer(i64),
79    /// An unsigned integer value.
80    Unsigned(u64),
81    /// A floating-point value.
82    Float(f64),
83    /// A boolean value.
84    Boolean(bool),
85}
86
87/// Metadata for an Engine object.
88///
89/// Metadata is owned by the object and moves with it; it is not tied to the
90/// object's path.
91#[derive(Clone, Debug, PartialEq)]
92pub struct Metadata {
93    name: Name,
94    created: Timestamp,
95    modified: Timestamp,
96    accessed: Timestamp,
97    owner: Option<ActorId>,
98    authorization: AuthorizationData,
99    version: Option<String>,
100    declared_size: Option<u64>,
101    extensions: BTreeMap<String, MetadataValue>,
102}
103
104impl Metadata {
105    /// Creates metadata for a new object, with all timestamps set to `now`.
106    pub(crate) fn new(name: Name, now: Timestamp) -> Self {
107        Self {
108            name,
109            created: now,
110            modified: now,
111            accessed: now,
112            owner: None,
113            authorization: AuthorizationData::new(),
114            version: None,
115            declared_size: None,
116            extensions: BTreeMap::new(),
117        }
118    }
119
120    /// Creates the metadata of the filesystem root.
121    ///
122    /// The root is created by the store itself, before any clock exists, so
123    /// its timestamps are the virtual epoch.
124    pub(crate) fn for_root() -> Self {
125        Self {
126            name: Name::root(),
127            created: Timestamp::ZERO,
128            modified: Timestamp::ZERO,
129            accessed: Timestamp::ZERO,
130            owner: None,
131            authorization: AuthorizationData::new(),
132            version: None,
133            declared_size: None,
134            extensions: BTreeMap::new(),
135        }
136    }
137
138    /// The object's name.
139    pub fn name(&self) -> &Name {
140        &self.name
141    }
142
143    /// The creation time.
144    pub fn created(&self) -> Timestamp {
145        self.created
146    }
147
148    /// The last modification time.
149    pub fn modified(&self) -> Timestamp {
150        self.modified
151    }
152
153    /// The last access time.
154    pub fn accessed(&self) -> Timestamp {
155        self.accessed
156    }
157
158    /// The owning principal, if any.
159    pub fn owner(&self) -> Option<ActorId> {
160        self.owner
161    }
162
163    /// The opaque authorization data.
164    pub fn authorization(&self) -> &AuthorizationData {
165        &self.authorization
166    }
167
168    /// An optional version string (for example `17.2` for a bundle).
169    pub fn version(&self) -> Option<&str> {
170        self.version.as_deref()
171    }
172
173    /// The size declared for metadata-only files, if any.
174    pub fn declared_size(&self) -> Option<u64> {
175        self.declared_size
176    }
177
178    /// A single extension value by key.
179    pub fn extension(&self, key: &str) -> Option<&MetadataValue> {
180        self.extensions.get(key)
181    }
182
183    /// All extension values.
184    pub fn extensions(&self) -> &BTreeMap<String, MetadataValue> {
185        &self.extensions
186    }
187
188    pub(crate) fn set_name(&mut self, name: Name) {
189        self.name = name;
190    }
191
192    pub(crate) fn set_modified(&mut self, timestamp: Timestamp) {
193        self.modified = timestamp;
194    }
195
196    pub(crate) fn set_accessed(&mut self, timestamp: Timestamp) {
197        self.accessed = timestamp;
198    }
199
200    pub(crate) fn set_owner(&mut self, owner: Option<ActorId>) {
201        self.owner = owner;
202    }
203
204    pub(crate) fn set_authorization(&mut self, authorization: AuthorizationData) {
205        self.authorization = authorization;
206    }
207
208    /// Applies a patch. Fields not present in the patch are left unchanged.
209    ///
210    /// The whole patch is validated before anything is applied, so a patch
211    /// with any invalid key leaves the metadata exactly as it was.
212    pub(crate) fn apply(&mut self, patch: &MetadataPatch) -> Result<(), Error> {
213        for key in patch.extensions.keys() {
214            validate_metadata_key(key)?;
215        }
216        if let Some(version) = &patch.version {
217            self.version = version.clone();
218        }
219        if let Some(declared_size) = &patch.declared_size {
220            self.declared_size = *declared_size;
221        }
222        for (key, value) in &patch.extensions {
223            match value {
224                Some(value) => {
225                    self.extensions.insert(key.clone(), value.clone());
226                }
227                None => {
228                    self.extensions.remove(key);
229                }
230            }
231        }
232        Ok(())
233    }
234}
235
236/// Validates a metadata extension key.
237fn validate_metadata_key(key: &str) -> Result<(), Error> {
238    if key.is_empty() {
239        return Err(Error::InvalidMetadataKey(key.to_owned()));
240    }
241    Ok(())
242}
243
244/// A set of metadata changes to apply atomically.
245///
246/// The outer `Option` indicates whether the field is part of the patch; the
247/// inner `Option` is the new value, where `None` clears the field. For
248/// [`MetadataPatch::extensions`], a `None` value removes the key.
249#[derive(Clone, Debug, Default, PartialEq)]
250pub struct MetadataPatch {
251    /// The new version, or `Some(None)` to clear it.
252    pub version: Option<Option<String>>,
253    /// The new declared size, or `Some(None)` to clear it.
254    pub declared_size: Option<Option<u64>>,
255    /// Extension changes: key to new value, or `None` to remove the key.
256    pub extensions: BTreeMap<String, Option<MetadataValue>>,
257}
258
259impl MetadataPatch {
260    /// Returns `true` when the patch changes nothing.
261    pub fn is_empty(&self) -> bool {
262        self.version.is_none() && self.declared_size.is_none() && self.extensions.is_empty()
263    }
264}
265
266#[cfg(test)]
267mod tests {
268    use super::*;
269
270    #[test]
271    fn valid_names_are_accepted() {
272        for name in ["file.txt", "ls", "a b", "снег", "-"] {
273            assert!(Name::new(name).is_ok(), "expected {name:?} to be valid");
274        }
275    }
276
277    #[test]
278    fn invalid_names_are_rejected() {
279        for name in ["", "/", "a/b", "a\0b", ".", ".."] {
280            assert_eq!(
281                Name::new(name).err(),
282                Some(Error::InvalidName(name.to_owned())),
283                "expected {name:?} to be invalid"
284            );
285        }
286    }
287
288    #[test]
289    fn patch_applies_only_present_fields() {
290        let mut metadata = Metadata::new(Name::new("a").unwrap(), Timestamp::ZERO);
291        let patch = MetadataPatch {
292            version: Some(Some("1.0".to_owned())),
293            ..MetadataPatch::default()
294        };
295        metadata.apply(&patch).unwrap();
296        assert_eq!(metadata.version(), Some("1.0"));
297        assert_eq!(metadata.declared_size(), None);
298    }
299
300    #[test]
301    fn patch_removes_extensions_with_none() {
302        let mut metadata = Metadata::new(Name::new("a").unwrap(), Timestamp::ZERO);
303        metadata
304            .apply(&MetadataPatch {
305                extensions: BTreeMap::from([(
306                    "kind".to_owned(),
307                    Some(MetadataValue::String("bundle".to_owned())),
308                )]),
309                ..MetadataPatch::default()
310            })
311            .unwrap();
312        assert!(metadata.extension("kind").is_some());
313
314        metadata
315            .apply(&MetadataPatch {
316                extensions: BTreeMap::from([("kind".to_owned(), None)]),
317                ..MetadataPatch::default()
318            })
319            .unwrap();
320        assert!(metadata.extension("kind").is_none());
321    }
322}