### Implementing and Starting a SyncActor Source: https://docs.rs/actix/0.13.5/actix/sync/struct.SyncArbiter.html Example demonstrating the implementation of a SyncActor and starting it with a SyncArbiter pool. ```rust use actix::prelude::*; struct Fibonacci(pub u32); struct SyncActor; impl Actor for SyncActor { // It's important to note that you use "SyncContext" here instead of "Context". type Context = SyncContext; } impl Handler for SyncActor { type Result = Result; fn handle(&mut self, msg: Fibonacci, _: &mut Self::Context) -> Self::Result { if msg.0 == 0 { Err(()) } else if msg.0 == 1 { Ok(1) } else { let mut i = 0; let mut sum = 0; let mut last = 0; let mut curr = 1; while i < msg.0 - 1 { sum = last + curr; last = curr; curr = sum; i += 1; } Ok(sum) } } } fn main() { System::new().block_on(async { // Start the SyncArbiter with 2 threads, and receive the address of the Actor pool. let addr = SyncArbiter::start(2, || SyncActor); // send 5 messages for n in 5..10 { // As there are 2 threads, there are at least 2 messages always being processed // concurrently by the SyncActor. addr.do_send(Fibonacci(n)); } }); } ``` -------------------------------- ### Implementing and Starting a Supervisor Source: https://docs.rs/actix/0.13.5/actix/prelude/struct.Supervisor.html Example showing how to implement the Supervised trait for an actor and start it using a Supervisor. ```rust #[derive(Message)] #[rtype(result = "()")] struct Die; struct MyActor; impl Actor for MyActor { type Context = Context; } // To use actor with supervisor actor has to implement `Supervised` trait impl actix::Supervised for MyActor { fn restarting(&mut self, ctx: &mut Context) { println!("restarting"); } } impl Handler for MyActor { type Result = (); fn handle(&mut self, _: Die, ctx: &mut Context) { ctx.stop(); } } fn main() { let mut sys = System::new(); let addr = sys.block_on(async { actix::Supervisor::start(|_| MyActor) }); addr.do_send(Die); sys.run(); } ``` -------------------------------- ### Example Usage of actix::run Source: https://docs.rs/actix/0.13.5/actix/fn.run.html Demonstrates starting the system, executing an asynchronous sleep, and stopping the system. ```rust use std::time::{Duration, Instant};\nuse actix_rt::time::sleep;\n\nfn main() {\n actix::run(async move {\n sleep(Duration::from_millis(100)).await;\n actix::System::current().stop();\n });\n} ``` -------------------------------- ### fn start(self) -> Addr Source: https://docs.rs/actix/0.13.5/actix/trait.Actor.html Starts a new asynchronous actor and returns its address. ```APIDOC ## fn start(self) -> Addr ### Description Starts a new asynchronous actor and returns its address. This method is available when the actor uses the default Context. ### Signature `fn start(self) -> Addr` ### Example ```rust use actix::prelude::*; struct MyActor; impl Actor for MyActor { type Context = Context; } #[actix::main] async fn main() { let addr = MyActor.start(); } ``` ``` -------------------------------- ### Start an actor Source: https://docs.rs/actix/0.13.5/actix/prelude/trait.Actor.html Demonstrates how to implement the Actor trait and start an actor instance to obtain its address. ```rust use actix::prelude::*;\n\nstruct MyActor;\nimpl Actor for MyActor {\n type Context = Context;\n}\n\n#[actix::main]\nasync fn main() {\n // start actor and get its address\n let addr = MyActor.start();\n} ``` -------------------------------- ### run() Source: https://docs.rs/actix/0.13.5/actix/prelude/struct.SystemRunner.html Starts the event loop and returns once the System is stopped. ```APIDOC ### pub fn run(self) -> Result<(), Error> Starts the event loop and will return once System is stopped. ``` -------------------------------- ### Supervisor::start Source: https://docs.rs/actix/0.13.5/actix/prelude/struct.Supervisor.html Starts a new supervised actor in the current tokio runtime. ```APIDOC ## pub fn start(f: F) -> Addr ### Description Starts a new supervised actor in the current tokio runtime. The actor is created using the provided factory function. ### Parameters - **f** (FnOnce(&mut A::Context) -> A) - Required - A factory function that creates the actor instance. ### Returns - **Addr** - The address of the newly created supervised actor. ``` -------------------------------- ### Timeout Usage Example Source: https://docs.rs/actix/0.13.5/actix/clock/fn.timeout.html Demonstrates wrapping a oneshot channel receiver with a 10ms timeout. ```rust use tokio::time::timeout; use tokio::sync::oneshot; use std::time::Duration; let (tx, rx) = oneshot::channel(); // Wrap the future with a `Timeout` set to expire in 10 milliseconds. if let Err(_) = timeout(Duration::from_millis(10), rx).await { println!("did not receive value within 10 ms"); } ``` -------------------------------- ### Create and use an interval_at Source: https://docs.rs/actix/0.13.5/actix/clock/fn.interval_at.html Demonstrates initializing an interval with a start time and period, then awaiting ticks. ```rust use tokio::time::{interval_at, Duration, Instant}; #[tokio::main] async fn main() { let start = Instant::now() + Duration::from_millis(50); let mut interval = interval_at(start, Duration::from_millis(10)); interval.tick().await; // ticks after 50ms interval.tick().await; // ticks after 10ms interval.tick().await; // ticks after 10ms // approximately 70ms have elapsed. } ``` -------------------------------- ### get_or_start_default Source: https://docs.rs/actix/0.13.5/actix/registry/struct.Registry.html Queries the registry for an actor of type A. If the actor is not registered, it starts a new instance and returns its address. ```APIDOC ### pub fn get_or_start_default>>( &self, ) -> Addr Queries the registry for an actor, returning its address. If an actor of type A is not registered, a new actor is started and its address is returned. ``` -------------------------------- ### Examples of using actix_rt::spawn Source: https://docs.rs/actix/0.13.5/actix/fn.spawn.html Demonstrates spawning tasks that resolve successfully, panic, or are cancelled via the JoinHandle. ```rust // task resolves successfully assert_eq!(actix_rt::spawn(async { 1 }).await.unwrap(), 1); // task panics assert!(actix_rt::spawn(async { panic!("panic is caught at task boundary"); }) .await .unwrap_err() .is_panic()); // task is cancelled before completion let handle = actix_rt::spawn(actix_rt::time::sleep(Duration::from_secs(100))); handle.abort(); assert!(handle.await.unwrap_err().is_cancelled()); ``` -------------------------------- ### Actor Initialization Methods Source: https://docs.rs/actix/0.13.5/actix/prelude/trait.Actor.html Static methods used to construct and start actors within the Actix system. ```APIDOC ## fn start(self) -> Addr ### Description Starts a new asynchronous actor and returns its address. ## fn start_default() -> Addr ### Description Constructs a new actor using the `Default` trait and starts it, returning its address. ## fn create(f: F) -> Addr ### Description Starts a new asynchronous actor using a closure that provides the `Context` object during initialization. ``` -------------------------------- ### SyncArbiter::start_with_thread_builder Source: https://docs.rs/actix/0.13.5/actix/sync/struct.SyncArbiter.html Starts a new SyncArbiter with custom thread configuration using a thread builder factory. ```APIDOC ## SyncArbiter::start_with_thread_builder(threads: usize, thread_builder_factory: BF, factory: F) -> Addr ### Description Starts a new `SyncArbiter` with a specified number of worker threads. Each worker thread is configured using a `std::thread::Builder` provided by the `thread_builder_factory`. ### Parameters - **threads** (usize) - Required - The number of worker threads to spawn. - **thread_builder_factory** (BF) - Required - A closure that returns a `std::thread::Builder` for each thread. - **factory** (F) - Required - A closure that returns an instance of the actor (A). ``` -------------------------------- ### fn create(f: F) -> Addr Source: https://docs.rs/actix/0.13.5/actix/trait.Actor.html Starts a new asynchronous actor using a factory function that provides access to the actor's context. ```APIDOC ## fn create(f: F) -> Addr ### Description Starts a new asynchronous actor given a factory function. Use this method if you need the Context object during actor initialization. ### Signature `fn create(f: F) -> Addr where Self: Actor>, F: FnOnce(&mut Context) -> Self` ### Example ```rust use actix::prelude::*; struct MyActor { val: usize, } impl Actor for MyActor { type Context = Context; } #[actix::main] async fn main() { let addr = MyActor::create(|ctx: &mut Context| MyActor { val: 10 }); } ``` ``` -------------------------------- ### Implement Actor with SyncContext Source: https://docs.rs/actix/0.13.5/actix/sync/struct.SyncContext.html Example of using SyncContext as the actor context type. ```rust use actix::prelude::*; struct SyncActor; impl Actor for SyncActor { // It's important to note that you use "SyncContext" here instead of "Context". type Context = SyncContext; } ``` -------------------------------- ### Start a supervised actor Source: https://docs.rs/actix/0.13.5/actix/prelude/struct.Supervisor.html Initializes a new supervised actor in the current tokio runtime. The returned address type can be explicitly defined. ```rust struct MyActor; impl Actor for MyActor { type Context = Context; } // Get `Addr` of a MyActor actor let addr = actix::Supervisor::start(|_| MyActor); ``` -------------------------------- ### Implementing StreamHandler for an Actor Source: https://docs.rs/actix/0.13.5/actix/prelude/trait.StreamHandler.html Example showing how to implement StreamHandler to process stream items and handle completion. ```rust use actix::prelude::*; use futures_util::stream::once; #[derive(Message)] #[rtype(result = "()")] struct Ping; struct MyActor; impl StreamHandler for MyActor { fn handle(&mut self, item: Ping, ctx: &mut Context) { println!("PING"); System::current().stop() } fn finished(&mut self, ctx: &mut Self::Context) { println!("finished"); } } impl Actor for MyActor { type Context = Context; fn started(&mut self, ctx: &mut Context) { Self::add_stream(once(async { Ping }), ctx); } } #[actix::main] async fn main() { MyActor.start(); } ``` -------------------------------- ### SyncArbiter::start Source: https://docs.rs/actix/0.13.5/actix/sync/struct.SyncArbiter.html Starts a new SyncArbiter with a specified number of worker threads and an actor factory. ```APIDOC ## SyncArbiter::start(threads: usize, factory: F) -> Addr ### Description Starts a new `SyncArbiter` with a specified number of worker threads. Returns a single address of the started actor, which is used to communicate with the actors handled by the arbiter. ### Parameters - **threads** (usize) - Required - The number of worker threads to spawn. - **factory** (F) - Required - A closure that returns an instance of the actor (A). ``` -------------------------------- ### SyncArbiter::start Source: https://docs.rs/actix/0.13.5/actix/sync/struct.SyncArbiter.html Starts a SyncArbiter with a specified number of threads and an actor factory, returning an address to the actor pool. ```APIDOC ## SyncArbiter::start ### Description Starts the SyncArbiter with a defined number of threads and an actor factory. It returns an address that can be used to send messages to the pool of hosted Sync Actors. ### Signature `pub fn start(num: usize, factory: F) -> Addr` ### Parameters - **num** (usize) - The number of threads to spawn for the actor pool. - **factory** (F) - A closure or function that returns an instance of the Actor (A). ### Returns - **Addr** - An address to the pool of Sync Actors. ``` -------------------------------- ### SystemRegistry::get Source: https://docs.rs/actix/0.13.5/actix/registry/struct.SystemRegistry.html Retrieves the address of a system service. If the service actor is not currently running, it will be started automatically. ```APIDOC ## pub fn get>>(&mut self) -> Addr ### Description Returns the address of the specified service. If the service actor is not running, it gets started in the system. ### Parameters - **A** (Generic Type) - The actor type that implements `SystemService` and `Actor`. ``` -------------------------------- ### IntervalFunc::new_at Source: https://docs.rs/actix/0.13.5/actix/utils/struct.IntervalFunc.html Constructs a new IntervalFunc that starts at a specific time and then executes at a specified interval. ```APIDOC ## pub fn new_at(start: Instant, interval: Duration, task: F) -> IntervalFunc ### Description Constructs an `IntervalFunc` using the given `start` time, `interval` duration, and `task` function. ### Parameters - **start** (Instant) - The time at which the first execution should occur. - **interval** (Duration) - The time duration between subsequent executions. - **task** (F) - A closure with signature `FnMut(&mut A, &mut A::Context) + 'static` to be executed. ``` -------------------------------- ### Implement Handler with ResponseActFuture Source: https://docs.rs/actix/0.13.5/actix/prelude/type.ResponseActFuture.html Example demonstrating how to return a ResponseActFuture from an actor's message handler to perform async operations. ```rust use actix::prelude::*; #[derive(Message)] #[rtype(result = "Result")] struct Msg; struct MyActor; impl Actor for MyActor { type Context = Context; } impl Handler for MyActor { type Result = ResponseActFuture>; fn handle(&mut self, _: Msg, _: &mut Context) -> Self::Result { Box::pin( async { // Some async computation 42 } .into_actor(self) // converts future to ActorFuture .map(|res, _act, _ctx| { // Do some computation with actor's state or context Ok(res) }), ) } } ``` -------------------------------- ### Supervisor::start Source: https://docs.rs/actix/0.13.5/actix/prelude/struct.Supervisor.html Starts a new actor under the management of a supervisor. The supervisor will monitor the actor and trigger the restarting method if the actor fails. ```APIDOC ## Supervisor::start ### Description Starts a new actor under the management of a supervisor. The supervisor will monitor the actor and trigger the restarting method if the actor fails. ### Signature `pub fn start(f: F) -> Addr where F: FnOnce(&mut Context) -> A + Send, A: Supervised + Actor>` ### Parameters - **f** (FnOnce) - Required - A closure that creates the actor instance. ### Returns - **Addr** - The address of the supervised actor. ``` -------------------------------- ### Implement MessageResponse for ResponseFuture Source: https://docs.rs/actix/0.13.5/actix/prelude/type.ResponseFuture.html Examples demonstrating how to handle different message result types using ResponseFuture within an Actix actor handler. ```rust pub struct MyQuestion{} impl Message for MyQuestion { type Result = Result; } impl Handler for MyActorAsync { type Result = ResponseFuture>; fn handle(&mut self, question: MyQuestion, _ctx: &mut Context) -> Self::Result { Box::pin(async {Ok(5)}) } } ``` ```rust pub struct MyQuestion{} impl Message for MyQuestion { type Result = Option; } impl Handler for MyActorAsync { type Result = ResponseFuture>; fn handle(&mut self, question: MyQuestion, _ctx: &mut Context) -> Self::Result { Box::pin(async {Some(5)}) } } ``` ```rust pub struct MyQuestion{} impl Message for MyQuestion { type Result = u8; } impl Handler for MyActorAsync { type Result = ResponseFuture; fn handle(&mut self, question: MyQuestion, _ctx: &mut Context) -> Self::Result { Box::pin(async {5}) } } ``` -------------------------------- ### Supervisor::start_in_arbiter Source: https://docs.rs/actix/0.13.5/actix/prelude/struct.Supervisor.html Starts a new supervised actor in a specific arbiter's thread. ```APIDOC ## pub fn start_in_arbiter(sys: &ArbiterHandle, f: F) -> Addr ### Description Starts a new supervised actor within the thread managed by the specified ArbiterHandle. ### Parameters - **sys** (&ArbiterHandle) - Required - The handle to the arbiter where the actor will run. - **f** (FnOnce(&mut Context) -> A) - Required - A factory function that creates the actor instance. ### Returns - **Addr** - The address of the newly created supervised actor. ``` -------------------------------- ### Mocker Handler Implementation Source: https://docs.rs/actix/0.13.5/actix/prelude/trait.Handler.html Example implementation of the Handler trait for the Mocker struct. ```rust impl Handler for Mocker where M: Message + 'static, ::Result: MessageResponse, M>, Source§ #### type Result = ::Result ``` -------------------------------- ### Implementing ActorFuture in a Handler Source: https://docs.rs/actix/0.13.5/actix/fut/future/trait.ActorFuture.html Example of using ActorFuture to defer work to another actor and update the initiating actor's state upon completion. ```rust use actix::prelude::*; // The response type returned by the actor future type OriginalActorResponse = (); // The error type returned by the actor future type MessageError = (); // This is the needed result for the DeferredWork message // It's a result that combine both Response and Error from the future response. type DeferredWorkResult = Result; impl Handler for OriginalActor { // Notice the `Response` is an `ActorFuture`-ized version of `Self::Message::Result`. type Result = ResponseActFuture; fn handle(&mut self, _msg: DeferredWork, _ctx: &mut Context) -> Self::Result { // this creates a `Future` representing the `.send` and subsequent // `Result` from `other_actor` let update_self = self.other_actor .send(OtherMessage {}) // Wrap that future so chained handlers can access the actor // (`self` in the synchronous code) as well as the context. .into_actor(self) // once the wrapped future resolves, update this actor's state .map(|result, actor, _ctx| { match result { Ok(v) => { // update actor (self) state actor.inner_state.update_from(v); Ok(()) }, // Failed to send message to other_actor Err(_e) => Err(()), } }); // box and return the wrapped future Box::pin(update_self) } } ``` -------------------------------- ### Arbiter::new Source: https://docs.rs/actix/0.13.5/actix/prelude/struct.Arbiter.html Spawns a new Arbiter thread and starts its event loop. Panics if a System is not registered on the current thread. ```APIDOC ## pub fn new() -> Arbiter ### Description Spawn a new Arbiter thread and start its event loop. ### Panics Panics if a System is not registered on the current thread. ``` -------------------------------- ### Using TimerFunc in an Actor Source: https://docs.rs/actix/0.13.5/actix/utils/struct.TimerFunc.html Example of spawning a delayed function into an actor's context using TimerFunc. ```rust use std::time::Duration; use actix::prelude::*; use actix::utils::TimerFunc; struct MyActor; impl MyActor { fn stop(&mut self, context: &mut Context) { System::current().stop(); } } impl Actor for MyActor { type Context = Context; fn started(&mut self, context: &mut Context) { // spawn a delayed future into our context TimerFunc::new(Duration::from_millis(100), Self::stop) .spawn(context); } } ``` -------------------------------- ### actix::run(f: R) -> Result<()> Source: https://docs.rs/actix/0.13.5/actix/fn.run.html Starts the actix system and executes the supplied future. The function blocks the current thread until the system shuts down via System::current().stop(). ```APIDOC ## fn run(f: R) -> Result<()> ### Description Starts the actix system and executes the supplied future. This function creates and starts the system with default configuration, spawns the future onto the current arbiter, and blocks the current thread until the system shuts down. ### Signature `pub fn run(f: R) -> Result<()> where R: Future + 'static` ### Parameters - **f** (R) - Required - A future that implements `Future + 'static` to be executed by the system. ### Panics This function will panic if the actix system is already running. ### Example ```rust use std::time::{Duration, Instant}; use actix_rt::time::sleep; fn main() { actix::run(async move { sleep(Duration::from_millis(100)).await; actix::System::current().stop(); }); } ``` ``` -------------------------------- ### Create a failed future with actix::fut::err Source: https://docs.rs/actix/0.13.5/actix/fut/future/result/fn.err.html Initializes a future that resolves immediately to an error result. Requires the actix crate and appropriate actor context setup. ```rust pub fn err(e: E) -> Ready> ⓘ ``` ```rust use actix::{fut, Actor, Context}; struct MyActor; impl Actor for MyActor { type Context = Context; } let future_of_err_1 = fut::err::(1); ``` -------------------------------- ### Using SystemRegistry with SystemService Source: https://docs.rs/actix/0.13.5/actix/registry/struct.SystemRegistry.html Demonstrates how to implement SystemService and interact with it using the registry. ```rust use actix::prelude::*;\n\n#[derive(Message)]\n#[rtype(result = "()")]\nstruct Ping;\n\n#[derive(Default)]\nstruct MyActor1;\n\nimpl Actor for MyActor1 {\n type Context = Context;\n}\nimpl actix::Supervised for MyActor1 {}\n\nimpl SystemService for MyActor1 {\n fn service_started(&mut self, ctx: &mut Context) {\n println!("Service started");\n }\n}\n\nimpl Handler for MyActor1 {\n type Result = ();\n\n fn handle(&mut self, _: Ping, ctx: &mut Context) {\n println!("ping");\n }\n}\n\nstruct MyActor2;\n\nimpl Actor for MyActor2 {\n type Context = Context;\n\n fn started(&mut self, _: &mut Context) {\n let act = MyActor1::from_registry();\n act.do_send(Ping);\n }\n}\n\n#[actix::main]\nasync fn main() {\n // Start MyActor2\n let addr = MyActor2.start();\n} ``` -------------------------------- ### System::new Source: https://docs.rs/actix/0.13.5/actix/prelude/struct.System.html Creates a new system. Panics if the underlying Tokio runtime cannot be created. ```APIDOC ### pub fn new() -> SystemRunner Creates a new system. Panics if the underlying Tokio runtime can not be created. ``` -------------------------------- ### interval_at(start: Instant, period: Duration) -> Interval Source: https://docs.rs/actix/0.13.5/actix/clock/fn.interval_at.html Creates a new Interval that yields with an interval of period with the first tick completing at start. The default MissedTickBehavior is Burst, which can be configured via set_missed_tick_behavior. ```APIDOC ## interval_at(start: Instant, period: Duration) -> Interval ### Description Creates a new `Interval` that yields with an interval of `period` with the first tick completing at `start`. The interval ticks indefinitely until the `Interval` value is dropped. ### Parameters - **start** (Instant) - The time at which the first tick completes. - **period** (Duration) - The duration between subsequent ticks. ### Panics This function panics if `period` is zero. ### Example ```rust use tokio::time::{interval_at, Duration, Instant}; #[tokio::main] async fn main() { let start = Instant::now() + Duration::from_millis(50); let mut interval = interval_at(start, Duration::from_millis(10)); interval.tick().await; // ticks after 50ms interval.tick().await; // ticks after 10ms interval.tick().await; // ticks after 10ms } ``` ``` -------------------------------- ### as_mut Source: https://docs.rs/actix/0.13.5/actix/prelude/type.ResponseFuture.html Gets a mutable reference to the pinned value this Pin points to. ```APIDOC ## pub fn as_mut(&mut self) -> Pin<&mut ::Target> ### Description Gets a mutable reference to the pinned value this Pin points to. This is useful when doing multiple calls to functions that consume the pinning pointer. ``` -------------------------------- ### #[main] Source: https://docs.rs/actix/0.13.5/actix/attr.main.html Marks an async main function as the actix system entry-point. ```APIDOC ## #[main] ### Description Marks an async main function as the `actix` system entry-point. This macro is available only when the `macros` feature flag is enabled. ### Usage ```rust #[actix::main] async fn main() { println!("Hello world"); } ``` ``` -------------------------------- ### as_ref Source: https://docs.rs/actix/0.13.5/actix/prelude/type.ResponseFuture.html Gets a shared reference to the pinned value this Pin points to. ```APIDOC ## pub fn as_ref(&self) -> Pin<&::Target> ### Description Gets a shared reference to the pinned value this Pin points to. This is a safe way to go from &Pin> to Pin<&T>. ``` -------------------------------- ### Create an actor with context Source: https://docs.rs/actix/0.13.5/actix/prelude/trait.Actor.html Shows how to initialize an actor using the create method, which provides access to the actor's context during construction. ```rust use actix::prelude::*;\n\nstruct MyActor {\n val: usize,\n}\nimpl Actor for MyActor {\n type Context = Context;\n}\n\n#[actix::main]\nasync fn main() {\n let addr = MyActor::create(|ctx: &mut Context| MyActor { val: 10 });\n} ``` -------------------------------- ### System::with_tokio_rt Source: https://docs.rs/actix/0.13.5/actix/prelude/struct.System.html Creates a new System using the Tokio Runtime returned from a closure. ```APIDOC ### pub fn with_tokio_rt(runtime_factory: F) -> SystemRunner where F: FnOnce() -> Runtime Create a new System using the Tokio Runtime returned from a closure. ``` -------------------------------- ### as_deref_mut Source: https://docs.rs/actix/0.13.5/actix/prelude/type.ResponseFuture.html Gets Pin<&mut T> to the underlying pinned value from this nested Pin-pointer. ```APIDOC ## pub fn as_deref_mut(self: Pin<&mut Pin>) -> Pin<&mut ::Target> ### Description Gets Pin<&mut T> to the underlying pinned value from this nested Pin-pointer. ``` -------------------------------- ### Arbiter::try_current Source: https://docs.rs/actix/0.13.5/actix/struct.Arbiter.html Attempts to get the current running arbiter handle without panicking. ```APIDOC ## pub fn try_current() -> Option ### Description Try to get current running arbiter handle. Returns None if no Arbiter has been started. ``` -------------------------------- ### Create and run a new Context Source: https://docs.rs/actix/0.13.5/actix/prelude/struct.Context.html Demonstrates creating a context without spawning it and then running an actor within it. ```rust struct Actor1 { actor2_addr: Addr, } struct Actor2 { actor1_addr: Addr, } let ctx1 = Context::::new(); let ctx2 = Context::::new(); let actor1 = Actor1 { actor2_addr: ctx2.address() }; let actor2 = Actor2 { actor1_addr: ctx1.address() }; ctx1.run(actor1); ctx2.run(actor2); ``` -------------------------------- ### System::current Source: https://docs.rs/actix/0.13.5/actix/prelude/struct.System.html Retrieves the currently running system. Panics if no system is registered on the current thread. ```APIDOC ### pub fn current() -> System Get current running system. Panics if no system is registered on the current thread. ``` -------------------------------- ### Set mailbox capacity Source: https://docs.rs/actix/0.13.5/actix/prelude/struct.Context.html Configures the mailbox capacity for an actor within its started lifecycle method. ```rust struct MyActor; impl Actor for MyActor { type Context = Context; fn started(&mut self, ctx: &mut Self::Context) { ctx.set_mailbox_capacity(1); System::current().stop(); } } let addr = sys.block_on(async { MyActor.start() }); sys.run(); ``` -------------------------------- ### Implement MessageResult in an Actor Source: https://docs.rs/actix/0.13.5/actix/prelude/struct.MessageResult.html Example showing how to use MessageResult as the return type for a message handler. ```rust use actix::prelude::*; #[derive(Message)] #[rtype(Response)] struct Msg; struct Response; struct MyActor; impl Actor for MyActor { type Context = Context; } impl Handler for MyActor { type Result = MessageResult; fn handle(&mut self, _: Msg, _: &mut Context) -> Self::Result { MessageResult(Response {}) } } ``` -------------------------------- ### Create Response instances Source: https://docs.rs/actix/0.13.5/actix/prelude/struct.Response.html Methods for creating asynchronous and synchronous responses. ```rust pub fn fut(fut: T) -> Self where T: Future + 'static, ``` ```rust pub fn reply(val: I) -> Self ``` -------------------------------- ### Writer::handle Source: https://docs.rs/actix/0.13.5/actix/io/struct.Writer.html Returns the SpawnHandle for this writer. ```APIDOC ### pub fn handle(&self) -> SpawnHandle Returns the SpawnHandle associated with the writer. ``` -------------------------------- ### Basic usage of interval Source: https://docs.rs/actix/0.13.5/actix/clock/fn.interval.html Demonstrates creating an interval and awaiting ticks, where the first tick completes immediately. ```rust use tokio::time::{self, Duration}; #[tokio::main] async fn main() { let mut interval = time::interval(Duration::from_millis(10)); interval.tick().await; // ticks immediately interval.tick().await; // ticks after 10ms interval.tick().await; // ticks after 10ms // approximately 20ms have elapsed. } ``` -------------------------------- ### Create an Instant Source: https://docs.rs/actix/0.13.5/actix/clock/struct.Instant.html Obtain the current time as an Instant. ```rust use tokio::time::Instant; let now = Instant::now(); ``` -------------------------------- ### System::try_current Source: https://docs.rs/actix/0.13.5/actix/prelude/struct.System.html Attempts to retrieve the currently running system without panicking. ```APIDOC ### pub fn try_current() -> Option Try to get current running system. Returns None if no System has been started. ``` -------------------------------- ### Context::run Source: https://docs.rs/actix/0.13.5/actix/struct.Context.html Spawns an actor into the context and returns its address. ```APIDOC ## pub fn run(self, act: A) -> Addr ### Description Spawns the provided actor into the context and returns an address to communicate with it. ``` -------------------------------- ### Define Actix main entry-point Source: https://docs.rs/actix/0.13.5/actix/attr.main.html Marks an async main function as the Actix system entry-point. Requires the macros feature flag. ```rust #[main] ``` ```rust #[actix::main] async fn main() { println!("Hello world"); } ``` -------------------------------- ### #[actix::test] Source: https://docs.rs/actix/0.13.5/actix/attr.test.html Marks an async test function to use the actix system entry-point. This macro is available when the 'macros' feature flag is enabled. ```APIDOC ## #[actix::test] ### Description Marks async test functions to use the `actix` system entry-point. This macro is required for testing asynchronous code within the Actix framework. ### Usage Apply the attribute to an `async fn` test function. ### Example ```rust #[actix::test] async fn my_test() { assert!(true); } ``` ``` -------------------------------- ### Handle Message with Option Source: https://docs.rs/actix/0.13.5/actix/dev/trait.MessageResponse.html Demonstrates implementing a handler that returns an Option using ResponseFuture. ```rust pub struct MyQuestion{} impl Message for MyQuestion { type Result = Option; } impl Handler for MyActorAsync { type Result = ResponseFuture>; fn handle(&mut self, question: MyQuestion, _ctx: &mut Context) -> Self::Result { Box::pin(async {Some(5)}) } } ``` -------------------------------- ### Implementing AtomicResponse in a Handler Source: https://docs.rs/actix/0.13.5/actix/prelude/struct.AtomicResponse.html Example of using AtomicResponse within a Handler to ensure exclusive state access during asynchronous operations. ```rust impl Handler for MyActor { type Result = AtomicResponse; fn handle(&mut self, _: Msg, _: &mut Context) -> Self::Result { AtomicResponse::new(Box::pin( async {} .into_actor(self) .map(|_, this, _| { this.0 = 30; }) .then(|_, this, _| { sleep(Duration::from_secs(3)).into_actor(this) }) .map(|_, this, _| { this.0 -= 1; this.0 }), )) } } ``` -------------------------------- ### Writer::new Source: https://docs.rs/actix/0.13.5/actix/io/struct.Writer.html Creates a new instance of the Writer. ```APIDOC ### pub fn new(io: T, ctx: &mut C) -> Self Creates a new Writer instance wrapping an AsyncWrite type. ``` -------------------------------- ### Actor Trait Definition Source: https://docs.rs/actix/0.13.5/actix/prelude/trait.Actor.html The Actor trait requires implementation of an ActorContext and provides default lifecycle hooks and methods for starting actors. ```rust pub trait Actor: Sized + Unpin + 'static { type Context: ActorContext; // Provided methods fn started(&mut self, ctx: &mut Self::Context) { ... } fn stopping(&mut self, ctx: &mut Self::Context) -> Running { ... } fn stopped(&mut self, ctx: &mut Self::Context) { ... } fn start(self) -> Addr where Self: Actor> { ... } fn start_default() -> Addr where Self: Actor> + Default { ... } fn start_in_arbiter(wrk: &ArbiterHandle, f: F) -> Addr where Self: Actor>, F: FnOnce(&mut Context) -> Self + Send + 'static { ... } fn create(f: F) -> Addr where Self: Actor>, F: FnOnce(&mut Context) -> Self { ... } } ``` -------------------------------- ### Import Actix Dev Prelude Source: https://docs.rs/actix/0.13.5/actix/dev/index.html Use this glob import to bring common Actix traits into scope for library development. ```rust use actix::dev::*; ``` -------------------------------- ### ready(t: T) -> Ready Source: https://docs.rs/actix/0.13.5/actix/fut/fn.ready.html Creates a future that is immediately ready with a value. ```APIDOC ## ready(t: T) -> Ready ### Description Creates a future that is immediately ready with a value. ### Signature `pub fn ready(t: T) -> Ready` ### Example ```rust use futures::future; let a = future::ready(1); assert_eq!(a.await, 1); ``` ``` -------------------------------- ### Importing the Actix Prelude Source: https://docs.rs/actix/0.13.5/actix/prelude/index.html Use this glob import at the top of modules to access common Actix traits and types. ```rust use actix::prelude::*; ``` -------------------------------- ### pub fn upgrade(&self) -> Option> Source: https://docs.rs/actix/0.13.5/actix/struct.WeakAddr.html Attempts to upgrade the WeakAddr pointer to an Addr. Returns None if the actor has been dropped or the address is disconnected. ```APIDOC ## pub fn upgrade(&self) -> Option> ### Description Attempts to upgrade the `WeakAddr` pointer to an `Addr`. Returns `None` if the actor has since been dropped or the underlying address is disconnected. ``` -------------------------------- ### fn spawn(f: Fut) -> JoinHandle<::Output> Source: https://docs.rs/actix/0.13.5/actix/fn.spawn.html Spawns a future on the current thread as a new task. The task can be cancelled via the returned JoinHandle, and panics within the future are caught. ```APIDOC ## fn spawn(f: Fut) -> JoinHandle<::Output> ### Description Spawns a future on the current thread as a new task. If not immediately awaited, the task can be cancelled using `JoinHandle::abort`. The provided future is spawned as a new task; therefore, panics are caught. ### Signature `pub fn spawn(f: Fut) -> JoinHandle<::Output>` ### Constraints - `Fut`: Future + 'static - `::Output`: 'static ### Panics Panics if the Actix system is not running. ### Example ```rust // task resolves successfully assert_eq!(actix_rt::spawn(async { 1 }).await.unwrap(), 1); // task panics assert!(actix_rt::spawn(async { panic!("panic is caught at task boundary"); }) .await .unwrap_err() .is_panic()); // task is cancelled before completion let handle = actix_rt::spawn(actix_rt::time::sleep(Duration::from_secs(100))); handle.abort(); assert!(handle.await.unwrap_err().is_cancelled()); ``` ``` -------------------------------- ### ok(t: T) -> Ready> Source: https://docs.rs/actix/0.13.5/actix/fut/future/result/index.html Creates a leaf future from an immediate value of a finished and successful computation. ```APIDOC ## ok(t: T) ### Description Creates a "leaf future" from an immediate value of a finished and successful computation. ### Parameters - **t** (T) - Required - The success value to be returned by the future. ``` -------------------------------- ### Demonstrate unsafe pinning with Rc Source: https://docs.rs/actix/0.13.5/actix/fut/future/type.LocalBoxActorFuture.html Illustrates how creating a Pin from an Rc can lead to undefined behavior due to potential aliasing and mutable access after dropping the pin. ```rust use std::rc::Rc; use std::pin::Pin; fn move_pinned_rc(mut x: Rc) { // This should mean the pointee can never move again. let pin = unsafe { Pin::new_unchecked(Rc::clone(&x)) }; { let p: Pin<&T> = pin.as_ref(); // ... } drop(pin); let content = Rc::get_mut(&mut x).unwrap(); // Potential UB down the road ⚠️ // Now, if `x` was the only reference, we have a mutable reference to // data that we pinned above, which we could use to move it as we have // seen in the previous example. We have violated the pinning API contract. } ``` -------------------------------- ### Envelope Constructor Methods Source: https://docs.rs/actix/0.13.5/actix/dev/struct.Envelope.html Methods for creating new Envelope instances, including standard message creation and proxy-based creation. ```rust pub fn new(msg: M, tx: Option>) -> Self where A: Handler, A::Context: AsyncContext, M: Message + Send + 'static, M::Result: Send, ``` ```rust pub fn with_proxy(proxy: Box + Send>) -> Self ``` -------------------------------- ### Safely pin closures using the pin! macro Source: https://docs.rs/actix/0.13.5/actix/fut/future/type.LocalBoxActorFuture.html Shows the recommended approach for pinning futures within closures by using the pin! macro to avoid unsafe pinning. ```rust use std::pin::pin; use std::task::Context; use std::future::Future; fn move_pinned_closure(mut x: impl Future, cx: &mut Context<'_>) { let mut x = pin!(x); // Create a closure that captures `x: Pin<&mut _>`, which is safe to move. let mut closure = move || { let _ignore = x.as_mut().poll(cx); }; // Call the closure, so the future can assume it has been pinned. closure(); // Move the closure somewhere else. let mut moved = closure; // Calling it again here is fine (except that we might be polled a future that already // returned `Poll::Ready`, but that is a separate problem). moved(); } ``` -------------------------------- ### SystemRegistry::set Source: https://docs.rs/actix/0.13.5/actix/registry/struct.SystemRegistry.html Registers a new actor in the system registry using its address. ```APIDOC ## pub fn set>>(addr: Addr) ### Description Adds a new actor to the registry by its address. This method will panic if the actor is already running. ### Parameters - **addr** (Addr) - The address of the actor to register. ``` -------------------------------- ### Define and use an ArbiterService Source: https://docs.rs/actix/0.13.5/actix/registry/struct.Registry.html Demonstrates defining an actor as an ArbiterService and accessing it from the registry within a separate Arbiter. ```rust use actix::prelude::*; #[derive(Message)] #[rtype(result = "()")] struct Ping; #[derive(Default)] struct MyActor1; impl Actor for MyActor1 { type Context = Context; } impl actix::Supervised for MyActor1 {} impl ArbiterService for MyActor1 { fn service_started(&mut self, ctx: &mut Context) { println!("Service started"); } } impl Handler for MyActor1 { type Result = (); fn handle(&mut self, _: Ping, ctx: &mut Context) { println!("ping"); } } struct MyActor2; impl Actor for MyActor2 { type Context = Context; fn started(&mut self, _: &mut Context) { // get MyActor1 address from the registry let act = MyActor1::from_registry(); act.do_send(Ping); } } #[actix::main] async fn main() { // Start MyActor2 in new Arbiter Arbiter::new().spawn_fn(|| { MyActor2.start(); }); } ``` -------------------------------- ### Construct Pin with Unpin type Source: https://docs.rs/actix/0.13.5/actix/fut/future/type.LocalBoxActorFuture.html Demonstrates creating a Pin for a type that implements Unpin. ```rust use std::pin::Pin; let mut val: u8 = 5; // Since `val` doesn't care about being moved, we can safely create a "facade" `Pin` // which will allow `val` to participate in `Pin`-bound apis without checking that // pinning guarantees are actually upheld. let mut pinned: Pin<&mut u8> = Pin::new(&mut val); ``` -------------------------------- ### Demonstrate unsafe pinning with mutable references Source: https://docs.rs/actix/0.13.5/actix/fut/future/type.LocalBoxActorFuture.html Illustrates how creating a Pin from a mutable reference can lead to undefined behavior if the value is moved after pinning. ```rust use std::mem; use std::pin::Pin; fn move_pinned_ref(mut a: T, mut b: T) { unsafe { let p: Pin<&mut T> = Pin::new_unchecked(&mut a); // This should mean the pointee `a` can never move again. } mem::swap(&mut a, &mut b); // Potential UB down the road ⚠️ // The address of `a` changed to `b`'s stack slot, so `a` got moved even // though we have previously pinned it! We have violated the pinning API contract. } ``` -------------------------------- ### Use with select! Source: https://docs.rs/actix/0.13.5/actix/clock/struct.Sleep.html Demonstrates pinning a Sleep instance to use it within a select! loop. ```rust use tokio::time::{self, Duration, Instant}; #[tokio::main] async fn main() { let sleep = time::sleep(Duration::from_millis(10)); tokio::pin!(sleep); loop { tokio::select! { () = &mut sleep => { println!("timer elapsed"); sleep.as_mut().reset(Instant::now() + Duration::from_millis(50)); }, } } } ``` -------------------------------- ### Registering a stream with add_stream Source: https://docs.rs/actix/0.13.5/actix/prelude/trait.AsyncContext.html Demonstrates how to register a stream with an actor's context using add_stream, allowing the actor to process stream items as messages. ```rust use actix::prelude::*; use futures_util::stream::once; #[derive(Message)] #[rtype(result = "()")] struct Ping; struct MyActor; impl StreamHandler for MyActor { fn handle(&mut self, item: Ping, ctx: &mut Context) { println!("PING"); System::current().stop(); } fn finished(&mut self, ctx: &mut Self::Context) { println!("finished"); } } impl Actor for MyActor { type Context = Context; fn started(&mut self, ctx: &mut Context) { // add stream ctx.add_stream(once(async { Ping })); } } fn main() { let mut sys = System::new(); let addr = sys.block_on(async { MyActor.start() }); sys.run(); } ``` -------------------------------- ### Addr::downgrade Source: https://docs.rs/actix/0.13.5/actix/struct.Addr.html Returns a downgraded WeakAddr. ```APIDOC ### pub fn downgrade(&self) -> WeakAddr Returns a downgraded WeakAddr. ``` -------------------------------- ### Create a leaf future from a Result Source: https://docs.rs/actix/0.13.5/actix/fut/future/result/fn.result.html Demonstrates creating futures that resolve immediately with either Ok or Err values using the actix::fut::result function. ```rust use actix::{fut, Actor, Context}; struct MyActor; impl Actor for MyActor { type Context = Context; } let future_of_1 = fut::result::(Ok(1)); let future_of_err_2 = fut::result::(Err(2)); ``` -------------------------------- ### Response::fut Source: https://docs.rs/actix/0.13.5/actix/prelude/struct.Response.html Creates an asynchronous response from a future. ```APIDOC ## pub fn fut(fut: T) -> Self ### Description Creates an asynchronous response from a provided future. ### Parameters - **fut** (T) - Required - A future that resolves to the response type I, where T: Future + 'static. ```