### service_builder Example Source: https://docs.rs/async-nats/latest/async_nats/service/trait.ServiceExt.html Example demonstrating how to use the service_builder to create and start a service with custom configurations. ```rust use async_nats::service::ServiceExt; use futures_util::StreamExt; let client = async_nats::connect("demo.nats.io").await?; let mut service = client .service_builder() .description("some service") .stats_handler(|endpoint, stats| serde_json::json!({ "endpoint": endpoint })) .start("products", "1.0.0") .await?; let mut endpoint = service.endpoint("get").await?; if let Some(request) = endpoint.next().await { request.respond(Ok("hello".into())).await?; } ``` -------------------------------- ### Service API Example Source: https://docs.rs/async-nats/latest/async_nats/index.html Example of starting a service using the Service API. ```rust use async_nats::service::ServiceExt; // Connect to the NATS server let client = async_nats::connect("demo.nats.io").await?; let mut service = client .service_builder() .description("some service") .stats_handler(|endpoint, stats| serde_json::json!({ "endpoint": endpoint })) .start("products", "1.0.0") .await?; ``` -------------------------------- ### server_info example Source: https://docs.rs/async-nats/latest/src/async_nats/client.rs.html Example of how to use server_info to get the server information. ```rust # #[tokio::main] # async fn main () -> Result<(), async_nats::Error> { let client = async_nats::connect("demo.nats.io").await?; println!("info: {:?}", client.server_info()); # Ok(()) # } ``` -------------------------------- ### Using Service Builder Source: https://docs.rs/async-nats/latest/src/async_nats/service/mod.rs.html Example demonstrating how to use the `service_builder` to configure and start a service. ```rust # #[tokio::main] # async fn main() -> Result<(), async_nats::Error> { use async_nats::service::ServiceExt; use futures_util::StreamExt; let client = async_nats::connect("demo.nats.io").await?; let mut service = client .service_builder() .description("some service") .stats_handler(|endpoint, stats| serde_json::json!({ "endpoint": endpoint })) .start("products", "1.0.0") .await?; let mut endpoint = service.endpoint("get").await?; if let Some(request) = endpoint.next().await { request.respond(Ok("hello".into())).await?; } # Ok(()) # } ``` -------------------------------- ### Get or Create Consumer Example Source: https://docs.rs/async-nats/latest/src/async_nats/jetstream/stream.rs.html Example of getting a consumer if it exists, or creating it if it doesn't. ```rust # #[tokio::main] # async fn main() -> Result<(), async_nats::Error> { use async_nats::jetstream::consumer; use futures_util::StreamExt; let client = async_nats::connect("localhost:4222").await?; let jetstream = async_nats::jetstream::new(client); let stream = jetstream.get_stream("events").await?; let consumer = stream .get_or_create_consumer( "pull", consumer::pull::Config { durable_name: Some("pull".to_string()), ..Default::default() }, ) .await?; # Ok(()) # } ``` -------------------------------- ### Basic Service Usage Example Source: https://docs.rs/async-nats/latest/src/async_nats/service/mod.rs.html An example demonstrating how to start a service, create an endpoint, and respond to a request. ```rust # #[tokio::main] # async fn main() -> Result<(), async_nats::Error> { use async_nats::service::ServiceExt; use futures_util::StreamExt; let client = async_nats::connect("demo.nats.io").await?; let mut service = client.service_builder().start("generator", "1.0.0").await?; let mut endpoint = service.endpoint("get").await?; if let Some(request) = endpoint.next().await { request.respond(Ok("hello".into())).await?; } # Ok(()) # } ``` -------------------------------- ### trim_start_matches examples Source: https://docs.rs/async-nats/latest/async_nats/subject/struct.Subject.html Examples demonstrating the usage of trim_start_matches with different patterns. ```rust assert_eq!("11foo1bar11".trim_start_matches('1'), "foo1bar11"); assert_eq!("123foo1bar123".trim_start_matches(char::is_numeric), "foo1bar123"); let x: &[_] = &['1', '2']; assert_eq!("12foo1bar12".trim_start_matches(x), "foo1bar12"); ``` -------------------------------- ### Connect Options Example Source: https://docs.rs/async-nats/latest/src/async_nats/options.rs.html Example of how to use ConnectOptions to customize connection settings. ```Rust #[tokio::main] async fn main() -> Result<(), async_nats::ConnectError> { let mut options = async_nats::ConnectOptions::new() .require_tls(true) .ping_interval(std::time::Duration::from_secs(10)) .connect("demo.nats.io") .await?; Ok(()) } ``` -------------------------------- ### Examples Source: https://docs.rs/async-nats/latest/async_nats/struct.ConnectOptions.html Example of using ConnectOptions to configure a connection. ```rust let mut options = async_nats::ConnectOptions::new() .require_tls(true) .ping_interval(std::time::Duration::from_secs(10)) .connect("demo.nats.io") .await?; ``` -------------------------------- ### Service Instance Example Source: https://docs.rs/async-nats/latest/async_nats/service/struct.Service.html Example of creating and using a Service instance. ```rust use async_nats::service::ServiceExt; use futures_util::StreamExt; let client = async_nats::connect("demo.nats.io").await?; let mut service = client.service_builder().start("generator", "1.0.0").await?; let mut endpoint = service.endpoint("get").await?; if let Some(request) = endpoint.next().await { request.respond(Ok("hello".into())).await?; } ``` -------------------------------- ### Object Store Get Example Source: https://docs.rs/async-nats/latest/src/async_nats/jetstream/object_store/mod.rs.html Demonstrates how to retrieve an object from an Object Store and read its content. ```rust // Copyright 2020-2022 The NATS Authors // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //! Object Store module use std::collections::{HashMap, VecDeque}; use std::fmt::Display; use std::{cmp, str::FromStr, task::Poll, time::Duration}; use crate::crypto::Sha256; use crate::subject::Subject; use crate::{HeaderMap, HeaderValue}; use base64::engine::general_purpose::URL_SAFE; use base64::engine::Engine; use bytes::BytesMut; use futures_util::future::BoxFuture; use std::sync::LazyLock; use tokio::io::AsyncReadExt; use futures_util::{Stream, StreamExt}; use regex::Regex; use serde::{Deserialize, Serialize}; use tracing::{debug, trace}; use super::consumer::push::{OrderedConfig, OrderedError}; use super::consumer::{DeliverPolicy, StreamError, StreamErrorKind}; use super::context::{PublishError, PublishErrorKind}; use super::stream::{self, ConsumerError, ConsumerErrorKind, PurgeError, PurgeErrorKind}; use super::{consumer::push::Ordered, stream::StorageType}; use crate::error::Error; use crate::header::NATS_ROLLUP; use time::{serde::rfc3339, OffsetDateTime}; const DEFAULT_CHUNK_SIZE: usize = 128 * 1024; const ROLLUP_SUBJECT: &str = "sub"; static BUCKET_NAME_RE: LazyLock = LazyLock::new(|| Regex::new(r"\A[a-zA-Z0-9_-]+\z").unwrap()); static OBJECT_NAME_RE: LazyLock = LazyLock::new(|| Regex::new(r"\A[-/_=\.a-zA-Z0-9]+\z").unwrap()); pub(crate) fn is_valid_bucket_name(bucket_name: &str) -> bool { BUCKET_NAME_RE.is_match(bucket_name) } pub(crate) fn is_valid_object_name(object_name: &str) -> bool { if object_name.is_empty() || object_name.starts_with('.') || object_name.ends_with('.') { return false; } OBJECT_NAME_RE.is_match(object_name) } pub(crate) fn encode_object_name(object_name: &str) -> String { URL_SAFE.encode(object_name) } /// Configuration values for object store buckets. #[derive(Debug, Default, Clone, Serialize, Deserialize)] pub struct Config { /// Name of the storage bucket. pub bucket: String, /// A short description of the purpose of this storage bucket. pub description: Option, /// Maximum age of any value in the bucket, expressed in nanoseconds #[serde(default, with = "serde_nanos")] pub max_age: Duration, /// How large the storage bucket may become in total bytes. pub max_bytes: i64, /// The type of storage backend, `File` (default) and `Memory` pub storage: StorageType, /// How many replicas to keep for each value in a cluster, maximum 5. pub num_replicas: usize, /// Sets compression of the underlying stream. pub compression: bool, // Cluster and tag placement. pub placement: Option, } /// A blob store capable of storing large objects efficiently in streams. #[derive(Clone)] pub struct ObjectStore { pub(crate) name: String, pub(crate) stream: crate::jetstream::stream::Stream, } impl ObjectStore { /// 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> { /// use tokio::io::AsyncReadExt; /// 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 object = bucket.get("FOO").await?; /// /// // Object implements `tokio::io::AsyncRead`. /// let mut bytes = vec![]; /// object.read_to_end(&mut bytes).await?; /// # Ok(()) /// # } /// ``` pub async fn get + Send>(&self, object_name: T) -> Result { self.get_impl(object_name).await } fn get_impl<'bucket, 'future, T>( &'bucket self, object_name: T, ) -> BoxFuture<'future, Result> where T: AsRef + Send + 'future, 'bucket: 'future, { Box::pin(async move { ``` -------------------------------- ### Example: Getting Consumer Info (Updates Cache) Source: https://docs.rs/async-nats/latest/src/async_nats/jetstream/consumer/mod.rs.html Demonstrates how to connect to NATS, get a stream, retrieve a consumer, and then call the `info()` method to get the consumer's information, updating the local cache. ```rust # #[tokio::main] # async fn main() -> Result<(), async_nats::Error> { use async_nats::jetstream::consumer::PullConsumer; let client = async_nats::connect("localhost:4222").await?; let jetstream = async_nats::jetstream::new(client); let mut consumer: PullConsumer = jetstream .get_stream("events") .await? .get_consumer("pull") .await?; let info = consumer.info().await?; # Ok(()) # } ``` -------------------------------- ### publish example Source: https://docs.rs/async-nats/latest/src/async_nats/client.rs.html Example of how to publish a message to a subject. ```rust # #[tokio::main] # async fn main() -> Result<(), async_nats::Error> { let client = async_nats::connect("demo.nats.io").await?; client.publish("events.data", "payload".into()).await?; # Ok(()) # } ``` -------------------------------- ### Examples Source: https://docs.rs/async-nats/latest/async_nats/jetstream/consumer/struct.Consumer.html Example of retrieving consumer info using `info()`. ```rust use async_nats::jetstream::consumer::PullConsumer; let client = async_nats::connect("localhost:4222").await?; let jetstream = async_nats::jetstream::new(client); let mut consumer: PullConsumer = jetstream .get_stream("events") .await?; .get_consumer("pull") .await?; let info = consumer.info().await?; ``` -------------------------------- ### Examples Source: https://docs.rs/async-nats/latest/async_nats/jetstream/consumer/struct.Consumer.html Example of retrieving consumer info using `get_info()`. ```rust use async_nats::jetstream::consumer::PullConsumer; let client = async_nats::connect("localhost:4222").await?; let jetstream = async_nats::jetstream::new(client); let mut consumer: PullConsumer = jetstream .get_stream("events") .await?; .get_consumer("pull") .await?; let info = consumer.get_info().await?; ``` -------------------------------- ### TLS Configuration Example Source: https://docs.rs/async-nats/latest/src/async_nats/tls.rs.html Example of configuring TLS with client authentication. ```rust 111 // if there are no client certs provided, connect with just TLS. 112 Ok(builder.with_no_client_auth()) 113 } 114 } 115 }?; 116 Ok(tls_config) 117} ``` -------------------------------- ### ContextBuilder Example Source: https://docs.rs/async-nats/latest/async_nats/jetstream/context/struct.ContextBuilder.html Example of creating a ContextBuilder and setting various options. ```rust let client = async_nats::connect("demo.nats.io").await?; let context = ContextBuilder::new() .timeout(Duration::from_secs(5)) .api_prefix("MY.JS.API") .max_ack_inflight(1000) .build(client); ``` -------------------------------- ### Examples Source: https://docs.rs/async-nats/latest/async_nats/header/struct.HeaderValue.html Example of creating and inserting headers. ```rust let mut headers = HeaderMap::new(); headers.insert("Key", "Value"); headers.insert("Another", "AnotherValue"); ``` -------------------------------- ### Connect to NATS Example Source: https://docs.rs/async-nats/latest/async_nats/struct.Subscriber.html Example of establishing a connection to a NATS server. ```rust let mut nc = async_nats::connect("demo.nats.io").await?; ``` -------------------------------- ### trim_prefix examples Source: https://docs.rs/async-nats/latest/async_nats/subject/struct.Subject.html Examples demonstrating trim_prefix, which removes an optional prefix. ```rust #![feature(trim_prefix_suffix)] // Prefix present - removes it assert_eq!("foo:bar".trim_prefix("foo:"), "bar"); assert_eq!("foofoo".trim_prefix("foo"), "foo"); // Prefix absent - returns original string assert_eq!("foo:bar".trim_prefix("bar"), "foo:bar"); // Method chaining example assert_eq!("".trim_prefix('<').trim_suffix('>'), "https://example.com/"); ``` -------------------------------- ### HeaderMap::new() Example Source: https://docs.rs/async-nats/latest/src/async_nats/header.rs.html Example of creating an empty HeaderMap. ```rust use async_nats::HeaderMap; let map = HeaderMap::new(); assert!(map.is_empty()); ``` -------------------------------- ### HeaderMap Example Source: https://docs.rs/async-nats/latest/src/async_nats/header.rs.html Example of creating and using HeaderMap to publish with headers. ```rust use async_nats::HeaderMap; #[tokio::main] async fn main() -> Result<(), async_nats::Error> { let client = async_nats::connect("demo.nats.io").await?; let mut headers = HeaderMap::new(); headers.insert("Key", "Value"); client .publish_with_headers("subject", headers, "payload".into()) .await?; Ok(()) } ``` -------------------------------- ### Consumer Info Example Source: https://docs.rs/async-nats/latest/src/async_nats/jetstream/stream.rs.html Example of retrieving information about a consumer. ```rust # #[tokio::main] # async fn main() -> Result<(), async_nats::Error> { use async_nats::jetstream::consumer; let client = async_nats::connect("localhost:4222").await?; let jetstream = async_nats::jetstream::new(client); let stream = jetstream.get_stream("events").await?; let info = stream.consumer_info("pull").await?; # Ok(()) # } ``` -------------------------------- ### Example using credentials_file builder method Source: https://docs.rs/async-nats/latest/async_nats/struct.ConnectOptions.html This example demonstrates using the `credentials_file` builder method to specify a credentials file for authentication. ```rust let nc = async_nats::ConnectOptions::new() .credentials_file("path/to/my.creds") .await? .connect("connect.ngs.global") .await?; ``` -------------------------------- ### min_ack_pending Example Source: https://docs.rs/async-nats/latest/async_nats/jetstream/consumer/pull/struct.BatchBuilder.html Sets overflow threshold for minimum pending acknowledgments before this stream will start getting messages. To use overflow, Consumer needs to have enabled Config::priority_groups and PriorityPolicy::Overflow set. ```rust use async_nats::jetstream::consumer::PullConsumer; use futures_util::StreamExt; 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 .batch() .expires(std::time::Duration::from_secs(30)) .group("A") .min_ack_pending(100) .messages() .await?; while let Some(message) = messages.next().await { let message = message?; println!("message: {:?}", message); message.ack().await?; } ``` -------------------------------- ### Get Consumer Source: https://docs.rs/async-nats/latest/async_nats/jetstream/stream/struct.Stream.html Example of getting a handle to a consumer. ```rust use async_nats::jetstream::consumer; use futures_util::StreamExt; let client = async_nats::connect("localhost:4222").await?; let jetstream = async_nats::jetstream::new(client); let stream = jetstream.get_stream("events").await?; let consumer: consumer::PullConsumer = stream.get_consumer("pull").await?; ``` -------------------------------- ### Example using credentials builder method Source: https://docs.rs/async-nats/latest/async_nats/struct.ConnectOptions.html This example demonstrates using the `credentials` builder method to specify a credentials string for authentication. ```rust let creds = "-----BEGIN NATS USER JWT----- eyJ0eXAiOiJqd3QiLCJhbGciOiJlZDI1NTE5...\n------END NATS USER JWT------\n\n************************* IMPORTANT *************************\nNKEY Seed printed below can be used sign and prove identity.\nNKEYs are sensitive and should be treated as secrets.\n\n-----BEGIN USER NKEY SEED----- SUAIO3FHUX5PNV2LQIIP7TZ3N4L7TX3W53MQGEIVYFIGA635OZCKEYHFLM\n------END USER NKEY SEED------\n"; let nc = async_nats::ConnectOptions::new() .credentials(creds) .expect("failed to parse static creds") .connect("connect.ngs.global") .await?; ``` -------------------------------- ### reset Example Source: https://docs.rs/async-nats/latest/async_nats/jetstream/consumer/struct.Consumer.html Example of how to reset a Consumer's delivery state. ```rust use async_nats::jetstream::consumer::PullConsumer; let client = async_nats::connect("localhost:4222").await?; let jetstream = async_nats::jetstream::new(client); let mut consumer: PullConsumer = jetstream .get_stream("events") .await? .get_consumer("processor") .await?; consumer.reset(Some(42)).await?; ``` -------------------------------- ### Get Consumer Example Source: https://docs.rs/async-nats/latest/src/async_nats/jetstream/stream.rs.html Example of retrieving a consumer by name. ```rust # #[tokio::main] # async fn main() -> Result<(), async_nats::Error> { use async_nats::jetstream::consumer; use futures_util::StreamExt; let client = async_nats::connect("localhost:4222").await?; let jetstream = async_nats::jetstream::new(client); let stream = jetstream.get_stream("events").await?; let consumer: consumer::PullConsumer = stream.get_consumer("pull").await?; # Ok(()) # } ``` -------------------------------- ### max_payload example Source: https://docs.rs/async-nats/latest/src/async_nats/client.rs.html Example of how to use max_payload to get the maximum payload size. ```rust # #[tokio::main] # async fn main () -> Result<(), async_nats::Error> { let client = async_nats::connect("demo.nats.io").await?; println!("max payload: {:?}", client.max_payload()); # Ok(()) # } ``` -------------------------------- ### Get or Create Consumer Source: https://docs.rs/async-nats/latest/async_nats/jetstream/stream/struct.Stream.html Example of getting or creating a consumer with a specific configuration. ```rust use async_nats::jetstream::consumer; use futures_util::StreamExt; let client = async_nats::connect("localhost:4222").await?; let jetstream = async_nats::jetstream::new(client); let stream = jetstream.get_stream("events").await?; let consumer = stream .get_or_create_consumer( "pull", consumer::pull::Config { durable_name: Some("pull".to_string()), ..Default::default() }, ) .await?; ``` -------------------------------- ### Get server info Source: https://docs.rs/async-nats/latest/async_nats/client/struct.Client.html Example of how to get the last received info from the server. ```rust let client = async_nats::connect("demo.nats.io").await?; println!("info: {:?}", client.server_info()); ``` -------------------------------- ### Example using with_credentials_file Source: https://docs.rs/async-nats/latest/async_nats/struct.ConnectOptions.html This example shows how to connect to NATS using credentials from a file. ```rust let nc = async_nats::ConnectOptions::with_credentials_file("path/to/my.creds") .await? .connect("connect.ngs.global") .await?; ``` -------------------------------- ### Add Endpoint Example Source: https://docs.rs/async-nats/latest/async_nats/service/struct.Service.html Example of adding a new endpoint to the Service. ```rust use async_nats::service::ServiceExt; let client = async_nats::connect("demo.nats.io").await?; let mut service = client.service_builder().start("service", "1.0.0").await?; let products = service.endpoint("products").await?; ``` -------------------------------- ### Get Consumer from Stream Source: https://docs.rs/async-nats/latest/src/async_nats/jetstream/context.rs.html Example of how to get a consumer directly from the JetStream context. ```rust # #[tokio::main] # async fn main() -> Result<(), async_nats::Error> { 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_consumer_from_stream("consumer", "stream") .await?; # Ok(()) # } ``` -------------------------------- ### Connecting with options example Source: https://docs.rs/async-nats/latest/src/async_nats/lib.rs.html Example of connecting to a NATS server using `connect_with_options` and publishing a message. ```rust # #[tokio::main] # async fn main() -> Result<(), async_nats::Error> { let mut nc = async_nats::connect_with_options("demo.nats.io", async_nats::ConnectOptions::new()).await?; nc.publish("test", "data".into()).await?; # Ok(()) # } ``` -------------------------------- ### Get Stream Example Source: https://docs.rs/async-nats/latest/src/async_nats/jetstream/context.rs.html Demonstrates how to get a handle to an existing stream on the server. ```rust #[tokio::main] # async fn main() -> Result<(), async_nats::Error> { let client = async_nats::connect("localhost:4222").await?; let jetstream = async_nats::jetstream::new(client); let stream = jetstream.get_stream("events").await?; # Ok(()) # } ``` -------------------------------- ### Example using with_credentials Source: https://docs.rs/async-nats/latest/async_nats/struct.ConnectOptions.html This example shows how to connect to NATS using a credentials string. ```rust let creds = "-----BEGIN NATS USER JWT----- eyJ0eXAiOiJqd3QiLCJhbGciOiJlZDI1NTE5...\n------END NATS USER JWT------\n\n************************* IMPORTANT *************************\nNKEY Seed printed below can be used sign and prove identity.\nNKEYs are sensitive and should be treated as secrets.\n\n-----BEGIN USER NKEY SEED----- SUAIO3FHUX5PNV2LQIIP7TZ3N4L7TX3W53MQGEIVYFIGA635OZCKEYHFLM\n------END USER NKEY SEED------\n"; let nc = async_nats::ConnectOptions::with_credentials(creds) .expect("failed to parse static creds") .connect("connect.ngs.global") .await?; ``` -------------------------------- ### add_service Example Source: https://docs.rs/async-nats/latest/async_nats/service/trait.ServiceExt.html Example demonstrating how to add a service using the add_service method and handle requests. ```rust use async_nats::service::ServiceExt; use futures_util::StreamExt; let client = async_nats::connect("demo.nats.io").await?; let mut service = client .add_service(async_nats::service::Config { name: "generator".to_string(), version: "1.0.0".to_string(), description: None, stats_handler: None, metadata: None, queue_group: None, }) .await?; let mut endpoint = service.endpoint("get").await?; if let Some(request) = endpoint.next().await { request.respond(Ok("hello".into())).await?; } ``` -------------------------------- ### Example using add_root_certificates Source: https://docs.rs/async-nats/latest/async_nats/struct.ConnectOptions.html This example shows how to add root certificates to the connection options. ```rust let nc = async_nats::ConnectOptions::new() .add_root_certificates("mycerts.pem".into()) .connect("demo.nats.io") .await?; ``` -------------------------------- ### Get or Create Stream Example Source: https://docs.rs/async-nats/latest/src/async_nats/jetstream/context.rs.html Shows how to get a stream if it exists, or create it with the specified configuration if it does not. ```rust use async_nats::jetstream::stream::Config; let client = async_nats::connect("localhost:4222").await?; let jetstream = async_nats::jetstream::new(client); let stream = jetstream .get_or_create_stream(Config { name: "events".to_string(), max_messages: 10_000, ..Default::default() }) .await?; # Ok(()) # } ``` -------------------------------- ### Get Consumer from Stream Source: https://docs.rs/async-nats/latest/async_nats/jetstream/context/struct.Context.html Example of getting a Consumer straight from Context, without binding to a Stream first. ```rust 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_consumer_from_stream("consumer", "stream") .await?; ``` -------------------------------- ### Example using add_client_certificate Source: https://docs.rs/async-nats/latest/async_nats/struct.ConnectOptions.html This example demonstrates adding client certificates for authentication. ```rust let nc = async_nats::ConnectOptions::new() .add_client_certificate("cert.pem".into(), "key.pem".into()) .connect("demo.nats.io") .await?; ``` -------------------------------- ### Get default request timeout Source: https://docs.rs/async-nats/latest/async_nats/client/struct.Client.html Example of how to get the default timeout for requests set when creating the client. ```rust let client = async_nats::connect("demo.nats.io").await?; println!("default request timeout: {:?}", client.timeout()); ``` -------------------------------- ### get Example Source: https://docs.rs/async-nats/latest/async_nats/subject/struct.Subject.html Illustrates the safe retrieval of a subslice using `get`, which returns `None` for invalid or out-of-bounds indices. ```rust let v = String::from("🗻∈🌏"); assert_eq!(Some("🗻"), v.get(0..4)); // indices not on UTF-8 sequence boundaries assert!(v.get(1..).is_none()); assert!(v.get(..8).is_none()); // out of bounds assert!(v.get(..42).is_none()); ``` -------------------------------- ### Example Usage Source: https://docs.rs/async-nats/latest/async_nats/struct.Server.html Demonstrates how to retrieve server pool information and iterate through server details. ```rust let client = async_nats::connect("demo.nats.io").await?; let pool = client.server_pool().await?; for server in &pool { println!( "{:?}: {} failed attempts, connected: {}", server.addr, server.failed_attempts, server.did_connect ); } ``` -------------------------------- ### Putting an Object into the ObjectStore Source: https://docs.rs/async-nats/latest/src/async_nats/jetstream/object_store/mod.rs.html Example demonstrating how to open a file and put its contents into an Object Store bucket. ```rust # #[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(()) # } ``` -------------------------------- ### Try to get server info Source: https://docs.rs/async-nats/latest/async_nats/client/struct.Client.html Example of how to get the last received info from the server if one has been observed. Useful when retry_on_initial_connect is enabled. ```rust let client = async_nats::ConnectOptions::new() .retry_on_initial_connect() .connect("demo.nats.io") .await?; println!("info available: {}", client.try_server_info().is_some()); ``` -------------------------------- ### Pull Consumer Messages Example Source: https://docs.rs/async-nats/latest/src/async_nats/jetstream/consumer/pull.rs.html This example demonstrates how to create a stream, publish a message, get a pull consumer, and then consume messages from it, acknowledging each one. ```rust use futures_util::StreamExt; use futures_util::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", "data".into()).await?; let consumer = stream .get_or_create_consumer( "consumer", async_nats::jetstream::consumer::pull::Config { durable_name: Some("consumer".to_string()), ..Default::default() }, ) .await?; let mut messages = consumer.messages().await?.take(100); while let Some(Ok(message)) = messages.next().await { println!("got message {:?}", message); message.ack().await?; } Ok(()) ``` -------------------------------- ### Get Consumer Info Source: https://docs.rs/async-nats/latest/src/async_nats/jetstream/consumer/mod.rs.html Example of how to retrieve cached information about a consumer. ```rust # #[tokio::main] # async fn main() -> Result<(), async_nats::Error> { # let client = async_nats::connect("localhost:4222").await?; # let jetstream = async_nats::jetstream::new(client); # let mut consumer = jetstream # .get_stream("events") # .await? # .get_consumer("pull") # .await?; let info = consumer.cached_info(); # Ok(()) # } ``` -------------------------------- ### trim examples Source: https://docs.rs/async-nats/latest/async_nats/subject/struct.Subject.html Example demonstrating the `trim` method to remove leading and trailing whitespace. ```rust let s = "\n Hello\tworld\t\n"; assert_eq!("Hello\tworld", s.trim()); ``` -------------------------------- ### Connection State Source: https://docs.rs/async-nats/latest/async_nats/client/struct.Client.html Example of getting the current connection state. ```rust let client = async_nats::connect("demo.nats.io").await?; println!("connection state: {}", client.connection_state()); ``` -------------------------------- ### Example: Purge Key Source: https://docs.rs/async-nats/latest/src/async_nats/jetstream/kv/mod.rs.html Demonstrates purging a key using the `purge` method. ```rust # #[tokio::main] # async fn main() -> Result<(), async_nats::Error> { use futures_util::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(()) # } ``` -------------------------------- ### Get Object Info Source: https://docs.rs/async-nats/latest/src/async_nats/jetstream/object_store/mod.rs.html Example of how to retrieve information about an object in an Object Store. ```rust # #[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(()) # } ``` -------------------------------- ### Get Stream No Info Example Source: https://docs.rs/async-nats/latest/src/async_nats/jetstream/context.rs.html Demonstrates how to get a handle to a stream without fetching its full information, useful for efficiency when performing single operations on many streams. ```rust # #[tokio::main] # async fn main() -> Result<(), async_nats::Error> { let client = async_nats::connect("localhost:4222").await?; let jetstream = async_nats::jetstream::new(client); let stream = jetstream.get_stream_no_info("events").await?; # Ok(()) # } ``` -------------------------------- ### Get max payload size Source: https://docs.rs/async-nats/latest/async_nats/client/struct.Client.html Example of how to get the maximum payload size currently used by the client. Before the first server INFO message, it returns the default server payload limit. ```rust let client = async_nats::connect("demo.nats.io").await?; println!("max payload: {:?}", client.max_payload()); ``` -------------------------------- ### Complete Example Source: https://docs.rs/async-nats/latest/async_nats/index.html Connect to a NATS server, publish messages, and subscribe to receive them. ```rust use bytes::Bytes; use futures_util::StreamExt; #[tokio::main] async fn main() -> Result<(), async_nats::Error> { // Connect to the NATS server let client = async_nats::connect("demo.nats.io").await?; // Subscribe to the "messages" subject let mut subscriber = client.subscribe("messages").await?; // Publish messages to the "messages" subject for _ in 0..10 { client.publish("messages", "data".into()).await?; } // Receive and process messages while let Some(message) = subscriber.next().await { println!("Received message {:?}", message); } Ok(()) } ``` -------------------------------- ### Get Store Status Source: https://docs.rs/async-nats/latest/async_nats/jetstream/kv/struct.Store.html Example of how to query the server for the status of a Key-Value store. ```rust 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 status = kv.status().await?; println!("status: {:?}", status); ``` -------------------------------- ### trim_start basic usage Source: https://docs.rs/async-nats/latest/async_nats/subject/struct.Subject.html Example demonstrating the `trim_start` method to remove leading whitespace. ```rust let s = "\n Hello\tworld\t\n"; assert_eq!("Hello\tworld\t\n", s.trim_start()); ``` -------------------------------- ### Get a key-value bucket Source: https://docs.rs/async-nats/latest/src/async_nats/jetstream/context.rs.html This example demonstrates how to retrieve an existing key-value bucket by its name. ```rust # #[tokio::main] # async fn main() -> Result<(), async_nats::Error> { let client = async_nats::connect("demo.nats.io:4222").await?; let jetstream = async_nats::jetstream::new(client); let kv = jetstream.get_key_value("bucket").await?; # Ok(()) # } ``` -------------------------------- ### Example using jwt with a signing callback Source: https://docs.rs/async-nats/latest/async_nats/struct.ConnectOptions.html This example demonstrates how to use the `jwt` method with a custom signing callback to authenticate with NATS using JWT and an NKeys KeyPair. ```rust let seed = "SUANQDPB2RUOE4ETUA26CNX7FUKE5ZZKFCQIIW63OX225F2CO7UEXTM7ZY"; let key_pair = std::sync::Arc::new(nkeys::KeyPair::from_seed(seed).unwrap()); // load jwt from creds file or other secure source async fn load_jwt() -> std::io::Result { todo!(); } let jwt = load_jwt().await?; let nc = async_nats::ConnectOptions::new() .jwt(jwt, move |nonce| { let key_pair = key_pair.clone(); async move { key_pair.sign(&nonce).map_err(async_nats::AuthError::new) } }) .connect("localhost") .await?; ``` -------------------------------- ### Complete example Source: https://docs.rs/async-nats/latest/src/async_nats/lib.rs.html Connect to the NATS server, publish messages and subscribe to receive messages. ```rust use bytes::Bytes; use futures_util::StreamExt; #[tokio::main] async fn main() -> Result<(), async_nats::Error> { // Connect to the NATS server let client = async_nats::connect("demo.nats.io").await?; // Subscribe to the "messages" subject let mut subscriber = client.subscribe("messages").await?; // Publish messages to the "messages" subject for _ in 0..10 { client.publish("messages", "data".into()).await?; } // Receive and process messages while let Some(message) = subscriber.next().await { println!("Received message {:?}", message); } Ok(()) } ``` -------------------------------- ### Example Usage of PullConsumer::stream Source: https://docs.rs/async-nats/latest/src/async_nats/jetstream/consumer/pull.rs.html Demonstrates how to get a stream of messages from a PullConsumer, configure batching, and process messages. ```rust # #[tokio::main] # async fn main() -> Result<(), async_nats::Error> { use futures_util::StreamExt; use async_nats::jetstream::consumer::PullConsumer; let client = async_nats::connect("localhost:4222").await?; let jetstream = async_nats::jetstream::new(client); let consumer: PullConsumer = jetstream .get_stream("events").await? .get_consumer("pull").await?; let mut messages = consumer.stream() .max_messages_per_batch(100) .max_bytes_per_batch(1024) .messages().await?; while let Some(message) = messages.next().await { let message = message?; println!("message: {:?}", message); message.ack().await?; } # Ok(()) # } ``` -------------------------------- ### info() method example Source: https://docs.rs/async-nats/latest/async_nats/jetstream/consumer/type.OrderedPullConsumer.html Example of retrieving consumer info using the info() method. ```rust use async_nats::jetstream::consumer::PullConsumer; let client = async_nats::connect("localhost:4222").await?; let jetstream = async_nats::jetstream::new(client); let mut consumer: PullConsumer = jetstream .get_stream("events") .await? .get_consumer("pull") .await?; let info = consumer.info().await?; ``` -------------------------------- ### Example for get_raw_message Source: https://docs.rs/async-nats/latest/async_nats/jetstream/stream/struct.Stream.html Demonstrates creating or getting a stream, publishing a message, and then retrieving that message using `get_raw_message`. ```rust #[tokio::main] use futures_util::StreamExt; use futures_util::TryStreamExt; let client = async_nats::connect("localhost:4222").await?; let context = async_nats::jetstream::new(client); let stream = context .get_or_create_stream(async_nats::jetstream::stream::Config { name: "events".to_string(), max_messages: 10_000, ..Default::default() }) .await?; let publish_ack = context.publish("events", "data".into()).await?; let raw_message = stream.get_raw_message(publish_ack.await?.sequence).await?; println!("Retrieved raw message {:?}", raw_message); ``` -------------------------------- ### Publishing with Headers Example Source: https://docs.rs/async-nats/latest/async_nats/header/struct.HeaderMap.html An example demonstrating how to create a HeaderMap, insert key-value pairs, and then publish a message with these headers using the async-nats client. ```rust let client = async_nats::connect("demo.nats.io").await?; let mut headers = async_nats::HeaderMap::new(); headers.insert("Key", "Value"); client .publish_with_headers("subject", headers, "payload".into()) .await?; ``` -------------------------------- ### Examples Source: https://docs.rs/async-nats/latest/async_nats/struct.ConnectOptions.html Connect to the NATS Server leveraging all passed options. ```rust let nc = async_nats::ConnectOptions::new() .require_tls(true) .connect("demo.nats.io") .await?; ``` -------------------------------- ### Get an entry by key Source: https://docs.rs/async-nats/latest/async_nats/jetstream/kv/struct.Store.html This example shows how to retrieve an entry from the Key-Value store using its key. ```rust 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 value = kv.get("key").await?; match value { Some(bytes) => { let value_str = std::str::from_utf8(&bytes)?; println!("Value: {}", value_str); } None => { println!("Key not found or value not set"); } } ``` -------------------------------- ### Examples Source: https://docs.rs/async-nats/latest/async_nats/struct.ConnectOptions.html Use a builder to specify a username and password, to be used when authenticating against the NATS Server. ```rust let nc = async_nats::ConnectOptions::new() .user_and_password("derek".into(), "s3cr3t!".into()) .connect("demo.nats.io") .await?; ``` -------------------------------- ### HeaderMap::get_all() Example Source: https://docs.rs/async-nats/latest/async_nats/header/struct.HeaderMap.html Demonstrates how to get an iterator over all values associated with a particular key using `get_all()`. ```rust let mut headers = HeaderMap::new(); headers.append("Key", "Value1"); headers.append("Key", "Value2"); let mut values = headers.get_all("Key"); let value1 = values.next(); let value2 = values.next(); ``` -------------------------------- ### Directly Get Message by Sequence Source: https://docs.rs/async-nats/latest/src/async_nats/jetstream/stream.rs.html Example demonstrating how to retrieve a specific message from a stream using its sequence number. ```rust # #[tokio::main] # async fn main() -> Result<(), async_nats::Error> { let client = async_nats::connect("demo.nats.io").await?; let jetstream = async_nats::jetstream::new(client); let stream = jetstream.get_stream("events").await?; // Get message without headers let message = stream.direct_get_builder().sequence(100).send().await?; # Ok(()) # } ``` -------------------------------- ### Get Object Store Source: https://docs.rs/async-nats/latest/src/async_nats/jetstream/context.rs.html Example of how to retrieve an existing object store bucket using the JetStream context. ```rust # #[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("bucket").await?; # Ok(()) # } ``` -------------------------------- ### Client Capacity Example Source: https://docs.rs/async-nats/latest/src/async_nats/options.rs.html Example showing how to set a custom capacity for the client's internal channel. ```rust #[tokio::main] async fn main() -> std::result::Result<(), Box> { async_nats::ConnectOptions::new() .client_capacity(256) .connect("demo.nats.io") .await?; Ok(()) } ``` -------------------------------- ### Example for get_first_raw_message_by_subject Source: https://docs.rs/async-nats/latest/async_nats/jetstream/stream/struct.Stream.html Shows how to retrieve the first raw message for a given subject starting from a specific sequence number. ```rust #[tokio::main] use futures_util::StreamExt; use futures_util::TryStreamExt; let client = async_nats::connect("localhost:4222").await?; let context = async_nats::jetstream::new(client); let stream = context.get_stream_no_info("events").await?; let raw_message = stream .get_first_raw_message_by_subject("events.created", 10) .await?; println!("Retrieved raw message {:?}", raw_message); ``` -------------------------------- ### Basic Connection Source: https://docs.rs/async-nats/latest/async_nats/struct.ConnectOptions.html Example of creating new ConnectOptions and connecting to a NATS server. ```rust async_nats::ConnectOptions::new() .read_buffer_capacity(65535) .connect("demo.nats.io") .await?; ``` -------------------------------- ### FetchBuilder Example Source: https://docs.rs/async-nats/latest/async_nats/jetstream/consumer/pull/struct.FetchBuilder.html Demonstrates how to use FetchBuilder to configure batch fetching with max messages and max bytes. ```rust use async_nats::jetstream::consumer::PullConsumer; use futures_util::StreamExt; 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) .max_bytes(1024) .messages() .await?; while let Some(message) = messages.next().await { let message = message?; println!("message: {:?}", message); message.ack().await?; } ``` -------------------------------- ### Directly Get First Message for Subject Source: https://docs.rs/async-nats/latest/src/async_nats/jetstream/stream.rs.html Example demonstrating how to retrieve the first available message for a specific subject in a stream. ```rust # #[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", "data".into()).await?; let message = stream.direct_get_first_for_subject("events.data").await?; # Ok(()) # } ``` -------------------------------- ### HeaderMap::get() Example Source: https://docs.rs/async-nats/latest/async_nats/header/struct.HeaderMap.html Shows how to retrieve a single header value associated with a given key using the `get()` method. ```rust let mut headers = HeaderMap::new(); headers.append("Key", "Value"); let values = headers.get("Key").unwrap(); ``` -------------------------------- ### Example: Getting Consumer Info Without Cache Update Source: https://docs.rs/async-nats/latest/async_nats/jetstream/consumer/type.OrderedPushConsumer.html Demonstrates how to retrieve consumer information from the server without updating the cache. ```rust use async_nats::jetstream::consumer::PullConsumer; let client = async_nats::connect("localhost:4222").await?; let jetstream = async_nats::jetstream::new(client); let mut consumer: PullConsumer = jetstream .get_stream("events") .await?; .get_consumer("pull") .await?; let info = consumer.get_info().await?; ``` -------------------------------- ### Manually create a Box from scratch Source: https://docs.rs/async-nats/latest/async_nats/type.Error.html Example showing how to manually create a Box from scratch using the global allocator. ```rust use std::alloc::{alloc, Layout}; unsafe { let ptr = alloc(Layout::new::()) as *mut i32; // In general .write is required to avoid attempting to destruct // the (uninitialized) previous contents of `ptr`, though for this // simple example `*ptr = 5` would have worked as well. ptr.write(5); let x = Box::from_raw(ptr); } ```