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
use super::*;
use std::sync::mpsc::Sender;
#[derive(Clone, Debug)]
pub struct Subscription {
active: bool,
pub event_stream_sender: Sender<EventStreamMessage>,
pub query: Query
}
impl Subscription {
pub fn new(sender: Sender<EventStreamMessage>, query: Query) -> Subscription {
Subscription {
active: true,
event_stream_sender: sender,
query: query
}
}
pub fn send(&mut self, event: Event) -> Result<(), DatabaseError> {
let event_id = event.id;
match self.event_stream_sender.send(EventStreamMessage::Event(event)) {
Ok(_) => {
self.query.update(event_id);
if !self.is_active() || !self.query.is_active() {
self.active = false;
match self.event_stream_sender.send(EventStreamMessage::End) {
Ok(_) => Ok(()),
Err(_) => Err(DatabaseError::EventStreamError(EventStreamError::Closed))
}
} else {
Ok(())
}
},
Err(_) => {
self.active = false;
Err(DatabaseError::EventStreamError(EventStreamError::Closed))
}
}
}
pub fn is_active(&self) -> bool {
self.active
}
pub fn matches_event(&self, event: &Event) -> bool {
self.is_active() && self.query.is_active() && self.query.matches(event)
}
}
#[cfg(test)]
mod tests {
use super::super::*;
use std::sync::mpsc::channel;
#[test]
fn test_simple_subscription() {
let (sender, receiver) = channel();
let event = Event::new("data", vec!["tag1", "tag2"]).with_id(1);
let mut subscription = Subscription::new(sender, Query::current());
assert!(subscription.send(event.clone()).is_ok());
assert_eq!(receiver.recv(), Ok(EventStreamMessage::Event(event.clone())));
assert_eq!(subscription.query.interval().start, 1);
assert!(subscription.is_active());
drop(receiver);
assert_eq!(subscription.send(event.clone()), Err(DatabaseError::EventStreamError(EventStreamError::Closed)));
assert_eq!(subscription.query.interval().start, 1);
assert!(!subscription.is_active());
}
#[test]
fn test_subscription_event_stream_end() {
let (sender, receiver) = channel();
let event = Event::new("data", vec!["tag1", "tag2"]).with_id(1);
let mut subscription = Subscription::new(sender, Query::current().limit(1));
assert!(subscription.send(event.clone()).is_ok());
assert_eq!(receiver.recv(), Ok(EventStreamMessage::Event(event.clone())));
assert_eq!(receiver.recv(), Ok(EventStreamMessage::End));
assert_eq!(subscription.query.interval().start, 1);
assert!(!subscription.is_active());
drop(receiver);
assert_eq!(subscription.send(event.clone()), Err(DatabaseError::EventStreamError(EventStreamError::Closed)));
assert_eq!(subscription.query.interval().start, 1);
assert!(!subscription.is_active());
}
}