forked from nats-io/nats.rs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
stream.rs
1607 lines (1499 loc) · 53.8 KB
/
stream.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.
//
//! Manage operations on a [Stream], create/delete/update [Consumer][crate::jetstream::consumer::Consumer].
use std::collections::HashMap;
use std::{
fmt::Debug,
future::IntoFuture,
io::{self, ErrorKind},
pin::Pin,
str::FromStr,
task::Poll,
time::Duration,
};
use crate::{header::HeaderName, HeaderMap, HeaderValue};
use crate::{Error, StatusCode};
use bytes::Bytes;
use futures::{Future, TryFutureExt};
use serde::{Deserialize, Serialize};
use serde_json::json;
use time::{serde::rfc3339, OffsetDateTime};
use super::{
consumer::{self, Consumer, FromConsumer, IntoConsumerConfig},
response::Response,
Context, Message,
};
/// Handle to operations that can be performed on a `Stream`.
#[derive(Debug, Clone)]
pub struct Stream {
pub(crate) info: Info,
pub(crate) context: Context,
}
impl Stream {
/// Retrieves `info` about [Stream] from the server, updates the cached `info` inside
/// [Stream] and returns it.
///
/// # Examples
///
/// ```no_run
/// # #[tokio::main]
/// # async fn main() -> Result<(), async_nats::Error> {
/// let client = async_nats::connect("localhost:4222").await?;
/// let jetstream = async_nats::jetstream::new(client);
///
/// let mut stream = jetstream
/// .get_stream("events").await?;
///
/// let info = stream.info().await?;
/// # Ok(())
/// # }
/// ```
pub async fn info(&mut self) -> Result<&Info, Error> {
self.make_info_request(&json!({})).await
}
/// Retrieves `info` about [Stream] from the server, updates the cached `info` inside
/// [Stream] and returns it. This method returns the filtered subjects and the corresponding number of
/// messages for each.
///
/// # Examples
///
/// ```no_run
/// # #[tokio::main]
/// # async fn main() -> Result<(), async_nats::Error> {
/// let client = async_nats::connect("localhost:4222").await?;
/// let jetstream = async_nats::jetstream::new(client);
///
/// let mut stream = jetstream
/// .get_stream("events").await?;
///
/// let info = stream.info_with_subjects("events.*").await?;
/// # Ok(())
/// # }
/// ```
pub async fn info_with_subjects(&mut self, filter: &str) -> Result<&Info, Error> {
self.make_info_request(&json!({ "subjects_filter": filter }))
.await
}
async fn make_info_request(&mut self, value: &serde_json::Value) -> Result<&Info, Error> {
let subject = format!("STREAM.INFO.{}", self.info.config.name);
match self.context.request(subject, value).await? {
Response::Ok::<Info>(info) => {
self.info = info;
Ok(&self.info)
}
Response::Err { error } => Err(Box::new(std::io::Error::new(
ErrorKind::Other,
format!(
"nats: error while getting stream info: {}, {}, {}",
error.code, error.status, error.description
),
))),
}
}
/// Returns cached [Info] for the [Stream].
/// Cache is either from initial creation/retrieval of the [Stream] or last call to
/// [Stream::info].
///
/// # Examples
///
/// ```no_run
/// # #[tokio::main]
/// # async fn main() -> Result<(), async_nats::Error> {
/// let client = async_nats::connect("localhost:4222").await?;
/// let jetstream = async_nats::jetstream::new(client);
///
/// let stream = jetstream
/// .get_stream("events").await?;
///
/// let info = stream.cached_info();
/// # Ok(())
/// # }
/// ```
pub fn cached_info(&self) -> &Info {
&self.info
}
/// Gets next message for a [Stream].
///
/// Requires a [Stream] with `allow_direct` set to `true`.
/// This is different from [Stream::get_raw_message], as it can fetch [Message]
/// from any replica member. This means read after write is possible,
/// as that given replica might not yet catch up with the leader.
///
/// # Examples
///
/// ```no_run
/// # #[tokio::main]
/// # async fn main() -> Result<(), async_nats::Error> {
/// let client = async_nats::connect("demo.nats.io").await?;
/// let jetstream = async_nats::jetstream::new(client);
///
/// let stream = jetstream.create_stream(async_nats::jetstream::stream::Config {
/// name: "events".to_string(),
/// subjects: vec!["events.>".to_string()],
/// allow_direct: true,
/// ..Default::default()
/// }).await?;
///
/// jetstream.publish("events.data".into(), "data".into()).await?;
/// let pub_ack = jetstream.publish("events.data".into(), "data".into()).await?;
///
/// let message = stream
/// .direct_get_next_for_subject("events.data", Some(pub_ack.await?.sequence)).await?;
///
/// # Ok(())
/// # }
/// ```
pub async fn direct_get_next_for_subject<T: AsRef<str>>(
&self,
subject: T,
sequence: Option<u64>,
) -> Result<Message, Error> {
let request_subject = format!(
"{}.DIRECT.GET.{}",
&self.context.prefix, &self.info.config.name
);
let payload;
if let Some(sequence) = sequence {
payload = json!({
"seq": sequence,
"next_by_subj": subject.as_ref(),
});
} else {
payload = json!({
"next_by_subj": subject.as_ref(),
});
}
let response = self
.context
.client
.request(
request_subject,
serde_json::to_vec(&payload).map(Bytes::from)?,
)
.await
.map(|message| Message {
message,
context: self.context.clone(),
})?;
if let Some(status) = response.status {
if let Some(ref description) = response.description {
return Err(Box::from(std::io::Error::new(
ErrorKind::Other,
format!("{status} {description}"),
)));
}
}
Ok(response)
}
/// Gets first message from [Stream].
///
/// Requires a [Stream] with `allow_direct` set to `true`.
/// This is different from [Stream::get_raw_message], as it can fetch [Message]
/// from any replica member. This means read after write is possible,
/// as that given replica might not yet catch up with the leader.
///
/// # Examples
///
/// ```no_run
/// # #[tokio::main]
/// # async fn main() -> Result<(), async_nats::Error> {
/// let client = async_nats::connect("demo.nats.io").await?;
/// let jetstream = async_nats::jetstream::new(client);
///
/// let stream = jetstream.create_stream(async_nats::jetstream::stream::Config {
/// name: "events".to_string(),
/// subjects: vec!["events.>".to_string()],
/// allow_direct: true,
/// ..Default::default()
/// }).await?;
///
/// let pub_ack = jetstream.publish("events.data".into(), "data".into()).await?;
///
/// let message = stream.direct_get_first_for_subject("events.data").await?;
///
/// # Ok(())
/// # }
/// ```
pub async fn direct_get_first_for_subject<T: AsRef<str>>(
&self,
subject: T,
) -> Result<Message, Error> {
let request_subject = format!(
"{}.DIRECT.GET.{}",
&self.context.prefix, &self.info.config.name
);
let payload = json!({
"next_by_subj": subject.as_ref(),
});
let response = self
.context
.client
.request(
request_subject,
serde_json::to_vec(&payload).map(Bytes::from)?,
)
.await
.map(|message| Message {
message,
context: self.context.clone(),
})?;
if let Some(status) = response.status {
if let Some(ref description) = response.description {
return Err(Box::from(std::io::Error::new(
ErrorKind::Other,
format!("{status} {description}"),
)));
}
}
Ok(response)
}
/// Gets message from [Stream] with given `sequence id`.
///
/// Requires a [Stream] with `allow_direct` set to `true`.
/// This is different from [Stream::get_raw_message], as it can fetch [Message]
/// from any replica member. This means read after write is possible,
/// as that given replica might not yet catch up with the leader.
///
/// # Examples
///
/// ```no_run
/// # #[tokio::main]
/// # async fn main() -> Result<(), async_nats::Error> {
/// let client = async_nats::connect("demo.nats.io").await?;
/// let jetstream = async_nats::jetstream::new(client);
///
/// let stream = jetstream.create_stream(async_nats::jetstream::stream::Config {
/// name: "events".to_string(),
/// subjects: vec!["events.>".to_string()],
/// allow_direct: true,
/// ..Default::default()
/// }).await?;
///
/// let pub_ack = jetstream.publish("events.data".into(), "data".into()).await?;
///
/// let message = stream.direct_get(pub_ack.await?.sequence).await?;
///
/// # Ok(())
/// # }
/// ```
pub async fn direct_get(&self, sequence: u64) -> Result<Message, Error> {
let subject = format!(
"{}.DIRECT.GET.{}",
&self.context.prefix, &self.info.config.name
);
let payload = json!({
"seq": sequence,
});
let response = self
.context
.client
.request(subject, serde_json::to_vec(&payload).map(Bytes::from)?)
.await
.map(|message| Message {
context: self.context.clone(),
message,
})?;
if let Some(status) = response.status {
if let Some(ref description) = response.description {
return Err(Box::from(std::io::Error::new(
ErrorKind::Other,
format!("{status} {description}"),
)));
}
}
Ok(response)
}
/// Gets last message for a given `subject`.
///
/// Requires a [Stream] with `allow_direct` set to `true`.
/// This is different from [Stream::get_raw_message], as it can fetch [Message]
/// from any replica member. This means read after write is possible,
/// as that given replica might not yet catch up with the leader.
///
/// # Examples
///
/// ```no_run
/// # #[tokio::main]
/// # async fn main() -> Result<(), async_nats::Error> {
/// let client = async_nats::connect("demo.nats.io").await?;
/// let jetstream = async_nats::jetstream::new(client);
///
/// let stream = jetstream.create_stream(async_nats::jetstream::stream::Config {
/// name: "events".to_string(),
/// subjects: vec!["events.>".to_string()],
/// allow_direct: true,
/// ..Default::default()
/// }).await?;
///
/// jetstream.publish("events.data".into(), "data".into()).await?;
///
/// let message = stream.direct_get_last_for_subject("events.data").await?;
///
/// # Ok(())
/// # }
/// ```
pub async fn direct_get_last_for_subject<T: AsRef<str>>(
&self,
subject: T,
) -> Result<Message, Error> {
let subject = format!(
"{}.DIRECT.GET.{}.{}",
&self.context.prefix,
&self.info.config.name,
subject.as_ref()
);
let response = self
.context
.client
.request(subject, "".into())
.await
.map(|message| Message {
context: self.context.clone(),
message,
})?;
if let Some(status) = response.status {
if let Some(ref description) = response.description {
match status {
StatusCode::NOT_FOUND => {
return Err(Box::from(std::io::Error::new(
ErrorKind::NotFound,
"message not found in stream",
)))
}
// 408 is used in Direct Message for bad/empty payload.
StatusCode::TIMEOUT => {
return Err(Box::from(std::io::Error::new(
ErrorKind::Other,
"empty or invalid request",
)))
}
other => {
return Err(Box::from(std::io::Error::new(
ErrorKind::Other,
format!("{other}: {description}"),
)))
}
}
}
}
Ok(response)
}
/// Get a raw message from the stream.
///
/// # Examples
///
/// ```no_run
/// #[tokio::main]
/// # async fn mains() -> Result<(), async_nats::Error> {
/// use futures::StreamExt;
/// use futures::TryStreamExt;
///
/// let client = async_nats::connect("localhost:4222").await?;
/// let context = async_nats::jetstream::new(client);
///
/// let stream = context.get_or_create_stream(async_nats::jetstream::stream::Config {
/// name: "events".to_string(),
/// max_messages: 10_000,
/// ..Default::default()
/// }).await?;
///
/// let publish_ack = context.publish("events".to_string(), "data".into()).await?;
/// let raw_message = stream.get_raw_message(publish_ack.await?.sequence).await?;
/// println!("Retrieved raw message {:?}", raw_message);
/// # Ok(())
/// # }
/// ```
pub async fn get_raw_message(&self, sequence: u64) -> Result<RawMessage, Error> {
let subject = format!("STREAM.MSG.GET.{}", &self.info.config.name);
let payload = json!({
"seq": sequence,
});
let response: Response<GetRawMessage> = self.context.request(subject, &payload).await?;
match response {
Response::Err { error } => Err(Box::new(std::io::Error::new(
ErrorKind::Other,
format!(
"nats: error while getting message: {}, {}",
error.code, error.description
),
))),
Response::Ok(value) => Ok(value.message),
}
}
/// Get the last raw message from the stream by subject.
///
/// # Examples
///
/// ```no_run
/// #[tokio::main]
/// # async fn mains() -> Result<(), async_nats::Error> {
/// use futures::StreamExt;
/// use futures::TryStreamExt;
///
/// let client = async_nats::connect("localhost:4222").await?;
/// let context = async_nats::jetstream::new(client);
///
/// let stream = context.get_or_create_stream(async_nats::jetstream::stream::Config {
/// name: "events".to_string(),
/// max_messages: 10_000,
/// ..Default::default()
/// }).await?;
///
/// let publish_ack = context.publish("events".to_string(), "data".into()).await?;
/// let raw_message = stream.get_last_raw_message_by_subject("events").await?;
/// println!("Retrieved raw message {:?}", raw_message);
/// # Ok(())
/// # }
/// ```
pub async fn get_last_raw_message_by_subject(
&self,
stream_subject: &str,
) -> Result<RawMessage, Error> {
let subject = format!("STREAM.MSG.GET.{}", &self.info.config.name);
let payload = json!({
"last_by_subj": stream_subject,
});
let response: Response<GetRawMessage> = self.context.request(subject, &payload).await?;
match response {
Response::Err { error } => Err(Box::new(std::io::Error::new(ErrorKind::Other, error))),
Response::Ok(value) => Ok(value.message),
}
}
/// Delete a message from the stream.
///
/// # Examples
///
/// ```no_run
/// # #[tokio::main]
/// # async fn main() -> Result<(), async_nats::Error> {
/// let client = async_nats::connect("localhost:4222").await?;
/// let context = async_nats::jetstream::new(client);
///
/// let stream = context.get_or_create_stream(async_nats::jetstream::stream::Config {
/// name: "events".to_string(),
/// max_messages: 10_000,
/// ..Default::default()
/// }).await?;
///
/// let publish_ack = context.publish("events".to_string(), "data".into()).await?;
/// stream.delete_message(publish_ack.await?.sequence).await?;
/// # Ok(())
/// # }
/// ```
pub async fn delete_message(&self, sequence: u64) -> Result<bool, Error> {
let subject = format!("STREAM.MSG.DELETE.{}", &self.info.config.name);
let payload = json!({
"seq": sequence,
});
let response: Response<DeleteStatus> = self.context.request(subject, &payload).await?;
match response {
Response::Err { error } => Err(Box::new(std::io::Error::new(
ErrorKind::Other,
format!(
"nats: error while deleting message: {}, {}",
error.code, error.status
),
))),
Response::Ok(value) => Ok(value.success),
}
}
/// Purge `Stream` messages.
///
/// # Examples
///
/// ```no_run
/// # #[tokio::main]
/// # async fn main() -> Result<(), async_nats::Error> {
/// let client = async_nats::connect("demo.nats.io").await?;
/// let jetstream = async_nats::jetstream::new(client);
///
/// let stream = jetstream.get_stream("events").await?;
/// stream.purge().await?;
/// # Ok(())
/// # }
/// ```
pub fn purge(&self) -> Purge<No, No> {
Purge::build(self.clone())
}
/// Purge `Stream` messages for a matching subject.
///
/// # Examples
///
/// ```no_run
/// # #[tokio::main]
/// # #[allow(deprecated)]
/// # async fn main() -> Result<(), async_nats::Error> {
/// let client = async_nats::connect("demo.nats.io").await?;
/// let jetstream = async_nats::jetstream::new(client);
///
/// let stream = jetstream.get_stream("events").await?;
/// stream.purge_subject("data").await?;
/// # Ok(())
/// # }
/// ```
#[deprecated(
since = "0.25.0",
note = "Overloads have been replaced with an into_future based builder. Use Stream::purge().filter(subject) instead."
)]
pub async fn purge_subject<T>(&self, subject: T) -> Result<PurgeResponse, Error>
where
T: Into<String>,
{
self.purge().filter(subject).await
}
/// Create a new `Durable` or `Ephemeral` Consumer (if `durable_name` was not provided) and
/// returns the info from the server about created [Consumer][Consumer]
///
/// # Examples
///
/// ```no_run
/// # #[tokio::main]
/// # async fn main() -> Result<(), async_nats::Error> {
/// use async_nats::jetstream::consumer;
/// let client = async_nats::connect("localhost:4222").await?;
/// let jetstream = async_nats::jetstream::new(client);
///
/// let stream = jetstream.get_stream("events").await?;
/// let info = stream.create_consumer(consumer::pull::Config {
/// durable_name: Some("pull".to_string()),
/// ..Default::default()
/// }).await?;
/// # Ok(())
/// # }
/// ```
pub async fn create_consumer<C: IntoConsumerConfig + FromConsumer>(
&self,
config: C,
) -> Result<Consumer<C>, Error> {
let config = config.into_consumer_config();
let subject = {
if self.context.client.is_server_compatible(2, 9, 0) {
let filter = if config.filter_subject.is_empty() {
"".to_string()
} else {
format!(".{}", config.filter_subject)
};
config
.name
.as_ref()
.or(config.durable_name.as_ref())
.map(|name| {
format!(
"CONSUMER.CREATE.{}.{}{}",
self.info.config.name, name, filter
)
})
.unwrap_or_else(|| format!("CONSUMER.CREATE.{}", self.info.config.name))
} else if config.name.is_some() {
return Err(Box::new(std::io::Error::new(
ErrorKind::Other,
"can't use consumer name with server below version 2.9",
)));
} else if let Some(ref durable_name) = config.durable_name {
format!(
"CONSUMER.DURABLE.CREATE.{}.{}",
self.info.config.name, durable_name
)
} else {
format!("CONSUMER.CREATE.{}", self.info.config.name)
}
};
match self
.context
.request(
subject,
&json!({"stream_name": self.info.config.name.clone(), "config": config}),
)
.await?
{
Response::Err { error } => Err(Box::new(std::io::Error::new(
ErrorKind::Other,
format!(
"nats: error while creating stream: {}, {}, {}",
error.code, error.status, error.description
),
))),
Response::Ok::<consumer::Info>(info) => Ok(Consumer::new(
FromConsumer::try_from_consumer_config(info.clone().config)?,
info,
self.context.clone(),
)),
}
}
/// Retrieve [Info] about [Consumer] from the server.
///
/// # Examples
///
/// ```no_run
/// # #[tokio::main]
/// # async fn main() -> Result<(), async_nats::Error> {
/// use async_nats::jetstream::consumer;
/// let client = async_nats::connect("localhost:4222").await?;
/// let jetstream = async_nats::jetstream::new(client);
///
/// let stream = jetstream.get_stream("events").await?;
/// let info = stream.consumer_info("pull").await?;
/// # Ok(())
/// # }
/// ```
pub async fn consumer_info<T: AsRef<str>>(&self, name: T) -> Result<consumer::Info, Error> {
let name = name.as_ref();
let subject = format!("CONSUMER.INFO.{}.{}", self.info.config.name, name);
match self.context.request(subject, &json!({})).await? {
Response::Ok(info) => Ok(info),
Response::Err { error } => Err(Box::new(std::io::Error::new(
ErrorKind::Other,
format!(
"nats: error while getting consumer info: {}, {}, {}",
error.code, error.status, error.description
),
))),
}
}
/// Get [Consumer] from the the server. [Consumer] iterators can be used to retrieve
/// [Messages][crate::jetstream::Message] for a given [Consumer].
///
/// # Examples
///
/// ```no_run
/// # #[tokio::main]
/// # async fn main() -> Result<(), async_nats::Error> {
/// use async_nats::jetstream::consumer;
/// use futures::StreamExt;
/// let client = async_nats::connect("localhost:4222").await?;
/// let jetstream = async_nats::jetstream::new(client);
///
/// let stream = jetstream.get_stream("events").await?;
/// let consumer: consumer::PullConsumer = stream.get_consumer("pull").await?;
/// # Ok(())
/// # }
/// ```
pub async fn get_consumer<T: FromConsumer + IntoConsumerConfig>(
&self,
name: &str,
) -> Result<Consumer<T>, Error> {
let info = self.consumer_info(name).await?;
Ok(Consumer::new(
T::try_from_consumer_config(info.config.clone())?,
info,
self.context.clone(),
))
}
/// Create a [Consumer] with the given configuration if it is not present on the server. Returns a handle to the [Consumer].
///
/// Note: This does not validate if the [Consumer] on the server is compatible with the configuration passed in except Push/Pull compatibility.
///
/// # Examples
///
/// ```no_run
/// # #[tokio::main]
/// # async fn main() -> Result<(), async_nats::Error> {
/// use async_nats::jetstream::consumer;
/// use futures::StreamExt;
/// let client = async_nats::connect("localhost:4222").await?;
/// let jetstream = async_nats::jetstream::new(client);
///
/// let stream = jetstream.get_stream("events").await?;
/// let consumer = stream.get_or_create_consumer("pull", consumer::pull::Config {
/// durable_name: Some("pull".to_string()),
/// ..Default::default()
/// }).await?;
/// # Ok(())
/// # }
/// ```
pub async fn get_or_create_consumer<T: FromConsumer + IntoConsumerConfig>(
&self,
name: &str,
config: T,
) -> Result<Consumer<T>, Error> {
let subject = format!("CONSUMER.INFO.{}.{}", self.info.config.name, name);
match self.context.request(subject, &json!({})).await? {
Response::Err { error } if error.status == 404 => self.create_consumer(config).await,
Response::Err { error } => Err(Box::new(io::Error::new(
ErrorKind::Other,
format!(
"nats: error while getting or creating stream: {}, {}, {}",
error.code, error.status, error.description
),
))),
Response::Ok::<consumer::Info>(info) => Ok(Consumer::new(
T::try_from_consumer_config(info.config.clone())?,
info,
self.context.clone(),
)),
}
}
/// Delete a [Consumer] from the server.
///
/// # Examples
///
/// ```no_run
/// # #[tokio::main]
/// # async fn main() -> Result<(), async_nats::Error> {
/// use async_nats::jetstream::consumer;
/// use futures::StreamExt;
/// let client = async_nats::connect("localhost:4222").await?;
/// let jetstream = async_nats::jetstream::new(client);
///
/// jetstream.get_stream("events").await?
/// .delete_consumer("pull").await?;
/// # Ok(())
/// # }
/// ```
pub async fn delete_consumer(&self, name: &str) -> Result<DeleteStatus, Error> {
let subject = format!("CONSUMER.DELETE.{}.{}", self.info.config.name, name);
match self.context.request(subject, &json!({})).await? {
Response::Ok(delete_status) => Ok(delete_status),
Response::Err { error } => Err(Box::new(std::io::Error::new(
ErrorKind::Other,
format!(
"nats: error while deleting consumer: {}, {}, {}",
error.code, error.status, error.description
),
))),
}
}
/// Lists names of all consumers for current stream.
///
/// # Examples
///
/// ```no_run
/// # #[tokio::main]
/// # async fn main() -> Result<(), async_nats::Error> {
/// use futures::TryStreamExt;
/// let client = async_nats::connect("demo.nats.io:4222").await?;
/// let jetstream = async_nats::jetstream::new(client);
/// let stream = jetstream.get_stream("stream").await?;
/// let mut names = stream.consumer_names();
/// while let Some(consumer) = names.try_next().await? {
/// println!("consumer: {stream:?}");
/// }
/// # Ok(())
/// # }
/// ```
pub fn consumer_names(&self) -> ConsumerNames {
ConsumerNames {
context: self.context.clone(),
stream: self.info.config.name.clone(),
offset: 0,
page_request: None,
consumers: Vec::new(),
done: false,
}
}
/// Lists all consumers info for current stream.
///
/// # Examples
///
/// ```no_run
/// # #[tokio::main]
/// # async fn main() -> Result<(), async_nats::Error> {
/// use futures::TryStreamExt;
/// let client = async_nats::connect("demo.nats.io:4222").await?;
/// let jetstream = async_nats::jetstream::new(client);
/// let stream = jetstream.get_stream("stream").await?;
/// let mut consumers = stream.consumers();
/// while let Some(consumer) = consumers.try_next().await? {
/// println!("consumer: {consumer:?}");
/// }
/// # Ok(())
/// # }
/// ```
pub fn consumers(&self) -> Consumers {
Consumers {
context: self.context.clone(),
stream: self.info.config.name.clone(),
offset: 0,
page_request: None,
consumers: Vec::new(),
done: false,
}
}
}
/// `StreamConfig` determines the properties for a stream.
/// There are sensible defaults for most. If no subjects are
/// given the name will be used as the only subject.
#[derive(Debug, Default, Serialize, Deserialize, Clone, PartialEq, Eq)]
pub struct Config {
/// A name for the Stream. Must not have spaces, tabs or period `.` characters
pub name: String,
/// How large the Stream may become in total bytes before the configured discard policy kicks in
pub max_bytes: i64,
/// How large the Stream may become in total messages before the configured discard policy kicks in
#[serde(rename = "max_msgs")]
pub max_messages: i64,
/// Maximum amount of messages to keep per subject
#[serde(rename = "max_msgs_per_subject")]
pub max_messages_per_subject: i64,
/// When a Stream has reached its configured `max_bytes` or `max_msgs`, this policy kicks in.
/// `DiscardPolicy::New` refuses new messages or `DiscardPolicy::Old` (default) deletes old messages to make space
pub discard: DiscardPolicy,
/// Prevents a message from being added to a stream if the max_msgs_per_subject limit for the subject has been reached
#[serde(default, skip_serializing_if = "is_default")]
pub discard_new_per_subject: bool,
/// Which NATS subjects to populate this stream with. Supports wildcards. Defaults to just the
/// configured stream `name`.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub subjects: Vec<String>,
/// How message retention is considered, `Limits` (default), `Interest` or `WorkQueue`
pub retention: RetentionPolicy,
/// How many Consumers can be defined for a given Stream, -1 for unlimited
pub max_consumers: i32,
/// Maximum age of any message in the stream, expressed in nanoseconds
#[serde(with = "serde_nanos")]
pub max_age: Duration,
/// The largest message that will be accepted by the Stream
#[serde(default, skip_serializing_if = "is_default", rename = "max_msg_size")]
pub max_message_size: i32,
/// The type of storage backend, `File` (default) and `Memory`
pub storage: StorageType,
/// How many replicas to keep for each message in a clustered JetStream, maximum 5
pub num_replicas: usize,
/// Disables acknowledging messages that are received by the Stream
#[serde(default, skip_serializing_if = "is_default")]
pub no_ack: bool,
/// The window within which to track duplicate messages.
#[serde(default, skip_serializing_if = "is_default")]
pub duplicate_window: i64,
/// The owner of the template associated with this stream.
#[serde(default, skip_serializing_if = "is_default")]
pub template_owner: String,
/// Indicates the stream is sealed and cannot be modified in any way
#[serde(default, skip_serializing_if = "is_default")]
pub sealed: bool,
#[serde(default, skip_serializing_if = "is_default")]
/// A short description of the purpose of this stream.
pub description: Option<String>,
#[serde(
default,
rename = "allow_rollup_hdrs",
skip_serializing_if = "is_default"
)]
/// Indicates if rollups will be allowed or not.
pub allow_rollup: bool,
#[serde(default, skip_serializing_if = "is_default")]
/// Indicates deletes will be denied or not.
pub deny_delete: bool,
/// Indicates if purges will be denied or not.
#[serde(default, skip_serializing_if = "is_default")]
pub deny_purge: bool,
/// Optional republish config.
#[serde(default, skip_serializing_if = "is_default")]
pub republish: Option<Republish>,
/// Enables direct get, which would get messages from
/// non-leader.
#[serde(default, skip_serializing_if = "is_default")]
pub allow_direct: bool,
/// Enable direct access also for mirrors.
#[serde(default, skip_serializing_if = "is_default")]
pub mirror_direct: bool,
/// Stream mirror configuration.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub mirror: Option<Source>,
/// Sources configuration.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub sources: Option<Vec<Source>>,
#[cfg(feature = "server-2.10")]
// Additional stream metadata.
#[serde(default, skip_serializing_if = "is_default")]
pub metadata: HashMap<String, String>,
}
impl From<&Config> for Config {
fn from(sc: &Config) -> Config {
sc.clone()
}
}
impl From<&str> for Config {
fn from(s: &str) -> Config {
Config {
name: s.to_string(),
..Default::default()
}
}
}
// Republish is for republishing messages once committed to a stream.
#[derive(Serialize, Deserialize, Debug, Clone, Eq, PartialEq)]
pub struct Republish {
/// Subject that should be republished.
#[serde(rename = "src")]
pub source: String,
/// Subject where messages will be republished.
#[serde(rename = "dest")]
pub destination: String,
/// If true, only headers should be republished.
#[serde(default)]
pub headers_only: bool,
}
/// `DiscardPolicy` determines how we proceed when limits of messages or bytes are hit. The default, `Old` will
/// remove older messages. `New` will fail to store the new message.
#[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
pub enum DiscardPolicy {
/// will remove older messages when limits are hit.
#[serde(rename = "old")]
Old = 0,
/// will error on a StoreMsg call when limits are hit
#[serde(rename = "new")]
New = 1,
}