beekeeper/api.rs
1//! The top-level [`BeekeeperApi`] handle.
2//!
3//! Owns the C++ wallet manager (via [`ffi::BeekeeperHolder`]), the set of
4//! open session tokens, and the activity clock used for the inactivity
5//! timeout.
6
7use std::{
8 cell::RefCell,
9 collections::{HashMap, HashSet},
10 fs,
11 path::{Path, PathBuf},
12 rc::Rc,
13 time::{Duration, Instant, SystemTime},
14};
15
16use cxx::UniquePtr;
17
18use crate::{
19 consts::{LEGACY_WALLET_DIR, LEGACY_WALLET_EXT},
20 errors::BeekeeperError,
21 ffi, new_rust_storage_protocol,
22 options::BeekeeperOptions,
23 session::Session,
24};
25
26/// Auto-lock instant reported while the inactivity timeout is disabled:
27/// a far-future sentinel of UNIX epoch + 100 years.
28const NO_TIMEOUT_SENTINEL: Duration =
29 Duration::from_secs(60 * 60 * 24 * 365 * 100);
30
31/// Root handle for the Beekeeper wallet daemon.
32///
33/// A single `BeekeeperApi` owns one C++ wallet manager and zero or more
34/// sessions; each session in turn owns zero or more wallets.
35///
36/// Use [`BeekeeperApi::new`] to construct and
37/// [`create_session`](Self::create_session) to obtain an owned
38/// [`Session`](crate::session::Session) guard for further work.
39pub struct BeekeeperApi {
40 pub(crate) inner: Rc<RefCell<Inner>>,
41}
42
43/// Shared state behind a [`BeekeeperApi`] and every [`Session`] / wallet
44/// handle spawned from it.
45///
46/// Wrapped in `Rc<RefCell<..>>` so that sessions and wallets are owned
47/// values (with the session closing itself on `Drop`) rather than `&mut`
48/// borrows of the api.
49pub(crate) struct Inner {
50 pub(crate) holder: UniquePtr<ffi::BeekeeperHolder>,
51 sessions: HashSet<String>,
52 wallets_meta: HashMap<(String, String), WalletMeta>,
53 pub(crate) is_in_memory: bool,
54 unlock_timeout_ms: u32,
55 last_activity: Instant,
56 wallet_dir: PathBuf,
57}
58
59/// Per-wallet metadata that the C++ layer does not track.
60///
61/// Currently just the `is_temporary` flag (an in-memory-only wallet inside
62/// a persistent beekeeper). Stored on the Rust side because the C++ holder
63/// returns only `(name, unlocked)` pairs from `list_wallets`.
64#[derive(Clone, Copy)]
65pub(crate) struct WalletMeta {
66 pub is_temporary: bool,
67}
68
69impl BeekeeperApi {
70 /// Construct a new beekeeper instance.
71 ///
72 /// Accepts anything convertible into `Option<BeekeeperOptions>`:
73 /// pass a [`BeekeeperOptions`] value directly, or `None` to use
74 /// [`BeekeeperOptions::default()`].
75 ///
76 /// When the options are not in-memory this also creates
77 /// `<storage_root>/.beekeeper/` (if missing) for wallet files.
78 pub fn new(options: impl Into<Option<BeekeeperOptions>>) -> Self {
79 let options = options.into().unwrap_or_default();
80 let inner = Inner::new(&options);
81
82 Self {
83 inner: Rc::new(RefCell::new(inner)),
84 }
85 }
86
87 /// Open a new session and return it as an owned
88 /// [`Session`](crate::session::Session) guard.
89 ///
90 /// The session closes itself (locking its wallets first) when dropped;
91 /// there is no explicit `close` call.
92 pub fn create_session(&self) -> Result<Session, BeekeeperError> {
93 let token = {
94 let mut inner = self.inner.borrow_mut();
95 let token = inner.holder.pin_mut().create_session()?;
96 inner.sessions.insert(token.clone());
97 token
98 };
99
100 Ok(Session::new(Rc::clone(&self.inner), token))
101 }
102
103 /// Close every session, flush storage, and shut the C++ holder down.
104 ///
105 /// Named after the TS `delete()` API; there is no Rust destructor work
106 /// behind it. Calling it is useful when you want the storage flushed
107 /// deterministically before the process exits.
108 ///
109 /// Any [`Session`](crate::session::Session) guard still alive is closed
110 /// here; its later `Drop` becomes a no-op. After calling `delete` the
111 /// C++ storage handle has been closed; further operations will fail.
112 pub fn delete(&self) -> Result<(), BeekeeperError> {
113 let mut inner = self.inner.borrow_mut();
114 let tokens: Vec<String> = inner.sessions.drain().collect();
115 for token in tokens {
116 inner.holder.pin_mut().close_session(&token)?;
117 }
118 inner.wallets_meta.clear();
119 inner.holder.pin_mut().sync_storage();
120 inner.holder.pin_mut().close_storage();
121
122 Ok(())
123 }
124
125 /// Reset the inactivity clock to now.
126 ///
127 /// Used internally after every successful unlocked-wallet operation.
128 /// Call manually only if you have some other notion of activity to
129 /// keep the wallet alive.
130 pub fn refresh_timeout(&self) {
131 self.inner.borrow_mut().refresh_timeout();
132 }
133
134 /// If the inactivity timeout has elapsed, return [`BeekeeperError::TimedOut`].
135 /// Otherwise reset the clock.
136 ///
137 /// Every [`UnlockedWallet`](crate::wallet::UnlockedWallet) operation
138 /// calls this as its first step.
139 pub fn throw_if_timed_out_and_refresh(&self) -> Result<(), BeekeeperError> {
140 self.inner.borrow_mut().throw_if_timed_out_and_refresh()
141 }
142
143 /// `true` if the inactivity timeout is enabled and has elapsed.
144 ///
145 /// `unlock_timeout == 0` permanently returns `false`.
146 pub fn is_timed_out(&self) -> bool {
147 self.inner.borrow().is_timed_out()
148 }
149
150 /// Wall-clock instant at which the wallet will auto-lock.
151 ///
152 /// When the timeout is disabled this returns a far-future sentinel:
153 /// the UNIX epoch plus 100 years (≈ year 2069).
154 pub fn get_timeout_time(&self) -> SystemTime {
155 self.inner.borrow().get_timeout_time()
156 }
157
158 /// Names of every wallet found in the storage directory.
159 ///
160 /// Returns `[]` in in-memory mode, since there is nothing to scan. The
161 /// names are derived from filenames by stripping the `.wallet` suffix;
162 /// other files in the directory are ignored.
163 pub fn list_created_wallets(&self) -> Vec<String> {
164 self.inner.borrow().list_created_wallets()
165 }
166
167 /// The crate's SemVer string (compiled-in `CARGO_PKG_VERSION`).
168 pub fn version(&self) -> &'static str {
169 env!("CARGO_PKG_VERSION")
170 }
171}
172
173impl Inner {
174 fn new(options: &BeekeeperOptions) -> Self {
175 let (holder, wallet_dir) = new_holder(options);
176
177 Self {
178 holder,
179 sessions: HashSet::new(),
180 wallets_meta: HashMap::new(),
181 is_in_memory: options.in_memory,
182 unlock_timeout_ms: options.unlock_timeout.saturating_mul(1000),
183 last_activity: Instant::now(),
184 wallet_dir,
185 }
186 }
187
188 /// Record a wallet's metadata under `(token, name)`.
189 pub(crate) fn register_wallet(
190 &mut self,
191 token: &str,
192 name: &str,
193 is_temporary: bool,
194 ) {
195 self.wallets_meta.insert(
196 (token.to_string(), name.to_string()),
197 WalletMeta { is_temporary },
198 );
199 }
200
201 /// Drop the metadata entry recorded by [`register_wallet`](Self::register_wallet).
202 pub(crate) fn unregister_wallet(&mut self, token: &str, name: &str) {
203 self.wallets_meta
204 .remove(&(token.to_string(), name.to_string()));
205 }
206
207 /// Look up whether `(token, name)` was registered as a temporary wallet.
208 pub(crate) fn wallet_is_temporary(&self, token: &str, name: &str) -> bool {
209 self.wallets_meta
210 .get(&(token.to_string(), name.to_string()))
211 .map(|meta| meta.is_temporary)
212 .unwrap_or(false)
213 }
214
215 /// Reset the inactivity clock to now.
216 pub(crate) fn refresh_timeout(&mut self) {
217 self.last_activity = Instant::now();
218 }
219
220 /// If the inactivity timeout has elapsed, return [`BeekeeperError::TimedOut`].
221 /// Otherwise reset the clock.
222 pub(crate) fn throw_if_timed_out_and_refresh(
223 &mut self,
224 ) -> Result<(), BeekeeperError> {
225 if self.is_timed_out() {
226 return Err(BeekeeperError::TimedOut);
227 }
228 self.refresh_timeout();
229
230 Ok(())
231 }
232
233 /// `true` if the inactivity timeout is enabled and has elapsed.
234 pub(crate) fn is_timed_out(&self) -> bool {
235 self.unlock_timeout_ms > 0
236 && self.last_activity.elapsed().as_millis() as u64
237 >= u64::from(self.unlock_timeout_ms)
238 }
239
240 /// Wall-clock instant at which the wallet will auto-lock.
241 pub(crate) fn get_timeout_time(&self) -> SystemTime {
242 if self.unlock_timeout_ms == 0 {
243 return SystemTime::UNIX_EPOCH + NO_TIMEOUT_SENTINEL;
244 }
245 let elapsed = self.last_activity.elapsed();
246 let remaining =
247 Duration::from_millis(u64::from(self.unlock_timeout_ms))
248 .saturating_sub(elapsed);
249
250 SystemTime::now() + remaining
251 }
252
253 /// Names of every wallet found in the storage directory.
254 pub(crate) fn list_created_wallets(&self) -> Vec<String> {
255 if self.is_in_memory {
256 return Vec::new();
257 }
258 let Ok(entries) = fs::read_dir(&self.wallet_dir) else {
259 return Vec::new();
260 };
261 entries
262 .filter_map(|e| e.ok())
263 .filter_map(|e| {
264 e.file_name()
265 .to_str()?
266 .strip_suffix(LEGACY_WALLET_EXT)
267 .map(String::from)
268 })
269 .collect()
270 }
271
272 /// Lock every unlocked wallet in the session and return the (pre-lock)
273 /// holder-side listing.
274 pub(crate) fn lock_session_wallets(
275 &mut self,
276 token: &str,
277 ) -> Result<Vec<ffi::WalletDetails>, BeekeeperError> {
278 let wallets = self.holder.list_wallets(token)?;
279 for wd in wallets.iter().filter(|w| w.unlocked) {
280 self.holder.pin_mut().lock(&wd.name)?;
281 }
282
283 Ok(wallets)
284 }
285
286 /// Close the session identified by `token` on the C++ side and discard
287 /// all Rust-side bookkeeping associated with it.
288 pub(crate) fn close_session(
289 &mut self,
290 token: &str,
291 ) -> Result<(), BeekeeperError> {
292 self.holder.pin_mut().close_session(token)?;
293 self.forget_session(token);
294
295 Ok(())
296 }
297
298 /// Best-effort session teardown used by `Session::drop`: lock the
299 /// session's wallets, then close the session, ignoring errors.
300 ///
301 /// No-op when the session was already closed (e.g. by
302 /// [`BeekeeperApi::delete`]).
303 pub(crate) fn close_session_quietly(&mut self, token: &str) {
304 if !self.session_is_open(token) {
305 return;
306 }
307 let _ = self.lock_session_wallets(token);
308 let _ = self.close_session(token);
309 }
310
311 /// Drop the Rust-side bookkeeping for `token` without touching C++.
312 fn forget_session(&mut self, token: &str) {
313 self.sessions.remove(token);
314 self.wallets_meta.retain(|(t, _), _| t != token);
315 }
316
317 /// `true` while `token` refers to a session that has not been closed yet.
318 fn session_is_open(&self, token: &str) -> bool {
319 self.sessions.contains(token)
320 }
321}
322
323/// Build the C++ holder matching `options`, together with the wallet
324/// directory the persistent backend stores its files in (empty for the
325/// in-memory backend).
326fn new_holder(
327 options: &BeekeeperOptions,
328) -> (UniquePtr<ffi::BeekeeperHolder>, PathBuf) {
329 if options.in_memory {
330 let holder =
331 ffi::new_beekeeper_holder_in_memory(options.unlock_timeout);
332 return (holder, PathBuf::new());
333 }
334
335 let storage = new_rust_storage_protocol(&options.storage_root);
336 let holder = ffi::new_beekeeper_holder(storage, options.unlock_timeout);
337 let wallet_dir = Path::new(&options.storage_root).join(LEGACY_WALLET_DIR);
338
339 (holder, wallet_dir)
340}