rostra_client/
multiclient.rs1use std::collections::{HashMap, VecDeque};
2use std::io;
3use std::path::PathBuf;
4use std::sync::Arc;
5use std::time::Instant;
6
7use rostra_client_db::{Database, DbError};
8use rostra_core::id::RostraId;
9use rostra_util_error::FmtCompact as _;
10use snafu::{ResultExt as _, Snafu};
11use tokio::sync::RwLock;
12use tracing::{debug, info, warn};
13
14use crate::error::InitError;
15use crate::{Client, ClientHandle, LOG_TARGET};
16
17#[derive(Debug, Snafu)]
18pub enum MultiClientError {
19 #[snafu(display("Failed to initialize client"))]
20 ClientInit { source: InitError },
21 #[snafu(display("Failed to open client database"))]
22 Database { source: DbError },
23 #[snafu(transparent)]
24 Io { source: io::Error },
25}
26
27pub type MultiClientResult<T> = std::result::Result<T, MultiClientError>;
28struct ClientInfo {
29 client: Arc<Client>,
30 last_used: Instant,
31}
32
33#[derive(Clone)]
34pub struct MultiClient {
35 data_dir: PathBuf,
36 inner: Arc<tokio::sync::RwLock<HashMap<RostraId, ClientInfo>>>,
37 max_clients: usize,
38 usage_queue: Arc<tokio::sync::RwLock<VecDeque<RostraId>>>,
39 public_mode: bool,
42 pkarr_client: Arc<pkarr::Client>,
44}
45
46impl MultiClient {
47 pub fn new(
48 data_dir: PathBuf,
49 max_clients: usize,
50 public_mode: bool,
51 pkarr_client: Arc<pkarr::Client>,
52 ) -> Self {
53 Self {
54 data_dir,
55 inner: Arc::new(RwLock::new(Default::default())),
56 max_clients: max_clients.max(1), usage_queue: Arc::new(RwLock::new(VecDeque::new())),
58 public_mode,
59 pkarr_client,
60 }
61 }
62}
63
64impl MultiClient {
65 pub async fn load(&self, id: RostraId) -> MultiClientResult<Arc<Client>> {
66 {
68 let mut write = self.inner.write().await;
69 if let Some(client_info) = write.get_mut(&id) {
70 client_info.last_used = Instant::now();
72
73 self.update_usage_queue(id).await;
75
76 return Ok(client_info.client.clone());
77 }
78 }
79
80 let load_start = Instant::now();
82
83 let db_path = Database::mk_db_path(&self.data_dir, id).await?;
84
85 let compact = db_path.exists();
86 let mut db = Database::open(&db_path, id).await.context(DatabaseSnafu)?;
87 debug!(target: LOG_TARGET, id = %id, elapsed_ms = %load_start.elapsed().as_millis(), "Database opened");
88
89 if compact {
90 if let Err(err) = db.compact().await {
91 warn!(
92 target: LOG_TARGET,
93 err = %err.fmt_compact(),
94 path=%db_path.display(),
95 "Failed to compact database"
96 );
97 }
98 debug!(target: LOG_TARGET, id = %id, elapsed_ms = %load_start.elapsed().as_millis(), "Database compacted");
99 }
100
101 let client = Client::builder(id)
102 .db(db)
103 .public_mode(self.public_mode)
104 .pkarr_client(self.pkarr_client.clone())
105 .build()
106 .await
107 .context(ClientInitSnafu)?;
108 debug!(target: LOG_TARGET, id = %id, elapsed_ms = %load_start.elapsed().as_millis(), "Client built");
109
110 self.maybe_evict_clients().await?;
112
113 {
115 let mut write = self.inner.write().await;
116 write.insert(
117 id,
118 ClientInfo {
119 client: client.clone(),
120 last_used: Instant::now(),
121 },
122 );
123 }
124
125 self.update_usage_queue(id).await;
127
128 Ok(client)
129 }
130
131 async fn update_usage_queue(&self, id: RostraId) {
133 let mut queue = self.usage_queue.write().await;
134
135 if let Some(pos) = queue.iter().position(|&x| x == id) {
137 queue.remove(pos);
138 }
139
140 queue.push_front(id);
142 }
143
144 async fn maybe_evict_clients(&self) -> MultiClientResult<()> {
146 let mut write = self.inner.write().await;
147
148 if write.len() < self.max_clients {
150 return Ok(());
151 }
152
153 let to_evict = {
155 let queue = self.usage_queue.read().await;
156
157 let num_to_evict = write.len() + 1 - self.max_clients;
159 queue
160 .iter()
161 .rev()
162 .take(num_to_evict)
163 .cloned()
164 .collect::<Vec<_>>()
165 };
166
167 for id in to_evict {
169 if write.remove(&id).is_some() {
170 info!(
171 target: LOG_TARGET,
172 id = %id,
173 "Evicted client due to max_clients limit"
174 );
175 }
176 }
177
178 {
180 let mut queue = self.usage_queue.write().await;
181 queue.retain(|id| write.contains_key(id));
182 }
183
184 Ok(())
185 }
186
187 pub async fn get(&self, id: RostraId) -> Option<ClientHandle> {
188 let mut write = self.inner.write().await;
189 if let Some(client_info) = write.get_mut(&id) {
190 client_info.last_used = Instant::now();
192
193 self.update_usage_queue(id).await;
195
196 Some(client_info.client.handle())
197 } else {
198 None
199 }
200 }
201}