use crate::{
Config, Connection, Error, IntegrityReport, MemoryDeleteScope, MemoryDocument, MemorySearch,
MemorySearchResponse, Result, Row, Value,
};
use parking_lot::{Condvar, Mutex};
use std::{path::Path, sync::Arc};
use web_time::{Duration, Instant};
struct State {
connection: Option<Connection>,
owner: Option<u64>,
next_id: u64,
poisoned: bool,
}
struct Shared {
state: Mutex<State>,
changed: Condvar,
}
#[derive(Clone)]
pub struct SessionDatabase {
shared: Arc<Shared>,
}
impl SessionDatabase {
pub fn open(path: impl AsRef<Path>) -> Result<Self> {
Self::open_with_config(path, Config::default())
}
pub fn open_with_config(path: impl AsRef<Path>, config: Config) -> Result<Self> {
Self::from_connection(Connection::open_with_config(path, config)?)
}
pub fn open_in_memory() -> Result<Self> {
Self::open_in_memory_with_config(Config::default())
}
pub fn open_in_memory_with_config(config: Config) -> Result<Self> {
Self::from_connection(Connection::open_in_memory_with_config(config)?)
}
fn from_connection(connection: Connection) -> Result<Self> {
Ok(Self {
shared: Arc::new(Shared {
state: Mutex::new(State {
connection: Some(connection),
owner: None,
next_id: 1,
poisoned: false,
}),
changed: Condvar::new(),
}),
})
}
pub fn session(&self) -> Result<Session> {
self.session_with_timeout(Duration::ZERO)
}
pub fn session_with_timeout(&self, busy_timeout: Duration) -> Result<Session> {
let mut state = self.shared.state.lock();
if state.connection.is_none() {
return Err(Error::TransactionError("Session database is closed".into()));
}
let id = state.next_id;
state.next_id = id
.checked_add(1)
.ok_or_else(|| Error::ConstraintViolation("Session ID space exhausted".into()))?;
Ok(Session {
handle: Arc::new(SessionHandle {
shared: self.shared.clone(),
id,
busy_timeout,
closed: Mutex::new(false),
}),
})
}
pub fn close(&self) -> Result<()> {
let mut state = self.shared.state.lock();
if state.owner.is_some() {
return Err(Error::Busy("An active session owns a transaction".into()));
}
if let Some(connection) = &state.connection {
connection.close()?;
}
state.connection.take();
self.shared.changed.notify_all();
Ok(())
}
}
struct SessionHandle {
shared: Arc<Shared>,
id: u64,
busy_timeout: Duration,
closed: Mutex<bool>,
}
#[derive(Clone)]
pub struct Session {
handle: Arc<SessionHandle>,
}
struct TransactionGuard<'a> {
session: &'a Session,
armed: bool,
}
impl Drop for TransactionGuard<'_> {
fn drop(&mut self) {
if self.armed {
let _ = self.session.rollback();
}
}
}
impl Session {
fn access<T>(&self, operation: impl FnOnce(&Connection) -> Result<T>) -> Result<T> {
let started = Instant::now();
let shared = &self.handle.shared;
let mut state = shared.state.lock();
loop {
if *self.handle.closed.lock() {
return Err(Error::TransactionError("Session is closed".into()));
}
if state.poisoned {
return Err(Error::TransactionError(
"Session storage requires reopen after failed rollback".into(),
));
}
if state.connection.is_none() {
return Err(Error::TransactionError("Session database is closed".into()));
}
if state.owner.is_none_or(|owner| owner == self.handle.id) {
break;
}
let remaining = self.handle.busy_timeout.saturating_sub(started.elapsed());
if remaining.is_zero() || cfg!(target_arch = "wasm32") {
return Err(Error::Busy(
"Another session owns the active transaction".into(),
));
}
shared.changed.wait_for(&mut state, remaining);
}
let connection = state.connection.as_ref().expect("open session database");
let result = operation(connection);
state.owner = if connection.is_in_transaction() {
Some(self.handle.id)
} else {
None
};
if state.owner.is_none() {
shared.changed.notify_all();
}
result
}
pub fn execute(&self, sql: &str) -> Result<usize> {
self.execute_with_params(sql, &[])
}
pub fn execute_with_params(&self, sql: &str, values: &[Value]) -> Result<usize> {
self.access(|connection| connection.execute_with_params(sql, values))
}
pub fn query(&self, sql: &str) -> Result<Vec<Row>> {
self.query_with_params(sql, &[])
}
pub fn query_with_params(&self, sql: &str, values: &[Value]) -> Result<Vec<Row>> {
self.access(|connection| connection.query_with_params(sql, values))
}
pub fn begin(&self) -> Result<()> {
self.execute("BEGIN").map(|_| ())
}
pub fn commit(&self) -> Result<()> {
self.execute("COMMIT").map(|_| ())
}
pub fn rollback(&self) -> Result<()> {
self.execute("ROLLBACK").map(|_| ())
}
pub fn transaction<T>(&self, callback: impl FnOnce(&Session) -> Result<T>) -> Result<T> {
self.begin()?;
let mut guard = TransactionGuard {
session: self,
armed: true,
};
match callback(self) {
Ok(value) => {
self.commit()?;
guard.armed = false;
Ok(value)
}
Err(error) => {
self.rollback().map_err(|rollback| {
Error::TransactionError(format!("{error}; rollback also failed: {rollback}"))
})?;
guard.armed = false;
Err(error)
}
}
}
pub fn store_memory(&self, document: &MemoryDocument) -> Result<u64> {
self.access(|connection| connection.store_memory(document))
}
pub fn upsert_memory(&self, document: &MemoryDocument) -> Result<u64> {
self.access(|connection| connection.upsert_memory(document))
}
pub fn upsert_memory_batch(&self, documents: &[MemoryDocument]) -> Result<Vec<u64>> {
self.access(|connection| connection.upsert_memory_batch(documents))
}
pub fn delete_memories(&self, scope: &MemoryDeleteScope) -> Result<usize> {
self.access(|connection| connection.delete_memories(scope))
}
pub fn search_memories(&self, search: &MemorySearch) -> Result<MemorySearchResponse> {
self.access(|connection| connection.search_memories_detailed(search))
}
pub fn memory_request_json(&self, operation: &str, payload: &str) -> Result<String> {
self.access(|connection| connection.memory_request_json(operation, payload))
}
pub fn checkpoint(&self) -> Result<usize> {
self.access(Connection::checkpoint)
}
pub fn backup(&self, path: impl AsRef<Path>) -> Result<u32> {
self.access(|connection| connection.backup(path))
}
pub fn integrity_check(&self) -> Result<IntegrityReport> {
self.access(Connection::check_integrity)
}
pub fn close(&self) -> Result<()> {
let shared = &self.handle.shared;
let mut state = shared.state.lock();
let mut closed = self.handle.closed.lock();
if *closed {
return Ok(());
}
if state.owner == Some(self.handle.id) {
if let Some(connection) = &state.connection {
connection.rollback()?;
}
state.owner = None;
shared.changed.notify_all();
}
*closed = true;
Ok(())
}
}
impl Drop for SessionHandle {
fn drop(&mut self) {
let mut state = self.shared.state.lock();
if state.owner == Some(self.id) {
if let Some(connection) = &state.connection {
if connection.rollback().is_err() {
state.poisoned = true;
}
}
state.owner = None;
self.shared.changed.notify_all();
}
}
}