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
use crate::config::Config;
use crate::destination::routed_destination::{MessageRoutingBehaviour, RoutedDestination};
use crate::destination::message_condition::MessageCondition;
use crate::message::Message;
use crate::send_error::{SendError, SendErrors};
use serde::{Serialize, Deserialize};
use crate::send_error::borrowed::SendErrorBorrowed;
use crate::send_error::owned::SendErrorOwned;
use crate::send_error::reported::{ErrorReportSummary, ReportedSendError};

pub struct MessageRouter {
    destinations: Vec<Box<dyn RoutedDestination>>,
}

impl MessageRouter {
    pub fn empty() -> Self {
        Self {
            destinations: vec![],
        }
    }

    pub fn from_config(config: Config) -> Self {
        let destinations = config.take_destinations().into_iter()
            .map(|item| {
                let boxed: Box<dyn RoutedDestination> = Box::new(item);
                boxed
            })
            .collect();

        Self {
            destinations,
        }
    }

    pub fn add_destination(&mut self, destination: Box<dyn RoutedDestination>) {
        self.destinations.push(destination)
    }

    pub fn route<'a>(&self, message: &'a Message) -> Result<usize, SendErrors<'a>> {
        let mut errors: Vec<SendErrorBorrowed<'a>> = vec![];

        let mut sent_to_non_root_dest = false;

        let mut successful = 0;

        fn send_wrap<'a>(destination: &dyn RoutedDestination, message: &'a Message) -> Result<(), SendErrorBorrowed<'a>> {
            destination.send(message).map_err(|err| {
                SendErrorBorrowed::create(err, destination.get_id().to_owned(), message)
            })
        }

        fn send_to_dest<'a>(dest: &dyn RoutedDestination,
                            sent_to_non_root_dest: &mut bool,
                            successful: &mut usize,
                            errors: &mut Vec<SendErrorBorrowed<'a>>,
                            message: &'a Message) {
            match send_wrap(dest, message) {
                Ok(()) => {
                    if !dest.is_root() {
                        *sent_to_non_root_dest = true;
                    }
                    *successful += 1;
                }
                Err(send_err) => errors.push(send_err),
            }
        }

        for dest in self.destinations.iter()
            .filter(|dest| dest.get_routing_type().always_send_messages())
            .filter(|dest| dest.should_receive(message)) {

            send_to_dest(dest.as_ref(), &mut sent_to_non_root_dest, &mut successful, &mut errors, message);
        }

        if !sent_to_non_root_dest {
            // Find a drain.
            for dest in self.destinations.iter()
                .filter(|dest| dest.get_routing_type() == &MessageRoutingBehaviour::Drain)
                .filter(|dest| dest.should_receive(message)) {

                send_to_dest(dest.as_ref(), &mut sent_to_non_root_dest, &mut successful, &mut errors, message);
            }
        }

        if errors.is_empty() {
            return Ok(successful);
        }

        let root_destinations: Vec<_> = self.destinations.iter()
            .filter(|dest| dest.is_root())
            .map(|dest| dest.to_owned())
            .collect();

        let reported_errors = errors.into_iter().map(|error| {
            let report_message = error.create_report_message();
            let mut any_report_success = false;
            let mut report_fails = vec![];

            for root_dest in &root_destinations {
                match root_dest.send(&report_message) {
                    Ok(_) => {
                        any_report_success = true;
                    }
                    Err(send_err) => {
                        let send_err = SendErrorOwned::create(send_err, root_dest.get_id().to_owned(), report_message.clone());
                        report_fails.push(send_err);
                    }
                }
            }

            ReportedSendError::new(error, ErrorReportSummary::new(any_report_success, report_fails))
        }).collect();


        Err(SendErrors::new(message, reported_errors, successful))
    }

}

impl Default for MessageRouter {
    fn default() -> Self {
        Self::empty()
    }
}

/// Controls whether a Message should be sent to a destination.
///
/// It does this through two "filters"
/// - [`MessageRoutingBehaviour`]
/// - A list of [`MessageCondition`]s
///
/// # [`MessageRoutingBehaviour`] #
/// This filter is interdependent with the where the message has already be sent.
/// See the documentation for it for more details.
///
/// # [`MessageCondition`]s #
/// If none specified, all messages are allowed.
/// Otherwise it acts like a whitelist.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
pub struct RoutingInfo {
    // Whether errors with sending notifications will be reported to this destination.
    #[serde(default)]
    routing_type: MessageRoutingBehaviour,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    whitelist: Vec<MessageCondition>,
}

impl RoutingInfo {
    pub fn of(routing_type: MessageRoutingBehaviour) -> Self {
        Self {
            routing_type,
            whitelist: vec![]
        }
    }

    pub fn root() -> Self {
        Self::of(MessageRoutingBehaviour::Root)
    }

    pub fn get_routing_behaviour(&self) -> &MessageRoutingBehaviour {
        &self.routing_type
    }

    pub fn applies_to(&self, message: &Message) -> bool {
        if self.whitelist.is_empty() {
            return true;
        }
        self.whitelist.iter()
            .any(|condition| condition.matches(message))
    }
}