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
172
173
174
175
176
177
178
179
180
181
182
183
use std::collections::HashMap;
use std::fmt::{Debug, Formatter, Result as FmtResult};
use tokio::sync::mpsc::{channel, Receiver, Sender};
use tracing::*;
use crate::proto::ReadFrom;
use crate::zookeeper::RawResponse;
use crate::{KeeperState, WatchedEventType};
#[derive(Clone, Debug)]
pub struct WatchedEvent {
pub event_type: WatchedEventType,
pub keeper_state: KeeperState,
pub path: Option<String>,
}
#[derive(Debug, PartialEq)]
pub enum WatchType {
Child,
Data,
Exist,
}
pub struct Watch {
pub path: String,
pub watch_type: WatchType,
pub watcher: Box<dyn FnOnce(WatchedEvent) + Send>,
}
impl Debug for Watch {
fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
f.debug_struct("Watch")
.field("path", &self.path)
.field("watch_type", &self.watch_type)
.finish()
}
}
pub trait Watcher: Send {
fn handle(&self, event: WatchedEvent);
}
impl<F> Watcher for F
where
F: Fn(WatchedEvent) + Send,
{
fn handle(&self, event: WatchedEvent) {
self(event)
}
}
#[derive(Debug)]
pub enum WatchMessage {
Event(RawResponse),
Watch(Watch),
}
pub struct ZkWatch<W: Watcher> {
watcher: W,
watches: HashMap<String, Vec<Watch>>,
chroot: Option<String>,
tx: Sender<WatchMessage>,
rx: Receiver<WatchMessage>,
}
impl<W: Watcher> ZkWatch<W> {
pub fn new(watcher: W, chroot: Option<String>) -> Self {
trace!("ZkWatch::new");
let (tx, rx) = channel(64);
ZkWatch {
watches: HashMap::new(),
watcher,
chroot,
tx,
rx,
}
}
pub fn sender(&self) -> Sender<WatchMessage> {
self.tx.clone()
}
pub async fn run(mut self) {
while let Some(msg) = self.rx.recv().await {
self.process_message(msg);
}
}
fn process_message(&mut self, message: WatchMessage) {
match message {
WatchMessage::Event(response) => {
info!("Event thread got response {:?}", response.header);
let mut data = response.data;
match response.header.err {
0 => match WatchedEvent::read_from(&mut data) {
Ok(mut event) => {
self.cut_chroot(&mut event);
self.dispatch(&event);
}
Err(e) => error!("Failed to parse WatchedEvent {:?}", e),
},
e => error!("WatchedEvent.error {:?}", e),
}
}
WatchMessage::Watch(watch) => {
self.watches
.entry(watch.path.clone())
.or_insert(vec![])
.push(watch);
}
}
}
fn cut_chroot(&self, event: &mut WatchedEvent) {
if let Some(ref chroot) = self.chroot {
if event.path.is_some() {
event.path = Some(event.path.as_ref().unwrap()[chroot.len()..].to_owned());
}
}
}
fn dispatch(&mut self, event: &WatchedEvent) {
debug!("{:?}", event);
if let Some(watches) = self.find_watches(&event) {
for watch in watches.into_iter() {
(watch.watcher)(event.clone())
}
} else {
self.watcher.handle(event.clone())
}
}
fn find_watches(&mut self, event: &WatchedEvent) -> Option<Vec<Watch>> {
if let Some(ref path) = event.path {
match self.watches.remove(path) {
Some(watches) => {
let (matching, left): (_, Vec<Watch>) =
watches.into_iter().partition(|w| match event.event_type {
WatchedEventType::NodeChildrenChanged => {
w.watch_type == WatchType::Child
}
WatchedEventType::NodeCreated | WatchedEventType::NodeDataChanged => {
w.watch_type == WatchType::Data || w.watch_type == WatchType::Exist
}
WatchedEventType::NodeDeleted => true,
_ => false,
});
if !left.is_empty() {
self.watches.insert(path.to_owned(), left);
}
if matching.is_empty() {
None
} else {
Some(matching)
}
}
None => None,
}
} else {
None
}
}
}