Skip to main content

lockbook_server_lib/
guard.rs

1use db_rs::View;
2use db_rs::errors::Result;
3use db_rs::guard::WriteTx;
4use std::ops::{Deref, DerefMut};
5
6use crate::schema::{ServerDb, ServerV6};
7
8#[must_use]
9pub struct ServerTx<'a> {
10    db: &'a mut ServerDb,
11    tx: Option<WriteTx>,
12}
13
14impl<'a> ServerTx<'a> {
15    pub fn begin(db: &'a mut ServerDb) -> Result<Self> {
16        let tx = db.write_tx()?;
17        if let Some(bytes) = db.log_mut().take_incomplete_write() {
18            tracing::error!(bytes, "discarded an incomplete database write");
19        }
20        Ok(Self { db, tx: Some(tx) })
21    }
22
23    pub fn end(mut self) -> Result<()> {
24        self.tx.take().unwrap().end_tx(self.db).map(|_| ())
25    }
26}
27
28impl Deref for ServerTx<'_> {
29    type Target = ServerV6;
30
31    fn deref(&self) -> &Self::Target {
32        &self.db.schema
33    }
34}
35
36impl DerefMut for ServerTx<'_> {
37    fn deref_mut(&mut self) -> &mut Self::Target {
38        &mut self.db.schema
39    }
40}
41
42impl Drop for ServerTx<'_> {
43    fn drop(&mut self) {
44        if let Some(tx) = self.tx.take() {
45            if let Err(error) = tx.end_tx(self.db) {
46                tracing::error!(?error, "failed to flush database transaction on drop");
47            }
48        }
49    }
50}