### Actor on_start Initialization Example Source: https://docs.rs/kameo/latest/src/kameo/actor.rs.html Provides a basic example of implementing the `on_start` method for an actor. This method is called when the actor begins execution, allowing for initial state setup. ```rust use kameo::actor::{Actor, ActorRef}; use kameo::error::Infallible; struct MyActor; impl Actor for MyActor { type Args = Self; type Error = Infallible; async fn on_start( state: Self::Args, _actor_ref: ActorRef ) -> Result { Ok(state) } } ``` -------------------------------- ### Example of using PreparedActor Source: https://docs.rs/kameo/latest/kameo/actor/struct.PreparedActor.html Demonstrates preparing an actor, sending it a message using its ActorRef before it starts, and then running it. ```rust let prepared_actor = MyActor::prepare(); // Send it a message before it runs prepared_actor.actor_ref().tell("hello!").await?; prepared_actor.run(MyActor).await; ``` -------------------------------- ### Bootstrap a simple actor swarm Source: https://docs.rs/kameo/latest/kameo/remote/fn.bootstrap.html This example demonstrates how to use the `bootstrap` function to quickly start a local actor swarm. It then shows how to interact with spawned actors. ```rust #[tokio::main] async fn main() -> Result<(), Box> { // One line to get started! remote::bootstrap()?; // Now use remote actors normally let actor_ref = MyActor::spawn_default(); actor_ref.register("my_actor").await?; Ok(()) } ``` -------------------------------- ### Install and Run Kameo Console Source: https://docs.rs/kameo/latest/index.html Install the kameo_console binary using cargo and then run it, connecting to the specified address. ```bash cargo install kameo_console ``` ```bash kameo-console 127.0.0.1:9999 ``` -------------------------------- ### Example Search Queries Source: https://docs.rs/kameo/latest/kameo/mailbox/enum.Signal.html?search= Provides examples of common search queries that can be performed. These demonstrate different search patterns and types. ```text std::vec ``` ```text u32 -> bool ``` ```text Option, (T -> U) -> Option ``` -------------------------------- ### Example Search: u32 to bool Source: https://docs.rs/kameo/latest/kameo/console/fn.serve.html?search=std%3A%3Avec An example search query demonstrating a type conversion from `u32` to `bool`. ```text u32 -> bool ``` -------------------------------- ### Start Console Server Source: https://docs.rs/kameo/latest/src/kameo/console/server.rs.html Binds the server to the given address and starts serving snapshots in a background task. Returns a `ConsoleHandle` that can be used to manage the server. ```rust pub async fn serve(self, addr: impl ToSocketAddrs) -> io::Result { let listener = TcpListener::bind(addr).await?; let local_addr = listener.local_addr()?; let grave_window = self.grave_window; let task = tokio::spawn(async move { loop { match listener.accept().await { Ok((stream, _peer)) => { tokio::spawn(serve_client(stream, grave_window)); } Err(_err) => { #[cfg(feature = "tracing")] tracing::warn!("console failed to accept connection: {_err}"); } } } }); Ok(ConsoleHandle { task, local_addr }) } ``` -------------------------------- ### Example Searches for Rust Kameo Source: https://docs.rs/kameo/latest/src/kameo/links.rs.html?search= Provides example search queries for common Rust patterns and types. ```text Example searches: * std::vec * u32 -> bool * Option, (T -> U) -> Option ``` -------------------------------- ### Kameo Remote Behaviour Example Source: https://docs.rs/kameo/latest/src/kameo/remote/behaviour.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Demonstrates how to integrate the Kameo remote behaviour into a libp2p NetworkBehaviour. This setup allows for remote actor communication and discovery. ```rust use kameo::remote; use libp2p::{swarm::NetworkBehaviour, PeerId}; #[derive(NetworkBehaviour)] struct MyBehaviour { kameo: remote::Behaviour, // other behaviours... } let peer_id = PeerId::random(); let behaviour = remote::Behaviour::new(peer_id, remote::messaging::Config::default()); ``` -------------------------------- ### Example Search: Option to Option Source: https://docs.rs/kameo/latest/kameo/console/fn.serve.html?search=std%3A%3Avec An example search query illustrating a transformation from `Option` to `Option`. ```text Option, (T -> U) -> Option ``` -------------------------------- ### Serve Function Source: https://docs.rs/kameo/latest/src/kameo/console/server.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E A convenience function to start the console server with default settings. ```APIDOC ## serve ### Description Binds the console server to the specified address and starts serving snapshots using default configuration. This is a convenience function that uses `Console::builder().serve()` internally. ### Signature ```rust pub async fn serve(addr: impl ToSocketAddrs) -> io::Result ``` ### Parameters - `addr`: The network address to bind the server to (e.g., a string like "127.0.0.1:8080" or a `SocketAddr`). ### Returns - `io::Result`: On success, returns a `ConsoleHandle` that can be used to manage the running server. On failure, returns an `io::Error`. ### Example ```rust let handle = kameo::console::serve("127.0.0.1:9001").await?; ``` ``` -------------------------------- ### Example Searches Source: https://docs.rs/kameo/latest/kameo/remote/registry/enum.InvalidActorRegistration.html?search= Provides examples of how to search for invalid actor registrations. These examples demonstrate common search patterns. ```APIDOC ## Example Searches ### Description Provides examples of how to search for invalid actor registrations. These examples demonstrate common search patterns. ### Query Examples - `std::vec` - `u32 -> bool` - `Option, (T -> U) -> Option` ``` -------------------------------- ### Example Search: std::vec Source: https://docs.rs/kameo/latest/kameo/console/fn.serve.html?search=std%3A%3Avec An example search query for `std::vec`, commonly used in Rust for dynamic arrays. ```text std::vec ``` -------------------------------- ### Example: Blocking Enqueue and Receive Source: https://docs.rs/kameo/latest/src/kameo/request/ask.rs.html?search= Demonstrates enqueuing a message using `blocking_enqueue` and then receiving the reply. This example is run within a tokio runtime and uses thread spawning for the blocking operation. ```rust /// # Example /// /// ``` /// # use kameo::Actor; /// # use kameo::actor::Spawn; /// # /// # #[derive(kameo::Actor)] /// # struct MyActor; /// # /// # struct Msg; /// # /// # impl kameo::message::Message for MyActor { /// # type Reply = (); /// # async fn handle(&mut self, msg: Msg, ctx: &mut kameo::message::Context) -> Self::Reply { } /// # } /// # /// # tokio_test::block_on(async { /// # let actor_ref = MyActor::spawn(MyActor); /// # let msg = Msg; /// # std::thread::spawn(move || { /// # let f = move || { /// let pending = actor_ref.ask(Msg).blocking_enqueue()?; /// // Do some other tasks /// let reply = pending.recv()?; /// # Ok::<(), Box>(()) /// # }; /// # f().unwrap(); /// # }); /// # }); /// ``` ``` -------------------------------- ### Begin Actor Handler Source: https://docs.rs/kameo/latest/src/kameo/console/registry.rs.html?search= Records the start of a new message handler, including the message type and start time. Also increments the count for the specific message type. ```rust pub(crate) fn begin_handler(&self, message: &'static str) { *self.current_handler.lock().unwrap() = Some(CurrentHandler { message, since: Instant::now(), }); *self .message_types .lock() .unwrap() .entry(message) .or_insert(0) += 1; } ``` -------------------------------- ### Example: Waiting for Actor Startup Source: https://docs.rs/kameo/latest/src/kameo/actor/actor_ref.rs.html Shows how to spawn an actor and then use `wait_for_startup` to ensure it's ready before proceeding. Includes a simulated delay in the actor's `on_start` method. ```rust use std::time::Duration; use kameo::actor::{Actor, ActorRef, Spawn}; use kameo::error::Infallible; use tokio::time::sleep; struct MyActor; impl Actor for MyActor { type Args = Self; type Error = Infallible; async fn on_start( state: Self::Args, _actor_ref: ActorRef, ) -> Result { sleep(Duration::from_secs(2)).await; // Some io operation Ok(state) } } # tokio_test::block_on(async { let actor_ref = MyActor::spawn(MyActor); actor_ref.wait_for_startup().await; println!("Actor ready to handle messages!"); # Ok::<(), Box>(()) # }); ``` -------------------------------- ### Get Stream Position Source: https://docs.rs/kameo/latest/kameo/message/type.BoxMessage.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Returns the current seek position from the start of the stream. Part of the Seek trait implementation for Box. ```rust fn stream_position(&mut self) -> Result Returns the current seek position from the start of the stream. Read more Source ``` -------------------------------- ### Example: Actor Startup and Shutdown Handling Source: https://docs.rs/kameo/latest/src/kameo/actor/actor_ref.rs.html Demonstrates spawning an actor, stopping it gracefully, waiting for shutdown, and then checking the shutdown result using a callback. ```rust use kameo::actor::{Actor, ActorRef, Spawn, WeakActorRef}; use kameo::error::{ActorStopReason, Infallible}; struct MyActor; impl Actor for MyActor { type Args = Self; type Error = Infallible; async fn on_start( state: Self::Args, _actor_ref: ActorRef, ) -> Result { Ok(state) } } # tokio_test::block_on(async { let actor_ref = MyActor::spawn(MyActor); actor_ref.stop_gracefully().await.unwrap(); actor_ref.wait_for_shutdown().await; actor_ref.with_shutdown_result(|res| { assert!(res.is_ok()); }); # Ok::<(), Box>(()) # }); ``` -------------------------------- ### Get Actor Startup Result Source: https://docs.rs/kameo/latest/kameo/actor/struct.ActorRef.html Retrieves the startup result of an actor if it has finished starting up. Returns `None` if startup is still in progress. Does not block. ```rust use std::num::ParseIntError; use kameo::actor::{Actor, ActorRef, Spawn}; struct MyActor; impl Actor for MyActor { type Args = Self; type Error = ParseIntError; async fn on_start( _state: Self::Args, _actor_ref: ActorRef, ) -> Result { "invalid int".parse().map(|_: i32| MyActor) // Will always error } } let actor_ref = MyActor::spawn(MyActor); actor_ref.wait_for_startup().await; match actor_ref.get_startup_result() { Some(Ok(())) => println!("actor started successfully"), Some(Err(err)) => println!("actor failed to start: {err}"), None => println!("actor has not started yet"), } ``` -------------------------------- ### Example: Actor Startup Failure Handling Source: https://docs.rs/kameo/latest/src/kameo/actor/actor_ref.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Demonstrates how to use `wait_for_startup_with_result` to handle an actor that fails during its startup phase. ```rust use kameo::actor::{Actor, ActorRef, Spawn}; struct MyActor; #[derive(Debug)] struct NonCloneError; impl Actor for MyActor { type Args = Self; type Error = NonCloneError; async fn on_start( _state: Self::Args, _actor_ref: ActorRef, ) -> Result { Err(NonCloneError) // Will always error } } # tokio_test::block_on(async { let actor_ref = MyActor::spawn(MyActor); actor_ref.wait_for_startup_with_result(|res| { assert!(res.is_err()); }).await; # Ok::<(), Box>(()) # }); ``` -------------------------------- ### Example Usage of wait_for_startup Source: https://docs.rs/kameo/latest/src/kameo/actor/actor_ref.rs.html?search= Demonstrates waiting for an actor to complete its startup process before proceeding. ```rust use std::time::Duration; use kameo::actor::{Actor, ActorRef, Spawn}; use kameo::error::Infallible; use tokio::time::sleep; struct MyActor; impl Actor for MyActor { type Args = Self; type Error = Infallible; async fn on_start( state: Self::Args, _actor_ref: ActorRef, ) -> Result { sleep(Duration::from_secs(2)).await; // Some io operation Ok(state) } } # tokio_test::block_on(async { let actor_ref = MyActor::spawn(MyActor); actor_ref.wait_for_startup().await; println!("Actor ready to handle messages!"); # Ok::<(), Box>(()) # }); ``` -------------------------------- ### Attach Stream to Actor Source: https://docs.rs/kameo/latest/src/kameo/actor/actor_ref.rs.html?search= This example demonstrates how to attach a stream to an actor, sending start, next, and finish messages. It uses tokio's select macro for concurrent handling. ```rust pub fn attach_stream( &self, mut stream: S, start_value: T, finish_value: F, ) -> JoinHandle>>> where A: Message>, S: Stream + Send + Unpin + 'static, M: Send + 'static, T: Send + 'static, F: Send + 'static, { let actor_ref = self.clone(); tokio::spawn(async move { actor_ref .tell(StreamMessage::Started(start_value)) .send() .await?; loop { tokio::select! { msg = stream.next() => { match msg { Some(msg) => { actor_ref.tell(StreamMessage::Next(msg)).send().await?; } None => break, } } _ = actor_ref.wait_for_shutdown() => { return Ok(stream); } } } actor_ref .tell(StreamMessage::Finished(finish_value)) .send() .await?; Ok(stream) }) } ``` -------------------------------- ### serve Source: https://docs.rs/kameo/latest/kameo/console/fn.serve.html Binds `addr` and serves console snapshots with default settings. ```APIDOC ## serve ### Description Binds `addr` and serves console snapshots with default settings. ### Function Signature ```rust pub async fn serve(addr: impl ToSocketAddrs) -> Result ``` ### Parameters #### Path Parameters - **addr** (impl ToSocketAddrs) - Required - The address to bind to. ### Returns - **Result** - A handle to the console server. ``` -------------------------------- ### ActorRef Search Examples Source: https://docs.rs/kameo/latest/kameo/actor/struct.ActorRef.html?search= Examples of how to search for ActorRefs. These examples demonstrate different query patterns. ```APIDOC ## ActorRef Search ### Description Provides examples of search queries for ActorRefs. ### Example Searches * `std::vec` * `u32 -> bool` * `Option, (T -> U) -> Option` ``` -------------------------------- ### serve (free function) Source: https://docs.rs/kameo/latest/src/kameo/console/server.rs.html?search= Binds `addr` and serves console snapshots with default settings. This is a convenience function that uses the `Console::builder()`. ```APIDOC ## serve (free function) ### Description Binds `addr` and serves console snapshots with default settings. This is a convenience function that uses the `Console::builder()`. ### Method `async fn serve(addr: impl ToSocketAddrs) -> io::Result` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```rust // Example usage: // let console_handle = serve("127.0.0.1:9000").await?; ``` ### Response #### Success Response - **ConsoleHandle** - A handle to the running console server. #### Response Example ```rust // ConsoleHandle { task: JoinHandle<()>, local_addr: SocketAddr } ``` ERROR HANDLING: - Returns `io::Result` which can contain `io::Error` if binding fails. ``` -------------------------------- ### Kameo Prelude Usage Example Source: https://docs.rs/kameo/latest/src/kameo/lib.rs.html Demonstrates how to import commonly used types and functions from the kameo prelude with a single use statement. ```rust use kameo::prelude::*; ``` -------------------------------- ### OneForAll Supervision Strategy Example Source: https://docs.rs/kameo/latest/src/kameo/supervision.rs.html?search=u32+-%3E+bool Demonstrates the OneForAll strategy, where all children are restarted when any one child fails. ```text Supervisor ├── Child A (running) → Restarted ├── Child B (crashes) → Restarted └── Child C (running) → Restarted ``` -------------------------------- ### Example Usage of Restart Policies Source: https://docs.rs/kameo/latest/kameo/supervision/enum.RestartPolicy.html?search= Demonstrates how to apply Permanent, Transient, and Never restart policies when spawning supervised workers. ```rust use std::time::Duration; use kameo::actor::{Actor, ActorRef, Spawn}; use kameo::supervision::RestartPolicy; // Critical service that must always be running let critical = Worker::supervise(&supervisor_ref, Worker) .restart_policy(RestartPolicy::Permanent) .spawn() .await; // Worker that can exit normally when work is done let worker = Worker::supervise(&supervisor_ref, Worker) .restart_policy(RestartPolicy::Transient) .spawn() .await; // One-shot task that should run once and never be restarted let one_shot = Worker::supervise(&supervisor_ref, Worker) .restart_policy(RestartPolicy::Never) .spawn() .await; ``` -------------------------------- ### Kameo Remote Event Example Source: https://docs.rs/kameo/latest/src/kameo/remote/behaviour.rs.html Example of how to match on SwarmEvent to handle remote behaviour events, specifically for registry and messaging events. ```rust match swarm_event { SwarmEvent::Behaviour(remote::Event::Registry(registry_event)) => { // Handle registry events (actor registration, lookup, etc.) } SwarmEvent::Behaviour(remote::Event::Messaging(messaging_event)) => { ``` -------------------------------- ### Example: Actor Startup Error with Specific Type Source: https://docs.rs/kameo/latest/src/kameo/actor/actor_ref.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Illustrates waiting for an actor's startup result, expecting a specific error type during the `on_start` phase. ```rust use std::num::ParseIntError; use kameo::actor::{Actor, ActorRef, Spawn}; struct MyActor; impl Actor for MyActor { type Args = Self; type Error = ParseIntError; async fn on_start( _state: Self::Args, _actor_ref: ActorRef, ) -> Result { "invalid int".parse().map(|_: i32| MyActor) // Will always error } } # tokio_test::block_on(async { let actor_ref = MyActor::spawn(MyActor); let startup_result = actor_ref.wait_for_startup_result().await; assert!(startup_result.is_err()); # Ok::<(), Box>(()) # }); ``` -------------------------------- ### Default Remote Actor ID Example Source: https://docs.rs/kameo/latest/kameo/prelude/derive.RemoteActor.html?search=u32+-%3E+bool This example demonstrates the default behavior where the `REMOTE_ID` is automatically set to the fully qualified path of the struct. ```rust use kameo::RemoteActor; #[derive(RemoteActor)] struct MyActor { } assert_eq!(MyActor::REMOTE_ID, "my_crate::module::MyActor"); ``` -------------------------------- ### Creating an AskRequest Source: https://docs.rs/kameo/latest/src/kameo/request/ask.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Demonstrates the creation of an AskRequest using the `new` constructor. This is the initial step before configuring timeouts or sending the request. ```rust AskRequest { actor_ref: self.actor_ref, msg: self.msg, mailbox_timeout: Tm::default(), reply_timeout: Tr::default(), message_name: >::name(), #[cfg(all(debug_assertions, feature = ``` -------------------------------- ### DynMessage Trait Implementation Example Source: https://docs.rs/kameo/latest/kameo/message/trait.DynMessage.html?search= Example of implementing the DynMessage trait for a generic type T associated with an Actor type A. This requires A to be an Actor and Message, and T to be Send and 'static. ```rust impl DynMessage for T where A: Actor + Message, T: Send + 'static, ``` -------------------------------- ### Unbounded Mailbox Ask Request Setup Source: https://docs.rs/kameo/latest/src/kameo/request/ask.rs.html?search=u32+-%3E+bool Sets up an actor with an unbounded mailbox for handling ask requests. This snippet focuses on the initial setup before message handling. ```rust struct MyActor; impl Actor for MyActor { type Args = Self; type Error = Infallible; async fn on_start( state: Self::Args, _actor_ref: ActorRef, ) -> Result { Ok(state) } } #[derive(Clone, Copy, PartialEq, Eq)] struct Sleep(Duration); impl Message for MyActor { type Reply = bool; async fn handle( &mut self, Sleep(duration): Sleep, ``` -------------------------------- ### Console Builder Source: https://docs.rs/kameo/latest/src/kameo/console/server.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Use the `Console` builder to configure and start a console server. You can customize settings like the `grave_window` before serving. ```APIDOC ## Console Builder ### Description Provides a builder pattern for configuring and creating a console server instance. Allows customization of server settings before starting the service. ### Methods - `builder()`: Creates a new `Console` builder with default settings. - `grave_window(grave_window: Duration)`: Sets the duration for how long a stopped actor lingers in snapshots before being dropped. Defaults to 5 seconds. - `serve(addr: impl ToSocketAddrs)`: Binds the server to the given address and starts serving snapshots in a background task. Returns a `ConsoleHandle`. ### Example ```rust use std::time::Duration; let console_server = kameo::console::Console::builder() .grave_window(Duration::from_secs(10)) .serve("127.0.0.1:9000") .await?; ``` ``` -------------------------------- ### Example: Blocking Enqueue and Receive Reply Source: https://docs.rs/kameo/latest/src/kameo/request/ask.rs.html?search=std%3A%3Avec Demonstrates how to use `blocking_enqueue` to send a message and then receive its reply in a separate thread. This example requires `tokio_test` and `std::thread`. ```rust # use kameo::Actor; # use kameo::actor::Spawn; # # #[derive(kameo::Actor)] # struct MyActor; # # struct Msg; # # impl kameo::message::Message for MyActor { # type Reply = (); # async fn handle(&mut self, msg: Msg, ctx: &mut kameo::message::Context) -> Self::Reply { } # } # # tokio_test::block_on(async { # let actor_ref = MyActor::spawn(MyActor); # let msg = Msg; # std::thread::spawn(move || { # let f = move || { let pending = actor_ref.ask(Msg).blocking_enqueue()?; // Do some other tasks let reply = pending.recv()?; # Ok::<(), Box>(()) # }; # f().unwrap(); # }); # }); ``` -------------------------------- ### Example of Try Enqueuing a Message Source: https://docs.rs/kameo/latest/kameo/request/struct.AskRequest.html?search= Demonstrates how to try enqueuing a message using AskRequest and then await the pending reply. This is useful when immediate mailbox availability is not guaranteed. ```rust let pending = actor_ref.ask(Msg).try_enqueue()?; // Do some other tasks let reply = pending.await?; ``` -------------------------------- ### Import Kameo Prelude Source: https://docs.rs/kameo/latest/kameo/prelude/index.html Import all commonly used types and functions from the Kameo prelude with a single use statement. This is the recommended way to start using Kameo's core features. ```rust use kameo::prelude::*; ``` -------------------------------- ### Waiting for Startup with Ok Result Assertion Source: https://docs.rs/kameo/latest/src/kameo/actor/actor_ref.rs.html?search= Waits for an actor to start up and asserts that the startup hook completed successfully (is_ok). This is used to ensure an actor starts without panicking when expected. ```rust tokio::time::timeout( Duration::from_secs(1), aref.wait_for_startup_with_result(|r| assert!(r.is_ok())), ) .await .unwrap(); ``` -------------------------------- ### Example of Enqueuing a Message Source: https://docs.rs/kameo/latest/kameo/request/struct.AskRequest.html?search= Demonstrates how to enqueue a message using AskRequest and then await the pending reply. This pattern allows for other tasks to be performed while waiting for the actor's response. ```rust let pending = actor_ref.ask(Msg).enqueue().await?; // Do some other tasks let reply = pending.await?; ``` -------------------------------- ### Console::serve Source: https://docs.rs/kameo/latest/kameo/console/struct.Console.html Binds the console server to the specified address and starts serving snapshots in a background task. This method initiates the server's operation. ```APIDOC ## Console::serve ### Description Binds the given address and starts serving snapshots in a background task. ### Method `serve(self, addr: impl ToSocketAddrs) -> Result` ### Parameters #### Self Parameters - **addr** (impl ToSocketAddrs) - The address to bind the server to. ### Returns - `Result` - A `ConsoleHandle` if the server starts successfully, or an error. ``` -------------------------------- ### chunk_mut Source: https://docs.rs/kameo/latest/kameo/message/type.BoxReply.html Returns a mutable slice starting at the current position. ```APIDOC ## fn chunk_mut(&mut self) -> &mut UninitSlice ### Description Returns a mutable slice starting at the current BufMut position and of length between 0 and `BufMut::remaining_mut()`. ### Method N/A (Method call on a mutable reference) ### Parameters None ### Response #### Success Response - **&mut UninitSlice**: A mutable slice of uninitialized memory. ``` -------------------------------- ### try_get_u64 Source: https://docs.rs/kameo/latest/kameo/message/type.BoxReply.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Attempts to get an unsigned 64-bit integer from the message. ```APIDOC ## try_get_u64 ### Description Gets an unsigned 64-bit integer from `self`. ### Method `try_get_u64` ### Parameters This method takes no parameters. ### Returns A `Result` containing the unsigned 64-bit integer (`u64`) on success, or a `TryGetError` on failure. ``` -------------------------------- ### bootstrap Source: https://docs.rs/kameo/latest/kameo/remote/fn.bootstrap.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Boots a simple actor swarm with mDNS discovery for local development. This convenience function creates and runs a libp2p swarm with TCP and QUIC transports, mDNS peer discovery (local network only), and automatic listening on an OS-assigned port. For production use or custom configuration, use `kameo::remote::Behaviour` with your own libp2p swarm setup. ```APIDOC ## Function bootstrap ### Description Boots a simple actor swarm with mDNS discovery for local development. This convenience function creates and runs a libp2p swarm with: * TCP and QUIC transports * mDNS peer discovery (local network only) * Automatic listening on an OS-assigned port For production use or custom configuration, use `kameo::remote::Behaviour` with your own libp2p swarm setup. ### Signature ```rust pub fn bootstrap() -> Result> ``` ### Example ```rust #[tokio::main] async fn main() -> Result<(), Box> { // One line to get started! remote::bootstrap()?; // Now use remote actors normally let actor_ref = MyActor::spawn_default(); actor_ref.register("my_actor").await?; Ok(()) } ``` ``` -------------------------------- ### try_get_i8 Source: https://docs.rs/kameo/latest/kameo/message/type.BoxReply.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Attempts to get a signed 8-bit integer from the message. ```APIDOC ## try_get_i8 ### Description Gets a signed 8-bit integer from `self`. ### Method `try_get_i8` ### Parameters This method takes no parameters. ### Returns A `Result` containing the signed 8-bit integer (`i8`) on success, or a `TryGetError` on failure. ``` -------------------------------- ### on_start Method Source: https://docs.rs/kameo/latest/kameo/actor/trait.Actor.html?search=std%3A%3Avec Called when the actor starts, before processing any messages. Ensures initialization before external messages are handled. ```APIDOC ## Required Methods ### fn on_start( args: Self::Args, actor_ref: ActorRef, ) -> impl Future> + Send Called when the actor starts, before it processes any messages. Messages sent internally during `on_start` are prioritized. #### Parameters * `args`: Arguments to initialize the actor state. * `actor_ref`: A reference to the actor itself. #### Returns A future that resolves to `Result`, indicating success or failure during initialization. ##### Example ```rust struct MyActor; impl Actor for MyActor { type Args = Self; type Error = Infallible; async fn on_start( state: Self::Args, _actor_ref: ActorRef ) -> Result { Ok(state) } } ``` ``` -------------------------------- ### try_get_u8 Source: https://docs.rs/kameo/latest/kameo/message/type.BoxReply.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Attempts to get an unsigned 8-bit integer from the message. ```APIDOC ## try_get_u8 ### Description Gets an unsigned 8-bit integer from `self`. ### Method `try_get_u8` ### Parameters This method takes no parameters. ### Returns A `Result` containing the unsigned 8-bit integer (`u8`) on success, or a `TryGetError` on failure. ``` -------------------------------- ### fn type_id(&self) -> TypeId Source: https://docs.rs/kameo/latest/kameo/actor/struct.ActorRef.html?search= Gets the `TypeId` of `self`. ```APIDOC ## fn type_id(&self) -> TypeId ### Description Gets the `TypeId` of `self`. ### Blanket Implementations This is a blanket implementation for `T` where `T: 'static + ?Sized`. ``` -------------------------------- ### Actor Required Methods Source: https://docs.rs/kameo/latest/kameo/actor/trait.Actor.html?search= Details the `on_start` method, which is called when an actor begins execution. ```APIDOC ## Required Methods ### `fn on_start(args: Self::Args, actor_ref: ActorRef) -> impl Future> + Send` Called when the actor starts, before processing any messages. Internal messages sent during `on_start` are prioritized. #### Parameters * `args`: `Self::Args` - The arguments to initialize the actor with. * `actor_ref`: `ActorRef` - A reference to the actor itself. #### Returns * `impl Future> + Send` - A future that resolves to the actor's state or an error. ##### Example ```rust struct MyActor; impl Actor for MyActor { type Args = Self; type Error = Infallible; async fn on_start( state: Self::Args, _actor_ref: ActorRef ) -> Result { Ok(state) } } ``` ``` -------------------------------- ### Serve Console Snapshots Source: https://docs.rs/kameo/latest/kameo/console/struct.Console.html Binds the console server to the given address and starts serving snapshots in a background task. Returns a ConsoleHandle upon successful execution. ```rust pub async fn serve(self, addr: impl ToSocketAddrs) -> Result ``` -------------------------------- ### Getting RemoteActorRef ID Source: https://docs.rs/kameo/latest/src/kameo/actor/actor_ref.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Retrieves the unique identifier of the remote actor. ```rust /// Returns the unique identifier of the remote actor. pub fn id(&self) -> ActorId { self.id } ``` -------------------------------- ### try_get_u64 Source: https://docs.rs/kameo/latest/kameo/message/type.BoxReply.html?search= Attempts to get an unsigned 64-bit integer from the message box. ```APIDOC ## fn try_get_u64(&mut self) -> Result ### Description Gets an unsigned 64-bit integer from `self`. ### Method (Implicitly a method call on a mutable reference) ### Return Value Result: Ok(u64) if successful, or a TryGetError if the value cannot be retrieved. ``` -------------------------------- ### Example Search Queries Source: https://docs.rs/kameo/latest/kameo/remote/registry/enum.InvalidActorRegistration.html?search= Illustrative search queries for exploring types and their relationships within the system. ```text * std::vec ``` ```text * u32 -> bool ``` ```text * Option, (T -> U) -> Option ``` -------------------------------- ### Serve Console Snapshots with Defaults Source: https://docs.rs/kameo/latest/src/kameo/console/server.rs.html A convenience function to bind to an address and serve console snapshots using the default server settings. It internally uses `Console::builder().serve(addr).await`. ```rust pub async fn serve(addr: impl ToSocketAddrs) -> io::Result { Console::builder().serve(addr).await } ``` -------------------------------- ### try_get_i8 Source: https://docs.rs/kameo/latest/kameo/message/type.BoxReply.html?search= Attempts to get a signed 8-bit integer from the message box. ```APIDOC ## fn try_get_i8(&mut self) -> Result ### Description Gets a signed 8-bit integer from `self`. ### Method (Implicitly a method call on a mutable reference) ### Return Value Result: Ok(i8) if successful, or a TryGetError if the value cannot be retrieved. ``` -------------------------------- ### Console Server Builder Source: https://docs.rs/kameo/latest/src/kameo/console/server.rs.html Use the `Console::builder()` to create a new console server instance with default settings. You can then configure the `grave_window` before starting the server. ```rust pub fn builder() -> Console { Console::default() } ``` -------------------------------- ### try_get_u8 Source: https://docs.rs/kameo/latest/kameo/message/type.BoxReply.html?search= Attempts to get an unsigned 8-bit integer from the message box. ```APIDOC ## fn try_get_u8(&mut self) -> Result ### Description Gets an unsigned 8-bit integer from `self`. ### Method (Implicitly a method call on a mutable reference) ### Return Value Result: Ok(u8) if successful, or a TryGetError if the value cannot be retrieved. ``` -------------------------------- ### type_id Source: https://docs.rs/kameo/latest/kameo/mailbox/struct.MailboxSender.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Gets the `TypeId` of `self`. This is a fundamental operation for type introspection. ```APIDOC ## fn type_id(&self) -> TypeId ### Description Gets the `TypeId` of `self`. ### Method `type_id` ### Parameters None ### Returns - `TypeId`: The unique identifier for the type of `self`. ``` -------------------------------- ### serve Source: https://docs.rs/kameo/latest/src/kameo/console.rs.html?search= Exposes actor system snapshots over TCP to a console client. This is a ready-made function to quickly start the console server. ```APIDOC ## serve ### Description Starts a TCP server to expose actor system monitoring data to a console client. This function provides a convenient way to enable live monitoring without manual configuration. ### Method (Not specified, likely a function call in the SDK) ### Endpoint (Not applicable, this is an SDK function) ### Parameters (No specific parameters are detailed in the source for `serve` itself, but it implies interaction with the actor system and network) ### Request Example (Not applicable, this is an SDK function) ### Response (Not applicable, this function likely runs indefinitely or until stopped) ERROR HANDLING: (Error handling details are not specified in the source.) ``` -------------------------------- ### type_id Source: https://docs.rs/kameo/latest/kameo/console/struct.Console.html?search= Gets the `TypeId` of `self`. This method is part of the `Any` trait implementation. ```APIDOC ## fn type_id(&self) -> TypeId ### Description Gets the `TypeId` of `self`. ### Method `type_id` ### Parameters None ### Response #### Success Response - **TypeId**: The unique identifier for the type of `self`. ``` -------------------------------- ### type_id Source: https://docs.rs/kameo/latest/kameo/actor/struct.WeakActorRef.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Gets the `TypeId` of the object. This is useful for runtime type identification. ```APIDOC ## fn type_id(&self) -> TypeId ### Description Gets the `TypeId` of `self`. ### Method GET ### Endpoint N/A (Method on a trait implementation) ### Parameters None ### Response #### Success Response (200) - **TypeId**: The unique identifier for the type of `self`. ``` -------------------------------- ### ActorSwarm Initialization and Access Source: https://docs.rs/kameo/latest/src/kameo/remote/swarm.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Demonstrates how to initialize the ActorSwarm with a sender for swarm commands and the local peer ID, and how to retrieve a static reference to the initialized swarm. ```rust static ACTOR_SWARM: OnceLock = OnceLock::new(); impl ActorSwarm { /// Retrieves a reference to the current `ActorSwarm` if it has been bootstrapped. /// /// This function is useful for getting access to the swarm after initialization without /// needing to store the reference manually. /// /// ## Returns /// An optional reference to the `ActorSwarm`, or `None` if it has not been bootstrapped. pub fn get() -> Option<&'static Self> { ACTOR_SWARM.get() } pub(crate) fn set( swarm_tx: mpsc::UnboundedSender, local_peer_id: PeerId, ) -> Result<(), Self> { ACTOR_SWARM.set(ActorSwarm { swarm_tx: SwarmSender(swarm_tx), local_peer_id, }) } } ``` -------------------------------- ### Get &dyn Any reference Source: https://docs.rs/kameo/latest/kameo/actor/struct.ActorId.html?search= Converts a &Trait to &Any, necessary for generating the vtable. ```rust fn as_any(&self) -> &(dyn Any + 'static) ``` -------------------------------- ### fn on_start Source: https://docs.rs/kameo/latest/kameo/actor/trait.Actor.html Called when the actor starts, before processing any messages. Prioritizes internally sent messages for initialization. ```APIDOC ## fn on_start ### Description Called when the actor starts, before it processes any messages. Messages sent internally during `on_start` are prioritized. ### Signature `async fn on_start(args: Self::Args, actor_ref: ActorRef) -> impl Future> + Send` ### Parameters * `args`: `Self::Args` - Arguments to initialize the actor. * `actor_ref`: `ActorRef` - A reference to the actor itself. ### Returns `impl Future> + Send` - A future that resolves to the actor instance or an error. ### Example ```rust struct MyActor; impl Actor for MyActor { type Args = Self; type Error = Infallible; async fn on_start( state: Self::Args, _actor_ref: ActorRef ) -> Result { Ok(state) } } ``` ``` -------------------------------- ### impl Any for T Source: https://docs.rs/kameo/latest/kameo/actor/struct.ActorId.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Provides the `type_id` method to get the `TypeId` of the implementing type. ```APIDOC ## fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. ``` -------------------------------- ### bootstrap_on Source: https://docs.rs/kameo/latest/kameo/remote/fn.bootstrap_on.html Bootstraps the system with a specific listen address. This function attempts to establish a connection and peer identity based on the provided address. ```APIDOC ## Function bootstrap_on ### Description Bootstraps with a specific listen address. ### Signature ```rust pub fn bootstrap_on(addr: &str) -> Result> ``` ### Parameters #### Path Parameters - **addr** (*&str*) - The listen address to bootstrap with. ### Returns - **Result>** - Returns a `PeerId` on success or an error if bootstrapping fails. ``` -------------------------------- ### Supervisor with Watcher and Transient Restart Policy Source: https://docs.rs/kameo/latest/src/kameo/supervision.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Demonstrates setting up a supervisor with a linked watcher and a child process configured with a transient restart policy. It includes checks for spurious notifications and supervisor death. ```rust // Watcher peer-linked to the supervisor, not the child let watcher = LinkTracker::spawn(LinkTracker::new( watcher_died_count.clone(), watcher_start_count.clone(), )); watcher.link(&supervisor).await; let child = TestChild::supervise(&supervisor, TestChild::new(child_start_count.clone())) .restart_policy(RestartPolicy::Transient) .spawn() .await; tokio::time::sleep(Duration::from_millis(50)).await; let _ = child.tell(StopGracefully).await; tokio::time::sleep(Duration::from_millis(150)).await; // No spurious notifications from the child's death assert_eq!( watcher_died_count.load(Ordering::SeqCst), 0, "supervisor's peer links should not be spuriously notified when a child permanently dies" ); // Kill supervisor — watcher should still be notified (link not drained) supervisor.stop_gracefully().await.unwrap(); tokio::time::sleep(Duration::from_millis(150)).await; assert_eq!( watcher_died_count.load(Ordering::SeqCst), 1, "supervisor's peer links should still fire when supervisor itself dies" ); watcher.kill(); ``` -------------------------------- ### step_by Source: https://docs.rs/kameo/latest/kameo/message/type.BoxMessage.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Creates an iterator starting at the same point, but stepping by the given amount at each iteration. ```APIDOC ## fn step_by(self, step: usize) -> StepBy where Self: Sized, ### Description Creates an iterator starting at the same point, but stepping by the given amount at each iteration. ### Parameters * `step`: `usize` - The number of elements to step by at each iteration. ### Returns * `StepBy` - A new iterator that steps by the specified amount. ``` -------------------------------- ### Box from_raw Manual Allocation Example Source: https://docs.rs/kameo/latest/kameo/message/type.BoxMessage.html?search= Manually creates a Box from scratch using the global allocator. This involves allocating memory and then converting the raw pointer to a Box. ```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); } ``` -------------------------------- ### Get Mailbox Sender Source: https://docs.rs/kameo/latest/src/kameo/actor/actor_ref.rs.html Returns a reference to the mailbox sender associated with the ActorRef. ```rust /// Returns a reference to the mailbox sender. pub fn mailbox_sender(&self) -> &MailboxSender { &self.mailbox_sender } ``` -------------------------------- ### Run Kameo Console in Demo Mode Source: https://docs.rs/kameo/latest/index.html Run the kameo-console with the --demo flag to explore its features without a running application. ```bash kameo-console --demo ``` -------------------------------- ### Get Actor ID Source: https://docs.rs/kameo/latest/src/kameo/actor/actor_ref.rs.html Retrieves the unique identifier of the actor associated with this ActorRef. ```rust /// Returns the unique identifier of the actor. #[inline] pub fn id(&self) -> ActorId { self.id } ``` -------------------------------- ### Handling Startup Completion Source: https://docs.rs/kameo/latest/src/kameo/actor/kind.rs.html Marks the actor's startup as finished and processes any messages that were buffered during the startup phase. Returns a ControlFlow. ```rust pub(crate) async fn handle_startup_finished(&mut self) -> ControlFlow { self.finished_startup = true; for signal in mem::take(&mut self.startup_buffer).drain(..) { match signal { Signal::Message { message, actor_ref, reply, sent_within_actor, message_name, #[cfg(feature = "tracing")] caller_span, } => { self.handle_message( message, actor_ref, reply, sent_within_actor, message_name, #[cfg(feature = "tracing")] caller_span, ) .await?; } _ => unreachable!(), } } ControlFlow::Continue(()) } ``` -------------------------------- ### Console Builder Methods Source: https://docs.rs/kameo/latest/kameo/console/struct.Console.html?search=u32+-%3E+bool Provides methods to configure and build a console server instance. ```APIDOC ## Console Builder ### Description Builder for a console server. ### Methods #### `builder()` Creates a console builder with default settings. #### `grave_window(self, grave_window: Duration) -> Self` Sets how long a stopped actor lingers in snapshots before being dropped. Defaults to 5 seconds. Supervised actors that restart keep their id and never appear as stopped, so this only affects actors that truly terminate. #### `serve(self, addr: impl ToSocketAddrs) -> Result` Binds the given address and starts serving snapshots in a background task. ```