use std::{
cell::RefCell,
collections::{HashMap, HashSet},
fs,
path::{Path, PathBuf},
rc::Rc,
time::{Duration, Instant, SystemTime},
};
use cxx::UniquePtr;
use crate::{
consts::{LEGACY_WALLET_DIR, LEGACY_WALLET_EXT},
errors::BeekeeperError,
ffi, new_rust_storage_protocol,
options::BeekeeperOptions,
session::Session,
};
const NO_TIMEOUT_SENTINEL: Duration =
Duration::from_secs(60 * 60 * 24 * 365 * 100);
pub struct BeekeeperApi {
pub(crate) inner: Rc<RefCell<Inner>>,
}
pub(crate) struct Inner {
pub(crate) holder: UniquePtr<ffi::BeekeeperHolder>,
sessions: HashSet<String>,
wallets_meta: HashMap<(String, String), WalletMeta>,
pub(crate) is_in_memory: bool,
unlock_timeout_ms: u32,
last_activity: Instant,
wallet_dir: PathBuf,
}
#[derive(Clone, Copy)]
pub(crate) struct WalletMeta {
pub is_temporary: bool,
}
impl BeekeeperApi {
pub fn new(options: impl Into<Option<BeekeeperOptions>>) -> Self {
let options = options.into().unwrap_or_default();
let inner = Inner::new(&options);
Self {
inner: Rc::new(RefCell::new(inner)),
}
}
pub fn create_session(&self) -> Result<Session, BeekeeperError> {
let token = {
let mut inner = self.inner.borrow_mut();
let token = inner.holder.pin_mut().create_session()?;
inner.sessions.insert(token.clone());
token
};
Ok(Session::new(Rc::clone(&self.inner), token))
}
pub fn delete(&self) -> Result<(), BeekeeperError> {
let mut inner = self.inner.borrow_mut();
let tokens: Vec<String> = inner.sessions.drain().collect();
for token in tokens {
inner.holder.pin_mut().close_session(&token)?;
}
inner.wallets_meta.clear();
inner.holder.pin_mut().sync_storage();
inner.holder.pin_mut().close_storage();
Ok(())
}
pub fn refresh_timeout(&self) {
self.inner.borrow_mut().refresh_timeout();
}
pub fn throw_if_timed_out_and_refresh(&self) -> Result<(), BeekeeperError> {
self.inner.borrow_mut().throw_if_timed_out_and_refresh()
}
pub fn is_timed_out(&self) -> bool {
self.inner.borrow().is_timed_out()
}
pub fn get_timeout_time(&self) -> SystemTime {
self.inner.borrow().get_timeout_time()
}
pub fn list_created_wallets(&self) -> Vec<String> {
self.inner.borrow().list_created_wallets()
}
pub fn version(&self) -> &'static str {
env!("CARGO_PKG_VERSION")
}
}
impl Inner {
fn new(options: &BeekeeperOptions) -> Self {
let (holder, wallet_dir) = new_holder(options);
Self {
holder,
sessions: HashSet::new(),
wallets_meta: HashMap::new(),
is_in_memory: options.in_memory,
unlock_timeout_ms: options.unlock_timeout.saturating_mul(1000),
last_activity: Instant::now(),
wallet_dir,
}
}
pub(crate) fn register_wallet(
&mut self,
token: &str,
name: &str,
is_temporary: bool,
) {
self.wallets_meta.insert(
(token.to_string(), name.to_string()),
WalletMeta { is_temporary },
);
}
pub(crate) fn unregister_wallet(&mut self, token: &str, name: &str) {
self.wallets_meta
.remove(&(token.to_string(), name.to_string()));
}
pub(crate) fn wallet_is_temporary(&self, token: &str, name: &str) -> bool {
self.wallets_meta
.get(&(token.to_string(), name.to_string()))
.map(|meta| meta.is_temporary)
.unwrap_or(false)
}
pub(crate) fn refresh_timeout(&mut self) {
self.last_activity = Instant::now();
}
pub(crate) fn throw_if_timed_out_and_refresh(
&mut self,
) -> Result<(), BeekeeperError> {
if self.is_timed_out() {
return Err(BeekeeperError::TimedOut);
}
self.refresh_timeout();
Ok(())
}
pub(crate) fn is_timed_out(&self) -> bool {
self.unlock_timeout_ms > 0
&& self.last_activity.elapsed().as_millis() as u64
>= u64::from(self.unlock_timeout_ms)
}
pub(crate) fn get_timeout_time(&self) -> SystemTime {
if self.unlock_timeout_ms == 0 {
return SystemTime::UNIX_EPOCH + NO_TIMEOUT_SENTINEL;
}
let elapsed = self.last_activity.elapsed();
let remaining =
Duration::from_millis(u64::from(self.unlock_timeout_ms))
.saturating_sub(elapsed);
SystemTime::now() + remaining
}
pub(crate) fn list_created_wallets(&self) -> Vec<String> {
if self.is_in_memory {
return Vec::new();
}
let Ok(entries) = fs::read_dir(&self.wallet_dir) else {
return Vec::new();
};
entries
.filter_map(|e| e.ok())
.filter_map(|e| {
e.file_name()
.to_str()?
.strip_suffix(LEGACY_WALLET_EXT)
.map(String::from)
})
.collect()
}
pub(crate) fn lock_session_wallets(
&mut self,
token: &str,
) -> Result<Vec<ffi::WalletDetails>, BeekeeperError> {
let wallets = self.holder.list_wallets(token)?;
for wd in wallets.iter().filter(|w| w.unlocked) {
self.holder.pin_mut().lock(&wd.name)?;
}
Ok(wallets)
}
pub(crate) fn close_session(
&mut self,
token: &str,
) -> Result<(), BeekeeperError> {
self.holder.pin_mut().close_session(token)?;
self.forget_session(token);
Ok(())
}
pub(crate) fn close_session_quietly(&mut self, token: &str) {
if !self.session_is_open(token) {
return;
}
let _ = self.lock_session_wallets(token);
let _ = self.close_session(token);
}
fn forget_session(&mut self, token: &str) {
self.sessions.remove(token);
self.wallets_meta.retain(|(t, _), _| t != token);
}
fn session_is_open(&self, token: &str) -> bool {
self.sessions.contains(token)
}
}
fn new_holder(
options: &BeekeeperOptions,
) -> (UniquePtr<ffi::BeekeeperHolder>, PathBuf) {
if options.in_memory {
let holder =
ffi::new_beekeeper_holder_in_memory(options.unlock_timeout);
return (holder, PathBuf::new());
}
let storage = new_rust_storage_protocol(&options.storage_root);
let holder = ffi::new_beekeeper_holder(storage, options.unlock_timeout);
let wallet_dir = Path::new(&options.storage_root).join(LEGACY_WALLET_DIR);
(holder, wallet_dir)
}