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
use super::subscriber::*;
use super::pubsub_core::*;
use super::message_publisher::*;

use futures::future;
use futures::future::{BoxFuture};

use std::sync::*;
use std::collections::{VecDeque};

///
/// A weak publisher is a publisher that 
///
pub struct WeakPublisher<Message> {
    /// The shared core of this publisher
    pub (super) core: Weak<Mutex<PubCore<Message>>>
}

impl<Message: Clone> WeakPublisher<Message> {
    ///
    /// Counts the number of subscribers in this publisher
    /// 
    pub fn count_subscribers(&self) -> usize {
        self.core.upgrade()
            .map(|core| core.lock().unwrap().subscribers.len())
            .unwrap_or(0)
    }

    ///
    /// Creates a duplicate publisher that can be used to publish to the same streams as this object
    /// 
    pub fn republish(&self) -> Self {
        WeakPublisher {
            core:   Weak::clone(&self.core)
        }
    }
}

impl<Message: 'static+Send+Clone> MessagePublisher for WeakPublisher<Message> {
    type Message = Message;

    ///
    /// Subscribes to this publisher
    /// 
    /// Subscribers only receive messages sent to the publisher after they are created.
    /// 
    fn subscribe(&mut self) -> Subscriber<Message> {
        let core = self.core.upgrade();

        if let Some(core) = core {
            // Assign a subscriber ID
            let subscriber_id = {
                let mut core    = core.lock().unwrap();
                let id          = core.next_subscriber_id;
                core.next_subscriber_id += 1;

                id
            };

            // Create the subscriber core
            let sub_core = SubCore {
                id:                 subscriber_id,
                published:          true,
                waiting:            VecDeque::new(),
                reserved:           0,
                notify_waiting:     vec![],
                notify_ready:       vec![],
                notify_complete:    vec![]
            };

            // The new subscriber needs a reference to the sub_core and the pub_core
            let sub_core = Arc::new(Mutex::new(sub_core));
            let pub_core = Arc::downgrade(&core);

            // Register the subscriber with the core, so it will start receiving messages
            {
                let mut core = core.lock().unwrap();
                core.subscribers.insert(subscriber_id, Arc::clone(&sub_core));
            }

            // Create the subscriber
            Subscriber::new(pub_core, sub_core)
        } else {
            // Create a subscriber that is already closed
            let sub_core = SubCore {
                id:                 0,
                published:          true,
                waiting:            VecDeque::new(),
                reserved:           0,
                notify_waiting:     vec![],
                notify_ready:       vec![],
                notify_complete:    vec![]
            };

            Subscriber::new(Weak::default(), Arc::new(Mutex::new(sub_core)))
        }
    }

    ///
    /// Reserves a space for a message with the subscribers, returning when it's ready
    ///
    fn when_ready(&mut self) -> BoxFuture<'static, MessageSender<Message>> {
        let core = self.core.upgrade();

        if let Some(core) = core {
            let when_ready  = PubCore::send_all_subscribers(&core);

            Box::pin(when_ready)
        } else {
            Box::pin(future::ready(MessageSender::new(|_msg| {}, || {})))
        }
    }

    ///
    /// Waits until all subscribers have consumed all pending messages
    ///
    fn when_empty(&mut self) -> BoxFuture<'static, ()> {
        let core = self.core.upgrade();

        if let Some(core) = core {
            let when_empty  = PubCore::when_empty(&core);

            Box::pin(when_empty)
        } else {
            Box::pin(future::ready(()))
        }
    }

    ///
    /// Returns true if this publisher is closed (will not publish any further messages to its subscribers)
    ///
    fn is_closed(&self) -> bool { 
        self.core.upgrade().is_none()
    }

    ///
    /// Future that returns when this publisher is closed
    ///
    fn when_closed(&self) -> BoxFuture<'static, ()> {
        if let Some(core) = self.core.upgrade() {
            Box::pin(CoreClosedFuture::new(core))
        } else {
            Box::pin(future::ready(()))
        }
    }
}