### Environment Setup API Source: https://docs.rs/rabbitmq-stream-client/latest/rabbitmq_stream_client/index_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E This section details how to build the main access point, `Environment`, to connect to a RabbitMQ stream node. It provides a basic example and mentions `EnvironmentBuilder` for more connection options. ```APIDOC ## Building the Environment ### Description Establishes the main access point (`Environment`) to connect to a RabbitMQ stream node. For advanced configuration, refer to `EnvironmentBuilder`. ### Method Not applicable (constructor pattern) ### Endpoint Not applicable ### Parameters None directly for `Environment::builder().build()` ### Request Body None ### Request Example ```rust use rabbitmq_stream_client::Environment; let environment = Environment::builder().build().await?; ``` ### Response #### Success Response - **environment** (Environment) - An instance of the `Environment` struct, ready for connections. #### Response Example (Instance of Environment) ``` -------------------------------- ### Environment Setup Source: https://docs.rs/rabbitmq-stream-client/latest/rabbitmq_stream_client_search=u32+-%3E+bool Demonstrates how to build and connect to a RabbitMQ stream environment using the `Environment::builder()`. ```APIDOC ## Building the environment ### Description This section shows the basic setup for creating an `Environment` instance to connect to RabbitMQ stream. ### Method `Environment::builder().build().await?` ### Endpoint N/A (Client-side setup) ### Parameters N/A ### Request Example ```rust use rabbitmq_stream_client::Environment; let environment = Environment::builder().build().await?; ``` ### Response #### Success Response (200) An initialized `Environment` object allowing further operations. #### Response Example N/A (Object instantiation) ``` -------------------------------- ### Rust: HashMap get method example Source: https://docs.rs/rabbitmq-stream-client/latest/rabbitmq_stream_client/types/struct.Map_search=std%3A%3Avec Shows the usage of the `get()` method for retrieving a value from a `HashMap` in Rust by its key. It returns an `Option<&V>`, providing `Some(&value)` if the key exists or `None` if it doesn't. The key lookup supports borrowed types. ```rust use std::collections::HashMap; let mut map = HashMap::new(); map.insert(1, "a"); assert_eq!(map.get(&1), Some(&"a")); assert_eq!(map.get(&2), None); ``` -------------------------------- ### Rust: HashMap capacity example Source: https://docs.rs/rabbitmq-stream-client/latest/rabbitmq_stream_client/types/struct.Map_search=std%3A%3Avec Demonstrates how to get the capacity of a `HashMap` in Rust. The `capacity()` method returns the number of elements the map can hold without reallocating, providing a lower bound on its storage. This example is adapted from standard library documentation. ```rust use std::collections::HashMap; let map: HashMap = HashMap::with_capacity(100); assert!(map.capacity() >= 100); ``` -------------------------------- ### Environment Setup Source: https://docs.rs/rabbitmq-stream-client/latest/rabbitmq_stream_client/index_search=u32+-%3E+bool Demonstrates how to build the main access point 'Environment' to connect to a RabbitMQ stream node. ```APIDOC ## Building the Environment ### Description This section shows how to initialize the `Environment` object, which is the primary way to connect to a RabbitMQ stream node. ### Method `Environment::builder().build().await` ### Endpoint N/A (Local client initialization) ### Parameters None for the basic build. ### Request Body None ### Request Example ```rust use rabbitmq_stream_client::Environment; let environment = Environment::builder().build().await?; ``` ### Response #### Success Response (200) - **environment** (`Environment`) - An initialized environment object ready for connections. #### Response Example ```rust // No direct JSON response, returns a client object ``` ### Further Options For more connection options, refer to `EnvironmentBuilder`. ``` -------------------------------- ### HashMap Example Source: https://docs.rs/rabbitmq-stream-client/latest/rabbitmq_stream_client/types/struct.Map_search=u32+-%3E+bool Demonstrates the usage of a HashMap-like structure with custom equality and hashing for a struct `S`. ```APIDOC ## HashMap Example ### Description This example showcases how to use a `HashMap` with a custom struct `S` that implements `PartialEq`, `Eq`, and `Hash` traits. It highlights how equality and hashing are determined by the `id` field, ignoring the `name` field. ### Method N/A (Example Code) ### Endpoint N/A (Example Code) ### Parameters N/A ### Request Example ```rust use std::collections::HashMap; use std::hash::{Hash, Hasher}; #[derive(Clone, Copy, Debug)] struct S { id: u32, name: &'static str, // ignored by equality and hashing operations } impl PartialEq for S { fn eq(&self, other: &S) -> bool { self.id == other.id } } impl Eq for S {} impl Hash for S { fn hash(&self, state: &mut H) { self.id.hash(state); } } let j_a = S { id: 1, name: "Jessica" }; let j_b = S { id: 1, name: "Jess" }; let p = S { id: 2, name: "Paul" }; assert_eq!(j_a, j_b); let mut map = HashMap::new(); map.insert(j_a, "Paris"); assert_eq!(map.get_key_value(&j_a), Some((&j_a, &"Paris"))); assert_eq!(map.get_key_value(&j_b), Some((&j_a, &"Paris"))); // the notable case assert_eq!(map.get_key_value(&p), None); ``` ### Response N/A (Example Code) #### Success Response (200) N/A #### Response Example N/A ``` -------------------------------- ### Environment Creation from Client Options Source: https://docs.rs/rabbitmq-stream-client/latest/rabbitmq_stream_client/struct.Environment Demonstrates how to create an `Environment` instance using client options, allowing for configuration-based setup. ```APIDOC ## POST /websites/rs_rabbitmq-stream-client/environment/from-client-option ### Description Creates an environment instance from provided client options. This method is useful for initializing the environment with specific configurations. ### Method POST ### Endpoint /websites/rs_rabbitmq-stream-client/environment/from-client-option ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **client_options** (impl Into) - Required - The client options to use for creating the environment. ### Request Example ```json { "client_options": { "host": "localhost", "port": 5672, "tls": { "enabled": false } } } ``` ### Response #### Success Response (200) - **RabbitMQStreamResult** (object) - A result object containing the created `Environment` instance or an error. #### Response Example ```json { "example": "Ok(Environment object)" or "Err(RabbitMQStreamError details)" } ``` ``` -------------------------------- ### Producer Creation and Batch Sending Setup (Rust) Source: https://docs.rs/rabbitmq-stream-client/latest/src/rabbitmq_stream_client/producer.rs_search=u32+-%3E+bool This snippet illustrates the creation of an internal producer structure and the setup of a background task for batch sending messages. It utilizes a channel for communication between the producer and the batch sender. ```rust let (sender, receiver) = mpsc::channel(self.batch_size); let client = Arc::new(client); let producer = ProducerInternal { producer_id, stream: stream.to_string(), client, publish_sequence, waiting_confirmations, closed: Arc::new(AtomicBool::new(false)), sender, filter_value_extractor: self.filter_value_extractor, on_closed, }; let internal_producer = Arc::new(producer); schedule_batch_send( self.batch_size, receiver, internal_producer.client.clone(), producer_id, publish_version, ); let producer = Producer(internal_producer, PhantomData); Ok(producer) ``` -------------------------------- ### Environment Setup API Source: https://docs.rs/rabbitmq-stream-client/latest/rabbitmq_stream_client/struct.Environment_search=u32+-%3E+bool APIs related to setting up and managing the RabbitMQ Stream client environment. ```APIDOC ## POST /environment ### Description Allows for the creation of an Environment instance using provided client options. ### Method POST ### Endpoint /environment ### Parameters #### Request Body - **client_options** (ClientOptions) - Required - Configuration options for the client connection. ### Request Example ```json { "client_options": { "host": "localhost", "port": 5672, "user": "guest", "password": "guest", "virtual_host": "/", "tls": { "enabled": false } } } ``` ### Response #### Success Response (200) - **Environment** (Environment) - An instance of the Environment. #### Response Example ```json { "message": "Environment created successfully" } ``` ``` ```APIDOC ## GET /environment/builder ### Description Retrieves a builder for configuring the Environment. ### Method GET ### Endpoint /environment/builder ### Response #### Success Response (200) - **EnvironmentBuilder** (EnvironmentBuilder) - A builder object for Environment configuration. #### Response Example ```json { "message": "Environment builder retrieved" } ``` ``` -------------------------------- ### Environment Setup and Stream Management Source: https://docs.rs/rabbitmq-stream-client/latest/rabbitmq_stream_client/struct.Environment This section details how to set up the RabbitMQ stream environment and manage streams, including creating, deleting, and accessing stream-related builders. ```APIDOC ## POST /websites/rs_rabbitmq-stream-client/environment ### Description Provides access to the RabbitMQ stream client environment and allows for stream management operations. ### Method POST ### Endpoint /websites/rs_rabbitmq-stream-client/environment ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```json { "example": "No request body needed for environment access." } ``` ### Response #### Success Response (200) - **Environment** (object) - The main access point to a node. #### Response Example ```json { "example": "Environment object details..." } ``` ## GET /websites/rs_rabbitmq-stream-client/environment/builder ### Description Returns a builder for creating a stream with a specific configuration. ### Method GET ### Endpoint /websites/rs_rabbitmq-stream-client/environment/builder ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```json { "example": "No request body needed." } ``` ### Response #### Success Response (200) - **StreamCreator** (object) - Builder for creating streams. #### Response Example ```json { "example": "StreamCreator object details..." } ``` ## GET /websites/rs_rabbitmq-stream-client/environment/producer ### Description Returns a builder for creating a producer. ### Method GET ### Endpoint /websites/rs_rabbitmq-stream-client/environment/producer ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```json { "example": "No request body needed." } ``` ### Response #### Success Response (200) - **ProducerBuilder** (object) - Builder for creating producers. #### Response Example ```json { "example": "ProducerBuilder object details..." } ``` ## DELETE /websites/rs_rabbitmq-stream-client/environment/streams/{stream} ### Description Deletes a specific stream. ### Method DELETE ### Endpoint /websites/rs_rabbitmq-stream-client/environment/streams/{stream} ### Parameters #### Path Parameters - **stream** (string) - Required - The name of the stream to delete. #### Query Parameters None #### Request Body None ### Request Example ```json { "example": "No request body needed." } ``` ### Response #### Success Response (200) - **Result<(), StreamDeleteError>** (object) - Indicates success or failure of the deletion. #### Response Example ```json { "example": "Ok" or "Err(StreamDeleteError details)" } ``` ## DELETE /websites/rs_rabbitmq-stream-client/environment/super-streams/{super_stream} ### Description Deletes a specific super stream. ### Method DELETE ### Endpoint /websites/rs_rabbitmq-stream-client/environment/super-streams/{super_stream} ### Parameters #### Path Parameters - **super_stream** (string) - Required - The name of the super stream to delete. #### Query Parameters None #### Request Body None ### Request Example ```json { "example": "No request body needed." } ``` ### Response #### Success Response (200) - **Result<(), StreamDeleteError>** (object) - Indicates success or failure of the deletion. #### Response Example ```json { "example": "Ok" or "Err(StreamDeleteError details)" } ``` ``` -------------------------------- ### Rust: HashMap hasher reference example Source: https://docs.rs/rabbitmq-stream-client/latest/rabbitmq_stream_client/types/struct.Map_search=std%3A%3Avec Illustrates how to get a reference to the `BuildHasher` used by a `HashMap` in Rust. The `hasher()` method returns a reference to the `BuildHasher` instance, which is responsible for creating hashers for keys. ```rust use std::collections::HashMap; use std::hash::RandomState; let hasher = RandomState::new(); let map: HashMap = HashMap::with_hasher(hasher); let hasher: &RandomState = map.hasher(); ``` -------------------------------- ### Rust TryFrom Conversion Example Source: https://docs.rs/rabbitmq-stream-client/latest/rabbitmq_stream_client/types/struct.Message_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Demonstrates the usage of `TryFrom` trait for converting between types in Rust. It handles potential conversion errors by returning a `Result`. ```rust type Error = Infallible; fn try_from(value: U) -> Result>::Error> ``` ```rust impl TryInto for T where U: TryFrom, { type Error = >::Error; fn try_into(self) -> Result>::Error> { U::try_from(self) } } ``` -------------------------------- ### Rust Result and() Examples Source: https://docs.rs/rabbitmq-stream-client/latest/rabbitmq_stream_client/type.RabbitMQStreamResult_search=std%3A%3Avec Demonstrates the `and()` method, which returns the second Result if the first is Ok, otherwise returns the first Result's Err. Arguments are evaluated eagerly. ```rust let x: Result = Ok(2); let y: Result<&str, &str> = Err("late error"); assert_eq!(x.and(y), Err("late error")); ``` ```rust let x: Result = Err("early error"); let y: Result<&str, &str> = Ok("foo"); assert_eq!(x.and(y), Err("early error")); ``` ```rust let x: Result = Err("not a 2"); let y: Result<&str, &str> = Err("late error"); assert_eq!(x.and(y), Err("not a 2")); ``` ```rust let x: Result = Ok(2); let y: Result<&str, &str> = Ok("different result type"); assert_eq!(x.and(y), Ok("different result type")); ``` -------------------------------- ### Create RabbitMQ Environment from Client Options (Rust) Source: https://docs.rs/rabbitmq-stream-client/latest/rabbitmq_stream_client/struct.Environment Demonstrates how to create an `Environment` instance for the RabbitMQ stream client using provided client options. This is useful for initializing the connection with specific configurations. ```rust use rabbitmq_stream_client::Environment; use rabbitmq_stream_client::ClientOptions; #[derive(serde::Deserialize)] struct MyConfig { rabbitmq: ClientOptions } let j = r#"{ "rabbitmq": { "host": "localhost", "tls": { "enabled": false } } } "#; let my_config: MyConfig = serde_json::from_str(j).unwrap(); let env = Environment::from_client_option(my_config.rabbitmq) .await .unwrap(); ``` -------------------------------- ### Map Operations: put and get - Rust Source: https://docs.rs/rabbitmq-stream-client/latest/rabbitmq_stream_client/types/struct.Map_search= Provides methods to add (put) and retrieve (get) key-value pairs from the Map. The 'put' method returns the old value if the key already existed, while 'get' returns an optional reference to the value. ```rust pub fn put(&mut self, key: K, value: V) -> Option where K: Into, V: Into, pub fn get(&self, key: K) -> Option<&Value> where K: Into, ``` -------------------------------- ### Map Implementation: get Source: https://docs.rs/rabbitmq-stream-client/latest/rabbitmq_stream_client/types/type.Footer_search= Implements the `get` method for the Map type, allowing retrieval of a value associated with a given key. ```APIDOC ## impl Map ### pub fn get(&self, key: K) -> Option<&Value> #### Description Returns a reference to the value corresponding to the key. #### Method ```rust get(&self, key: K) -> Option<&Value> ``` #### Type Constraints ```rust where K: Into ``` ``` -------------------------------- ### Build Environment with RabbitMQ Stream Client (Rust) Source: https://docs.rs/rabbitmq-stream-client/latest/src/rabbitmq_stream_client/lib.rs_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Demonstrates how to initialize the RabbitMQ Stream client environment. This is the primary access point for connecting to a RabbitMQ node. It utilizes `Environment::builder().build().await?` for asynchronous connection setup. No external dependencies are explicitly mentioned beyond the library itself. ```rust use rabbitmq_stream_client::Environment; async fn doc_fn() -> Result<(), Box> { let environment = Environment::builder().build().await?; Ok(()) } ``` -------------------------------- ### Example: Using Sum with Option in Rust Source: https://docs.rs/rabbitmq-stream-client/latest/rabbitmq_stream_client/types/type.MessageResult_search= Illustrates the use of the `sum` method with an iterator of Option. The first example calculates the sum of character positions, returning Some value. The second example shows how a missing character (resulting in None) causes the sum to be None. ```rust let words = vec!["have", "a", "great", "day"]; let total: Option = words.iter().map(|w| w.find('a')).sum(); assert_eq!(total, Some(5)); let words = vec!["have", "a", "good", "day"]; let total: Option = words.iter().map(|w| w.find('a')).sum(); assert_eq!(total, None); ``` -------------------------------- ### Build RabbitMQ Stream Environment in Rust Source: https://docs.rs/rabbitmq-stream-client/latest/src/rabbitmq_stream_client/lib.rs Demonstrates how to initialize and build the Environment for connecting to a RabbitMQ Stream node. This is the primary entry point for interacting with the stream client. It requires no external dependencies beyond the library itself. ```rust use rabbitmq_stream_client::Environment; async fn build_environment() -> Result<(), Box> { let environment = Environment::builder().build().await?; // Use the environment for further operations Ok(()) } ``` -------------------------------- ### Get TypeId of ClientOptions in Rust Source: https://docs.rs/rabbitmq-stream-client/latest/rabbitmq_stream_client/struct.ClientOptions_search=std%3A%3Avec This implementation of the `Any` trait allows you to get the `TypeId` of a `ClientOptions` instance, which is useful for runtime type introspection. ```rust fn type_id(&self) -> TypeId ``` -------------------------------- ### Start Dispatching Responses in Rust Source: https://docs.rs/rabbitmq-stream-client/latest/src/rabbitmq_stream_client/client/dispatcher.rs_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Starts the response handling process by taking ownership of a stream of responses and dispatching them. This function is intended to be run asynchronously. ```rust pub async fn start(&self, stream: ChannelReceiver) where R: Stream> + Unpin + Send, R: 'static, { handle_response(self.0.clone(), stream).await } ``` -------------------------------- ### Rust Map get Method Implementation Source: https://docs.rs/rabbitmq-stream-client/latest/rabbitmq_stream_client/types/type.DeliveryAnnotations_search=std%3A%3Avec Implementation of the `get` method for the Map type. It retrieves a reference to the value associated with a given key, returning None if the key is not found. ```rust pub fn get(&self, key: K) -> Option<&Value> where K: Into, ``` -------------------------------- ### Implement `get` Method for Map in Rust Source: https://docs.rs/rabbitmq-stream-client/latest/rabbitmq_stream_client/types/type.DeliveryAnnotations Implements the `get` method for the `Map` type. This method allows retrieving a reference to a value associated with a given key from the map. ```rust pub fn get(&self, key: K) -> Option<&Value> where K: Into ``` -------------------------------- ### Build Environment using RabbitMQ Stream Client Source: https://docs.rs/rabbitmq-stream-client/latest/index Demonstrates how to build the main access point, Environment, to connect to a RabbitMQ stream node. This is the initial step for any interaction with the stream. ```rust use rabbitmq_stream_client::Environment; let environment = Environment::builder().build().await?; ``` -------------------------------- ### Client Initialization and Connection Source: https://docs.rs/rabbitmq-stream-client/latest/rabbitmq_stream_client/struct.Client_search=std%3A%3Avec Provides methods for initializing and establishing a connection to the RabbitMQ stream server. ```APIDOC ## POST /client/connect ### Description Establishes a connection to the RabbitMQ stream server. ### Method POST ### Endpoint /client/connect ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **opts** (ClientOptions) - Required - Connection options for the client. ### Request Example ```json { "opts": { /* ClientOptions object */ } } ``` ### Response #### Success Response (200) - **Client** (Client) - The established client connection object. #### Response Example ```json { "client": { /* Client object */ } } ``` ``` -------------------------------- ### TryFrom and TryInto Implementations Source: https://docs.rs/rabbitmq-stream-client/latest/rabbitmq_stream_client/struct.Consumer_search=u32+-%3E+bool Documentation for `TryFrom` and `TryInto` implementations, facilitating fallible conversions between types. ```APIDOC ### `impl TryFrom for T` **Description**: Provides a fallible conversion from type `U` into type `T`. #### Associated Types - **`Error`**: `Infallible` - The type returned in the event of a conversion error. #### Methods - **`try_from(value: U)`**: Performs the conversion. ### `impl TryInto for T` **Description**: Provides a fallible conversion from type `T` into type `U`. #### Associated Types - **`Error`**: `<U as TryFrom<T>>::Error` - The type returned in the event of a conversion error. #### Methods - **`try_into(self)`**: Performs the conversion. ``` -------------------------------- ### Start Heartbeat Task - Rust Source: https://docs.rs/rabbitmq-stream-client/latest/src/rabbitmq_stream_client/client/mod.rs_search=u32+-%3E+bool Initializes and starts a background task responsible for sending heartbeats to the server. The task's interval is derived from the negotiated heartbeat value. This function returns `None` if heartbeats are disabled (heartbeat value is 0). ```rust fn start_hearbeat_task( &self, heartbeat: u32, last_received_message: Arc>, ) -> Option { if heartbeat == 0 { return None; } let heartbeat_interval = (heartbeat / 2).max(1); let channel = self.channel.clone(); let client = self.clone(); // ... rest of the task implementation } ``` -------------------------------- ### Example: Using Product with Option in Rust Source: https://docs.rs/rabbitmq-stream-client/latest/rabbitmq_stream_client/types/type.MessageResult_search= Demonstrates how to use the `product` method on an iterator of Option. The first example successfully calculates the product of parsed numbers, while the second shows how a parsing error (resulting in None) short-circuits the product calculation. ```rust let nums = vec!["5", "10", "1", "2"]; let total: Option = nums.iter().map(|w| w.parse::().ok()).product(); assert_eq!(total, Some(100)); let nums = vec!["5", "10", "one", "2"]; let total: Option = nums.iter().map(|w| w.parse::().ok()).product(); assert_eq!(total, None); ``` -------------------------------- ### Rust: ClientOptions Auto and Blanket Implementations Source: https://docs.rs/rabbitmq-stream-client/latest/rabbitmq_stream_client/struct.ClientOptions_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Demonstrates various auto-traits and blanket implementations applied to `ClientOptions`. These include threading safety (`Send`, `Sync`, `Freeze`, `UnwindSafe`), generic conversions (`From`, `Into`, `TryFrom`, `TryInto`), ownership handling (`CloneToUninit`, `ToOwned`), and instrumentation (`Instrument`). ```rust impl Freeze for ClientOptions impl !RefUnwindSafe for ClientOptions impl Send for ClientOptions impl Sync for ClientOptions impl Unpin for ClientOptions impl !UnwindSafe for ClientOptions ``` ```rust impl Any for T where T: 'static + ?Sized fn type_id(&self) -> TypeId ``` ```rust impl Borrow for T where T: ?Sized fn borrow(&self) -> &T ``` ```rust impl BorrowMut for T where T: ?Sized fn borrow_mut(&mut self) -> &mut T ``` ```rust impl CloneToUninit for T where T: Clone unsafe fn clone_to_uninit(&self, dest: *mut u8) ``` ```rust impl From for T fn from(t: T) -> T ``` ```rust impl Instrument for T fn instrument(self, span: Span) -> Instrumented fn in_current_span(self) -> Instrumented ``` ```rust impl Into for T where U: From fn into(self) -> U ``` ```rust impl ToOwned for T where T: Clone type Owned = T fn to_owned(&self) -> T fn clone_into(&self, target: &mut T) ``` ```rust impl TryFrom for T where U: Into type Error = Infallible fn try_from(value: U) -> Result>::Error> ``` ```rust impl TryInto for T where U: TryFrom type Error = >::Error fn try_into(self) -> Result>::Error> ``` ```rust impl VZip for T where V: MultiLane fn vzip(self) -> V ``` ```rust impl WithSubscriber for T fn with_subscriber(self, subscriber: S) -> WithDispatch where S: Into fn with_current_subscriber(self) -> WithDispatch ``` ```rust impl DeserializeOwned for T where T: for<'de> Deserialize<'de> ``` -------------------------------- ### Rust: Implement get method for Map Source: https://docs.rs/rabbitmq-stream-client/latest/rabbitmq_stream_client/types/struct.Map_search=std%3A%3Avec Implements the `get` method for the `Map` struct, enabling retrieval of values associated with a given key. The key can be any type convertible into `AnnonationKey`. It returns an `Option<&Value>` containing a reference to the value if found, or `None` otherwise. ```rust pub fn get(&self, key: K) -> Option<&Value> where K: Into, ``` -------------------------------- ### Environment::from_client_option() Source: https://docs.rs/rabbitmq-stream-client/latest/rabbitmq_stream_client/struct.Environment_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Creates an `Environment` instance from client options, allowing initialization from configuration. ```APIDOC ## Environment::from_client_option() ### Description Create environment instance from client options. This allow to create an `Environment` instance from configuration. ### Method N/A ### Endpoint N/A ### Parameters * **client_options** (impl Into) - The client options to use for creating the environment. ### Request Example ```rust use rabbitmq_stream_client::Environment; use rabbitmq_stream_client::ClientOptions; #[derive(serde::Deserialize)] struct MyConfig { rabbitmq: ClientOptions } let j = r#"{ "rabbitmq": { "host": "localhost", "tls": { "enabled": false } } } "#; let my_config: MyConfig = serde_json::from_str(j).unwrap(); let env = Environment::from_client_option(my_config.rabbitmq) .await .unwrap(); ``` ### Response #### Success Response (200) - **Environment** - An instance of the Environment. #### Response Example N/A ``` -------------------------------- ### TryFrom and TryInto Conversions Source: https://docs.rs/rabbitmq-stream-client/latest/rabbitmq_stream_client/struct.Consumer Documentation for the `TryFrom` and `TryInto` trait implementations for stream conversions. ```APIDOC ## `TryFrom` for `T` ### Associated Types * `Error`: The type returned in the event of a conversion error. ### Methods * `try_from(value: U) -> Result`: Performs the conversion. ## `TryInto` for `T` ### Associated Types * `Error`: The type returned in the event of a conversion error. ### Methods * `try_into(self) -> Result`: Performs the conversion. ``` -------------------------------- ### Get Metadata Source: https://docs.rs/rabbitmq-stream-client/latest/src/rabbitmq_stream_client/client/mod.rs Retrieves metadata for a list of streams. ```APIDOC ## POST /metadata ### Description Retrieves metadata information for a specified list of streams. This can include details like stream status, size, and configuration. ### Method POST ### Endpoint /metadata ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **streams** (Vec) - Required - A list of stream names for which to retrieve metadata. ### Request Example ```json { "streams": ["stream1", "stream2", "stream3"] } ``` ### Response #### Success Response (200) - **response** (HashMap) - A map where keys are stream names and values are their corresponding metadata. #### Response Example ```json { "stream1": {"status": "active", "size": 10240}, "stream2": {"status": "inactive", "size": 0} } ``` ``` -------------------------------- ### Build RabbitMQ Stream Environment Source: https://docs.rs/rabbitmq-stream-client/latest/src/rabbitmq_stream_client/lib.rs_search= Demonstrates how to build the initial environment to connect to a RabbitMQ stream node. This is the primary access point for interacting with the stream client. ```rust use rabbitmq_stream_client::Environment; async fn build_environment() -> Result<(), Box> { let environment = Environment::builder().build().await?; // Further operations can be performed using this environment Ok(()) } ``` -------------------------------- ### ClientOptions Blanket Implementations (Rust) Source: https://docs.rs/rabbitmq-stream-client/latest/rabbitmq_stream_client/struct.ClientOptions Lists blanket implementations for `ClientOptions` such as `Any`, `Borrow`, `BorrowMut`, `CloneToUninit`, `From`, `Instrument`, `Into`, `ToOwned`, `TryFrom`, `TryInto`, `VZip`, and `WithSubscriber`. ```rust impl Any for T impl Borrow for T impl BorrowMut for T impl CloneToUninit for T impl From for T impl Instrument for T impl Into for T impl ToOwned for T impl TryFrom for T impl TryInto for T impl VZip for T impl WithSubscriber for T ``` -------------------------------- ### Publishing Messages Source: https://docs.rs/rabbitmq-stream-client/latest/rabbitmq_stream_client/index_search=u32+-%3E+bool Provides an example of how to create a producer and send messages to a specified stream. ```APIDOC ## Publishing Messages ### Description This section illustrates how to create a `Producer` to send messages to a RabbitMQ stream and confirms their delivery. ### Method `Environment::producer().build("your_stream_name").await` followed by `producer.send_with_confirm(Message)`. ### Endpoint N/A (Interaction with a specific stream on the connected node) ### Parameters #### Path Parameters - **stream_name** (string) - Required - The name of the stream to publish messages to. #### Query Parameters None #### Request Body - **Message** (`rabbitmq_stream_client::types::Message`) - Required - The message object to be sent. Can be built using `Message::builder()`. - **body** (string or bytes) - The content of the message. ### Request Example ```rust use rabbitmq_stream_client::{Environment, types::Message}; let environment = Environment::builder().build().await?; let producer = environment.producer().build("mystream").await?; for i in 0..10 { producer .send_with_confirm(Message::builder().body(format!("message fonbet{}", i)).build()) .await?; } producer.close().await?; ``` ### Response #### Success Response (200) - **ConfirmationStatus** (`rabbitmq_stream_client::types::ConfirmationStatus`) - Indicates the status of the message confirmation. #### Response Example ```json { "status": "Confirmed" } ``` ### Further Options For more producer options, refer to `ProducerBuilder`. ``` -------------------------------- ### Rust: Start Dispatcher Task to Handle Responses Source: https://docs.rs/rabbitmq-stream-client/latest/src/rabbitmq_stream_client/client/dispatcher.rs The `start` method initializes and runs the `handle_response` task. This asynchronous function continuously listens for incoming `Response` objects from the provided `ChannelReceiver`. It processes each response, dispatching it based on its correlation ID or notifying the handler if it's a general message. Error handling and dispatcher closure logic are noted as TODOs. ```Rust use futures::Stream; use rabbitmq_stream_protocol::Response; use tokio::spawn; use crate::error::ClientError; // Assuming ChannelReceiver struct and DispatcherState are defined elsewhere // pub(crate) struct ChannelReceiver { ... } // pub(crate) struct DispatcherState { ... } // pub trait MessageHandler { ... } impl where T: MessageHandler, { pub async fn start(&self, stream: ChannelReceiver) where R: Stream> + Unpin + Send, R: 'static, { handle_response(self.0.clone(), stream).await } } async fn handle_response(state: DispatcherState, mut stream: ChannelReceiver) where H: MessageHandler, T: Stream> + Unpin + Send, T: 'static, { tokio::spawn(async move { // TODO implements Error handling and close of dispatcher trace!("Dispatcher task: listening for messages"); while let Some(result) = stream.next().await { match result { Ok(item) => match item.correlation_id() { // ... further processing based on item and correlation_id }, Err(e) => { // Handle stream error } } } }); } ``` -------------------------------- ### Get Super Stream Partitions Source: https://docs.rs/rabbitmq-stream-client/latest/src/rabbitmq_stream_client/client/mod.rs Retrieves the partition information for a given super stream. ```APIDOC ## POST /partitions ### Description Retrieves a list of partitions associated with a specific super stream. This is useful for understanding the distribution of data within a super stream. ### Method POST ### Endpoint /partitions ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **super_stream** (String) - Required - The name of the super stream to query. ### Request Example ```json { "super_stream": "my_super_stream" } ``` ### Response #### Success Response (200) - **response** (SuperStreamPartitionsResponse) - Contains details about the partitions of the super stream. #### Response Example ```json { "partitions": ["partition1", "partition2"] } ``` ``` -------------------------------- ### Rust: Initialize and Configure EnvironmentBuilder Source: https://docs.rs/rabbitmq-stream-client/latest/rabbitmq_stream_client/struct.EnvironmentBuilder Demonstrates how to create and configure an EnvironmentBuilder for a RabbitMQ stream client. It shows setting various connection parameters like host, username, password, port, TLS, and heartbeat. The builder pattern is used for a fluent API. ```rust use rabbitmq_stream_client::EnvironmentBuilder; use rabbitmq_stream_client::types::TlsConfiguration; // Example usage of EnvironmentBuilder #[tokio::main] async fn main() { let tls_config = TlsConfiguration::new(); // Replace with actual TLS config if needed let environment = EnvironmentBuilder::new() .host("localhost") .port(5672) .username("guest") .password("guest") .virtual_host("/") .tls(tls_config) .heartbeat(30) .load_balancer_mode(false) .client_provided_name("my-stream-client") .build() .await; match environment { Ok(env) => { println!("Successfully built environment: {:?}", env); } Err(e) => { eprintln!("Failed to build environment: {}", e); } } } ``` -------------------------------- ### Build Client Options Source: https://docs.rs/rabbitmq-stream-client/latest/src/rabbitmq_stream_client/client/options.rs_search=std%3A%3Avec Illustrates constructing `ClientOptions` using a builder pattern. This includes setting host, port, user credentials, virtual host, heartbeat interval, max frame size, TLS configuration, metrics collector, and load balancer mode. Assertions verify that the built options match the configured values. ```rust let options = ClientOptions::builder() .host("test") .port(8888) .user("test_user") .password("test_pass") .v_host("/test_vhost") .heartbeat(10000) .max_frame_size(1) .tls(TlsConfiguration::builder().enable(true).build().unwrap()) .collector(Arc::new(NopMetricsCollector {})) .load_balancer_mode(true) .build(); assert_eq!(options.host, "test"); assert_eq!(options.port, 8888); assert_eq!(options.user, "test_user"); assert_eq!(options.password, "test_pass"); assert_eq!(options.v_host, "/test_vhost"); assert_eq!(options.heartbeat, 10000); assert_eq!(options.max_frame_size, 1); assert!(matches!(options.tls, TlsConfiguration::Untrusted)); assert!(options.load_balancer_mode); ``` -------------------------------- ### CloneToUninit for ClientOptions in Rust (Nightly) Source: https://docs.rs/rabbitmq-stream-client/latest/rabbitmq_stream_client/struct.ClientOptions_search=std%3A%3Avec This is a nightly-only experimental API that allows cloning `ClientOptions` directly into uninitialized memory. Use with caution as it requires unsafe operations. ```rust unsafe fn clone_to_uninit(&self, dest: *mut u8) ``` -------------------------------- ### Get Metadata for Streams Source: https://docs.rs/rabbitmq-stream-client/latest/src/rabbitmq_stream_client/client/mod.rs_search=std%3A%3Avec Retrieves metadata for one or more streams, such as their status, configuration, and other relevant information. ```APIDOC ## POST /metadata ### Description Retrieves metadata for a list of streams. ### Method POST ### Endpoint /metadata ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **streams** (array of strings) - Required - A list of stream names for which to retrieve metadata. ### Request Example ```json { "streams": ["stream1", "stream2"] } ``` ### Response #### Success Response (200) - **metadata** (HashMap) - A map where keys are stream names and values are their metadata. - **status** (string) - Indicates the success status of the operation. #### Response Example ```json { "metadata": { "stream1": {"name": "stream1", "...other_metadata..."} }, "status": "ok" } ``` ``` -------------------------------- ### Get Option Value or Default in Rust Source: https://docs.rs/rabbitmq-stream-client/latest/rabbitmq_stream_client/types/type.MessageResult_search= Returns the contained Some value or a provided default. Arguments are eagerly evaluated. ```rust pub fn unwrap_or(self, default: T) -> T Returns the contained `Some` value or a provided default. Arguments passed to `unwrap_or` are eagerly evaluated; if you are passing the result of a function call, it is recommended to use `unwrap_or_else`, which is lazily evaluated. ##### §Examples ``` assert_eq!(Some("car").unwrap_or("bike"), "car"); assert_eq!(None.unwrap_or("bike"), "bike"); ``` ``` -------------------------------- ### TryFrom and TryInto Implementations Source: https://docs.rs/rabbitmq-stream-client/latest/rabbitmq_stream_client/types/struct.SuperStreamConsumer_search=std%3A%3Avec Implementations for `TryFrom` and `TryInto` traits, enabling fallible conversions. ```APIDOC ## TryFrom and TryInto Implementations ### Description Implementations for `TryFrom` and `TryInto` traits, enabling fallible conversions. ### `impl TryFrom for T` #### Type `Error` - **Description**: The type returned in the event of a conversion error. - **Type**: `Infallible` #### `fn try_from(value: U)` - **Description**: Performs the conversion. - **Parameters**: `value` (U): The value to convert. - **Returns**: `Result>::Error>` ### `impl TryInto for T` #### Type `Error` - **Description**: The type returned in the event of a conversion error. - **Type**: `>::Error` #### `fn try_into(self)` - **Description**: Performs the conversion. - **Returns**: `Result>::Error>` ``` -------------------------------- ### Consume and Get Response Kind in Rust Source: https://docs.rs/rabbitmq-stream-client/latest/rabbitmq_stream_client/types/struct.Response Consumes the `Response` object and returns its `ResponseKind`. This method takes ownership of the `Response`. ```Rust pub fn kind(self) -> ResponseKind ``` -------------------------------- ### Get Option Value or Compute Default in Rust Source: https://docs.rs/rabbitmq-stream-client/latest/rabbitmq_stream_client/types/type.MessageResult_search= Returns the contained Some value or computes it from a closure. The closure is lazily evaluated. ```rust pub fn unwrap_or_else(self, f: F) -> T where F: FnOnce() -> T, Returns the contained `Some` value or computes it from a closure. ##### §Examples ``` let k = 10; assert_eq!(Some(4).unwrap_or_else(|| 2 * k), 4); assert_eq!(None.unwrap_or_else(|| 2 * k), 20); ``` ``` -------------------------------- ### Create and Configure RabbitMQ Stream Producer in Rust Source: https://docs.rs/rabbitmq-stream-client/latest/src/rabbitmq_stream_client/producer.rs This code demonstrates the creation of a RabbitMQ stream producer. It involves setting up handlers, declaring a publisher, and determining the initial publish sequence. The producer is configured with various options like batch size, name, and filter extractors. Dependencies include the `rabbitmq-stream` client library and Tokio for asynchronous operations. It returns a `Result` containing either a configured `Producer` or a `ProducerCreateError`. ```rust pub async fn create(self) -> Result> { // ... (producer creation logic) if response.is_ok() { let (sender, receiver) = mpsc::channel(self.batch_size); let client = Arc::new(client); let producer = ProducerInternal { producer_id, stream: stream.to_string(), client, publish_sequence, waiting_confirmations, closed: Arc::new(AtomicBool::new(false)), sender, filter_value_extractor: self.filter_value_extractor, on_closed, }; let internal_producer = Arc::new(producer); schedule_batch_send( self.batch_size, receiver, internal_producer.client.clone(), producer_id, publish_version, ); let producer = Producer(internal_producer, PhantomData); Ok(producer) } else { Err(ProducerCreateError::Create { stream: stream.to_owned(), status: response.code().clone(), }) } } pub fn on_closed(mut self, on_closed: Box) -> ProducerBuilder { self.on_closed = Some(on_closed); self } pub fn batch_size(mut self, batch_size: usize) -> Self { self.batch_size = batch_size; self } /// Don't use this in production, it is only for testing purposes. pub fn overwrite_heartbeat(mut self, heartbeat: u32) -> ProducerBuilder { self.overwrite_heartbeat = Some(heartbeat); self } pub fn client_provided_name(mut self, name: &str) -> Self { self.client_provided_name = String::from(name); self } pub fn name(mut self, name: &str) -> ProducerBuilder { self.name = Some(name.to_owned()); ProducerBuilder { environment: self.environment, name: self.name, batch_size: self.batch_size, data: PhantomData, filter_value_extractor: None, client_provided_name: String::from("rust-stream-producer"), on_closed: self.on_closed, overwrite_heartbeat: None, } } pub fn filter_value_extractor( mut self, filter_value_extractor: impl Fn(&Message) -> String + Send + Sync + 'static, ) -> Self { let f = Arc::new(filter_value_extractor); self.filter_value_extractor = Some(f); self } pub fn filter_value_extractor_arc( mut self, filter_value_extractor: Option, ) -> Self { self.filter_value_extractor = filter_value_extractor; self } ``` -------------------------------- ### Result Termination Source: https://docs.rs/rabbitmq-stream-client/latest/rabbitmq_stream_client/type.RabbitMQStreamResult_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Provides the `report` method for Result types, which is used to get the representation of the value as a status code. ```APIDOC ## `report(self) -> ExitCode` ### Description Is called to get the representation of the value as status code. This status code is returned to the operating system. ### Method `report` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```rust // let exit_code = my_result.report(); ``` ### Response #### Success Response (200) Returns an `ExitCode` representing the status. #### Response Example ```json { "example": "ExitCode::SUCCESS" } ``` ``` -------------------------------- ### ClientOptions Configuration Source: https://docs.rs/rabbitmq-stream-client/latest/rabbitmq_stream_client/struct.ClientOptions_search= This section details the methods available for configuring ClientOptions, which are used to establish connections to RabbitMQ streams. ```APIDOC ## Struct ClientOptions ### Description Represents the configuration options for a RabbitMQ stream client connection. ### Methods #### `builder()` - **Returns**: `ClientOptionsBuilder` - **Description**: Returns a builder for creating new `ClientOptions` instances. #### `set_port(port: u16)` - **Parameters**: - `port` (u16) - Required - The port number for the RabbitMQ stream server. - **Description**: Sets the port number for the client connection. #### `set_client_provided_name(name: &str)` - **Parameters**: - `name` (str) - Required - The name to be provided by the client. - **Description**: Sets a client-provided name for identification purposes. ``` -------------------------------- ### ClientOptions Implementations Source: https://docs.rs/rabbitmq-stream-client/latest/rabbitmq_stream_client/struct.ClientOptions_search= Details on traits implemented for ClientOptions, including Clone, Debug, Default, and Deserialize. ```APIDOC ## Implementations for ClientOptions ### `impl Clone for ClientOptions` #### `clone(&self) -> ClientOptions` - **Description**: Returns a duplicate of the `ClientOptions` value. #### `clone_from(&mut self, source: &Self)` - **Description**: Performs copy-assignment from a source `ClientOptions` value. ### `impl Debug for ClientOptions` #### `fmt(&self, f: &mut Formatter<'_>) -> Result` - **Description**: Formats the `ClientOptions` value using the given formatter. ### `impl Default for ClientOptions` #### `default() -> Self` - **Description**: Returns the default `ClientOptions` value. ### `impl<'de> Deserialize<'de> for ClientOptions` #### `deserialize<__D>(__deserializer: __D) -> Result` - **Description**: Deserializes `ClientOptions` from a Serde deserializer. ```