Skip to main content

link_cli/engine/
transaction.rs

1use super::{
2    error, validation::ReadSet, Engine, IsolationLevel, Row, Rows, SerializableValidation,
3    Snapshot, State,
4};
5use crate::{GenericLink, LinkError, LinksStorage, TransitionLogStore};
6use doublets::data::LinkReference;
7use std::{collections::BTreeMap, sync::Mutex};
8
9/// Private writes by address; `None` removes the row.
10pub(super) type StagedWrites<T> = BTreeMap<T, Option<Row<T>>>;
11
12/// An isolated write set with the same raw LinksStorage API as other backends.
13/// Dropping or rolling back discards the write set; allocation may leave gaps.
14pub struct EngineTransaction<T: LinkReference, L: TransitionLogStore> {
15    pub(super) engine: Engine<T, L>,
16    pub(super) base: Snapshot<T>,
17    pub(super) writes: StagedWrites<T>,
18    pub(super) savepoints: Vec<(u64, StagedWrites<T>)>,
19    pub(super) reserved: std::collections::VecDeque<T>,
20    pub(super) closed: bool,
21    pub(super) isolation: IsolationLevel,
22    pub(super) reads: Option<Mutex<ReadSet<T>>>,
23    pub(super) locks: Option<super::pessimistic::WriteLocks<T>>,
24}
25impl<T: LinkReference, L: TransitionLogStore> EngineTransaction<T, L> {
26    pub(super) fn check_open(&self) -> Result<(), LinkError> {
27        if self.closed {
28            Err(error("transaction is closed"))
29        } else {
30            Ok(())
31        }
32    }
33    fn acquire_write(&mut self, id: T) -> Result<(), LinkError> {
34        if let Some(locks) = &mut self.locks {
35            let state = self.engine.lock()?;
36            let mut state = locks.wait_turn(state, id)?;
37            locks.acquire(&mut state, id, self.base.revision)?;
38        }
39        Ok(())
40    }
41    /// Reads a link and reserves its address for this session, like SQL
42    /// `SELECT ... FOR UPDATE`. Another session's write or lock of the address
43    /// is then refused (or waits, with `lock_wait`) until this session ends, so
44    /// a read-modify-write cannot be overtaken. A missing address is reserved
45    /// too, which keeps other sessions from creating it. Refused with `busy`
46    /// while another session owns the address, and with `conflict` when the
47    /// link changed after this session began. Needs pessimistic concurrency.
48    pub fn lock_for_update(&mut self, id: T) -> Result<Option<GenericLink<T>>, LinkError> {
49        self.check_open()?;
50        if self.locks.is_none() {
51            return Err(error("lock for update requires pessimistic concurrency"));
52        }
53        self.acquire_write(id)?;
54        Ok(self.row(id).map(|row| row.link))
55    }
56    /// Identifies this session's write ownership while it lasts. `None` unless
57    /// the engine selected pessimistic concurrency.
58    pub fn write_owner(&self) -> Option<u64> {
59        self.locks.as_ref().map(|locks| locks.token() as u64)
60    }
61    /// The owner that refused this session's last write, once. Lets a caller that
62    /// cannot block, such as JavaScript on one thread, wait and detect cycles itself.
63    pub fn take_write_blocker(&mut self) -> Option<u64> {
64        self.locks
65            .as_mut()?
66            .take_blocker()
67            .map(|owner| owner as u64)
68    }
69    fn row(&self, id: T) -> Option<Row<T>> {
70        if !self.closed {
71            if let Some(reads) = &self.reads {
72                reads
73                    .lock()
74                    .expect("read-set mutex poisoned")
75                    .keys
76                    .insert(id);
77            }
78        }
79        if let Some(row) = self.writes.get(&id) {
80            return row.clone();
81        }
82        if self.isolation == IsolationLevel::ReadCommitted && !self.closed {
83            return self
84                .engine
85                .state
86                .lock()
87                .ok()?
88                .current
89                .rows
90                .get(&id)
91                .cloned();
92        }
93        self.base.rows.get(&id).cloned()
94    }
95    fn view(&self) -> Rows<T> {
96        if !self.closed {
97            if let Some(reads) = &self.reads {
98                reads.lock().expect("read-set mutex poisoned").scanned = true;
99            }
100        }
101        let mut rows = if self.isolation == IsolationLevel::ReadCommitted && !self.closed {
102            self.engine
103                .state
104                .lock()
105                .expect("engine mutex poisoned")
106                .current
107                .rows
108                .as_ref()
109                .clone()
110        } else {
111            self.base.rows.as_ref().clone()
112        };
113        for (id, row) in &self.writes {
114            match row {
115                Some(row) => {
116                    rows.insert(*id, row.clone());
117                }
118                None => {
119                    rows.remove(id);
120                }
121            }
122        }
123        rows
124    }
125    pub fn get_name(&self, id: T) -> Option<String> {
126        self.row(id).and_then(|row| row.name)
127    }
128    pub fn set_name(&mut self, id: T, name: Option<String>) -> Result<(), LinkError> {
129        self.check_open()?;
130        let mut row = self.row(id).ok_or_else(|| LinkError::not_found(id))?;
131        self.acquire_write(id)?;
132        row.name = name;
133        self.writes.insert(id, Some(row));
134        Ok(())
135    }
136    pub fn get_by_name(&self, name: &str) -> Option<T> {
137        self.view()
138            .values()
139            .find(|row| row.name.as_deref() == Some(name))
140            .map(|row| row.link.index)
141    }
142    pub fn rollback(&mut self) {
143        if !self.closed {
144            let mut state = self
145                .engine
146                .state
147                .lock()
148                .unwrap_or_else(|poison| poison.into_inner());
149            state.active -= 1;
150            if let Some(mut locks) = self.locks.take() {
151                locks.release(&mut state);
152            }
153            if state.active == 0 {
154                state.changed.clear();
155            }
156            self.closed = true;
157            self.writes.clear();
158            self.savepoints.clear();
159            self.reserved.clear();
160            self.reads.take();
161        }
162    }
163    pub fn commit(&mut self) -> Result<u64, LinkError> {
164        self.check_open()?;
165        let engine = self.engine.clone();
166        let mut state = match engine.lock() {
167            Ok(state) => state,
168            Err(cause) => {
169                self.rollback();
170                return Err(cause);
171            }
172        };
173        self.commit_locked(&mut state)
174    }
175
176    // Group preparation uses the same validation against private tentative
177    // state, with a memory journal instead of the engine's physical log.
178    pub(super) fn commit_locked<M: TransitionLogStore>(
179        &mut self,
180        state: &mut State<T, M>,
181    ) -> Result<u64, LinkError> {
182        self.check_open()?;
183        // Every commit attempt ends this session, including conflicts/failures.
184        state.active -= 1;
185        self.closed = true;
186        self.savepoints.clear();
187        self.reserved.clear();
188        // Publication holds this mutex until completion, so no writer can
189        // acquire released addresses yet. Release before fallible callbacks
190        // also avoids retaining ownership if a custom log panics.
191        if let Some(mut locks) = self.locks.take() {
192            locks.release(state);
193        }
194        let writes = std::mem::take(&mut self.writes);
195        let reads = self.reads.take().map(Mutex::into_inner);
196        let result = (|| {
197            let reads = reads
198                .transpose()
199                .map_err(|_| error("read-set mutex poisoned"))?;
200            if self.isolation == IsolationLevel::Serializable
201                && (state.options.serializable_validation == SerializableValidation::Revision
202                    || reads.as_ref().is_some_and(|reads| reads.scanned))
203                && state.current.revision != self.base.revision
204            {
205                return Err(error(
206                    "conflict: database revision changed (serializable validation)",
207                ));
208            }
209            if reads.as_ref().is_some_and(|reads| {
210                reads.keys.iter().any(|id| {
211                    state
212                        .changed
213                        .get(id)
214                        .is_some_and(|revision| *revision > self.base.revision)
215                })
216            }) {
217                return Err(error("conflict: a read link changed since begin"));
218            }
219            if writes.keys().any(|id| {
220                state
221                    .changed
222                    .get(id)
223                    .is_some_and(|revision| *revision > self.base.revision)
224            }) {
225                return Err(error("conflict: a written link changed since begin"));
226            }
227            if writes.is_empty() {
228                return Ok(state.current.revision);
229            }
230            let mut rows = state.current.rows.as_ref().clone();
231            for (id, row) in &writes {
232                match row {
233                    Some(row) => {
234                        rows.insert(*id, row.clone());
235                    }
236                    None => {
237                        rows.remove(id);
238                    }
239                }
240            }
241            self.base = state.publish(rows, writes.keys().copied())?;
242            self.writes.clear();
243            Ok(self.base.revision)
244        })();
245        // Validate the last committer before reclaiming generations: otherwise
246        // an intervening delete/recreate could be mistaken for an unchanged row.
247        if state.active == 0 {
248            state.changed.clear();
249        }
250        result
251    }
252}
253impl<T: LinkReference, L: TransitionLogStore> Drop for EngineTransaction<T, L> {
254    fn drop(&mut self) {
255        self.rollback();
256    }
257}
258
259impl<T: LinkReference, L: TransitionLogStore> LinksStorage<T> for EngineTransaction<T, L> {
260    fn create_link(&mut self, source: T, target: T) -> Result<T, LinkError> {
261        self.check_open()?;
262        let id = {
263            let mut state = self.engine.lock()?;
264            // A fresh address has no owner; a reserved one may have been picked explicitly.
265            if let (Some(locks), Some(id)) = (&mut self.locks, self.reserved.front().copied()) {
266                state = locks.wait_turn(state, id)?;
267            }
268            let (id, next) = if let Some(id) = self.reserved.front().copied() {
269                (id, state.next)
270            } else {
271                let id = T::try_from(state.next)
272                    .map_err(|_| LinkError::AddressOutOfRange(state.next))?;
273                let next = state
274                    .next
275                    .checked_add(1)
276                    .ok_or_else(|| error("address space exhausted"))?;
277                (id, next)
278            };
279            if let Some(locks) = &mut self.locks {
280                locks.acquire(&mut state, id, self.base.revision)?;
281            }
282            state.next = next;
283            id
284        };
285        if self.reserved.front() == Some(&id) {
286            self.reserved.pop_front();
287        }
288        self.writes.insert(
289            id,
290            Some(Row {
291                link: GenericLink::new(id, source, target),
292                name: None,
293            }),
294        );
295        Ok(id)
296    }
297    fn ensure_link_created(&mut self, id: T) -> Result<T, LinkError> {
298        self.check_open()?;
299        if id == T::from_byte(0) {
300            return Err(error("zero is not a stored address"));
301        }
302        if self.row(id).is_none() {
303            let address: u128 = id
304                .try_into()
305                .map_err(|_| error("address conversion failed"))?;
306            let mut state = self.engine.lock()?;
307            if let Some(locks) = &mut self.locks {
308                state = locks.wait_turn(state, id)?;
309            }
310            let next = state.next.max(
311                address
312                    .checked_add(1)
313                    .ok_or_else(|| error("address space exhausted"))?,
314            );
315            if let Some(locks) = &mut self.locks {
316                locks.acquire(&mut state, id, self.base.revision)?;
317            }
318            state.next = next;
319            self.writes.insert(
320                id,
321                Some(Row {
322                    link: GenericLink::new(id, T::from_byte(0), T::from_byte(0)),
323                    name: None,
324                }),
325            );
326        }
327        self.reserved.retain(|pending| *pending != id);
328        Ok(id)
329    }
330    fn get_link(&self, id: T) -> Option<GenericLink<T>> {
331        self.row(id).map(|row| row.link)
332    }
333    fn update_link(&mut self, id: T, source: T, target: T) -> Result<GenericLink<T>, LinkError> {
334        self.check_open()?;
335        let mut row = self.row(id).ok_or_else(|| LinkError::not_found(id))?;
336        self.acquire_write(id)?;
337        let previous = row.link;
338        row.link = GenericLink::new(id, source, target);
339        self.writes.insert(id, Some(row));
340        Ok(previous)
341    }
342    fn delete_link(&mut self, id: T) -> Result<GenericLink<T>, LinkError> {
343        self.check_open()?;
344        let previous = self.row(id).ok_or_else(|| LinkError::not_found(id))?.link;
345        self.acquire_write(id)?;
346        self.writes.insert(id, None);
347        Ok(previous)
348    }
349    fn all_links(&self) -> Vec<GenericLink<T>> {
350        self.view().values().map(|row| row.link).collect()
351    }
352    /// Flush commits the staged transaction, rather than exposing uncommitted data.
353    fn flush(&mut self) -> Result<(), LinkError> {
354        self.commit().map(|_| ())
355    }
356}