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
use std::{collections::BTreeMap, thread};

use crate::{
    objects::{BehindHandle, Object},
    storage::ObjectId,
    validate::ValidationError,
};

use super::{objects::InsertObject, State};

/// Errors that occurred while validating the objects inserted into the stores
#[derive(Default)]
pub struct Validation(pub BTreeMap<ObjectId, ValidationFailed>);

impl Drop for Validation {
    fn drop(&mut self) {
        let num_errors = self.0.len();
        if num_errors > 0 {
            println!(
                "Dropping `Validation` with {num_errors} unhandled validation \
                errors:"
            );

            for event in self.0.values() {
                println!("{}", event.err);
            }

            if !thread::panicking() {
                panic!();
            }
        }
    }
}

impl State for Validation {
    type Command = InsertObject;
    type Event = ValidationFailed;

    fn decide(&self, command: Self::Command, events: &mut Vec<Self::Event>) {
        let mut errors = Vec::new();
        command.object.validate(&mut errors);

        for err in errors {
            events.push(ValidationFailed {
                object: command.object.clone().into(),
                err,
            });
        }
    }

    fn evolve(&mut self, event: &Self::Event) {
        self.0.insert(event.object.id(), event.clone());
    }
}

/// An event produced by the validation service
#[derive(Clone)]
pub struct ValidationFailed {
    /// The object for which validation failed
    pub object: Object<BehindHandle>,

    /// The validation error
    pub err: ValidationError,
}