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
use std::marker::PhantomData;

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Attribute {
    key: String,
    value: String,
}

impl Attribute {
    pub fn new(key: String, value: String) -> Self {
        Self { key, value }
    }
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub enum EventType {
    Message,
    Custom(String),
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Event {
    tpe: EventType,
    attributes: Vec<Attribute>,
}

impl Event {
    pub fn new(tpe: EventType, attrs: Vec<(String, String)>) -> Self {
        Self {
            tpe,
            attributes: attrs
                .into_iter()
                .map(|(k, v)| Attribute::new(k, v))
                .collect(),
        }
    }
}

pub type HandlerResult<T, E> = Result<HandlerOutput<T>, E>;

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct HandlerOutput<T> {
    pub result: T,
    pub log: Vec<String>,
    pub events: Vec<Event>,
}

impl<T> HandlerOutput<T> {
    pub fn builder() -> HandlerOutputBuilder<T> {
        HandlerOutputBuilder::new()
    }
}

#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct HandlerOutputBuilder<T> {
    log: Vec<String>,
    events: Vec<Event>,
    marker: PhantomData<T>,
}

impl<T> HandlerOutputBuilder<T> {
    pub fn new() -> Self {
        Self {
            log: vec![],
            events: vec![],
            marker: PhantomData,
        }
    }

    pub fn with_log(mut self, log: impl Into<Vec<String>>) -> Self {
        self.log.append(&mut log.into());
        self
    }

    pub fn log(&mut self, log: impl Into<String>) {
        self.log.push(log.into());
    }

    pub fn with_events(mut self, events: impl Into<Vec<Event>>) -> Self {
        self.events.append(&mut events.into());
        self
    }

    pub fn emit(&mut self, event: impl Into<Event>) {
        self.events.push(event.into());
    }

    pub fn with_result(self, result: T) -> HandlerOutput<T> {
        HandlerOutput {
            result,
            log: self.log,
            events: self.events,
        }
    }
}