Skip to main content

link_cli/engine/
branch.rs

1//! Independent branch journals and atomic, row-level three-way merges.
2use super::{error, journal, ConcurrencyControl, Engine, EngineOptions, Rows, Snapshot};
3use crate::{LinkError, TransitionLogStore};
4use doublets::data::LinkReference;
5use std::collections::BTreeSet;
6
7pub struct Branch<T: LinkReference, P: TransitionLogStore, L: TransitionLogStore> {
8    parent: Engine<T, P>,
9    engine: Engine<T, L>,
10    base: Snapshot<T>,
11    base_next: u128,
12}
13
14impl<T: LinkReference, P: TransitionLogStore> Engine<T, P> {
15    /// Seed an empty independent log with a flushed copy of the current state.
16    /// Branch addresses are independent; divergent allocation collisions conflict.
17    pub fn fork<L: TransitionLogStore>(
18        &self,
19        log: L,
20        options: EngineOptions,
21    ) -> Result<Branch<T, P, L>, LinkError> {
22        let (snapshot, next) = {
23            let state = self.lock()?;
24            (state.current.clone(), state.next)
25        };
26        let engine = Engine::open(log, options)?;
27        let base = {
28            let mut state = engine.lock()?;
29            if state.current.revision != 0 {
30                return Err(error("fork requires an empty branch log"));
31            }
32            state.next = next;
33            state.publish(
34                snapshot.rows.as_ref().clone(),
35                snapshot.rows.keys().copied(),
36            )?
37        };
38        Ok(Branch {
39            parent: self.clone(),
40            engine,
41            base,
42            base_next: next,
43        })
44    }
45
46    /// Restore a branch using a merge-base record saved by its previous owner.
47    /// The caller must associate that descriptor with the same logical parent.
48    /// A descriptor must identify a real committed revision of the branch log.
49    pub fn resume_branch<L: TransitionLogStore>(
50        &self,
51        mut log: L,
52        options: EngineOptions,
53        merge_base_record: &str,
54    ) -> Result<Branch<T, P, L>, LinkError> {
55        drop(self.lock()?);
56        let (mut base, next) = journal::decode::<T>(merge_base_record)?;
57        let mut found = false;
58        let mut previous = Snapshot {
59            revision: 0,
60            rows: std::sync::Arc::new(Rows::new(options.state_structure)),
61        };
62        let mut previous_next = 1;
63        for (index, record) in log.read_log_entries()?.into_iter().enumerate() {
64            let (snapshot, allocator) = if index == 0 && record.starts_with("engine3|") {
65                journal::decode_checkpoint(&record, options.state_structure)?
66            } else {
67                journal::decode_after(&record, &previous, previous_next, options.state_structure)?
68            };
69            if snapshot.revision == base.revision && snapshot.rows == base.rows && allocator == next
70            {
71                found = true;
72            }
73            previous = snapshot;
74            previous_next = allocator;
75        }
76        if !found {
77            return Err(error("merge base is not a committed branch revision"));
78        }
79        let structure = options.state_structure;
80        let engine = Engine::open(log, options)?;
81        base.rows =
82            std::sync::Arc::new(std::sync::Arc::unwrap_or_clone(base.rows).adapt(structure, None));
83        Ok(Branch {
84            parent: self.clone(),
85            engine,
86            base,
87            base_next: next,
88        })
89    }
90}
91
92impl<T: LinkReference, P: TransitionLogStore, L: TransitionLogStore> Branch<T, P, L> {
93    pub fn engine(&self) -> &Engine<T, L> {
94        &self.engine
95    }
96    pub fn into_engine(self) -> Engine<T, L> {
97        self.engine
98    }
99
100    /// Persist this descriptor with application metadata after each merge.
101    /// Reusing an older descriptor is conservative: overlapping changes conflict.
102    pub fn merge_base_record(&self) -> String {
103        journal::encode(&self.base, self.base_next)
104    }
105
106    /// Merge the branch's current committed snapshot; unfinished sessions are private.
107    /// All constraints, history, flush, poisoning and conflict rules still apply.
108    pub fn merge(&mut self) -> Result<u64, LinkError> {
109        let (incoming, next) = {
110            let state = self.engine.lock()?;
111            (state.current.clone(), state.committed_next)
112        };
113        let mut state = self.parent.lock()?;
114        if state.options.concurrency == ConcurrencyControl::Exclusive && state.active > 0 {
115            return Err(error("busy: an exclusive transaction is active"));
116        }
117        let keys: BTreeSet<_> = self
118            .base
119            .rows
120            .keys()
121            .chain(incoming.rows.keys())
122            .copied()
123            .collect();
124        let mut rows = state.current.rows.as_ref().clone();
125        let mut changes = Vec::new();
126        for id in keys {
127            let before = self.base.rows.get(&id);
128            let after = incoming.rows.get(&id);
129            if before == after {
130                continue;
131            }
132            let current = rows.get(&id);
133            if current != before && current != after {
134                return Err(error("conflict: branch and parent changed the same row"));
135            }
136            if current == after {
137                continue;
138            }
139            if state.write_owners.contains_key(&id) {
140                return Err(error("busy: another transaction owns this write address"));
141            }
142            match after {
143                Some(row) => {
144                    rows.insert(id, row.clone());
145                }
146                None => {
147                    rows.remove(&id);
148                }
149            }
150            changes.push(id);
151        }
152        state.next = state.next.max(next);
153        let revision = if changes.is_empty() && state.next == state.committed_next {
154            state.current.revision
155        } else {
156            state.publish(rows, changes)?.revision
157        };
158        self.base = incoming;
159        self.base_next = next;
160        Ok(revision)
161    }
162}