Struct async_nats::Client
source · pub struct Client { /* private fields */ }Expand description
Client is a Cloneable handle to NATS connection.
Client should not be created directly. Instead, one of two methods can be used:
crate::connect and crate::ConnectOptions::connect
Implementations§
source§impl Client
impl Client
sourcepub fn server_info(&self) -> ServerInfo
pub fn server_info(&self) -> ServerInfo
Returns last received info from the server.
Examples
let client = async_nats::connect("demo.nats.io").await?;
println!("info: {:?}", client.server_info());Examples found in repository?
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
pub fn is_server_compatible(&self, major: i64, minor: i64, patch: i64) -> bool {
let info = self.server_info();
let server_version_captures = VERSION_RE.captures(&info.version).unwrap();
let server_major = server_version_captures
.get(1)
.map(|m| m.as_str().parse::<i64>().unwrap())
.unwrap();
let server_minor = server_version_captures
.get(2)
.map(|m| m.as_str().parse::<i64>().unwrap())
.unwrap();
let server_patch = server_version_captures
.get(3)
.map(|m| m.as_str().parse::<i64>().unwrap())
.unwrap();
if server_major < major
|| (server_major == major && server_minor < minor)
|| (server_major == major && server_minor == minor && server_patch < patch)
{
return false;
}
true
}sourcepub fn is_server_compatible(&self, major: i64, minor: i64, patch: i64) -> bool
pub fn is_server_compatible(&self, major: i64, minor: i64, patch: i64) -> bool
Returns true if the server version is compatible with the version components.
Examples
let client = async_nats::connect("demo.nats.io").await?;
assert!(client.is_server_compatible(2, 8, 4));Examples found in repository?
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
pub async fn get_object_store<T: AsRef<str>>(
&self,
bucket_name: T,
) -> Result<ObjectStore, Error> {
if !self.client.is_server_compatible(2, 6, 2) {
return Err(Box::new(io::Error::new(
ErrorKind::Other,
"object-store requires at least server version 2.6.2",
)));
}
let bucket_name = bucket_name.as_ref();
if !is_valid_bucket_name(bucket_name) {
return Err(Box::new(io::Error::new(
io::ErrorKind::InvalidInput,
"invalid bucket name",
)));
}
let stream_name = format!("OBJ_{bucket_name}");
let stream = self.get_stream(stream_name).await?;
Ok(ObjectStore {
name: bucket_name.to_string(),
stream,
})
}More examples
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
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(),
)),
}
}sourcepub async fn publish(
&self,
subject: String,
payload: Bytes
) -> Result<(), PublishError>
pub async fn publish(
&self,
subject: String,
payload: Bytes
) -> Result<(), PublishError>
Publish a Message to a given subject.
Examples
let client = async_nats::connect("demo.nats.io").await?;
client.publish("events.data".into(), "payload".into()).await?;Examples found in repository?
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
pub async fn ack(&self) -> Result<(), Error> {
if let Some(ref reply) = self.reply {
self.context
.client
.publish(reply.to_string(), "".into())
.map_err(Error::from)
.await
} else {
Err(Box::new(std::io::Error::new(
std::io::ErrorKind::Other,
"No reply subject, not a JetStream message",
)))
}
}
/// Acknowledges a message delivery by sending a chosen [AckKind] variant to the server.
///
/// # Examples
///
/// ```no_run
/// # #[tokio::main]
/// # async fn main() -> Result<(), async_nats::Error> {
/// use futures::StreamExt;
/// use async_nats::jetstream::AckKind;
/// 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.fetch().max_messages(100).messages().await?;
///
/// while let Some(message) = messages.next().await {
/// message?.ack_with(AckKind::Nak).await?;
/// }
/// # Ok(())
/// # }
/// ```
pub async fn ack_with(&self, kind: AckKind) -> Result<(), Error> {
if let Some(ref reply) = self.reply {
self.context
.client
.publish(reply.to_string(), kind.into())
.map_err(Error::from)
.await
} else {
Err(Box::new(std::io::Error::new(
std::io::ErrorKind::Other,
"No reply subject, not a JetStream message",
)))
}
}More examples
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
fn poll_next(mut self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> Poll<Option<Self::Item>> {
loop {
match self.subscriber.receiver.poll_recv(cx) {
Poll::Ready(maybe_message) => match maybe_message {
Some(message) => match message.status {
Some(StatusCode::IDLE_HEARTBEAT) => {
if let Some(subject) = message.reply {
// TODO store pending_publish as a future and return errors from it
let client = self.context.client.clone();
tokio::task::spawn(async move {
client
.publish(subject, Bytes::from_static(b""))
.await
.unwrap();
});
}
continue;
}
Some(_) => {
continue;
}
None => {
return Poll::Ready(Some(Ok(jetstream::Message {
context: self.context.clone(),
message,
})))
}
},
None => return Poll::Ready(None),
},
Poll::Pending => return Poll::Pending,
}
}
}
}
/// Configuration for consumers. From a high level, the
/// `durable_name` and `deliver_subject` fields have a particularly
/// strong influence on the consumer's overall behavior.
#[derive(Debug, Default, Serialize, Deserialize, Clone, PartialEq, Eq)]
pub struct Config {
/// The delivery subject used by the push consumer.
#[serde(default)]
pub deliver_subject: String,
/// Setting `durable_name` to `Some(...)` will cause this consumer
/// to be "durable". This may be a good choice for workloads that
/// benefit from the `JetStream` server or cluster remembering the
/// progress of consumers for fault tolerance purposes. If a consumer
/// crashes, the `JetStream` server or cluster will remember which
/// messages the consumer acknowledged. When the consumer recovers,
/// this information will allow the consumer to resume processing
/// where it left off. If you're unsure, set this to `Some(...)`.
///
/// Setting `durable_name` to `None` will cause this consumer to
/// be "ephemeral". This may be a good choice for workloads where
/// you don't need the `JetStream` server to remember the consumer's
/// progress in the case of a crash, such as certain "high churn"
/// workloads or workloads where a crashed instance is not required
/// to recover.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub durable_name: Option<String>,
/// A name of the consumer. Can be specified for both durable and ephemeral
/// consumers.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
/// A short description of the purpose of this consumer.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
/// Deliver group to use.
pub deliver_group: Option<String>,
/// Allows for a variety of options that determine how this consumer will receive messages
#[serde(flatten)]
pub deliver_policy: DeliverPolicy,
/// How messages should be acknowledged
pub ack_policy: AckPolicy,
/// How long to allow messages to remain un-acknowledged before attempting redelivery
#[serde(default, with = "serde_nanos", skip_serializing_if = "is_default")]
pub ack_wait: Duration,
/// Maximum number of times a specific message will be delivered. Use this to avoid poison pill messages that repeatedly crash your consumer processes forever.
#[serde(default, skip_serializing_if = "is_default")]
pub max_deliver: i64,
/// When consuming from a Stream with many subjects, or wildcards, this selects only specific incoming subjects. Supports wildcards.
#[serde(default, skip_serializing_if = "is_default")]
pub filter_subject: String,
/// Whether messages are sent as quickly as possible or at the rate of receipt
pub replay_policy: ReplayPolicy,
/// The rate of message delivery in bits per second
#[serde(default, skip_serializing_if = "is_default")]
pub rate_limit: u64,
/// What percentage of acknowledgments should be samples for observability, 0-100
#[serde(default, skip_serializing_if = "is_default")]
pub sample_frequency: u8,
/// The maximum number of waiting consumers.
#[serde(default, skip_serializing_if = "is_default")]
pub max_waiting: i64,
/// The maximum number of unacknowledged messages that may be
/// in-flight before pausing sending additional messages to
/// this consumer.
#[serde(default, skip_serializing_if = "is_default")]
pub max_ack_pending: i64,
/// Only deliver headers without payloads.
#[serde(default, skip_serializing_if = "is_default")]
pub headers_only: bool,
/// Enable flow control messages
#[serde(default, skip_serializing_if = "is_default")]
pub flow_control: bool,
/// Enable idle heartbeat messages
#[serde(default, with = "serde_nanos", skip_serializing_if = "is_default")]
pub idle_heartbeat: Duration,
/// Number of consumer replicas
#[serde(default, skip_serializing_if = "is_default")]
pub num_replicas: usize,
/// Force consumer to use memory storage.
#[serde(default, skip_serializing_if = "is_default")]
pub memory_storage: bool,
}
impl FromConsumer for Config {
fn try_from_consumer_config(config: super::Config) -> Result<Self, Error> {
if config.deliver_subject.is_none() {
return Err(Box::new(io::Error::new(
ErrorKind::Other,
"push consumer must have delivery subject",
)));
}
Ok(Config {
deliver_subject: config.deliver_subject.unwrap(),
durable_name: config.durable_name,
name: config.name,
description: config.description,
deliver_group: config.deliver_group,
deliver_policy: config.deliver_policy,
ack_policy: config.ack_policy,
ack_wait: config.ack_wait,
max_deliver: config.max_deliver,
filter_subject: config.filter_subject,
replay_policy: config.replay_policy,
rate_limit: config.rate_limit,
sample_frequency: config.sample_frequency,
max_waiting: config.max_waiting,
max_ack_pending: config.max_ack_pending,
headers_only: config.headers_only,
flow_control: config.flow_control,
idle_heartbeat: config.idle_heartbeat,
num_replicas: config.num_replicas,
memory_storage: config.memory_storage,
})
}
}
impl IntoConsumerConfig for Config {
fn into_consumer_config(self) -> jetstream::consumer::Config {
jetstream::consumer::Config {
deliver_subject: Some(self.deliver_subject),
durable_name: self.durable_name,
name: self.name,
description: self.description,
deliver_group: self.deliver_group,
deliver_policy: self.deliver_policy,
ack_policy: self.ack_policy,
ack_wait: self.ack_wait,
max_deliver: self.max_deliver,
filter_subject: self.filter_subject,
replay_policy: self.replay_policy,
rate_limit: self.rate_limit,
sample_frequency: self.sample_frequency,
max_waiting: self.max_waiting,
max_ack_pending: self.max_ack_pending,
headers_only: self.headers_only,
flow_control: self.flow_control,
idle_heartbeat: self.idle_heartbeat,
max_batch: 0,
max_expires: Duration::default(),
inactive_threshold: Duration::default(),
num_replicas: self.num_replicas,
memory_storage: self.memory_storage,
}
}
}
impl IntoConsumerConfig for &Config {
fn into_consumer_config(self) -> jetstream::consumer::Config {
self.clone().into_consumer_config()
}
}
fn is_default<T: Default + Eq>(t: &T) -> bool {
t == &T::default()
}
/// Configuration for consumers. From a high level, the
/// `durable_name` and `deliver_subject` fields have a particularly
/// strong influence on the consumer's overall behavior.
#[derive(Debug, Default, Serialize, Deserialize, Clone, PartialEq, Eq)]
pub struct OrderedConfig {
/// The delivery subject used by the push consumer.
#[serde(default)]
pub deliver_subject: String,
/// A name of the consumer. Can be specified for both durable and ephemeral
/// consumers.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
/// A short description of the purpose of this consumer.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
#[serde(default, skip_serializing_if = "is_default")]
pub filter_subject: String,
/// Whether messages are sent as quickly as possible or at the rate of receipt
pub replay_policy: ReplayPolicy,
/// The rate of message delivery in bits per second
#[serde(default, skip_serializing_if = "is_default")]
pub rate_limit: u64,
/// What percentage of acknowledgments should be samples for observability, 0-100
#[serde(default, skip_serializing_if = "is_default")]
pub sample_frequency: u8,
/// Only deliver headers without payloads.
#[serde(default, skip_serializing_if = "is_default")]
pub headers_only: bool,
/// Allows for a variety of options that determine how this consumer will receive messages
#[serde(flatten)]
pub deliver_policy: DeliverPolicy,
/// The maximum number of waiting consumers.
#[serde(default, skip_serializing_if = "is_default")]
pub max_waiting: i64,
}
impl FromConsumer for OrderedConfig {
fn try_from_consumer_config(config: crate::jetstream::consumer::Config) -> Result<Self, Error>
where
Self: Sized,
{
if config.deliver_subject.is_none() {
return Err(Box::new(io::Error::new(
ErrorKind::Other,
"push consumer must have delivery subject",
)));
}
Ok(OrderedConfig {
name: config.name,
deliver_subject: config.deliver_subject.unwrap(),
description: config.description,
filter_subject: config.filter_subject,
replay_policy: config.replay_policy,
rate_limit: config.rate_limit,
sample_frequency: config.sample_frequency,
headers_only: config.headers_only,
deliver_policy: config.deliver_policy,
max_waiting: config.max_waiting,
})
}
}
impl IntoConsumerConfig for OrderedConfig {
fn into_consumer_config(self) -> super::Config {
jetstream::consumer::Config {
deliver_subject: Some(self.deliver_subject),
durable_name: None,
name: self.name,
description: self.description,
deliver_group: None,
deliver_policy: self.deliver_policy,
ack_policy: AckPolicy::None,
ack_wait: Duration::from_secs(60 * 60 * 22),
max_deliver: 1,
filter_subject: self.filter_subject,
replay_policy: self.replay_policy,
rate_limit: self.rate_limit,
sample_frequency: self.sample_frequency,
max_waiting: self.max_waiting,
max_ack_pending: 0,
headers_only: self.headers_only,
flow_control: true,
idle_heartbeat: Duration::from_secs(5),
max_batch: 0,
max_expires: Duration::default(),
inactive_threshold: Duration::from_secs(30),
num_replicas: 1,
memory_storage: true,
}
}
}
impl Consumer<OrderedConfig> {
pub async fn messages<'a>(self) -> Result<Ordered<'a>, Error> {
let subscriber = self
.context
.client
.subscribe(self.info.config.deliver_subject.clone().unwrap())
.await?;
let last_seen = Arc::new(Mutex::new(Instant::now()));
let last_sequence = Arc::new(AtomicU64::new(0));
let consumer_sequence = Arc::new(AtomicU64::new(0));
let (shutdown_tx, shutdown_rx) = tokio::sync::oneshot::channel();
tokio::task::spawn({
let last_seen = last_seen.clone();
let stream_name = self.info.stream_name.clone();
let config = self.config.clone();
let mut context = self.context.clone();
let last_sequence = last_sequence.clone();
let consumer_sequence = consumer_sequence.clone();
let state = self.context.client.state.clone();
async move {
loop {
let current_state = state.borrow().to_owned();
tokio::select! {
_ = context.client.state.changed() => {
if state.borrow().to_owned() != State::Connected || current_state == State::Connected {
continue;
}
debug!("reconnected. trigger consumer recreation");
},
_ = tokio::time::sleep(Duration::from_secs(5)) => {
debug!("heartbeat check");
if !last_seen
.lock()
.unwrap()
.elapsed()
.gt(&Duration::from_secs(10)) {
trace!("last seen ok. wait");
continue;
}
debug!("last seen not ok");
}
}
debug!(
"idle heartbeats expired. recreating consumer s: {}, {:?}",
stream_name, config
);
let retry_strategy = ExponentialBackoff::from_millis(500).take(5);
let consumer = Retry::spawn(retry_strategy, || {
recreate_ephemeral_consumer(
context.clone(),
config.clone(),
stream_name.clone(),
last_sequence.load(Ordering::Relaxed),
)
})
.await;
if let Err(err) = consumer {
shutdown_tx.send(err).unwrap();
break;
}
*last_seen.lock().unwrap() = Instant::now();
debug!("resetting consume sequence to 0");
consumer_sequence.store(0, Ordering::Relaxed);
}
}
});
Ok(Ordered {
context: self.context.clone(),
consumer: self,
subscriber: Some(subscriber),
subscriber_future: None,
stream_sequence: last_sequence,
consumer_sequence,
last_seen,
shutdown: shutdown_rx,
})
}
}
pub struct Ordered<'a> {
context: Context,
consumer: Consumer<OrderedConfig>,
subscriber: Option<Subscriber>,
subscriber_future: Option<BoxFuture<'a, Result<Subscriber, Error>>>,
stream_sequence: Arc<AtomicU64>,
consumer_sequence: Arc<AtomicU64>,
last_seen: Arc<Mutex<Instant>>,
shutdown: tokio::sync::oneshot::Receiver<Error>,
}
impl<'a> futures::Stream for Ordered<'a> {
type Item = Result<Message, Error>;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> Poll<Option<Self::Item>> {
loop {
match self.shutdown.try_recv() {
Ok(err) => return Poll::Ready(Some(Err(err))),
Err(TryRecvError::Closed) => {
return Poll::Ready(Some(Err(Box::from(io::Error::new(
ErrorKind::Other,
"push consumer task closed",
)))))
}
Err(TryRecvError::Empty) => {}
}
if self.subscriber.is_none() {
match self.subscriber_future.as_mut() {
None => {
let context = self.context.clone();
let sequence = self.stream_sequence.clone();
let config = self.consumer.config.clone();
let stream_name = self.consumer.info.stream_name.clone();
self.subscriber_future = Some(Box::pin(async move {
recreate_consumer_and_subscription(
context,
config,
stream_name,
sequence.load(Ordering::Relaxed),
)
.await
}));
match self.subscriber_future.as_mut().unwrap().as_mut().poll(cx) {
Poll::Ready(subscriber) => {
self.subscriber_future = None;
self.subscriber = Some(subscriber?);
}
Poll::Pending => {
return Poll::Pending;
}
}
}
Some(subscriber) => match subscriber.as_mut().poll(cx) {
Poll::Ready(subscriber) => {
self.subscriber_future = None;
self.consumer_sequence.store(0, Ordering::Relaxed);
self.subscriber = Some(subscriber?);
}
Poll::Pending => {
return Poll::Pending;
}
},
}
}
if let Some(subscriber) = self.subscriber.as_mut() {
match subscriber.receiver.poll_recv(cx) {
Poll::Ready(maybe_message) => {
match maybe_message {
Some(message) => {
*self.last_seen.lock().unwrap() = Instant::now();
match message.status {
Some(StatusCode::IDLE_HEARTBEAT) => {
debug!("received idle heartbeats");
if let Some(headers) = message.headers.as_ref() {
if let Some(sequence) =
headers.get(crate::header::NATS_LAST_STREAM)
{
let sequence: u64 = sequence
.iter().next().unwrap()
.parse()
.map_err(|err|
Box::new(io::Error::new(
ErrorKind::Other,
format!("could not parse header into u64: {err}"))
))?;
if sequence
!= self.stream_sequence.load(Ordering::Relaxed)
{
self.subscriber = None;
}
}
}
if let Some(subject) = message.reply {
// TODO store pending_publish as a future and return errors from it
let client = self.context.client.clone();
tokio::task::spawn(async move {
client
.publish(subject, Bytes::from_static(b""))
.await
.unwrap();
});
}
continue;
}
Some(_) => {
continue;
}
None => {
let jetstream_message = jetstream::message::Message {
message,
context: self.context.clone(),
};
let info = jetstream_message.info()?;
trace!("consumer sequence: {:?}, stream sequence {:?}, consumer sequence in message: {:?} stream sequence in message: {:?}",
self.consumer_sequence,
self.stream_sequence,
info.consumer_sequence,
info.stream_sequence);
if info.consumer_sequence
!= self.consumer_sequence.load(Ordering::Relaxed) + 1
&& info.stream_sequence
!= self.stream_sequence.load(Ordering::Relaxed) + 1
{
debug!(
"ordered consumer mismatch. current {}, info: {}",
self.consumer_sequence.load(Ordering::Relaxed),
info.consumer_sequence
);
self.subscriber = None;
continue;
}
self.stream_sequence
.store(info.stream_sequence, Ordering::Relaxed);
self.consumer_sequence
.store(info.consumer_sequence, Ordering::Relaxed);
return Poll::Ready(Some(Ok(jetstream_message)));
}
}
}
None => {
debug!("received None from subscription");
return Poll::Ready(None);
}
}
}
Poll::Pending => return Poll::Pending,
}
}
}
}sourcepub async fn publish_with_headers(
&self,
subject: String,
headers: HeaderMap,
payload: Bytes
) -> Result<(), PublishError>
pub async fn publish_with_headers(
&self,
subject: String,
headers: HeaderMap,
payload: Bytes
) -> Result<(), PublishError>
Publish a Message with headers to a given subject.
Examples
use std::str::FromStr;
let client = async_nats::connect("demo.nats.io").await?;
let mut headers = async_nats::HeaderMap::new();
headers.insert("X-Header", async_nats::HeaderValue::from_str("Value").unwrap());
client.publish_with_headers("events.data".into(), headers, "payload".into()).await?;sourcepub async fn publish_with_reply(
&self,
subject: String,
reply: String,
payload: Bytes
) -> Result<(), PublishError>
pub async fn publish_with_reply(
&self,
subject: String,
reply: String,
payload: Bytes
) -> Result<(), PublishError>
Publish a Message to a given subject, with specified response subject to which the subscriber can respond. This method does not await for the response.
Examples
let client = async_nats::connect("demo.nats.io").await?;
client.publish_with_reply("events.data".into(), "reply_subject".into(), "payload".into()).await?;Examples found in repository?
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
pub(crate) async fn request_batch<I: Into<BatchConfig>>(
&self,
batch: I,
inbox: String,
) -> Result<(), Error> {
let subject = format!(
"{}.CONSUMER.MSG.NEXT.{}.{}",
self.context.prefix, self.info.stream_name, self.info.name
);
let payload = serde_json::to_vec(&batch.into())?;
self.context
.client
.publish_with_reply(subject, inbox, payload.into())
.await?;
Ok(())
}
/// Returns a batch of specified number of messages, or if there are less messages on the
/// [Stream] than requested, returns all available messages.
///
/// # Example
///
/// ```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 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(())
/// # }
/// ```
pub fn fetch(&self) -> FetchBuilder {
FetchBuilder::new(self)
}
/// Returns a batch of specified number of messages unless timeout happens first.
///
/// # Example
///
/// ```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 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(())
/// # }
/// ```
pub fn batch(&self) -> BatchBuilder {
BatchBuilder::new(self)
}
/// Returns a sequence of [Batches][Batch] allowing for iterating over batches, and then over
/// messages in those batches.
///
/// # Example
///
/// ```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 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(())
/// # }
/// ```
pub fn sequence(&self, batch: usize) -> Result<Sequence, Error> {
let context = self.context.clone();
let subject = format!(
"{}.CONSUMER.MSG.NEXT.{}.{}",
self.context.prefix, self.info.stream_name, self.info.name
);
let request = serde_json::to_vec(&BatchConfig {
batch,
..Default::default()
})
.map(Bytes::from)?;
Ok(Sequence {
context,
subject,
request,
pending_messages: batch,
next: None,
})
}
}
pub struct Batch {
pending_messages: usize,
subscriber: Subscriber,
context: Context,
}
impl<'a> Batch {
async fn batch(batch: BatchConfig, consumer: &Consumer<Config>) -> Result<Batch, Error> {
let inbox = consumer.context.client.new_inbox();
let subscription = consumer.context.client.subscribe(inbox.clone()).await?;
consumer.request_batch(batch, inbox.clone()).await?;
Ok(Batch {
pending_messages: batch.batch,
subscriber: subscription,
context: consumer.context.clone(),
})
}
}
impl futures::Stream for Batch {
type Item = Result<jetstream::Message, Error>;
fn poll_next(
mut self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<Option<Self::Item>> {
if self.pending_messages == 0 {
return std::task::Poll::Ready(None);
}
match self.subscriber.receiver.poll_recv(cx) {
Poll::Ready(maybe_message) => match maybe_message {
Some(message) => match message.status.unwrap_or(StatusCode::OK) {
StatusCode::TIMEOUT => Poll::Ready(None),
StatusCode::IDLE_HEARTBEAT => Poll::Pending,
StatusCode::OK => {
self.pending_messages -= 1;
Poll::Ready(Some(Ok(jetstream::Message {
context: self.context.clone(),
message,
})))
}
status => Poll::Ready(Some(Err(Box::new(std::io::Error::new(
std::io::ErrorKind::Other,
format!(
"error while processing messages from the stream: {}, {:?}",
status, message.description
),
))))),
},
None => Poll::Ready(None),
},
std::task::Poll::Pending => std::task::Poll::Pending,
}
}
}
pub struct Sequence<'a> {
context: Context,
subject: String,
request: Bytes,
pending_messages: usize,
next: Option<BoxFuture<'a, Result<Batch, Error>>>,
}
impl<'a> futures::Stream for Sequence<'a> {
type Item = Result<Batch, Error>;
fn poll_next(
mut self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<Option<Self::Item>> {
match self.next.as_mut() {
None => {
let context = self.context.clone();
let subject = self.subject.clone();
let request = self.request.clone();
let pending_messages = self.pending_messages;
self.next = Some(Box::pin(async move {
let inbox = context.client.new_inbox();
let subscriber = context.client.subscribe(inbox.clone()).await?;
context
.client
.publish_with_reply(subject, inbox, request)
.await?;
Ok(Batch {
pending_messages,
subscriber,
context,
})
}));
match self.next.as_mut().unwrap().as_mut().poll(cx) {
Poll::Ready(result) => {
self.next = None;
Poll::Ready(Some(result))
}
Poll::Pending => Poll::Pending,
}
}
Some(next) => match next.as_mut().poll(cx) {
Poll::Ready(result) => {
self.next = None;
Poll::Ready(Some(result))
}
Poll::Pending => Poll::Pending,
},
}
}
}
pub struct Stream {
pending_messages: usize,
pending_bytes: usize,
request_result_rx: tokio::sync::mpsc::Receiver<Result<bool, crate::Error>>,
request_tx: tokio::sync::watch::Sender<()>,
subscriber: Subscriber,
batch_config: BatchConfig,
context: Context,
pending_request: bool,
task_handle: JoinHandle<()>,
heartbeat_handle: Option<JoinHandle<()>>,
last_seen: Arc<Mutex<Instant>>,
heartbeats_missing: tokio::sync::mpsc::Receiver<()>,
terminated: bool,
}
impl Drop for Stream {
fn drop(&mut self) {
self.task_handle.abort();
if let Some(handle) = self.heartbeat_handle.take() {
handle.abort()
}
}
}
impl Stream {
async fn stream(
batch_config: BatchConfig,
consumer: &Consumer<Config>,
) -> Result<Stream, Error> {
let inbox = consumer.context.client.new_inbox();
let subscription = consumer.context.client.subscribe(inbox.clone()).await?;
let subject = format!(
"{}.CONSUMER.MSG.NEXT.{}.{}",
consumer.context.prefix, consumer.info.stream_name, consumer.info.name
);
let (request_result_tx, request_result_rx) = tokio::sync::mpsc::channel(1);
let (request_tx, mut request_rx) = tokio::sync::watch::channel(());
let task_handle = tokio::task::spawn({
let consumer = consumer.clone();
let batch = batch_config;
let mut context = consumer.context.clone();
let subject = subject;
let inbox = inbox.clone();
async move {
loop {
// this is just in edge case of missing response for some reason.
let expires = batch_config
.expires
.map(|expires| match expires {
0 => futures::future::Either::Left(future::pending()),
t => futures::future::Either::Right(tokio::time::sleep(
Duration::from_nanos(t as u64)
.saturating_add(Duration::from_secs(5)),
)),
})
.unwrap_or_else(|| futures::future::Either::Left(future::pending()));
// Need to check previous state, as `changed` will always fire on first
// call.
let prev_state = context.client.state.borrow().to_owned();
let mut pending_reset = false;
tokio::select! {
_ = context.client.state.changed() => {
let state = context.client.state.borrow().to_owned();
if !(state == crate::connection::State::Connected
&& prev_state != State::Connected) {
continue;
}
debug!("detected !Connected -> Connected state change");
match consumer.fetch_info().await {
Ok(info) => {
if info.num_waiting == 0 {
pending_reset = true;
}
}
Err(err) => {
if let Err(err) = request_result_tx.send(Err(err)).await {
debug!("failed to sent request result: {}", err);
}
},
}
},
_ = request_rx.changed() => debug!("task received request request"),
_ = expires => debug!("expired pull request"),
}
let request = serde_json::to_vec(&batch).map(Bytes::from).unwrap();
let result = context
.client
.publish_with_reply(subject.clone(), inbox.clone(), request.clone())
.await;
if let Err(err) = consumer.context.client.flush().await {
debug!("flush failed: {}", err);
}
debug!("request published");
// TODO: add tracing instead of ignoring this.
request_result_tx
.send(result.map(|_| pending_reset).map_err(|err| {
Box::from(std::io::Error::new(std::io::ErrorKind::Other, err))
}))
.await
.unwrap();
trace!("result send over tx");
}
// }
}
});
let last_seen = Arc::new(Mutex::new(Instant::now()));
let (missed_heartbeat_tx, missed_heartbeat_rx) = tokio::sync::mpsc::channel(1);
let heartbeat_handle = if !batch_config.idle_heartbeat.is_zero() {
debug!("spawning heartbeat checker task");
Some(tokio::task::spawn({
let last_seen = last_seen.clone();
async move {
loop {
tokio::time::sleep(batch_config.idle_heartbeat).await;
debug!("checking for missed heartbeats");
if last_seen
.lock()
.unwrap()
.elapsed()
.gt(&batch_config.idle_heartbeat.saturating_mul(2))
{
debug!("missed heartbeat threshold met");
missed_heartbeat_tx.send(()).await.unwrap();
break;
}
}
}
}))
} else {
None
};
Ok(Stream {
task_handle,
heartbeat_handle,
request_result_rx,
request_tx,
batch_config,
pending_messages: 0,
pending_bytes: 0,
subscriber: subscription,
context: consumer.context.clone(),
pending_request: false,
last_seen,
heartbeats_missing: missed_heartbeat_rx,
terminated: false,
})
}More examples
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
pub async fn send_publish(
&self,
subject: String,
publish: Publish,
) -> Result<PublishAckFuture, Error> {
let inbox = self.client.new_inbox();
let response = self.client.subscribe(inbox.clone()).await?;
tokio::time::timeout(self.timeout, async {
if let Some(headers) = publish.headers {
self.client
.publish_with_reply_and_headers(
subject,
inbox.clone(),
headers,
publish.payload,
)
.await
} else {
self.client
.publish_with_reply(subject, inbox.clone(), publish.payload)
.await
}
})
.map_err(|_| {
std::io::Error::new(ErrorKind::TimedOut, "JetStream publish request timed out")
})
.await??;
Ok(PublishAckFuture {
timeout: self.timeout,
subscription: response,
})
}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
pub async fn double_ack(&self) -> Result<(), Error> {
if let Some(ref reply) = self.reply {
let inbox = self.context.client.new_inbox();
let mut subscription = self.context.client.subscribe(inbox.clone()).await?;
self.context
.client
.publish_with_reply(reply.to_string(), inbox, AckKind::Ack.into())
.await?;
match tokio::time::timeout(self.context.timeout, subscription.next())
.await
.map_err(|_| {
std::io::Error::new(
std::io::ErrorKind::TimedOut,
"double ack response timed out",
)
})? {
Some(_) => Ok(()),
None => Err(Box::new(std::io::Error::new(
std::io::ErrorKind::Other,
"subscription dropped",
))),
}
} else {
Err(Box::new(std::io::Error::new(
std::io::ErrorKind::Other,
"No reply subject, not a JetStream message",
)))
}
}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
pub async fn send_request(&self, subject: String, request: Request) -> Result<Message, Error> {
let inbox = request.inbox.unwrap_or_else(|| self.new_inbox());
let timeout = request.timeout.unwrap_or(self.request_timeout);
let mut sub = self.subscribe(inbox.clone()).await?;
let payload: Bytes = request.payload.unwrap_or_else(Bytes::new);
match request.headers {
Some(headers) => {
self.publish_with_reply_and_headers(subject, inbox, headers, payload)
.await?
}
None => self.publish_with_reply(subject, inbox, payload).await?,
}
self.flush().await?;
let request = match timeout {
Some(timeout) => {
tokio::time::timeout(timeout, sub.next())
.map_err(|_| std::io::Error::new(ErrorKind::TimedOut, "request timed out"))
.await?
}
None => sub.next().await,
};
match request {
Some(message) => {
if message.status == Some(StatusCode::NO_RESPONDERS) {
return Err(Box::new(std::io::Error::new(
ErrorKind::NotFound,
"nats: no responders",
)));
}
Ok(message)
}
None => Err(Box::new(io::Error::new(
ErrorKind::BrokenPipe,
"did not receive any message",
))),
}
}sourcepub async fn publish_with_reply_and_headers(
&self,
subject: String,
reply: String,
headers: HeaderMap,
payload: Bytes
) -> Result<(), PublishError>
pub async fn publish_with_reply_and_headers(
&self,
subject: String,
reply: String,
headers: HeaderMap,
payload: Bytes
) -> Result<(), PublishError>
Publish a Message to a given subject with headers and specified response subject to which the subscriber can respond. This method does not await for the response.
Examples
use std::str::FromStr;
let client = async_nats::connect("demo.nats.io").await?;
let mut headers = async_nats::HeaderMap::new();
client.publish_with_reply_and_headers("events.data".into(), "reply_subject".into(), headers, "payload".into()).await?;Examples found in repository?
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
pub async fn send_publish(
&self,
subject: String,
publish: Publish,
) -> Result<PublishAckFuture, Error> {
let inbox = self.client.new_inbox();
let response = self.client.subscribe(inbox.clone()).await?;
tokio::time::timeout(self.timeout, async {
if let Some(headers) = publish.headers {
self.client
.publish_with_reply_and_headers(
subject,
inbox.clone(),
headers,
publish.payload,
)
.await
} else {
self.client
.publish_with_reply(subject, inbox.clone(), publish.payload)
.await
}
})
.map_err(|_| {
std::io::Error::new(ErrorKind::TimedOut, "JetStream publish request timed out")
})
.await??;
Ok(PublishAckFuture {
timeout: self.timeout,
subscription: response,
})
}More examples
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
pub async fn send_request(&self, subject: String, request: Request) -> Result<Message, Error> {
let inbox = request.inbox.unwrap_or_else(|| self.new_inbox());
let timeout = request.timeout.unwrap_or(self.request_timeout);
let mut sub = self.subscribe(inbox.clone()).await?;
let payload: Bytes = request.payload.unwrap_or_else(Bytes::new);
match request.headers {
Some(headers) => {
self.publish_with_reply_and_headers(subject, inbox, headers, payload)
.await?
}
None => self.publish_with_reply(subject, inbox, payload).await?,
}
self.flush().await?;
let request = match timeout {
Some(timeout) => {
tokio::time::timeout(timeout, sub.next())
.map_err(|_| std::io::Error::new(ErrorKind::TimedOut, "request timed out"))
.await?
}
None => sub.next().await,
};
match request {
Some(message) => {
if message.status == Some(StatusCode::NO_RESPONDERS) {
return Err(Box::new(std::io::Error::new(
ErrorKind::NotFound,
"nats: no responders",
)));
}
Ok(message)
}
None => Err(Box::new(io::Error::new(
ErrorKind::BrokenPipe,
"did not receive any message",
))),
}
}sourcepub async fn request(
&self,
subject: String,
payload: Bytes
) -> Result<Message, Error>
pub async fn request(
&self,
subject: String,
payload: Bytes
) -> Result<Message, Error>
Sends the request with headers.
Examples
let client = async_nats::connect("demo.nats.io").await?;
let response = client.request("service".into(), "data".into()).await?;Examples found in repository?
697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713
pub async fn request<T, V>(&self, subject: String, payload: &T) -> Result<Response<V>, Error>
where
T: ?Sized + Serialize,
V: DeserializeOwned,
{
let request = serde_json::to_vec(&payload).map(Bytes::from)?;
debug!("JetStream request sent: {:?}", request);
let message = self
.client
.request(format!("{}.{}", self.prefix, subject), request)
.await?;
let response = serde_json::from_slice(message.payload.as_ref())?;
Ok(response)
}More examples
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
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)
}sourcepub async fn request_with_headers(
&self,
subject: String,
headers: HeaderMap,
payload: Bytes
) -> Result<Message, Error>
pub async fn request_with_headers(
&self,
subject: String,
headers: HeaderMap,
payload: Bytes
) -> Result<Message, Error>
Sends the request with headers.
Examples
let client = async_nats::connect("demo.nats.io").await?;
let mut headers = async_nats::HeaderMap::new();
headers.insert("Key", "Value");
let response = client.request_with_headers("service".into(), headers, "data".into()).await?;sourcepub async fn send_request(
&self,
subject: String,
request: Request
) -> Result<Message, Error>
pub async fn send_request(
&self,
subject: String,
request: Request
) -> Result<Message, Error>
Sends the request created by the Request.
Examples
let client = async_nats::connect("demo.nats.io").await?;
let request = async_nats::Request::new().payload("data".into());
let response = client.send_request("service".into(), request).await?;Examples found in repository?
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
pub async fn request(&self, subject: String, payload: Bytes) -> Result<Message, Error> {
trace!("request sent to subject: {} ({})", subject, payload.len());
let request = Request::new().payload(payload);
self.send_request(subject, request).await
}
/// Sends the request with headers.
///
/// # Examples
/// ```no_run
///
/// # #[tokio::main]
/// # async fn main() -> Result<(), async_nats::Error> {
/// let client = async_nats::connect("demo.nats.io").await?;
/// let mut headers = async_nats::HeaderMap::new();
/// headers.insert("Key", "Value");
/// let response = client.request_with_headers("service".into(), headers, "data".into()).await?;
/// # Ok(())
/// # }
/// ```
pub async fn request_with_headers(
&self,
subject: String,
headers: HeaderMap,
payload: Bytes,
) -> Result<Message, Error> {
let request = Request::new().headers(headers).payload(payload);
self.send_request(subject, request).await
}sourcepub fn new_inbox(&self) -> String
pub fn new_inbox(&self) -> String
Create a new globally unique inbox which can be used for replies.
Examples
let reply = nc.new_inbox();
let rsub = nc.subscribe(reply).await?;Examples found in repository?
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
async fn batch(batch: BatchConfig, consumer: &Consumer<Config>) -> Result<Batch, Error> {
let inbox = consumer.context.client.new_inbox();
let subscription = consumer.context.client.subscribe(inbox.clone()).await?;
consumer.request_batch(batch, inbox.clone()).await?;
Ok(Batch {
pending_messages: batch.batch,
subscriber: subscription,
context: consumer.context.clone(),
})
}
}
impl futures::Stream for Batch {
type Item = Result<jetstream::Message, Error>;
fn poll_next(
mut self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<Option<Self::Item>> {
if self.pending_messages == 0 {
return std::task::Poll::Ready(None);
}
match self.subscriber.receiver.poll_recv(cx) {
Poll::Ready(maybe_message) => match maybe_message {
Some(message) => match message.status.unwrap_or(StatusCode::OK) {
StatusCode::TIMEOUT => Poll::Ready(None),
StatusCode::IDLE_HEARTBEAT => Poll::Pending,
StatusCode::OK => {
self.pending_messages -= 1;
Poll::Ready(Some(Ok(jetstream::Message {
context: self.context.clone(),
message,
})))
}
status => Poll::Ready(Some(Err(Box::new(std::io::Error::new(
std::io::ErrorKind::Other,
format!(
"error while processing messages from the stream: {}, {:?}",
status, message.description
),
))))),
},
None => Poll::Ready(None),
},
std::task::Poll::Pending => std::task::Poll::Pending,
}
}
}
pub struct Sequence<'a> {
context: Context,
subject: String,
request: Bytes,
pending_messages: usize,
next: Option<BoxFuture<'a, Result<Batch, Error>>>,
}
impl<'a> futures::Stream for Sequence<'a> {
type Item = Result<Batch, Error>;
fn poll_next(
mut self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<Option<Self::Item>> {
match self.next.as_mut() {
None => {
let context = self.context.clone();
let subject = self.subject.clone();
let request = self.request.clone();
let pending_messages = self.pending_messages;
self.next = Some(Box::pin(async move {
let inbox = context.client.new_inbox();
let subscriber = context.client.subscribe(inbox.clone()).await?;
context
.client
.publish_with_reply(subject, inbox, request)
.await?;
Ok(Batch {
pending_messages,
subscriber,
context,
})
}));
match self.next.as_mut().unwrap().as_mut().poll(cx) {
Poll::Ready(result) => {
self.next = None;
Poll::Ready(Some(result))
}
Poll::Pending => Poll::Pending,
}
}
Some(next) => match next.as_mut().poll(cx) {
Poll::Ready(result) => {
self.next = None;
Poll::Ready(Some(result))
}
Poll::Pending => Poll::Pending,
},
}
}
}
pub struct Stream {
pending_messages: usize,
pending_bytes: usize,
request_result_rx: tokio::sync::mpsc::Receiver<Result<bool, crate::Error>>,
request_tx: tokio::sync::watch::Sender<()>,
subscriber: Subscriber,
batch_config: BatchConfig,
context: Context,
pending_request: bool,
task_handle: JoinHandle<()>,
heartbeat_handle: Option<JoinHandle<()>>,
last_seen: Arc<Mutex<Instant>>,
heartbeats_missing: tokio::sync::mpsc::Receiver<()>,
terminated: bool,
}
impl Drop for Stream {
fn drop(&mut self) {
self.task_handle.abort();
if let Some(handle) = self.heartbeat_handle.take() {
handle.abort()
}
}
}
impl Stream {
async fn stream(
batch_config: BatchConfig,
consumer: &Consumer<Config>,
) -> Result<Stream, Error> {
let inbox = consumer.context.client.new_inbox();
let subscription = consumer.context.client.subscribe(inbox.clone()).await?;
let subject = format!(
"{}.CONSUMER.MSG.NEXT.{}.{}",
consumer.context.prefix, consumer.info.stream_name, consumer.info.name
);
let (request_result_tx, request_result_rx) = tokio::sync::mpsc::channel(1);
let (request_tx, mut request_rx) = tokio::sync::watch::channel(());
let task_handle = tokio::task::spawn({
let consumer = consumer.clone();
let batch = batch_config;
let mut context = consumer.context.clone();
let subject = subject;
let inbox = inbox.clone();
async move {
loop {
// this is just in edge case of missing response for some reason.
let expires = batch_config
.expires
.map(|expires| match expires {
0 => futures::future::Either::Left(future::pending()),
t => futures::future::Either::Right(tokio::time::sleep(
Duration::from_nanos(t as u64)
.saturating_add(Duration::from_secs(5)),
)),
})
.unwrap_or_else(|| futures::future::Either::Left(future::pending()));
// Need to check previous state, as `changed` will always fire on first
// call.
let prev_state = context.client.state.borrow().to_owned();
let mut pending_reset = false;
tokio::select! {
_ = context.client.state.changed() => {
let state = context.client.state.borrow().to_owned();
if !(state == crate::connection::State::Connected
&& prev_state != State::Connected) {
continue;
}
debug!("detected !Connected -> Connected state change");
match consumer.fetch_info().await {
Ok(info) => {
if info.num_waiting == 0 {
pending_reset = true;
}
}
Err(err) => {
if let Err(err) = request_result_tx.send(Err(err)).await {
debug!("failed to sent request result: {}", err);
}
},
}
},
_ = request_rx.changed() => debug!("task received request request"),
_ = expires => debug!("expired pull request"),
}
let request = serde_json::to_vec(&batch).map(Bytes::from).unwrap();
let result = context
.client
.publish_with_reply(subject.clone(), inbox.clone(), request.clone())
.await;
if let Err(err) = consumer.context.client.flush().await {
debug!("flush failed: {}", err);
}
debug!("request published");
// TODO: add tracing instead of ignoring this.
request_result_tx
.send(result.map(|_| pending_reset).map_err(|err| {
Box::from(std::io::Error::new(std::io::ErrorKind::Other, err))
}))
.await
.unwrap();
trace!("result send over tx");
}
// }
}
});
let last_seen = Arc::new(Mutex::new(Instant::now()));
let (missed_heartbeat_tx, missed_heartbeat_rx) = tokio::sync::mpsc::channel(1);
let heartbeat_handle = if !batch_config.idle_heartbeat.is_zero() {
debug!("spawning heartbeat checker task");
Some(tokio::task::spawn({
let last_seen = last_seen.clone();
async move {
loop {
tokio::time::sleep(batch_config.idle_heartbeat).await;
debug!("checking for missed heartbeats");
if last_seen
.lock()
.unwrap()
.elapsed()
.gt(&batch_config.idle_heartbeat.saturating_mul(2))
{
debug!("missed heartbeat threshold met");
missed_heartbeat_tx.send(()).await.unwrap();
break;
}
}
}
}))
} else {
None
};
Ok(Stream {
task_handle,
heartbeat_handle,
request_result_rx,
request_tx,
batch_config,
pending_messages: 0,
pending_bytes: 0,
subscriber: subscription,
context: consumer.context.clone(),
pending_request: false,
last_seen,
heartbeats_missing: missed_heartbeat_rx,
terminated: false,
})
}More examples
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?,
})
}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())
}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
pub async fn send_publish(
&self,
subject: String,
publish: Publish,
) -> Result<PublishAckFuture, Error> {
let inbox = self.client.new_inbox();
let response = self.client.subscribe(inbox.clone()).await?;
tokio::time::timeout(self.timeout, async {
if let Some(headers) = publish.headers {
self.client
.publish_with_reply_and_headers(
subject,
inbox.clone(),
headers,
publish.payload,
)
.await
} else {
self.client
.publish_with_reply(subject, inbox.clone(), publish.payload)
.await
}
})
.map_err(|_| {
std::io::Error::new(ErrorKind::TimedOut, "JetStream publish request timed out")
})
.await??;
Ok(PublishAckFuture {
timeout: self.timeout,
subscription: response,
})
}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
pub async fn double_ack(&self) -> Result<(), Error> {
if let Some(ref reply) = self.reply {
let inbox = self.context.client.new_inbox();
let mut subscription = self.context.client.subscribe(inbox.clone()).await?;
self.context
.client
.publish_with_reply(reply.to_string(), inbox, AckKind::Ack.into())
.await?;
match tokio::time::timeout(self.context.timeout, subscription.next())
.await
.map_err(|_| {
std::io::Error::new(
std::io::ErrorKind::TimedOut,
"double ack response timed out",
)
})? {
Some(_) => Ok(()),
None => Err(Box::new(std::io::Error::new(
std::io::ErrorKind::Other,
"subscription dropped",
))),
}
} else {
Err(Box::new(std::io::Error::new(
std::io::ErrorKind::Other,
"No reply subject, not a JetStream message",
)))
}
}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
pub async fn send_request(&self, subject: String, request: Request) -> Result<Message, Error> {
let inbox = request.inbox.unwrap_or_else(|| self.new_inbox());
let timeout = request.timeout.unwrap_or(self.request_timeout);
let mut sub = self.subscribe(inbox.clone()).await?;
let payload: Bytes = request.payload.unwrap_or_else(Bytes::new);
match request.headers {
Some(headers) => {
self.publish_with_reply_and_headers(subject, inbox, headers, payload)
.await?
}
None => self.publish_with_reply(subject, inbox, payload).await?,
}
self.flush().await?;
let request = match timeout {
Some(timeout) => {
tokio::time::timeout(timeout, sub.next())
.map_err(|_| std::io::Error::new(ErrorKind::TimedOut, "request timed out"))
.await?
}
None => sub.next().await,
};
match request {
Some(message) => {
if message.status == Some(StatusCode::NO_RESPONDERS) {
return Err(Box::new(std::io::Error::new(
ErrorKind::NotFound,
"nats: no responders",
)));
}
Ok(message)
}
None => Err(Box::new(io::Error::new(
ErrorKind::BrokenPipe,
"did not receive any message",
))),
}
}sourcepub async fn subscribe(&self, subject: String) -> Result<Subscriber, Error>
pub async fn subscribe(&self, subject: String) -> Result<Subscriber, Error>
Subscribes to a subject to receive messages.
Examples
use futures::StreamExt;
let client = async_nats::connect("demo.nats.io").await?;
let mut subscription = client.subscribe("events.>".into()).await?;
while let Some(message) = subscription.next().await {
println!("received message: {:?}", message);
}Examples found in repository?
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
pub async fn messages(&self) -> Result<Messages, Error> {
let deliver_subject = self.info.config.deliver_subject.clone().unwrap();
let subscriber = self.context.client.subscribe(deliver_subject).await?;
Ok(Messages {
context: self.context.clone(),
subscriber,
})
}
}
pub struct Messages {
context: Context,
subscriber: Subscriber,
}
impl futures::Stream for Messages {
type Item = Result<Message, Error>;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> Poll<Option<Self::Item>> {
loop {
match self.subscriber.receiver.poll_recv(cx) {
Poll::Ready(maybe_message) => match maybe_message {
Some(message) => match message.status {
Some(StatusCode::IDLE_HEARTBEAT) => {
if let Some(subject) = message.reply {
// TODO store pending_publish as a future and return errors from it
let client = self.context.client.clone();
tokio::task::spawn(async move {
client
.publish(subject, Bytes::from_static(b""))
.await
.unwrap();
});
}
continue;
}
Some(_) => {
continue;
}
None => {
return Poll::Ready(Some(Ok(jetstream::Message {
context: self.context.clone(),
message,
})))
}
},
None => return Poll::Ready(None),
},
Poll::Pending => return Poll::Pending,
}
}
}
}
/// Configuration for consumers. From a high level, the
/// `durable_name` and `deliver_subject` fields have a particularly
/// strong influence on the consumer's overall behavior.
#[derive(Debug, Default, Serialize, Deserialize, Clone, PartialEq, Eq)]
pub struct Config {
/// The delivery subject used by the push consumer.
#[serde(default)]
pub deliver_subject: String,
/// Setting `durable_name` to `Some(...)` will cause this consumer
/// to be "durable". This may be a good choice for workloads that
/// benefit from the `JetStream` server or cluster remembering the
/// progress of consumers for fault tolerance purposes. If a consumer
/// crashes, the `JetStream` server or cluster will remember which
/// messages the consumer acknowledged. When the consumer recovers,
/// this information will allow the consumer to resume processing
/// where it left off. If you're unsure, set this to `Some(...)`.
///
/// Setting `durable_name` to `None` will cause this consumer to
/// be "ephemeral". This may be a good choice for workloads where
/// you don't need the `JetStream` server to remember the consumer's
/// progress in the case of a crash, such as certain "high churn"
/// workloads or workloads where a crashed instance is not required
/// to recover.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub durable_name: Option<String>,
/// A name of the consumer. Can be specified for both durable and ephemeral
/// consumers.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
/// A short description of the purpose of this consumer.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
/// Deliver group to use.
pub deliver_group: Option<String>,
/// Allows for a variety of options that determine how this consumer will receive messages
#[serde(flatten)]
pub deliver_policy: DeliverPolicy,
/// How messages should be acknowledged
pub ack_policy: AckPolicy,
/// How long to allow messages to remain un-acknowledged before attempting redelivery
#[serde(default, with = "serde_nanos", skip_serializing_if = "is_default")]
pub ack_wait: Duration,
/// Maximum number of times a specific message will be delivered. Use this to avoid poison pill messages that repeatedly crash your consumer processes forever.
#[serde(default, skip_serializing_if = "is_default")]
pub max_deliver: i64,
/// When consuming from a Stream with many subjects, or wildcards, this selects only specific incoming subjects. Supports wildcards.
#[serde(default, skip_serializing_if = "is_default")]
pub filter_subject: String,
/// Whether messages are sent as quickly as possible or at the rate of receipt
pub replay_policy: ReplayPolicy,
/// The rate of message delivery in bits per second
#[serde(default, skip_serializing_if = "is_default")]
pub rate_limit: u64,
/// What percentage of acknowledgments should be samples for observability, 0-100
#[serde(default, skip_serializing_if = "is_default")]
pub sample_frequency: u8,
/// The maximum number of waiting consumers.
#[serde(default, skip_serializing_if = "is_default")]
pub max_waiting: i64,
/// The maximum number of unacknowledged messages that may be
/// in-flight before pausing sending additional messages to
/// this consumer.
#[serde(default, skip_serializing_if = "is_default")]
pub max_ack_pending: i64,
/// Only deliver headers without payloads.
#[serde(default, skip_serializing_if = "is_default")]
pub headers_only: bool,
/// Enable flow control messages
#[serde(default, skip_serializing_if = "is_default")]
pub flow_control: bool,
/// Enable idle heartbeat messages
#[serde(default, with = "serde_nanos", skip_serializing_if = "is_default")]
pub idle_heartbeat: Duration,
/// Number of consumer replicas
#[serde(default, skip_serializing_if = "is_default")]
pub num_replicas: usize,
/// Force consumer to use memory storage.
#[serde(default, skip_serializing_if = "is_default")]
pub memory_storage: bool,
}
impl FromConsumer for Config {
fn try_from_consumer_config(config: super::Config) -> Result<Self, Error> {
if config.deliver_subject.is_none() {
return Err(Box::new(io::Error::new(
ErrorKind::Other,
"push consumer must have delivery subject",
)));
}
Ok(Config {
deliver_subject: config.deliver_subject.unwrap(),
durable_name: config.durable_name,
name: config.name,
description: config.description,
deliver_group: config.deliver_group,
deliver_policy: config.deliver_policy,
ack_policy: config.ack_policy,
ack_wait: config.ack_wait,
max_deliver: config.max_deliver,
filter_subject: config.filter_subject,
replay_policy: config.replay_policy,
rate_limit: config.rate_limit,
sample_frequency: config.sample_frequency,
max_waiting: config.max_waiting,
max_ack_pending: config.max_ack_pending,
headers_only: config.headers_only,
flow_control: config.flow_control,
idle_heartbeat: config.idle_heartbeat,
num_replicas: config.num_replicas,
memory_storage: config.memory_storage,
})
}
}
impl IntoConsumerConfig for Config {
fn into_consumer_config(self) -> jetstream::consumer::Config {
jetstream::consumer::Config {
deliver_subject: Some(self.deliver_subject),
durable_name: self.durable_name,
name: self.name,
description: self.description,
deliver_group: self.deliver_group,
deliver_policy: self.deliver_policy,
ack_policy: self.ack_policy,
ack_wait: self.ack_wait,
max_deliver: self.max_deliver,
filter_subject: self.filter_subject,
replay_policy: self.replay_policy,
rate_limit: self.rate_limit,
sample_frequency: self.sample_frequency,
max_waiting: self.max_waiting,
max_ack_pending: self.max_ack_pending,
headers_only: self.headers_only,
flow_control: self.flow_control,
idle_heartbeat: self.idle_heartbeat,
max_batch: 0,
max_expires: Duration::default(),
inactive_threshold: Duration::default(),
num_replicas: self.num_replicas,
memory_storage: self.memory_storage,
}
}
}
impl IntoConsumerConfig for &Config {
fn into_consumer_config(self) -> jetstream::consumer::Config {
self.clone().into_consumer_config()
}
}
fn is_default<T: Default + Eq>(t: &T) -> bool {
t == &T::default()
}
/// Configuration for consumers. From a high level, the
/// `durable_name` and `deliver_subject` fields have a particularly
/// strong influence on the consumer's overall behavior.
#[derive(Debug, Default, Serialize, Deserialize, Clone, PartialEq, Eq)]
pub struct OrderedConfig {
/// The delivery subject used by the push consumer.
#[serde(default)]
pub deliver_subject: String,
/// A name of the consumer. Can be specified for both durable and ephemeral
/// consumers.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
/// A short description of the purpose of this consumer.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
#[serde(default, skip_serializing_if = "is_default")]
pub filter_subject: String,
/// Whether messages are sent as quickly as possible or at the rate of receipt
pub replay_policy: ReplayPolicy,
/// The rate of message delivery in bits per second
#[serde(default, skip_serializing_if = "is_default")]
pub rate_limit: u64,
/// What percentage of acknowledgments should be samples for observability, 0-100
#[serde(default, skip_serializing_if = "is_default")]
pub sample_frequency: u8,
/// Only deliver headers without payloads.
#[serde(default, skip_serializing_if = "is_default")]
pub headers_only: bool,
/// Allows for a variety of options that determine how this consumer will receive messages
#[serde(flatten)]
pub deliver_policy: DeliverPolicy,
/// The maximum number of waiting consumers.
#[serde(default, skip_serializing_if = "is_default")]
pub max_waiting: i64,
}
impl FromConsumer for OrderedConfig {
fn try_from_consumer_config(config: crate::jetstream::consumer::Config) -> Result<Self, Error>
where
Self: Sized,
{
if config.deliver_subject.is_none() {
return Err(Box::new(io::Error::new(
ErrorKind::Other,
"push consumer must have delivery subject",
)));
}
Ok(OrderedConfig {
name: config.name,
deliver_subject: config.deliver_subject.unwrap(),
description: config.description,
filter_subject: config.filter_subject,
replay_policy: config.replay_policy,
rate_limit: config.rate_limit,
sample_frequency: config.sample_frequency,
headers_only: config.headers_only,
deliver_policy: config.deliver_policy,
max_waiting: config.max_waiting,
})
}
}
impl IntoConsumerConfig for OrderedConfig {
fn into_consumer_config(self) -> super::Config {
jetstream::consumer::Config {
deliver_subject: Some(self.deliver_subject),
durable_name: None,
name: self.name,
description: self.description,
deliver_group: None,
deliver_policy: self.deliver_policy,
ack_policy: AckPolicy::None,
ack_wait: Duration::from_secs(60 * 60 * 22),
max_deliver: 1,
filter_subject: self.filter_subject,
replay_policy: self.replay_policy,
rate_limit: self.rate_limit,
sample_frequency: self.sample_frequency,
max_waiting: self.max_waiting,
max_ack_pending: 0,
headers_only: self.headers_only,
flow_control: true,
idle_heartbeat: Duration::from_secs(5),
max_batch: 0,
max_expires: Duration::default(),
inactive_threshold: Duration::from_secs(30),
num_replicas: 1,
memory_storage: true,
}
}
}
impl Consumer<OrderedConfig> {
pub async fn messages<'a>(self) -> Result<Ordered<'a>, Error> {
let subscriber = self
.context
.client
.subscribe(self.info.config.deliver_subject.clone().unwrap())
.await?;
let last_seen = Arc::new(Mutex::new(Instant::now()));
let last_sequence = Arc::new(AtomicU64::new(0));
let consumer_sequence = Arc::new(AtomicU64::new(0));
let (shutdown_tx, shutdown_rx) = tokio::sync::oneshot::channel();
tokio::task::spawn({
let last_seen = last_seen.clone();
let stream_name = self.info.stream_name.clone();
let config = self.config.clone();
let mut context = self.context.clone();
let last_sequence = last_sequence.clone();
let consumer_sequence = consumer_sequence.clone();
let state = self.context.client.state.clone();
async move {
loop {
let current_state = state.borrow().to_owned();
tokio::select! {
_ = context.client.state.changed() => {
if state.borrow().to_owned() != State::Connected || current_state == State::Connected {
continue;
}
debug!("reconnected. trigger consumer recreation");
},
_ = tokio::time::sleep(Duration::from_secs(5)) => {
debug!("heartbeat check");
if !last_seen
.lock()
.unwrap()
.elapsed()
.gt(&Duration::from_secs(10)) {
trace!("last seen ok. wait");
continue;
}
debug!("last seen not ok");
}
}
debug!(
"idle heartbeats expired. recreating consumer s: {}, {:?}",
stream_name, config
);
let retry_strategy = ExponentialBackoff::from_millis(500).take(5);
let consumer = Retry::spawn(retry_strategy, || {
recreate_ephemeral_consumer(
context.clone(),
config.clone(),
stream_name.clone(),
last_sequence.load(Ordering::Relaxed),
)
})
.await;
if let Err(err) = consumer {
shutdown_tx.send(err).unwrap();
break;
}
*last_seen.lock().unwrap() = Instant::now();
debug!("resetting consume sequence to 0");
consumer_sequence.store(0, Ordering::Relaxed);
}
}
});
Ok(Ordered {
context: self.context.clone(),
consumer: self,
subscriber: Some(subscriber),
subscriber_future: None,
stream_sequence: last_sequence,
consumer_sequence,
last_seen,
shutdown: shutdown_rx,
})
}
}
pub struct Ordered<'a> {
context: Context,
consumer: Consumer<OrderedConfig>,
subscriber: Option<Subscriber>,
subscriber_future: Option<BoxFuture<'a, Result<Subscriber, Error>>>,
stream_sequence: Arc<AtomicU64>,
consumer_sequence: Arc<AtomicU64>,
last_seen: Arc<Mutex<Instant>>,
shutdown: tokio::sync::oneshot::Receiver<Error>,
}
impl<'a> futures::Stream for Ordered<'a> {
type Item = Result<Message, Error>;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> Poll<Option<Self::Item>> {
loop {
match self.shutdown.try_recv() {
Ok(err) => return Poll::Ready(Some(Err(err))),
Err(TryRecvError::Closed) => {
return Poll::Ready(Some(Err(Box::from(io::Error::new(
ErrorKind::Other,
"push consumer task closed",
)))))
}
Err(TryRecvError::Empty) => {}
}
if self.subscriber.is_none() {
match self.subscriber_future.as_mut() {
None => {
let context = self.context.clone();
let sequence = self.stream_sequence.clone();
let config = self.consumer.config.clone();
let stream_name = self.consumer.info.stream_name.clone();
self.subscriber_future = Some(Box::pin(async move {
recreate_consumer_and_subscription(
context,
config,
stream_name,
sequence.load(Ordering::Relaxed),
)
.await
}));
match self.subscriber_future.as_mut().unwrap().as_mut().poll(cx) {
Poll::Ready(subscriber) => {
self.subscriber_future = None;
self.subscriber = Some(subscriber?);
}
Poll::Pending => {
return Poll::Pending;
}
}
}
Some(subscriber) => match subscriber.as_mut().poll(cx) {
Poll::Ready(subscriber) => {
self.subscriber_future = None;
self.consumer_sequence.store(0, Ordering::Relaxed);
self.subscriber = Some(subscriber?);
}
Poll::Pending => {
return Poll::Pending;
}
},
}
}
if let Some(subscriber) = self.subscriber.as_mut() {
match subscriber.receiver.poll_recv(cx) {
Poll::Ready(maybe_message) => {
match maybe_message {
Some(message) => {
*self.last_seen.lock().unwrap() = Instant::now();
match message.status {
Some(StatusCode::IDLE_HEARTBEAT) => {
debug!("received idle heartbeats");
if let Some(headers) = message.headers.as_ref() {
if let Some(sequence) =
headers.get(crate::header::NATS_LAST_STREAM)
{
let sequence: u64 = sequence
.iter().next().unwrap()
.parse()
.map_err(|err|
Box::new(io::Error::new(
ErrorKind::Other,
format!("could not parse header into u64: {err}"))
))?;
if sequence
!= self.stream_sequence.load(Ordering::Relaxed)
{
self.subscriber = None;
}
}
}
if let Some(subject) = message.reply {
// TODO store pending_publish as a future and return errors from it
let client = self.context.client.clone();
tokio::task::spawn(async move {
client
.publish(subject, Bytes::from_static(b""))
.await
.unwrap();
});
}
continue;
}
Some(_) => {
continue;
}
None => {
let jetstream_message = jetstream::message::Message {
message,
context: self.context.clone(),
};
let info = jetstream_message.info()?;
trace!("consumer sequence: {:?}, stream sequence {:?}, consumer sequence in message: {:?} stream sequence in message: {:?}",
self.consumer_sequence,
self.stream_sequence,
info.consumer_sequence,
info.stream_sequence);
if info.consumer_sequence
!= self.consumer_sequence.load(Ordering::Relaxed) + 1
&& info.stream_sequence
!= self.stream_sequence.load(Ordering::Relaxed) + 1
{
debug!(
"ordered consumer mismatch. current {}, info: {}",
self.consumer_sequence.load(Ordering::Relaxed),
info.consumer_sequence
);
self.subscriber = None;
continue;
}
self.stream_sequence
.store(info.stream_sequence, Ordering::Relaxed);
self.consumer_sequence
.store(info.consumer_sequence, Ordering::Relaxed);
return Poll::Ready(Some(Ok(jetstream_message)));
}
}
}
None => {
debug!("received None from subscription");
return Poll::Ready(None);
}
}
}
Poll::Pending => return Poll::Pending,
}
}
}
}
}
async fn recreate_consumer_and_subscription(
context: Context,
config: OrderedConfig,
stream_name: String,
sequence: u64,
) -> Result<Subscriber, Error> {
let subscriber = context
.client
.subscribe(config.deliver_subject.clone())
.await?;
recreate_ephemeral_consumer(context, config, stream_name, sequence).await?;
Ok(subscriber)
}More examples
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
async fn batch(batch: BatchConfig, consumer: &Consumer<Config>) -> Result<Batch, Error> {
let inbox = consumer.context.client.new_inbox();
let subscription = consumer.context.client.subscribe(inbox.clone()).await?;
consumer.request_batch(batch, inbox.clone()).await?;
Ok(Batch {
pending_messages: batch.batch,
subscriber: subscription,
context: consumer.context.clone(),
})
}
}
impl futures::Stream for Batch {
type Item = Result<jetstream::Message, Error>;
fn poll_next(
mut self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<Option<Self::Item>> {
if self.pending_messages == 0 {
return std::task::Poll::Ready(None);
}
match self.subscriber.receiver.poll_recv(cx) {
Poll::Ready(maybe_message) => match maybe_message {
Some(message) => match message.status.unwrap_or(StatusCode::OK) {
StatusCode::TIMEOUT => Poll::Ready(None),
StatusCode::IDLE_HEARTBEAT => Poll::Pending,
StatusCode::OK => {
self.pending_messages -= 1;
Poll::Ready(Some(Ok(jetstream::Message {
context: self.context.clone(),
message,
})))
}
status => Poll::Ready(Some(Err(Box::new(std::io::Error::new(
std::io::ErrorKind::Other,
format!(
"error while processing messages from the stream: {}, {:?}",
status, message.description
),
))))),
},
None => Poll::Ready(None),
},
std::task::Poll::Pending => std::task::Poll::Pending,
}
}
}
pub struct Sequence<'a> {
context: Context,
subject: String,
request: Bytes,
pending_messages: usize,
next: Option<BoxFuture<'a, Result<Batch, Error>>>,
}
impl<'a> futures::Stream for Sequence<'a> {
type Item = Result<Batch, Error>;
fn poll_next(
mut self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<Option<Self::Item>> {
match self.next.as_mut() {
None => {
let context = self.context.clone();
let subject = self.subject.clone();
let request = self.request.clone();
let pending_messages = self.pending_messages;
self.next = Some(Box::pin(async move {
let inbox = context.client.new_inbox();
let subscriber = context.client.subscribe(inbox.clone()).await?;
context
.client
.publish_with_reply(subject, inbox, request)
.await?;
Ok(Batch {
pending_messages,
subscriber,
context,
})
}));
match self.next.as_mut().unwrap().as_mut().poll(cx) {
Poll::Ready(result) => {
self.next = None;
Poll::Ready(Some(result))
}
Poll::Pending => Poll::Pending,
}
}
Some(next) => match next.as_mut().poll(cx) {
Poll::Ready(result) => {
self.next = None;
Poll::Ready(Some(result))
}
Poll::Pending => Poll::Pending,
},
}
}
}
pub struct Stream {
pending_messages: usize,
pending_bytes: usize,
request_result_rx: tokio::sync::mpsc::Receiver<Result<bool, crate::Error>>,
request_tx: tokio::sync::watch::Sender<()>,
subscriber: Subscriber,
batch_config: BatchConfig,
context: Context,
pending_request: bool,
task_handle: JoinHandle<()>,
heartbeat_handle: Option<JoinHandle<()>>,
last_seen: Arc<Mutex<Instant>>,
heartbeats_missing: tokio::sync::mpsc::Receiver<()>,
terminated: bool,
}
impl Drop for Stream {
fn drop(&mut self) {
self.task_handle.abort();
if let Some(handle) = self.heartbeat_handle.take() {
handle.abort()
}
}
}
impl Stream {
async fn stream(
batch_config: BatchConfig,
consumer: &Consumer<Config>,
) -> Result<Stream, Error> {
let inbox = consumer.context.client.new_inbox();
let subscription = consumer.context.client.subscribe(inbox.clone()).await?;
let subject = format!(
"{}.CONSUMER.MSG.NEXT.{}.{}",
consumer.context.prefix, consumer.info.stream_name, consumer.info.name
);
let (request_result_tx, request_result_rx) = tokio::sync::mpsc::channel(1);
let (request_tx, mut request_rx) = tokio::sync::watch::channel(());
let task_handle = tokio::task::spawn({
let consumer = consumer.clone();
let batch = batch_config;
let mut context = consumer.context.clone();
let subject = subject;
let inbox = inbox.clone();
async move {
loop {
// this is just in edge case of missing response for some reason.
let expires = batch_config
.expires
.map(|expires| match expires {
0 => futures::future::Either::Left(future::pending()),
t => futures::future::Either::Right(tokio::time::sleep(
Duration::from_nanos(t as u64)
.saturating_add(Duration::from_secs(5)),
)),
})
.unwrap_or_else(|| futures::future::Either::Left(future::pending()));
// Need to check previous state, as `changed` will always fire on first
// call.
let prev_state = context.client.state.borrow().to_owned();
let mut pending_reset = false;
tokio::select! {
_ = context.client.state.changed() => {
let state = context.client.state.borrow().to_owned();
if !(state == crate::connection::State::Connected
&& prev_state != State::Connected) {
continue;
}
debug!("detected !Connected -> Connected state change");
match consumer.fetch_info().await {
Ok(info) => {
if info.num_waiting == 0 {
pending_reset = true;
}
}
Err(err) => {
if let Err(err) = request_result_tx.send(Err(err)).await {
debug!("failed to sent request result: {}", err);
}
},
}
},
_ = request_rx.changed() => debug!("task received request request"),
_ = expires => debug!("expired pull request"),
}
let request = serde_json::to_vec(&batch).map(Bytes::from).unwrap();
let result = context
.client
.publish_with_reply(subject.clone(), inbox.clone(), request.clone())
.await;
if let Err(err) = consumer.context.client.flush().await {
debug!("flush failed: {}", err);
}
debug!("request published");
// TODO: add tracing instead of ignoring this.
request_result_tx
.send(result.map(|_| pending_reset).map_err(|err| {
Box::from(std::io::Error::new(std::io::ErrorKind::Other, err))
}))
.await
.unwrap();
trace!("result send over tx");
}
// }
}
});
let last_seen = Arc::new(Mutex::new(Instant::now()));
let (missed_heartbeat_tx, missed_heartbeat_rx) = tokio::sync::mpsc::channel(1);
let heartbeat_handle = if !batch_config.idle_heartbeat.is_zero() {
debug!("spawning heartbeat checker task");
Some(tokio::task::spawn({
let last_seen = last_seen.clone();
async move {
loop {
tokio::time::sleep(batch_config.idle_heartbeat).await;
debug!("checking for missed heartbeats");
if last_seen
.lock()
.unwrap()
.elapsed()
.gt(&batch_config.idle_heartbeat.saturating_mul(2))
{
debug!("missed heartbeat threshold met");
missed_heartbeat_tx.send(()).await.unwrap();
break;
}
}
}
}))
} else {
None
};
Ok(Stream {
task_handle,
heartbeat_handle,
request_result_rx,
request_tx,
batch_config,
pending_messages: 0,
pending_bytes: 0,
subscriber: subscription,
context: consumer.context.clone(),
pending_request: false,
last_seen,
heartbeats_missing: missed_heartbeat_rx,
terminated: false,
})
}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
pub async fn send_publish(
&self,
subject: String,
publish: Publish,
) -> Result<PublishAckFuture, Error> {
let inbox = self.client.new_inbox();
let response = self.client.subscribe(inbox.clone()).await?;
tokio::time::timeout(self.timeout, async {
if let Some(headers) = publish.headers {
self.client
.publish_with_reply_and_headers(
subject,
inbox.clone(),
headers,
publish.payload,
)
.await
} else {
self.client
.publish_with_reply(subject, inbox.clone(), publish.payload)
.await
}
})
.map_err(|_| {
std::io::Error::new(ErrorKind::TimedOut, "JetStream publish request timed out")
})
.await??;
Ok(PublishAckFuture {
timeout: self.timeout,
subscription: response,
})
}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
pub async fn double_ack(&self) -> Result<(), Error> {
if let Some(ref reply) = self.reply {
let inbox = self.context.client.new_inbox();
let mut subscription = self.context.client.subscribe(inbox.clone()).await?;
self.context
.client
.publish_with_reply(reply.to_string(), inbox, AckKind::Ack.into())
.await?;
match tokio::time::timeout(self.context.timeout, subscription.next())
.await
.map_err(|_| {
std::io::Error::new(
std::io::ErrorKind::TimedOut,
"double ack response timed out",
)
})? {
Some(_) => Ok(()),
None => Err(Box::new(std::io::Error::new(
std::io::ErrorKind::Other,
"subscription dropped",
))),
}
} else {
Err(Box::new(std::io::Error::new(
std::io::ErrorKind::Other,
"No reply subject, not a JetStream message",
)))
}
}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
pub async fn send_request(&self, subject: String, request: Request) -> Result<Message, Error> {
let inbox = request.inbox.unwrap_or_else(|| self.new_inbox());
let timeout = request.timeout.unwrap_or(self.request_timeout);
let mut sub = self.subscribe(inbox.clone()).await?;
let payload: Bytes = request.payload.unwrap_or_else(Bytes::new);
match request.headers {
Some(headers) => {
self.publish_with_reply_and_headers(subject, inbox, headers, payload)
.await?
}
None => self.publish_with_reply(subject, inbox, payload).await?,
}
self.flush().await?;
let request = match timeout {
Some(timeout) => {
tokio::time::timeout(timeout, sub.next())
.map_err(|_| std::io::Error::new(ErrorKind::TimedOut, "request timed out"))
.await?
}
None => sub.next().await,
};
match request {
Some(message) => {
if message.status == Some(StatusCode::NO_RESPONDERS) {
return Err(Box::new(std::io::Error::new(
ErrorKind::NotFound,
"nats: no responders",
)));
}
Ok(message)
}
None => Err(Box::new(io::Error::new(
ErrorKind::BrokenPipe,
"did not receive any message",
))),
}
}sourcepub async fn queue_subscribe(
&self,
subject: String,
queue_group: String
) -> Result<Subscriber, Error>
pub async fn queue_subscribe(
&self,
subject: String,
queue_group: String
) -> Result<Subscriber, Error>
Subscribes to a subject with a queue group to receive messages.
Examples
use futures::StreamExt;
let client = async_nats::connect("demo.nats.io").await?;
let mut subscription = client.queue_subscribe("events.>".into(), "queue".into()).await?;
while let Some(message) = subscription.next().await {
println!("received message: {:?}", message);
}sourcepub async fn flush(&self) -> Result<(), Error>
pub async fn flush(&self) -> Result<(), Error>
Flushes the internal buffer ensuring that all messages are sent.
Examples
let client = async_nats::connect("demo.nats.io").await?;
client.flush().await?;Examples found in repository?
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
pub async fn send_request(&self, subject: String, request: Request) -> Result<Message, Error> {
let inbox = request.inbox.unwrap_or_else(|| self.new_inbox());
let timeout = request.timeout.unwrap_or(self.request_timeout);
let mut sub = self.subscribe(inbox.clone()).await?;
let payload: Bytes = request.payload.unwrap_or_else(Bytes::new);
match request.headers {
Some(headers) => {
self.publish_with_reply_and_headers(subject, inbox, headers, payload)
.await?
}
None => self.publish_with_reply(subject, inbox, payload).await?,
}
self.flush().await?;
let request = match timeout {
Some(timeout) => {
tokio::time::timeout(timeout, sub.next())
.map_err(|_| std::io::Error::new(ErrorKind::TimedOut, "request timed out"))
.await?
}
None => sub.next().await,
};
match request {
Some(message) => {
if message.status == Some(StatusCode::NO_RESPONDERS) {
return Err(Box::new(std::io::Error::new(
ErrorKind::NotFound,
"nats: no responders",
)));
}
Ok(message)
}
None => Err(Box::new(io::Error::new(
ErrorKind::BrokenPipe,
"did not receive any message",
))),
}
}More examples
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
async fn stream(
batch_config: BatchConfig,
consumer: &Consumer<Config>,
) -> Result<Stream, Error> {
let inbox = consumer.context.client.new_inbox();
let subscription = consumer.context.client.subscribe(inbox.clone()).await?;
let subject = format!(
"{}.CONSUMER.MSG.NEXT.{}.{}",
consumer.context.prefix, consumer.info.stream_name, consumer.info.name
);
let (request_result_tx, request_result_rx) = tokio::sync::mpsc::channel(1);
let (request_tx, mut request_rx) = tokio::sync::watch::channel(());
let task_handle = tokio::task::spawn({
let consumer = consumer.clone();
let batch = batch_config;
let mut context = consumer.context.clone();
let subject = subject;
let inbox = inbox.clone();
async move {
loop {
// this is just in edge case of missing response for some reason.
let expires = batch_config
.expires
.map(|expires| match expires {
0 => futures::future::Either::Left(future::pending()),
t => futures::future::Either::Right(tokio::time::sleep(
Duration::from_nanos(t as u64)
.saturating_add(Duration::from_secs(5)),
)),
})
.unwrap_or_else(|| futures::future::Either::Left(future::pending()));
// Need to check previous state, as `changed` will always fire on first
// call.
let prev_state = context.client.state.borrow().to_owned();
let mut pending_reset = false;
tokio::select! {
_ = context.client.state.changed() => {
let state = context.client.state.borrow().to_owned();
if !(state == crate::connection::State::Connected
&& prev_state != State::Connected) {
continue;
}
debug!("detected !Connected -> Connected state change");
match consumer.fetch_info().await {
Ok(info) => {
if info.num_waiting == 0 {
pending_reset = true;
}
}
Err(err) => {
if let Err(err) = request_result_tx.send(Err(err)).await {
debug!("failed to sent request result: {}", err);
}
},
}
},
_ = request_rx.changed() => debug!("task received request request"),
_ = expires => debug!("expired pull request"),
}
let request = serde_json::to_vec(&batch).map(Bytes::from).unwrap();
let result = context
.client
.publish_with_reply(subject.clone(), inbox.clone(), request.clone())
.await;
if let Err(err) = consumer.context.client.flush().await {
debug!("flush failed: {}", err);
}
debug!("request published");
// TODO: add tracing instead of ignoring this.
request_result_tx
.send(result.map(|_| pending_reset).map_err(|err| {
Box::from(std::io::Error::new(std::io::ErrorKind::Other, err))
}))
.await
.unwrap();
trace!("result send over tx");
}
// }
}
});
let last_seen = Arc::new(Mutex::new(Instant::now()));
let (missed_heartbeat_tx, missed_heartbeat_rx) = tokio::sync::mpsc::channel(1);
let heartbeat_handle = if !batch_config.idle_heartbeat.is_zero() {
debug!("spawning heartbeat checker task");
Some(tokio::task::spawn({
let last_seen = last_seen.clone();
async move {
loop {
tokio::time::sleep(batch_config.idle_heartbeat).await;
debug!("checking for missed heartbeats");
if last_seen
.lock()
.unwrap()
.elapsed()
.gt(&batch_config.idle_heartbeat.saturating_mul(2))
{
debug!("missed heartbeat threshold met");
missed_heartbeat_tx.send(()).await.unwrap();
break;
}
}
}
}))
} else {
None
};
Ok(Stream {
task_handle,
heartbeat_handle,
request_result_rx,
request_tx,
batch_config,
pending_messages: 0,
pending_bytes: 0,
subscriber: subscription,
context: consumer.context.clone(),
pending_request: false,
last_seen,
heartbeats_missing: missed_heartbeat_rx,
terminated: false,
})
}sourcepub fn connection_state(&self) -> State
pub fn connection_state(&self) -> State
Returns the current state of the connection.
Examples
let client = async_nats::connect("demo.nats.io").await?;
println!("connection state: {}", client.connection_state());