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