/
mod.rs
1814 lines (1622 loc) · 64.9 KB
/
mod.rs
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
996
997
998
999
1000
// Copyright 2020-2022 The NATS Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Support for the `JetStream` at-least-once messaging system.
//!
//! # Examples
//!
//! Create a new stream with default options:
//!
//! ```no_run
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! let nc = nats::connect("my_server::4222")?;
//! let js = nats::jetstream::new(nc);
//!
//! // add_stream converts a str into a
//! // default `StreamConfig`.
//! js.add_stream("my_stream")?;
//!
//! # Ok(()) }
//! ```
//!
//! Create a new stream with configuration:
//!
//! ```no_run
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! use nats::jetstream::{StreamConfig, StorageType};
//!
//! let nc = nats::connect("my_server::4222")?;
//! let js = nats::jetstream::new(nc);
//!
//! js.add_stream(StreamConfig {
//! name: "my_memory_stream".to_string(),
//! max_bytes: 5 * 1024 * 1024 * 1024,
//! storage: StorageType::Memory,
//! ..Default::default()
//! })?;
//!
//! # Ok(()) }
//! ```
//!
//! Create a new consumer:
//!
//! ```no_run
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! let nc = nats::connect("my_server::4222")?;
//! let js = nats::jetstream::new(nc);
//!
//! js.add_stream("my_stream")?;
//! js.add_consumer("my_stream", "my_consumer")?;
//!
//! # Ok(()) }
//! ```
//!
//! Create a new consumer with configuration:
//!
//! ```no_run
//! use nats::jetstream::{ ConsumerConfig };
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! let nc = nats::connect("my_server::4222")?;
//! let js = nats::jetstream::new(nc);
//!
//! js.add_stream("my_stream")?;
//! js.add_consumer("my_stream", ConsumerConfig {
//! deliver_subject: Some("my_deliver_subject".to_string()),
//! durable_name: Some("my_durable_consumer".to_string()),
//! ..Default::default()
//! })?;
//!
//! # Ok(()) }
//! ```
//!
//! Create a new subscription:
//!
//! ```no_run
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! let nc = nats::connect("my_server::4222")?;
//! let js = nats::jetstream::new(nc);
//!
//! js.add_stream("my_stream")?;
//! let subscription = js.subscribe("my_stream")?;
//!
//! # Ok(()) }
//! ```
//! This will attempt to bind to an existing consumer if it exists, otherwise it will create a new
//! internally managed consumer resource that gets destroyed when the subscription is dropped.
//!
use std::{
collections::VecDeque,
convert::TryFrom,
error, fmt,
fmt::Debug,
io::{self, ErrorKind},
time::Duration,
};
use parking_lot::Mutex;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;
use std::thread;
use serde::{de::DeserializeOwned, Deserialize, Serialize};
use serde_repr::{Deserialize_repr, Serialize_repr};
const ORDERED_IDLE_HEARTBEAT: Duration = Duration::from_nanos(5_000_000_000);
/// Pull subscriptions
pub mod pull_subscription;
/// Push subscriptions
pub mod push_subscription;
mod types;
// We use a fully qualified crate path so these are documented as re-exports.
pub use crate::jetstream::pull_subscription::PullSubscription;
pub use crate::jetstream::push_subscription::PushSubscription;
pub use types::*;
#[deprecated(note = "Use PullSubscribeOptions instead")]
#[doc(hidden)]
pub type PullSubscibeOptions = PullSubscribeOptions;
use crate::{
header::{self, HeaderMap},
Connection, Message,
};
/// `JetStream` options
#[derive(Clone)]
pub struct JetStreamOptions {
pub(crate) api_prefix: String,
pub(crate) has_domain: bool,
}
impl Debug for JetStreamOptions {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
f.debug_map()
.entry(&"api_prefix", &self.api_prefix)
.finish()
}
}
impl Default for JetStreamOptions {
fn default() -> JetStreamOptions {
JetStreamOptions {
api_prefix: "$JS.API.".to_string(),
has_domain: false,
}
}
}
impl JetStreamOptions {
/// `Options` for `JetStream` operations.
///
/// # Example
///
/// ```
/// let options = nats::JetStreamOptions::new();
/// ```
pub fn new() -> JetStreamOptions {
JetStreamOptions::default()
}
/// Set a custom `JetStream` API prefix.
///
/// # Example
///
/// ```
/// let options = nats::JetStreamOptions::new()
/// .api_prefix("some_exported_prefix".to_string());
/// ```
pub fn api_prefix(mut self, mut api_prefix: String) -> Self {
if !api_prefix.ends_with('.') {
api_prefix.push('.');
}
self.api_prefix = api_prefix;
self
}
/// Set a custom `JetStream` API prefix from a domain.
///
/// # Example
///
/// ```
/// let options = nats::JetStreamOptions::new()
/// .domain("some_domain");
/// ```
pub fn domain(mut self, domain: &str) -> Self {
if domain.is_empty() {
self.api_prefix("".to_string())
} else {
self.has_domain = true;
self.api_prefix(format!("$JS.{}.API", domain))
}
}
}
/// `ApiResponse` is a standard response from the `JetStream` JSON Api
#[derive(Debug, Serialize, Deserialize)]
#[serde(untagged)]
enum ApiResponse<T> {
// Note:
// Serde will try to match the data against each variant in order and the first one that
// deserializes successfully is the one returned.
//
// Therefore the error case must come first, otherwise it can be ignored.
Err { error: Error },
Ok(T),
}
/// `ErrorCode` which can be returned from a server an a response when an error occurs.
#[derive(Debug, PartialEq, Eq, Serialize_repr, Deserialize_repr, Clone, Copy)]
#[repr(u64)]
pub enum ErrorCode {
/// Peer not a member
ClusterPeerNotMember = 10040,
/// Consumer expected to be ephemeral but detected a durable name set in subject
ConsumerEphemeralWithDurableInSubject = 10019,
/// Stream external delivery prefix {prefix} overlaps with stream subject {subject}
StreamExternalDelPrefixOverlaps = 10022,
/// Resource limits exceeded for account
AccountResourcesExceeded = 10002,
/// JetStream system temporarily unavailable
ClusterNotAvail = 10008,
/// Subjects overlap with an existing stream
StreamSubjectOverlap = 10065,
/// Wrong last sequence: {seq}
StreamWrongLastSequence = 10071,
/// Template name in subject does not match request
TemplateNameNotMatchSubject = 10073,
/// No suitable peers for placement
ClusterNoPeers = 10005,
/// Consumer expected to be ephemeral but a durable name was set in request
ConsumerEphemeralWithDurableName = 10020,
/// Insufficient resources
InsufficientResources = 10023,
/// Stream mirror must have max message size >= source
MirrorMaxMessageSizeTooBig = 10030,
/// Generic stream template deletion failed error string
StreamTemplateDelete = 10067,
/// Bad request
BadRequest = 10003,
/// Not currently supported in clustered mode
ClusterUnSupportFeature = 10036,
/// Consumer not found
ConsumerNotFound = 10014,
/// Stream source must have max message size >= target
SourceMaxMessageSizeTooBig = 10046,
/// Generic stream assignment error string
StreamAssignment = 10048,
/// Message size exceeds maximum allowed
StreamMessageExceedsMaximum = 10054,
/// Generic template creation failed string
StreamTemplateCreate = 10066,
/// Invalid JSON
InvalidJSON = 10025,
/// Stream external delivery prefix {prefix} must not contain wildcards
StreamInvalidExternalDeliverySubject = 10024,
/// Restore failed: {err}
StreamRestore = 10062,
/// Incomplete results
ClusterIncomplete = 10004,
/// Account not found
NoAccount = 10035,
/// General RAFT error string
RaftGeneral = 10041,
/// JetStream unable to subscribe to restore snapshot {subject}: {err}
RestoreSubscribeFailed = 10042,
/// General stream deletion error string
StreamDelete = 10050,
/// Stream external api prefix {prefix} must not overlap with {subject}
StreamExternalApiOverlap = 10021,
/// Stream mirrors can not also contain subjects
MirrorWithSubjects = 10034,
/// JetStream not enabled
NotEnabled = 10076,
/// JetStream not enabled for account
NotEnabledForAccount = 10039,
/// Sequence {seq} not found
SequenceNotFound = 10043,
/// Mirror configuration can not be updated
StreamMirrorNotUpdatable = 10055,
/// Expected stream sequence does not match
StreamSequenceNotMatch = 10063,
/// Wrong last msg Id: {id}
StreamWrongLastMsgId = 10070,
/// JetStream unable to open temp storage for restore
TempStorageFailed = 10072,
/// Insufficient storage resources available
StorageResourcesExceeded = 10047,
/// Stream name in subject does not match request
StreamMismatch = 10056,
/// Expected stream does not match
StreamNotMatch = 10060,
/// Generic mirror consumer setup failure string
MirrorConsumerSetupFailed = 10029,
/// Expected an empty request payload
NotEmptyRequest = 10038,
/// Stream name already in use
StreamNameExist = 10058,
/// Tags placement not supported for operation
ClusterTags = 10011,
/// Maximum consumers limit reached
MaximumConsumersLimit = 10026,
/// General source consumer setup failure string
SourceConsumerSetupFailed = 10045,
/// General consumer creation failure string
ConsumerCreate = 10012,
/// Consumer expected to be durable but no durable name set in subject
ConsumerDurableNameNotInSubject = 10016,
/// General stream limits exceeded error string
StreamLimits = 10053,
/// Replicas configuration can not be updated
StreamReplicasNotUpdatable = 10061,
/// Template not found
StreamTemplateNotFound = 10068,
/// JetStream cluster not assigned to this server
ClusterNotAssigned = 10007,
/// JetStream cluster can not handle request
ClusterNotLeader = 10009,
/// Consumer name already in use
ConsumerNameExist = 10013,
/// Stream mirrors can not also contain other sources
MirrorWithSources = 10031,
/// Stream not found
StreamNotFound = 10059,
/// JetStream clustering support required
ClusterRequired = 10010,
/// Consumer expected to be durable but a durable name was not set
ConsumerDurableNameNotSet = 10018,
/// Maximum number of streams reached
MaximumStreamsLimit = 10027,
/// Stream mirrors can not have both start seq and start time configured
MirrorWithStartSeqAndTime = 10032,
/// Snapshot failed: {err}
StreamSnapshot = 10064,
/// Generic stream update error string
StreamUpdate = 10069,
/// JetStream not in clustered mode
ClusterNotActive = 10006,
/// Consumer name in subject does not match durable name in request
ConsumerDurableNameNotMatchSubject = 10017,
/// Insufficient memory resources available
MemoryResourcesExceeded = 10028,
/// Stream mirrors can not contain filtered subjects
MirrorWithSubjectFilters = 10033,
/// Generic stream creation error string
StreamCreate = 10049,
/// Server is not a member of the cluster
ClusterServerNotMember = 10044,
/// No message found
NoMessageFound = 10037,
/// Deliver subject not valid
SnapshotDeliverSubjectInvalid = 10015,
/// General stream failure string
StreamGeneralErrorF = 10051,
/// Stream configuration validation error string
StreamInvalidConfigF = 10052,
/// Replicas > 1 not supported in non-clustered mode
StreamReplicasNotSupported = 10074,
/// Generic message deletion failure error string
StreamMsgDeleteFailedF = 10057,
/// Peer remap failed
PeerRemap = 10075,
/// Generic error when storing a message failed
StreamStoreFailedF = 10077,
/// Consumer config required
ConsumerConfigRequired = 10078,
/// Consumer deliver subject has wildcards
ConsumerDeliverToWildcards = 10079,
/// Consumer in push mode can not set max waiting
ConsumerPushMaxWaiting = 10080,
/// Consumer deliver subject forms a cycle
ConsumerDeliverCycle = 10081,
/// Consumer requires ack policy for max ack pending
ConsumerMaxPendingAckPolicyRequired = 10082,
/// JSConsumerMaxRequestBatchNegative consumer max request batch needs to be > 0
JSConsumerMaxRequestBatchNegative = 10114,
/// JSConsumerMaxRequestExpiresToSmall consumer max request expires needs to be >= 1ms
JSConsumerMaxRequestExpiresToSmall = 10115,
/// Consumer idle heartbeat needs to be >= 100ms
ConsumerSmallHeartbeat = 10083,
/// Consumer in pull mode requires ack policy
ConsumerPullRequiresAck = 10084,
/// Consumer in pull mode requires a durable name
ConsumerPullNotDurable = 10085,
/// Consumer in pull mode can not have rate limit set
ConsumerPullWithRateLimit = 10086,
/// Consumer max waiting needs to be positive
ConsumerMaxWaitingNegative = 10087,
/// Consumer idle heartbeat requires a push based consumer
ConsumerHBRequiresPush = 10088,
/// Consumer flow control requires a push based consumer
ConsumerFCRequiresPush = 10089,
/// Consumer direct requires a push based consumer
ConsumerDirectRequiresPush = 10090,
/// Consumer direct requires an ephemeral consumer
ConsumerDirectRequiresEphemeral = 10091,
/// Consumer direct on a mapped consumer
ConsumerOnMapped = 10092,
/// Consumer filter subject is not a valid subset of the interest subjects
ConsumerFilterNotSubset = 10093,
/// Generic delivery policy error
ConsumerInvalidPolicy = 10094,
/// Failed to parse consumer sampling configuration: {err}
ConsumerInvalidSampling = 10095,
/// Stream not valid
StreamInvalid = 10096,
/// Workqueue stream requires explicit ack
ConsumerWQRequiresExplicitAck = 10098,
/// Multiple non-filtered consumers not allowed on workqueue stream
ConsumerWQMultipleUnfiltered = 10099,
/// Filtered consumer not unique on workqueue stream
ConsumerWQConsumerNotUnique = 10100,
/// Consumer must be deliver all on workqueue stream
ConsumerWQConsumerNotDeliverAll = 10101,
/// Consumer name is too long, maximum allowed is {max}
ConsumerNameTooLong = 10102,
/// Durable name can not contain '.', '*', '>'
ConsumerBadDurableName = 10103,
/// Error creating store for consumer: {err}
ConsumerStoreFailed = 10104,
/// Consumer already exists and is still active
ConsumerExistingActive = 10105,
/// Consumer replacement durable config not the same
ConsumerReplacementWithDifferentName = 10106,
/// Consumer description is too long, maximum allowed is {max}
ConsumerDescriptionTooLong = 10107,
/// Header size exceeds maximum allowed of 64k
StreamHeaderExceedsMaximum = 10097,
}
/// `Error` type returned from an API response when an error occurs.
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Error {
code: usize,
err_code: ErrorCode,
description: Option<String>,
}
impl Error {
/// Returns the status code assosciated with this error
pub fn code(&self) -> usize {
self.code
}
/// Returns the server side error code associated with this error.
pub fn error_code(&self) -> ErrorCode {
self.err_code
}
}
impl fmt::Display for Error {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
fmt,
"{} (code {}, error code {})",
self.code,
self.description.as_ref().unwrap_or(&"unknown".to_string()),
self.err_code as u64,
)
}
}
impl error::Error for Error {}
#[derive(Debug, Default, Serialize, Deserialize, Clone)]
struct PagedRequest {
offset: i64,
}
#[derive(Debug, Default, Serialize, Deserialize, Clone)]
struct PagedResponse<T> {
pub r#type: String,
#[serde(alias = "streams", alias = "consumers")]
pub items: Option<VecDeque<T>>,
// related to paging
pub total: usize,
pub offset: usize,
pub limit: usize,
}
/// An iterator over paged `JetStream` API operations.
#[derive(Debug)]
pub struct PagedIterator<'a, T> {
manager: &'a JetStream,
subject: String,
offset: i64,
items: VecDeque<T>,
done: bool,
}
impl<'a, T> std::iter::FusedIterator for PagedIterator<'a, T> where T: DeserializeOwned + Debug {}
impl<'a, T> Iterator for PagedIterator<'a, T>
where
T: DeserializeOwned + Debug,
{
type Item = io::Result<T>;
fn next(&mut self) -> Option<io::Result<T>> {
if self.done {
return None;
}
if !self.items.is_empty() {
return Some(Ok(self.items.pop_front().unwrap()));
}
let req = serde_json::ser::to_vec(&PagedRequest {
offset: self.offset,
})
.unwrap();
let res: io::Result<PagedResponse<T>> = self.manager.js_request(&self.subject, &req);
let mut page = match res {
Err(e) => {
self.done = true;
return Some(Err(e));
}
Ok(page) => page,
};
if page.items.is_none() {
self.done = true;
return None;
}
let items = page.items.take().unwrap();
self.offset += i64::try_from(items.len()).unwrap();
self.items = items;
if self.items.is_empty() {
self.done = true;
None
} else {
Some(Ok(self.items.pop_front().unwrap()))
}
}
}
/// A context for performing `JetStream` operations.
#[derive(Clone, Debug)]
pub struct JetStream {
pub(crate) connection: Connection,
pub(crate) options: JetStreamOptions,
}
impl JetStream {
/// Create a new `JetStream` context.
pub fn new(connection: Connection, options: JetStreamOptions) -> Self {
Self {
connection,
options,
}
}
/// Publishes a message to `JetStream`
pub fn publish(&self, subject: &str, data: impl AsRef<[u8]>) -> io::Result<PublishAck> {
self.publish_with_options_or_headers(subject, None, None, data)
}
/// Publishes a message to `JetStream` with the given options.
pub fn publish_with_options(
&self,
subject: &str,
data: impl AsRef<[u8]>,
options: &PublishOptions,
) -> io::Result<PublishAck> {
self.publish_with_options_or_headers(subject, Some(options), None, data)
}
/// Publishes a `Message` to `JetStream`.
pub fn publish_message(&self, message: &Message) -> io::Result<PublishAck> {
self.publish_with_options_or_headers(
&message.subject,
None,
message.headers.as_ref(),
&message.data,
)
}
/// Publishes a `Message` to `JetStream` with the given options.
pub fn publish_message_with_options(
&self,
message: &Message,
options: &PublishOptions,
) -> io::Result<PublishAck> {
self.publish_with_options_or_headers(
&message.subject,
Some(options),
message.headers.as_ref(),
&message.data,
)
}
/// Publishes a message to `JetStream` with the given options and/or headers.
pub(crate) fn publish_with_options_or_headers(
&self,
subject: &str,
maybe_options: Option<&PublishOptions>,
maybe_headers: Option<&HeaderMap>,
msg: impl AsRef<[u8]>,
) -> io::Result<PublishAck> {
let maybe_headers = if let Some(options) = maybe_options {
let mut headers = maybe_headers.map_or_else(HeaderMap::default, HeaderMap::clone);
if let Some(v) = options.id.as_ref() {
headers.insert(header::NATS_MSG_ID, v.to_string());
}
if let Some(v) = options.expected_last_msg_id.as_ref() {
headers.insert(header::NATS_EXPECTED_LAST_MSG_ID, v.to_string());
}
if let Some(v) = options.expected_stream.as_ref() {
headers.insert(header::NATS_EXPECTED_STREAM, v.to_string());
}
if let Some(v) = options.expected_last_sequence.as_ref() {
headers.insert(header::NATS_EXPECTED_LAST_SEQUENCE, v.to_string());
}
if let Some(v) = options.expected_last_subject_sequence.as_ref() {
headers.insert(header::NATS_EXPECTED_LAST_SUBJECT_SEQUENCE, v.to_string());
}
Some(headers)
} else {
maybe_headers.cloned()
};
let maybe_timeout = maybe_options.and_then(|options| options.timeout);
let res_msg = self.connection.request_with_headers_or_timeout(
subject,
maybe_headers.as_ref(),
maybe_timeout,
msg,
)?;
let res: ApiResponse<PublishAck> = serde_json::de::from_slice(&res_msg.data)?;
match res {
ApiResponse::Ok(pub_ack) => Ok(pub_ack),
ApiResponse::Err { error, .. } => {
log::debug!(
"failed to parse API response: {:?}",
std::str::from_utf8(&res_msg.data)
);
Err(io::Error::new(ErrorKind::Other, error))
}
}
}
/// Create an ephemeral push consumer subscription.
///
/// # Example
///
/// ```
/// # fn main() -> std::io::Result<()> {
/// # let client = nats::connect("demo.nats.io")?;
/// # let context = nats::jetstream::new(client);
/// # context.add_stream("ephemeral");
/// # context.publish("ephemeral", "hello");
/// #
/// let subscription = context.subscribe("ephemeral")?;
/// println!("Received message {:?}", subscription.next());
/// # Ok(())
/// # }
/// ```
pub fn subscribe(&self, subject: &str) -> io::Result<PushSubscription> {
self.do_push_subscribe(subject, None, None)
}
/// Creates a pull subscription.
///
/// # Example
/// ```
/// # use nats::jetstream::BatchOptions;
/// # fn main() -> std::io::Result<()> {
/// # let client = nats::connect("demo.nats.io")?;
/// # let context = nats::jetstream::new(client);
/// #
/// # context.add_stream("next")?;
/// # for _ in 0..10 {
/// context.publish("next", b"foo")?;
/// }
/// let consumer = context.pull_subscribe("next")?;
///
/// consumer.fetch_with_handler(10, |message| {
/// println!("received message: {:?}", message);
/// Ok(())
/// })?;
/// # Ok(())
/// # }
/// ```
pub fn pull_subscribe(&self, subject: &str) -> io::Result<PullSubscription> {
self.do_pull_subscribe(subject, None)
}
/// Creates a `PullSubscription` with options.
pub fn pull_subscribe_with_options(
&self,
subject: &str,
options: &PullSubscribeOptions,
) -> io::Result<PullSubscription> {
self.do_pull_subscribe(subject, Some(options))
}
pub(crate) fn do_pull_subscribe(
&self,
subject: &str,
maybe_options: Option<&PullSubscribeOptions>,
) -> io::Result<PullSubscription> {
// Find the stream mapped to the subject if not bound to a stream already.
let stream_name = maybe_options
.and_then(|options| options.stream_name.to_owned())
.map_or_else(|| self.stream_name_by_subject(subject), Ok)?;
let maybe_durable_consumer =
maybe_options.and_then(|options| options.durable_name.to_owned());
let process_consumer_info = |info: ConsumerInfo| {
// run the standard validation for pull consumer.
info.config.validate_for(&ConsumerKind::Pull)?;
// check mismatches between user config and info
// Make sure this new subject matches or is a subset.
if !info.config.filter_subject.is_empty() && subject != info.config.filter_subject {
return Err(io::Error::new(
io::ErrorKind::Other,
"subjects do not match",
));
}
Ok(info)
};
// check if this subscription is bind only. If not, create a new Pull Consumer
let (consumer_info, consumer_ownership) = {
if let Some(durable_name) = maybe_durable_consumer {
// bind to consumer
match self.consumer_info(stream_name, durable_name) {
Ok(info) => (info, ConsumerOwnership::No),
Err(err) => {
return Err(io::Error::new(
ErrorKind::NotFound,
format!("provided durable consumer doesn't exist: {}", err),
));
}
}
} else {
// create ephemeral consumer
let consumer_config = {
maybe_options
.and_then(|options| options.consumer_config.clone())
.unwrap_or_else(|| ConsumerConfig {
deliver_policy: DeliverPolicy::All,
ack_policy: AckPolicy::Explicit,
// Do filtering always, server will clear as needed.
filter_subject: subject.to_string(),
replay_policy: ReplayPolicy::Instant,
..Default::default()
})
};
consumer_config.validate_for(&ConsumerKind::Pull)?;
(
self.add_consumer(stream_name, consumer_config)?,
ConsumerOwnership::Yes,
)
}
};
let consumer_info = process_consumer_info(consumer_info)?;
let inbox = self.connection.new_inbox();
let (pid, messages) = self.connection.0.client.subscribe(inbox.as_str(), None)?;
Ok(PullSubscription::new(
pid,
consumer_info,
consumer_ownership,
inbox,
messages,
self.clone(),
))
}
/// Creates a push consumer subscription with options.
///
/// If said consumer is named and already exists, this will attempt to bind this consumer to
/// that one, else will attempt to create a new internally managed consumer resource.
///
/// # Example
///
/// ```no_run
/// # use nats::jetstream::{ SubscribeOptions };
/// # fn main() -> std::io::Result<()> {
/// # let nc = nats::connect("demo.nats.io")?;
/// # let js = nats::jetstream::new(nc);
/// let sub = js.subscribe_with_options("foo", &SubscribeOptions::bind("existing_stream".to_string(), "existing_consumer".to_string()))?;
/// # Ok(())
/// # }
/// ```
pub fn subscribe_with_options(
&self,
subject: &str,
options: &SubscribeOptions,
) -> io::Result<PushSubscription> {
self.do_push_subscribe(subject, None, Some(options))
}
/// Creates a push-based consumer subscription with a queue group.
/// The queue group will be used as the durable name.
///
/// # Example
///
/// ```
/// # fn main() -> std::io::Result<()> {
/// # let client = nats::connect("demo.nats.io")?;
/// # let context = nats::jetstream::new(client);
/// # context.add_stream("queue");
/// let subscription = context.queue_subscribe("queue", "queue_group")?;
/// # Ok(())
/// # }
/// ```
pub fn queue_subscribe(&self, subject: &str, queue: &str) -> io::Result<PushSubscription> {
self.do_push_subscribe(subject, Some(queue), None)
}
/// Creates a push-based consumer subscription with a queue group and options.
///
/// If a durable name is not set within the options provided options then the queue group will
/// be used as the durable name.
///
pub fn queue_subscribe_with_options(
&self,
subject: &str,
queue: &str,
options: &SubscribeOptions,
) -> io::Result<PushSubscription> {
self.do_push_subscribe(subject, Some(queue), Some(options))
}
fn do_push_subscribe(
&self,
subject: &str,
maybe_queue: Option<&str>,
maybe_options: Option<&SubscribeOptions>,
) -> io::Result<PushSubscription> {
// If no stream name is specified the subject cannot be empty.
if subject.is_empty()
&& maybe_options
.map(|options| options.stream_name.as_ref())
.is_none()
{
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"Subject required",
));
}
let wants_idle_heartbeat =
maybe_options.map_or(false, |options| options.idle_heartbeat.is_some());
let wants_flow_control =
maybe_options.map_or(false, |options| options.flow_control.is_some());
if maybe_queue.is_some() {
// Queue subscriber cannot have idle heartbeats
if wants_idle_heartbeat {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"queue subscription doesn't support idle heartbeat",
));
}
// Nor flow control since messages will randomly dispatched to members.
if wants_flow_control {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"queue subscription doesn't support flow control",
));
}
};
// Checks specific to ordered consumers.
if let Some(options) = maybe_options.filter(|options| options.ordered) {
// Check for queue subscription.
if maybe_queue.is_some() {
return Err(io::Error::new(
io::ErrorKind::Other,
"queues not be set for an ordered consumer",
));
}
// Check for durable name
if options.durable_name.is_some() {
return Err(io::Error::new(
io::ErrorKind::Other,
"durable name can not be set for an ordered consumer",
));
}
// Check for bound consumers.
if options.consumer_name.is_some() {
return Err(io::Error::new(
io::ErrorKind::Other,
"can not bind existing consumer for an ordered consumer",
));
}
// Check for ack policy.
if options.ack_policy.is_some() {
return Err(io::Error::new(
io::ErrorKind::Other,
"ack policy can not be set for an ordered consumer",
));
}
// Check for max deliver.
if options.max_deliver.is_some() {
return Err(io::Error::new(
io::ErrorKind::Other,
"max deliver can not be set for an ordered consumer",
));
}
// Check for deliver subject (we pick our own).
if options.deliver_subject.is_some() {
return Err(io::Error::new(
io::ErrorKind::Other,
"deliver subject can not be set for an ordered consumer",
));
}
}
let process_consumer_info = |info: ConsumerInfo| {
// Make sure this new subject matches or is a subset.
if !info.config.filter_subject.is_empty() && subject != info.config.filter_subject {
return Err(io::Error::new(
io::ErrorKind::Other,
"subject does not match consumer",
));
}
if let Some(deliver_group) = info.config.deliver_group.as_ref() {
if let Some(queue) = maybe_queue {
if deliver_group != queue {
return Err(io::Error::new(
io::ErrorKind::Other,
format!(
"cannot create a queue subscription {} for a consumer with a deliver group {}",
queue, deliver_group
),
));
}
} else {
return Err(io::Error::new(
io::ErrorKind::Other,
format!(
"cannot create a subscription for a consumer with a deliver group {}",
deliver_group
),
));
}
} else {
// Prevent an user from attempting to create a queue subscription on
// a consumer that was not created with a deliver group.
if maybe_queue.is_some() {
return Err(io::Error::new(
io::ErrorKind::Other,
"cannot create a queue subscription for a consumer without a deliver group",
));
}
// Need to reject a non queue subscription to a non queue consumer if the consumer
// is already bound.
if maybe_queue.is_some() && info.push_bound {
return Err(io::Error::new(
io::ErrorKind::Other,
"consumer is already bound to a subscription",
));
}
}