use std::collections::BTreeMap;
use std::sync::Arc;
use smallvec::smallvec;
use crate::db::{CommitDraft, Db};
use crate::entry::{validate_key, Entry, Op, Value};
use crate::error::{Error, Result};
use crate::id::CommitId;
use crate::store::Root;
#[derive(Debug, Clone)]
enum Staged {
Put(Value),
Delete,
}
#[derive(Debug)]
pub struct Txn {
db: Db,
branch: String,
base: CommitId,
base_root: Root,
base_seq: u64,
staged: BTreeMap<String, Staged>,
}
impl Txn {
pub(crate) fn open(db: Db, branch: &str) -> Result<Self> {
let base = db.head(branch)?;
let commit = db.commit(base)?;
Ok(Txn {
db,
branch: branch.to_owned(),
base,
base_root: commit.root.clone(),
base_seq: commit.seq,
staged: BTreeMap::new(),
})
}
pub fn branch(&self) -> &str {
&self.branch
}
pub fn base(&self) -> CommitId {
self.base
}
pub fn is_empty(&self) -> bool {
self.staged.is_empty()
}
pub fn put(&mut self, key: &str, value: Value) -> Result<()> {
validate_key(key)?;
value.validate()?;
self.db.check_dim(value.embedding.as_ref())?;
self.staged.insert(key.to_owned(), Staged::Put(value));
Ok(())
}
pub fn delete(&mut self, key: &str) -> Result<()> {
validate_key(key)?;
self.staged.insert(key.to_owned(), Staged::Delete);
Ok(())
}
pub fn get(&self, key: &str) -> Option<Arc<Entry>> {
match self.staged.get(key) {
Some(Staged::Delete) => None,
Some(Staged::Put(v)) => {
let created = self
.base_root
.get(key)
.map_or(self.base_seq + 1, |e| e.created_seq);
Some(Arc::new(v.clone().into_entry(self.base_seq + 1, created)))
}
None => self.base_root.get(key).cloned(),
}
}
pub fn rollback(self) {
drop(self);
}
pub fn commit(self, message: Option<String>) -> Result<CommitId> {
let seq = self.base_seq + 1;
let mut ops: Vec<Op> = Vec::with_capacity(self.staged.len());
for (key, staged) in &self.staged {
match staged {
Staged::Put(value) => ops.push(Op::Put {
key: key.clone(),
value: value.clone(),
}),
Staged::Delete => {
if self.base_root.get(key).is_some() {
ops.push(Op::Delete { key: key.clone() });
}
}
}
}
if ops.is_empty() {
return Ok(self.base);
}
let mut root = self.base_root.clone();
apply_ops(&mut root, &ops, seq);
self.db.commit_onto(
&self.branch,
self.base,
CommitDraft {
parents: smallvec![self.base],
root,
seq,
message,
ops,
},
)
}
}
pub(crate) fn apply_ops(root: &mut Root, ops: &[Op], seq: u64) {
for op in ops {
match op {
Op::Put { key, value } => {
let created = root.get(key).map_or(seq, |e| e.created_seq);
root.insert_mut(
key.clone(),
Arc::new(value.clone().into_entry(seq, created)),
);
}
Op::Delete { key } | Op::Evict { key } => {
root.remove_mut(key);
}
}
}
}
impl Drop for Txn {
fn drop(&mut self) {
}
}
pub fn with_txn<F>(
db: &Db,
branch: &str,
message: &str,
retries: usize,
mut f: F,
) -> Result<CommitId>
where
F: FnMut(&mut Txn) -> Result<()>,
{
let mut last = None;
for _ in 0..retries.max(1) {
let mut txn = db.begin(branch)?;
f(&mut txn)?;
match txn.commit(Some(message.to_owned())) {
Ok(id) => return Ok(id),
Err(e @ Error::Conflict { .. }) => last = Some(e),
Err(e) => return Err(e),
}
}
Err(last.unwrap_or_else(|| Error::NoSuchBranch(branch.to_owned())))
}