Skip to main content

storage_kit/ns/
memory.rs

1//! [`Memory`]: an in-memory mount with exact versions, for tests and scratch trees.
2//!
3//! It is also the reference for the conformance suite: where `HostDir` is best effort (versions, watch latency) `Memory`
4//! is exact, so a behaviour difference between the two is either a declared [`Caps`] difference or a bug.
5//!
6//! - `if_version` is **exact**: the check and the change happen under one lock.
7//! - `watch` is **immediate** ([`WatchKind::Native`]): the batch is queued before the writing call returns.
8//! - Versions are a counter made unique **per instance** (an instance number and a random part in its high bits), so a
9//!   version from one `Memory` never validates against another. A directory's version changes whenever an entry is
10//!   added to, removed from or renamed in it (and may change more often).
11//! - No ownership or mode (`owner_mode` is false), no hard links, no symlinks; nothing to escape from.
12//!
13//! [`MemoryOptions`] can switch capabilities off so the suite can prove a backend that declares a capability false
14//! really returns `Unsupported` for it.
15
16use std::collections::BTreeMap;
17use std::sync::atomic::{AtomicU32, Ordering};
18use std::sync::{Arc, Mutex, MutexGuard, Weak};
19
20use super::backend::{Backend, Caps, Entry, Kind, Stat, Version, WatchKind, WriteOp};
21use super::error::{Feature, InputReason, NsError, NsErrorKind, NsResult};
22use super::path::{case_fold_key, NsPath};
23use super::watch::{new_epoch, BatchSender, Watch, WatchOpts};
24
25/// Which optional capabilities a [`Memory`] provides. The default is all of them.
26#[derive(Debug, Clone, Copy, PartialEq, Eq)]
27#[non_exhaustive]
28pub struct MemoryOptions {
29    /// `write` is available. When false every `write` is `Unsupported(Feature::Write)`.
30    pub writable: bool,
31    /// `Replace` is available. When false it is `Unsupported(Feature::AtomicReplace)`.
32    pub atomic_replace: bool,
33    /// `watch` is available. When false it is `Unsupported(Feature::Watch)` and `caps().watch` is `WatchKind::None`.
34    pub watch: bool,
35}
36
37impl MemoryOptions {
38    /// Set [`MemoryOptions::writable`].
39    #[must_use]
40    pub fn writable(mut self, on: bool) -> Self {
41        self.writable = on;
42        self
43    }
44
45    /// Set [`MemoryOptions::atomic_replace`].
46    #[must_use]
47    pub fn atomic_replace(mut self, on: bool) -> Self {
48        self.atomic_replace = on;
49        self
50    }
51
52    /// Set [`MemoryOptions::watch`].
53    #[must_use]
54    pub fn watch(mut self, on: bool) -> Self {
55        self.watch = on;
56        self
57    }
58}
59
60impl Default for MemoryOptions {
61    fn default() -> Self {
62        MemoryOptions {
63            writable: true,
64            atomic_replace: true,
65            watch: true,
66        }
67    }
68}
69
70enum Node {
71    File {
72        data: Vec<u8>,
73        ver: u128,
74    },
75    Dir {
76        children: BTreeMap<String, Node>,
77        ver: u128,
78    },
79}
80
81impl Node {
82    fn version(&self) -> Version {
83        let ver = match self {
84            Node::File { ver, .. } | Node::Dir { ver, .. } => *ver,
85        };
86        let mut bytes = vec![b'm'];
87        bytes.extend_from_slice(&ver.to_le_bytes());
88        Version::from_bytes(&bytes)
89    }
90
91    fn kind(&self) -> Kind {
92        match self {
93            Node::File { .. } => Kind::File,
94            Node::Dir { .. } => Kind::Dir,
95        }
96    }
97}
98
99struct Watcher {
100    id: u64,
101    dir: NsPath,
102    opts: WatchOpts,
103    sender: BatchSender,
104    /// Whether the watched directory existed after the last mutation: its going away and coming back are `rescan`s.
105    present: bool,
106}
107
108struct State {
109    root: Node,
110    counter: u128,
111    watchers: Vec<Watcher>,
112    next_watch_id: u64,
113}
114
115/// The first version number of a new `Memory`: `[instance: 32][random: 32][counter: 64]`. The instance part is unique in
116/// this process and the random part makes a collision across processes vanishingly unlikely, so a version taken from
117/// one `Memory` is never equal to one of another: used as `if_version` against the wrong mount it is a
118/// `VersionMismatch`, not a lucky match.
119fn fresh_counter_base() -> u128 {
120    static INSTANCES: AtomicU32 = AtomicU32::new(0);
121    let instance = u128::from(INSTANCES.fetch_add(1, Ordering::Relaxed));
122    let random = u128::from(new_epoch() as u32);
123    (instance << 96) | (random << 64)
124}
125
126fn tick(counter: &mut u128) -> u128 {
127    *counter += 1;
128    *counter
129}
130
131fn lookup<'a>(root: &'a Node, path: &NsPath) -> NsResult<&'a Node> {
132    let mut cur = root;
133    for name in path.components() {
134        cur = match cur {
135            Node::Dir { children, .. } => children
136                .get(name)
137                .ok_or_else(|| NsError::at(NsErrorKind::NotFound, path))?,
138            Node::File { .. } => return Err(NsError::at(NsErrorKind::NotADirectory, path)),
139        };
140    }
141    Ok(cur)
142}
143
144type DirMut<'a> = (&'a mut BTreeMap<String, Node>, &'a mut u128);
145
146fn dir_mut<'a>(root: &'a mut Node, path: &NsPath) -> NsResult<DirMut<'a>> {
147    let mut cur = root;
148    for name in path.components() {
149        cur = match cur {
150            Node::Dir { children, .. } => children
151                .get_mut(name)
152                .ok_or_else(|| NsError::at(NsErrorKind::NotFound, path))?,
153            Node::File { .. } => return Err(NsError::at(NsErrorKind::NotADirectory, path)),
154        };
155    }
156    match cur {
157        Node::Dir { children, ver } => Ok((children, ver)),
158        Node::File { .. } => Err(NsError::at(NsErrorKind::NotADirectory, path)),
159    }
160}
161
162/// Same-name or case-fold clash between `name` and the keys of `children`, ignoring `ignore`.
163fn conflict(
164    children: &BTreeMap<String, Node>,
165    name: &str,
166    ignore: Option<&str>,
167) -> Option<NsErrorKind> {
168    let key = case_fold_key(name);
169    let mut fold = false;
170    for existing in children.keys() {
171        if Some(existing.as_str()) == ignore {
172            continue;
173        }
174        if existing == name {
175            return Some(NsErrorKind::AlreadyExists);
176        }
177        if case_fold_key(existing) == key {
178            fold = true;
179        }
180    }
181    fold.then_some(NsErrorKind::CaseCollision)
182}
183
184fn check_version(node: &Node, if_version: Option<&Version>, path: &NsPath) -> NsResult<()> {
185    match if_version {
186        Some(v) if *v != node.version() => Err(NsError::at(NsErrorKind::VersionMismatch, path)),
187        _ => Ok(()),
188    }
189}
190
191fn no_data(data: &[u8], path: &NsPath) -> NsResult<()> {
192    if data.is_empty() {
193        Ok(())
194    } else {
195        Err(NsError::at(
196            NsErrorKind::InvalidInput(InputReason::UnexpectedData),
197            path,
198        ))
199    }
200}
201
202fn no_version(if_version: Option<&Version>, path: &NsPath) -> NsResult<()> {
203    if if_version.is_none() {
204        Ok(())
205    } else {
206        Err(NsError::at(
207            NsErrorKind::InvalidInput(InputReason::VersionOnCreate),
208            path,
209        ))
210    }
211}
212
213/// An in-memory mount. Cheap to clone: clones share one tree. See the [module docs](self).
214#[derive(Clone)]
215pub struct Memory {
216    state: Arc<Mutex<State>>,
217    opts: MemoryOptions,
218}
219
220impl std::fmt::Debug for Memory {
221    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
222        f.debug_struct("Memory")
223            .field("opts", &self.opts)
224            .finish_non_exhaustive()
225    }
226}
227
228impl Default for Memory {
229    fn default() -> Self {
230        Self::new()
231    }
232}
233
234impl Memory {
235    /// An empty tree with every capability.
236    pub fn new() -> Self {
237        Self::with_options(MemoryOptions::default())
238    }
239
240    /// An empty tree with some capabilities switched off.
241    pub fn with_options(opts: MemoryOptions) -> Self {
242        let base = fresh_counter_base();
243        Memory {
244            state: Arc::new(Mutex::new(State {
245                root: Node::Dir {
246                    children: BTreeMap::new(),
247                    ver: base,
248                },
249                counter: base,
250                watchers: Vec::new(),
251                next_watch_id: 0,
252            })),
253            opts,
254        }
255    }
256
257    /// Put a file in place, creating missing parent directories, regardless of the capability switches. For setting up
258    /// a tree that is then read through a read-only `Memory`.
259    pub fn preload(&self, path: &NsPath, data: &[u8]) -> NsResult<()> {
260        let mut dirs = Vec::new();
261        let mut cur = path.parent();
262        while let Some(p) = cur {
263            if p.is_root() {
264                break;
265            }
266            cur = p.parent();
267            dirs.push(p);
268        }
269        for dir in dirs.into_iter().rev() {
270            match self.apply(&dir, WriteOp::MakeDir, &[], None) {
271                Ok(_) => {}
272                Err(e) if e.kind() == NsErrorKind::AlreadyExists => {}
273                Err(e) => return Err(e),
274            }
275        }
276        self.apply(path, WriteOp::Replace, data, None).map(|_| ())
277    }
278
279    fn lock(&self) -> MutexGuard<'_, State> {
280        self.state.lock().unwrap_or_else(|e| e.into_inner())
281    }
282
283    /// The write itself, with no capability checks. Returns the version and nothing else; watchers are notified here.
284    fn apply(
285        &self,
286        path: &NsPath,
287        op: WriteOp,
288        data: &[u8],
289        if_version: Option<&Version>,
290    ) -> NsResult<Version> {
291        let mut guard = self.lock();
292        let st = &mut *guard;
293        let (version, affected) = match op {
294            WriteOp::CreateExclusive => {
295                no_version(if_version, path)?;
296                create(st, path, Some(data))?
297            }
298            WriteOp::MakeDir => {
299                no_data(data, path)?;
300                no_version(if_version, path)?;
301                create(st, path, None)?
302            }
303            WriteOp::Replace => replace(st, path, data, if_version)?,
304            WriteOp::Remove => {
305                no_data(data, path)?;
306                remove(st, path, if_version)?
307            }
308            WriteOp::RenameWithinMount { to } => {
309                no_data(data, path)?;
310                rename(st, path, &to, if_version)?
311            }
312        };
313        notify(st, &affected);
314        Ok(version)
315    }
316}
317
318fn split(path: &NsPath, what_for_root: NsErrorKind) -> NsResult<(NsPath, &str)> {
319    match (path.parent(), path.file_name()) {
320        (Some(parent), Some(name)) => Ok((parent, name)),
321        _ => Err(NsError::at(what_for_root, path)),
322    }
323}
324
325/// `CreateExclusive` (`data` is `Some`) and `MakeDir` (`None`).
326fn create(st: &mut State, path: &NsPath, data: Option<&[u8]>) -> NsResult<(Version, Vec<NsPath>)> {
327    let (parent, name) = split(path, NsErrorKind::AlreadyExists)?;
328    let State { root, counter, .. } = st;
329    let (children, parent_ver) = dir_mut(root, &parent).map_err(|e| e.or_at(path))?;
330    if let Some(kind) = conflict(children, name, None) {
331        return Err(NsError::at(kind, path));
332    }
333    let ver = tick(counter);
334    let node = match data {
335        Some(d) => Node::File {
336            data: d.to_vec(),
337            ver,
338        },
339        None => Node::Dir {
340            children: BTreeMap::new(),
341            ver,
342        },
343    };
344    let version = node.version();
345    children.insert(name.to_string(), node);
346    *parent_ver = tick(counter);
347    Ok((version, vec![path.clone(), parent]))
348}
349
350fn replace(
351    st: &mut State,
352    path: &NsPath,
353    data: &[u8],
354    if_version: Option<&Version>,
355) -> NsResult<(Version, Vec<NsPath>)> {
356    let (parent, name) = split(path, NsErrorKind::IsADirectory)?;
357    let State { root, counter, .. } = st;
358    let (children, parent_ver) = dir_mut(root, &parent).map_err(|e| e.or_at(path))?;
359    match children.get_mut(name) {
360        Some(Node::Dir { .. }) => Err(NsError::at(NsErrorKind::IsADirectory, path)),
361        Some(node @ Node::File { .. }) => {
362            check_version(node, if_version, path)?;
363            let ver = tick(counter);
364            *node = Node::File {
365                data: data.to_vec(),
366                ver,
367            };
368            Ok((node.version(), vec![path.clone(), parent]))
369        }
370        None => {
371            if if_version.is_some() {
372                return Err(NsError::at(NsErrorKind::NotFound, path));
373            }
374            if let Some(NsErrorKind::CaseCollision) = conflict(children, name, None) {
375                return Err(NsError::at(NsErrorKind::CaseCollision, path));
376            }
377            let node = Node::File {
378                data: data.to_vec(),
379                ver: tick(counter),
380            };
381            let version = node.version();
382            children.insert(name.to_string(), node);
383            *parent_ver = tick(counter);
384            Ok((version, vec![path.clone(), parent]))
385        }
386    }
387}
388
389fn remove(
390    st: &mut State,
391    path: &NsPath,
392    if_version: Option<&Version>,
393) -> NsResult<(Version, Vec<NsPath>)> {
394    let (parent, name) = split(path, NsErrorKind::InvalidInput(InputReason::MountRoot))?;
395    let State { root, counter, .. } = st;
396    let (children, parent_ver) = dir_mut(root, &parent).map_err(|e| e.or_at(path))?;
397    let node = children
398        .get(name)
399        .ok_or_else(|| NsError::at(NsErrorKind::NotFound, path))?;
400    check_version(node, if_version, path)?;
401    if let Node::Dir {
402        children: inner, ..
403    } = node
404    {
405        if !inner.is_empty() {
406            return Err(NsError::at(NsErrorKind::NotEmpty, path));
407        }
408    }
409    let version = node.version();
410    children.remove(name);
411    *parent_ver = tick(counter);
412    Ok((version, vec![path.clone(), parent]))
413}
414
415fn rename(
416    st: &mut State,
417    from: &NsPath,
418    to: &NsPath,
419    if_version: Option<&Version>,
420) -> NsResult<(Version, Vec<NsPath>)> {
421    let root_err = NsErrorKind::InvalidInput(InputReason::MountRoot);
422    let (from_parent, from_name) = split(from, root_err)?;
423    let (to_parent, to_name) = split(to, root_err)?;
424    if from == to {
425        // Not a no-op: the name is taken. Only a respelling of one's own name may "collide" with itself.
426        return Err(NsError::at(NsErrorKind::AlreadyExists, to));
427    }
428    if to.starts_with(from) {
429        return Err(NsError::at(
430            NsErrorKind::InvalidInput(InputReason::MoveIntoSelf),
431            to,
432        ));
433    }
434    // Validate everything first (read-only), so the mutation below cannot fail half way.
435    let node = lookup(&st.root, from)?;
436    check_version(node, if_version, from)?;
437    let version = node.version();
438    let to_dir = lookup(&st.root, &to_parent).map_err(|e| e.or_at(to))?;
439    let Node::Dir { children, .. } = to_dir else {
440        return Err(NsError::at(NsErrorKind::NotADirectory, to));
441    };
442    let ignore = (from_parent == to_parent).then_some(from_name);
443    if let Some(kind) = conflict(children, to_name, ignore) {
444        return Err(NsError::at(kind, to));
445    }
446
447    let State { root, counter, .. } = st;
448    let (src_children, src_ver) = dir_mut(root, &from_parent)?;
449    let Some(moved) = src_children.remove(from_name) else {
450        return Err(NsError::at(NsErrorKind::NotFound, from));
451    };
452    *src_ver = tick(counter);
453    let (dst_children, dst_ver) = dir_mut(root, &to_parent)?;
454    dst_children.insert(to_name.to_string(), moved);
455    *dst_ver = tick(counter);
456    Ok((
457        version,
458        vec![from.clone(), to.clone(), from_parent, to_parent],
459    ))
460}
461
462/// Tell every watcher about a mutation. `affected` are the paths whose entry (or whose directory listing) changed.
463fn notify(st: &mut State, affected: &[NsPath]) {
464    let State { root, watchers, .. } = st;
465    watchers.retain_mut(|w| {
466        let present = matches!(lookup(root, &w.dir), Ok(Node::Dir { .. }));
467        if present != w.present {
468            // The watched directory went away or came back: events may have been lost, so say so.
469            w.present = present;
470            return w.sender.send(Vec::new(), true, w.opts.max_entries);
471        }
472        if !present {
473            return true;
474        }
475        let changed: Vec<NsPath> = affected
476            .iter()
477            .filter(|p| {
478                **p != w.dir
479                    && p.starts_with(&w.dir)
480                    && (w.opts.recursive || p.parent().as_ref() == Some(&w.dir))
481            })
482            .cloned()
483            .collect();
484        changed.is_empty() || w.sender.send(changed, false, w.opts.max_entries)
485    });
486}
487
488impl Backend for Memory {
489    fn caps(&self) -> Caps {
490        Caps {
491            writable: self.opts.writable,
492            atomic_replace: self.opts.writable && self.opts.atomic_replace,
493            exact_if_version: true,
494            watch: if self.opts.watch {
495                WatchKind::Native
496            } else {
497                WatchKind::None
498            },
499            owner_mode: false,
500            case_sensitive: true,
501            strict_confinement: true,
502        }
503    }
504
505    fn walk(&self, path: &NsPath) -> NsResult<Vec<Entry>> {
506        let st = self.lock();
507        match lookup(&st.root, path)? {
508            Node::Dir { children, .. } => Ok(children
509                .iter()
510                .map(|(name, node)| Entry {
511                    name: name.clone(),
512                    kind: node.kind(),
513                })
514                .collect()),
515            Node::File { .. } => Err(NsError::at(NsErrorKind::NotADirectory, path)),
516        }
517    }
518
519    fn read(&self, path: &NsPath, max: u64) -> NsResult<(Vec<u8>, Version)> {
520        let st = self.lock();
521        match lookup(&st.root, path)? {
522            node @ Node::File { data, .. } => {
523                if data.len() as u64 > max {
524                    return Err(NsError::at(NsErrorKind::TooLarge, path));
525                }
526                Ok((data.clone(), node.version()))
527            }
528            Node::Dir { .. } => Err(NsError::at(NsErrorKind::IsADirectory, path)),
529        }
530    }
531
532    fn stat(&self, path: &NsPath) -> NsResult<Stat> {
533        let st = self.lock();
534        let node = lookup(&st.root, path)?;
535        Ok(Stat {
536            kind: node.kind(),
537            size: match node {
538                Node::File { data, .. } => data.len() as u64,
539                Node::Dir { .. } => 0,
540            },
541            version: node.version(),
542            owner: None,
543            mode: None,
544            links: None,
545            modified: None,
546        })
547    }
548
549    fn write(
550        &self,
551        path: &NsPath,
552        op: WriteOp,
553        data: &[u8],
554        if_version: Option<&Version>,
555    ) -> NsResult<Version> {
556        if !self.opts.writable {
557            return Err(NsError::at(NsErrorKind::Unsupported(Feature::Write), path));
558        }
559        if matches!(op, WriteOp::Replace) && !self.opts.atomic_replace {
560            return Err(NsError::at(
561                NsErrorKind::Unsupported(Feature::AtomicReplace),
562                path,
563            ));
564        }
565        self.apply(path, op, data, if_version)
566    }
567
568    fn watch(&self, path: &NsPath, opts: WatchOpts) -> NsResult<Watch> {
569        if !self.opts.watch {
570            return Err(NsError::at(NsErrorKind::Unsupported(Feature::Watch), path));
571        }
572        let mut st = self.lock();
573        match lookup(&st.root, path)? {
574            Node::Dir { .. } => {}
575            Node::File { .. } => return Err(NsError::at(NsErrorKind::NotADirectory, path)),
576        }
577        let (sender, rx) = BatchSender::channel();
578        let id = st.next_watch_id;
579        st.next_watch_id += 1;
580        st.watchers.push(Watcher {
581            id,
582            dir: path.clone(),
583            opts,
584            sender,
585            present: true,
586        });
587        let weak: Weak<Mutex<State>> = Arc::downgrade(&self.state);
588        Ok(Watch::new(rx, move || {
589            if let Some(state) = weak.upgrade() {
590                let mut st = state.lock().unwrap_or_else(|e| e.into_inner());
591                st.watchers.retain(|w| w.id != id);
592            }
593        }))
594    }
595}