Skip to main content

bitwarden_ipc/traits/
session_repository.rs

1use std::{collections::HashMap, fmt::Debug};
2
3use tokio::sync::RwLock;
4
5use crate::endpoint::Endpoint;
6
7pub trait SessionRepository<Session>: Send + Sync + 'static {
8    type GetError: Debug + Send + Sync + 'static;
9    type SaveError: Debug + Send + Sync + 'static;
10    type RemoveError: Debug + Send + Sync + 'static;
11
12    fn get(
13        &self,
14        destination: Endpoint,
15    ) -> impl std::future::Future<Output = Result<Option<Session>, Self::GetError>>;
16    fn save(
17        &self,
18        destination: Endpoint,
19        session: Session,
20    ) -> impl std::future::Future<Output = Result<(), Self::SaveError>>;
21    fn remove(
22        &self,
23        destination: Endpoint,
24    ) -> impl std::future::Future<Output = Result<(), Self::RemoveError>>;
25}
26
27/// An in-memory session repository implementation that stores sessions in a `HashMap` protected by
28/// an `RwLock`. This is a simple implementation that can be used for testing or in scenarios where
29/// persistence is not required.
30pub type InMemorySessionRepository<Session> = RwLock<HashMap<Endpoint, Session>>;
31impl<Session> SessionRepository<Session> for InMemorySessionRepository<Session>
32where
33    Session: Clone + Send + Sync + 'static,
34{
35    type GetError = ();
36    type SaveError = ();
37    type RemoveError = ();
38
39    async fn get(&self, destination: Endpoint) -> Result<Option<Session>, ()> {
40        Ok(self.read().await.get(&destination).cloned())
41    }
42
43    async fn save(&self, destination: Endpoint, session: Session) -> Result<(), ()> {
44        self.write().await.insert(destination, session);
45        Ok(())
46    }
47
48    async fn remove(&self, destination: Endpoint) -> Result<(), ()> {
49        self.write().await.remove(&destination);
50        Ok(())
51    }
52}