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
use std::collections::BTreeMap;

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

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

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

impl Drop for Validation {
    fn drop(&mut self) {
        if !self.0.is_empty() {
            println!("Dropping `Validation` with unhandled validation errors:");

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

            panic!();
        }
    }
}

impl State for Validation {
    type Command = ObjectToInsert;
    type Event = ValidationEvent;

    fn decide(&self, command: Self::Command, events: &mut Vec<Self::Event>) {
        let err = command.object.validate().err();
        events.push(ValidationEvent {
            object: command.object.into(),
            err,
        });
    }

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

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

    /// The validation error, if the validation resulted in one
    ///
    /// If this is `None`, the object has been validated successfully.
    pub err: Option<ValidationError>,
}