snix_store/pathinfoservice/
memory.rs1use super::{PathInfo, PathInfoService};
2use async_stream::try_stream;
3use futures::stream::BoxStream;
4use nix_compat::nixbase32;
5use snix_castore::Error;
6use snix_castore::composition::{CompositionContext, ServiceBuilder};
7use std::{collections::HashMap, sync::Arc};
8use tokio::sync::RwLock;
9use tonic::async_trait;
10use tracing::instrument;
11
12#[derive(Default)]
13pub struct MemoryPathInfoService {
14 instance_name: String,
15 db: Arc<RwLock<HashMap<[u8; 20], PathInfo>>>,
16}
17
18#[async_trait]
19impl PathInfoService for MemoryPathInfoService {
20 #[instrument(level = "trace", skip_all, fields(path_info.digest = nixbase32::encode(&digest), instance_name = %self.instance_name))]
21 async fn get(&self, digest: [u8; 20]) -> Result<Option<PathInfo>, Error> {
22 let db = self.db.read().await;
23
24 match db.get(&digest) {
25 None => Ok(None),
26 Some(path_info) => Ok(Some(path_info.clone())),
27 }
28 }
29
30 #[instrument(level = "trace", skip_all, fields(path_info.root_node = ?path_info.node, instance_name = %self.instance_name))]
31 async fn put(&self, path_info: PathInfo) -> Result<PathInfo, Error> {
32 let mut db = self.db.write().await;
34 db.insert(*path_info.store_path.digest(), path_info.clone());
35
36 Ok(path_info)
37 }
38
39 fn list(&self) -> BoxStream<'static, Result<PathInfo, Error>> {
40 let db = self.db.clone();
41
42 Box::pin(try_stream! {
43 let db = db.read().await;
44 let it = db.iter();
45
46 for (_k, v) in it {
47 yield v.clone()
48 }
49 })
50 }
51}
52
53#[derive(serde::Deserialize, Debug)]
54#[serde(deny_unknown_fields)]
55pub struct MemoryPathInfoServiceConfig {}
56
57impl TryFrom<url::Url> for MemoryPathInfoServiceConfig {
58 type Error = Box<dyn std::error::Error + Send + Sync>;
59 fn try_from(url: url::Url) -> Result<Self, Self::Error> {
60 if url.has_host() || !url.path().is_empty() {
62 return Err(Error::StorageError("invalid url".to_string()).into());
63 }
64 Ok(MemoryPathInfoServiceConfig {})
65 }
66}
67
68#[async_trait]
69impl ServiceBuilder for MemoryPathInfoServiceConfig {
70 type Output = dyn PathInfoService;
71 async fn build<'a>(
72 &'a self,
73 instance_name: &str,
74 _context: &CompositionContext,
75 ) -> Result<Arc<dyn PathInfoService>, Box<dyn std::error::Error + Send + Sync + 'static>> {
76 Ok(Arc::new(MemoryPathInfoService {
77 instance_name: instance_name.to_string(),
78 db: Default::default(),
79 }))
80 }
81}