This repository has been archived by the owner on Dec 6, 2021. It is now read-only.
/
sub.rs
194 lines (158 loc) · 5.9 KB
/
sub.rs
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
184
185
186
187
188
189
190
191
192
193
194
use std::collections::HashMap;
use std::net::SocketAddr;
use std::{fmt, io};
use futures::{Future, Poll, Async, AsyncSink, Stream, Sink};
use log::{error, warn};
use meilies::resp::RespMsgError;
use meilies::reqresp::{Request, RequestMsgError, Response, ResponseMsgError};
use meilies::stream::{Stream as EsStream, StreamName};
use tokio::sync::mpsc;
use futures::stream::SplitStream;
use tokio_retry::RetryIf;
use super::{connect, retry_strategy, must_retry, SteelConnection};
#[derive(Default)]
struct StreamContext {
reconnected: bool,
position: Option<u64>,
}
pub struct EventStream {
state: HashMap<StreamName, StreamContext>,
connection: SteelConnection,
}
impl EventStream {
fn connect(addr: SocketAddr) -> impl Future<Item=EventStream, Error=tokio_retry::Error<io::Error>> {
RetryIf::spawn(retry_strategy(), move || {
warn!("Connecting to {}", addr);
connect(&addr)
.map(move |connection| {
let connection = SteelConnection::new(addr, connection);
EventStream { state: HashMap::new(), connection }
})
}, must_retry)
}
fn send_stream_subscriptions(&mut self) -> Result<(), ProtocolError> {
// Now that a new connection has been successfully established
// we can re-send our subscriptions with the appropriate event number.
let mut streams = Vec::with_capacity(self.state.len());
for (name, context) in &mut self.state {
context.reconnected = true;
let stream = EsStream { name: name.clone(), from: context.position.into() };
streams.push(stream);
}
let subscription = Request::Subscribe { streams };
self.start_send(subscription)?;
self.poll_complete()?;
Ok(())
}
}
impl Stream for EventStream {
type Item = Result<Response, String>;
type Error = ProtocolError;
fn poll(&mut self) -> Result<Async<Option<Self::Item>>, Self::Error> {
let result = match self.connection.poll() {
Ok(Async::Ready(Some(item))) => {
match &item {
Ok(Response::Event { stream, number, .. }) => {
self.state.entry(stream.clone()).or_default().position = Some(number.0 + 1);
},
Ok(Response::Subscribed { stream }) => {
// if we were already subscribed to a stream and we are reconnecting
// we do not return the message validating a subscription to the user
if self.state.get(&stream).map_or(false, |c| c.reconnected) {
return self.poll();
}
},
_otherwise => (),
}
Ok(Async::Ready(Some(item)))
},
otherwise => otherwise,
};
if self.connection.has_been_reconnected() {
self.send_stream_subscriptions()?;
}
result.map_err(ProtocolError::ResponseMsgError)
}
}
impl Sink for EventStream {
type SinkItem = Request;
type SinkError = ProtocolError;
fn start_send(&mut self, item: Self::SinkItem) -> Result<AsyncSink<Self::SinkItem>, Self::SinkError> {
if let Request::Subscribe { streams } = &item {
for EsStream { name, from } in streams {
self.state.entry(name.clone()).or_default().position = (*from).into();
}
}
let result = self.connection.start_send(item);
if self.connection.has_been_reconnected() {
self.send_stream_subscriptions()?;
}
result.map_err(ProtocolError::RequestMsgError)
}
fn poll_complete(&mut self) -> Result<Async<()>, Self::SinkError> {
let result = self.connection.poll_complete();
if self.connection.has_been_reconnected() {
self.send_stream_subscriptions()?;
}
result.map_err(ProtocolError::RequestMsgError)
}
}
pub fn sub_connect(
addr: SocketAddr
) -> impl Future<Item=(SubController, SubStream), Error=tokio_retry::Error<io::Error>>
{
EventStream::connect(addr)
.map_err(|e| dbg!(e))
.map(|connection| {
let (writer, reader) = connection.split();
let (sender, receiver) = mpsc::unbounded_channel();
let x = receiver
.map_err(|e| {
let error = RespMsgError::IoError(io::Error::new(io::ErrorKind::BrokenPipe, e));
ProtocolError::RequestMsgError(RequestMsgError::RespMsgError(error))
})
.map(Into::into)
.forward(writer)
.map_err(|e| error!("{:?}", e))
.map(|_| ());
tokio::spawn(x);
let controller = SubController { sender };
let sub_stream = SubStream { connection: reader };
(controller, sub_stream)
})
}
#[derive(Clone)]
pub struct SubController {
sender: mpsc::UnboundedSender<Request>,
}
impl SubController {
pub fn subscribe_to(&mut self, stream: EsStream) {
let command = Request::Subscribe { streams: vec![stream] };
if let Err(e) = self.sender.try_send(command) {
error!("{}", e);
}
}
}
pub struct SubStream {
connection: SplitStream<EventStream>,
}
#[derive(Debug)]
pub enum ProtocolError {
ResponseMsgError(ResponseMsgError),
RequestMsgError(RequestMsgError),
}
impl fmt::Display for ProtocolError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
ProtocolError::ResponseMsgError(error) => write!(f, "{}", error),
ProtocolError::RequestMsgError(error) => write!(f, "{}", error),
}
}
}
impl Stream for SubStream {
type Item = Result<Response, String>;
type Error = ProtocolError;
fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> {
self.connection.poll()
}
}