link-cli 3.0.1

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
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
//! Damaged journals: what `check_journal` reports, what `recover_journal`
//! keeps, and that a repaired file journal opens at the recovered revision.
use link_cli::engine::recovery::{check_journal, recover_journal};
use link_cli::engine::{Constraint, Engine, EngineOptions, MemoryLog, RevisionEncoding};
use link_cli::LinksStorage;

/// Revision k holds links 1..=k, each pointing at itself.
fn journal(commits: u64, encoding: RevisionEncoding) -> Vec<String> {
    let options = EngineOptions {
        revision_encoding: encoding,
        ..EngineOptions::default()
    };
    let db = Engine::<u64, _>::open(MemoryLog::default(), options).unwrap();
    for _ in 0..commits {
        let mut tx = db.begin().unwrap();
        let id = tx.create_link(0, 0).unwrap();
        tx.update_link(id, id, id).unwrap();
        tx.commit().unwrap();
    }
    db.into_log().ok().unwrap().entries
}

fn expected(revision: u64) -> Vec<(u64, u64, u64)> {
    (1..=revision).map(|id| (id, id, id)).collect()
}

#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
#[cfg_attr(not(target_arch = "wasm32"), test)]
fn an_intact_journal_reports_every_record() {
    for encoding in [RevisionEncoding::Snapshot, RevisionEncoding::Changes] {
        let entries = journal(4, encoding);
        let check = check_journal::<u64>(&entries, &EngineOptions::default());
        assert!(check.is_intact());
        assert_eq!(
            (check.valid_records, check.total_records, check.revision),
            (4, 4, 4)
        );
        assert_eq!(check.discarded_records(), 0);
    }
    let empty = check_journal::<u64>(&[], &EngineOptions::default());
    assert!(empty.is_intact());
    assert_eq!(empty.revision, 0);
}

#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
#[cfg_attr(not(target_arch = "wasm32"), test)]
fn damage_anywhere_keeps_exactly_the_records_before_it() {
    for encoding in [RevisionEncoding::Snapshot, RevisionEncoding::Changes] {
        let entries = journal(3, encoding);
        for record in 0..entries.len() {
            // Every bit that keeps the ASCII record valid UTF-8, including the
            // one that only changes the case of a checksum letter.
            let flips = (0..entries[record].len())
                .flat_map(|position| (0..7).map(move |bit| (position, 1u8 << bit)));
            for (position, mask) in flips {
                let mut damaged = entries.clone();
                let mut bytes = damaged[record].clone().into_bytes();
                bytes[position] ^= mask;
                damaged[record] = String::from_utf8(bytes).unwrap();
                let check = check_journal::<u64>(&damaged, &EngineOptions::default());
                let damage = check.damage.as_ref().unwrap_or_else(|| {
                    panic!("{encoding:?} flip {mask:#04x} at {record}:{position} went unnoticed")
                });
                assert_eq!(damage.record, record);
                assert_eq!(check.valid_records, record);
                assert_eq!(check.revision, record as u64);
                assert_eq!(check.discarded_records(), entries.len() - record);
                let recovery =
                    recover_journal::<u64>(&[damaged], &EngineOptions::default()).unwrap();
                let db = Engine::<u64, _>::open(
                    MemoryLog {
                        entries: recovery.entries,
                    },
                    EngineOptions::default(),
                )
                .unwrap();
                let links = db
                    .snapshot()
                    .unwrap()
                    .links()
                    .into_iter()
                    .map(|link| (link.index, link.source, link.target))
                    .collect::<Vec<_>>();
                assert_eq!(links, expected(record as u64));
            }
        }
    }
}

#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
#[cfg_attr(not(target_arch = "wasm32"), test)]
fn missing_reordered_and_foreign_records_end_the_valid_prefix() {
    let entries = journal(4, RevisionEncoding::Snapshot);
    let options = EngineOptions::default();
    let mut missing = entries.clone();
    missing.remove(1);
    let check = check_journal::<u64>(&missing, &options);
    assert_eq!((check.valid_records, check.revision), (1, 1));
    assert!(check.damage.unwrap().reason.contains("contiguous"));
    let mut swapped = entries.clone();
    swapped.swap(2, 3);
    assert_eq!(check_journal::<u64>(&swapped, &options).valid_records, 2);
    let mut foreign = entries.clone();
    foreign.insert(2, "not a journal record".into());
    let check = check_journal::<u64>(&foreign, &options);
    assert_eq!((check.valid_records, check.total_records), (2, 5));
    // A wider-address record is refused by a narrower reader, not truncated.
    let wide = Engine::<u64, _>::open(MemoryLog::default(), options.clone()).unwrap();
    let mut tx = wide.begin().unwrap();
    let id = tx.create_link(0, 0).unwrap();
    tx.update_link(id, u64::from(u32::MAX) + 1, id).unwrap();
    tx.commit().unwrap();
    drop(tx);
    let wide = wide.into_log().ok().unwrap().entries;
    let check = check_journal::<u32>(&wide, &options);
    assert_eq!(check.valid_records, 0);
    assert!(check_journal::<u64>(&wide, &options).is_intact());
}

#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
#[cfg_attr(not(target_arch = "wasm32"), test)]
fn selected_constraints_are_part_of_the_check() {
    let db = Engine::<u64, _>::open(MemoryLog::default(), EngineOptions::default()).unwrap();
    let mut tx = db.begin().unwrap();
    tx.create_link(5, 5).unwrap();
    tx.commit().unwrap();
    drop(tx);
    let entries = db.into_log().ok().unwrap().entries;
    assert!(check_journal::<u64>(&entries, &EngineOptions::default()).is_intact());
    let strict = EngineOptions {
        constraints: vec![Constraint::References],
        ..EngineOptions::default()
    };
    let check = check_journal::<u64>(&entries, &strict);
    assert_eq!(check.valid_records, 0);
    assert!(check.damage.unwrap().reason.contains("dangling"));
}

#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
#[cfg_attr(not(target_arch = "wasm32"), test)]
fn a_checkpoint_is_only_accepted_first() {
    let db = Engine::<u64, _>::open(
        MemoryLog {
            entries: journal(3, RevisionEncoding::Snapshot),
        },
        EngineOptions::default(),
    )
    .unwrap();
    let checkpoint = db.export_checkpoint().unwrap();
    assert!(checkpoint[0].starts_with("engine3|"));
    let check = check_journal::<u64>(&checkpoint, &EngineOptions::default());
    assert_eq!((check.valid_records, check.revision), (1, 3));
    let mut late = journal(3, RevisionEncoding::Snapshot);
    late.push(checkpoint[0].clone());
    assert_eq!(
        check_journal::<u64>(&late, &EngineOptions::default()).valid_records,
        3
    );
}

#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
#[cfg_attr(not(target_arch = "wasm32"), test)]
fn an_intact_copy_restores_what_the_damaged_one_lost() {
    let entries = journal(5, RevisionEncoding::Changes);
    let mut damaged = entries.clone();
    damaged[2].replace_range(10..12, "zz");
    let lagging = entries[..3].to_vec();
    let options = EngineOptions::default();
    let recovery = recover_journal::<u64>(
        &[damaged.clone(), lagging.clone(), entries.clone()],
        &options,
    )
    .unwrap();
    assert_eq!(recovery.source, 2);
    assert_eq!(recovery.revision, 5);
    assert_eq!(recovery.entries, entries);
    assert_eq!(
        recovery
            .checks
            .iter()
            .map(|check| check.valid_records)
            .collect::<Vec<_>>(),
        vec![2, 3, 5]
    );
    // Ties keep the earliest copy, normally the primary.
    let tie = recover_journal::<u64>(&[lagging.clone(), lagging], &options).unwrap();
    assert_eq!(tie.source, 0);
}

#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
#[cfg_attr(not(target_arch = "wasm32"), test)]
fn copies_that_disagree_are_refused() {
    let options = EngineOptions::default();
    let first = journal(3, RevisionEncoding::Snapshot);
    let other = {
        let db = Engine::<u64, _>::open(MemoryLog::default(), options.clone()).unwrap();
        for (source, target) in [(0, 0), (1, 1)] {
            let mut tx = db.begin().unwrap();
            tx.create_link(source, target).unwrap();
            tx.commit().unwrap();
        }
        db.into_log().ok().unwrap().entries
    };
    let error = recover_journal::<u64>(&[first, other], &options).unwrap_err();
    assert!(error.to_string().contains("diverge"), "{error}");
    let error = recover_journal::<u64>(&[], &options).unwrap_err();
    assert!(error.to_string().contains("at least one copy"), "{error}");
}

#[cfg(not(target_arch = "wasm32"))]
mod file {
    use super::*;
    use link_cli::engine::recovery::{read_journal_file_lossy, repair_journal_file};
    use link_cli::{FileTransitionLog, TransitionLogStore};
    use std::path::Path;

    fn write(path: &Path, entries: &[String]) {
        let mut text = String::new();
        for entry in entries {
            text.push_str(entry);
            text.push('\n');
        }
        std::fs::write(path, text).unwrap();
    }

    fn open_revision(path: &Path) -> u64 {
        let log = FileTransitionLog::open_exclusive(path).unwrap();
        let db = Engine::<u64, _>::open(log, EngineOptions::default()).unwrap();
        let snapshot = db.snapshot().unwrap();
        let links = snapshot
            .links()
            .into_iter()
            .map(|link| (link.index, link.source, link.target))
            .collect::<Vec<_>>();
        assert_eq!(links, expected(snapshot.revision));
        snapshot.revision
    }

    #[test]
    fn every_damaged_byte_of_a_file_is_repaired_to_its_valid_prefix() {
        let directory = tempfile::tempdir().unwrap();
        let path = directory.path().join("links.journal");
        let entries = journal(3, RevisionEncoding::Changes);
        write(&path, &entries);
        let pristine = std::fs::read(&path).unwrap();
        let mut starts = vec![0usize];
        for (index, byte) in pristine.iter().enumerate() {
            if *byte == b'\n' {
                starts.push(index + 1);
            }
        }
        for position in 0..pristine.len() {
            let mut bytes = pristine.clone();
            bytes[position] = if bytes[position] == 0xff { 0 } else { 0xff };
            std::fs::write(&path, &bytes).unwrap();
            // The final newline turns the last record into a torn tail, which
            // opening drops by design; every other byte is refused.
            if position + 1 < pristine.len() {
                let refused = FileTransitionLog::open(&path).and_then(|log| {
                    Engine::<u64, _>::open(log, EngineOptions::default()).map(|_| ())
                });
                assert!(refused.is_err(), "damage at {position} opened");
            }
            let repair = repair_journal_file::<u64>(&path, &[], &EngineOptions::default()).unwrap();
            let line = starts.iter().filter(|start| **start <= position).count() as u64 - 1;
            assert_eq!(repair.recovery.revision, line, "damage at {position}");
            assert!(repair.changed);
            let preserved = repair.preserved.unwrap();
            assert_eq!(std::fs::read(&preserved).unwrap(), bytes);
            std::fs::remove_file(preserved).unwrap();
            assert_eq!(open_revision(&path), line);
        }
    }

    #[test]
    fn a_replica_file_restores_the_lost_suffix_and_evidence_is_kept() {
        let directory = tempfile::tempdir().unwrap();
        let path = directory.path().join("primary.journal");
        let replica = directory.path().join("replica.journal");
        let entries = journal(4, RevisionEncoding::Snapshot);
        write(&path, &entries);
        write(&replica, &entries);
        // A zeroed block, as a lost page write leaves behind.
        let mut bytes = std::fs::read(&path).unwrap();
        let middle = bytes.len() / 2;
        bytes[middle..middle + 24].fill(0);
        std::fs::write(&path, &bytes).unwrap();
        let first =
            repair_journal_file::<u64>(&path, &[&replica], &EngineOptions::default()).unwrap();
        assert_eq!((first.recovery.source, first.recovery.revision), (1, 4));
        assert_eq!(
            first.preserved.as_deref(),
            Some(directory.path().join("primary.journal.damaged-1").as_path())
        );
        assert_eq!(open_revision(&path), 4);
        // A second damage does not overwrite the first evidence.
        std::fs::write(&path, b"garbage\n").unwrap();
        let second =
            repair_journal_file::<u64>(&path, &[&replica], &EngineOptions::default()).unwrap();
        assert_eq!(
            second.preserved.as_deref(),
            Some(directory.path().join("primary.journal.damaged-2").as_path())
        );
        assert_eq!(
            std::fs::read(directory.path().join("primary.journal.damaged-1")).unwrap(),
            bytes
        );
        // An intact journal is left alone.
        let again =
            repair_journal_file::<u64>(&path, &[&replica], &EngineOptions::default()).unwrap();
        assert!(!again.changed && again.preserved.is_none());
    }

    /// Power loss can persist the newline of a never-flushed record while a
    /// sector before it reads back as zeros. Trailing lines holding a NUL are
    /// therefore torn; a NUL in front of an intact record is still damage.
    #[test]
    fn trailing_lines_zeroed_by_power_loss_are_torn() {
        let directory = tempfile::tempdir().unwrap();
        let path = directory.path().join("links.journal");
        let entries = journal(4, RevisionEncoding::Snapshot);
        let intact = |count: usize| -> Vec<u8> {
            entries[..count]
                .iter()
                .flat_map(|entry| format!("{entry}\n").into_bytes())
                .collect()
        };
        let zeroed = |entry: &str| -> Vec<u8> {
            let mut bytes = entry.as_bytes().to_vec();
            let middle = bytes.len() / 2;
            bytes[middle..middle + 4].fill(0);
            bytes.push(b'\n');
            bytes
        };
        let cases: Vec<(Vec<u8>, u64)> = vec![
            // A zeroed hole in the last record, its newline kept.
            ([intact(3), zeroed(&entries[3])].concat(), 3),
            // Two trailing records with holes, a blank line between them.
            (
                [
                    intact(2),
                    zeroed(&entries[2]),
                    b"\n".to_vec(),
                    zeroed(&entries[3]),
                ]
                .concat(),
                2,
            ),
            // A record that is all zeros, then zeros past the last newline.
            (
                [intact(4), vec![0; 40], b"\n".to_vec(), vec![0; 7]].concat(),
                4,
            ),
            // Only zeroed lines.
            (
                [vec![0; 9], b"\n".to_vec(), zeroed(&entries[0])].concat(),
                0,
            ),
        ];
        for (bytes, revision) in cases {
            std::fs::write(&path, &bytes).unwrap();
            assert_eq!(
                read_journal_file_lossy(&path).unwrap(),
                entries[..revision as usize]
            );
            assert_eq!(open_revision(&path), revision);
            assert_eq!(std::fs::read(&path).unwrap(), intact(revision as usize));
            // The writer continues after the cut.
            let log = FileTransitionLog::open_exclusive(&path).unwrap();
            let db = Engine::<u64, _>::open(log, EngineOptions::default()).unwrap();
            let mut tx = db.begin().unwrap();
            let id = tx.create_link(0, 0).unwrap();
            tx.update_link(id, id, id).unwrap();
            tx.commit().unwrap();
            drop((tx, db));
            assert_eq!(open_revision(&path), revision + 1);
        }
        // A hole in front of an intact record is damage: opening refuses it,
        // the lossy reader keeps it for repair to judge.
        let bytes = [
            zeroed(&entries[0]),
            intact(2)[entries[0].len() + 1..].to_vec(),
        ]
        .concat();
        std::fs::write(&path, &bytes).unwrap();
        assert_eq!(read_journal_file_lossy(&path).unwrap().len(), 2);
        assert!(Engine::<u64, _>::open(
            FileTransitionLog::open_exclusive(&path).unwrap(),
            EngineOptions::default()
        )
        .is_err());
        assert_eq!(std::fs::read(&path).unwrap(), bytes, "damage is not cut");
        let repair = repair_journal_file::<u64>(&path, &[], &EngineOptions::default()).unwrap();
        assert_eq!(repair.recovery.revision, 0);
        // Appends refuse NUL, so a record can never end up holding one.
        let mut log = FileTransitionLog::open_exclusive(&path).unwrap();
        assert!(log.append_log_entry("a\0b").is_err());
    }

    #[test]
    fn torn_tails_invalid_utf8_and_missing_files_are_read_leniently() {
        let directory = tempfile::tempdir().unwrap();
        let path = directory.path().join("links.journal");
        assert!(read_journal_file_lossy(&path).unwrap().is_empty());
        let missing = repair_journal_file::<u64>(&path, &[], &EngineOptions::default()).unwrap();
        assert!(!missing.changed && missing.recovery.entries.is_empty());
        let entries = journal(2, RevisionEncoding::Snapshot);
        let mut bytes = Vec::new();
        bytes.extend_from_slice(entries[0].as_bytes());
        bytes.extend_from_slice(b"\n\n");
        bytes.extend_from_slice(entries[1].as_bytes());
        bytes.extend_from_slice(b"\n\xc3\x28 torn");
        std::fs::write(&path, &bytes).unwrap();
        assert_eq!(read_journal_file_lossy(&path).unwrap(), entries);
        let repair = repair_journal_file::<u64>(&path, &[], &EngineOptions::default()).unwrap();
        assert!(repair.recovery.checks[0].is_intact());
        assert!(repair.changed, "the blank line and torn tail are rewritten");
        assert_eq!(open_revision(&path), 2);
        // Invalid UTF-8 inside a complete record is damage, not a read error.
        let mut bytes = std::fs::read(&path).unwrap();
        bytes[entries[0].len() + 3] = 0xc3;
        std::fs::write(&path, &bytes).unwrap();
        assert!(FileTransitionLog::open(&path)
            .unwrap()
            .read_log_entries()
            .is_err());
        let repair = repair_journal_file::<u64>(&path, &[], &EngineOptions::default()).unwrap();
        assert_eq!(repair.recovery.revision, 1);
    }

    #[test]
    fn a_running_writer_blocks_repair() {
        let directory = tempfile::tempdir().unwrap();
        let path = directory.path().join("links.journal");
        let _writer = FileTransitionLog::open_exclusive(&path).unwrap();
        let error = repair_journal_file::<u64>(&path, &[], &EngineOptions::default()).unwrap_err();
        assert!(error.to_string().contains("busy"), "{error}");
    }

    #[test]
    fn divergent_file_copies_leave_the_journal_untouched() {
        let directory = tempfile::tempdir().unwrap();
        let path = directory.path().join("links.journal");
        let other = directory.path().join("other.journal");
        write(&path, &journal(2, RevisionEncoding::Snapshot));
        write(&other, &journal(2, RevisionEncoding::Changes));
        let before = std::fs::read(&path).unwrap();
        assert!(repair_journal_file::<u64>(&path, &[&other], &EngineOptions::default()).is_err());
        assert_eq!(std::fs::read(&path).unwrap(), before);
    }

    /// A replica whose extra records are damaged still holds more lines than
    /// the primary, so a writer keeps refusing: the primary's repair has
    /// nothing valid to add. Repairing the replica first drops its damaged
    /// tail, and the writer starts.
    #[test]
    fn a_replica_with_a_damaged_extra_record_is_repaired_before_the_primary() {
        use link_cli::engine::replication::{ReplicatedLog, Synchronization};
        let directory = tempfile::tempdir().unwrap();
        let path = directory.path().join("primary.journal");
        let replica = directory.path().join("replica.journal");
        let entries = journal(3, RevisionEncoding::Changes);
        write(&path, &entries[..2]);
        let mut damaged = entries.clone();
        damaged[2] = damaged[2].replacen('|', "#", 1);
        write(&replica, &damaged);
        let start = || {
            let log = ReplicatedLog::new(
                FileTransitionLog::open_exclusive(&path).unwrap(),
                vec![FileTransitionLog::open_exclusive(&replica).unwrap()],
                Synchronization::Synchronous {
                    acknowledgements: 2,
                },
            )
            .unwrap();
            Engine::<u64, _>::open(log, EngineOptions::default()).map(|db| db.snapshot().unwrap())
        };
        let refused = start().err().unwrap().to_string();
        assert!(
            refused.contains("holds 1 records the primary lacks"),
            "{refused}"
        );
        let primary =
            repair_journal_file::<u64>(&path, &[&replica], &EngineOptions::default()).unwrap();
        assert!(!primary.changed);
        assert!(start().is_err());
        let copy =
            repair_journal_file::<u64>(&replica, &[&path], &EngineOptions::default()).unwrap();
        assert_eq!((copy.changed, copy.recovery.revision), (true, 2));
        assert_eq!(start().unwrap().revision, 2);
    }
}