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
use std::io; use std::{sync::Arc, thread, time::Duration}; use async_mutex::Mutex; use blocking::block_on; use crossbeam_channel::RecvTimeoutError; use futures::prelude::*; use smol::Timer; use crate::{asynk, Message}; /// A `Subscription` receives `Message`s published to specific NATS `Subject`s. #[derive(Clone, Debug)] pub struct Subscription(pub(crate) Arc<Mutex<asynk::Subscription>>); impl Subscription { /// Get the next message, or None if the subscription /// has been unsubscribed or the connection closed. /// /// # Example /// ``` /// # fn main() -> std::io::Result<()> { /// # let nc = nats::connect("demo.nats.io")?; /// # let sub = nc.subscribe("foo")?; /// # nc.publish("foo", "hello")?; /// if let Some(msg) = sub.next() {} /// # Ok(()) /// # } /// ``` pub fn next(&self) -> Option<Message> { block_on(async { self.0.lock().await.next().await }).map(Message::from_async) } /// Try to get the next message, or None if no messages /// are present or if the subscription has been unsubscribed /// or the connection closed. /// /// # Example /// ``` /// # fn main() -> std::io::Result<()> { /// # let nc = nats::connect("demo.nats.io")?; /// # let sub = nc.subscribe("foo")?; /// if let Some(msg) = sub.try_next() { /// println!("Received {}", msg); /// } /// # Ok(()) /// # } /// ``` pub fn try_next(&self) -> Option<Message> { self.0 .try_lock() .and_then(|mut s| s.try_next()) .map(Message::from_async) } /// Get the next message, or a timeout error if no messages are available for timout. /// /// # Example /// ``` /// # fn main() -> std::io::Result<()> { /// # let nc = nats::connect("demo.nats.io")?; /// # let sub = nc.subscribe("foo")?; /// if let Ok(msg) = sub.next_timeout(std::time::Duration::from_secs(1)) {} /// # Ok(()) /// # } /// ``` pub fn next_timeout(&self, timeout: Duration) -> Result<Message, RecvTimeoutError> { block_on(async move { futures::select! { msg = async { self.0.lock().await.next().await }.fuse() => { match msg { Some(msg) => Ok(Message::from_async(msg)), None => Err(RecvTimeoutError::Disconnected), } } _ = Timer::after(timeout).fuse() => Err(RecvTimeoutError::Timeout), } }) } /// Returns a blocking message iterator. Same as calling `iter()`. /// /// # Example /// ```no_run /// # fn main() -> std::io::Result<()> { /// # let nc = nats::connect("demo.nats.io")?; /// # let sub = nc.subscribe("foo")?; /// for msg in sub.messages() {} /// # Ok(()) /// # } /// ``` pub const fn messages(&self) -> Iter<'_> { Iter { subscription: self } } /// Returns a blocking message iterator. /// /// # Example /// ```no_run /// # fn main() -> std::io::Result<()> { /// # let nc = nats::connect("demo.nats.io")?; /// # let sub = nc.subscribe("foo")?; /// for msg in sub.iter() {} /// # Ok(()) /// # } /// ``` pub const fn iter(&self) -> Iter<'_> { Iter { subscription: self } } /// Returns a non-blocking message iterator. /// /// # Example /// ``` /// # fn main() -> std::io::Result<()> { /// # let nc = nats::connect("demo.nats.io")?; /// # let sub = nc.subscribe("foo")?; /// for msg in sub.try_iter() {} /// # Ok(()) /// # } /// ``` pub const fn try_iter(&self) -> TryIter<'_> { TryIter { subscription: self } } /// Returns a blocking message iterator with a time deadline for blocking. /// /// # Example /// ``` /// # fn main() -> std::io::Result<()> { /// # let nc = nats::connect("demo.nats.io")?; /// # let sub = nc.subscribe("foo")?; /// for msg in sub.timeout_iter(std::time::Duration::from_secs(1)) {} /// # Ok(()) /// # } /// ``` pub const fn timeout_iter(&self, timeout: Duration) -> TimeoutIter<'_> { TimeoutIter { subscription: self, to: timeout, } } /// Attach a closure to handle messages. /// This closure will execute in a separate thread. /// The result of this call is a `Handler` which can not be /// iterated and must be unsubscribed or closed directly to unregister interest. /// A `Handler` will not unregister interest with the server when `drop(&mut self)` is called. /// /// # Example /// ``` /// # fn main() -> std::io::Result<()> { /// # let nc = nats::connect("demo.nats.io")?; /// nc.subscribe("bar")?.with_handler(move |msg| { /// println!("Received {}", &msg); /// Ok(()) /// }); /// # Ok(()) /// # } /// ``` pub fn with_handler<F>(self, handler: F) -> Handler where F: Fn(Message) -> io::Result<()> + Sync + Send + 'static, { // This will allow us to not have to capture the return. When it is dropped it // will not unsubscribe from the server. // self.do_unsub = false; let (sid, subject) = block_on(async { let inner = self.0.lock().await; (inner.sid, inner.subject.clone()) }); let sub = self.clone(); thread::Builder::new() .name(format!("nats_subscriber_{}_{}", sid, subject)) .spawn(move || { for m in sub.iter() { if let Err(e) = handler(m) { // TODO(dlc) - Capture for last error? log::error!("Error in callback! {:?}", e); } } }) .expect("threads should be spawnable"); Handler { sub: self } } /// Unsubscribe a subscription immediately without draining. /// Use `drain` instead if you want any pending messages /// to be processed by a handler, if one is configured. /// /// # Example /// ``` /// # fn main() -> std::io::Result<()> { /// # let nc = nats::connect("demo.nats.io")?; /// let sub = nc.subscribe("foo")?; /// sub.unsubscribe()?; /// # Ok(()) /// # } /// ``` pub fn unsubscribe(self) -> io::Result<()> { Ok(()) } /// Close a subscription. Same as `unsubscribe` /// /// Use `drain` instead if you want any pending messages /// to be processed by a handler, if one is configured. /// /// # Example /// ``` /// # fn main() -> std::io::Result<()> { /// # let nc = nats::connect("demo.nats.io")?; /// let sub = nc.subscribe("foo")?; /// sub.close()?; /// # Ok(()) /// # } /// ``` pub fn close(self) -> io::Result<()> { Ok(()) } /// Send an unsubscription then flush the connection, /// allowing any unprocessed messages to be handled /// by a handler function if one is configured. /// /// After the flush returns, we know that a round-trip /// to the server has happened after it received our /// unsubscription, so we shut down the subscriber /// afterwards. /// /// A similar method exists on the `Connection` struct /// which will drain all subscriptions for the NATS /// client, and transition the entire system into /// the closed state afterward. /// /// # Example /// /// ``` /// # use std::sync::{Arc, atomic::{AtomicBool, Ordering::SeqCst}}; /// # use std::thread; /// # use std::time::Duration; /// # fn main() -> std::io::Result<()> { /// # let nc = nats::connect("demo.nats.io")?; /// /// let mut sub = nc.subscribe("test.drain")?; /// /// nc.publish("test.drain", "message")?; /// sub.drain()?; /// /// let mut received = false; /// for _ in sub { /// received = true; /// } /// /// assert!(received); /// /// # Ok(()) /// # } /// ``` pub fn drain(&mut self) -> io::Result<()> { block_on(async { self.0.lock().await.drain().await }) } } impl IntoIterator for Subscription { type Item = Message; type IntoIter = IntoIter; fn into_iter(self) -> IntoIter { IntoIter { subscription: self } } } impl<'a> IntoIterator for &'a Subscription { type Item = Message; type IntoIter = Iter<'a>; fn into_iter(self) -> Iter<'a> { Iter { subscription: self } } } /// A `Handler` may be used to unsubscribe a handler thread. pub struct Handler { sub: Subscription, } impl Handler { /// Unsubscribe a subscription. /// /// # Example /// ``` /// # fn main() -> std::io::Result<()> { /// # let nc = nats::connect("demo.nats.io")?; /// let sub = nc.subscribe("foo")?.with_handler(move |msg| { /// println!("Received {}", &msg); /// Ok(()) /// }); /// sub.unsubscribe()?; /// # Ok(()) /// # } /// ``` pub fn unsubscribe(self) -> io::Result<()> { let mut sub = block_on(self.sub.0.lock()); sub.active = false; block_on(sub.client.unsubscribe(sub.sid)) } } /// A non-blocking iterator over messages from a `Subscription` pub struct TryIter<'a> { subscription: &'a Subscription, } impl<'a> Iterator for TryIter<'a> { type Item = Message; fn next(&mut self) -> Option<Self::Item> { self.subscription.try_next() } } /// An iterator over messages from a `Subscription` pub struct Iter<'a> { subscription: &'a Subscription, } impl<'a> Iterator for Iter<'a> { type Item = Message; fn next(&mut self) -> Option<Self::Item> { self.subscription.next() } } /// An iterator over messages from a `Subscription` pub struct IntoIter { subscription: Subscription, } impl Iterator for IntoIter { type Item = Message; fn next(&mut self) -> Option<Self::Item> { self.subscription.next() } } /// An iterator over messages from a `Subscription` /// where `None` will be returned if a new `Message` /// has not been received by the end of a timeout. pub struct TimeoutIter<'a> { subscription: &'a Subscription, to: Duration, } impl<'a> Iterator for TimeoutIter<'a> { type Item = Message; fn next(&mut self) -> Option<Self::Item> { self.subscription.next_timeout(self.to).ok() } }