Struct async_nats::jetstream::consumer::Consumer
source · pub struct Consumer<T: IntoConsumerConfig> { /* private fields */ }Implementations§
source§impl Consumer<Config>
impl Consumer<Config>
sourcepub async fn messages(&self) -> Result<Stream, Error>
pub async fn messages(&self) -> Result<Stream, Error>
Returns a stream of messages for Pull Consumer.
Example
use futures::StreamExt;
use futures::TryStreamExt;
let client = async_nats::connect("localhost:4222").await?;
let jetstream = async_nats::jetstream::new(client);
let stream = jetstream.get_or_create_stream(async_nats::jetstream::stream::Config {
name: "events".to_string(),
max_messages: 10_000,
..Default::default()
}).await?;
jetstream.publish("events".to_string(), "data".into()).await?;
let consumer = stream.get_or_create_consumer("consumer", async_nats::jetstream::consumer::pull::Config {
durable_name: Some("consumer".to_string()),
..Default::default()
}).await?;
let mut messages = consumer.messages().await?.take(100);
while let Some(Ok(message)) = messages.next().await {
println!("got message {:?}", message);
message.ack().await?;
}
Ok(())sourcepub fn stream(&self) -> StreamBuilder<'_>
pub fn stream(&self) -> StreamBuilder<'_>
Enables customization of Stream by setting timeouts, heartbeats, maximum number of messages or bytes buffered.
Examples
use futures::StreamExt;
use async_nats::jetstream::consumer::PullConsumer;
let client = async_nats::connect("localhost:4222").await?;
let jetstream = async_nats::jetstream::new(client);
let consumer: PullConsumer = jetstream
.get_stream("events").await?
.get_consumer("pull").await?;
let mut messages = consumer.stream()
.max_messages_per_batch(100)
.max_bytes_per_batch(1024)
.messages().await?;
while let Some(message) = messages.next().await {
let message = message?;
println!("message: {:?}", message);
message.ack().await?;
}sourcepub fn fetch(&self) -> FetchBuilder<'_>
pub fn fetch(&self) -> FetchBuilder<'_>
Returns a batch of specified number of messages, or if there are less messages on the Stream than requested, returns all available messages.
Example
use futures::StreamExt;
use futures::TryStreamExt;
let client = async_nats::connect("localhost:4222").await?;
let jetstream = async_nats::jetstream::new(client);
let stream = jetstream.get_or_create_stream(async_nats::jetstream::stream::Config {
name: "events".to_string(),
max_messages: 10_000,
..Default::default()
}).await?;
jetstream.publish("events".to_string(), "data".into()).await?;
let consumer = stream.get_or_create_consumer("consumer", async_nats::jetstream::consumer::pull::Config {
durable_name: Some("consumer".to_string()),
..Default::default()
}).await?;
for _ in 0..100 {
jetstream.publish("events".to_string(), "data".into()).await?;
}
let mut messages = consumer.fetch().max_messages(200).messages().await?;
// will finish after 100 messages, as that is the number of messages available on the
// stream.
while let Some(Ok(message)) = messages.next().await {
println!("got message {:?}", message);
message.ack().await?;
}
Ok(())sourcepub fn batch(&self) -> BatchBuilder<'_>
pub fn batch(&self) -> BatchBuilder<'_>
Returns a batch of specified number of messages unless timeout happens first.
Example
use futures::StreamExt;
use futures::TryStreamExt;
let client = async_nats::connect("localhost:4222").await?;
let jetstream = async_nats::jetstream::new(client);
let stream = jetstream.get_or_create_stream(async_nats::jetstream::stream::Config {
name: "events".to_string(),
max_messages: 10_000,
..Default::default()
}).await?;
jetstream.publish("events".to_string(), "data".into()).await?;
let consumer = stream.get_or_create_consumer("consumer", async_nats::jetstream::consumer::pull::Config {
durable_name: Some("consumer".to_string()),
..Default::default()
}).await?;
let mut messages = consumer.batch().max_messages(100).messages().await?;
while let Some(Ok(message)) = messages.next().await {
println!("got message {:?}", message);
message.ack().await?;
}
Ok(())sourcepub fn sequence(&self, batch: usize) -> Result<Sequence<'_>, Error>
pub fn sequence(&self, batch: usize) -> Result<Sequence<'_>, Error>
Returns a sequence of Batches allowing for iterating over batches, and then over messages in those batches.
Example
use futures::StreamExt;
use futures::TryStreamExt;
let client = async_nats::connect("localhost:4222").await?;
let jetstream = async_nats::jetstream::new(client);
let stream = jetstream.get_or_create_stream(async_nats::jetstream::stream::Config {
name: "events".to_string(),
max_messages: 10_000,
..Default::default()
}).await?;
jetstream.publish("events".to_string(), "data".into()).await?;
let consumer = stream.get_or_create_consumer("consumer", async_nats::jetstream::consumer::pull::Config {
durable_name: Some("consumer".to_string()),
..Default::default()
}).await?;
let mut iter = consumer.sequence(50).unwrap().take(10);
while let Ok(Some(mut batch)) = iter.try_next().await {
while let Ok(Some(message)) = batch.try_next().await {
println!("message received: {:?}", message);
}
}
Ok(())source§impl Consumer<Config>
impl Consumer<Config>
sourcepub async fn messages(&self) -> Result<Messages, Error>
pub async fn messages(&self) -> Result<Messages, Error>
Returns a stream of messages for Push Consumer.
Example
use futures::StreamExt;
use futures::TryStreamExt;
use async_nats::jetstream::consumer::PushConsumer;
let client = async_nats::connect("localhost:4222").await?;
let jetstream = async_nats::jetstream::new(client);
let stream = jetstream.get_or_create_stream(async_nats::jetstream::stream::Config {
name: "events".to_string(),
max_messages: 10_000,
..Default::default()
}).await?;
jetstream.publish("events".to_string(), "data".into()).await?;
let consumer: PushConsumer = stream.get_or_create_consumer("consumer", async_nats::jetstream::consumer::push::Config {
durable_name: Some("consumer".to_string()),
deliver_subject: "deliver".to_string(),
..Default::default()
}).await?;
let mut messages = consumer.messages().await?.take(100);
while let Some(Ok(message)) = messages.next().await {
println!("got message {:?}", message);
message.ack().await?;
}
Ok(())source§impl Consumer<OrderedConfig>
impl Consumer<OrderedConfig>
sourcepub async fn messages<'a>(self) -> Result<Ordered<'a>, Error>
pub async fn messages<'a>(self) -> Result<Ordered<'a>, Error>
Examples found in repository?
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
pub async fn get<T: AsRef<str>>(&self, object_name: T) -> Result<Object<'_>, Error> {
let object_info = self.info(object_name).await?;
// if let Some(link) = object_info.link {
// return self.get(link.name).await;
// }
let chunk_subject = format!("$O.{}.C.{}", self.name, object_info.nuid);
let subscription = self
.stream
.create_consumer(crate::jetstream::consumer::push::OrderedConfig {
filter_subject: chunk_subject,
deliver_subject: self.stream.context.client.new_inbox(),
..Default::default()
})
.await?
.messages()
.await?;
Ok(Object::new(subscription, object_info))
}
/// Gets an [Object] from the [ObjectStore].
///
/// [Object] implements [tokio::io::AsyncRead] that allows
/// to read the data from Object Store.
///
/// # 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 bucket = jetstream.get_object_store("store").await?;
/// bucket.delete("FOO").await?;
/// # Ok(())
/// # }
/// ```
pub async fn delete<T: AsRef<str>>(&self, object_name: T) -> Result<(), Error> {
let object_name = object_name.as_ref();
let mut object_info = self.info(object_name).await?;
object_info.chunks = 0;
object_info.size = 0;
object_info.deleted = true;
let data = serde_json::to_vec(&object_info)?;
let mut headers = HeaderMap::default();
headers.insert(NATS_ROLLUP, HeaderValue::from_str(ROLLUP_SUBJECT)?);
let subject = format!("$O.{}.M.{}", &self.name, encode_object_name(object_name));
self.stream
.context
.publish_with_headers(subject, headers, data.into())
.await?;
let chunk_subject = format!("$O.{}.C.{}", self.name, object_info.nuid);
self.stream.purge_subject(&chunk_subject).await?;
Ok(())
}
/// Retrieves [Object] [ObjectInfo].
///
/// # 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 bucket = jetstream.get_object_store("store").await?;
/// let info = bucket.info("FOO").await?;
/// # Ok(())
/// # }
/// ```
pub async fn info<T: AsRef<str>>(&self, object_name: T) -> Result<ObjectInfo, Error> {
let object_name = object_name.as_ref();
let object_name = encode_object_name(object_name);
if !is_valid_object_name(&object_name) {
return Err(Box::new(io::Error::new(
io::ErrorKind::InvalidInput,
"invalid object name",
)));
}
// Grab last meta value we have.
let subject = format!("$O.{}.M.{}", &self.name, &object_name);
let message = self
.stream
.get_last_raw_message_by_subject(subject.as_str())
.await?;
let decoded_payload = base64::decode(message.payload)
.map_err(|err| Box::new(std::io::Error::new(ErrorKind::Other, err)))?;
let object_info = serde_json::from_slice::<ObjectInfo>(&decoded_payload)?;
Ok(object_info)
}
/// Puts an [Object] into the [ObjectStore].
/// This method implements `tokio::io::AsyncRead`.
///
/// # 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 bucket = jetstream.get_object_store("store").await?;
/// let mut file = tokio::fs::File::open("foo.txt").await?;
/// bucket.put("file", &mut file).await.unwrap();
/// # Ok(())
/// # }
/// ```
pub async fn put<T>(
&self,
meta: T,
data: &mut (impl tokio::io::AsyncRead + std::marker::Unpin),
) -> Result<ObjectInfo, Error>
where
ObjectMeta: From<T>,
{
let object_meta: ObjectMeta = meta.into();
let encoded_object_name = encode_object_name(&object_meta.name);
if !is_valid_object_name(&encoded_object_name) {
return Err(Box::new(io::Error::new(
io::ErrorKind::InvalidInput,
"invalid object name",
)));
}
// Fetch any existing object info, if there is any for later use.
let maybe_existing_object_info = match self.info(&encoded_object_name).await {
Ok(object_info) => Some(object_info),
Err(_) => None,
};
let object_nuid = nuid::next();
let chunk_subject = format!("$O.{}.C.{}", &self.name, &object_nuid);
let mut object_chunks = 0;
let mut object_size = 0;
let mut buffer = Box::new([0; DEFAULT_CHUNK_SIZE]);
let mut context = ring::digest::Context::new(&SHA256);
loop {
let n = data.read(&mut *buffer).await?;
if n == 0 {
break;
}
context.update(&buffer[..n]);
object_size += n;
object_chunks += 1;
// FIXME: this is ugly
let payload = bytes::Bytes::from(buffer[..n].to_vec());
self.stream
.context
.publish(chunk_subject.clone(), payload)
.await?;
}
let digest = context.finish();
let subject = format!("$O.{}.M.{}", &self.name, &encoded_object_name);
let object_info = ObjectInfo {
name: object_meta.name,
description: object_meta.description,
link: object_meta.link,
bucket: self.name.clone(),
nuid: object_nuid,
chunks: object_chunks,
size: object_size,
digest: format!(
"SHA-256={}",
base64::encode_config(digest, base64::URL_SAFE)
),
modified: OffsetDateTime::now_utc(),
deleted: false,
};
let mut headers = HeaderMap::new();
headers.insert(NATS_ROLLUP, ROLLUP_SUBJECT.parse::<HeaderValue>()?);
let data = serde_json::to_vec(&object_info)?;
// publish meta.
self.stream
.context
.publish_with_headers(subject, headers, data.into())
.await?;
// Purge any old chunks.
if let Some(existing_object_info) = maybe_existing_object_info {
let chunk_subject = format!("$O.{}.C.{}", &self.name, &existing_object_info.nuid);
self.stream.purge_subject(&chunk_subject).await?;
}
Ok(object_info)
}
/// Creates a [Watch] stream over changes in the [ObjectStore].
///
/// # Examples
///
/// ```no_run
/// # #[tokio::main]
/// # async fn main() -> Result<(), async_nats::Error> {
/// use futures::StreamExt;
/// let client = async_nats::connect("demo.nats.io").await?;
/// let jetstream = async_nats::jetstream::new(client);
///
/// let bucket = jetstream.get_object_store("store").await?;
/// let mut watcher = bucket.watch().await.unwrap();
/// while let Some(object) = watcher.next().await {
/// println!("detected changes in {:?}", object?);
/// }
/// # Ok(())
/// # }
/// ```
pub async fn watch(&self) -> Result<Watch<'_>, Error> {
let subject = format!("$O.{}.M.>", self.name);
let ordered = self
.stream
.create_consumer(crate::jetstream::consumer::push::OrderedConfig {
deliver_policy: super::consumer::DeliverPolicy::New,
deliver_subject: self.stream.context.client.new_inbox(),
description: Some("object store watcher".to_string()),
filter_subject: subject,
..Default::default()
})
.await?;
Ok(Watch {
subscription: ordered.messages().await?,
})
}
/// Returns a [List] stream with all not deleted [Objects][Object] in the [ObjectStore].
///
/// # Examples
///
/// ```no_run
/// # #[tokio::main]
/// # async fn main() -> Result<(), async_nats::Error> {
/// use futures::StreamExt;
/// let client = async_nats::connect("demo.nats.io").await?;
/// let jetstream = async_nats::jetstream::new(client);
///
/// let bucket = jetstream.get_object_store("store").await?;
/// let mut list = bucket.list().await.unwrap();
/// while let Some(object) = list.next().await {
/// println!("object {:?}", object?);
/// }
/// # Ok(())
/// # }
/// ```
pub async fn list(&self) -> Result<List<'_>, Error> {
trace!("starting Object List");
let subject = format!("$O.{}.M.>", self.name);
let ordered = self
.stream
.create_consumer(crate::jetstream::consumer::push::OrderedConfig {
deliver_policy: super::consumer::DeliverPolicy::All,
deliver_subject: self.stream.context.client.new_inbox(),
description: Some("object store list".to_string()),
filter_subject: subject,
..Default::default()
})
.await?;
Ok(List {
done: ordered.info.num_pending == 0,
subscription: ordered.messages().await?,
})
}More examples
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
pub async fn watch<T: AsRef<str>>(&self, key: T) -> Result<Watch<'_>, Error> {
let subject = format!("{}{}", self.prefix.as_str(), key.as_ref());
let consumer = self
.stream
.create_consumer(super::consumer::push::OrderedConfig {
deliver_subject: self.stream.context.client.new_inbox(),
description: Some("kv watch consumer".to_string()),
filter_subject: subject,
replay_policy: super::consumer::ReplayPolicy::Instant,
deliver_policy: DeliverPolicy::New,
..Default::default()
})
.await?;
Ok(Watch {
subscription: consumer.messages().await?,
prefix: self.prefix.clone(),
bucket: self.name.clone(),
})
}
/// Creates a [futures::Stream] over [Entries][Entry] for all keys, which yields
/// values whenever there are changes in the bucket.
///
/// # Examples
///
/// ```no_run
/// # #[tokio::main]
/// # async fn main() -> Result<(), async_nats::Error> {
/// use futures::StreamExt;
/// let client = async_nats::connect("demo.nats.io:4222").await?;
/// let jetstream = async_nats::jetstream::new(client);
/// let kv = jetstream.create_key_value(async_nats::jetstream::kv::Config {
/// bucket: "kv".to_string(),
/// history: 10,
/// ..Default::default()
/// }).await?;
/// let mut entries = kv.watch_all().await?;
/// while let Some(entry) = entries.next().await {
/// println!("entry: {:?}", entry);
/// }
/// # Ok(())
/// # }
/// ```
pub async fn watch_all(&self) -> Result<Watch<'_>, Error> {
self.watch(ALL_KEYS).await
}
pub async fn get<T: Into<String>>(&self, key: T) -> Result<Option<Vec<u8>>, Error> {
match self.entry(key).await {
Ok(Some(entry)) => match entry.operation {
Operation::Put => Ok(Some(entry.value)),
_ => Ok(None),
},
Ok(None) => Ok(None),
Err(err) => Err(err),
}
}
/// Updates a value for a given key, but only if passed `revision` is the last `revision` in
/// the bucket.
///
/// # Examples
///
/// ```no_run
/// # #[tokio::main]
/// # async fn main() -> Result<(), async_nats::Error> {
/// use futures::StreamExt;
/// let client = async_nats::connect("demo.nats.io:4222").await?;
/// let jetstream = async_nats::jetstream::new(client);
/// let kv = jetstream.create_key_value(async_nats::jetstream::kv::Config {
/// bucket: "kv".to_string(),
/// history: 10,
/// ..Default::default()
/// }).await?;
/// let revision = kv.put("key", "value".into()).await?;
/// kv.update("key", "updated".into(), revision).await?;
/// # Ok(())
/// # }
/// ```
pub async fn update<T: AsRef<str>>(
&self,
key: T,
value: Bytes,
revision: u64,
) -> Result<u64, Error> {
if !is_valid_key(key.as_ref()) {
return Err(Box::new(io::Error::new(
io::ErrorKind::InvalidInput,
"invalid key",
)));
}
let subject = format!("{}{}", self.prefix.as_str(), key.as_ref());
let mut headers = crate::HeaderMap::default();
headers.insert(
header::NATS_EXPECTED_LAST_SUBJECT_SEQUENCE,
HeaderValue::from(revision),
);
self.stream
.context
.publish_with_headers(subject, headers, value)
.await?
.await
.map(|publish_ack| publish_ack.sequence)
}
/// Deletes a given key. This is a non-destructive operation, which sets a `DELETE` marker.
///
/// # Examples
///
/// ```no_run
/// # #[tokio::main]
/// # async fn main() -> Result<(), async_nats::Error> {
/// use futures::StreamExt;
/// let client = async_nats::connect("demo.nats.io:4222").await?;
/// let jetstream = async_nats::jetstream::new(client);
/// let kv = jetstream.create_key_value(async_nats::jetstream::kv::Config {
/// bucket: "kv".to_string(),
/// history: 10,
/// ..Default::default()
/// }).await?;
/// kv.put("key", "value".into()).await?;
/// kv.delete("key").await?;
/// # Ok(())
/// # }
/// ```
pub async fn delete<T: AsRef<str>>(&self, key: T) -> Result<(), Error> {
if !is_valid_key(key.as_ref()) {
return Err(Box::new(io::Error::new(
io::ErrorKind::InvalidInput,
"invalid key",
)));
}
let mut subject = String::new();
if self.use_jetstream_prefix {
subject.push_str(&self.stream.context.prefix);
subject.push('.');
}
subject.push_str(self.put_prefix.as_ref().unwrap_or(&self.prefix));
subject.push_str(key.as_ref());
let mut headers = crate::HeaderMap::default();
// TODO: figure out which headers k/v should be where.
headers.insert(KV_OPERATION, KV_OPERATION_DELETE.parse::<HeaderValue>()?);
self.stream
.context
.publish_with_headers(subject, headers, "".into())
.await?;
Ok(())
}
/// Purges all the revisions of a entry destructively, leaving behind a single purge entry in-place.
///
/// # Examples
///
/// ```no_run
/// # #[tokio::main]
/// # async fn main() -> Result<(), async_nats::Error> {
/// use futures::StreamExt;
/// let client = async_nats::connect("demo.nats.io:4222").await?;
/// let jetstream = async_nats::jetstream::new(client);
/// let kv = jetstream.create_key_value(async_nats::jetstream::kv::Config {
/// bucket: "kv".to_string(),
/// history: 10,
/// ..Default::default()
/// }).await?;
/// kv.put("key", "value".into()).await?;
/// kv.put("key", "another".into()).await?;
/// kv.purge("key").await?;
/// # Ok(())
/// # }
/// ```
pub async fn purge<T: AsRef<str>>(&self, key: T) -> Result<(), Error> {
if !is_valid_key(key.as_ref()) {
return Err(Box::new(io::Error::new(
io::ErrorKind::InvalidInput,
"invalid key",
)));
}
let subject = format!("{}{}", self.prefix.as_str(), key.as_ref());
let mut headers = crate::HeaderMap::default();
headers.insert(KV_OPERATION, HeaderValue::from(KV_OPERATION_PURGE));
headers.insert(NATS_ROLLUP, HeaderValue::from(ROLLUP_SUBJECT));
self.stream
.context
.publish_with_headers(subject, headers, "".into())
.await?;
Ok(())
}
/// Returns a [futures::Stream] that allows iterating over all [Operations][Operation] that
/// happen for given key.
///
/// # Examples
///
/// ```no_run
/// # #[tokio::main]
/// # async fn main() -> Result<(), async_nats::Error> {
/// use futures::StreamExt;
/// let client = async_nats::connect("demo.nats.io:4222").await?;
/// let jetstream = async_nats::jetstream::new(client);
/// let kv = jetstream.create_key_value(async_nats::jetstream::kv::Config {
/// bucket: "kv".to_string(),
/// history: 10,
/// ..Default::default()
/// }).await?;
/// let mut entries = kv.history("kv").await?;
/// while let Some(entry) = entries.next().await {
/// println!("entry: {:?}", entry);
/// }
/// # Ok(())
/// # }
/// ```
pub async fn history<T: AsRef<str>>(&self, key: T) -> Result<History<'_>, Error> {
if !is_valid_key(key.as_ref()) {
return Err(Box::new(io::Error::new(
io::ErrorKind::InvalidInput,
"invalid key",
)));
}
let subject = format!("{}{}", self.prefix.as_str(), key.as_ref());
let consumer = self
.stream
.create_consumer(super::consumer::push::OrderedConfig {
deliver_subject: self.stream.context.client.new_inbox(),
description: Some("kv history consumer".to_string()),
filter_subject: subject,
replay_policy: super::consumer::ReplayPolicy::Instant,
..Default::default()
})
.await?;
Ok(History {
subscription: consumer.messages().await?,
done: false,
prefix: self.prefix.clone(),
bucket: self.name.clone(),
})
}
/// Returns a [futures::Stream] that allows iterating over all keys in the bucket.
///
/// # Examples
///
/// ```no_run
/// # #[tokio::main]
/// # async fn main() -> Result<(), async_nats::Error> {
/// use futures::StreamExt;
/// let client = async_nats::connect("demo.nats.io:4222").await?;
/// let jetstream = async_nats::jetstream::new(client);
/// let kv = jetstream.create_key_value(async_nats::jetstream::kv::Config {
/// bucket: "kv".to_string(),
/// history: 10,
/// ..Default::default()
/// }).await?;
/// let mut entries = kv.keys().await?;
/// while let Some(key) = entries.next() {
/// println!("key: {:?}", key);
/// }
/// # Ok(())
/// # }
/// ```
pub async fn keys(&self) -> Result<collections::hash_set::IntoIter<String>, Error> {
let subject = format!("{}>", self.prefix.as_str());
let consumer = self
.stream
.create_consumer(super::consumer::push::OrderedConfig {
deliver_subject: self.stream.context.client.new_inbox(),
description: Some("kv history consumer".to_string()),
filter_subject: subject,
headers_only: true,
replay_policy: super::consumer::ReplayPolicy::Instant,
..Default::default()
})
.await?;
let mut entries = History {
done: consumer.info.num_pending == 0,
subscription: consumer.messages().await?,
prefix: self.prefix.clone(),
bucket: self.name.clone(),
};
let mut keys = HashSet::new();
while let Some(entry) = entries.try_next().await? {
keys.insert(entry.key);
}
Ok(keys.into_iter())
}source§impl<T: IntoConsumerConfig> Consumer<T>
impl<T: IntoConsumerConfig> Consumer<T>
sourcepub fn new(config: T, info: Info, context: Context) -> Self
pub fn new(config: T, info: Info, context: Context) -> Self
Examples found in repository?
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
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(),
)),
}
}source§impl<T: IntoConsumerConfig> Consumer<T>
impl<T: IntoConsumerConfig> Consumer<T>
sourcepub async fn info(&mut self) -> Result<&Info, Error>
pub async fn info(&mut self) -> Result<&Info, Error>
Retrieves info about Consumer from the server, updates the cached info inside
Consumer and returns it.
Examples
use async_nats::jetstream::consumer::PullConsumer;
let client = async_nats::connect("localhost:4222").await?;
let jetstream = async_nats::jetstream::new(client);
let mut consumer: PullConsumer = jetstream
.get_stream("events").await?
.get_consumer("pull").await?;
let info = consumer.info().await?;sourcepub fn cached_info(&self) -> &Info
pub fn cached_info(&self) -> &Info
Returns cached Info for the Consumer. Cache is either from initial creation/retrieval of the Consumer or last call to Info.
Examples
use async_nats::jetstream::consumer::PullConsumer;
let client = async_nats::connect("localhost:4222").await?;
let jetstream = async_nats::jetstream::new(client);
let consumer: PullConsumer = jetstream
.get_stream("events").await?
.get_consumer("pull").await?;
let info = consumer.cached_info();