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
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
use std::cell::RefCell;
use std::fmt::Debug;
use std::io::Error as IoError;
use std::mem;
use std::net::{SocketAddr, UdpSocket};
use std::os::unix::net::UnixDatagram;
use std::path::Path;
use std::sync::Arc;
use std::thread::{self, JoinHandle};

use log;
use parking_lot::RwLock;
use serde::de::DeserializeOwned;
use serde::Serialize;

use crate::net::{self, Udp, UnixUdp};

// the callback type for passing messages into the callback
type Callback<T> = Box<dyn Send + Fn(T)>;

#[derive(Clone)]
enum SubscriberPort {
    UdpPort(u16),
    UnixDatagram(String),
}

const PUBSUB_ERROR: &str = "PubSubError";

trait PublishHandler<T>
where
    T: DeserializeOwned + Serialize,
{
    fn name(&self) -> &'static str;

    // Send a message
    fn send(&self, message: &T) -> Result<usize, IoError>;

    // return the UDP socket addr
    fn udp(&self) -> Option<SocketAddr> {
        None
    }

    // return the path of the Unix socket
    fn unix_datagram(&self) -> Option<String> {
        None
    }
}

// TODO have a publish queue
/// The Publisher publishes messages of type `T` to its subscribers.
pub struct Publisher<T> {
    name: String,
    handlers: Vec<Box<dyn PublishHandler<T>>>,
}

impl<T> Publisher<T>
where
    T: DeserializeOwned + Serialize,
{
    /// Create a new publisher with a name.
    ///
    /// Args:
    /// * `name`: The name of the publisher.
    pub fn new(name: &str) -> Publisher<T> {
        Publisher {
            name: String::from(name),
            handlers: Vec::new(),
        }
    }

    /// Publish a message to the subscribers.
    ///
    /// By default, the publisher has no subscribers. Subscribers must be added before the `publish`
    /// method does anything. Without subscribers, `publish` is a no-op.
    ///
    pub fn publish(&mut self, message: &T) {
        let tmp = mem::take(&mut self.handlers);
        for handler in tmp.into_iter() {
            if let Err(err) = handler.send(message) {
                log::error!(
                    "Failed to publish to '{}' publisher {} with error: {}",
                    self.name,
                    handler.name(),
                    err
                );
            } else {
                self.handlers.push(handler);
            }
        }
    }

    /// Add a UDP endpoint to publish to.
    ///
    /// Args:
    /// * `addr`: The address of the UDP endpoint.
    pub fn add_udp_endpoint(&mut self, addr: SocketAddr) {
        for handler in self.handlers.iter() {
            if let Some(socket_addr) = handler.udp() {
                if addr == socket_addr {
                    return;
                }
            }
        }
        self.handlers.push(Box::new(UdpPublisher { addr }));
    }

    /// Add a Unix Datagram endpoint to publish to.
    ///
    /// Args:
    /// * `path`: The Unix socket path to publish to.
    pub fn add_unix_datagram_endpoint(&mut self, path: &str) {
        for handler in self.handlers.iter() {
            if let Some(socket_addr) = handler.unix_datagram() {
                if path == socket_addr {
                    return;
                }
            }
        }
        self.handlers.push(Box::new(UnixDatagramPublisher {
            path: String::from(path),
        }));
    }

    /// Return the total number of Publish endpoints.
    pub fn num_endpoints(&self) -> usize {
        self.handlers.len()
    }
}

struct UdpPublisher {
    addr: SocketAddr,
}

impl<T> PublishHandler<T> for UdpPublisher
where
    T: DeserializeOwned + Serialize,
{
    fn name(&self) -> &'static str {
        "UDP"
    }

    fn send(&self, message: &T) -> Result<usize, IoError> {
        // TODO bring this into a new() function
        let udp = UdpSocket::bind("0.0.0.0:0").unwrap();
        let msg_bytes = net::construct_message(message);
        udp.send_to(&msg_bytes, self.addr)
    }

    fn udp(&self) -> Option<SocketAddr> {
        Some(self.addr)
    }
}

struct UnixDatagramPublisher {
    path: String,
}

impl<T> PublishHandler<T> for UnixDatagramPublisher
where
    T: DeserializeOwned + Serialize,
{
    fn name(&self) -> &'static str {
        "Unix Datagram"
    }

    fn send(&self, message: &T) -> Result<usize, IoError> {
        // sometimes the subscriber endpoint is slow to show up. don't treat it as an error to send
        // when the endpoint doesn't exist yet.
        // TODO make it an error
        if !Path::new(&self.path).exists() {
            return Ok(0);
        }

        // TODO bring this into a new() function
        let socket = UnixDatagram::unbound().unwrap();
        let msg_bytes = net::construct_message(message);
        socket.send_to(&msg_bytes, &self.path)
    }

    fn unix_datagram(&self) -> Option<String> {
        Some(self.path.clone())
    }
}

/// The Subscriber receives messages of type `T` and processes them with a callback.
pub struct Subscriber {
    name: String,
    subscribe_port: SubscriberPort,
    stop_requested: Arc<RwLock<bool>>,
    thread: Option<JoinHandle<()>>,
}

impl Subscriber {
    fn new<T>(
        name: &'static str,
        subscribe_port: SubscriberPort,
        callback: Callback<T>,
    ) -> Subscriber
    where
        T: Debug + DeserializeOwned + Serialize + 'static,
    {
        let stop_requested = Arc::new(RwLock::new(false));
        let is_stop_requested = stop_requested.clone();
        let thread_subscribe_port = subscribe_port.clone();

        let thread = thread::spawn(move || {
            let subscriber: Box<dyn SubscribeHandler<T>> = match thread_subscribe_port {
                SubscriberPort::UdpPort(port) => Box::new(UdpSubscriber::new(port)),
                SubscriberPort::UnixDatagram(path) => {
                    Box::new(UnixDatagramSubscriber::new(Path::new(&path)))
                }
            };
            while !*is_stop_requested.read() {
                match subscriber.recv() {
                    Ok(msg) => (*callback)(msg),
                    Err(err) => {
                        log::debug!("recv error on Subscriber '{}' with error:\n{}", name, err)
                    }
                };
            }
        });

        Subscriber {
            name: String::from(name),
            subscribe_port,
            stop_requested,
            thread: Some(thread),
        }
    }

    /// Create a subscriber that listens on a UDP port.
    ///
    /// Args:
    /// * `name` The name to refer to the subscriber.
    /// * `port`: The UDP port to listen for new messages on.
    /// * `callback`: The function to call on incoming data.
    pub fn with_udp_port<T>(name: &'static str, port: u16, callback: Callback<T>) -> Subscriber
    where
        T: Debug + DeserializeOwned + Serialize + 'static,
    {
        Subscriber::new(name, SubscriberPort::UdpPort(port), callback)
    }

    /// Create a subscriber that listens on a Unix Datagram socket.
    ///
    /// Args:
    /// * `name` The name to refer to the subscriber.
    /// * `path`: The unix socket path to bind the server to.
    /// * `callback`: The function to call on incoming data.
    pub fn with_unix_datagram<T>(
        name: &'static str,
        path: &str,
        callback: Callback<T>,
    ) -> Subscriber
    where
        T: Debug + DeserializeOwned + Serialize + 'static,
    {
        Subscriber::new(
            name,
            SubscriberPort::UnixDatagram(String::from(path)),
            callback,
        )
    }

    /// Check if the Subscriber is running.
    pub fn is_running(&self) -> bool {
        self.thread.is_some()
    }

    /// Stop the Subscriber
    pub fn stop(&mut self) {
        if self.is_running() {
            log::debug!("Stopping Subscriber: {}", self.name);
            *self.stop_requested.write() = true;
            self.send_stop_signal();
            self.thread.take().unwrap().join().unwrap();
        }
    }

    fn send_stop_signal(&self) {
        match &self.subscribe_port {
            SubscriberPort::UdpPort(port) => self.send_stop_signal_udp(*port),
            SubscriberPort::UnixDatagram(path) => self.send_stop_signal_unix(&path),
        }
    }

    fn send_stop_signal_udp(&self, port: u16) {
        let addr = format!("127.0.0.1:{}", port);
        let mut udp = Udp::new(UdpSocket::bind("0.0.0.0:0").unwrap());
        udp.set_write_addr(addr.parse().unwrap());
        net::write_stop_signal(Ok(udp), &self.name);
    }

    fn send_stop_signal_unix(&self, path: &str) {
        let mut unix = UnixUdp::new(UnixDatagram::unbound().unwrap());
        unix.set_path(path);
        net::write_stop_signal(Ok(unix), &self.name);
    }
}

impl Drop for Subscriber {
    fn drop(&mut self) {
        self.stop();
    }
}

trait SubscribeHandler<T>
where
    T: DeserializeOwned + Serialize,
{
    fn recv(&self) -> Result<T, IoError>;
}

struct UdpSubscriber {
    udp: RefCell<Option<Udp>>,
}

impl UdpSubscriber {
    fn new(port: u16) -> UdpSubscriber {
        let addr: SocketAddr = format!("0.0.0.0:{}", port).parse().unwrap();
        let listener = UdpSocket::bind(addr).expect(&format!("Cannot bind to UDP port: {}", port));

        UdpSubscriber {
            udp: RefCell::new(Some(Udp::new(listener))),
        }
    }
}

impl<T> SubscribeHandler<T> for UdpSubscriber
where
    T: DeserializeOwned + Serialize,
{
    fn recv(&self) -> Result<T, IoError> {
        let mut udp = self.udp.borrow_mut().take().unwrap();
        let response = net::recv(&mut udp, None, PUBSUB_ERROR, false);
        *self.udp.borrow_mut() = Some(udp);
        response
    }
}

struct UnixDatagramSubscriber {
    unix: RefCell<Option<UnixUdp>>,
}

impl UnixDatagramSubscriber {
    fn new(path: &Path) -> UnixDatagramSubscriber {
        UnixDatagramSubscriber {
            unix: RefCell::new(Some(UnixUdp::new(
                UnixDatagram::bind(path)
                    .expect(&format!("Cannot bind to Unix datagram socket: {:?}", path)),
            ))),
        }
    }
}

impl<T> SubscribeHandler<T> for UnixDatagramSubscriber
where
    T: DeserializeOwned + Serialize,
{
    fn recv(&self) -> Result<T, IoError> {
        let mut unix = self.unix.borrow_mut().take().unwrap();
        let response = net::recv(&mut unix, None, PUBSUB_ERROR, false);
        *self.unix.borrow_mut() = Some(unix);
        response
    }
}

#[cfg(test)]
mod tests {
    use std::io::Write;
    use std::sync::Arc;
    use std::time::{Duration, Instant};

    use parking_lot::Mutex;
    use portpicker;
    use serde::Deserialize;
    use tempfile;

    use super::*;

    fn setup_logging() {
        let _ = env_logger::builder()
            .format(|buf, record| {
                writeln!(
                    buf,
                    "{}:{} [{}] - {}",
                    record.file().unwrap_or("unknown"),
                    record.line().unwrap_or(0),
                    record.level(),
                    record.args()
                )
            })
            .is_test(true)
            .try_init();
    }

    #[test]
    fn start_stop_subscriber_udp() {
        setup_logging();
        let port: u16 = portpicker::pick_unused_port().unwrap();
        let mut subscriber: Subscriber =
            Subscriber::with_udp_port::<i32>("test", port, Box::new(|_| {}));
        assert!(subscriber.is_running());
        subscriber.stop();
        assert!(!subscriber.is_running());
    }

    #[test]
    fn start_stop_subscriber_unix_datagram() {
        setup_logging();
        let tempdir = tempfile::tempdir().unwrap();
        let socket = tempdir.path().join("socket");
        let socket = socket.as_path().to_str().unwrap();
        let mut subscriber: Subscriber =
            Subscriber::with_unix_datagram::<i32>("test", socket, Box::new(|_| {}));
        assert!(subscriber.is_running());
        subscriber.stop();
        assert!(!subscriber.is_running());
    }

    #[test]
    fn one_publisher_many_subscribers() {
        #[derive(Deserialize, Serialize, Debug, Clone)]
        struct TestMessage {
            name: String,
            value: u32,
        }

        impl TestMessage {
            fn eq(&self, other: &TestMessage) -> bool {
                self.name == other.name && self.value == other.value
            }
        }

        let null_message = TestMessage {
            name: String::new(),
            value: 0,
        };

        let test_message = TestMessage {
            name: String::from("test_message"),
            value: 123,
        };

        let mut publisher = Publisher::new("test");

        let udp_port: u16 = portpicker::pick_unused_port().unwrap();
        let udp_sub_msg = Arc::new(Mutex::new(null_message.clone()));
        let udp_msg_clone = Arc::clone(&udp_sub_msg);
        let mut udp_subscriber: Subscriber = Subscriber::with_udp_port::<TestMessage>(
            "test",
            udp_port,
            Box::new(move |msg| {
                let mut data = udp_msg_clone.lock();
                *data = msg.clone();
            }),
        );
        publisher.add_udp_endpoint(format!("127.0.0.1:{}", udp_port).parse().unwrap());
        assert!(udp_subscriber.is_running());

        let unix_dgram_sub_msg = Arc::new(Mutex::new(null_message.clone()));
        let unix_dgram_msg_clone = Arc::clone(&unix_dgram_sub_msg);
        let tempdir = tempfile::tempdir().unwrap();
        let socket = tempdir.path().join("socket");
        let socket = socket.as_path().to_str().unwrap();
        let mut unix_subsciber = Subscriber::with_unix_datagram::<TestMessage>(
            "test",
            socket,
            Box::new(move |msg| {
                let mut data = unix_dgram_msg_clone.lock();
                *data = msg.clone();
            }),
        );
        publisher.add_unix_datagram_endpoint(socket);
        assert!(unix_subsciber.is_running());

        // TODO(rdomagalski) make this reliable
        let start = Instant::now();
        let timeout = Duration::from_secs(5);
        while start.elapsed() < timeout {
            if Path::new(socket).exists() {
                break;
            } else {
                thread::sleep(Duration::from_millis(10));
            }
        }

        let n_subscribers = 2;

        let start = Instant::now();
        while start.elapsed() < timeout {
            publisher.publish(&test_message);
            thread::sleep(Duration::from_millis(10));

            let udp_data = udp_sub_msg.lock();
            let unix_dgram_data = unix_dgram_sub_msg.lock();
            if udp_data.eq(&test_message) && unix_dgram_data.eq(&test_message) {
                break;
            }
            if publisher.num_endpoints() != n_subscribers {
                break;
            }
        }
        let timed_out = start.elapsed() >= timeout;
        udp_subscriber.stop();
        unix_subsciber.stop();

        assert!(!timed_out);
        assert_eq!(publisher.num_endpoints(), n_subscribers);

        assert!(!udp_subscriber.is_running());
        assert!(!unix_subsciber.is_running());
    }
}