Skip to main content

beekeeper/
session.rs

1//! Per-session wallet operations.
2//!
3//! A [`Session`] is an owned guard returned by
4//! [`BeekeeperApi::create_session`](crate::api::BeekeeperApi::create_session);
5//! it closes itself (locking its wallets first) when dropped.
6
7use std::{cell::RefCell, rc::Rc, time::SystemTime};
8
9use crate::{
10    api::Inner,
11    errors::BeekeeperError,
12    wallet::{CreatedWallet, LockedWallet, UnlockedWallet, WalletInfo},
13};
14
15/// Owned guard over one beekeeper session.
16///
17/// Sessions don't own the underlying C++ state — they share it with the
18/// parent [`BeekeeperApi`](crate::api::BeekeeperApi) (and with any wallet
19/// handles), so multiple sessions can be alive at once. Dropping the guard
20/// closes the session; there is no explicit `close` call.
21pub struct Session {
22    inner: Rc<RefCell<Inner>>,
23    token: String,
24    is_temporary: Option<bool>,
25}
26
27/// Snapshot returned by [`Session::get_info`].
28///
29/// `now` is the wall-clock at the moment the call was made; `timeout_time`
30/// is the wall-clock instant at which the wallet manager will auto-lock
31/// (or far-future if the timeout is disabled).
32pub struct SessionInfo {
33    pub now: SystemTime,
34    pub timeout_time: SystemTime,
35}
36
37impl Session {
38    pub(crate) fn new(inner: Rc<RefCell<Inner>>, token: String) -> Self {
39        Self {
40            inner,
41            token,
42            is_temporary: None,
43        }
44    }
45
46    /// Builder-style override for the `is_temporary` flag applied by
47    /// [`create_wallet`](Self::create_wallet).
48    ///
49    /// When never called, wallets default to temporary if and only if the
50    /// beekeeper was opened with
51    /// [`BeekeeperOptions::in_memory`](crate::options::BeekeeperOptions::in_memory).
52    ///
53    /// ```no_run
54    /// # use beekeeper::prelude::*;
55    /// # let bk = BeekeeperApi::new(None);
56    /// let session = bk.create_session().unwrap().is_temporary(true);
57    /// let created = session.create_wallet("scratch", "password").unwrap();
58    /// ```
59    pub fn is_temporary(mut self, is_temporary: bool) -> Self {
60        self.is_temporary = Some(is_temporary);
61        self
62    }
63
64    /// Capture a [`SessionInfo`] snapshot.
65    ///
66    /// Does not mutate the activity clock.
67    pub fn get_info(&self) -> SessionInfo {
68        SessionInfo {
69            now: SystemTime::now(),
70            timeout_time: self.inner.borrow().get_timeout_time(),
71        }
72    }
73
74    /// `true` when a wallet with the given name exists in the underlying
75    /// wallet manager.
76    ///
77    /// The check is process-wide, not session-scoped: any wallet known to
78    /// the wallet manager counts, whether or not this session opened it.
79    pub fn has_wallet(&self, name: &str) -> Result<bool, BeekeeperError> {
80        Ok(self.inner.borrow().holder.has_wallet(name)?)
81    }
82
83    /// All wallets currently opened in this session (locked or unlocked),
84    /// enriched with their `is_temporary` flag.
85    pub fn list_wallets(&self) -> Result<Vec<WalletInfo>, BeekeeperError> {
86        let inner = self.inner.borrow();
87        let details = inner.holder.list_wallets(&self.token)?;
88
89        Ok(details
90            .into_iter()
91            .map(|wd| self.wallet_info(&inner, wd.name, wd.unlocked))
92            .collect())
93    }
94
95    /// All wallets present on disk, opened or not.
96    ///
97    /// Each entry is reported as `unlocked: false`; the `is_temporary` flag
98    /// is filled in from this session's metadata if the wallet was created
99    /// or opened through this session in the past, otherwise defaults to
100    /// `false`.
101    ///
102    /// In in-memory mode this returns an empty vector.
103    pub fn list_created_wallets(&self) -> Vec<WalletInfo> {
104        let inner = self.inner.borrow();
105        inner
106            .list_created_wallets()
107            .into_iter()
108            .map(|name| self.wallet_info(&inner, name, false))
109            .collect()
110    }
111
112    /// Create a brand-new wallet and return it as a [`CreatedWallet`].
113    ///
114    /// `password` accepts anything convertible into `Option<&str>` — pass a
115    /// `&str` directly, or `None` to have the C++ side generate a random
116    /// password, returned in the [`CreatedWallet::password`] field.
117    ///
118    /// Whether the wallet is temporary is controlled by the
119    /// [`is_temporary`](Self::is_temporary) builder; unset, it defaults to
120    /// the beekeeper-wide
121    /// [`BeekeeperOptions::in_memory`](crate::options::BeekeeperOptions::in_memory)
122    /// flag.
123    pub fn create_wallet<'p>(
124        &self,
125        name: &str,
126        password: impl Into<Option<&'p str>>,
127    ) -> Result<CreatedWallet, BeekeeperError> {
128        let password = password.into();
129        let (is_temp, generated_pw) = self.create_on_holder(name, password)?;
130        let wallet = UnlockedWallet::new(
131            Rc::clone(&self.inner),
132            name.to_string(),
133            is_temp,
134        );
135
136        Ok(CreatedWallet {
137            wallet,
138            password: password.map_or(generated_pw, str::to_string),
139        })
140    }
141
142    /// Open an existing wallet and return its [`LockedWallet`] handle.
143    ///
144    /// The wallet is registered with `is_temporary: false` because
145    /// previously-persisted wallets are by definition non-temporary.
146    /// Opening an already-open wallet is a no-op.
147    pub fn open_wallet(
148        &self,
149        name: &str,
150    ) -> Result<LockedWallet, BeekeeperError> {
151        {
152            let mut inner = self.inner.borrow_mut();
153            inner.holder.pin_mut().open_wallet(&self.token, name)?;
154            inner.register_wallet(&self.token, name, false);
155        }
156
157        Ok(LockedWallet::new(
158            Rc::clone(&self.inner),
159            name.to_string(),
160            false,
161        ))
162    }
163
164    /// Close `name` on the C++ side and drop its metadata entry.
165    ///
166    /// This does **not** lock the wallet first — call
167    /// [`UnlockedWallet::lock`](crate::wallet::UnlockedWallet::lock) yourself
168    /// if the wallet is unlocked. The higher-level [`LockedWallet::close`]
169    /// and [`UnlockedWallet::close`](crate::wallet::UnlockedWallet::close)
170    /// methods do the right thing automatically.
171    pub fn close_wallet(&self, name: &str) -> Result<(), BeekeeperError> {
172        let mut inner = self.inner.borrow_mut();
173        inner.holder.pin_mut().close_wallet(name)?;
174        inner.unregister_wallet(&self.token, name);
175
176        Ok(())
177    }
178
179    /// Lock every unlocked wallet in this session and return the resulting
180    /// (post-lock) wallet listing, with every `unlocked` field `false`.
181    ///
182    /// Wallets opened via a different handle of the same session are also
183    /// locked.
184    pub fn lock_all(&self) -> Result<Vec<WalletInfo>, BeekeeperError> {
185        let mut inner = self.inner.borrow_mut();
186        let wallets = inner.lock_session_wallets(&self.token)?;
187
188        Ok(wallets
189            .into_iter()
190            .map(|wd| self.wallet_info(&inner, wd.name, false))
191            .collect())
192    }
193
194    /// Ask the C++ holder to create the wallet and register its metadata.
195    ///
196    /// Returns the applied `is_temporary` flag and the holder-generated
197    /// password (meaningful when the caller passed no password).
198    fn create_on_holder(
199        &self,
200        name: &str,
201        password: Option<&str>,
202    ) -> Result<(bool, String), BeekeeperError> {
203        let mut inner = self.inner.borrow_mut();
204        let is_temp = self.is_temporary.unwrap_or(inner.is_in_memory);
205        let generated_pw = inner.holder.pin_mut().create_wallet(
206            &self.token,
207            name,
208            password.unwrap_or(""),
209            is_temp,
210        )?;
211        inner.register_wallet(&self.token, name, is_temp);
212
213        Ok((is_temp, generated_pw))
214    }
215
216    /// Combine a holder-side listing entry with the Rust-tracked
217    /// `is_temporary` flag.
218    fn wallet_info(
219        &self,
220        inner: &Inner,
221        name: String,
222        unlocked: bool,
223    ) -> WalletInfo {
224        WalletInfo {
225            is_temporary: inner.wallet_is_temporary(&self.token, &name),
226            name,
227            unlocked,
228        }
229    }
230}
231
232/// Locks everything in the session, then closes the session itself.
233///
234/// Errors are ignored: the session may already have been closed by
235/// [`BeekeeperApi::delete`](crate::api::BeekeeperApi::delete), in which
236/// case this is a no-op.
237impl Drop for Session {
238    fn drop(&mut self) {
239        self.inner.borrow_mut().close_session_quietly(&self.token);
240    }
241}