Commit 749c94eb authored by Benjamin Woodruff's avatar Benjamin Woodruff

Some manual cleanup

parent 8d841c64
......@@ -9594,7 +9594,6 @@ dependencies = [
"serde_path_to_error",
"smallvec",
"tempfile",
"thread_local",
"tokio",
"tracing",
"turbo-bincode",
......
......@@ -56,7 +56,6 @@ serde_path_to_error = { workspace = true }
smallvec = { workspace = true }
tokio = { workspace = true }
tracing = { workspace = true }
thread_local = { workspace = true }
turbo-bincode = { workspace = true }
turbo-persistence = { workspace = true }
turbo-rcstr = { workspace = true }
......
......@@ -4,24 +4,22 @@ mod tx_cache;
use std::{fs::create_dir_all, path::Path, thread::available_parallelism};
use anyhow::{Context, Result};
use lmdb::{
Database, DatabaseFlags, Environment, EnvironmentFlags, RwTransaction, Transaction, WriteFlags,
};
use lmdb::{Database, DatabaseFlags, Environment, EnvironmentFlags, Transaction, WriteFlags};
use crate::database::{
key_value_database::{KeySpace, KeyValueDatabase},
lmdb::tx_cache::{ReadTxGuard, TxCache, WriteTxGuard},
lmdb::tx_cache::{RoTransactionGuard, RwTransactionGuard, TxCache},
write_batch::{BaseWriteBatch, SerialWriteBatch, WriteBatch, WriteBuffer},
};
pub struct LmdbValueBuffer<'l> {
ptr: *const u8,
len: usize,
_guard: ReadTxGuard<'l>,
_guard: RoTransactionGuard<'l>,
}
impl<'l> LmdbValueBuffer<'l> {
fn from_raw_parts(ptr: *const u8, len: usize, guard: ReadTxGuard<'l>) -> Self {
fn from_raw_parts(ptr: *const u8, len: usize, guard: RoTransactionGuard<'l>) -> Self {
Self {
ptr,
len,
......@@ -93,12 +91,12 @@ impl LmbdKeyValueDatabase {
}
}
fn get_read_tx(&self) -> ReadTxGuard<'_> {
fn get_read_tx(&self) -> RoTransactionGuard<'_> {
self.tx_cache.get_read_tx()
}
fn begin_write(&self) -> WriteTxGuard<'_> {
self.tx_cache.begin_write(&self.env)
fn get_write_tx(&self) -> Result<RwTransactionGuard<'_>> {
self.tx_cache.get_write_tx(&self.env)
}
fn get_from_tx<'tx>(
......@@ -108,7 +106,7 @@ impl LmbdKeyValueDatabase {
) -> Result<Option<&'tx [u8]>> {
match extended_key::get(tx, db, key) {
Ok(result) => Ok(Some(result)),
Err(err) if err == lmdb::Error::NotFound => Ok(None),
Err(lmdb::Error::NotFound) => Ok(None),
Err(err) => Err(err.into()),
}
}
......@@ -154,18 +152,15 @@ impl KeyValueDatabase for LmbdKeyValueDatabase {
fn write_batch(
&self,
) -> Result<WriteBatch<'_, Self::SerialWriteBatch<'_>, Self::ConcurrentWriteBatch<'_>>> {
let write_guard = self.begin_write();
Ok(WriteBatch::serial(LmbdWriteBatch {
tx: self.env.begin_rw_txn()?,
_write_guard: Some(write_guard),
write_tx_guard: self.get_write_tx()?,
this: self,
}))
}
}
pub struct LmbdWriteBatch<'l> {
tx: RwTransaction<'l>,
_write_guard: Option<WriteTxGuard<'l>>,
write_tx_guard: RwTransactionGuard<'l>,
this: &'l LmbdKeyValueDatabase,
}
......@@ -180,21 +175,12 @@ impl<'a> BaseWriteBatch<'a> for LmbdWriteBatch<'a> {
where
'a: 'l,
{
LmbdKeyValueDatabase::get_from_tx(&self.tx, self.this.db(key_space), key)
LmbdKeyValueDatabase::get_from_tx(&*self.write_tx_guard, self.this.db(key_space), key)
}
fn commit(self) -> Result<()> {
let Self {
tx,
mut _write_guard,
..
} = self;
tx.commit()?;
_write_guard
.take()
.expect("write guard is always present")
.commit();
Ok(())
let Self { write_tx_guard, .. } = self;
write_tx_guard.commit()
}
}
......@@ -206,7 +192,7 @@ impl<'a> SerialWriteBatch<'a> for LmbdWriteBatch<'a> {
value: WriteBuffer<'_>,
) -> Result<()> {
extended_key::put(
&mut self.tx,
&mut self.write_tx_guard,
self.this.db(key_space),
&key,
&value,
......@@ -217,7 +203,7 @@ impl<'a> SerialWriteBatch<'a> for LmbdWriteBatch<'a> {
fn delete(&mut self, key_space: KeySpace, key: WriteBuffer<'_>) -> Result<()> {
extended_key::delete(
&mut self.tx,
&mut self.write_tx_guard,
self.this.db(key_space),
&key,
WriteFlags::empty(),
......
use std::{
mem::transmute,
ops::Deref,
ops::{Deref, DerefMut},
rc::Rc,
sync::{
Arc, Mutex, PoisonError, RwLock, RwLockWriteGuard,
atomic::{AtomicU64, Ordering},
......@@ -8,7 +9,8 @@ use std::{
},
};
use lmdb::{Environment, RoTransaction};
use anyhow::Result;
use lmdb::{Environment, RoTransaction, RwTransaction, Transaction};
pub struct SendRoTransaction<'tx> {
tx: RoTransaction<'tx>,
......@@ -58,13 +60,14 @@ impl QueueState {
}
}
struct ReadTxGuardInner<'db> {
struct RoTransactionGuardInner<'db> {
// Option<> is so that the Drop impl can take ownership of the transaction
lease: Option<SendRoTransaction<'db>>,
sender: SyncSender<SendRoTransaction<'static>>,
generation: &'db AtomicU64,
}
impl Drop for ReadTxGuardInner<'_> {
impl Drop for RoTransactionGuardInner<'_> {
fn drop(&mut self) {
let Some(lease) = self.lease.take() else {
return;
......@@ -82,46 +85,59 @@ impl Drop for ReadTxGuardInner<'_> {
}
#[derive(Clone)]
pub struct ReadTxGuard<'db> {
inner: Arc<ReadTxGuardInner<'db>>,
pub struct RoTransactionGuard<'db> {
inner: Rc<RoTransactionGuardInner<'db>>,
}
impl<'db> Deref for ReadTxGuard<'db> {
impl<'db> Deref for RoTransactionGuard<'db> {
type Target = SendRoTransaction<'db>;
fn deref(&self) -> &Self::Target {
self.inner
.lease
.as_ref()
.expect("read transaction lease is always present")
self.inner.lease.as_ref().unwrap()
}
}
pub struct WriteTxGuard<'db> {
env: &'db Environment,
generation: u64,
capacity: usize,
queue: Option<RwLockWriteGuard<'db, QueueState>>,
pub struct RwTransactionGuard<'db> {
tx: RwTransaction<'db>,
_queue_guard: RebuildQueueOnDrop<'db>,
}
impl WriteTxGuard<'_> {
fn rebuild_queue(&mut self) {
if let Some(queue) = self.queue.as_mut() {
**queue = QueueState::new(self.env, self.capacity, self.generation);
}
impl<'db> Deref for RwTransactionGuard<'db> {
type Target = RwTransaction<'db>;
fn deref(&self) -> &Self::Target {
&self.tx
}
}
impl DerefMut for RwTransactionGuard<'_> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.tx
}
}
pub fn commit(mut self) {
self.rebuild_queue();
self.queue = None;
impl RwTransactionGuard<'_> {
// We can't use the method provided by Deref<Target = RwTransaction<'_>> here because this
// consumes the guard
pub fn commit(self) -> Result<()> {
self.tx.commit()?;
Ok(())
}
}
impl Drop for WriteTxGuard<'_> {
struct RebuildQueueOnDrop<'db> {
queue: RwLockWriteGuard<'db, QueueState>,
env: &'db Environment,
generation: u64,
capacity: usize,
}
impl Drop for RebuildQueueOnDrop<'_> {
fn drop(&mut self) {
if self.queue.is_some() {
self.rebuild_queue();
}
// We might avoid some allocation overhead if we used RoTransaction::reset and
// InactiveTransaction::renew, but we don't care much about perf here.
// https://docs.rs/lmdb/latest/lmdb/struct.RoTransaction.html#method.reset
*self.queue = QueueState::new(self.env, self.capacity, self.generation);
}
}
......@@ -140,20 +156,24 @@ impl TxCache {
}
}
pub fn begin_write<'db>(&'db self, env: &'db Environment) -> WriteTxGuard<'db> {
pub fn get_write_tx<'db>(&'db self, env: &'db Environment) -> Result<RwTransactionGuard<'db>> {
let generation = self.generation.fetch_add(1, Ordering::AcqRel) + 1;
let queue = self.queue.write().unwrap_or_else(PoisonError::into_inner);
WriteTxGuard {
env,
generation,
capacity: self.capacity,
queue: Some(queue),
}
let tx = env.begin_rw_txn()?;
Ok(RwTransactionGuard {
tx,
_queue_guard: RebuildQueueOnDrop {
queue,
env,
generation,
capacity: self.capacity,
},
})
}
/// NOTE: Callers should avoid acquiring multiple guards at once. If a single thread tries to
/// acquire more than `capacity` read transactions, it could deadlock.
pub fn get_read_tx<'db>(&'db self) -> ReadTxGuard<'db> {
pub fn get_read_tx<'db>(&'db self) -> RoTransactionGuard<'db> {
loop {
let (sender, receiver) = {
let queue = self.queue.read().unwrap_or_else(PoisonError::into_inner);
......@@ -177,8 +197,8 @@ impl TxCache {
let lease =
unsafe { transmute::<SendRoTransaction<'static>, SendRoTransaction<'db>>(lease) };
return ReadTxGuard {
inner: Arc::new(ReadTxGuardInner {
return RoTransactionGuard {
inner: Rc::new(RoTransactionGuardInner {
lease: Some(lease),
sender,
generation: &self.generation,
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment