snix_castore/fs/
root_nodes.rs

1use std::collections::BTreeMap;
2
3use crate::nodes::Directory;
4use crate::{Error, Node, path::PathComponent};
5use futures::stream::BoxStream;
6use tonic::async_trait;
7
8/// Provides an interface for looking up root nodes  in snix-castore by given
9/// a lookup key (usually the basename), and optionally allow a listing.
10#[async_trait]
11pub trait RootNodes: Send + Sync {
12    /// Looks up a root CA node based on the basename of the node in the root
13    /// directory of the filesystem.
14    async fn get_by_basename(&self, name: &PathComponent) -> Result<Option<Node>, Error>;
15
16    /// Lists all root CA nodes in the filesystem, as a tuple of (base)name
17    /// and Node.
18    /// An error can be returned in case listing is not allowed.
19    fn list(&self) -> BoxStream<Result<(PathComponent, Node), Error>>;
20}
21
22#[async_trait]
23/// Implements RootNodes for something deref'ing to a BTreeMap of Nodes, where
24/// the key is the node name.
25impl<T> RootNodes for T
26where
27    T: AsRef<BTreeMap<PathComponent, Node>> + Send + Sync,
28{
29    async fn get_by_basename(&self, name: &PathComponent) -> Result<Option<Node>, Error> {
30        Ok(self.as_ref().get(name).cloned())
31    }
32
33    fn list(&self) -> BoxStream<Result<(PathComponent, Node), Error>> {
34        Box::pin(tokio_stream::iter(
35            self.as_ref()
36                .iter()
37                .map(|(name, node)| Ok((name.to_owned(), node.to_owned()))),
38        ))
39    }
40}
41
42#[async_trait]
43impl RootNodes for Directory {
44    async fn get_by_basename(&self, name: &PathComponent) -> Result<Option<Node>, Error> {
45        Ok(self
46            .nodes()
47            .find(|(key, _)| *key == name)
48            .map(|(_, node)| node.clone()))
49    }
50
51    fn list(&self) -> BoxStream<Result<(PathComponent, Node), Error>> {
52        Box::pin(tokio_stream::iter(
53            self.nodes()
54                .map(|(name, node)| Ok((name.to_owned(), node.to_owned()))),
55        ))
56    }
57}