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
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
//! An async Rust client for the NATS.io ecosystem.
//!
//! `git clone https://github.com/nats-io/nats.rs`
//!
//! NATS.io is a simple, secure and high performance open source messaging
//! system for cloud native applications, `IoT` messaging, and microservices
//! architectures.
//!
//! For more information see [https://nats.io/].
//!
//! [https://nats.io/]: https://nats.io/
//!
//! ## Examples
//!
//! Basic connections, and those with options. The compiler will force these to
//! be correct.
//!
//! ```no_run
//! # smol::block_on(async {
//! let nc = nats::asynk::connect("demo.nats.io").await?;
//!
//! let nc2 = nats::asynk::Options::with_user_pass("derek", "s3cr3t!")
//!     .with_name("My Rust NATS App")
//!     .connect("127.0.0.1")
//!     .await?;
//!
//! let nc3 = nats::asynk::Options::with_credentials("path/to/my.creds")
//!     .connect("connect.ngs.global")
//!     .await?;
//!
//! let nc4 = nats::asynk::Options::new()
//!     .add_root_certificate("my-certs.pem")
//!     .connect("tls://demo.nats.io:4443")
//!     .await?;
//! # std::io::Result::Ok(()) });
//! ```
//!
//! ### Publish
//!
//! ```
//! # smol::block_on(async {
//! let nc = nats::asynk::connect("demo.nats.io").await?;
//! nc.publish("my.subject", "Hello World!").await?;
//!
//! nc.publish("my.subject", "my message").await?;
//!
//! // Publish a request manually.
//! let reply = nc.new_inbox();
//! let rsub = nc.subscribe(&reply).await?;
//! nc.publish_request("my.subject", &reply, "Help me!").await?;
//! # std::io::Result::Ok(()) });
//! ```
//!
//! ### Subscribe
//!
//! ```no_run
//! # smol::block_on(async {
//! # use std::time::Duration;
//! let nc = nats::asynk::connect("demo.nats.io").await?;
//! let sub = nc.subscribe("foo").await?;
//!
//! // Receive a message.
//! if let Some(msg) = sub.next().await {}
//!
//! // Queue subscription.
//! let qsub = nc.queue_subscribe("foo", "my_group").await?;
//! # std::io::Result::Ok(()) });
//! ```
//!
//! ### Request/Response
//!
//! ```no_run
//! # use std::time::Duration;
//! # smol::block_on(async {
//! let nc = nats::asynk::connect("demo.nats.io").await?;
//! let resp = nc.request("foo", "Help me?").await?;
//!
//! // With multiple responses.
//! let rsub = nc.request_multi("foo", "Help").await?;
//! if let Some(msg) = rsub.next().await {}
//! if let Some(msg) = rsub.next().await {}
//!
//! // Publish a request manually.
//! let reply = nc.new_inbox();
//! let rsub = nc.subscribe(&reply).await?;
//! nc.publish_request("foo", &reply, "Help me!").await?;
//! let response = rsub.next().await;
//! # std::io::Result::Ok(()) });
//! ```

use std::fmt;
use std::io;
use std::net::IpAddr;
use std::path::Path;
use std::sync::{atomic::AtomicBool, Arc};
use std::time::Duration;

use blocking::unblock;
use crossbeam_channel::{Receiver, Sender};

use crate::Headers;

/// Connect to a NATS server at the given url.
///
/// # Example
/// ```
/// # smol::block_on(async {
/// let nc = nats::asynk::connect("demo.nats.io").await?;
/// # std::io::Result::Ok(()) });
/// ```
pub async fn connect(nats_url: &str) -> io::Result<Connection> {
    Options::new().connect(nats_url).await
}

/// A NATS client connection.
#[derive(Clone, Debug)]
pub struct Connection {
    inner: crate::Connection,
}

impl Connection {
    fn new(inner: crate::Connection) -> Connection {
        Self { inner }
    }

    /// Publishes a message.
    pub async fn publish(
        &self,
        subject: &str,
        msg: impl AsRef<[u8]>,
    ) -> io::Result<()> {
        self.publish_with_reply_or_headers(subject, None, None, msg)
            .await
    }

    /// Publishes a message with a reply subject.
    pub async fn publish_request(
        &self,
        subject: &str,
        reply: &str,
        msg: impl AsRef<[u8]>,
    ) -> io::Result<()> {
        if let Some(res) = self.inner.try_publish_with_reply_or_headers(
            subject,
            Some(reply),
            None,
            &msg,
        ) {
            return res;
        }
        let subject = subject.to_string();
        let reply = reply.to_string();
        let msg = msg.as_ref().to_vec();
        let inner = self.inner.clone();
        unblock(move || inner.publish_request(&subject, &reply, msg)).await
    }

    /// Creates a new unique subject for receiving replies.
    pub fn new_inbox(&self) -> String {
        self.inner.new_inbox()
    }

    /// Publishes a message and waits for the response.
    pub async fn request(
        &self,
        subject: &str,
        msg: impl AsRef<[u8]>,
    ) -> io::Result<Message> {
        let subject = subject.to_string();
        let msg = msg.as_ref().to_vec();
        let inner = self.inner.clone();
        let msg = unblock(move || inner.request(&subject, msg)).await?;
        Ok(msg.into())
    }

    /// Publishes a message and waits for the response or until the
    /// timeout duration is reached
    pub async fn request_timeout(
        &self,
        subject: &str,
        msg: impl AsRef<[u8]>,
        timeout: Duration,
    ) -> io::Result<Message> {
        let subject = subject.to_string();
        let msg = msg.as_ref().to_vec();
        let inner = self.inner.clone();
        let msg =
            unblock(move || inner.request_timeout(&subject, msg, timeout))
                .await?;
        Ok(msg.into())
    }

    /// Publishes a message and returns a subscription for awaiting the
    /// response.
    pub async fn request_multi(
        &self,
        subject: &str,
        msg: impl AsRef<[u8]>,
    ) -> io::Result<Subscription> {
        let subject = subject.to_string();
        let msg = msg.as_ref().to_vec();
        let inner = self.inner.clone();
        let sub = unblock(move || inner.request_multi(&subject, msg)).await?;
        let (_closer_tx, closer_rx) = crossbeam_channel::bounded(0);
        Ok(Subscription {
            inner: sub,
            _closer_tx,
            closer_rx,
        })
    }

    /// Creates a subscription.
    pub async fn subscribe(&self, subject: &str) -> io::Result<Subscription> {
        let subject = subject.to_string();
        let inner = self.inner.clone();
        let inner = unblock(move || inner.subscribe(&subject)).await?;
        let (_closer_tx, closer_rx) = crossbeam_channel::bounded(0);
        Ok(Subscription {
            inner,
            _closer_tx,
            closer_rx,
        })
    }

    /// Creates a queue subscription.
    pub async fn queue_subscribe(
        &self,
        subject: &str,
        queue: &str,
    ) -> io::Result<Subscription> {
        let subject = subject.to_string();
        let queue = queue.to_string();
        let inner = self.inner.clone();
        let inner =
            unblock(move || inner.queue_subscribe(&subject, &queue)).await?;
        let (_closer_tx, closer_rx) = crossbeam_channel::bounded(0);
        Ok(Subscription {
            inner,
            _closer_tx,
            closer_rx,
        })
    }

    /// Flushes by performing a round trip to the server.
    pub async fn flush(&self) -> io::Result<()> {
        let inner = self.inner.clone();
        unblock(move || inner.flush()).await
    }

    /// Flushes by performing a round trip to the server or times out after a
    /// duration of time.
    pub async fn flush_timeout(&self, timeout: Duration) -> io::Result<()> {
        let inner = self.inner.clone();
        unblock(move || inner.flush_timeout(timeout)).await
    }

    /// Calculates the round trip time between this client and the server.
    pub async fn rtt(&self) -> io::Result<Duration> {
        let inner = self.inner.clone();
        unblock(move || inner.rtt()).await
    }

    /// Returns the client IP as known by the most recently connected server.
    ///
    /// Supported as of server version 2.1.6.
    pub fn client_ip(&self) -> io::Result<IpAddr> {
        self.inner.client_ip()
    }

    /// Returns the client ID as known by the most recently connected server.
    pub fn client_id(&self) -> u64 {
        self.inner.client_id()
    }

    /// Unsubscribes all subscriptions and flushes the connection.
    ///
    /// Remaining messages can still be received by existing [`Subscription`]s.
    pub async fn drain(&self) -> io::Result<()> {
        let inner = self.inner.clone();
        unblock(move || inner.drain()).await
    }

    /// Closes the connection.
    pub async fn close(&self) -> io::Result<()> {
        let inner = self.inner.clone();
        unblock(move || inner.close()).await;
        Ok(())
    }

    /// Publish a message which may have a reply subject or headers set.
    pub async fn publish_with_reply_or_headers(
        &self,
        subject: &str,
        reply: Option<&str>,
        headers: Option<&Headers>,
        msg: impl AsRef<[u8]>,
    ) -> io::Result<()> {
        if let Some(res) = self
            .inner
            .try_publish_with_reply_or_headers(subject, reply, headers, &msg)
        {
            return res;
        }
        let subject = subject.to_string();
        let reply = reply.map(str::to_owned);
        let headers = headers.map(Headers::clone);
        let msg = msg.as_ref().to_vec();
        let inner = self.inner.clone();
        unblock(move || {
            inner.publish_with_reply_or_headers(
                &subject,
                reply.as_deref(),
                headers.as_ref(),
                msg,
            )
        })
        .await
    }
}

/// A subscription to a subject.
#[derive(Debug)]
pub struct Subscription {
    inner: crate::Subscription,

    // Dropping this signals to any receivers that the subscription has been closed. These should
    // be dropped after inner is dropped, so if another thread is currently blocking, the
    // subscription is closed on that thread.
    _closer_tx: Sender<()>,
    closer_rx: Receiver<()>,
}

impl Subscription {
    /// Gets the next message, or returns `None` if the subscription
    /// has been unsubscribed or the connection is closed.
    pub async fn next(&self) -> Option<Message> {
        if let Some(msg) = self.inner.try_next() {
            return Some(msg.into());
        }
        let inner = self.inner.clone();
        let closer = self.closer_rx.clone();
        let msg = unblock(move || {
            // If the subscription is dropped, we should stop blocking this thread immediately.
            crossbeam_channel::select! {
                recv(closer) -> _ => None,
                recv(inner.receiver()) -> msg => msg.ok(),
            }
        })
        .await?;
        Some(msg.into())
    }

    /// 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.inner.try_next().map(From::from)
    }

    /// Stops listening for new messages, but the remaining queued messages can
    /// still be received.
    pub async fn drain(&self) -> io::Result<()> {
        let inner = self.inner.clone();
        unblock(move || inner.drain()).await
    }

    /// Stops listening for new messages and discards the remaining queued
    /// messages.
    pub async fn unsubscribe(&self) -> io::Result<()> {
        let inner = self.inner.clone();
        unblock(move || inner.unsubscribe()).await
    }
}

/// A message received on a subject.
#[derive(Clone)]
pub struct Message {
    /// The subject this message came from.
    pub subject: String,

    /// Optional reply subject that may be used for sending a response to this
    /// message.
    pub reply: Option<String>,

    /// The message contents.
    pub data: Vec<u8>,

    /// Optional headers associated with this `Message`.
    pub headers: Option<Headers>,

    /// Client for publishing on the reply subject.
    #[doc(hidden)]
    pub client: crate::Client,

    /// Whether this message has already been successfully double-acked
    /// using `JetStream`.
    #[doc(hidden)]
    pub double_acked: Arc<AtomicBool>,
}

impl From<crate::Message> for Message {
    fn from(sync: crate::Message) -> Message {
        Message {
            subject: sync.subject,
            reply: sync.reply,
            data: sync.data,
            headers: sync.headers,
            client: sync.client,
            double_acked: sync.double_acked,
        }
    }
}

impl Message {
    /// Respond to a request message.
    pub async fn respond(&self, msg: impl AsRef<[u8]>) -> io::Result<()> {
        match self.reply.as_ref() {
            None => Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                "no reply subject available",
            )),
            Some(reply) => {
                if let Some(res) =
                    self.client.try_publish(reply, None, None, msg.as_ref())
                {
                    return res;
                }
                let reply = reply.to_string();
                let msg = msg.as_ref().to_vec();
                let client = self.client.clone();
                unblock(move || {
                    client.publish(&reply, None, None, msg.as_ref())
                })
                .await
            }
        }
    }
}

impl fmt::Debug for Message {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
        f.debug_struct("Message")
            .field("subject", &self.subject)
            .field("headers", &self.headers)
            .field("reply", &self.reply)
            .field("length", &self.data.len())
            .finish()
    }
}

/// Connect options.
#[derive(Debug, Default)]
pub struct Options {
    inner: crate::Options,
}

impl Options {
    /// `Options` for establishing a new NATS `Connection`.
    ///
    /// # Example
    /// ```
    /// # smol::block_on(async {
    /// let options = nats::asynk::Options::new();
    /// let nc = options.connect("demo.nats.io").await?;
    /// # std::io::Result::Ok(()) });
    /// ```
    pub fn new() -> Options {
        Options {
            inner: crate::Options::new(),
        }
    }

    /// Authenticate with NATS using a token.
    ///
    /// # Example
    /// ```
    /// # smol::block_on(async {
    /// let nc = nats::asynk::Options::with_token("t0k3n!")
    ///     .connect("demo.nats.io")
    ///     .await?;
    /// # std::io::Result::Ok(()) });
    /// ```
    pub fn with_token(token: &str) -> Options {
        Options {
            inner: crate::Options::with_token(token),
        }
    }

    /// Authenticate with NATS using a username and password.
    ///
    /// # Example
    /// ```
    /// # smol::block_on(async {
    /// let nc = nats::asynk::Options::with_user_pass("derek", "s3cr3t!")
    ///     .connect("demo.nats.io")
    ///     .await?;
    /// # std::io::Result::Ok(()) });
    /// ```
    pub fn with_user_pass(user: &str, password: &str) -> Options {
        Options {
            inner: crate::Options::with_user_pass(user, password),
        }
    }

    /// Authenticate with NATS using a `.creds` file.
    ///
    /// # Example
    /// ```no_run
    /// # smol::block_on(async {
    /// let nc = nats::asynk::Options::with_credentials("path/to/my.creds")
    ///     .connect("connect.ngs.global")
    ///     .await?;
    /// # std::io::Result::Ok(()) });
    /// ```
    pub fn with_credentials(path: impl AsRef<Path>) -> Options {
        Options {
            inner: crate::Options::with_credentials(path),
        }
    }

    /// Authenticate with a function that loads user JWT and a signature
    /// function.
    ///
    /// # Example
    /// ```no_run
    /// let seed = "SUANQDPB2RUOE4ETUA26CNX7FUKE5ZZKFCQIIW63OX225F2CO7UEXTM7ZY";
    /// let kp = nkeys::KeyPair::from_seed(seed).unwrap();
    ///
    /// fn load_jwt() -> std::io::Result<String> {
    ///     todo!()
    /// }
    ///
    /// # smol::block_on(async {
    /// let nc = nats::asynk::Options::with_jwt(load_jwt, move |nonce| kp.sign(nonce).unwrap())
    ///     .connect("localhost")
    ///     .await?;
    /// # std::io::Result::Ok(()) });
    /// ```
    pub fn with_jwt<J, S>(jwt_cb: J, sig_cb: S) -> Options
    where
        J: Fn() -> io::Result<String> + Send + Sync + 'static,
        S: Fn(&[u8]) -> Vec<u8> + Send + Sync + 'static,
    {
        Options {
            inner: crate::Options::with_jwt(jwt_cb, sig_cb),
        }
    }

    /// Authenticate with NATS using a public key and a signature function.
    ///
    /// # Example
    /// ```no_run
    /// let nkey = "UAMMBNV2EYR65NYZZ7IAK5SIR5ODNTTERJOBOF4KJLMWI45YOXOSWULM";
    /// let seed = "SUANQDPB2RUOE4ETUA26CNX7FUKE5ZZKFCQIIW63OX225F2CO7UEXTM7ZY";
    /// let kp = nkeys::KeyPair::from_seed(seed).unwrap();
    ///
    /// # smol::block_on(async {
    /// let nc = nats::asynk::Options::with_nkey(nkey, move |nonce| kp.sign(nonce).unwrap())
    ///     .connect("localhost")
    ///     .await?;
    /// # std::io::Result::Ok(()) });
    /// ```
    pub fn with_nkey<F>(nkey: &str, sig_cb: F) -> Options
    where
        F: Fn(&[u8]) -> Vec<u8> + Send + Sync + 'static,
    {
        Options {
            inner: crate::Options::with_nkey(nkey, sig_cb),
        }
    }

    /// Set client certificate and private key files.
    ///
    /// # Example
    /// ```no_run
    /// # smol::block_on(async {
    /// let nc = nats::asynk::Options::new()
    ///     .client_cert("client-cert.pem", "client-key.pem")
    ///     .connect("nats://localhost:4443")
    ///     .await?;
    /// # std::io::Result::Ok(()) });
    /// ```
    pub fn client_cert(
        self,
        cert: impl AsRef<Path>,
        key: impl AsRef<Path>,
    ) -> Options {
        Options {
            inner: self.inner.client_cert(cert, key),
        }
    }

    /// Add a name option to this configuration.
    ///
    /// # Example
    /// ```
    /// # smol::block_on(async {
    /// let nc = nats::asynk::Options::new()
    ///     .with_name("My App")
    ///     .connect("demo.nats.io")
    ///     .await?;
    /// # std::io::Result::Ok(()) });
    /// ```
    pub fn with_name(self, name: &str) -> Options {
        Options {
            inner: self.inner.with_name(name),
        }
    }

    /// Select option to not deliver messages that we have published.
    ///
    /// # Example
    /// ```
    /// # smol::block_on(async {
    /// let nc = nats::asynk::Options::new()
    ///     .no_echo()
    ///     .connect("demo.nats.io")
    ///     .await?;
    /// # std::io::Result::Ok(()) });
    /// ```
    pub fn no_echo(self) -> Options {
        Options {
            inner: self.inner.no_echo(),
        }
    }

    /// Set the maximum number of reconnect attempts.
    /// If no servers remain that are under this threshold,
    /// then no further reconnect shall be attempted.
    /// The reconnect attempt for a server is reset upon
    /// successfull connection.
    /// If None then there is no maximum number of attempts.
    ///
    /// # Example
    /// ```
    /// # smol::block_on(async {
    /// let nc = nats::asynk::Options::new()
    ///     .max_reconnects(3)
    ///     .connect("demo.nats.io")
    ///     .await?;
    /// # std::io::Result::Ok(()) });
    /// ```
    pub fn max_reconnects<T: Into<Option<usize>>>(
        self,
        max_reconnects: T,
    ) -> Options {
        Options {
            inner: self.inner.max_reconnects(max_reconnects),
        }
    }

    /// Set the maximum amount of bytes to buffer
    /// when accepting outgoing traffic in disconnected
    /// mode.
    ///
    /// The default value is 8mb.
    ///
    /// # Example
    /// ```
    /// # smol::block_on(async {
    /// let nc = nats::asynk::Options::new()
    ///     .reconnect_buffer_size(64 * 1024)
    ///     .connect("demo.nats.io")
    ///     .await?;
    /// # std::io::Result::Ok(()) });
    /// ```
    pub fn reconnect_buffer_size(
        self,
        reconnect_buffer_size: usize,
    ) -> Options {
        Options {
            inner: self.inner.reconnect_buffer_size(reconnect_buffer_size),
        }
    }

    /// Establish a `Connection` with a NATS server.
    ///
    /// Multiple servers may be specified by separating
    /// them with commas.
    ///
    /// # Example
    ///
    /// ```
    /// # smol::block_on(async {
    /// let options = nats::asynk::Options::new();
    /// let nc = options.connect("demo.nats.io").await?;
    /// # std::io::Result::Ok(()) });
    /// ```
    ///
    /// In the below case, the second server is configured
    /// to use TLS but the first one is not. Using the
    /// `tls_required` method can ensure that all
    /// servers are connected to with TLS, if that is
    /// your intention.
    ///
    ///
    /// ```
    /// # smol::block_on(async {
    /// let options = nats::asynk::Options::new();
    /// let nc = options
    ///     .connect("nats://demo.nats.io:4222,tls://demo.nats.io:4443")
    ///     .await?;
    /// # std::io::Result::Ok(()) });
    /// ```
    pub async fn connect(self, nats_url: &str) -> io::Result<Connection> {
        let nats_url = nats_url.to_string();
        let conn = unblock(move || self.inner.connect(&nats_url)).await?;
        Ok(Connection::new(conn))
    }

    /// Set a callback to be executed when connectivity to
    /// a server has been lost.
    ///
    /// # Example
    ///
    /// ```
    /// # smol::block_on(async {
    /// let nc = nats::asynk::Options::new()
    ///     .disconnect_callback(|| println!("connection has been lost"))
    ///     .connect("demo.nats.io")
    ///     .await?;
    /// # std::io::Result::Ok(()) });
    /// ```
    pub fn disconnect_callback<F>(self, cb: F) -> Self
    where
        F: Fn() + Send + Sync + 'static,
    {
        Options {
            inner: self.inner.disconnect_callback(cb),
        }
    }

    /// Set a callback to be executed when connectivity to a
    /// server has been reestablished.
    ///
    /// # Example
    ///
    /// ```
    /// # smol::block_on(async {
    /// let nc = nats::asynk::Options::new()
    ///     .reconnect_callback(|| println!("connection has been reestablished"))
    ///     .connect("demo.nats.io")
    ///     .await?;
    /// # std::io::Result::Ok(()) });
    /// ```
    pub fn reconnect_callback<F>(self, cb: F) -> Self
    where
        F: Fn() + Send + Sync + 'static,
    {
        Options {
            inner: self.inner.reconnect_callback(cb),
        }
    }

    /// Set a callback to be executed when the client has been
    /// closed due to exhausting reconnect retries to known servers
    /// or by completing a drain request.
    ///
    /// # Example
    ///
    /// ```
    /// # smol::block_on(async {
    /// let nc = nats::asynk::Options::new()
    ///     .close_callback(|| println!("connection has been closed"))
    ///     .connect("demo.nats.io")
    ///     .await?;
    /// # std::io::Result::Ok(()) });
    /// ```
    pub fn close_callback<F>(self, cb: F) -> Self
    where
        F: Fn() + Send + Sync + 'static,
    {
        Options {
            inner: self.inner.close_callback(cb),
        }
    }

    /// Set a callback to be executed for calculating the backoff duration
    /// to wait before a server reconnection attempt.
    ///
    /// The function takes the number of reconnects as an argument
    /// and returns the `Duration` that should be waited before
    /// making the next connection attempt.
    ///
    /// It is recommended that some random jitter is added to
    /// your returned `Duration`.
    ///
    /// # Example
    ///
    /// ```
    /// # use std::time::Duration;
    /// # smol::block_on(async {
    /// let nc = nats::asynk::Options::new()
    ///     .reconnect_delay_callback(|c| Duration::from_millis(std::cmp::min((c * 100) as u64, 8000)))
    ///     .connect("demo.nats.io")
    ///     .await?;
    /// # std::io::Result::Ok(()) });
    /// ```
    pub fn reconnect_delay_callback<F>(self, cb: F) -> Self
    where
        F: Fn(usize) -> Duration + Send + Sync + 'static,
    {
        Options {
            inner: self.inner.reconnect_delay_callback(cb),
        }
    }

    /// Setting this requires that TLS be set for all server connections.
    ///
    /// If you only want to use TLS for some server connections, you may
    /// declare them separately in the connect string by prefixing them
    /// with `tls://host:port` instead of `nats://host:port`.
    ///
    /// # Examples
    /// ```no_run
    /// # smol::block_on(async {
    /// let nc = nats::asynk::Options::new()
    ///     .tls_required(true)
    ///     .connect("tls://demo.nats.io:4443")
    ///     .await?;
    /// # std::io::Result::Ok(()) });
    /// ```
    pub fn tls_required(self, tls_required: bool) -> Options {
        Options {
            inner: self.inner.tls_required(tls_required),
        }
    }

    /// Adds a root certificate file.
    ///
    /// The file must be PEM encoded. All certificates in the file will be used.
    ///
    /// # Examples
    /// ```no_run
    /// # smol::block_on(async {
    /// let nc = nats::asynk::Options::new()
    ///     .add_root_certificate("my-certs.pem")
    ///     .connect("tls://demo.nats.io:4443")
    ///     .await?;
    /// # std::io::Result::Ok(()) });
    /// ```
    pub fn add_root_certificate(self, path: impl AsRef<Path>) -> Options {
        Options {
            inner: self.inner.add_root_certificate(path),
        }
    }
}