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::fmt::{Debug};
use std::clone::{Clone};
use std::net::SocketAddr;
use std::sync::{Arc, Mutex};
use futures::sync::mpsc;
use futures::sync::mpsc::{UnboundedReceiver, UnboundedSender, SendError};
use futures::sync::oneshot;
use tokio::prelude::*;
use tokio_codec::{Encoder, Decoder};
use tokio::spawn;
use tokio::net::udp::{UdpSocket, UdpFramed};
use error::Error;
pub type IncomingRx<REQ> = UnboundedReceiver<(REQ, SocketAddr)>;
pub type OutgoingTx<RESP> = UnboundedSender<(RESP, SocketAddr)>;
#[derive(Clone)]
pub struct UdpConnection<CODEC: Encoder + Decoder>
{
incoming_rx: Arc<Mutex<IncomingRx<<CODEC as Decoder>::Item>>>,
outgoing_tx: Arc<Mutex<OutgoingTx<<CODEC as Encoder>::Item>>>,
exit_tx: Arc<Mutex<Option<(oneshot::Sender<()>, oneshot::Sender<()>)>>>,
}
impl <CODEC> UdpConnection<CODEC>
where
CODEC: Encoder + Decoder + Clone + Send + 'static,
<CODEC as Encoder>::Item: Send + Debug,
<CODEC as Encoder>::Error: Send + Debug,
<CODEC as Decoder>::Item: Send + Debug,
<CODEC as Decoder>::Error: Send + Debug,
{
pub fn new(addr: &SocketAddr, codec: CODEC) -> Result<UdpConnection<CODEC>, Error> {
trace!("[connector] creating connection (udp address: {})", addr);
let socket = UdpSocket::bind(&addr)?;
Ok(UdpConnection::from_socket(socket, codec))
}
fn from_socket(socket: UdpSocket, codec: CODEC) -> UdpConnection<CODEC> {
let framed = UdpFramed::new(socket, codec);
let (tx, rx) = framed.split();
let (incoming_tx, incoming_rx) = mpsc::unbounded::<_>();
let (incoming_exit_tx, incoming_exit_rx) = oneshot::channel::<()>();
let rx_handle = rx.for_each(move |(data, addr)| {
debug!("[udp connection] receive from: '{:?}' data: '{:?}'", addr, data);
incoming_tx.clone().send((data, addr)).wait().unwrap();
Ok(())
})
.map_err(|e| panic!("[udp connection] error: {:?}", e))
.select2(incoming_exit_rx)
.then(|_| {
info!("[udp connection] closing incoming handler");
Ok(())
});
spawn(rx_handle);
let (outgoing_tx, outgoing_rx) = mpsc::unbounded::<_>();
let (outgoing_exit_tx, outgoing_exit_rx) = oneshot::channel::<()>();
let tx_handle = tx.send_all(outgoing_rx.map_err(|_| panic!() ))
.select2(outgoing_exit_rx)
.then(|_| {
info!("[udp connection] closing outgoing handler");
Ok(())
});
spawn(tx_handle);
UdpConnection{
incoming_rx: Arc::new(Mutex::new(incoming_rx)),
outgoing_tx: Arc::new(Mutex::new(outgoing_tx)),
exit_tx: Arc::new(Mutex::new(Some((incoming_exit_tx, outgoing_exit_tx)))),
}
}
pub fn send(&mut self, addr: SocketAddr, data: <CODEC as Encoder>::Item) {
let unlocked = self.outgoing_tx.lock().unwrap();
let _err = unlocked.unbounded_send((data, addr));
}
pub fn shutdown(self) {
let tx = self.exit_tx.lock().unwrap().take().unwrap();
let _ = tx.0.send(());
let _ = tx.1.send(());
}
}
unsafe impl<CODEC> Send for UdpConnection<CODEC>
where
CODEC: Encoder + Decoder + Clone,
{}
impl<CODEC> Sink for UdpConnection<CODEC>
where
CODEC: Encoder + Decoder + Clone,
{
type SinkItem = (<CODEC as Encoder>::Item, SocketAddr);
type SinkError = SendError<(<CODEC as Encoder>::Item, SocketAddr)>;
fn start_send(
&mut self,
item: Self::SinkItem,
) -> Result<AsyncSink<Self::SinkItem>, Self::SinkError> {
trace!("[connection] start send");
self.outgoing_tx.lock().unwrap().start_send(item)
}
fn poll_complete(&mut self) -> Result<Async<()>, Self::SinkError> {
trace!("[connection] send complete");
self.outgoing_tx.lock().unwrap().poll_complete()
}
}
impl<CODEC> Stream for UdpConnection<CODEC>
where
CODEC: Encoder + Decoder + Clone,
{
type Item = (<CODEC as Decoder>::Item, SocketAddr);
type Error = ();
fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> {
trace!("[connection] poll receive");
self.incoming_rx.lock().unwrap().poll()
}
}
#[derive(Clone, Debug)]
pub struct UdpInfo {
pub address: SocketAddr,
}