stratum-node-config 0.1.0-alpha.4

Versioned stratum.toml schema, comment-preserving editor, semantic validator, change preview and public-config hash for Stratum nodes
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
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
//! Property test for the list editor's comment ownership.
//!
//! The test builds an array from a model that records who owns each comment,
//! independently of the crate, renders it as TOML, applies two random edits
//! in a row through [`preview`], and checks each result against the model:
//!
//! - the edited array parses to exactly the requested values;
//! - every comment owned by a surviving element appears exactly once, its
//!   head lines directly above it in order and its line comment on its own
//!   line after it;
//! - every comment owned by a removed element is absent;
//! - the array's own comments (the `[` line, the lines before `]`, and the
//!   comment after `]`) appear exactly once and in place;
//! - no comment is duplicated, merged with another comment, or placed on a
//!   line where it would read as another element's;
//! - a document written with CRLF line endings (half the cases) keeps CRLF
//!   on every line, and an LF document gains no carriage return.
//!
//! Ownership follows the documented model: the `k`-th occurrence of a value
//! in the new list takes the `k`-th occurrence in the old one, with its
//! comments. The second edit is judged against the ownership carried through
//! the first, which catches a comment that drifts to another element.

use std::collections::{HashMap, VecDeque};
use std::fmt::Write as _;

use proptest::prelude::*;
use stratum_node_config::{preview, Change, Value};

const PATH: &str = "backup.age_recipients";
const PREFIX: &str = "schema_version = 1\n[backup]\nage_recipients = ";

/// Values come from a small alphabet so duplicates are common.
fn alphabet() -> impl Strategy<Value = String> {
    (0u8..5).prop_map(|i| format!("v{i}"))
}

/// One element as generated: its value, how many comment lines sit above
/// it, whether a comment ends its line, and whether it shares a line with
/// the previous element (or with the `[`).
#[derive(Debug, Clone)]
struct GenElement {
    value: String,
    heads: usize,
    tail: bool,
    same_line: bool,
}

/// Whether the generated array is written on one line, with no comments
/// inside, or across lines.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Layout {
    SingleLine,
    Multiline,
}

#[derive(Debug, Clone)]
struct GenArray {
    layout: Layout,
    indent: &'static str,
    opening: bool,
    elements: Vec<GenElement>,
    closing: usize,
    trailing_comma: bool,
    outer: bool,
    endings: Endings,
}

/// The line ending the generated document is written with.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Endings {
    Lf,
    CrLf,
}

fn gen_element() -> impl Strategy<Value = GenElement> {
    (alphabet(), 0usize..3, any::<bool>(), any::<bool>()).prop_map(
        |(value, heads, tail, same_line)| GenElement {
            value,
            heads,
            tail,
            same_line,
        },
    )
}

fn gen_array() -> impl Strategy<Value = GenArray> {
    (
        any::<bool>(),
        prop_oneof![Just("  "), Just("    "), Just("\t")],
        any::<bool>(),
        prop_oneof![
            1 => Just(0usize..1),
            4 => Just(1usize..6),
        ]
        .prop_flat_map(|n| proptest::collection::vec(gen_element(), n)),
        0usize..3,
        any::<bool>(),
        any::<bool>(),
        prop_oneof![Just(Endings::Lf), Just(Endings::CrLf)],
    )
        .prop_map(
            |(
                single_line,
                indent,
                opening,
                mut elements,
                closing,
                trailing_comma,
                outer,
                endings,
            )| {
                // Make the generated layout well formed: a comment ends its
                // line, so the next element cannot share it, and head lines
                // start a line, so an element with heads cannot share one.
                for i in 0..elements.len() {
                    let previous_ends_line = if i == 0 {
                        opening
                    } else {
                        elements[i - 1].tail
                    };
                    let e = &mut elements[i];
                    if single_line {
                        e.heads = 0;
                        e.tail = false;
                        e.same_line = true;
                    } else if e.heads > 0 || previous_ends_line {
                        e.same_line = false;
                    }
                }
                GenArray {
                    layout: if single_line {
                        Layout::SingleLine
                    } else {
                        Layout::Multiline
                    },
                    indent,
                    opening: opening && !single_line,
                    elements,
                    closing: if single_line { 0 } else { closing },
                    trailing_comma,
                    outer,
                    endings,
                }
            },
        )
}

/// An element of the model: its value and the comment tokens it owns.
#[derive(Debug, Clone, PartialEq, Eq)]
struct Owned {
    value: String,
    heads: Vec<String>,
    tail: Option<String>,
}

/// The ownership model of a rendered array.
#[derive(Debug, Clone)]
struct Model {
    opening: Option<String>,
    elements: Vec<Owned>,
    closing: Vec<String>,
    outer: Option<String>,
}

impl Model {
    /// Applies a new list: the k-th occurrence of a value takes the k-th
    /// old occurrence and its comments; new elements own nothing.
    fn edit(&self, list: &[String]) -> Self {
        let mut queues: HashMap<&str, VecDeque<&Owned>> = HashMap::new();
        for e in &self.elements {
            queues.entry(e.value.as_str()).or_default().push_back(e);
        }
        let elements = list
            .iter()
            .map(|v| {
                queues
                    .get_mut(v.as_str())
                    .and_then(VecDeque::pop_front)
                    .cloned()
                    .unwrap_or_else(|| Owned {
                        value: v.clone(),
                        heads: Vec::new(),
                        tail: None,
                    })
            })
            .collect();
        Self {
            elements,
            ..self.clone()
        }
    }

    fn values(&self) -> Vec<String> {
        self.elements.iter().map(|e| e.value.clone()).collect()
    }

    fn tokens(&self) -> Vec<&str> {
        let mut all: Vec<&str> = self.opening.iter().map(String::as_str).collect();
        for e in &self.elements {
            all.extend(e.heads.iter().map(String::as_str));
            all.extend(e.tail.iter().map(String::as_str));
        }
        all.extend(self.closing.iter().map(String::as_str));
        all.extend(self.outer.iter().map(String::as_str));
        all
    }
}

/// Renders the generated array as a document and returns it with its model.
fn render(g: &GenArray) -> (String, Model) {
    let mut next = 0;
    let mut token = || {
        next += 1;
        format!("c{next}")
    };
    let mut out = String::from(PREFIX);
    out.push('[');
    let opening = g.opening.then(&mut token);
    if let Some(t) = &opening {
        let _ = write!(out, " # {t}");
    }
    let first_same_line = g.elements.first().is_some_and(|e| e.same_line);
    if !(g.layout == Layout::SingleLine) && !first_same_line {
        out.push('\n');
    }
    let mut elements = Vec::new();
    let n = g.elements.len();
    for (i, e) in g.elements.iter().enumerate() {
        let heads: Vec<String> = (0..e.heads).map(|_| token()).collect();
        if e.same_line {
            if i > 0 {
                out.push(' ');
            }
        } else {
            for h in &heads {
                let _ = writeln!(out, "{}# {h}", g.indent);
            }
            out.push_str(g.indent);
        }
        let _ = write!(out, "{:?}", e.value);
        if i + 1 < n || g.trailing_comma {
            out.push(',');
        }
        let tail = e.tail.then(&mut token);
        if let Some(t) = &tail {
            let _ = write!(out, " # {t}");
        }
        let next_shares = g.elements.get(i + 1).is_some_and(|x| x.same_line);
        if !(g.layout == Layout::SingleLine) && !next_shares {
            out.push('\n');
        }
        elements.push(Owned {
            value: e.value.clone(),
            heads,
            tail,
        });
    }
    let closing: Vec<String> = (0..g.closing).map(|_| token()).collect();
    for c in &closing {
        let _ = writeln!(out, "{}# {c}", g.indent);
    }
    out.push(']');
    let outer = g.outer.then(&mut token);
    if let Some(t) = &outer {
        let _ = write!(out, " # {t}");
    }
    out.push('\n');
    (
        out,
        Model {
            opening,
            elements,
            closing,
            outer,
        },
    )
}

/// A line of the array text: the values on it, whether it holds `[` or `]`
/// outside a string, and its comment.
#[derive(Debug)]
struct Line {
    values: Vec<String>,
    open: bool,
    close: bool,
    comment: Option<String>,
}

impl Line {
    fn comment_only(&self) -> bool {
        self.values.is_empty() && !self.open && !self.close && self.comment.is_some()
    }
}

fn scan(array_text: &str) -> Result<Vec<Line>, TestCaseError> {
    let mut lines = Vec::new();
    for raw in array_text.lines() {
        let (code, comment) = match raw.find('#') {
            Some(i) => (&raw[..i], Some(raw[i + 1..].trim().to_owned())),
            None => (raw, None),
        };
        if let Some(c) = &comment {
            prop_assert!(
                c.starts_with('c') && c[1..].chars().all(|ch| ch.is_ascii_digit()),
                "merged or malformed comment {c:?} in line {raw:?}"
            );
        }
        let parts: Vec<&str> = code.split('"').collect();
        prop_assert!(parts.len() % 2 == 1, "unbalanced quotes in {raw:?}");
        let values = parts
            .iter()
            .skip(1)
            .step_by(2)
            .map(|s| (*s).to_owned())
            .collect();
        let outside: String = parts.iter().step_by(2).copied().collect();
        lines.push(Line {
            values,
            open: outside.contains('['),
            close: outside.contains(']'),
            comment,
        });
    }
    Ok(lines)
}

/// The run of comment-only lines directly above line `at`, top to bottom.
fn comments_above(lines: &[Line], at: usize) -> Vec<String> {
    let mut run = Vec::new();
    let mut i = at;
    while i > 0 && lines[i - 1].comment_only() {
        i -= 1;
        run.push(lines[i].comment.clone().unwrap_or_default());
    }
    run.reverse();
    run
}

/// Checks that every line break of `text` has the generated ending, then
/// checks the LF form of `text` against `model`.
fn check_with_endings(text: &str, model: &Model, endings: Endings) -> Result<(), TestCaseError> {
    if endings == Endings::CrLf {
        prop_assert!(
            !text.replace("\r\n", "").contains('\n'),
            "a line break of a CRLF document is not CRLF: {text:?}"
        );
        check(&text.replace("\r\n", "\n"), model)
    } else {
        prop_assert!(
            !text.contains('\r'),
            "an LF document gained a carriage return: {text:?}"
        );
        check(text, model)
    }
}

/// Checks the edited document `text` against `model`.
fn check(text: &str, model: &Model) -> Result<(), TestCaseError> {
    prop_assert!(
        text.starts_with(PREFIX),
        "text before the array changed: {text:?}"
    );
    let doc: toml_edit::DocumentMut = text
        .parse()
        .map_err(|e| TestCaseError::fail(format!("does not parse: {e}\n{text}")))?;
    let parsed: Vec<String> = doc["backup"]["age_recipients"]
        .as_array()
        .ok_or_else(|| TestCaseError::fail("not an array"))?
        .iter()
        .map(|v| v.as_str().unwrap_or("<non-string>").to_owned())
        .collect();
    prop_assert_eq!(&parsed, &model.values(), "parsed values\n{}", text);

    let array_text = &text[PREFIX.len()..];
    let lines = scan(array_text)?;

    // Each comment appears exactly once, and only the expected ones appear.
    let mut seen: Vec<&str> = lines.iter().filter_map(|l| l.comment.as_deref()).collect();
    let mut want = model.tokens();
    seen.sort_unstable();
    want.sort_unstable();
    prop_assert_eq!(seen, want, "comment set\n{}", text);

    check_elements(text, &lines, model)?;
    check_array_comments(text, &lines, model)
}

/// Each element's value order, line comment and head lines.
fn check_elements(text: &str, lines: &[Line], model: &Model) -> Result<(), TestCaseError> {
    // Position of every value in reading order.
    let positions: Vec<(usize, usize, usize)> = lines
        .iter()
        .enumerate()
        .flat_map(|(li, l)| (0..l.values.len()).map(move |k| (li, k, l.values.len())))
        .collect();
    prop_assert_eq!(
        positions.len(),
        model.elements.len(),
        "value count\n{}",
        text
    );

    for (e, &(li, k, on_line)) in model.elements.iter().zip(&positions) {
        let line = &lines[li];
        prop_assert_eq!(&line.values[k], &e.value, "value order\n{}", text);
        let last_on_line = k + 1 == on_line;
        let line_comment = line
            .comment
            .as_deref()
            .filter(|c| Some(*c) != model.outer.as_deref());
        match &e.tail {
            Some(t) => {
                prop_assert!(
                    last_on_line,
                    "{} is not last on the line of {t}\n{text}",
                    e.value
                );
                prop_assert_eq!(
                    line_comment,
                    Some(t.as_str()),
                    "tail of {}\n{}",
                    e.value,
                    text
                );
            }
            None if last_on_line => {
                prop_assert_eq!(line_comment, None, "{} gained a comment\n{}", e.value, text);
            }
            None => {}
        }
        let first_on_line = k == 0;
        if first_on_line {
            prop_assert_eq!(
                &comments_above(lines, li),
                &e.heads,
                "heads of {}\n{}",
                e.value,
                text
            );
        } else {
            prop_assert!(
                e.heads.is_empty(),
                "{} has heads but shares a line\n{text}",
                e.value
            );
        }
    }

    Ok(())
}

/// The `[` line, the comments before `]` and the comment after it.
fn check_array_comments(text: &str, lines: &[Line], model: &Model) -> Result<(), TestCaseError> {
    let open_line = lines.iter().position(|l| l.open);
    prop_assert_eq!(open_line, Some(0), "[ line\n{}", text);
    if let Some(t) = &model.opening {
        prop_assert_eq!(
            lines[0].comment.as_deref(),
            Some(t.as_str()),
            "opening\n{}",
            text
        );
        prop_assert!(
            lines[0].values.is_empty(),
            "value on the opening line\n{text}"
        );
    }
    let close_line = lines
        .iter()
        .position(|l| l.close)
        .ok_or_else(|| TestCaseError::fail("no ]"))?;
    prop_assert_eq!(
        &comments_above(lines, close_line),
        &model.closing,
        "closing\n{}",
        text
    );
    if let Some(t) = &model.outer {
        prop_assert_eq!(
            lines[close_line].comment.as_deref(),
            Some(t.as_str()),
            "outer\n{}",
            text
        );
    }
    Ok(())
}

/// A random edit of `old`: insert, remove, reorder, clear, replace, fill or
/// an arbitrary new list.
fn edit_of(old: Vec<String>) -> BoxedStrategy<Vec<String>> {
    let n = old.len();
    let mut arms: Vec<BoxedStrategy<Vec<String>>> = vec![
        Just(old.clone()).prop_shuffle().boxed(),
        Just(Vec::new()).boxed(),
        proptest::collection::vec(alphabet(), 0..7).boxed(),
        {
            let old = old.clone();
            (0..=n, alphabet())
                .prop_map(move |(i, v)| {
                    let mut l = old.clone();
                    l.insert(i, v);
                    l
                })
                .boxed()
        },
        Just(old.clone()).boxed(),
    ];
    if n > 0 {
        let o = old.clone();
        arms.push(
            (0..n)
                .prop_map(move |i| {
                    let mut l = o.clone();
                    l.remove(i);
                    l
                })
                .boxed(),
        );
        let o = old.clone();
        arms.push(
            (0..n, alphabet())
                .prop_map(move |(i, v)| {
                    let mut l = o.clone();
                    l[i] = v;
                    l
                })
                .boxed(),
        );
        let o = old;
        arms.push(
            proptest::sample::subsequence((0..n).collect::<Vec<_>>(), 0..=n)
                .prop_shuffle()
                .prop_map(move |idx| idx.iter().map(|&i| o[i].clone()).collect())
                .boxed(),
        );
    }
    proptest::strategy::Union::new(arms).boxed()
}

fn case() -> impl Strategy<Value = (GenArray, Vec<String>, Vec<String>)> {
    gen_array().prop_flat_map(|g| {
        let old: Vec<String> = g.elements.iter().map(|e| e.value.clone()).collect();
        (Just(g), edit_of(old)).prop_flat_map(|(g, first)| {
            let second = edit_of(first.clone());
            (Just(g), Just(first), second)
        })
    })
}

fn apply(text: &str, list: &[String]) -> Result<String, TestCaseError> {
    let p = preview(text, &[Change::new(PATH, Value::from(list.to_vec()))])
        .map_err(|e| TestCaseError::fail(format!("preview failed: {e}\n{text}")))?;
    Ok(p.text().to_owned())
}

proptest! {
    #![proptest_config(ProptestConfig::with_cases(2048))]

    #[test]
    fn list_edits_keep_every_comment_with_its_owner((g, first, second) in case()) {
        let (lf_base, model) = render(&g);
        let base = if g.endings == Endings::CrLf { lf_base.replace('\n', "\r\n") } else { lf_base };
        check_with_endings(&base, &model, g.endings)?;

        let text1 = apply(&base, &first)?;
        let model1 = model.edit(&first);
        check_with_endings(&text1, &model1, g.endings)?;
        if first == model.values() {
            prop_assert_eq!(&text1, &base, "unchanged list must be byte-identical");
        }

        let text2 = apply(&text1, &second)?;
        let model2 = model1.edit(&second);
        check_with_endings(&text2, &model2, g.endings)?;
        if second == first {
            prop_assert_eq!(&text2, &text1, "unchanged list must be byte-identical");
        }
    }
}