Skip to main content

link_cli/transactions/
mod.rs

1//! Optional transactions layer for the Rust link-cli.
2//!
3//! Mirrors the C# `TransactionsDecorator` in
4//! `csharp/Foundation.Data.Doublets.Cli.Library/TransactionsDecorator.cs`.
5//!
6//! The decorator records every `create` / `update` / `delete` as a
7//! reversible [`GenericTransition`] in a sidecar log. It supports
8//! explicit transactions, sync commits, three retention policies, and
9//! crash recovery (R1-R7, R10).
10//!
11//! Optional — when not opted in, the bare
12//! [`NamedTypesDecorator`] behaves
13//! identically (R8, R9, R17).
14//!
15//! # Reuse outside the CLI
16//!
17//! [`GenericTransactionsDecorator`] is generic over three things:
18//!
19//! * `T` — the doublets address type (`u32`, `u64`, `usize`, ...);
20//! * `S` — the wrapped store, any [`LinksStorage<T>`] implementation,
21//!   including [`DoubletsStorage`](crate::DoubletsStorage) over a
22//!   file-mapped or caller-owned `doublets::unit::Store`;
23//! * `L` — the transitions log, any [`TransitionLogStore`].
24//!
25//! [`TransactionsDecorator`] is the `u32` + `NamedTypesDecorator`
26//! specialisation used by `clink` itself.
27//!
28//! ```no_run
29//! use link_cli::transactions::{
30//!     CommitMode, FileTransitionLog, GenericTransactionsDecorator, LogRetentionPolicy,
31//! };
32//! use link_cli::DoubletsStorage;
33//!
34//! # fn main() -> Result<(), link_cli::LinkError> {
35//! let store = DoubletsStorage::<usize, _>::open_exclusive("db.links")?;
36//! let log = FileTransitionLog::open("db.transitions.log")?;
37//! let mut tx = GenericTransactionsDecorator::new(
38//!     store,
39//!     log,
40//!     LogRetentionPolicy::default(),
41//!     CommitMode::default(),
42//!     false,
43//! )?;
44//!
45//! tx.begin_transaction()?;
46//! let link = tx.create(0, 0)?;
47//! tx.commit()?;
48//! tx.save()?;
49//! # let _ = link;
50//! # Ok(())
51//! # }
52//! ```
53//!
54//! # Durability
55//!
56//! Transitions are durably logged before commit is acknowledged. Commit then
57//! flushes the wrapped data before persisting its applied markers. Recovery
58//! replays committed-but-unapplied transitions and undoes logged uncommitted
59//! changes, reporting replay and flush failures.
60//!
61//! The default [`RowUndoPolicy::Observed`] mutates the store before recording
62//! callbacks and leaves a crash window for unlogged changes. Select
63//! [`RowUndoPolicy::WriteAheadImage`] to flush a complete logical undo image
64//! before the first effect and reconcile complete history after each write.
65//! It requires exclusive ownership and an adapter supporting logical replay;
66//! it does not repair torn physical storage. The optional
67//! [`crate::engine::Engine`] stages private changes until durable publication.
68
69mod log;
70// Replay, recovery and retention live in a submodule; see transactions/recovery.rs.
71mod commit;
72mod compaction;
73mod journal_file;
74mod journal_validation;
75mod names;
76mod record;
77mod recording;
78mod recovery;
79mod row_undo;
80mod types;
81mod undo_image;
82mod version_replay;
83
84use std::collections::HashSet;
85use std::path::{Path, PathBuf};
86use std::sync::atomic::{AtomicU64, Ordering};
87use web_time::{SystemTime, UNIX_EPOCH};
88
89use doublets::data::LinkReference;
90
91use crate::error::LinkError;
92use crate::link::GenericLink;
93use crate::named_types::NamedTypesDecorator;
94use crate::storage::{LinksStorage, LinksStorageRef};
95
96pub use journal_file::{
97    import_links_journal, is_links_journal, make_legacy_transitions_filename,
98    make_transitions_log_filename, open_transitions_journal,
99};
100pub use log::{FileTransitionLog, ReplaceableTransitionLogStore, TransitionLogStore};
101pub use record::{JournalRecord, NameChange};
102pub use types::{
103    CommitMode, DoubletLink, GenericDoubletLink, GenericTransition, LogRetentionPolicy, Transition,
104    TransitionKind,
105};
106use types::{COMMIT_MARKER_PREFIX, ROLLBACK_MARKER_PREFIX, TRANSITION_NAME_PREFIX};
107pub use undo_image::RowUndoPolicy;
108
109/// Pending state of a transaction (used by the explicit transaction
110/// handle and by per-write auto-transactions).
111#[derive(Clone)]
112struct PendingTransaction<T> {
113    id: u128,
114    transitions: Vec<JournalRecord<T>>,
115    auto_commit: bool,
116    rollback_only: bool,
117    commit_attempted: bool,
118    started_ms: i64,
119    image: Option<undo_image::UndoImage<T>>,
120}
121
122/// One link address and the `(before, after)` states a single logical
123/// write left it in, after collapsing repeated callbacks for that address.
124type ObservedChange<T> = (T, GenericDoubletLink<T>, GenericDoubletLink<T>);
125type TransitionChange<T> = (TransitionKind, GenericDoubletLink<T>, GenericDoubletLink<T>);
126
127/// Folds one `(before, after)` callback into `observed`.
128///
129/// Mirrors the handler `TransactionsDecorator.RunWrite` installs in the C#
130/// implementation: repeated callbacks for the same address are collapsed into
131/// a single change that keeps the *first* `before` (the state the rollback has
132/// to restore) and the *last* `after` (the state the write ended at), and the
133/// first-seen order of addresses is preserved so the transitions replay in the
134/// order the storage produced them.
135fn record_observed<T: LinkReference>(
136    observed: &mut Vec<ObservedChange<T>>,
137    before: GenericLink<T>,
138    after: GenericLink<T>,
139) {
140    let zero = T::from_byte(0);
141    let key = if before.index != zero {
142        before.index
143    } else {
144        after.index
145    };
146    if key == zero {
147        return;
148    }
149    let before = GenericDoubletLink::from_link(&before);
150    let after = GenericDoubletLink::from_link(&after);
151    match observed.iter_mut().find(|(index, _, _)| *index == key) {
152        Some(entry) => {
153            // A null first before means the address did not exist. A later
154            // update must not replace it with the intermediate created row.
155            entry.2 = after;
156        }
157        None => observed.push((key, before, after)),
158    }
159}
160
161/// Snapshot of an open transaction (returned by [`GenericTransactionsDecorator::begin_transaction`]).
162#[derive(Debug, Clone)]
163pub struct TransactionHandle {
164    pub id: u128,
165    pub started_ms: i64,
166}
167
168/// The transactions decorator wraps any [`LinksStorage`] and records
169/// every write as a reversible [`GenericTransition`] in `log_store`.
170pub struct GenericTransactionsDecorator<T, S, L>
171where
172    T: LinkReference,
173    S: LinksStorage<T>,
174    L: TransitionLogStore,
175{
176    inner: S,
177    log_store: L,
178    log: Vec<JournalRecord<T>>,
179    committed: HashSet<u128>,
180    rolled_back: HashSet<u128>,
181    applied: HashSet<i64>,
182    current: Option<PendingTransaction<T>>,
183    sequence_counter: i64,
184    applied_sequence: i64,
185    retention_policy: LogRetentionPolicy,
186    commit_mode: CommitMode,
187    version_replay: bool,
188    recovery_pending: bool,
189    reload_pending: bool,
190    trace: bool,
191    row_undo: RowUndoPolicy,
192    /// Entries in the durable journal, and its newest commit/rollback marker.
193    journal_entries: usize,
194    last_decision: Option<String>,
195}
196
197/// The `u32` + [`NamedTypesDecorator`] specialisation with the original
198/// links-backed sidecar log.
199pub type TransactionsDecorator =
200    GenericTransactionsDecorator<u32, NamedTypesDecorator, NamedTypesDecorator>;
201
202/// The specialisation `clink` uses: an append-only [`FileTransitionLog`]
203/// journal, whose cost per write does not grow with history (issue #195).
204pub type FileTransactionsDecorator =
205    GenericTransactionsDecorator<u32, NamedTypesDecorator, FileTransitionLog>;
206
207impl<T, S, L> GenericTransactionsDecorator<T, S, L>
208where
209    T: LinkReference,
210    S: LinksStorage<T>,
211    L: TransitionLogStore,
212{
213    /// Creates a new transactions decorator wrapping `inner`, using
214    /// `log_store` as the sidecar log. Runs crash recovery before
215    /// returning.
216    pub fn new(
217        inner: S,
218        log_store: L,
219        retention_policy: LogRetentionPolicy,
220        commit_mode: CommitMode,
221        trace: bool,
222    ) -> Result<Self, LinkError> {
223        let mut decorator = Self {
224            inner,
225            log_store,
226            log: Vec::new(),
227            committed: HashSet::new(),
228            rolled_back: HashSet::new(),
229            applied: HashSet::new(),
230            current: None,
231            sequence_counter: 0,
232            applied_sequence: 0,
233            retention_policy,
234            commit_mode,
235            version_replay: false,
236            recovery_pending: false,
237            reload_pending: false,
238            trace,
239            row_undo: RowUndoPolicy::Observed,
240            journal_entries: 0,
241            last_decision: None,
242        };
243        decorator.recover()?;
244        Ok(decorator)
245    }
246
247    /// Conventional filename of the links-backed transitions log
248    /// (`<stem>.transitions.links`). `clink` now keeps its journal in
249    /// [`make_transitions_log_filename`] and imports this store once.
250    pub fn make_transitions_database_filename<P: AsRef<Path>>(database_filename: P) -> PathBuf {
251        let path = database_filename.as_ref();
252        let stem = path
253            .file_stem()
254            .and_then(|s| s.to_str())
255            .unwrap_or_default();
256        let name = format!("{stem}.transitions.links");
257        match path.parent() {
258            Some(parent) if !parent.as_os_str().is_empty() => parent.join(name),
259            _ => PathBuf::from(name),
260        }
261    }
262
263    pub fn retention_policy(&self) -> &LogRetentionPolicy {
264        &self.retention_policy
265    }
266
267    pub fn set_retention_policy(&mut self, policy: LogRetentionPolicy) {
268        self.retention_policy = policy;
269    }
270
271    pub fn commit_mode(&self) -> CommitMode {
272        self.commit_mode
273    }
274
275    pub fn set_commit_mode(&mut self, mode: CommitMode) {
276        self.commit_mode = mode;
277    }
278
279    pub fn applied_sequence(&self) -> i64 {
280        self.applied_sequence
281    }
282
283    pub fn last_logged_sequence(&self) -> i64 {
284        self.sequence_counter
285    }
286
287    /// Higher layers must distinguish a durable decision from a failed
288    /// checkpoint before deciding whether cleanup may undo the transaction.
289    pub(crate) fn is_transaction_committed(&self, id: u128) -> bool {
290        self.committed.contains(&id)
291    }
292
293    pub(crate) fn is_transaction_rolled_back(&self, id: u128) -> bool {
294        self.rolled_back.contains(&id)
295    }
296
297    pub(crate) fn has_open_transaction(&self) -> bool {
298        self.current.is_some() || self.version_replay || self.recovery_pending
299    }
300
301    pub(crate) fn must_finish_commit(&self, id: u128) -> bool {
302        self.is_transaction_committed(id)
303            || self
304                .current
305                .as_ref()
306                .is_some_and(|pending| pending.id == id && pending.commit_attempted)
307    }
308
309    /// Returns a snapshot of the transitions log in sequence order.
310    pub fn log(&self) -> Vec<GenericTransition<T>> {
311        self.log.iter().map(|record| record.transition).collect()
312    }
313
314    /// Complete retained records, including optional name payloads.
315    pub fn journal(&self) -> Vec<JournalRecord<T>> {
316        self.log.clone()
317    }
318
319    pub fn inner(&self) -> &S {
320        &self.inner
321    }
322
323    pub fn inner_mut(&mut self) -> &mut S {
324        &mut self.inner
325    }
326
327    pub fn log_store(&self) -> &L {
328        &self.log_store
329    }
330
331    pub fn log_store_mut(&mut self) -> &mut L {
332        &mut self.log_store
333    }
334
335    pub fn into_inner(self) -> (S, L) {
336        (self.inner, self.log_store)
337    }
338
339    /// Makes both the data store and the transitions log durable.
340    pub fn flush(&mut self) -> Result<(), LinkError> {
341        if self.recovery_pending {
342            return self.recover();
343        }
344        self.ensure_no_version_replay()?;
345        if self
346            .current
347            .as_ref()
348            .is_some_and(|pending| pending.commit_attempted)
349        {
350            return self.commit_current();
351        }
352        self.inner.flush()?;
353        self.log_store.flush_log()?;
354        Ok(())
355    }
356
357    /// Alias of [`flush`](Self::flush), kept for parity with the other
358    /// decorators and with the C# API.
359    pub fn save(&mut self) -> Result<(), LinkError> {
360        self.flush()
361    }
362
363    /// Cheap check for "has another process written to the wrapped
364    /// store since we last read or wrote it?".
365    pub fn has_external_changes(&self) -> Result<bool, LinkError> {
366        self.inner.has_external_changes()
367    }
368
369    /// Re-reads the wrapped store and rebuilds the transactions state
370    /// from the log — the recovery path after another process wrote.
371    pub fn reload(&mut self) -> Result<(), LinkError> {
372        if self.current.is_some() || self.version_replay {
373            return Err(LinkError::Transaction(
374                "Cannot reload while a transaction is open.".to_string(),
375            ));
376        }
377        self.recovery_pending = true;
378        self.reload_pending = true;
379        self.recover()
380    }
381
382    // ----- Write API ------------------------------------------------------
383
384    pub fn create(&mut self, source: T, target: T) -> Result<T, LinkError> {
385        let names_before = self.inner.capture_names()?;
386        let owns = self.ensure_open_transaction()?;
387        let mut observed = Vec::new();
388        let outcome = self
389            .inner
390            .create_link_observed(source, target, &mut |before, after| {
391                record_observed(&mut observed, before, after)
392            });
393        self.record_observed_transitions(&observed, owns, names_before.as_ref())?;
394        let id = match outcome {
395            Ok(id) => id,
396            Err(error) => {
397                self.fence_failed_image();
398                if owns {
399                    if observed.is_empty()
400                        && self
401                            .current
402                            .as_ref()
403                            .is_none_or(|owner| owner.image.is_none())
404                    {
405                        self.current = None;
406                    } else {
407                        self.rollback()?;
408                    }
409                }
410                return Err(error);
411            }
412        };
413        self.complete_image_observations(owns)?;
414        if owns {
415            self.commit_current()?;
416        }
417        Ok(id)
418    }
419
420    pub fn update(&mut self, id: T, source: T, target: T) -> Result<GenericLink<T>, LinkError> {
421        self.update_observed(id, source, target, &mut |_, _| {})
422    }
423
424    /// [`Self::update`], reporting every change the underlying store made.
425    ///
426    /// An update that would duplicate an existing doublet is resolved into a
427    /// merge that deletes the updated link, so one call can report several
428    /// changes, exactly like C#'s `links.Update(restriction, substitution, handler)`.
429    pub fn update_observed(
430        &mut self,
431        id: T,
432        source: T,
433        target: T,
434        observer: &mut dyn FnMut(GenericLink<T>, GenericLink<T>),
435    ) -> Result<GenericLink<T>, LinkError> {
436        let before = self.snapshot(id);
437        let names_before = self.inner.capture_names()?;
438        let owns = self.ensure_open_transaction()?;
439        let mut observed: Vec<ObservedChange<T>> = Vec::new();
440        let outcome = self
441            .inner
442            .update_link_observed(id, source, target, &mut |before, after| {
443                observer(before, after);
444                record_observed(&mut observed, before, after)
445            });
446        let prev = match outcome {
447            Ok(prev) => prev,
448            Err(err) => {
449                self.fence_failed_image();
450                // Callbacks describe changes already made, even if a later
451                // part of the storage operation fails.
452                self.record_observed_transitions(&observed, owns, names_before.as_ref())?;
453                if owns {
454                    if observed.is_empty()
455                        && self
456                            .current
457                            .as_ref()
458                            .is_none_or(|owner| owner.image.is_none())
459                    {
460                        self.current = None;
461                    } else {
462                        self.rollback()?;
463                    }
464                }
465                return Err(err);
466            }
467        };
468        if observed.is_empty() {
469            let after = self
470                .inner
471                .get_link(id)
472                .map(|link| GenericDoubletLink::from_link(&link))
473                .unwrap_or_else(|| GenericDoubletLink::new(id, source, target));
474            self.record_transition(
475                TransitionKind::Update,
476                before,
477                after,
478                owns,
479                names_before.as_ref(),
480            )?;
481        } else {
482            self.record_observed_transitions(&observed, owns, names_before.as_ref())?;
483        }
484        self.complete_image_observations(owns)?;
485        if owns {
486            self.commit_current()?;
487        }
488        Ok(prev)
489    }
490
491    pub fn delete(&mut self, id: T) -> Result<GenericLink<T>, LinkError> {
492        self.delete_observed(id, &mut |_, _| {})
493    }
494
495    /// [`Self::delete`], reporting every change the underlying store made.
496    ///
497    /// Deleting a link cascades into every link that still used it, and those
498    /// deletions are changes of their own: the C# CLI hands
499    /// `AdvancedMixedQueryProcessor.RemoveLinks` a handler that `links.Delete`
500    /// calls once per removed link, so `--changes` lists the usages too. The
501    /// observer is the same seam, threaded through the decorator stack.
502    pub fn delete_observed(
503        &mut self,
504        id: T,
505        observer: &mut dyn FnMut(GenericLink<T>, GenericLink<T>),
506    ) -> Result<GenericLink<T>, LinkError> {
507        let before = self.snapshot(id);
508        let names_before = self.inner.capture_names()?;
509        let owns = self.ensure_open_transaction()?;
510        let mut observed: Vec<ObservedChange<T>> = Vec::new();
511        let outcome = self.inner.delete_link_observed(id, &mut |before, after| {
512            observer(before, after);
513            record_observed(&mut observed, before, after)
514        });
515        let deleted = match outcome {
516            Ok(d) => d,
517            Err(err) => {
518                self.fence_failed_image();
519                // Callbacks describe changes already made, even if a later
520                // part of the storage operation fails.
521                self.record_observed_transitions(&observed, owns, names_before.as_ref())?;
522                if owns {
523                    if observed.is_empty()
524                        && self
525                            .current
526                            .as_ref()
527                            .is_none_or(|owner| owner.image.is_none())
528                    {
529                        self.current = None;
530                    } else {
531                        self.rollback()?;
532                    }
533                }
534                return Err(err);
535            }
536        };
537        if observed.is_empty() {
538            self.record_transition(
539                TransitionKind::Delete,
540                before,
541                GenericDoubletLink::empty(),
542                owns,
543                names_before.as_ref(),
544            )?;
545        } else {
546            self.record_observed_transitions(&observed, owns, names_before.as_ref())?;
547        }
548        self.complete_image_observations(owns)?;
549        if owns {
550            self.commit_current()?;
551        }
552        Ok(deleted)
553    }
554
555    /// Composite create-and-update used by callers that want a link
556    /// initialised with source/target in a single pair of transitions
557    /// (matches the C# `CreateAndUpdate` extension semantics, which
558    /// always emits a Create followed by an Update transition).
559    pub fn create_and_update(&mut self, source: T, target: T) -> Result<T, LinkError> {
560        let owns = self.ensure_open_transaction()?;
561        let zero = T::from_byte(0);
562        let outcome = self.create(zero, zero).and_then(|id| {
563            self.update(id, source, target)?;
564            Ok(id)
565        });
566        let id = match outcome {
567            Ok(id) => id,
568            Err(error) => {
569                self.fence_failed_image();
570                if owns {
571                    self.rollback()?;
572                }
573                return Err(error);
574            }
575        };
576        if owns {
577            self.commit_current()?;
578        }
579        Ok(id)
580    }
581
582    pub fn exists(&self, id: T) -> bool {
583        self.inner.link_exists(id)
584    }
585
586    pub fn search(&self, source: T, target: T) -> Option<T> {
587        self.inner.search_link(source, target)
588    }
589
590    pub fn get_or_create(&mut self, source: T, target: T) -> Result<T, LinkError> {
591        if let Some(existing) = self.inner.search_link(source, target) {
592            return Ok(existing);
593        }
594        self.create(source, target)
595    }
596
597    pub fn ensure_created(&mut self, id: T) -> Result<T, LinkError> {
598        if id == T::from_byte(0) || self.inner.link_exists(id) {
599            return Ok(id);
600        }
601        let names_before = self.inner.capture_names()?;
602        let owns = self.ensure_open_transaction()?;
603        let mut observed = Vec::new();
604        let outcome = self
605            .inner
606            .ensure_link_created_observed(id, &mut |before, after| {
607                record_observed(&mut observed, before, after)
608            });
609        self.record_observed_transitions(&observed, owns, names_before.as_ref())?;
610        match outcome {
611            Ok(created) => {
612                self.complete_image_observations(owns)?;
613                if owns {
614                    self.commit_current()?;
615                }
616                Ok(created)
617            }
618            Err(error) => {
619                self.fence_failed_image();
620                if owns {
621                    self.rollback()?;
622                }
623                Err(error)
624            }
625        }
626    }
627
628    /// Current state of `id` as a doublet, or an empty one at `id`.
629    fn snapshot(&self, id: T) -> GenericDoubletLink<T> {
630        let zero = T::from_byte(0);
631        self.inner
632            .get_link(id)
633            .map(|link| GenericDoubletLink::from_link(&link))
634            .unwrap_or_else(|| GenericDoubletLink::new(id, zero, zero))
635    }
636
637    pub(crate) fn ensure_write_allowed(&self) -> Result<(), LinkError> {
638        self.ensure_no_version_replay()?;
639        self.ensure_recovery_complete()?;
640        if self
641            .current
642            .as_ref()
643            .is_some_and(|pending| pending.commit_attempted)
644        {
645            return Err(LinkError::Transaction(
646                "Retry transaction commit before further writes; its outcome may be unknown."
647                    .into(),
648            ));
649        }
650        if self.current.as_ref().is_some_and(|tx| tx.rollback_only) {
651            return Err(LinkError::Transaction(
652                "Transaction requires rollback before further writes.".into(),
653            ));
654        }
655        Ok(())
656    }
657
658    fn ensure_open_transaction(&mut self) -> Result<bool, LinkError> {
659        self.ensure_write_allowed()?;
660        if self.sequence_counter == i64::MAX {
661            return Err(LinkError::Transaction(
662                "Transaction sequence space is exhausted.".into(),
663            ));
664        }
665        let owns = self.current.is_none();
666        if owns {
667            self.current = Some(PendingTransaction {
668                id: self.allocate_transaction_id(),
669                transitions: Vec::new(),
670                auto_commit: true,
671                rollback_only: false,
672                commit_attempted: false,
673                started_ms: now_unix_ms(),
674                image: None,
675            });
676        }
677        if let Err(error) = self.prepare_row_undo() {
678            self.current
679                .as_mut()
680                .expect("open transaction")
681                .rollback_only = true;
682            if owns {
683                self.rollback()?;
684            }
685            return Err(error);
686        }
687        Ok(owns)
688    }
689
690    fn write_marker(&mut self, name: &str) -> Result<(), LinkError> {
691        if name.starts_with(COMMIT_MARKER_PREFIX) || name.starts_with(ROLLBACK_MARKER_PREFIX) {
692            self.last_decision = Some(name.to_string());
693        }
694        self.append_journal_entry(name)
695    }
696
697    // ----- Transaction handle --------------------------------------------
698
699    fn allocate_transaction_id(&self) -> u128 {
700        // Realtime can repeat after restart while the process counter resets.
701        // Durable decisions outlive retained payloads, so consult the existing
702        // recovered indexes before assigning an ID to either kind of owner.
703        let mut collided = false;
704        loop {
705            let id = new_transaction_id();
706            if id != 0 && !self.committed.contains(&id) && !self.rolled_back.contains(&id) {
707                if collided && self.trace {
708                    crate::diagnostics::stderr!(
709                        "[Transactions] Skipped previously decided transaction IDs."
710                    );
711                }
712                return id;
713            }
714            collided = true;
715        }
716    }
717
718    pub fn begin_transaction(&mut self) -> Result<TransactionHandle, LinkError> {
719        self.ensure_no_version_replay()?;
720        self.ensure_recovery_complete()?;
721        if self.current.is_some() {
722            return Err(LinkError::Transaction(
723                "Nested transactions are not supported.".to_string(),
724            ));
725        }
726        let id = self.allocate_transaction_id();
727        let started_ms = now_unix_ms();
728        self.current = Some(PendingTransaction {
729            id,
730            transitions: Vec::new(),
731            auto_commit: false,
732            rollback_only: false,
733            commit_attempted: false,
734            started_ms,
735            image: None,
736        });
737        Ok(TransactionHandle { id, started_ms })
738    }
739
740    /// Finish the transaction. An append/flush error can have an unknown
741    /// outcome: retry commit, rollback or save to finish the attempted decision.
742    /// Further writes remain fenced until that work succeeds.
743    pub fn commit(&mut self) -> Result<(), LinkError> {
744        if self.recovery_pending {
745            return self.recover();
746        }
747        if self.current.is_none() {
748            return Ok(());
749        }
750        self.commit_current()
751    }
752
753    /// Undo an open transaction, or finish its attempted commit if a previous
754    /// commit failed with a possibly durable decision.
755    pub fn rollback(&mut self) -> Result<(), LinkError> {
756        if self.recovery_pending {
757            return self.recover();
758        }
759        if self
760            .current
761            .as_ref()
762            .is_some_and(|pending| pending.commit_attempted)
763        {
764            // A commit append/flush may have persisted before returning an error.
765            return self.commit_current();
766        }
767        // Once undo begins, an error can leave the data partially restored.
768        // Keep the abort decision until every rollback step succeeds.
769        if let Some(current) = self.current.as_mut() {
770            current.rollback_only = true;
771        }
772        let pending = match self.current.clone() {
773            Some(p) => p,
774            None => return Ok(()),
775        };
776        let result = if let Some(image) = &pending.image {
777            self.restore_image(image)
778        } else {
779            pending
780                .transitions
781                .iter()
782                .rev()
783                .try_for_each(|transition| self.try_revert_record(transition))
784        };
785        result?;
786        self.inner.flush()?;
787        self.write_marker(&format!("{ROLLBACK_MARKER_PREFIX}{:032x}", pending.id))?;
788        self.log_store.flush_log()?;
789        self.rolled_back.insert(pending.id);
790        self.current = None;
791        if self.trace {
792            crate::diagnostics::stderr!(
793                "[Transactions] Rolled back tx {:032x} ({} transitions).",
794                pending.id,
795                pending.transitions.len(),
796            );
797        }
798        self.enforce_retention()?;
799        Ok(())
800    }
801}
802
803/// Read paths that lend out references, available whenever the wrapped
804/// store keeps its links resident in memory.
805impl<T, S, L> GenericTransactionsDecorator<T, S, L>
806where
807    T: LinkReference,
808    S: LinksStorageRef<T>,
809    L: TransitionLogStore,
810{
811    pub fn get(&self, id: T) -> Option<&GenericLink<T>> {
812        self.inner.get_link_ref(id)
813    }
814
815    pub fn all(&self) -> Vec<&GenericLink<T>> {
816        self.inner.all_link_refs()
817    }
818
819    pub fn query(
820        &self,
821        index: Option<T>,
822        source: Option<T>,
823        target: Option<T>,
824    ) -> Vec<&GenericLink<T>> {
825        self.inner.query_link_refs(index, source, target)
826    }
827}
828
829// ----- Helpers ----------------------------------------------------------
830
831static TX_COUNTER: AtomicU64 = AtomicU64::new(0);
832
833fn new_transaction_id() -> u128 {
834    // Produce a candidate; journal ownership additionally excludes recovered
835    // decisions because this timestamp/counter pair can repeat after restart.
836    let count = TX_COUNTER.fetch_add(1, Ordering::Relaxed) as u128;
837    let now = now_unix_ms() as u128;
838    (now << 64) | count
839}
840
841fn now_unix_ms() -> i64 {
842    SystemTime::now()
843        .duration_since(UNIX_EPOCH)
844        .map(|d| d.as_millis() as i64)
845        .unwrap_or(0)
846}
847
848#[cfg(test)]
849mod contract_tests;
850#[cfg(test)]
851mod tests {
852    use super::*;
853
854    #[test]
855    fn retention_policy_parses_specs() {
856        assert!(matches!(
857            LogRetentionPolicy::parse("infinite").unwrap(),
858            LogRetentionPolicy::Infinite
859        ));
860        assert!(matches!(
861            LogRetentionPolicy::parse("sized:1000").unwrap(),
862            LogRetentionPolicy::Sized {
863                max_transitions: 1000
864            }
865        ));
866        assert!(matches!(
867            LogRetentionPolicy::parse("chunked:500:/tmp/x").unwrap(),
868            LogRetentionPolicy::Chunked { chunk_size: 500, archive_directory }
869                if archive_directory == Path::new("/tmp/x")
870        ));
871        assert!(LogRetentionPolicy::parse("garbage").is_err());
872    }
873
874    #[test]
875    fn transition_round_trips_through_serialize() {
876        let t = Transition {
877            transaction_id: 0xabcdef1234567890u128,
878            sequence: 42,
879            timestamp_ms: 1234567890,
880            kind: TransitionKind::Update,
881            before: DoubletLink::new(1, 2, 3),
882            after: DoubletLink::new(1, 4, 5),
883        };
884        let parsed = Transition::try_parse(&t.serialize()).unwrap();
885        assert_eq!(t, parsed);
886    }
887
888    #[test]
889    fn wide_transition_is_rejected_by_a_narrow_address_type() {
890        let wide = GenericTransition::<u64> {
891            transaction_id: 7,
892            sequence: 1,
893            timestamp_ms: 0,
894            kind: TransitionKind::Create,
895            before: GenericDoubletLink::empty(),
896            after: GenericDoubletLink::new(u32::MAX as u64 + 1, 0, 0),
897        };
898        assert!(matches!(
899            GenericTransition::<u32>::parse(&wide.serialize()),
900            Err(LinkError::AddressOutOfRange(_))
901        ));
902        assert!(GenericTransition::<u64>::parse(&wide.serialize()).is_ok());
903    }
904}