mysql_replication/engine/
transaction.rs1use crate::{Change, Error, OwnedChange, Result, engine::checkpoint::State};
2use std::path::Path;
3
4pub struct TransactionBuffer {
8 changes: Vec<OwnedChange>,
9 bytes: usize,
10 limit: usize,
11 active: bool,
12}
13impl TransactionBuffer {
14 pub fn new(limit: usize) -> Self {
15 Self {
16 changes: Vec::new(),
17 bytes: 0,
18 limit,
19 active: false,
20 }
21 }
22 pub fn begin(&mut self) -> Result<()> {
23 if self.active {
24 return Err(crate::error::invalid(
25 "nested transaction / incomplete start position",
26 ));
27 }
28 self.active = true;
29 Ok(())
30 }
31 pub fn is_active(&self) -> bool {
32 self.active
33 }
34 pub fn push(&mut self, change: Change<'_>) -> Result<()> {
35 if !self.active {
36 return Err(crate::error::invalid(
37 "row outside BEGIN; start at a transaction boundary",
38 ));
39 }
40 let owned = change.into_owned();
41 let bytes = owned.memory_bytes();
42 let total = self
43 .bytes
44 .checked_add(bytes)
45 .ok_or(Error::TransactionLimit(self.limit))?;
46 let size = std::mem::size_of::<OwnedChange>();
47 let mut capacity = self.changes.capacity();
48 if self.changes.len() == capacity {
49 let maximum =
50 (self.limit.saturating_sub(total) / size).saturating_add(self.changes.len() + 1);
51 capacity = capacity.saturating_mul(2).max(8).min(maximum);
52 }
53 let unused_capacity = capacity
54 .saturating_sub(self.changes.len() + 1)
55 .saturating_mul(size);
56 if total.saturating_add(unused_capacity) > self.limit {
57 return Err(Error::TransactionLimit(self.limit));
58 }
59 if capacity > self.changes.capacity() {
60 self.changes.reserve_exact(capacity - self.changes.len());
61 }
62 self.changes.push(owned);
63 self.bytes = total;
64 Ok(())
65 }
66 pub fn rollback(&mut self) {
67 self.changes.clear();
68 self.bytes = 0;
69 self.active = false;
70 }
71 pub fn commit_with(
72 &mut self,
73 state: &State,
74 state_path: Option<&Path>,
75 emit: impl FnOnce(&[OwnedChange]) -> Result<()>,
76 ) -> Result<()> {
77 if !self.active {
78 return Err(crate::error::invalid("commit outside BEGIN"));
79 }
80 emit(&self.changes)?;
81 if let Some(path) = state_path {
82 state.save(path)?;
83 }
84 self.rollback();
85 Ok(())
86 }
87}