link-cli 3.3.2

A CLI tool and reusable library for links manipulation backed by a LiNo-notation doublet storage engine.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
//! Optional staged links engine: concurrency, immutable history, and a
//! replaceable commit log. See `docs/ENGINE-STRATEGIES.md` for costs and limits.
//!
//! Unlike the legacy undo decorator, no underlying mapped data is modified
//! while a transaction is open. A checksummed logical revision is flushed
//! before it becomes visible. The log is the authoritative storage.
#[cfg(feature = "address-reservations")]
pub mod address_allocator;
#[cfg(feature = "author-fencing")]
pub mod author_fence;
#[cfg(not(target_arch = "wasm32"))]
mod background_compaction;
#[cfg(test)]
mod boundary_tests;
mod branch;
#[cfg(feature = "causal")]
pub mod causal;
#[cfg(feature = "causal-batches")]
pub mod causal_batch;
#[cfg(feature = "causal-merkle")]
pub mod causal_merkle;
#[cfg(feature = "causal-sessions")]
pub mod causal_named;
#[cfg(feature = "causal-projection")]
pub mod causal_projection;
#[cfg(feature = "causal")]
pub mod causal_replica;
#[cfg(feature = "causal-sessions")]
pub mod causal_session;
mod changes;
mod checkpoint;
pub mod cluster;
mod commit;
#[cfg(test)]
mod constraint_cost_tests;
mod constraint_index;
#[cfg(test)]
mod cost_tests;
mod delta;
#[cfg(feature = "etcd")]
pub mod etcd;
mod group;
mod journal;
#[cfg(feature = "physical-lsm")]
pub mod lsm;
pub mod maintenance;
mod named;
mod object_cache;
pub mod paged;
pub mod partitioned;
mod pessimistic;
mod query_reservation;
mod query_scratch;
pub mod raft;
pub mod reclaiming;
pub mod recovery;
pub mod replication;
mod rows;
mod savepoint;
#[cfg(test)]
mod shared_cost_tests;
mod sorted_runs;
#[cfg(all(feature = "sqlite", not(target_arch = "wasm32")))]
pub mod sqlite;
mod timed_log;
mod transaction;
mod validation;

use crate::{GenericLink, LinkError, TransitionLogStore};
use doublets::data::LinkReference;
use std::collections::BTreeMap;
use std::sync::{Arc, Mutex, MutexGuard};

#[cfg(not(target_arch = "wasm32"))]
pub use background_compaction::BackgroundCompaction;
pub use branch::Branch;
pub use checkpoint::restore_backup;
pub use delta::DeltaLog;
pub use group::GroupCommitOutcome;
pub use journal::MemoryLog;
use rows::Rows;
pub use savepoint::Savepoint;
pub use timed_log::{revision_at, TimedLog};
pub use transaction::EngineTransaction;
pub use validation::SerializableValidation;

/// In-memory revision representation, independent of durability and isolation.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum StateStructure {
    /// Clone complete sorted rows for each changed revision (the existing path).
    #[default]
    Flat,
    /// Share immutable entries and path-copy an ordered tree for changed rows.
    Shared,
    /// Share immutable sorted runs; merge occupied event-count tiers on writes.
    SortedRuns,
}

/// Logical journal payload, independent of the physical log's encoding.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum RevisionEncoding {
    /// Existing complete engine1 revisions.
    #[default]
    Snapshot,
    /// Canonical engine2 changed-row records bound to the preceding revision.
    Changes,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ConcurrencyControl {
    #[default]
    Optimistic,
    /// A second transaction fails immediately rather than blocking indefinitely.
    Exclusive,
    /// Reserve written addresses until session end; competing writes fail fast
    /// unless `lock_wait` is selected.
    Pessimistic,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum IsolationLevel {
    ReadCommitted,
    Snapshot,
    /// Serializable commits; whole-revision validation is the default strategy.
    #[default]
    Serializable,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum HistoryPolicy {
    #[default]
    None,
    /// Includes the current revision; active transactions pin their own snapshot.
    Last(usize),
    All,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Constraint {
    /// Every nonzero source/target must reference a row in the committed state.
    References,
    /// Reject duplicate source/target pairs instead of silently merging them.
    UniquePairs,
    UniqueNames,
}

/// Constraint maintenance, independent of concurrency and serializable reads.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ConstraintValidation {
    /// Scan the complete candidate; no retained constraint indexes.
    #[default]
    Scan,
    /// Retain immutable indexes only for selected constraints; update changed rows.
    Indexed,
}

#[derive(Debug, Clone, Default)]
pub struct EngineOptions {
    pub state_structure: StateStructure,
    pub revision_encoding: RevisionEncoding,
    pub concurrency: ConcurrencyControl,
    /// How long a pessimistic write waits for another session's address, instead
    /// of failing at once. Native only: a wasm32 thread cannot wait for another.
    pub lock_wait: Option<std::time::Duration>,
    pub isolation: IsolationLevel,
    pub serializable_validation: SerializableValidation,
    pub history: HistoryPolicy,
    pub constraints: Vec<Constraint>,
    pub constraint_validation: ConstraintValidation,
    pub trace: bool,
    /// Reject volatile or unknown log adapters, rather than claiming durability.
    pub require_durable_flush: bool,
}

impl EngineOptions {
    fn tracks_generations(&self) -> bool {
        self.concurrency == ConcurrencyControl::Pessimistic
            || (self.concurrency == ConcurrencyControl::Optimistic
                && (self.isolation != IsolationLevel::Serializable
                    || self.serializable_validation == SerializableValidation::ReadSet))
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Row<T> {
    pub link: GenericLink<T>,
    pub name: Option<String>,
}

/// Immutable revision, safe to keep after history retention or transaction end.
#[derive(Debug, Clone)]
pub struct Snapshot<T> {
    pub revision: u64,
    rows: Arc<Rows<T>>,
}
impl<T: LinkReference> Snapshot<T> {
    pub fn links(&self) -> Vec<GenericLink<T>> {
        self.rows.values().map(|row| row.link).collect()
    }
    pub fn get(&self, id: T) -> Option<&Row<T>> {
        self.rows.get(&id)
    }
    /// Legacy sorted-map view. Shared snapshots lazily copy O(N) rows/names on
    /// the first call; snapshot clones share that cache. Prefer `iter` or `get`.
    pub fn rows(&self) -> &BTreeMap<T, Row<T>> {
        self.rows.materialize()
    }
    /// Sorted borrowed rows without materializing the legacy BTreeMap view.
    pub fn iter(&self) -> impl Iterator<Item = (&T, &Row<T>)> {
        self.rows.iter()
    }
}

struct State<T, L> {
    log: L,
    current: Snapshot<T>,
    history: BTreeMap<u64, (Snapshot<T>, u128)>,
    changed: BTreeMap<T, u64>,
    write_owners: BTreeMap<T, Arc<()>>,
    lock_waits: Option<pessimistic::LockWaits>,
    next: u128,
    committed_next: u128,
    active: usize,
    poisoned: bool,
    /// The revision the last compaction published, for `compact_journal_after`.
    compacted_revision: u64,
    options: EngineOptions,
    constraint_index: Option<constraint_index::ConstraintIndex<T>>,
}

/// Share clones of this handle across threads. All writes must use its sessions;
/// opening multiple independent writers on the same log is not supported.
pub struct Engine<T, L> {
    state: Arc<Mutex<State<T, L>>>,
}
impl<T, L> Clone for Engine<T, L> {
    fn clone(&self) -> Self {
        Self {
            state: self.state.clone(),
        }
    }
}

fn error(message: &str) -> LinkError {
    LinkError::Transaction(message.into())
}

impl<T: LinkReference, L: TransitionLogStore> Engine<T, L> {
    pub fn open(mut log: L, options: EngineOptions) -> Result<Self, LinkError> {
        if options.serializable_validation == SerializableValidation::ReadSet
            && options.isolation != IsolationLevel::Serializable
        {
            return Err(error("read-set validation requires serializable isolation"));
        }
        if options.lock_wait.is_some() && options.concurrency != ConcurrencyControl::Pessimistic {
            return Err(error("lock waiting requires pessimistic concurrency"));
        }
        if options.require_durable_flush && !log.supports_durable_flush() {
            return Err(error("selected log does not support durable flush"));
        }
        if options.history == HistoryPolicy::Last(0) {
            return Err(error("history limit must be positive"));
        }
        let entries = log.read_log_entries()?;
        let mut state = State::empty(log, options);
        for (index, entry) in entries.iter().enumerate() {
            state.replay(index, entry)?;
        }
        // No transaction predates open, so recovered rows need no conflict
        // generations. Track only changes made while a session can be stale.
        if state.options.constraint_validation == ConstraintValidation::Indexed {
            state.constraint_index = constraint_index::ConstraintIndex::build(
                &state.options.constraints,
                &state.current.rows,
            )?;
        }
        Ok(Self {
            state: Arc::new(Mutex::new(state)),
        })
    }

    fn lock(&self) -> Result<MutexGuard<'_, State<T, L>>, LinkError> {
        let state = self
            .state
            .lock()
            .map_err(|_| error("engine mutex poisoned"))?;
        if state.poisoned {
            return Err(error(
                "indeterminate journal outcome; close and reopen before continuing",
            ));
        }
        Ok(state)
    }
    pub fn snapshot(&self) -> Result<Snapshot<T>, LinkError> {
        Ok(self.lock()?.current.clone())
    }
    pub fn snapshot_at(&self, revision: u64) -> Result<Snapshot<T>, LinkError> {
        let state = self.lock()?;
        if revision == state.current.revision {
            return Ok(state.current.clone());
        }
        state
            .history
            .get(&revision)
            .map(|(snapshot, _)| snapshot.clone())
            .ok_or_else(|| error("revision is not retained"))
    }
    pub fn begin(&self) -> Result<EngineTransaction<T, L>, LinkError> {
        let mut state = self.lock()?;
        if state.options.concurrency == ConcurrencyControl::Exclusive && state.active > 0 {
            return Err(error("busy: an exclusive transaction is active"));
        }
        state.active += 1;
        Ok(EngineTransaction {
            engine: self.clone(),
            base: state.current.clone(),
            writes: BTreeMap::new(),
            savepoints: Vec::new(),
            reserved: std::collections::VecDeque::new(),
            closed: false,
            isolation: state.options.isolation,
            reads: (state.options.serializable_validation == SerializableValidation::ReadSet
                && state.options.concurrency != ConcurrencyControl::Exclusive)
                .then(|| Mutex::new(validation::ReadSet::default())),
            locks: (state.options.concurrency == ConcurrencyControl::Pessimistic)
                .then(pessimistic::WriteLocks::default),
        })
    }
    /// Run a caller's replication/catch-up/diagnostics operation under the same
    /// mutex as commits. An error poisons the engine because its outcome may be unknown.
    pub fn with_log<R>(
        &self,
        operation: impl FnOnce(&mut L) -> Result<R, LinkError>,
    ) -> Result<R, LinkError> {
        let mut state = self.lock()?;
        match operation(&mut state.log) {
            Ok(result) => Ok(result),
            Err(error) => {
                state.poisoned = true;
                Err(error)
            }
        }
    }
    /// Extract the authoritative log once every other handle/session is dropped.
    pub fn into_log(self) -> Result<L, Self> {
        match Arc::try_unwrap(self.state) {
            Ok(mutex) => Ok(mutex
                .into_inner()
                .unwrap_or_else(|poison| poison.into_inner())
                .log),
            Err(state) => Err(Self { state }),
        }
    }
}

impl<T: LinkReference, L> State<T, L> {
    /// Revision zero, before any record is replayed.
    fn empty(log: L, options: EngineOptions) -> Self {
        let mut state = State {
            current: Snapshot {
                revision: 0,
                rows: Arc::new(Rows::new(options.state_structure)),
            },
            history: BTreeMap::new(),
            changed: BTreeMap::new(),
            write_owners: BTreeMap::new(),
            lock_waits: options.lock_wait.map(pessimistic::LockWaits::new),
            next: 1,
            committed_next: 1,
            active: 0,
            poisoned: false,
            compacted_revision: 0,
            options,
            constraint_index: None,
            log,
        };
        state.retain();
        state
    }
    /// Apply one recovered record with every rule `Engine::open` enforces.
    /// Only a first record may be an engine3 checkpoint.
    fn replay(&mut self, index: usize, entry: &str) -> Result<(), LinkError> {
        let (snapshot, next) = if index == 0 && entry.starts_with("engine3|") {
            let decoded = journal::decode_checkpoint(entry, self.options.state_structure)?;
            self.history.clear();
            decoded
        } else {
            journal::decode_after(
                entry,
                &self.current,
                self.next,
                self.options.state_structure,
            )?
        };
        self.validate(&snapshot.rows)?;
        self.next = next;
        self.committed_next = next;
        self.current = snapshot;
        self.retain();
        Ok(())
    }
    fn retain(&mut self) {
        match self.options.history {
            HistoryPolicy::None => {}
            HistoryPolicy::All => {
                self.history.insert(
                    self.current.revision,
                    (self.current.clone(), self.committed_next),
                );
            }
            HistoryPolicy::Last(limit) => {
                self.history.insert(
                    self.current.revision,
                    (self.current.clone(), self.committed_next),
                );
                while self.history.len() > limit {
                    self.history.pop_first();
                }
            }
        }
    }
    fn validate(&self, rows: &Rows<T>) -> Result<(), LinkError> {
        let zero = T::from_byte(0);
        for constraint in &self.options.constraints {
            match constraint {
                Constraint::References => {
                    for row in rows.values() {
                        if [row.link.source, row.link.target]
                            .iter()
                            .any(|id| *id != zero && !rows.contains_key(id))
                        {
                            return Err(error("constraint: dangling link reference"));
                        }
                    }
                }
                Constraint::UniquePairs => {
                    let mut pairs = std::collections::BTreeSet::new();
                    for row in rows.values() {
                        if !pairs.insert((row.link.source, row.link.target)) {
                            return Err(error("constraint: duplicate pair"));
                        }
                    }
                }
                Constraint::UniqueNames => {
                    let mut names = std::collections::BTreeSet::new();
                    for name in rows.values().filter_map(|row| row.name.as_ref()) {
                        if !names.insert(name) {
                            return Err(error("constraint: duplicate name"));
                        }
                    }
                }
            }
        }
        Ok(())
    }
}