### Spawn Method Documentation Example Source: https://docs.rs/kameo/latest/kameo/actor/trait Provides an example of using the `spawn` method for creating an actor. This method is used to spawn an actor in a Tokio task with a default bounded mailbox (capacity 64) and is the most common way to start an actor asynchronously. ```rust use kameo::Actor; use kameo::actor::Spawn; #[derive(Actor)] struct MyActor; // Spawns with a default bounded mailbox (capacity 64) let actor_ref = MyActor::spawn(MyActor); ``` -------------------------------- ### Sender Send Method Example (Tokio) Source: https://docs.rs/kameo/latest/kameo/reply/type Demonstrates how to use the send method of a oneshot channel, which attempts to send a value. It consumes self and returns an error if the receiver has already been dropped. This example is suitable for both synchronous and asynchronous code. ```rust use tokio::sync::oneshot; let (tx, rx) = oneshot::channel(); tokio::spawn(async move { if let Err(_) = tx.send(3) { println!("the receiver dropped"); } }); match rx.await { Ok(v) => println!("got = {:?}", v), Err(_) => println!("the sender dropped"), } ``` -------------------------------- ### Basic Actor Spawning with kameo Source: https://docs.rs/kameo/latest/kameo/actor/trait Demonstrates how to spawn an actor using the `spawn` method. This is the standard way to start an actor with explicit initialization arguments. The actor is run in a Tokio task with a default bounded mailbox. ```rust use kameo::Actor; use kameo::actor::Spawn; #[derive(Actor)] struct Counter { count: i32, } // Spawn with explicit initialization let actor_ref = Counter::spawn(Counter { count: 0 }); ``` -------------------------------- ### Rust: Register an Actor for Distributed Communication with Kameo Source: https://docs.rs/kameo/latest/kameo/index This example demonstrates how to spawn an actor and then register it using a name, making it discoverable for remote communication within a distributed Kameo system. The `register` method is used for this purpose. ```rust // Spawn and register the actor let actor_ref = MyActor::spawn(MyActor::default()); actor_ref.register("my_actor").await?; ``` -------------------------------- ### Bootstrap Distributed Actor System with Kameo (Rust) Source: https://docs.rs/kameo/latest/kameo/remote/index Demonstrates a one-line setup to bootstrap a distributed actor system using Kameo's `remote::bootstrap()` function. This is ideal for quick prototyping and development environments. It returns a `PeerId` upon successful bootstrapping. ```rust use kameo::remote; #[tokio::main] async fn main() -> Result<(), Box> { // One line to bootstrap a distributed actor system let peer_id = remote::bootstrap()?; // Now use actors normally // actor_ref.register("my_actor").await?; Ok(()) } ``` -------------------------------- ### Example Usage of LookupStream in Rust Source: https://docs.rs/kameo/latest/kameo/remote/struct Demonstrates how to use LookupStream to find all instances of a specific actor ('my-service') and process each discovered actor reference. It utilizes `try_next().await` to asynchronously retrieve actor references. ```rust let mut stream = RemoteActorRef::::lookup_all("my-service"); while let Some(actor_ref) = stream.try_next().await? { // Handle each discovered actor } ``` -------------------------------- ### Rust: Define and Implement a Basic Actor with Kameo Source: https://docs.rs/kameo/latest/kameo/index This example demonstrates how to define a simple actor named 'Counter' using Kameo's derive macro and Message trait. It includes defining the actor's state and implementing a handler for an 'Inc' message, which increments a counter and returns the new count. ```rust use kameo::Actor; use kameo::actor::Spawn; use kameo::message::{Context, Message}; // Implement the actor #[derive(Actor)] struct Counter { count: i64, } // Define message struct Inc { amount: i64 } // Implement message handler impl Message for Counter { type Reply = i64; async fn handle(&mut self, msg: Inc, _ctx: &mut Context) -> Self::Reply { self.count += msg.amount; self.count } } ``` -------------------------------- ### Sender Closed Method Example (Tokio) Source: https://docs.rs/kameo/latest/kameo/reply/type Shows how to use the closed async method to wait for the associated Receiver handle to close. This is useful for aborting computations when the receiver is no longer interested in the result, often used with select!. ```rust use tokio::sync::oneshot; let (mut tx, rx) = oneshot::channel::<()>(); tokio::spawn(async move { drop(rx); }); tx.closed().await; println!("the receiver dropped"); ``` -------------------------------- ### Sender poll_closed Method Example (Tokio) Source: https://docs.rs/kameo/latest/kameo/reply/type Shows the usage of the poll_closed method, which checks if the oneshot channel is closed and schedules a wakeup if it's not. This is an advanced, lower-level API for checking channel status. ```rust use tokio::sync::oneshot; use std::future::poll_fn; let (mut tx, mut rx) = oneshot::channel::<()>(); tokio::spawn(async move { rx.close(); }); poll_fn(|cx| tx.poll_closed(cx)).await; println!("the receiver dropped"); ``` -------------------------------- ### Sender Closed Method with Select! Example (Tokio) Source: https://docs.rs/kameo/latest/kameo/reply/type Illustrates using the closed method within a tokio::select! macro to handle cases where the receiver might drop while a computation is in progress. This prevents sending data if the receiver is gone. ```rust use tokio::sync::oneshot; use tokio::time::{self, Duration}; async fn compute() -> String { // Complex computation returning a `String` } let (mut tx, rx) = oneshot::channel(); tokio::spawn(async move { tokio::select! { _ = tx.closed() => { // The receiver dropped, no need to do any further work } value = compute() => { // The send can fail if the channel was closed at the exact same // time as when compute() finished, so just ignore the failure. let _ = tx.send(value); } } }); // Wait for up to 10 seconds let _ = time::timeout(Duration::from_secs(10), rx).await; ``` -------------------------------- ### Sender is_closed Method Example (Tokio) Source: https://docs.rs/kameo/latest/kameo/reply/type Demonstrates the is_closed method, which returns true if the associated Receiver handle has been dropped. Calling send after is_closed returns true will always result in an error. ```rust use tokio::sync::oneshot; let (tx, rx) = oneshot::channel(); assert!(!tx.is_closed()); drop(rx); assert!(tx.is_closed()); assert!(tx.send("never received").is_err()); ``` -------------------------------- ### Attempt to Get Next Item from TryStream in Rust Source: https://docs.rs/kameo/latest/kameo/remote/struct The `try_next` method on `TryStream` returns a `Future` that attempts to resolve the next item. If the stream yields an `Ok` value, it's returned. If an `Err` is encountered, that error is returned immediately. This is a convenient way to process one item at a time from a `TryStream`. ```rust fn try_next(&mut self) -> TryNext<'_, Self> where Self: Unpin, ``` -------------------------------- ### Get Owned Type Source: https://docs.rs/kameo/latest/kameo/error/enum Defines the `Owned` type associated with a type `T`, which is typically `T` itself when `T` is `Clone`. This is part of the `ToOwned` trait. ```rust type Owned = T ``` -------------------------------- ### Import Kameo Prelude in Rust Source: https://docs.rs/kameo/latest/kameo/prelude/index This snippet shows how to import commonly used types and functions from the kameo crate using a single 'use' statement. It's essential for setting up actor systems and utilizing core features. Dependencies include the kameo crate itself. ```Rust use kameo::prelude::* ``` -------------------------------- ### Rust Blanket Implementation: Any for T Source: https://docs.rs/kameo/latest/kameo/actor/struct This blanket implementation allows any type T that is 'static and ?Sized to be treated as a type that implements the Any trait. It provides the type_id method to get the TypeId of the instance. ```Rust impl Any for T where T: 'static + ?Sized, fn type_id(&self) -> TypeId ``` -------------------------------- ### Rust: Config Builder Methods Source: https://docs.rs/kameo/latest/kameo/remote/messaging/struct Provides methods for configuring the Config struct. These methods follow a builder pattern, allowing chaining to set request timeouts, maximum concurrent streams, and maximum request/response sizes. ```rust pub fn with_request_timeout(self, v: Duration) -> Self Sets the timeout for inbound and outbound requests. ``` ```rust pub fn with_max_concurrent_streams(self, num_streams: usize) -> Self Sets the upper bound for the number of concurrent inbound + outbound streams. ``` ```rust pub fn with_request_size_maximum(self, bytes: u64) -> Self Sets the limit for request size in bytes. ``` ```rust pub fn with_response_size_maximum(self, bytes: u64) -> Self Sets the limit for response size in bytes. ``` -------------------------------- ### Rust: Config From for Codec Source: https://docs.rs/kameo/latest/kameo/remote/messaging/struct Implements the From trait to convert a Config instance into a Codec. This allows for seamless integration of Config into systems that expect a Codec type. ```rust fn from(config: Config) -> Self Converts to this type from the input type. ``` -------------------------------- ### Behaviour Constructor and Registration Methods Source: https://docs.rs/kameo/latest/kameo/remote/registry/struct Provides methods for initializing a Behaviour instance and managing actor registrations. The `new` function creates a new registry behaviour, while `register` adds an actor to the distributed registry. `cancel_registration` allows for stopping ongoing registration processes. ```rust pub fn new(local_peer_id: PeerId) -> Self pub fn register( &mut self, name: impl Into>, registration: ActorRegistration<'static>, ) -> Result pub fn cancel_registration(&mut self, query_id: &QueryId) -> bool ``` -------------------------------- ### Rust: Spawn and Interact with a Kameo Actor Source: https://docs.rs/kameo/latest/kameo/index This code snippet shows how to spawn a Kameo actor (previously defined) and send messages to it. It uses the `ask` method to send an 'Inc' message and await a reply, then asserts the expected result. ```rust // Spawn the actor and obtain its reference let actor_ref = Counter::spawn(Counter { count: 0 }); // Send messages to the actor let count = actor_ref.ask(Inc { amount: 42 }).await?; assert_eq!(count, 42); ``` -------------------------------- ### Rust Type Conversion Implementations (From, Into, TryFrom, TryInto) Source: https://docs.rs/kameo/latest/kameo/remote/registry/struct Provides flexible type conversion mechanisms using `From`, `Into`, `TryFrom`, and `TryInto` traits. These traits facilitate seamless conversions between compatible types, with `TryFrom` and `TryInto` supporting fallible conversions. ```rust impl From for T fn from(t: T) -> T ``` ```rust impl Into for T where U: From, fn into(self) -> U ``` ```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 ``` -------------------------------- ### Prepare Actor for Spawning (Rust) Source: https://docs.rs/kameo/latest/kameo/actor/trait Creates a prepared actor, providing access to its ActorRef before the actual spawning. This allows for configuring relationships or states before the actor is fully operational. It returns a PreparedActor instance. ```rust use kameo::Actor; use kameo::actor::Spawn; #[derive(Actor)] struct MyActor; let other_actor = MyActor::spawn(MyActor); let prepared_actor = MyActor::prepare(); prepared_actor.actor_ref().link(&other_actor).await; let actor_ref = prepared_actor.spawn(MyActor); ``` -------------------------------- ### Poll Next Item from Unpin Stream in Rust Source: https://docs.rs/kameo/latest/kameo/remote/struct The `poll_next_unpin` method is a convenience function for polling the next item from a stream that implements `Unpin`. It simplifies the process of getting the next value from such streams without needing explicit pinning. ```rust fn poll_next_unpin(&mut self, cx: &mut Context<'_>) -> Poll> where Self: Unpin, ``` -------------------------------- ### Chain Two Streams (Rust) Source: https://docs.rs/kameo/latest/kameo/remote/struct Appends one stream to another, creating a single stream that yields all items from the first stream, followed by all items from the second stream. The second stream only starts producing items after the first one is exhausted. ```Rust fn chain(self, other: St) -> Chain where St: Stream, Self: Sized, ``` -------------------------------- ### Get Owned Type from Borrowed (Rust) Source: https://docs.rs/kameo/latest/kameo/mailbox/struct Implements `ToOwned` trait, providing `Owned` type alias and `to_owned` method for creating an owned version from a borrowed reference, typically via cloning. `clone_into` replaces existing owned data with a clone of the borrowed data. Requires `Clone` trait. ```Rust type Owned = T ``` ```Rust fn to_owned(&self) -> T ``` ```Rust fn clone_into(&self, target: &mut T) ``` -------------------------------- ### Custom Libp2p Swarm with Kameo Behaviour (Rust) Source: https://docs.rs/kameo/latest/kameo/remote/index Illustrates how to integrate Kameo's `remote::Behaviour` into a custom libp2p swarm for production deployments. This allows for full control over transports, discovery, and protocol composition. It requires defining a custom `NetworkBehaviour` struct that includes the Kameo behaviour. ```rust use kameo::remote; use libp2p::swarm::NetworkBehaviour; #[derive(NetworkBehaviour)] struct MyBehaviour { kameo: remote::Behaviour, // Add other libp2p behaviors as needed } // Create custom libp2p swarm with full control over // transports, discovery, and protocol composition ``` -------------------------------- ### Rust: Context reply for early responses Source: https://docs.rs/kameo/latest/kameo/message/struct Demonstrates the `reply` method of the Context struct, which serves as a shorthand for sending a reply to the caller immediately. It returns a `DelegatedReply` and is useful when direct access to the `ReplySender` is not needed. ```rust pub fn reply(&mut self, reply: R::Value) -> DelegatedReply ``` -------------------------------- ### WeakMailboxSender Struct API Source: https://docs.rs/kameo/latest/kameo/mailbox/struct Documentation for the WeakMailboxSender struct and its associated methods. ```APIDOC ## Struct WeakMailboxSender ### Description A mailbox sender that does not prevent the channel from being closed. This is similar to `tokio`'s `mpsc::WeakSender` and `mpsc::WeakUnboundedSender`. ### Methods #### `upgrade(&self) -> Option>` * **Description**: Tries to convert a `WeakMailboxSender` into a `MailboxSender`. Returns `Some` if there are other `MailboxSender` instances alive and the channel hasn't been dropped, otherwise returns `None`. * **See also**: `tokio`'s `mpsc::WeakSender::upgrade` and `mpsc::WeakUnboundedSender::upgrade`. #### `strong_count(&self) -> usize` * **Description**: Returns the number of `MailboxSender` handles. * **See also**: `tokio`'s `mpsc::WeakSender::strong_count` and `mpsc::WeakUnboundedSender::strong_count`. #### `weak_count(&self) -> usize` * **Description**: Returns the number of `WeakMailboxSender` handles. * **See also**: `tokio`'s `mpsc::WeakSender::weak_count` and `mpsc::WeakUnboundedSender::weak_count`. ### Trait Implementations #### `Clone` for `WeakMailboxSender` * **`clone(&self) -> Self`**: Returns a duplicate of the value. * **`clone_from(&mut self, source: &Self)`**: Performs copy-assignment from `source`. #### `Debug` for `WeakMailboxSender` * **`fmt(&self, f: &mut Formatter<'_>) -> Result`**: Formats the value using the given formatter. ``` -------------------------------- ### Rust StreamMessage Enum Definition Source: https://docs.rs/kameo/latest/kameo/message/enum Defines the `StreamMessage` enum, a generic type for handling stream data attached to an actor. It has three variants: `Next` for stream items, `Started` for stream initiation, and `Finished` for stream completion. This enum is typically used with `ActorRef::attach_stream`. ```rust pub enum StreamMessage { Next(T), Started(S), Finished(F), } ``` -------------------------------- ### Reply Trait Implementation for ReplySender - Rust Source: https://docs.rs/kameo/latest/kameo/reply/struct Demonstrates the implementation of the Reply trait for ReplySender. This allows ReplySender itself to be treated as a reply in certain contexts, defining its associated types like Ok, Error, and Value. ```rust impl Reply for ReplySender Source ``` -------------------------------- ### Methods for WeakReplyRecipient (Rust) Source: https://docs.rs/kameo/latest/kameo/actor/struct Provides core functionalities for `WeakReplyRecipient`. These include retrieving the associated `ActorId`, attempting to convert the weak reference into a strong `ReplyRecipient` (which succeeds only if other strong references exist), and querying the number of strong and weak references. ```rust pub fn id(&self) -> ActorId pub fn upgrade(&self) -> Option> pub fn strong_count(&self) -> usize pub fn weak_count(&self) -> usize ``` -------------------------------- ### CloneToUninit Trait (Rust) Source: https://docs.rs/kameo/latest/kameo/error/enum Presents the `CloneToUninit` trait implementation. This is an experimental, nightly-only API for efficiently cloning data into uninitialized memory, useful for performance-critical operations. ```rust unsafe fn clone_to_uninit(&self, dest: *mut u8) ``` -------------------------------- ### Instrumentation and Subscriber Traits Source: https://docs.rs/kameo/latest/kameo/request/struct Documentation for traits related to instrumenting code with spans and managing subscribers. ```APIDOC ## `Instrument` Trait ### Description Instruments a type with a provided `Span` or the current `Span`. ### Method `fn instrument(self, span: Span) -> Instrumented` `fn in_current_span(self) -> Instrumented` ### Endpoint N/A (Trait implementation) ### Parameters - `span` (Span): The span to instrument with. ### Request Example N/A ### Response #### Success Response - `Instrumented`: A wrapper type that includes the span information. #### Response Example N/A ## `WithSubscriber` Trait ### Description Attaches a `Subscriber` to a type, enabling tracing and diagnostics. ### Method `fn with_subscriber(self, subscriber: S) -> WithDispatch` where S: Into `fn with_current_subscriber(self) -> WithDispatch` ### Endpoint N/A (Trait implementation) ### Parameters - `subscriber` (S): The subscriber to attach (must be convertible into `Dispatch`). ### Request Example N/A ### Response #### Success Response - `WithDispatch`: A wrapper type that includes the attached subscriber. #### Response Example N/A ``` -------------------------------- ### VZip Implementation Source: https://docs.rs/kameo/latest/kameo/error/struct Provides a `vzip` method for types `T` that are compatible with a `MultiLane` context, returning a `V` type. This is likely related to zipped iteration or vectorization. ```Rust impl VZip for T where V: MultiLane, Source§ #### fn vzip(self) -> V ``` -------------------------------- ### Rust: Config Blanket Implementations Source: https://docs.rs/kameo/latest/kameo/remote/messaging/struct Details blanket implementations for the Config struct, providing generic functionality through traits like Any, AsTaggedExplicit, AsTaggedImplicit, Borrow, BorrowMut, CloneToUninit, Downcast, DynClone, DynMessage. ```rust impl Any for T where T: 'static + ?Sized, ``` ```rust impl<'a, T, E> AsTaggedExplicit<'a, E> for T where T: 'a, ``` ```rust impl<'a, T, E> AsTaggedImplicit<'a, E> for T where T: 'a, ``` ```rust impl Borrow for T where T: ?Sized, ``` ```rust impl BorrowMut for T where T: ?Sized, ``` ```rust impl CloneToUninit for T where T: Clone, ``` ```rust impl Downcast for T where T: Any, ``` ```rust impl DowncastSend for T where T: Any + Send, ``` ```rust impl DowncastSync for T where T: Any + Send + Sync, ``` ```rust impl DynClone for T where T: Clone, ``` ```rust impl DynMessage for T where A: Actor + Message, T: Send + 'static, ``` -------------------------------- ### Type Casting and Conversion Traits Source: https://docs.rs/kameo/latest/kameo/request/struct Documentation for traits related to type casting, conversion, and ownership. ```APIDOC ## `as_any` Trait Method ### Description Casts the type to a `Box`. ### Method `fn` ### Endpoint N/A (Method on `Box`) ### Parameters N/A ### Request Example N/A ### Response #### Success Response - `Box`: A boxed trait object representing any type. #### Response Example N/A ## `From` Trait ### Description Provides a way to convert one type into another. ### Method `fn from(t: T) -> T` ### Endpoint N/A (Trait implementation) ### Parameters - `t` (T): The value to convert. ### Request Example N/A ### Response #### Success Response - `T`: The converted value. #### Response Example N/A ## `Into` Trait ### Description Provides a way to convert a type into another type, where the target type implements `From`. ### Method `fn into(self) -> U` ### Endpoint N/A (Trait implementation) ### Parameters - `self` (T): The value to convert. ### Request Example N/A ### Response #### Success Response - `U`: The converted value. #### Response Example N/A ## `IntoEither` Trait ### Description Converts a value into either the left or right variant of an `Either` enum. ### Method `fn into_either(self, into_left: bool) -> Either` `fn into_either_with(self, into_left: F) -> Either` where F: FnOnce(&Self) -> bool ### Endpoint N/A (Trait implementation) ### Parameters - `into_left` (bool): If true, converts to `Left`; otherwise, converts to `Right`. - `into_left` (FnOnce(&Self) -> bool): A closure that determines whether to convert to `Left`. ### Request Example N/A ### Response #### Success Response - `Either`: The value wrapped in either `Left` or `Right`. #### Response Example N/A ## `Same` Trait ### Description Indicates that a type is the same as its output type. ### Type Alias `type Output = T` ### Endpoint N/A (Trait definition) ### Parameters N/A ### Request Example N/A ### Response N/A #### Response Example N/A ## `ToOwned` Trait ### Description Provides a way to create an owned version of a borrowed type, typically by cloning. ### Type Alias `type Owned = T` ### Method `fn to_owned(&self) -> T` `fn clone_into(&self, target: &mut T)` ### Endpoint N/A (Trait implementation) ### Parameters - `self` (&T): The borrowed value to create an owned version from. - `target` (&mut T): The mutable reference to an owned value to be updated. ### Request Example N/A ### Response #### Success Response - `T`: The owned value. #### Response Example N/A ## `TryFrom` Trait ### Description Provides a fallible way to convert one type into another. ### Type Alias `type Error = Infallible` ### Method `fn try_from(value: U) -> Result>::Error>` ### Endpoint N/A (Trait implementation) ### Parameters - `value` (U): The value to attempt conversion. ### Request Example N/A ### Response #### Success Response - `Result`: Ok containing the converted value on success, or Err on failure. #### Response Example N/A ## `TryInto` Trait ### Description Provides a fallible way to convert a type into another type, where the target type implements `TryFrom`. ### Type Alias `type Error = >::Error` ### Method `fn try_into(self) -> Result>::Error>` ### Endpoint N/A (Trait implementation) ### Parameters - `self` (T): The value to attempt conversion. ### Request Example N/A ### Response #### Success Response - `Result`: Ok containing the converted value on success, or Err on failure. #### Response Example N/A ## `VZip` Trait ### Description Zips a value with a multi-lane structure. ### Method `fn vzip(self) -> V` ### Endpoint N/A (Trait implementation) ### Parameters - `self` (T): The value to zip. ### Request Example N/A ### Response #### Success Response - `V`: The zipped multi-lane structure. #### Response Example N/A ``` -------------------------------- ### Type Conversion Utilities (Rust) Source: https://docs.rs/kameo/latest/kameo/message/struct Provides methods for converting between different type representations, such as `Box` and specific types implementing `Downcast`. These are essential for generic programming and message handling where type information needs to be dynamically determined. ```rust impl Downcast for T where T: Any, { fn into_any(self: Box) -> Box; fn into_any_rc(self: Rc) -> Rc; fn as_any(&self) -> &(dyn Any + 'static); fn as_any_mut(&mut self) -> &mut (dyn Any + 'static); } ``` ```rust impl DowncastSend for T where T: Any + Send, { fn into_any_send(self: Box) -> Box; } ``` ```rust impl DowncastSync for T where T: Any + Send + Sync, { fn into_any_sync(self: Box) -> Box; fn into_any_arc(self: Arc) -> Arc; } ``` -------------------------------- ### Rust Blanket Implementation: CloneToUninit for T Source: https://docs.rs/kameo/latest/kameo/actor/struct This nightly-only experimental API allows types that implement Clone to be cloned into uninitialized memory. The clone_to_uninit method performs copy-assignment to a raw pointer. ```Rust impl CloneToUninit for T where T: Clone, unsafe fn clone_to_uninit(&self, dest: *mut u8) ``` -------------------------------- ### Implement CloneToUninit for Generic Types in Rust Source: https://docs.rs/kameo/latest/kameo/request/struct This snippet shows the experimental nightly-only implementation of CloneToUninit for types that implement Clone. It provides an unsafe method to copy data to an uninitialized memory location. ```rust impl CloneToUninit for T where T: Clone { unsafe fn clone_to_uninit(&self, dest: *mut u8); } ``` -------------------------------- ### TryInto Conversion in Rust Source: https://docs.rs/kameo/latest/kameo/message/struct Implements `TryInto` for `T`, allowing fallible conversions from `T` to `U`. This relies on `U` implementing `TryFrom`. The `try_into` method returns a `Result` that reflects the success or failure of the underlying `TryFrom` conversion. ```rust impl TryInto for T where U: TryFrom {} ``` ```rust type Error = >::Error ``` ```rust fn try_into(self) -> Result>::Error> ``` -------------------------------- ### Rust: Config Clone Implementation Source: https://docs.rs/kameo/latest/kameo/remote/messaging/struct Implements the Clone trait for the Config struct, allowing instances of Config to be duplicated. This is useful for creating independent configurations or for passing configurations by value. ```rust fn clone(&self) -> Config Returns a duplicate of the value. Read more ``` ```rust fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Read more ``` -------------------------------- ### Subscriber Attachment Source: https://docs.rs/kameo/latest/kameo/error/struct Allows types to be associated with a `tracing` subscriber. `with_subscriber` attaches a provided subscriber, while `with_current_subscriber` uses the globally configured subscriber. ```Rust impl WithSubscriber for T Source§ #### fn with_subscriber(self, subscriber: S) -> WithDispatch where S: Into, ``` ```Rust #### fn with_current_subscriber(self) -> WithDispatch ``` -------------------------------- ### Handling kameo::remote::Event in Swarm Event Loop (Rust) Source: https://docs.rs/kameo/latest/kameo/remote/enum Demonstrates how to handle the kameo::remote::Event enum within a libp2p Swarm event loop. It shows pattern matching to differentiate between registry and messaging events for appropriate handling. ```rust use kameo::remote; use libp2p::swarm::SwarmEvent; // In your swarm event loop: match swarm_event { SwarmEvent::Behaviour(remote::Event::Registry(registry_event)) => { // Handle registry events (actor registration, lookup, etc.) } SwarmEvent::Behaviour(remote::Event::Messaging(messaging_event)) => { // Handle messaging events (message delivery, timeouts, etc.) } _ => {} } ``` -------------------------------- ### Chunking Ready Stream Elements Source: https://docs.rs/kameo/latest/kameo/remote/struct Similar to `try_chunks`, but specifically chunks successful and ready elements from the stream into vectors. This is optimized for scenarios where element readiness is a factor. ```Rust fn try_ready_chunks(self, capacity: usize) -> TryReadyChunks where Self: Sized, ``` -------------------------------- ### Reply Trait Implementation for WeakReplyRecipient (Rust) Source: https://docs.rs/kameo/latest/kameo/actor/struct Shows how `WeakReplyRecipient` implements the `Reply` trait, defining its associated types for success (`Ok`), error (`Error`), and the value sent back (`Value`). It also includes methods for converting the reply to a `Result`, handling errors, and extracting the value, demonstrating its role in asynchronous communication patterns. ```rust impl Reply for WeakReplyRecipient { type Ok = WeakReplyRecipient; type Error = Infallible; type Value = WeakReplyRecipient; fn to_result(self) -> Result fn into_any_err(self) -> Option> fn into_value(self) -> Self::Value fn downcast_ok(ok: Box) -> Self::Ok fn downcast_err(err: BoxSendError) -> SendError } ``` -------------------------------- ### Rust: Config Default Implementation Source: https://docs.rs/kameo/latest/kameo/remote/messaging/struct Implements the Default trait for the Config struct, providing a default configuration. This allows creating a Config instance with standard settings without explicit parameterization. ```rust fn default() -> Self Returns the “default value” for a type. Read more ``` -------------------------------- ### Default Actor Spawning with kameo Source: https://docs.rs/kameo/latest/kameo/actor/trait Illustrates spawning an actor using `spawn_default`. This method requires the actor to implement the `Default` trait and is suitable for actors that can be initialized with their default values. It also runs the actor in a Tokio task with a default bounded mailbox. ```rust use kameo::Actor; use kameo::actor::Spawn; #[derive(Actor, Default)] struct Counter { count: i32, } // Spawn with default initialization let actor_ref = Counter::spawn_default(); ``` -------------------------------- ### Instrumentation with Spans Source: https://docs.rs/kameo/latest/kameo/error/struct Allows types to be instrumented with `tracing` spans. `instrument` applies a provided span, while `in_current_span` uses the active span in the current context. ```Rust impl Instrument for T Source§ #### fn instrument(self, span: Span) -> Instrumented ``` ```Rust #### fn in_current_span(self) -> Instrumented ``` -------------------------------- ### Spawn Actor with Default Initialization (Rust) Source: https://docs.rs/kameo/latest/kameo/actor/trait Spawns an actor using its default initialization. This is a convenience method for actors implementing the `Default` trait. It runs the actor in a non-blocking Tokio task with a default bounded mailbox of capacity 64. Use `spawn` or `spawn_with_mailbox` for custom configurations. ```rust use kameo::Actor; use kameo::actor::Spawn; #[derive(Actor, Default)] struct MyActor { count: i32, } // Spawns with default state and bounded mailbox (capacity 64) let actor_ref = MyActor::spawn_default(); ``` -------------------------------- ### DynClone Implementation for Generic Types Source: https://docs.rs/kameo/latest/kameo/error/struct Provides a `__clone_box` method for types that implement `Clone`, allowing for dynamic cloning operations. ```Rust impl DynClone for T where T: Clone, Source§ #### fn __clone_box(&self, _: Private) -> *mut () ``` -------------------------------- ### Rust: Context spawn for asynchronous task handling Source: https://docs.rs/kameo/latest/kameo/message/struct Shows how to use the `spawn` method from the Context struct to execute intensive operations asynchronously in detached tasks. This method returns a `DelegatedReply` and is essential for non-blocking actor behavior. Error handling differs for 'ask' vs. 'tell' requests, and spawned tasks are independent of the actor's lifecycle. ```rust pub fn spawn(&mut self, future: F) -> DelegatedReply where F: Future + Send + 'static, // Example Usage: use kameo::prelude::*; #[derive(Actor)] struct MyActor; struct ProcessData { data: Vec, } impl Message for MyActor { type Reply = DelegatedReply>; async fn handle(&mut self, msg: ProcessData, ctx: &mut Context) -> Self::Reply { ctx.spawn(async move { tokio::time::sleep(std::time::Duration::from_secs(10)).await; if msg.data.is_empty() { Err(std::io::Error::new(std::io::ErrorKind::InvalidInput, "Empty data")) } else { Ok(String::from_utf8_lossy(&msg.data).to_string()) } }) } } ``` -------------------------------- ### Rust: Add Kameo Dependency to Cargo.toml Source: https://docs.rs/kameo/latest/kameo/index This snippet shows how to add the Kameo library as a dependency to your Rust project's Cargo.toml file. It can be done by directly editing the file or using the cargo add command. ```rust [dependencies] kameo = "0.19" ``` ```bash cargo add kameo ``` -------------------------------- ### Prepare Actor with Custom Mailbox (Rust) Source: https://docs.rs/kameo/latest/kameo/actor/trait Creates a prepared actor with a specified mailbox configuration, enabling ActorRef access prior to spawning. This is useful for setting up custom mailbox behaviors or capacities during the preparation phase. It takes mailbox sender and receiver tuples. ```rust use kameo::Actor; use kameo::actor::Spawn; use kameo::mailbox; #[derive(Actor)] struct MyActor; let other_actor = MyActor::spawn(MyActor); let prepared_actor = MyActor::prepare_with_mailbox(mailbox::unbounded()); prepared_actor.actor_ref().link(&other_actor).await; let actor_ref = prepared_actor.spawn(MyActor); ``` -------------------------------- ### Rust Blanket Implementation: Equivalent for Q Source: https://docs.rs/kameo/latest/kameo/actor/struct This implementation allows types Q that implement Eq to be compared for equality with types K that borrow as Q. The equivalent method returns a boolean indicating equality. ```Rust impl Equivalent for Q where Q: Eq + ?Sized, K: Borrow + ?Sized, fn equivalent(&self, key: &K) -> bool ``` -------------------------------- ### Spawning Linked Actors for Supervision with kameo Source: https://docs.rs/kameo/latest/kameo/actor/trait Illustrates spawning an actor with a supervision link to another actor using `spawn_link`. This is crucial for implementing supervision strategies where a parent actor monitors and potentially restarts its children. ```rust use kameo::Actor; use kameo::actor::Spawn; #[derive(Actor)] struct Supervisor; #[derive(Actor)] struct Worker; let supervisor = Supervisor::spawn(Supervisor); // Link worker to supervisor before spawning let worker = Worker::spawn_link(&supervisor, Worker).await; ``` -------------------------------- ### Custom Mailbox Spawning with kameo Source: https://docs.rs/kameo/latest/kameo/actor/trait Shows how to spawn an actor with a custom mailbox configuration using `spawn_with_mailbox`. This allows for fine-grained control over message handling, such as using an unbounded mailbox for high message throughput. ```rust use kameo::Actor; use kameo::actor::Spawn; use kameo::mailbox; #[derive(Actor)] struct HighThroughput; // Spawn with unbounded mailbox for high message rates let actor_ref = HighThroughput::spawn_with_mailbox( HighThroughput, mailbox::unbounded() ); ``` -------------------------------- ### Box and Pin a Local Stream (Rust) Source: https://docs.rs/kameo/latest/kameo/remote/struct Wraps a stream in a `Box` and pins it, creating a dynamically sized type that is not necessarily `Send`. This is useful for abstracting over stream types within a single thread. ```Rust fn boxed_local<'a>(self) -> Pin + 'a>> where Self: Sized + 'a, ``` -------------------------------- ### Rust Instrument Trait Implementation Source: https://docs.rs/kameo/latest/kameo/remote/registry/struct Allows types to be instrumented with `tracing` spans, enabling structured logging and context propagation. The `instrument` and `in_current_span` methods facilitate integration with the `tracing` ecosystem. ```rust impl Instrument for T fn instrument(self, span: Span) -> Instrumented fn in_current_span(self) -> Instrumented ``` -------------------------------- ### SendError Conversions and Comparisons (Rust) Source: https://docs.rs/kameo/latest/kameo/error/enum Demonstrates functions for converting TrySendError to SendError, and for comparing SendError instances for equality and inequality. These are fundamental operations for error handling and state management. ```rust fn from(err: TrySendError>) -> Self fn eq(&self, other: &SendError) -> bool fn ne(&self, other: &Rhs) -> bool ``` -------------------------------- ### Box and Pin a Sendable Stream (Rust) Source: https://docs.rs/kameo/latest/kameo/remote/struct Wraps a stream in a `Box` and pins it, making it a dynamically sized type that can be sent across threads. This is useful for abstracting over different stream types that implement `Send`. ```Rust fn boxed<'a>(self) -> Pin + Send + 'a>> where Self: Sized + Send + 'a, ``` -------------------------------- ### Convert Box to Box Source: https://docs.rs/kameo/latest/kameo/reply/struct Converts a Box to Box, supporting dynamic dispatch for types that are both Send and Sync. This is crucial for concurrent programming. ```Rust fn into_any_sync(self: Box) -> Box ``` -------------------------------- ### Chunk Ready Stream Items (Rust) Source: https://docs.rs/kameo/latest/kameo/remote/struct Groups items that are ready to be yielded from a stream into vectors of a specified capacity. This is similar to `chunks` but operates on items that are immediately available, potentially offering better performance in certain asynchronous scenarios. ```Rust fn ready_chunks(self, capacity: usize) -> ReadyChunks where Self: Sized, ``` -------------------------------- ### Unordered Buffered Future Processing (Rust) Source: https://docs.rs/kameo/latest/kameo/remote/struct Creates a stream that buffers a specified number of pending futures, yielding results in any order. This adapter is useful when the order of completion does not matter and maximum throughput is desired. ```Rust fn buffer_unordered(self, n: usize) -> BufferUnordered where Self::Item: Future, Self: Sized, ``` -------------------------------- ### Zipping Streams with Multiple Lanes Source: https://docs.rs/kameo/latest/kameo/remote/struct Implements the `VZip` functionality for types that support multi-lane operations. This is likely related to combining multiple streams or data sources in a zipped fashion. ```Rust fn vzip(self) -> V where V: MultiLane, ``` -------------------------------- ### Rust AsTaggedExplicit and AsTaggedImplicit Implementations Source: https://docs.rs/kameo/latest/kameo/remote/registry/struct These implementations facilitate tagged parsing for explicit and implicit message classes. They return a `TaggedParser` which encapsulates the parsing logic based on class and tag. ```rust impl<'a, T, E> AsTaggedExplicit<'a, E> for T where T: 'a, fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E> ``` ```rust impl<'a, T, E> AsTaggedImplicit<'a, E> for T where T: 'a, fn implicit( self, class: Class, constructed: bool, tag: u32, ) -> TaggedParser<'a, Implicit, Self, E> ``` -------------------------------- ### DynMessage Handling for Actors Source: https://docs.rs/kameo/latest/kameo/error/struct Enables actors to handle dynamic messages (`dyn Message`). The `handle_dyn` function processes messages with actor state and a reply sender, returning a future. The `as_any` function casts the message to a `Box`. ```Rust impl DynMessage for T where A: Actor + Message, T: Send + 'static, Source§ #### fn handle_dyn<'a>( self: Box, state: &'a mut A, actor_ref: ActorRef, tx: Option, SendError, Box>>>>, stop: &'a mut bool, ) -> Pin>> + Send + 'a>> ``` ```Rust #### fn as_any(self: Box) -> Box ``` -------------------------------- ### Error Handling Traits Source: https://docs.rs/kameo/latest/kameo/request/struct Documentation for traits related to error handling and reporting. ```APIDOC ## `ReplyError` Trait ### Description Represents a type that can be used as an error in replies or responses. ### Endpoint N/A (Trait definition) ### Parameters N/A ### Request Example N/A ### Response N/A #### Response Example N/A ``` -------------------------------- ### Send Reply using ReplySender - Rust Source: https://docs.rs/kameo/latest/kameo/reply/struct The `send` method consumes the ReplySender and sends the specified reply. It enforces a single-use pattern for ReplySender, ensuring that a reply is sent only once per message. This is crucial for preventing deadlocks and managing communication flow. ```rust pub fn send(self, reply: R) where R: Reply, ``` -------------------------------- ### ToString Implementation Source: https://docs.rs/kameo/latest/kameo/error/struct Converts a type into a `String`. This implementation requires the type to implement the `Display` trait. ```Rust impl ToString for T where T: Display + ?Sized, Source§ #### fn to_string(&self) -> String ``` -------------------------------- ### Attaching Subscribers in Rust Source: https://docs.rs/kameo/latest/kameo/remote/enum These methods attach a `Subscriber` to a type, returning a `WithDispatch` wrapper. You can attach a specific subscriber or the current default subscriber. ```Rust fn with_subscriber(self, subscriber: S) -> WithDispatch where S: Into, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. ``` ```Rust fn with_current_subscriber(self) -> WithDispatch Attaches the current default `Subscriber` to this type, returning a `WithDispatch` wrapper. ``` -------------------------------- ### Convert &Trait to &dyn Any Source: https://docs.rs/kameo/latest/kameo/reply/struct Converts a reference &Trait to &dyn Any. This is necessary because Rust cannot directly generate the vtable for &Any from &Trait. ```Rust fn as_any(&self) -> &(dyn Any + 'static) ``` -------------------------------- ### Debug Trait Implementation for ReplySender - Rust Source: https://docs.rs/kameo/latest/kameo/reply/struct Shows the implementation of the Debug trait for ReplySender, enabling formatted printing of ReplySender instances for debugging purposes. This is part of the standard Rust trait system for providing debug representations. ```rust impl Debug for ReplySender Source ``` -------------------------------- ### TryFrom and TryInto Conversions Source: https://docs.rs/kameo/latest/kameo/request/struct The `TryFrom` and `TryInto` traits facilitate fallible conversions between types. `try_from` attempts a conversion from `U` to `T`, returning a `Result`. `try_into` is the reciprocal, attempting conversion from `T` to `U`. ```Rust type Error = Infallible; fn try_from(value: U) -> Result>::Error>; ``` ```Rust type Error = >::Error; fn try_into(self) -> Result>::Error>; ``` -------------------------------- ### Trait Implementations for WeakReplyRecipient (Rust) Source: https://docs.rs/kameo/latest/kameo/actor/struct Details the standard Rust trait implementations for `WeakReplyRecipient`. This includes `Clone` for creating copies, `Debug` for representation, `Hash` and `Ord` for ordering and hashing, `PartialEq` for equality checks, and `Eq` for total equality. These traits enable various operations and comparisons on `WeakReplyRecipient` instances. ```rust impl Clone for WeakReplyRecipient impl Debug for WeakReplyRecipient impl Hash for WeakReplyRecipient impl Ord for WeakReplyRecipient impl PartialEq for WeakReplyRecipient impl Eq for WeakReplyRecipient ``` -------------------------------- ### Peek at Stream Items (Rust) Source: https://docs.rs/kameo/latest/kameo/remote/struct Creates a stream that provides a `peek` method, allowing inspection of the next item without consuming it. This is useful for implementing lookahead logic or conditional processing based on upcoming items. ```Rust fn peekable(self) -> Peekable where Self: Sized, ```