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
use std::io;
use std::marker::PhantomData;
use typename::TypeName;
use futures::{Async, Poll};
use futures::stream::{Stream, Fuse};
use strymon_model::{Topic, TopicType, TopicSchema};
use strymon_communication::rpc::*;
use Coordinator;
use super::publish::PublicationError;
use super::subscribe::SubscriptionError;
use util::StreamsUnordered;
pub struct Service<N: Name> {
server: Fuse<Server<N>>,
clients: StreamsUnordered<Incoming<N>>,
topic: Topic,
coord: Coordinator,
}
impl<N: Name> Drop for Service<N> {
fn drop(&mut self) {
if let Err(err) = self.coord.unpublish(self.topic.id) {
warn!("failed to unpublish service: {:?}", err)
}
}
}
impl<N: Name> Stream for Service<N> {
type Item = RequestBuf<N>;
type Error = io::Error;
fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> {
while let Async::Ready(Some((_, client))) = self.server.poll()? {
self.clients.push(client);
}
match self.clients.poll() {
Ok(Async::Ready(None)) if !self.server.is_done() => {
Ok(Async::NotReady)
}
other => other,
}
}
}
pub struct Client<N: Name> {
queue: Outgoing,
topic: Topic,
coord: Coordinator,
name: PhantomData<N>,
}
impl<N: Name> Client<N> {
pub fn request<R: Request<N>>(&self, r: &R) -> Response<N, R> {
self.queue.request(r)
}
}
impl<N: Name> Drop for Client<N> {
fn drop(&mut self) {
if let Err(err) = self.coord.unsubscribe(self.topic.id) {
warn!("failed to unpublish service: {:?}", err)
}
}
}
impl Coordinator {
pub fn announce_service<N: Name + TypeName>(
&self,
name: &str,
) -> Result<Service<N>, PublicationError> {
let server = self.network.server(None)?.fuse();
let addr = {
let (host, port) = server.get_ref().external_addr();
(host.to_string(), port)
};
let schema = TopicSchema::Service(TopicType::of::<N>());
let topic = self.publish_request(name.to_string(), schema, addr)?;
let clients = StreamsUnordered::new();
let coord = self.clone();
Ok(Service {
server,
clients,
topic,
coord,
})
}
pub fn bind_service<N: Name + TypeName>(
&self,
name: &str,
blocking: bool,
) -> Result<Client<N>, SubscriptionError> {
let topic = self.subscribe_request(name, blocking)?;
let schema = TopicSchema::Service(TopicType::of::<N>());
if topic.schema != schema {
return Err(SubscriptionError::TypeMismatch);
}
let queue = {
let addr = (&*topic.addr.0, topic.addr.1);
let (tx, _) = self.network.client::<N, _>(addr)?;
tx
};
let coord = self.clone();
let name = PhantomData;
Ok(Client {
queue,
topic,
coord,
name,
})
}
}