scrusted-yaml 0.2.0

Validates, loads and resolves scripted-yaml files: YAML with FEEL formulas in marked keys, reloaded live.
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
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
//! Live reload (SPEC 6): rule files change while the server runs. A change goes live only after
//! it passes every gate, in one atomic swap; a broken change is refused and the previous version
//! keeps serving.

use arc_swap::ArcSwap;
use scrusted_feel::Map;
use serde_reflection::{ContainerFormat, Format, Registry, Samples, Tracer, TracerConfig};
use std::collections::{BTreeMap, HashMap};
use std::io;
use std::path::PathBuf;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, Mutex, Weak};
use std::time::SystemTime;

use crate::api::AsVars;
use crate::files::{Files, Source};
use crate::problem::{Problem, Severity};
use crate::{Document, LoadError, ResolveError, ResolveOptions, ScrustedYaml, ShapeCheck, Value};

/// All live documents at one moment (SPEC 6.3).
pub struct Snapshot {
    /// Goes up by one at each published change.
    pub generation: u64,
    documents: BTreeMap<String, Document>,
    texts: BTreeMap<String, (String, String)>,
}

impl Snapshot {
    /// A document by name.
    pub fn document(&self, file: &str) -> Option<&Document> {
        self.documents.get(file)
    }

    /// The names of the files.
    pub fn files(&self) -> impl Iterator<Item = &str> {
        self.documents.keys().map(String::as_str)
    }

    /// Resolves one file of this snapshot.
    pub fn resolve(&self, file: &str, vars: &(impl AsVars + ?Sized), options: &ResolveOptions) -> Result<Value, ResolveError> {
        self.get(file)?.resolve(vars, options)
    }

    /// Resolves one file of this snapshot into a type.
    pub fn resolve_as<T: serde::de::DeserializeOwned>(
        &self,
        file: &str,
        vars: &(impl AsVars + ?Sized),
        options: &ResolveOptions,
    ) -> Result<T, ResolveError> {
        self.get(file)?.resolve_as(vars, options)
    }

    fn get(&self, file: &str) -> Result<&Document, ResolveError> {
        self.documents.get(file).ok_or_else(|| ResolveError {
            problems: vec![Problem {
                file: file.to_string(),
                line: 0,
                column: 0,
                key: String::new(),
                message: "no such file in the live set".into(),
                severity: Severity::Error,
            }],
        })
    }
}

/// What happened to a change (SPEC 6.4).
#[derive(Debug, Clone, PartialEq)]
pub enum ReloadEvent {
    /// The change went live.
    Reloaded {
        /// The new generation.
        generation: u64,
        /// The files that changed.
        files: Vec<String>,
    },
    /// The change was refused; the previous version keeps serving.
    Refused {
        /// The files that changed.
        files: Vec<String>,
        /// Why.
        problems: Vec<Problem>,
    },
}

/// A refused change of a file.
#[derive(Debug, Clone, PartialEq)]
pub struct Refusal {
    /// The version that was refused.
    pub version: String,
    /// When.
    pub at: SystemTime,
    /// Why.
    pub problems: Vec<Problem>,
}

/// The state of one file of the live set.
#[derive(Debug, Clone, PartialEq)]
pub struct FileStatus {
    /// Its name.
    pub file: String,
    /// The version that is live.
    pub version: String,
    /// When it went live.
    pub live_since: SystemTime,
    /// The last change that was refused, if it is not live since.
    pub refused: Option<Refusal>,
}

type Listener = Box<dyn Fn(&ReloadEvent) + Send + Sync>;

struct Inner {
    library: ScrustedYaml,
    source: Arc<dyn Files>,
    overlay: Arc<Overlay>,
    current: ArcSwap<Snapshot>,
    generation: AtomicU64,
    status: Mutex<BTreeMap<String, FileStatus>>,
    history: Mutex<HashMap<String, Vec<(String, String)>>>,
    listeners: Mutex<Vec<Listener>>,
    gate: Mutex<()>,
    stop: AtomicBool,
    watcher: Mutex<Option<Box<dyn std::any::Any + Send>>>,
}

/// A live set of documents: one atomic snapshot, reloaded through the gates (SPEC 6).
#[derive(Clone)]
pub struct Live {
    inner: Arc<Inner>,
}

/// Why a reload did not go live.
#[derive(Debug, Clone, PartialEq)]
pub struct Refused {
    /// The problems of the gates.
    pub problems: Vec<Problem>,
}

impl std::fmt::Display for Refused {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&crate::problem::error_text(&self.problems))
    }
}

impl std::error::Error for Refused {}

/// The application's files, with a file pinned to an earlier text after a rollback.
struct Overlay {
    source: Arc<dyn Files>,
    pinned: Mutex<HashMap<String, (String, String)>>,
}

impl Files for Overlay {
    fn read(&self, path: &str, from: Option<&str>) -> io::Result<Option<Source>> {
        let found = self.source.read(path, from)?;
        if let Some(found) = &found
            && let Some((text, _)) = self.pinned.lock().unwrap_or_else(|e| e.into_inner()).get(&found.name)
        {
            return Ok(Some(Source { name: found.name.clone(), text: text.clone() }));
        }
        Ok(found)
    }
    fn version(&self, name: &str) -> io::Result<Option<String>> {
        self.source.version(name)
    }
    fn list(&self) -> io::Result<Vec<String>> {
        self.source.list()
    }
    fn key(&self, name: &str) -> String {
        self.source.key(name)
    }
    fn watch_root(&self) -> Option<PathBuf> {
        self.source.watch_root()
    }
}

fn problem(file: &str, message: String) -> Problem {
    Problem { file: file.to_string(), line: 0, column: 0, key: String::new(), message, severity: Severity::Error }
}

impl ScrustedYaml {
    /// Loads every file of the source through the gates, then watches it (SPEC 6.1). A file that
    /// does not pass stops the boot.
    pub fn live(&self) -> Result<Live, LoadError> {
        let source = self.inner.files.clone();
        let overlay = Arc::new(Overlay { source: source.clone(), pinned: Mutex::new(HashMap::new()) });
        let mut library = self.clone();
        library.inner = Arc::new(crate::Library {
            files: overlay.clone(),
            markers: self.inner.markers.clone(),
            strict: self.inner.strict,
            live: self.inner.live.clone(),
        });
        let live = Live {
            inner: Arc::new(Inner {
                library,
                source,
                overlay,
                current: ArcSwap::from_pointee(Snapshot { generation: 0, documents: BTreeMap::new(), texts: BTreeMap::new() }),
                generation: AtomicU64::new(0),
                status: Mutex::new(BTreeMap::new()),
                history: Mutex::new(HashMap::new()),
                listeners: Mutex::new(Vec::new()),
                gate: Mutex::new(()),
                stop: AtomicBool::new(false),
                watcher: Mutex::new(None),
            }),
        };
        let (snapshot, _) = live.inner.build().map_err(|r| LoadError::Invalid(r.problems))?;
        live.inner.publish(snapshot, Vec::new());
        live.start_watching();
        Ok(live)
    }
}

impl Inner {
    /// Gates 1 to 6 for the whole set, as the source holds it now.
    fn build(&self) -> Result<(Snapshot, Vec<String>), Refused> {
        let names = self.source.list().map_err(|e| Refused { problems: vec![problem("", format!("cannot list the files: {e}"))] })?;
        let mut documents = BTreeMap::new();
        let mut texts = BTreeMap::new();
        let mut problems = Vec::new();
        let options = ResolveOptions::default();
        for name in &names {
            // gate 1: read
            let text = match self.overlay.read(name, None) {
                Ok(Some(found)) => found.text,
                Ok(None) => continue,
                Err(e) => {
                    problems.push(problem(name, e.to_string()));
                    continue;
                }
            };
            let version = self.source.version(name).ok().flatten().unwrap_or_default();
            texts.insert(name.clone(), (version, text.clone()));
            // gates 2 to 4: parse, validate, and every file is loaded again against the others
            match self.library.load_text(&text, name) {
                Ok(doc) => {
                    documents.insert(name.clone(), doc);
                }
                Err(LoadError::Invalid(found)) => problems.extend(found.into_iter().filter(|p| p.severity == Severity::Error)),
            }
        }
        if problems.is_empty() {
            let config = &self.library.inner.live;
            for (name, doc) in &documents {
                // gate 5: tests
                if config.run_tests {
                    for result in doc.test(&options) {
                        if !result.passed() {
                            problems.push(problem(name, format!("the test \"{}\" fails: {}", result.about, result.failures.join("; "))));
                        }
                    }
                }
                // gate 6: shape
                for (file, check) in &config.shapes {
                    if file == name {
                        let samples: Vec<Map> = config.samples.iter().filter(|(f, _)| f == name).map(|(_, v)| v.clone()).collect();
                        for why in check(doc, &samples, &options) {
                            problems.push(problem(name, why));
                        }
                    }
                }
            }
            for (file, _) in &config.shapes {
                if !documents.contains_key(file) {
                    problems.push(problem(file, "a file registered with .shape() is not in the live set".into()));
                }
            }
        }
        if !problems.is_empty() {
            return Err(Refused { problems });
        }
        let previous = self.current.load();
        let changed: Vec<String> =
            texts.iter().filter(|(n, (_, t))| previous.texts.get(*n).is_none_or(|(_, old)| old != t)).map(|(n, _)| n.clone()).collect();
        let removed: Vec<String> = previous.texts.keys().filter(|n| !texts.contains_key(*n)).cloned().collect();
        let generation = self.generation.load(Ordering::SeqCst) + 1;
        Ok((Snapshot { generation, documents, texts }, changed.into_iter().chain(removed).collect()))
    }

    /// Gate 7: one atomic pointer write.
    fn publish(&self, snapshot: Snapshot, changed: Vec<String>) {
        let now = SystemTime::now();
        {
            let mut status = self.status.lock().unwrap_or_else(|e| e.into_inner());
            let mut history = self.history.lock().unwrap_or_else(|e| e.into_inner());
            status.retain(|name, _| snapshot.texts.contains_key(name));
            for (name, (version, text)) in &snapshot.texts {
                let entry = status.entry(name.clone()).or_insert_with(|| FileStatus {
                    file: name.clone(),
                    version: version.clone(),
                    live_since: now,
                    refused: None,
                });
                if entry.version != *version || changed.contains(name) || entry.refused.is_some() {
                    if changed.contains(name) || entry.version != *version {
                        entry.live_since = now;
                    }
                    entry.version = version.clone();
                    entry.refused = None;
                }
                let versions = history.entry(name.clone()).or_default();
                if versions.last().is_none_or(|(_, t)| t != text) {
                    versions.push((version.clone(), text.clone()));
                    if versions.len() > 16 {
                        versions.remove(0);
                    }
                }
            }
        }
        let generation = snapshot.generation;
        self.generation.store(generation, Ordering::SeqCst);
        self.current.store(Arc::new(snapshot));
        if generation > 1 {
            self.emit(&ReloadEvent::Reloaded { generation, files: changed });
        }
    }

    fn refuse(&self, refused: &Refused, files: Vec<String>) {
        let now = SystemTime::now();
        {
            let mut status = self.status.lock().unwrap_or_else(|e| e.into_inner());
            for name in &files {
                let version = self.source.version(name).ok().flatten().unwrap_or_default();
                if let Some(s) = status.get_mut(name) {
                    s.refused = Some(Refusal { version, at: now, problems: refused.problems.clone() });
                }
            }
        }
        self.emit(&ReloadEvent::Refused { files, problems: refused.problems.clone() });
    }

    fn emit(&self, event: &ReloadEvent) {
        let listeners = self.listeners.lock().unwrap_or_else(|e| e.into_inner());
        if listeners.is_empty() {
            match event {
                ReloadEvent::Reloaded { generation, files } => tracing::info!(generation, ?files, "scrusted-yaml: reloaded"),
                ReloadEvent::Refused { files, problems } => {
                    tracing::error!(?files, problems = %crate::problem::error_text(problems), "scrusted-yaml: a change was refused")
                }
            }
        }
        for listener in listeners.iter() {
            listener(event);
        }
    }

    /// Reads everything again; publishes when something changed and every gate passes.
    fn reload(&self) -> Result<u64, Refused> {
        let _gate = self.gate.lock().unwrap_or_else(|e| e.into_inner());
        // a file pinned by a rollback is released when its source changes again
        {
            let mut pinned = self.overlay.pinned.lock().unwrap_or_else(|e| e.into_inner());
            pinned.retain(|name, (_, version)| self.source.version(name).ok().flatten().as_deref() == Some(version.as_str()));
        }
        match self.build() {
            Ok((snapshot, changed)) => {
                if changed.is_empty() {
                    return Ok(self.generation.load(Ordering::SeqCst));
                }
                let generation = snapshot.generation;
                self.publish(snapshot, changed);
                Ok(generation)
            }
            Err(refused) => {
                let current = self.current.load();
                let files: Vec<String> = self
                    .source
                    .list()
                    .unwrap_or_default()
                    .into_iter()
                    .filter(|n| {
                        let now = self.overlay.read(n, None).ok().flatten().map(|f| f.text);
                        current.texts.get(n).map(|(_, t)| t.clone()) != now
                    })
                    .collect();
                self.refuse(&refused, files);
                Err(refused)
            }
        }
    }

    /// True when a version of the source differs from the live one.
    fn changed(&self) -> bool {
        let current = self.current.load();
        let names = self.source.list().unwrap_or_default();
        if names.len() != current.texts.len() {
            return true;
        }
        names.iter().any(|n| current.texts.get(n).is_none_or(|(v, _)| self.source.version(n).ok().flatten().as_deref() != Some(v.as_str())))
    }
}

impl Live {
    /// The current snapshot: one atomic load.
    pub fn snapshot(&self) -> Arc<Snapshot> {
        self.inner.current.load_full()
    }

    /// The current generation.
    pub fn generation(&self) -> u64 {
        self.inner.generation.load(Ordering::SeqCst)
    }

    /// Resolves a file of the current snapshot.
    pub fn resolve(&self, file: &str, vars: &(impl AsVars + ?Sized), options: &ResolveOptions) -> Result<Value, ResolveError> {
        self.inner.current.load().resolve(file, vars, options)
    }

    /// Resolves a file of the current snapshot into a type.
    pub fn resolve_as<T: serde::de::DeserializeOwned>(
        &self,
        file: &str,
        vars: &(impl AsVars + ?Sized),
        options: &ResolveOptions,
    ) -> Result<T, ResolveError> {
        self.inner.current.load().resolve_as(file, vars, options)
    }

    /// Receives every reload and refusal. With no listener, they go to `tracing`.
    pub fn on_reload(&self, listener: impl Fn(&ReloadEvent) + Send + Sync + 'static) {
        self.inner.listeners.lock().unwrap_or_else(|e| e.into_inner()).push(Box::new(listener));
    }

    /// Per file: the live version, since when, and the last refused change.
    pub fn status(&self) -> Vec<FileStatus> {
        self.inner.status.lock().unwrap_or_else(|e| e.into_inner()).values().cloned().collect()
    }

    /// Re-reads everything now (for a deploy hook). The generation that serves after it.
    pub fn reload_now(&self) -> Result<u64, Refused> {
        self.inner.reload()
    }

    /// Publishes the previous good version of a file again, through the gates. It stays until the
    /// file changes in the source.
    pub fn rollback(&self, file: &str) -> Result<u64, Refused> {
        let previous = {
            let history = self.inner.history.lock().unwrap_or_else(|e| e.into_inner());
            let versions = history.get(file).cloned().unwrap_or_default();
            versions.len().checked_sub(2).and_then(|i| versions.get(i).cloned())
        };
        let Some((_, text)) = previous else {
            return Err(Refused { problems: vec![problem(file, "there is no previous version to go back to".into())] });
        };
        let version = self.inner.source.version(file).ok().flatten().unwrap_or_default();
        self.inner.overlay.pinned.lock().unwrap_or_else(|e| e.into_inner()).insert(file.to_string(), (text, version));
        let result = self.inner.reload();
        if result.is_err() {
            self.inner.overlay.pinned.lock().unwrap_or_else(|e| e.into_inner()).remove(file);
        }
        result
    }

    /// Stops watching and polling.
    pub fn stop(&self) {
        self.inner.stop.store(true, Ordering::SeqCst);
        *self.inner.watcher.lock().unwrap_or_else(|e| e.into_inner()) = None;
    }

    fn start_watching(&self) {
        let config = &self.inner.library.inner.live;
        let weak: Weak<Inner> = Arc::downgrade(&self.inner);
        if let Some(root) = self.inner.source.watch_root() {
            let handler = {
                let weak = weak.clone();
                move |result: notify_debouncer_full::DebounceEventResult| {
                    if let (Ok(events), Some(inner)) = (result, weak.upgrade())
                        && !events.is_empty()
                        && !inner.stop.load(Ordering::SeqCst)
                    {
                        let _ = inner.reload();
                    }
                }
            };
            match notify_debouncer_full::new_debouncer(config.debounce, None, handler) {
                Ok(mut debouncer) => match debouncer.watch(&root, notify_debouncer_full::notify::RecursiveMode::Recursive) {
                    Ok(()) => *self.inner.watcher.lock().unwrap_or_else(|e| e.into_inner()) = Some(Box::new(debouncer)),
                    Err(e) => tracing::error!(error = %e, "scrusted-yaml: cannot watch {}", root.display()),
                },
                Err(e) => tracing::error!(error = %e, "scrusted-yaml: cannot watch {}", root.display()),
            }
        }
        if let Some(every) = config.poll {
            std::thread::spawn(move || {
                loop {
                    std::thread::sleep(every);
                    let Some(inner) = weak.upgrade() else { return };
                    if inner.stop.load(Ordering::SeqCst) {
                        return;
                    }
                    if inner.changed() {
                        let _ = inner.reload();
                    }
                }
            });
        }
    }
}

impl Drop for Inner {
    fn drop(&mut self) {
        self.stop.store(true, Ordering::SeqCst);
    }
}

// ── gate 6: shapes ──

/// The fields a type requires: not `Option`, no `#[serde(default)]`. None when the type cannot be traced.
pub fn required_fields<T: serde::de::DeserializeOwned>() -> Option<Vec<String>> {
    let mut tracer = Tracer::new(TracerConfig::default());
    let samples = Samples::new();
    let (format, _) = tracer.trace_type::<T>(&samples).ok()?;
    let registry = tracer.registry().ok()?;
    let fields = match &format {
        Format::TypeName(name) => match registry.get(name)? {
            ContainerFormat::Struct(fields) => fields.clone(),
            _ => return None,
        },
        _ => return None,
    };
    let full: Map = fields.iter().map(|f| (f.name.as_str().into(), sample(&f.value, &registry, 0))).collect();
    let mut required = Vec::new();
    for field in &fields {
        if matches!(field.value, Format::Option(_)) {
            continue;
        }
        let mut without = full.clone();
        without.shift_remove(field.name.as_str());
        if scrusted_feel::serde_value::from_value::<T>(Value::from(without)).is_err() {
            required.push(field.name.clone());
        }
    }
    Some(required)
}

fn sample(format: &Format, registry: &Registry, depth: usize) -> Value {
    if depth > 8 {
        return Value::Null;
    }
    match format {
        Format::Bool => Value::Bool(false),
        Format::I8
        | Format::I16
        | Format::I32
        | Format::I64
        | Format::I128
        | Format::U8
        | Format::U16
        | Format::U32
        | Format::U64
        | Format::U128 => Value::from(0),
        Format::F32 | Format::F64 => Value::from(0),
        Format::Char => Value::from("a"),
        Format::Str => Value::from(""),
        Format::Option(_) | Format::Unit => Value::Null,
        Format::Seq(_) | Format::Tuple(_) | Format::TupleArray { .. } | Format::Bytes => Value::from(Vec::new()),
        Format::Map { .. } => Value::from(Map::new()),
        Format::TypeName(name) => match registry.get(name) {
            Some(ContainerFormat::Struct(fields)) => {
                Value::from(fields.iter().map(|f| (f.name.as_str().into(), sample(&f.value, registry, depth + 1))).collect::<Map>())
            }
            Some(ContainerFormat::NewTypeStruct(inner)) => sample(inner, registry, depth + 1),
            Some(ContainerFormat::Enum(variants)) => variants.values().next().map(|v| Value::from(v.name.as_str())).unwrap_or(Value::Null),
            _ => Value::Null,
        },
        Format::Variable(_) => Value::Null,
    }
}

/// The shape gate for `T` (SPEC 6.2, gate 6).
pub(crate) fn shape_check<T: serde::de::DeserializeOwned + 'static>() -> Arc<ShapeCheck> {
    let required = required_fields::<T>();
    let type_name = std::any::type_name::<T>();
    Arc::new(move |doc: &Document, samples: &[Map], options: &ResolveOptions| {
        let mut why = Vec::new();
        if let Some(required) = &required {
            let model = &doc.inner.model;
            let keys: Vec<String> = model.data().iter().map(|e| model.tree.entry(*e).key.name.to_string()).collect();
            for field in required {
                if !keys.contains(field) {
                    why.push(format!("{type_name} needs the key \"{field}\", which the file does not have"));
                }
            }
        }
        for (index, test) in doc.inner.model.tests().iter().enumerate() {
            let vars = test.as_map().and_then(|m| m.get("vars")).and_then(|v| v.as_map()).cloned().unwrap_or_default();
            if let Err(e) = doc.resolve_as::<T>(&vars, options) {
                why.push(format!("$tests entry {}: {}", index + 1, e.message()));
            }
        }
        for (index, vars) in samples.iter().enumerate() {
            if let Err(e) = doc.resolve_as::<T>(vars, options) {
                why.push(format!("sample {}: {}", index + 1, e.message()));
            }
        }
        why
    })
}