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
use crate::routing_rules::{CloudEventFields, RoutingRules, RoutingTable};
use cerk::kernel::{BrokerEvent, Config, IncomingCloudEvent, OutgoingCloudEvent, RoutingResult};
use cerk::runtime::channel::{BoxedReceiver, BoxedSender};
use cerk::runtime::{InternalServerFn, InternalServerFnRefStatic, InternalServerId};
use cloudevents::{AttributesReader, Event};
use serde_json;
use serde_json::error::Error as SerdeErrorr;

fn compare_field<F>(field: &CloudEventFields, cloud_event: &Event, compare: F) -> bool
where
    F: for<'a> Fn(Option<&'a str>) -> bool,
{
    match field {
        CloudEventFields::Id => compare(Some(cloud_event.id())),
        CloudEventFields::Source => compare(Some(cloud_event.source().as_str())),
        CloudEventFields::Subject => cloud_event
            .subject()
            .and_then(|s| Some(compare(Some(s))))
            .unwrap_or_else(|| false),
        CloudEventFields::Dataschema => compare(cloud_event.dataschema().map(|s| s.as_str())),
        CloudEventFields::Type => compare(Some(cloud_event.ty())),
    }
}

fn route_to_port(rules: &RoutingRules, cloud_event: &Event) -> bool {
    match rules {
        RoutingRules::And(rules) => rules.iter().all(|rule| route_to_port(rule, cloud_event)),
        RoutingRules::Or(rules) => rules.iter().any(|rule| route_to_port(rule, cloud_event)),
        RoutingRules::Exact(field, value) => compare_field(field, cloud_event, |field| {
            field == value.as_ref().map(|s| &**s)
        }),
        RoutingRules::Contains(field, value) => compare_field(field, cloud_event, |field| {
            field.map_or(false, |f| f.contains(value.as_str()))
        }),
        RoutingRules::StartsWith(field, value) => compare_field(field, cloud_event, |field| {
            field.map_or(false, |f| f.starts_with(value.as_str()))
        }),
        RoutingRules::EndsWith(field, value) => compare_field(field, cloud_event, |field| {
            field.map_or(false, |f| f.ends_with(value.as_str()))
        }),
    }
}

fn route_event(
    event: IncomingCloudEvent,
    sender_to_kernel: &BoxedSender,
    port_config: &RoutingTable,
) {
    let IncomingCloudEvent {
        cloud_event,
        routing_id,
        incoming_id,
        args,
    } = event;
    let routing: Vec<_> = port_config
        .iter()
        .filter(|(_, rules)| route_to_port(rules, &cloud_event))
        .map(|(port_id, _)| OutgoingCloudEvent {
            routing_id: routing_id.clone(),
            cloud_event: cloud_event.clone(),
            destination_id: port_id.clone(),
            args: args.clone(),
        })
        .collect();
    sender_to_kernel.send(BrokerEvent::RoutingResult(RoutingResult {
        routing_id,
        incoming_id,
        routing,
        args,
    }))
}

fn parse_config(config_update: String) -> Result<RoutingTable, SerdeErrorr> {
    serde_json::from_str::<RoutingTable>(&config_update)
}

/// This is the main function to start the router.
pub fn router_start(id: InternalServerId, inbox: BoxedReceiver, sender_to_kernel: BoxedSender) {
    info!("start broadcast router with id {}", id);
    let mut config: Option<RoutingTable> = None;
    loop {
        match inbox.receive() {
            BrokerEvent::Init => info!("{} initiated", id),
            BrokerEvent::IncomingCloudEvent(event) => {
                if let Some(config) = config.as_ref() {
                    route_event(event, &sender_to_kernel, config);
                } else {
                    error!("No configs defined yet, event will be droped");
                }
            }
            BrokerEvent::ConfigUpdated(updated_config, _) => {
                if let Config::String(string_config) = updated_config {
                    match parse_config(string_config) {
                        Ok(parsed_config) => config = Some(parsed_config),
                        Err(err) => panic!("was not able to parse configs {:?}", err),
                    }
                }
            }
            broker_event => warn!("event {} not implemented", broker_event),
        }
    }
}

/// This is the pointer for the main function to start the router.
pub static ROUTER_RULE_BASED: InternalServerFnRefStatic = &(router_start as InternalServerFn);

#[cfg(test)]
mod tests {
    use super::*;
    use crate::routing_rules::{CloudEventFields, RoutingRules};
    use cloudevents::{EventBuilder, EventBuilderV10};

    #[test]
    fn rout_to_port_by_id() {
        let rule = RoutingRules::Exact(CloudEventFields::Id, Some("1234".to_string()));
        // positive
        assert!(route_to_port(
            &rule,
            &EventBuilderV10::new()
                .id("1234")
                .ty("test type")
                .source("http://example.com/testi")
                .build()
                .unwrap(),
        ));
        // negative
        assert!(!route_to_port(
            &rule,
            &EventBuilderV10::new()
                .id("12345")
                .ty("test type")
                .source("http://example.com/testi")
                .build()
                .unwrap(),
        ));
    }

    #[test]
    fn rout_to_port_by_type_and_source() {
        let rule = RoutingRules::And(vec![
            RoutingRules::StartsWith(CloudEventFields::Type, "testtype".to_string()),
            RoutingRules::Contains(CloudEventFields::Source, "testsource".to_string()),
        ]);
        // positive
        assert!(route_to_port(
            &rule,
            &EventBuilderV10::new()
                .id("1")
                .ty("testtype1")
                .source("http://example.com/1testsource1")
                .build()
                .unwrap(),
        ));
        // negative
        // positive
        assert!(!route_to_port(
            &rule,
            &EventBuilderV10::new()
                .id("1")
                .ty("1testtype")
                .source("http://example.com/1test1source1")
                .build()
                .unwrap(),
        ));
    }
}