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
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
#![doc(html_root_url = "https://docs.rs/stan/0.0.16")]

//! NATS Streaming client wrapper built on top of [NATS.rs](https://github.com/nats-io/nats.rs)
//!
//! # Examples
//! ```
//! use nats;
//! use std::{io, str::from_utf8, time};
//!# mod test_utils;
//!
//! fn main() -> io::Result<()> {
//!     let nats_url = "nats://127.0.0.1:4222";
//!#    let server = test_utils::server()?;
//!#    let nats_url = &format!("localhost:{}", server.port);
//!     let nc = nats::connect(nats_url)?;
//!     let sc = stan::connect(nc, "test-cluster", "rust-client-1")?;
//!
//!     sc.publish("foo", "hello from rust 1")?;
//!
//!     sc.subscribe("foo", Default::default())?
//!         .with_handler(|msg| {
//!             println!("sub 1 got {:?}", from_utf8(&msg.data));
//!             Ok(())
//!         });
//!
//!     let sub = sc
//!         .subscribe(
//!             "foo",
//!             stan::SubscriptionConfig {
//!                 queue_group: Some("queue-group-name"),
//!                 durable_name: Some("my-durable-queue"),
//!                 start: stan::SubscriptionStart::AllAvailable,
//!                 ..Default::default()
//!             },
//!         )?
//!         .with_handler(|msg| {
//!             println!("sub 2 got {:?}", from_utf8(&msg.data));
//!             msg.ack()?;
//!             println!("manually acked!");
//!             Ok(())
//!         });
//!
//!     for msg in sc.subscribe("foo", Default::default())?.messages() {
//!         println!("sub 3 got {:?}", from_utf8(&msg.data));
//!         msg.ack()?;
//!         break; // just break for the example to run
//!     }
//!
//!     for msg in sc
//!         .subscribe("foo", Default::default())?
//!         .timeout_iter(time::Duration::from_secs(1))
//!     {
//!         println!("sub 4 got {:?}", from_utf8(&msg.data));
//!         msg.ack()?;
//!         break; // just break for the example to run
//!     }
//!
//!     sc.publish("foo", "hello from rust 2")?;
//!     sc.publish("foo", "hello from rust 3")?;
//!
//!     sub.unsubscribe()?;
//!
//!     sc.publish("foo", "hello from rust 4")?;
//!     Ok(())
//! }
//!```
//!
//! # Rationale
//!
//! We were interested in at-least-once delivery with NATS, and the
//! options here today are NATS Streaming, Lightbridge or Jetstream.
//!
//! Jetstream is the future of at-least-once delivery on NATS, but is
//! still in development, while NATS Streaming has been battle tested
//! in production.
//!
//! At the same time, the NATS team is providing an awesome rust
//! client that also has support for Jetstream, but they are not
//! planning on supporting NATS Streaming (reasonable since Jetstream
//! is their main focus).
//!
//! Since NATS Streaming is just a layer on top of NATS, this library
//! was written to just wrap the nats.rs client to handle the NATS
//! Streaming protocol, for those like us stuck with NATS Streaming.
//!

use bytes::Bytes;
use prost::Message as ProstMessage;
use std::{
    convert::TryInto,
    fmt, io,
    sync::{Arc, Mutex},
    time,
};

mod proto;
mod utils;

const DEFAULT_ACKS_SUBJECT: &str = "_STAN.acks";
const DEFAULT_DISCOVER_SUBJECT: &str = "_STAN.discover";
const DEFAULT_ACK_WAIT: i32 = 5;
const DEFAULT_MAX_INFLIGHT: i32 = 1024;
const PROTOCOL: i32 = 1;
const DEFAULT_PING_INTERVAL: i32 = 5;
const DEFAULT_PING_MAX_OUT: i32 = 88;

#[derive(Clone)]
/// NATS Streaming subscription
///
///# Example:
///```
/// use nats;
/// use std::{io, str::from_utf8, time};
///# mod test_utils;
///
/// fn main() -> io::Result<()> {
///     let nats_url = "nats://127.0.0.1:4222";
///#    let server = test_utils::server()?;
///#    let nats_url = &format!("localhost:{}", server.port);
///     let nc = nats::connect(nats_url)?;
///     let sc = stan::connect(nc, "test-cluster", "rust-client-1")?;
///#
///#     sc.publish("foo", "hello from rust 1")?;
///#
///      let sub1 = sc
///          .subscribe("foo", Default::default())?
///          .with_handler(|msg| {
///              println!("sub1 got {:?}", from_utf8(&msg.data));
///              msg.ack()?;
///              println!("manually acked!");
///              Ok(())
///          });
///
///      sc.subscribe("foo", Default::default())?
///          .with_handler(|msg| {
///              println!("sub 2 got {:?}", from_utf8(&msg.data));
///              Ok(())
///          });
///
///      for msg in sc.subscribe("foo", Default::default())?.messages() {
///          println!("sub 3 got {:?}", from_utf8(&msg.data));
///          msg.ack()?;
///#        break;
///      }
///
///      for msg in sc
///          .subscribe("foo", Default::default())?
///          .timeout_iter(time::Duration::from_secs(1))
///      {
///          println!("sub 4 got {:?}", from_utf8(&msg.data));
///          msg.ack()?;
///#        break;
///      }
///
///      Ok(())
///  }
pub struct Subscription {
    nats_subscription: nats::Subscription,
    inner: Arc<InnerSub>,
    // Keep a reference to Client to only drop it once the
    // subscription is closed. Note that we need it last in the struct
    // to be dropped after we drop the inner subscription
    // (i.e. unsubscribe)
    client: Client,
}

struct InnerSub {
    nats_connection: nats::Connection,
    client_id: String,
    subject: String,
    ack_inbox: String,
    durable_name: String,
    unsub_req_subject: String,
}

impl InnerSub {
    fn unsubscribe(&self) -> io::Result<()> {
        let req = proto::UnsubscribeRequest {
            client_id: self.client_id.to_owned(),
            subject: self.subject.to_owned(),
            inbox: self.ack_inbox.to_owned(),
            durable_name: self.durable_name.to_owned(),
        };
        let mut buf: Vec<u8> = Vec::new();
        req.encode(&mut buf)?;
        self.nats_connection.publish(&self.unsub_req_subject, &buf)
    }
}

impl Drop for InnerSub {
    fn drop(&mut self) {
        // We do not want to unsubscribe a durable subscription by
        // default, only non-durable ones. See:
        // https://github.com/nats-io/stan.go#closing-the-group
        if self.durable_name == "" {
            // TODO: better error handling?
            if let Err(err) = self.unsubscribe() {
                log::error!("stan - error closing subscription: {:?}", err)
            } else {
                log::debug!("stan - subscription closed")
            }
        }
    }
}

impl Subscription {
    /// Returns a blocking message iterator.
    /// Same as calling `iter()`.
    ///```
    ///# use nats;
    ///# use std::{io, str::from_utf8};
    ///# mod test_utils;
    ///#
    ///#  fn main() -> io::Result<()> {
    ///#     let nats_url = "nats://127.0.0.1:4222";
    ///#     let server = test_utils::server()?;
    ///#     let nats_url = &format!("localhost:{}", server.port);
    ///#     let nc = nats::connect(nats_url)?;
    ///#     let sc = stan::connect(nc, "test-cluster", "rust-client-1")?;
    ///#
    ///#     sc.publish("foo", "hello from rust 1")?;
    ///#
    ///      for msg in sc.subscribe("foo", Default::default())?.messages() {
    ///          println!("received: {:?}", from_utf8(&msg.data));
    ///          msg.ack()?;
    ///#         break; // just break for the example to run
    ///      }
    ///#
    ///#     Ok(())
    ///# }
    ///```
    pub fn messages(&self) -> Iter<'_> {
        Iter { subscription: self }
    }

    /// Returns a blocking message iterator.
    ///```
    ///# use nats;
    ///# use std::{io, str::from_utf8};
    ///# mod test_utils;
    ///#
    ///#  fn main() -> io::Result<()> {
    ///#     let nats_url = "nats://127.0.0.1:4222";
    ///#     let server = test_utils::server()?;
    ///#     let nats_url = &format!("localhost:{}", server.port);
    ///#     let nc = nats::connect(nats_url)?;
    ///#     let sc = stan::connect(nc, "test-cluster", "rust-client-1")?;
    ///#
    ///#     sc.publish("foo", "hello from rust 1")?;
    ///#
    ///      for msg in sc.subscribe("foo", Default::default())?.iter() {
    ///          println!("received: {:?}", from_utf8(&msg.data));
    ///          msg.ack()?;
    ///#         break; // just break for the example to run
    ///      }
    ///#
    ///#     Ok(())
    ///# }
    ///```
    pub fn iter(&self) -> Iter<'_> {
        Iter { subscription: self }
    }

    /// Returns a non-blocking message iterator.
    ///```
    ///# use nats;
    ///# use std::{io, str::from_utf8};
    ///# mod test_utils;
    ///#
    ///#  fn main() -> io::Result<()> {
    ///#     let nats_url = "nats://127.0.0.1:4222";
    ///#     let server = test_utils::server()?;
    ///#     let nats_url = &format!("localhost:{}", server.port);
    ///#     let nc = nats::connect(nats_url)?;
    ///#     let sc = stan::connect(nc, "test-cluster", "rust-client-1")?;
    ///#
    ///#     sc.publish("foo", "hello from rust 1")?;
    ///#
    ///      for msg in sc.subscribe("foo", Default::default())?.try_iter() {
    ///          println!("received: {:?}", from_utf8(&msg.data));
    ///          msg.ack()?;
    ///#         break; // just break for the example to run
    ///      }
    ///#
    ///#     Ok(())
    ///# }
    ///```
    pub fn try_iter(&self) -> TryIter<'_> {
        TryIter { subscription: self }
    }

    /// Returns a blocking message iterator with a time
    /// deadline for blocking.
    ///```
    ///# use nats;
    ///# use std::{io, str::from_utf8, time};
    ///# mod test_utils;
    ///#
    ///#  fn main() -> io::Result<()> {
    ///#     let nats_url = "nats://127.0.0.1:4222";
    ///#     let server = test_utils::server()?;
    ///#     let nats_url = &format!("localhost:{}", server.port);
    ///#     let nc = nats::connect(nats_url)?;
    ///#     let sc = stan::connect(nc, "test-cluster", "rust-client-1")?;
    ///#
    ///#     sc.publish("foo", "hello from rust 1")?;
    ///#
    ///      for msg in sc
    ///          .subscribe("foo", Default::default())?
    ///          .timeout_iter(time::Duration::from_secs(1))
    ///      {
    ///          println!("received: {:?}", from_utf8(&msg.data));
    ///          msg.ack()?;
    ///#         break; // just break for the example to run
    ///      }
    ///#     Ok(())
    ///# }
    ///```
    pub fn timeout_iter(&self, timeout: time::Duration) -> TimeoutIter<'_> {
        TimeoutIter {
            subscription: self,
            to: timeout,
        }
    }

    /// Process subscription messages in a separate thread.
    /// Messages are automatically acked unless the handler returns an error.
    /// Messages can also be manually acked by calling msg.ack().
    ///
    /// # Examples:
    ///
    /// Automatic ack:
    ///```
    ///# use nats;
    ///# use std::{io, str::from_utf8};
    ///# mod test_utils;
    ///#
    ///# fn main() -> io::Result<()> {
    ///#    let nats_url = "nats://127.0.0.1:4222";
    ///#    let server = test_utils::server()?;
    ///#    let nats_url = &format!("localhost:{}", server.port);
    ///#    let nc = nats::connect(nats_url)?;
    ///#    let sc = stan::connect(nc, "test-cluster", "rust-client-1")?;
    ///#
    ///     sc.subscribe("foo", Default::default())?
    ///         .with_handler(|msg| {
    ///             println!("{:?}", from_utf8(&msg.data));
    ///             Ok(())
    ///         });
    ///
    ///#    Ok(())
    ///# }
    ///```
    ///
    /// Manual ack:
    ///```
    ///# use nats;
    ///# use std::{io, str::from_utf8};
    ///# mod test_utils;
    ///#
    ///# fn main() -> io::Result<()> {
    ///#    let nats_url = "nats://127.0.0.1:4222";
    ///#    let server = test_utils::server()?;
    ///#    let nats_url = &format!("localhost:{}", server.port);
    ///#    let nc = nats::connect(nats_url)?;
    ///#    let sc = stan::connect(nc, "test-cluster", "rust-client-1")?;
    ///#
    ///     sc.subscribe("foo", Default::default())?
    ///         .with_handler(|msg| {
    ///             println!("{:?}", from_utf8(&msg.data));
    ///             msg.ack()?;
    ///             println!("this happens after the ack");
    ///             Ok(())
    ///         });
    ///
    ///#    sc.publish("foo", "hello from rust 1")?;
    ///#    Ok(())
    ///# }
    ///```
    pub fn with_handler<F>(self, handler: F) -> nats::subscription::Handler
    where
        F: Fn(&Message) -> io::Result<()> + Send + 'static,
    {
        self.nats_subscription.clone().with_handler(move |msg| {
            let nats_connection = self.inner.nats_connection.to_owned();
            let ack_inbox = self.inner.ack_inbox.to_owned();
            let msg = Message::from_nats_message(msg, nats_connection, ack_inbox)?;
            handler(&msg)?;
            msg.ack()
        })
    }

    /// Get the next message with blocking, or None if the subscription has been closed
    /// Note: the message needs to be manually acked!
    ///```
    /// use nats;
    /// use std::{io, str::from_utf8};
    ///# mod test_utils;
    ///#
    /// fn main() -> io::Result<()> {
    ///    let nats_url = "nats://127.0.0.1:4222";
    ///#   let server = test_utils::server()?;
    ///#   let nats_url = &format!("localhost:{}", server.port);
    ///    let nc = nats::connect(nats_url)?;
    ///    let sc = stan::connect(nc, "test-cluster", "rust-client-1")?;
    ///    sc.publish("foo", "hello from rust 1")?;
    ///
    ///    let sub = sc.subscribe("foo", Default::default())?;
    ///    if let Some(msg) = sub.next() {
    ///       println!("received: {:?}", from_utf8(&msg.data));
    ///       msg.ack()?
    ///    }
    ///
    ///    Ok(())
    /// }
    ///```
    pub fn next(&self) -> Option<Message> {
        let msg = self.nats_subscription.next()?;
        let nats_connection = self.inner.nats_connection.to_owned();
        let ack_inbox = self.inner.ack_inbox.to_owned();
        Message::from_nats_message(msg, nats_connection, ack_inbox).ok()
    }

    /// Get the next message without blocking, or None if none available
    /// Note: the message needs to be manually acked!
    ///```
    /// use nats;
    /// use std::{io, str::from_utf8};
    ///# mod test_utils;
    ///#
    /// fn main() -> io::Result<()> {
    ///    let nats_url = "nats://127.0.0.1:4222";
    ///#   let server = test_utils::server()?;
    ///#   let nats_url = &format!("localhost:{}", server.port);
    ///    let nc = nats::connect(nats_url)?;
    ///    let sc = stan::connect(nc, "test-cluster", "rust-client-1")?;
    ///    sc.publish("foo", "hello from rust 1")?;
    ///
    ///    let sub = sc.subscribe("foo", Default::default())?;
    ///    if let Some(msg) = sub.try_next() {
    ///       println!("received: {:?}", from_utf8(&msg.data));
    ///       msg.ack()?
    ///    }
    ///
    ///    Ok(())
    /// }
    ///```
    pub fn try_next(&self) -> Option<Message> {
        let msg = self.nats_subscription.try_next()?;
        let nats_connection = self.inner.nats_connection.to_owned();
        let ack_inbox = self.inner.ack_inbox.to_owned();
        Message::from_nats_message(msg, nats_connection, ack_inbox).ok()
    }

    /// Get the next message without blocking, or None if none available
    /// Note: the message needs to be manually acked!
    ///```
    /// use nats;
    /// use std::{io, str::from_utf8};
    ///# mod test_utils;
    ///#
    /// fn main() -> io::Result<()> {
    ///    let nats_url = "nats://127.0.0.1:4222";
    ///#   let server = test_utils::server()?;
    ///#   let nats_url = &format!("localhost:{}", server.port);
    ///    let nc = nats::connect(nats_url)?;
    ///    let sc = stan::connect(nc, "test-cluster", "rust-client-1")?;
    ///    sc.publish("foo", "hello from rust 1")?;
    ///
    ///    let sub = sc.subscribe("foo", Default::default())?;
    ///    if let Ok(msg) = sub.next_timeout(std::time::Duration::from_secs(1)) {
    ///       println!("received: {:?}", from_utf8(&msg.data));
    ///       msg.ack()?
    ///    }
    ///
    ///    Ok(())
    /// }
    ///```
    pub fn next_timeout(&self, timeout: time::Duration) -> io::Result<Message> {
        let msg = self.nats_subscription.next_timeout(timeout)?;
        let nats_connection = self.inner.nats_connection.to_owned();
        let ack_inbox = self.inner.ack_inbox.to_owned();
        Message::from_nats_message(msg, nats_connection, ack_inbox)
    }

    /// Close this subscription.
    ///
    /// For subscriptions that are not durable (i.e. with no
    /// durable_name), this is called automatically when the
    /// subscription is dropped.
    ///
    /// For durable subscriptions, beware that unsubscribing all the
    /// clients will also delete the durable queue.
    ///
    ///```
    /// use nats;
    /// use std::{io, str::from_utf8};
    ///# mod test_utils;
    ///#
    /// fn main() -> io::Result<()> {
    ///    let nats_url = "nats://127.0.0.1:4222";
    ///#   let server = test_utils::server()?;
    ///#   let nats_url = &format!("localhost:{}", server.port);
    ///    let nc = nats::connect(nats_url)?;
    ///    let sc = stan::connect(nc, "test-cluster", "rust-client-1")?;
    ///
    ///    let sub = sc.subscribe("foo", Default::default())?;
    ///    sub.unsubscribe();
    ///
    ///    Ok(())
    /// }
    ///```
    pub fn unsubscribe(&self) -> io::Result<()> {
        self.inner.unsubscribe()
    }
}

/// 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: time::Duration,
}

impl<'a> Iterator for TimeoutIter<'a> {
    type Item = Message;
    fn next(&mut self) -> Option<Self::Item> {
        self.subscription.next_timeout(self.to).ok()
    }
}

#[derive(Debug)]
/// List of possible starting positions for a new `Subscription`
pub enum SubscriptionStart {
    /// Only receive new messages, starting from now
    NewOnly,
    /// Start receiving from the last received message (default)
    LastReceived,
    /// Send all available messages on the subject
    AllAvailable,
    /// Start at a given message sequence. You can use that to build your own durable queue
    FromSequence(u64),
    /// Replay starting from a given timestamp (need to be in the past)
    FromTimestamp(time::SystemTime),
    /// Replay from a duration in the past
    FromPast(time::Duration),
}

impl Default for SubscriptionStart {
    fn default() -> Self {
        Self::LastReceived
    }
}

#[derive(Debug)]
/// Configuration to pass to subscription. Defaults to no queue group,
/// no durable queue and starts from last received message.
pub struct SubscriptionConfig<'a> {
    /// Name of the queue group, see: https://docs.nats.io/nats-concepts/queue
    pub queue_group: Option<&'a str>,
    /// Set this to keep position after reconnect, see: https://docs.nats.io/developing-with-nats-streaming/durables
    pub durable_name: Option<&'a str>,
    /// Position to start the subscription from
    pub start: SubscriptionStart,
    pub max_in_flight: i32,
    pub ack_wait_in_secs: i32,
}

impl<'a> Default for SubscriptionConfig<'a> {
    fn default() -> Self {
        Self {
            queue_group: None,
            durable_name: None,
            start: SubscriptionStart::default(),
            max_in_flight: DEFAULT_MAX_INFLIGHT,
            ack_wait_in_secs: DEFAULT_ACK_WAIT,
        }
    }
}

impl<'a> SubscriptionConfig<'a> {
    fn start_position(&self) -> i32 {
        match self.start {
            SubscriptionStart::NewOnly => proto::StartPosition::NewOnly,
            SubscriptionStart::LastReceived => proto::StartPosition::LastReceived,
            SubscriptionStart::AllAvailable => proto::StartPosition::First,
            SubscriptionStart::FromSequence(_) => proto::StartPosition::SequenceStart,
            SubscriptionStart::FromTimestamp(_) | SubscriptionStart::FromPast(_) => {
                proto::StartPosition::TimeDeltaStart
            }
        }
        .into()
    }

    fn start_sequence(&self) -> u64 {
        if let SubscriptionStart::FromSequence(seq) = self.start {
            seq
        } else {
            0
        }
    }

    fn start_time_delta(&self) -> io::Result<i64> {
        match self.start {
            SubscriptionStart::FromTimestamp(t) => {
                let now = time::SystemTime::now();
                if t > now {
                    return Err(io::Error::new(
                        io::ErrorKind::InvalidInput,
                        "SubscriptionStart::FromTimestamp is in the future",
                    ));
                }
                match now.duration_since(t) {
                    Ok(d) => Ok(-utils::u128_to_i64(d.as_nanos())?),
                    Err(err) => Err(io::Error::new(io::ErrorKind::InvalidInput, err)),
                }
            }
            SubscriptionStart::FromPast(d) => Ok(-utils::u128_to_i64(d.as_nanos())?),
            _ => Ok(0),
        }
    }
}

#[derive(Debug, Clone)]
/// NATS Streaming message received on a given `Subscription`
pub struct Message {
    pub sequence: u64,
    pub subject: String,
    pub data: Vec<u8>,
    pub timestamp: time::SystemTime,
    pub redelivered: bool,
    pub redelivery_count: u32,
    nats_connection: nats::Connection,
    ack_inbox: String,
    acked: Arc<Mutex<bool>>,
}

impl Message {
    fn from_nats_message(
        msg: nats::Message,
        nats_connection: nats::Connection,
        ack_inbox: String,
    ) -> io::Result<Self> {
        let m = proto::MsgProto::decode(Bytes::from(msg.data))?;
        let sequence = m.sequence.to_owned();
        let timestamp = time::SystemTime::UNIX_EPOCH
            + time::Duration::from_nanos(m.timestamp.try_into().unwrap());
        let acked = Arc::new(Mutex::new(false));

        Ok(Self {
            sequence: sequence.to_owned(),
            subject: m.subject.to_owned(),
            data: m.data,
            timestamp,
            redelivered: m.redelivered,
            redelivery_count: m.redelivery_count,
            nats_connection,
            ack_inbox,
            acked,
        })
    }

    /// Ack message
    pub fn ack(&self) -> io::Result<()> {
        let mut acked = self.acked.lock().unwrap();
        if !*acked {
            let ack = proto::Ack {
                subject: self.subject.to_string(),
                sequence: self.sequence.to_owned(),
            };
            let mut buf: Vec<u8> = Vec::new();
            ack.encode(&mut buf)?;
            self.nats_connection.publish(&self.ack_inbox, &buf)?;
            *acked = true;
        }
        Ok(())
    }
}

#[derive(Clone)]
/// NATS Streaming client
pub struct Client {
    cluster_id: String,
    conn_id: Vec<u8>,
    discover_subject: String,
    heartbeat_subject: String,
    inner: Arc<InnerClient>,
}

struct InnerClient {
    nats_connection: nats::Connection,
    client_id: String,
    pub_prefix: String,
    sub_req_subject: String,
    unsub_req_subject: String,
    close_req_subject: String,
    sub_close_req_subject: String,
}

fn nats_request<Req: prost::Message, Res: prost::Message + Default>(
    nats_connection: nats::Connection,
    subject: &str,
    req: Req,
) -> io::Result<Res> {
    let mut buf = Vec::new();
    req.encode(&mut buf)?;
    let resp = nats_connection.request_timeout(&subject, buf, time::Duration::from_secs(2))?;
    Ok(Res::decode(Bytes::from(resp.data))?)
}

impl Drop for InnerClient {
    fn drop(&mut self) {
        let res: io::Result<proto::CloseResponse> = nats_request(
            self.nats_connection.clone(),
            &self.close_req_subject,
            proto::CloseRequest {
                client_id: self.client_id.to_owned(),
            },
        );

        if let Err(err) = res {
            log::error!("stan - error closing client: {}", err)
        } else {
            log::debug!("stan - client closed")
        }
    }
}

impl Client {
    /// Start a new client, establishing a new NATS Streaming connection,
    /// Same as stan::connect().
    ///
    /// # Example:
    ///```
    ///# use nats;
    ///# use std::io;
    ///# mod test_utils;
    ///#
    ///# fn main() -> io::Result<()> {
    ///    let nats_url = "nats://127.0.0.1:4222";
    ///#   let server = test_utils::server()?;
    ///#   let nats_url = &format!("localhost:{}", server.port);
    ///    let nc = nats::connect(nats_url)?;
    ///    let sc = stan::Client::start(nc, "test-cluster", "rust-client-1")?;
    ///#    Ok(())
    ///# }
    ///```
    pub fn start(
        nats_connection: nats::Connection,
        cluster_id: &str,
        client_id: &str,
    ) -> io::Result<Client> {
        let discover_subject = DEFAULT_DISCOVER_SUBJECT.to_owned() + "." + cluster_id;
        let heartbeat_subject = utils::uuid();
        let conn_id = utils::uuid().as_bytes().to_owned();

        // Start heartbeat handler
        nats_connection
            .subscribe(&heartbeat_subject)?
            .with_handler(|msg| {
                if let Some(reply) = msg.reply {
                    msg.client.publish(&reply, None, None, &[])?;
                }
                Ok(())
            });

        let conn_req = proto::ConnectRequest {
            client_id: client_id.to_string(),
            heartbeat_inbox: heartbeat_subject.to_owned(),
            protocol: PROTOCOL,
            conn_id: conn_id.to_owned(),
            ping_interval: DEFAULT_PING_INTERVAL,
            ping_max_out: DEFAULT_PING_MAX_OUT,
        };

        let conn_resp: proto::ConnectResponse =
            nats_request(nats_connection.clone(), &discover_subject, conn_req)?;
        if conn_resp.error != "" {
            return Err(io::Error::new(io::ErrorKind::Other, conn_resp.error));
        }

        Ok(Client {
            cluster_id: cluster_id.to_owned(),
            conn_id: conn_id.to_owned(),
            discover_subject,
            heartbeat_subject,

            inner: Arc::new(InnerClient {
                nats_connection,
                client_id: client_id.to_owned(),
                pub_prefix: conn_resp.pub_prefix,
                sub_req_subject: conn_resp.sub_requests,
                unsub_req_subject: conn_resp.unsub_requests,
                close_req_subject: conn_resp.close_requests,
                sub_close_req_subject: conn_resp.sub_close_requests,
            }),
        })
    }

    /// Publish to a given subject. Will return an error if failed to
    /// receive a ack back from the streaming server.
    ///
    /// # Example:
    ///```
    ///# use nats;
    ///# use std::io;
    ///# mod test_utils;
    ///#
    /// fn main() -> io::Result<()> {
    ///    let nats_url = "nats://127.0.0.1:4222";
    ///#   let server = test_utils::server()?;
    ///#   let nats_url = &format!("localhost:{}", server.port);
    ///    let nc = nats::connect(nats_url)?;
    ///#    let sc = stan::connect(nc, "test-cluster", "rust-client-1")?;
    ///#
    ///    sc.publish("foo", "hello from rust 1")
    ///# }
    ///```
    pub fn publish(&self, subject: &str, msg: impl AsRef<[u8]>) -> io::Result<()> {
        let stan_subject = self.inner.pub_prefix.to_owned() + "." + subject;

        let msg = proto::PubMsg {
            client_id: self.inner.client_id.to_owned(),
            guid: utils::uuid(),
            subject: subject.to_owned(),
            reply: "".to_string(), // unused in stan.go
            data: msg.as_ref().to_vec(),
            conn_id: self.conn_id.to_owned(),
            sha256: [].to_vec(), // unused in stan.go
        };

        let ack_inbox = DEFAULT_ACKS_SUBJECT.to_owned() + "." + &utils::uuid();
        let ack_sub = self.inner.nats_connection.subscribe(&ack_inbox)?;

        let mut buf: Vec<u8> = Vec::new();
        msg.encode(&mut buf)?;
        self.inner
            .nats_connection
            .publish_request(&stan_subject, &ack_inbox, &buf)?;

        let resp = ack_sub.next_timeout(time::Duration::from_secs(1))?;
        let ack = proto::PubAck::decode(Bytes::from(resp.data))?;
        if ack.error != "" {
            return Err(io::Error::new(io::ErrorKind::Other, ack.error));
        }
        Ok(())
    }

    /// Start a subscription.
    ///
    /// # Example:
    ///```
    /// use nats;
    /// use std::{io, str::from_utf8};
    ///# mod test_utils;
    ///#
    /// fn main() -> io::Result<()> {
    ///    let nats_url = "nats://127.0.0.1:4222";
    ///#   let server = test_utils::server()?;
    ///#   let nats_url = &format!("localhost:{}", server.port);
    ///    let nc = nats::connect(nats_url)?;
    ///    let sc = stan::connect(nc, "test-cluster", "rust-client-1")?;
    ///
    ///    sc.publish("foo", "hello from rust 1")?;
    ///
    ///    let sub = sc
    ///        .subscribe("foo", Default::default())?
    ///        .with_handler(|msg| {
    ///            println!("{:?}", from_utf8(&msg.data));
    ///            Ok(())
    ///        });
    ///
    ///    sc.publish("foo", "hello from rust 2")?;
    ///    sc.publish("foo", "hello from rust 3")
    /// }
    ///```
    pub fn subscribe(&self, subject: &str, config: SubscriptionConfig) -> io::Result<Subscription> {
        let inbox = self.inner.nats_connection.new_inbox();
        let sub = self.inner.nats_connection.subscribe(&inbox)?;
        let durable_name = config.durable_name.unwrap_or("").to_string();

        let req = proto::SubscriptionRequest {
            client_id: self.inner.client_id.to_owned(),
            subject: subject.to_string(),
            q_group: config.queue_group.unwrap_or("").to_string(),
            inbox: inbox.to_owned(),
            durable_name: durable_name.to_owned(),
            max_in_flight: config.max_in_flight,
            ack_wait_in_secs: config.ack_wait_in_secs,
            start_position: config.start_position(),
            start_sequence: config.start_sequence(),
            start_time_delta: config.start_time_delta()?,
        };
        let res: proto::SubscriptionResponse = nats_request(
            self.inner.nats_connection.clone(),
            &self.inner.sub_req_subject,
            req,
        )?;
        if res.error != "" {
            return Err(io::Error::new(io::ErrorKind::Other, res.error));
        }

        Ok(Subscription {
            nats_subscription: sub,
            client: self.clone(),
            inner: Arc::new(InnerSub {
                ack_inbox: res.ack_inbox,
                nats_connection: self.inner.nats_connection.to_owned(),
                client_id: self.inner.client_id.to_owned(),
                subject: subject.to_owned(),
                unsub_req_subject: self.inner.unsub_req_subject.to_owned(),
                durable_name: durable_name.to_owned(),
            }),
        })
    }
}

impl fmt::Debug for Client {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Client")
            .field("cluster_id", &self.cluster_id)
            .field("client_id", &self.inner.client_id)
            .field("conn_id", &self.conn_id)
            .field("pub_prefix", &self.inner.pub_prefix)
            .field("sub_req_subject", &self.inner.sub_req_subject)
            .field("unsub_req_subject", &self.inner.unsub_req_subject)
            .field("close_req_subject", &self.inner.close_req_subject)
            .field("sub_close_req_subject", &self.inner.sub_close_req_subject)
            .field("discover_subject", &self.discover_subject)
            .field("heartbeat_subject", &self.heartbeat_subject)
            .finish()
    }
}

/// Establishes a new NATS Streaming connection, returning a `Client`
///
/// # Example:
///```
///# use nats;
///# use std::io;
///# mod test_utils;
///#
///# fn main() -> io::Result<()> {
///    let nats_url = "nats://127.0.0.1:4222";
///#   let server = test_utils::server()?;
///#   let nats_url = &format!("localhost:{}", server.port);
///    let nc = nats::connect(nats_url)?;
///     let sc = stan::connect(nc, "test-cluster", "rust-client-1")?;
///#    Ok(())
///# }
///```
pub fn connect(
    nats_connection: nats::Connection,
    cluster_id: &str,
    client_id: &str,
) -> io::Result<Client> {
    Client::start(nats_connection, cluster_id, client_id)
}