Skip to main content

link_cli/engine/
causal_session.rs

1//! Ordinary owned links/names staging with explicit-token local publication.
2use super::{
3    causal::{CausalPayload, CausalVersion},
4    causal_batch::{CausalBatch, CausalBatchEdit},
5    causal_projection::{CausalConflictPolicy, CausalProjection, CausalProjectionOptions},
6    cluster::AtomicJournalStore,
7    Constraint, ConstraintValidation, Engine, EngineOptions, EngineTransaction, MemoryLog, Row,
8    Rows, Snapshot, StateStructure,
9};
10use crate::{GenericLink, LinkError, LinksStorage};
11use std::{
12    collections::{BTreeMap, BTreeSet, VecDeque},
13    sync::Arc,
14};
15
16#[derive(Clone, Debug, Default)]
17pub struct CausalWorkspaceOptions {
18    pub state_structure: StateStructure,
19    pub constraints: Vec<Constraint>,
20    pub constraint_validation: ConstraintValidation,
21    pub projection: CausalProjectionOptions,
22    pub trace: bool,
23}
24
25/// A sealed standard-engine workspace with an independent reserved cursor.
26/// No ordinary engine handle or unguarded allocating callback escapes.
27pub struct CausalWorkspace {
28    engine: Option<Engine<u64, MemoryLog>>,
29    inner: Option<EngineTransaction<u64, MemoryLog>>,
30    original: BTreeMap<u64, Row<u64>>,
31    retained: BTreeMap<u64, Vec<CausalVersion>>,
32    first: u64,
33    last: u64,
34    next: u128,
35    reserved: VecDeque<u64>,
36    final_rows: Vec<Row<u64>>,
37}
38fn invalid() -> LinkError {
39    super::error("invalid or frozen causal workspace")
40}
41impl CausalWorkspace {
42    /// Borrow the standard query/named-store interface with checked u64 writes
43    /// and a u128 wildcard outside the complete stored address domain.
44    pub fn named_links(&mut self) -> super::causal_named::CausalNamedLinks<'_> {
45        super::causal_named::CausalNamedLinks { workspace: self }
46    }
47
48    pub(super) fn query_save(&mut self) -> Result<(), LinkError> {
49        self.active().map(|_| ())
50    }
51
52    pub(super) fn reserve_query(
53        &mut self,
54        processor: &crate::GenericQueryProcessor<u128>,
55        restriction: &crate::lino_link::LinoLink,
56        substitution: &crate::lino_link::LinoLink,
57    ) -> anyhow::Result<Option<std::collections::HashSet<u128>>> {
58        self.active()?;
59        let rows = self
60            .rows()
61            .into_iter()
62            .map(|row| {
63                let link = row.link;
64                (
65                    u128::from(link.index),
66                    Row {
67                        link: GenericLink::new(
68                            link.index.into(),
69                            link.source.into(),
70                            link.target.into(),
71                        ),
72                        name: row.name,
73                    },
74                )
75            })
76            .collect();
77        let mut scratch = super::query_scratch::QueryScratch {
78            rows,
79            next: self.next,
80            last: self.last.into(),
81            reserved: self.reserved.iter().copied().map(u128::from).collect(),
82            allocated: Vec::new(),
83            fresh_range: Some((
84                self.first.into(),
85                self.last.into(),
86                self.retained.keys().copied().map(u128::from).collect(),
87            )),
88            limits: Some(crate::query_options::QueryLimits::causal()),
89        };
90        processor.preview(&mut scratch, restriction, substitution)?;
91        self.next = self.next.max(scratch.next);
92        for id in scratch.allocated {
93            let id = u64::try_from(id).map_err(|_| invalid())?;
94            if !self.reserved.contains(&id) {
95                self.reserved.push_back(id);
96            }
97        }
98        Ok(Some(scratch.rows.into_keys().collect()))
99    }
100
101    pub fn new(
102        versions: &[CausalVersion],
103        first: u64,
104        last: u64,
105        policy: CausalConflictPolicy,
106        options: CausalWorkspaceOptions,
107    ) -> Result<Self, LinkError> {
108        if first == 0 || first > last {
109            return Err(invalid());
110        }
111        let projection = CausalProjection::new(versions, policy, options.projection)?;
112        let mut retained: BTreeMap<u64, Vec<CausalVersion>> = BTreeMap::new();
113        for version in projection.versions() {
114            if (first..=last).contains(&version.address) {
115                return Err(invalid());
116            }
117            retained.entry(version.address).or_default().push(version);
118        }
119        let original: BTreeMap<_, _> = projection
120            .rows()
121            .into_iter()
122            .map(|row| (row.link.index, row))
123            .collect();
124        let engine = Engine::open(
125            MemoryLog::default(),
126            EngineOptions {
127                state_structure: options.state_structure,
128                constraints: options.constraints,
129                constraint_validation: options.constraint_validation,
130                trace: options.trace,
131                ..Default::default()
132            },
133        )?;
134        {
135            let mut state = engine.lock()?;
136            let mut rows = Rows::new(options.state_structure);
137            for (id, row) in &original {
138                rows.insert(*id, row.clone());
139            }
140            state.validate(&rows)?;
141            if options.constraint_validation == ConstraintValidation::Indexed {
142                state.constraint_index = super::constraint_index::ConstraintIndex::build(
143                    &state.options.constraints,
144                    &rows,
145                )?;
146            }
147            // Ordinary journal next must exceed every visible address, even
148            // when the independent fresh reservation lies below a remote row.
149            let next = original
150                .last_key_value()
151                .map_or(1, |(id, _)| u128::from(*id) + 1);
152            state.next = next;
153            state.committed_next = next;
154            state.current = Snapshot {
155                revision: 0,
156                rows: Arc::new(rows),
157            };
158        }
159        let inner = Some(engine.begin()?);
160        Ok(Self {
161            engine: Some(engine),
162            inner,
163            original,
164            retained,
165            first,
166            last,
167            next: u128::from(first),
168            reserved: VecDeque::new(),
169            final_rows: Vec::new(),
170        })
171    }
172    fn active(&mut self) -> Result<&mut EngineTransaction<u64, MemoryLog>, LinkError> {
173        self.inner.as_mut().ok_or_else(invalid)
174    }
175    pub fn rows(&self) -> Vec<Row<u64>> {
176        self.inner.as_ref().map_or_else(
177            || self.final_rows.clone(),
178            |tx| {
179                tx.all_links()
180                    .into_iter()
181                    .map(|link| Row {
182                        name: tx.get_name(link.index),
183                        link,
184                    })
185                    .collect()
186            },
187        )
188    }
189    pub fn get_name(&self, id: u64) -> Option<String> {
190        self.inner.as_ref().map_or_else(
191            || {
192                self.final_rows
193                    .iter()
194                    .find(|row| row.link.index == id)
195                    .and_then(|row| row.name.clone())
196            },
197            |tx| tx.get_name(id),
198        )
199    }
200    pub fn get_by_name(&self, name: &str) -> Option<u64> {
201        self.inner.as_ref().map_or_else(
202            || {
203                self.final_rows
204                    .iter()
205                    .find(|row| row.name.as_deref() == Some(name))
206                    .map(|row| row.link.index)
207            },
208            |tx| tx.get_by_name(name),
209        )
210    }
211    pub fn set_name(&mut self, id: u64, name: Option<String>) -> Result<(), LinkError> {
212        self.active()?.set_name(id, name)
213    }
214    pub fn finish(&mut self) -> Result<Vec<CausalBatchEdit>, LinkError> {
215        let mut tx = self.inner.take().ok_or_else(invalid)?;
216        let engine = self.engine.take().ok_or_else(invalid)?;
217        // All ordinary constraints and the selected immutable representation
218        // are validated through the same commit path as a standard session.
219        tx.commit()?;
220        self.final_rows = engine
221            .snapshot()?
222            .iter()
223            .map(|(_, row)| row.clone())
224            .collect();
225        let final_rows: BTreeMap<_, _> = self
226            .final_rows
227            .iter()
228            .map(|row| (row.link.index, row))
229            .collect();
230        let keys: BTreeSet<_> = self
231            .original
232            .keys()
233            .chain(final_rows.keys())
234            .copied()
235            .collect();
236        let edits: Vec<_> = keys
237            .into_iter()
238            .filter_map(|id| {
239                let before = self.original.get(&id);
240                let after = final_rows.get(&id).copied();
241                if before == after {
242                    return None;
243                }
244                Some(CausalBatchEdit {
245                    address: id,
246                    observed: self.retained.get(&id).cloned().unwrap_or_default(),
247                    payload: after.map(|row| CausalPayload {
248                        source: row.link.source,
249                        target: row.link.target,
250                        name: row.name.clone(),
251                    }),
252                })
253            })
254            .collect();
255        self.original.clear();
256        self.retained.clear();
257        self.reserved.clear();
258        if edits.len() > 64 {
259            return Err(invalid());
260        }
261        super::causal_batch::normalize(&edits)?;
262        Ok(edits)
263    }
264    pub fn rollback(&mut self) {
265        self.inner.take();
266        self.engine.take();
267        self.original.clear();
268        self.retained.clear();
269        self.reserved.clear();
270        self.final_rows.clear();
271    }
272}
273impl LinksStorage<u64> for CausalWorkspace {
274    fn create_link(&mut self, source: u64, target: u64) -> Result<u64, LinkError> {
275        self.active()?;
276        let id = if let Some(id) = self.reserved.front().copied() {
277            id
278        } else {
279            if self.next > u128::from(self.last) {
280                return Err(invalid());
281            }
282            self.next as u64
283        };
284        let tx = self.active()?;
285        tx.ensure_link_created(id)?;
286        tx.update_link(id, source, target)?;
287        if self.reserved.front() == Some(&id) {
288            self.reserved.pop_front();
289        } else {
290            self.next += 1;
291        }
292        Ok(id)
293    }
294    fn ensure_link_created(&mut self, id: u64) -> Result<u64, LinkError> {
295        if id == 0 || (!(self.first..=self.last).contains(&id) && !self.retained.contains_key(&id))
296        {
297            return Err(invalid());
298        }
299        self.active()?.ensure_link_created(id)?;
300        if (self.first..=self.last).contains(&id) {
301            self.next = self.next.max(u128::from(id) + 1);
302        }
303        self.reserved.retain(|pending| *pending != id);
304        Ok(id)
305    }
306    fn get_link(&self, id: u64) -> Option<GenericLink<u64>> {
307        self.inner.as_ref().map_or_else(
308            || {
309                self.final_rows
310                    .iter()
311                    .find(|row| row.link.index == id)
312                    .map(|row| row.link)
313            },
314            |tx| tx.get_link(id),
315        )
316    }
317    fn update_link(
318        &mut self,
319        id: u64,
320        source: u64,
321        target: u64,
322    ) -> Result<GenericLink<u64>, LinkError> {
323        self.active()?.update_link(id, source, target)
324    }
325    fn delete_link(&mut self, id: u64) -> Result<GenericLink<u64>, LinkError> {
326        self.active()?.delete_link(id)
327    }
328    fn all_links(&self) -> Vec<GenericLink<u64>> {
329        self.inner.as_ref().map_or_else(
330            || self.final_rows.iter().map(|row| row.link).collect(),
331            LinksStorage::all_links,
332        )
333    }
334    fn flush(&mut self) -> Result<(), LinkError> {
335        Err(super::error(
336            "causal publication requires an explicit retry token",
337        ))
338    }
339}
340
341#[derive(Clone, Debug)]
342pub struct CausalPreparedBatch {
343    pub token: String,
344    pub generation: u64,
345    pub edits: Vec<CausalBatchEdit>,
346}
347pub struct CausalSession<S: AtomicJournalStore> {
348    batch: CausalBatch<S>,
349    workspace: CausalWorkspace,
350    generation: u64,
351    prepared: Option<CausalPreparedBatch>,
352    result: Option<Vec<CausalVersion>>,
353    disposed: bool,
354}
355impl<S: AtomicJournalStore> CausalSession<S> {
356    /// Standard named/query staging; preparation freezes the borrowed workspace.
357    pub fn named_links(&mut self) -> super::causal_named::CausalNamedLinks<'_> {
358        self.workspace.named_links()
359    }
360
361    pub fn new(
362        mut batch: CausalBatch<S>,
363        first: u64,
364        last: u64,
365        policy: CausalConflictPolicy,
366        options: CausalWorkspaceOptions,
367    ) -> Result<Self, LinkError> {
368        let snapshot = batch.snapshot()?;
369        let workspace = CausalWorkspace::new(&snapshot.versions, first, last, policy, options)?;
370        Ok(Self {
371            batch,
372            workspace,
373            generation: snapshot.generation,
374            prepared: None,
375            result: None,
376            disposed: false,
377        })
378    }
379    pub fn prepare(&mut self, token: &str) -> Result<CausalPreparedBatch, LinkError> {
380        if self.disposed {
381            return Err(invalid());
382        }
383        if let Some(request) = &self.prepared {
384            if request.token != token {
385                return Err(invalid());
386            }
387            return Ok(request.clone());
388        }
389        super::causal_batch::validate_token(token, 0)?;
390        let edits = self.workspace.finish()?;
391        super::causal_batch::validate_token(token, edits.len())?;
392        let request = CausalPreparedBatch {
393            token: token.into(),
394            generation: self.generation,
395            edits,
396        };
397        self.prepared = Some(request.clone());
398        Ok(request)
399    }
400    pub fn prepared(&self) -> Option<CausalPreparedBatch> {
401        self.prepared.clone()
402    }
403    pub fn commit(&mut self, token: &str) -> Result<Vec<CausalVersion>, LinkError> {
404        let request = self.prepare(token)?;
405        if let Some(result) = &self.result {
406            return Ok(result.clone());
407        }
408        let result = self
409            .batch
410            .write(&request.token, request.generation, &request.edits)?;
411        self.result = Some(result.clone());
412        Ok(result)
413    }
414    pub fn rollback(&mut self) {
415        self.workspace.rollback();
416        self.disposed = true;
417        self.result = None;
418    }
419    pub fn rows(&self) -> Vec<Row<u64>> {
420        self.workspace.rows()
421    }
422    pub fn get_name(&self, id: u64) -> Option<String> {
423        self.workspace.get_name(id)
424    }
425    pub fn get_by_name(&self, name: &str) -> Option<u64> {
426        self.workspace.get_by_name(name)
427    }
428    pub fn set_name(&mut self, id: u64, name: Option<String>) -> Result<(), LinkError> {
429        self.workspace.set_name(id, name)
430    }
431}
432impl<S: AtomicJournalStore> LinksStorage<u64> for CausalSession<S> {
433    fn create_link(&mut self, source: u64, target: u64) -> Result<u64, LinkError> {
434        self.workspace.create_link(source, target)
435    }
436    fn ensure_link_created(&mut self, id: u64) -> Result<u64, LinkError> {
437        self.workspace.ensure_link_created(id)
438    }
439    fn get_link(&self, id: u64) -> Option<GenericLink<u64>> {
440        self.workspace.get_link(id)
441    }
442    fn update_link(
443        &mut self,
444        id: u64,
445        source: u64,
446        target: u64,
447    ) -> Result<GenericLink<u64>, LinkError> {
448        self.workspace.update_link(id, source, target)
449    }
450    fn delete_link(&mut self, id: u64) -> Result<GenericLink<u64>, LinkError> {
451        self.workspace.delete_link(id)
452    }
453    fn all_links(&self) -> Vec<GenericLink<u64>> {
454        self.workspace.all_links()
455    }
456    fn flush(&mut self) -> Result<(), LinkError> {
457        self.workspace.flush()
458    }
459}