├── macros-test ├── tests │ ├── fail │ │ └── .gitkeep │ ├── pass │ │ ├── basic.rs │ │ └── generics.rs │ └── ui.rs ├── src │ └── lib.rs ├── Cargo.toml └── README.md ├── .gitignore ├── xtra ├── examples │ ├── basic_wasm_bindgen │ │ ├── test.sh │ │ ├── README.md │ │ ├── tests │ │ │ └── web.rs │ │ ├── Cargo.toml │ │ └── src │ │ │ └── lib.rs │ ├── basic_tokio.rs │ ├── basic_async_std.rs │ ├── basic_smol.rs │ ├── send_interval.rs │ ├── address_sink.rs │ ├── scoped_actor_task.rs │ ├── manual_actor_impl.rs │ ├── interleaved_messages.rs │ ├── message_stealing_multiple_actors.rs │ ├── custom_event_loop.rs │ ├── backpressure.rs │ └── crude_bench.rs ├── src │ ├── instrumentation.rs │ ├── instrumentation │ │ ├── stub.rs │ │ └── tracing.rs │ ├── chan │ │ ├── priority.rs │ │ ├── waiting_sender.rs │ │ ├── waiting_receiver.rs │ │ └── ptr.rs │ ├── scoped_task.rs │ ├── spawn.rs │ ├── context.rs │ ├── mailbox.rs │ ├── dispatch_future.rs │ ├── recv_future.rs │ ├── envelope.rs │ ├── lib.rs │ ├── address.rs │ ├── send_future.rs │ ├── message_channel.rs │ └── chan.rs ├── tests │ ├── public_api.rs │ └── instrumentation.rs ├── benches │ └── throughput.rs └── Cargo.toml ├── Cargo.toml ├── .cargo └── config.toml ├── .github ├── dependabot.yml └── workflows │ └── ci.yml ├── macros ├── Cargo.toml └── src │ └── lib.rs ├── LICENSE-ACTIX ├── README.md ├── BREAKING-CHANGES.md └── LICENSE /macros-test/tests/fail/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | **/*.rs.bk 3 | .idea/ 4 | *.iml 5 | -------------------------------------------------------------------------------- /xtra/examples/basic_wasm_bindgen/test.sh: -------------------------------------------------------------------------------- 1 | wasm-pack test --headless --firefox -------------------------------------------------------------------------------- /macros-test/src/lib.rs: -------------------------------------------------------------------------------- 1 | pub fn assert_actor() 2 | where 3 | A: xtra::Actor, 4 | { 5 | } 6 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [workspace] 2 | members = ["xtra/examples/basic_wasm_bindgen", "macros", "macros-test", "xtra"] 3 | resolver = "2" 4 | -------------------------------------------------------------------------------- /macros-test/tests/pass/basic.rs: -------------------------------------------------------------------------------- 1 | #[derive(xtra::Actor)] 2 | struct MyActor; 3 | 4 | fn main() { 5 | macros_test::assert_actor::() 6 | } 7 | -------------------------------------------------------------------------------- /xtra/examples/basic_wasm_bindgen/README.md: -------------------------------------------------------------------------------- 1 | # xtra wasm-bindgen example 2 | 3 | Run tests with `wasm-pack test --headless --firefox`, or run `./test.sh` on Linux. -------------------------------------------------------------------------------- /macros-test/tests/ui.rs: -------------------------------------------------------------------------------- 1 | #[test] 2 | fn ui() { 3 | let t = trybuild::TestCases::new(); 4 | t.pass("tests/pass/*.rs"); 5 | t.compile_fail("tests/fail/*.rs"); 6 | } 7 | -------------------------------------------------------------------------------- /.cargo/config.toml: -------------------------------------------------------------------------------- 1 | [alias] 2 | custom-fmt = "fmt -- --config group_imports=StdExternalCrate --config imports_granularity=module" 3 | check-custom-fmt = "fmt -- --check --config group_imports=StdExternalCrate --config imports_granularity=module" 4 | -------------------------------------------------------------------------------- /macros-test/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "macros-test" 3 | version = "0.1.0" 4 | edition = "2021" 5 | publish = false 6 | 7 | [dependencies] 8 | xtra = { path = "../xtra", features = ["macros"] } 9 | 10 | [dev-dependencies] 11 | trybuild = "1.0.64" 12 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: "cargo" 4 | directory: "/" 5 | schedule: 6 | interval: "daily" 7 | 8 | - package-ecosystem: "github-actions" 9 | directory: "/" 10 | schedule: 11 | interval: "daily" 12 | -------------------------------------------------------------------------------- /xtra/src/instrumentation.rs: -------------------------------------------------------------------------------- 1 | #[cfg(feature = "instrumentation")] 2 | mod tracing; 3 | 4 | #[cfg(feature = "instrumentation")] 5 | pub use self::tracing::*; 6 | 7 | #[cfg(not(feature = "instrumentation"))] 8 | mod stub; 9 | 10 | #[cfg(not(feature = "instrumentation"))] 11 | pub use self::stub::*; 12 | -------------------------------------------------------------------------------- /xtra/examples/basic_wasm_bindgen/tests/web.rs: -------------------------------------------------------------------------------- 1 | //! Test suite for the Web and headless browsers. 2 | 3 | #![cfg(target_arch = "wasm32")] 4 | 5 | extern crate wasm_bindgen_test; 6 | use wasm_bindgen_test::*; 7 | 8 | wasm_bindgen_test_configure!(run_in_browser); 9 | 10 | #[wasm_bindgen_test] 11 | async fn pass() { 12 | basic_wasm_bindgen::start().await.unwrap(); 13 | } 14 | -------------------------------------------------------------------------------- /macros/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "xtra-macros" 3 | version = "0.6.0" 4 | edition = "2021" 5 | license = "MPL-2.0" 6 | repository = "https://github.com/Restioson/xtra" 7 | description = "Helper macros for the xtra crate" 8 | documentation = "https://docs.rs/xtra-macros" 9 | 10 | [lib] 11 | proc-macro = true 12 | 13 | [dependencies] 14 | syn = "1" 15 | quote = "1" 16 | proc-macro2 = "1" 17 | -------------------------------------------------------------------------------- /macros-test/README.md: -------------------------------------------------------------------------------- 1 | # macros-test 2 | 3 | This is a testing crate for the macros provided by xtra as they are re-exported from the main `xtra` library. 4 | 5 | Moving the tests into a separate crate allows us to define test utils in the crate's `lib.rs` file and ensures the user-facing public macro API is as we expect. 6 | Users are meant to access the macros through the main `xtra` crate. 7 | The `xtra-macros` crate is an implementation detail that is enforced by `cargo` because proc-macros need to be in their own crate. 8 | -------------------------------------------------------------------------------- /xtra/examples/basic_wasm_bindgen/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "basic-wasm-bindgen" 3 | version = "0.1.0" 4 | authors = ["stoically "] 5 | edition = "2018" 6 | 7 | [lib] 8 | crate-type = ["cdylib", "rlib"] 9 | 10 | [dependencies] 11 | wasm-bindgen = { version = "0.2.81", default-features = false } 12 | wasm-bindgen-futures = { version = "0.4.13", default-features = false } 13 | xtra = { path = "../..", features = ["wasm_bindgen", "macros"] } 14 | 15 | [dev-dependencies] 16 | wasm-bindgen-test = { version = "0.3.13", default-features = false } 17 | console_error_panic_hook = "0.1.5" # First version that works on stable 18 | -------------------------------------------------------------------------------- /xtra/examples/basic_tokio.rs: -------------------------------------------------------------------------------- 1 | use xtra::prelude::*; 2 | 3 | #[derive(Default, xtra::Actor)] 4 | struct Printer { 5 | times: usize, 6 | } 7 | 8 | struct Print(String); 9 | 10 | impl Handler for Printer { 11 | type Return = (); 12 | 13 | async fn handle(&mut self, print: Print, _ctx: &mut Context) { 14 | self.times += 1; 15 | println!("Printing {}. Printed {} times so far.", print.0, self.times); 16 | } 17 | } 18 | 19 | #[tokio::main] 20 | async fn main() { 21 | let addr = xtra::spawn_tokio(Printer::default(), Mailbox::unbounded()); 22 | loop { 23 | addr.send(Print("hello".to_string())) 24 | .await 25 | .expect("Printer should not be dropped"); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /macros-test/tests/pass/generics.rs: -------------------------------------------------------------------------------- 1 | #[derive(xtra::Actor)] 2 | struct MyActor { 3 | phantom: std::marker::PhantomData<(A, B)> 4 | } 5 | 6 | #[derive(xtra::Actor)] 7 | struct MyActorWithBounds { 8 | phantom: std::marker::PhantomData<(A, B)> 9 | } 10 | 11 | #[derive(xtra::Actor)] 12 | struct MyActorWithWhere where A: Bar { 13 | phantom: std::marker::PhantomData<(A, B)> 14 | } 15 | 16 | struct Foo; 17 | 18 | trait Bar { } 19 | 20 | impl Bar for &'static str { 21 | 22 | } 23 | 24 | fn main() { 25 | macros_test::assert_actor::>(); 26 | macros_test::assert_actor::>(); 27 | macros_test::assert_actor::>(); 28 | } 29 | -------------------------------------------------------------------------------- /xtra/examples/basic_async_std.rs: -------------------------------------------------------------------------------- 1 | use xtra::prelude::*; 2 | 3 | #[derive(Default, xtra::Actor)] 4 | struct Printer { 5 | times: usize, 6 | } 7 | 8 | struct Print(String); 9 | 10 | impl Handler for Printer { 11 | type Return = (); 12 | 13 | async fn handle(&mut self, print: Print, _ctx: &mut Context) { 14 | self.times += 1; 15 | println!("Printing {}. Printed {} times so far.", print.0, self.times); 16 | } 17 | } 18 | 19 | #[async_std::main] 20 | async fn main() { 21 | let addr = xtra::spawn_async_std(Printer::default(), Mailbox::unbounded()); 22 | loop { 23 | addr.send(Print("hello".to_string())) 24 | .await 25 | .expect("Printer should not be dropped"); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /xtra/examples/basic_smol.rs: -------------------------------------------------------------------------------- 1 | use xtra::prelude::*; 2 | 3 | #[derive(Default, xtra::Actor)] 4 | struct Printer { 5 | times: usize, 6 | } 7 | 8 | struct Print(String); 9 | 10 | impl Handler for Printer { 11 | type Return = (); 12 | 13 | async fn handle(&mut self, print: Print, _ctx: &mut Context) { 14 | self.times += 1; 15 | println!("Printing {}. Printed {} times so far.", print.0, self.times); 16 | } 17 | } 18 | 19 | fn main() { 20 | smol::block_on(async { 21 | let addr = xtra::spawn_smol(Printer::default(), Mailbox::unbounded()); 22 | 23 | loop { 24 | addr.send(Print("hello".to_string())) 25 | .await 26 | .expect("Printer should not be dropped"); 27 | } 28 | }) 29 | } 30 | -------------------------------------------------------------------------------- /xtra/examples/basic_wasm_bindgen/src/lib.rs: -------------------------------------------------------------------------------- 1 | use wasm_bindgen::prelude::*; 2 | use wasm_bindgen::JsValue; 3 | use xtra::prelude::*; 4 | 5 | #[derive(xtra::Actor)] 6 | struct Echoer; 7 | 8 | struct Echo(String); 9 | 10 | impl Handler for Echoer { 11 | type Return = String; 12 | 13 | async fn handle(&mut self, echo: Echo, _ctx: &mut Context) -> String { 14 | echo.0 15 | } 16 | } 17 | 18 | #[wasm_bindgen] 19 | pub async fn start() -> Result<(), JsValue> { 20 | let addr = xtra::spawn_wasm_bindgen(Echoer, Mailbox::unbounded()); 21 | let response = addr 22 | .send(Echo("hello world".to_string())) 23 | .await 24 | .expect("Echoer should not be dropped"); 25 | 26 | assert_eq!(response, "hello world"); 27 | 28 | Ok(()) 29 | } 30 | -------------------------------------------------------------------------------- /xtra/examples/send_interval.rs: -------------------------------------------------------------------------------- 1 | use std::time::Duration; 2 | 3 | use futures_core::Stream; 4 | use futures_util::stream::repeat; 5 | use futures_util::StreamExt; 6 | use xtra::prelude::*; 7 | use xtra::Error; 8 | 9 | #[derive(Default, xtra::Actor)] 10 | struct Greeter; 11 | 12 | struct Greet; 13 | 14 | impl Handler for Greeter { 15 | type Return = (); 16 | 17 | async fn handle(&mut self, _: Greet, _ctx: &mut Context) { 18 | println!("Hello!"); 19 | } 20 | } 21 | 22 | #[tokio::main] 23 | async fn main() { 24 | let addr = xtra::spawn_tokio(Greeter, Mailbox::unbounded()); 25 | greeter_stream(500).forward(addr.into_sink()).await.unwrap(); 26 | } 27 | 28 | fn greeter_stream(delay: u64) -> impl Stream> { 29 | repeat(Duration::from_millis(delay)) 30 | .then(tokio::time::sleep) 31 | .map(|_| Ok(Greet)) 32 | } 33 | -------------------------------------------------------------------------------- /xtra/src/instrumentation/stub.rs: -------------------------------------------------------------------------------- 1 | use std::future::Future; 2 | 3 | #[derive(Clone)] 4 | pub struct Instrumentation {} 5 | 6 | #[derive(Clone)] 7 | pub struct Span(()); 8 | 9 | impl Span { 10 | pub fn in_scope(&self, f: impl FnOnce() -> R) -> R { 11 | f() 12 | } 13 | 14 | pub fn none() -> Span { 15 | Span(()) 16 | } 17 | 18 | pub fn is_none(&self) -> bool { 19 | true 20 | } 21 | } 22 | 23 | impl Instrumentation { 24 | pub fn empty() -> Self { 25 | Instrumentation {} 26 | } 27 | 28 | #[allow(unknown_lints, clippy::extra_unused_type_parameters)] // Needs to be consistent with non-stub impl. 29 | pub fn started() -> Self { 30 | Self::empty() 31 | } 32 | 33 | pub fn is_parent_none(&self) -> bool { 34 | true 35 | } 36 | 37 | pub fn apply(self, fut: F) -> (impl Future, Span) 38 | where 39 | F: Future, 40 | { 41 | (fut, Span(())) 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /xtra/examples/address_sink.rs: -------------------------------------------------------------------------------- 1 | use futures_util::stream::repeat; 2 | use futures_util::StreamExt; 3 | use xtra::prelude::*; 4 | 5 | #[derive(Default, xtra::Actor)] 6 | struct Accumulator { 7 | sum: u32, 8 | } 9 | 10 | struct Add(u32); 11 | 12 | struct GetSum; 13 | 14 | impl Handler for Accumulator { 15 | type Return = (); 16 | 17 | async fn handle(&mut self, Add(number): Add, _ctx: &mut Context) { 18 | self.sum += number; 19 | } 20 | } 21 | 22 | impl Handler for Accumulator { 23 | type Return = u32; 24 | 25 | async fn handle(&mut self, _: GetSum, _ctx: &mut Context) -> Self::Return { 26 | self.sum 27 | } 28 | } 29 | 30 | #[tokio::main] 31 | async fn main() { 32 | let addr = xtra::spawn_tokio(Accumulator::default(), Mailbox::unbounded()); 33 | 34 | repeat(10) 35 | .take(4) 36 | .map(|number| Ok(Add(number))) 37 | .forward(addr.clone().into_sink()) 38 | .await 39 | .unwrap(); 40 | 41 | let sum = addr.send(GetSum).await.unwrap(); 42 | println!("Sum is {}!", sum); 43 | } 44 | -------------------------------------------------------------------------------- /LICENSE-ACTIX: -------------------------------------------------------------------------------- 1 | Copyright (c) 2017 Nikolay Kim 2 | 3 | Permission is hereby granted, free of charge, to any 4 | person obtaining a copy of this software and associated 5 | documentation files (the "Software"), to deal in the 6 | Software without restriction, including without 7 | limitation the rights to use, copy, modify, merge, 8 | publish, distribute, sublicense, and/or sell copies of 9 | the Software, and to permit persons to whom the Software 10 | is furnished to do so, subject to the following 11 | conditions: 12 | 13 | The above copyright notice and this permission notice 14 | shall be included in all copies or substantial portions 15 | of the Software. 16 | 17 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF 18 | ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 19 | TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 20 | PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT 21 | SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 22 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 23 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR 24 | IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 25 | DEALINGS IN THE SOFTWARE. 26 | -------------------------------------------------------------------------------- /xtra/examples/scoped_actor_task.rs: -------------------------------------------------------------------------------- 1 | use futures_util::future; 2 | use xtra::prelude::*; 3 | 4 | #[derive(xtra::Actor)] 5 | struct MyActor; 6 | 7 | struct Print(String); 8 | 9 | impl Handler for MyActor { 10 | type Return = (); 11 | 12 | async fn handle(&mut self, print: Print, _ctx: &mut Context) { 13 | println!("Printing {}", print.0); 14 | } 15 | } 16 | 17 | struct DropChecker; 18 | 19 | impl Drop for DropChecker { 20 | fn drop(&mut self) { 21 | println!("The other task has been ended."); 22 | } 23 | } 24 | 25 | #[tokio::main] 26 | async fn main() { 27 | let addr = xtra::spawn_tokio(MyActor, Mailbox::unbounded()); 28 | addr.send(Print("hello".to_string())) 29 | .await 30 | .expect("Actor should not be dropped"); 31 | 32 | let task = async { 33 | let _checker = DropChecker; 34 | future::pending::<()>().await 35 | }; 36 | 37 | // This task will end as soon as the actor stops 38 | let task = tokio::spawn(xtra::scoped(&addr, task)); 39 | 40 | drop(addr); 41 | assert!(task.await.unwrap().is_none()); // should print "The other task has been ended." 42 | } 43 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | on: 2 | push: 3 | branches: [master] 4 | pull_request: 5 | 6 | name: Continuous integration 7 | 8 | concurrency: 9 | group: ${{ github.workflow }}-${{ github.ref }} 10 | cancel-in-progress: true 11 | 12 | env: 13 | RUSTFLAGS: '-Dwarnings' # Never tolerate warnings. 14 | 15 | jobs: 16 | ci: 17 | strategy: 18 | matrix: 19 | toolchain: [ 20 | stable, 21 | beta, 22 | 1.75.0 # MSRV 23 | ] 24 | args: [ 25 | --all-features, 26 | --no-default-features, 27 | ] 28 | runs-on: ubuntu-latest 29 | steps: 30 | - uses: actions/checkout@v3 31 | 32 | - uses: dtolnay/rust-toolchain@nightly 33 | 34 | - uses: dtolnay/rust-toolchain@master 35 | with: 36 | toolchain: ${{ matrix.toolchain }} 37 | components: clippy, rustfmt 38 | 39 | - run: cargo +nightly update -Z minimal-versions 40 | 41 | - uses: Swatinem/rust-cache@v2 42 | with: 43 | key: ${{ matrix.args }} 44 | 45 | - run: cargo check-custom-fmt 46 | 47 | - run: RUSTDOCFLAGS="--deny rustdoc::broken_intra_doc_links" cargo doc --no-deps --document-private-items --all-features 48 | 49 | - run: cargo clippy --all-targets ${{ matrix.args }} 50 | 51 | - run: cargo test ${{ matrix.args }} 52 | -------------------------------------------------------------------------------- /xtra/src/chan/priority.rs: -------------------------------------------------------------------------------- 1 | use std::cmp::Ordering; 2 | 3 | #[derive(Eq, PartialEq, Ord, PartialOrd, Copy, Clone)] 4 | pub enum Priority { 5 | Valued(u32), 6 | Shutdown, 7 | } 8 | 9 | impl Default for Priority { 10 | fn default() -> Self { 11 | Priority::Valued(0) 12 | } 13 | } 14 | 15 | pub trait HasPriority { 16 | fn priority(&self) -> Priority; 17 | } 18 | 19 | /// A wrapper struct that allows comparison and ordering for anything thas has a priority, i.e. implements [`HasPriority`]. 20 | pub struct ByPriority(pub T); 21 | 22 | impl HasPriority for ByPriority 23 | where 24 | T: HasPriority, 25 | { 26 | fn priority(&self) -> Priority { 27 | self.0.priority() 28 | } 29 | } 30 | 31 | impl PartialEq for ByPriority 32 | where 33 | T: HasPriority, 34 | { 35 | fn eq(&self, other: &Self) -> bool { 36 | self.0.priority().eq(&other.0.priority()) 37 | } 38 | } 39 | 40 | impl Eq for ByPriority where T: HasPriority {} 41 | 42 | impl PartialOrd for ByPriority 43 | where 44 | T: HasPriority, 45 | { 46 | fn partial_cmp(&self, other: &Self) -> Option { 47 | Some(self.cmp(other)) 48 | } 49 | } 50 | 51 | impl Ord for ByPriority 52 | where 53 | T: HasPriority, 54 | { 55 | fn cmp(&self, other: &Self) -> Ordering { 56 | self.0.priority().cmp(&other.0.priority()) 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /xtra/tests/public_api.rs: -------------------------------------------------------------------------------- 1 | //! Dedicated tests for checking the public API of xtra. 2 | 3 | use xtra::prelude::*; 4 | use xtra::refcount::{Either, RefCounter}; 5 | 6 | pub trait AddressExt {} 7 | 8 | // Ensures that we can abstract over addresses of any ref counter type. 9 | impl AddressExt for Address {} 10 | 11 | #[allow(dead_code)] 12 | // The mere existence of this function already ensures that these public APIs exist, which is what we want to test! 13 | #[allow(unknown_lints, clippy::let_underscore_future)] 14 | fn functions_on_address_with_generic_rc_counter( 15 | address1: Address, 16 | address2: Address, 17 | ) where 18 | A: Actor, 19 | Rc: RefCounter, 20 | Rc2: RefCounter, 21 | A: Handler<(), Return = ()>, 22 | { 23 | address1.len(); 24 | address1.capacity(); 25 | let _ = address1.join(); 26 | let _ = address1.send(()); 27 | let _ = address1.broadcast(()); 28 | address1.is_connected(); 29 | address1.is_empty(); 30 | let _ = address1.same_actor(&address2); 31 | } 32 | 33 | #[allow(dead_code)] // The mere existence of this function already ensures that these public APIs exist, which is what we want to test! 34 | fn converting_address_to_either_rc(address1: Address) 35 | where 36 | A: Actor, 37 | Rc: RefCounter + Into, 38 | A: Handler<(), Return = ()>, 39 | { 40 | address1.as_either(); 41 | } 42 | -------------------------------------------------------------------------------- /xtra/examples/manual_actor_impl.rs: -------------------------------------------------------------------------------- 1 | use xtra::prelude::*; 2 | 3 | #[derive(Default)] 4 | struct MessageCounter { 5 | num_messages: usize, 6 | } 7 | 8 | // With a manual `Actor` implementation, we can specify a `Stop` type and thus return something from the `stopped` lifecycle callback. 9 | 10 | impl Actor for MessageCounter { 11 | type Stop = usize; 12 | 13 | async fn stopped(self) -> Self::Stop { 14 | self.num_messages 15 | } 16 | } 17 | 18 | struct Ping; 19 | struct Stop; 20 | 21 | impl Handler for MessageCounter { 22 | type Return = (); 23 | 24 | async fn handle(&mut self, _: Ping, _: &mut Context) -> Self::Return { 25 | self.num_messages += 1; 26 | } 27 | } 28 | 29 | impl Handler for MessageCounter { 30 | type Return = (); 31 | 32 | async fn handle(&mut self, _: Stop, ctx: &mut Context) -> Self::Return { 33 | ctx.stop_self(); 34 | } 35 | } 36 | 37 | #[tokio::main] 38 | async fn main() { 39 | let (address, mailbox) = Mailbox::unbounded(); 40 | let run_future = xtra::run(mailbox, MessageCounter::default()); // `run_future` will resolve to `Actor::Stop`. 41 | let handle = tokio::spawn(run_future); 42 | 43 | address.send(Ping).await.unwrap(); 44 | address.send(Ping).await.unwrap(); 45 | address.send(Ping).await.unwrap(); 46 | address.send(Stop).await.unwrap(); 47 | 48 | let num_messages = handle.await.unwrap(); 49 | 50 | assert_eq!(num_messages, 3); 51 | } 52 | -------------------------------------------------------------------------------- /xtra/examples/interleaved_messages.rs: -------------------------------------------------------------------------------- 1 | use xtra::prelude::*; 2 | 3 | struct Initialized(Address); 4 | 5 | struct Hello; 6 | 7 | #[derive(xtra::Actor)] 8 | struct ActorA { 9 | actor_b: Address, 10 | } 11 | 12 | impl Handler for ActorA { 13 | type Return = (); 14 | 15 | async fn handle(&mut self, _: Hello, ctx: &mut Context) { 16 | println!("ActorA: Hello"); 17 | xtra::join(ctx.mailbox(), self, self.actor_b.send(Hello)) 18 | .await 19 | .unwrap(); 20 | } 21 | } 22 | 23 | #[derive(xtra::Actor)] 24 | struct ActorB; 25 | 26 | impl Handler for ActorB { 27 | type Return = (); 28 | 29 | async fn handle(&mut self, m: Initialized, ctx: &mut Context) { 30 | println!("ActorB: Initialized"); 31 | let actor_a = m.0; 32 | xtra::join(ctx.mailbox(), self, actor_a.send(Hello)) 33 | .await 34 | .unwrap(); 35 | } 36 | } 37 | 38 | impl Handler for ActorB { 39 | type Return = (); 40 | 41 | async fn handle(&mut self, _: Hello, _: &mut Context) { 42 | println!("ActorB: Hello"); 43 | } 44 | } 45 | 46 | fn main() { 47 | smol::block_on(async { 48 | let actor_b = xtra::spawn_smol(ActorB, Mailbox::unbounded()); 49 | let actor_a = xtra::spawn_smol( 50 | ActorA { 51 | actor_b: actor_b.clone(), 52 | }, 53 | Mailbox::unbounded(), 54 | ); 55 | actor_b.send(Initialized(actor_a.clone())).await.unwrap(); 56 | }) 57 | } 58 | -------------------------------------------------------------------------------- /xtra/src/instrumentation/tracing.rs: -------------------------------------------------------------------------------- 1 | use std::future::Future; 2 | 3 | pub use tracing::Span; 4 | 5 | #[derive(Clone)] 6 | pub struct Instrumentation { 7 | pub parent: Span, 8 | _waiting_for_actor: Span, 9 | } 10 | 11 | impl Instrumentation { 12 | pub fn empty() -> Self { 13 | Instrumentation { 14 | parent: Span::none(), 15 | _waiting_for_actor: Span::none(), 16 | } 17 | } 18 | 19 | pub fn started() -> Self { 20 | let parent = tracing::debug_span!( 21 | "xtra_actor_request", 22 | actor_type = %std::any::type_name::(), 23 | message_type = %std::any::type_name::(), 24 | ) 25 | .or_current(); 26 | 27 | let _waiting_for_actor = 28 | tracing::debug_span!(parent: &parent, "xtra_message_waiting_for_actor",).or_current(); 29 | 30 | Instrumentation { 31 | parent, 32 | _waiting_for_actor, 33 | } 34 | } 35 | 36 | pub fn is_parent_none(&self) -> bool { 37 | self.parent.is_none() 38 | } 39 | 40 | pub fn apply(self, fut: F) -> (impl Future, Span) 41 | where 42 | F: Future, 43 | { 44 | let executing = self.parent.in_scope(|| { 45 | tracing::debug_span!("xtra_message_handler", interrupted = tracing::field::Empty) 46 | .or_current() 47 | }); 48 | 49 | ( 50 | tracing::Instrument::instrument(fut, executing.clone()), 51 | executing, 52 | ) 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /xtra/examples/message_stealing_multiple_actors.rs: -------------------------------------------------------------------------------- 1 | //! Set the SMOL_THREADS environment variable to have more threads, else each receiving task will 2 | //! switch only after it has received many messages. 3 | 4 | use std::time::Duration; 5 | 6 | use xtra::prelude::*; 7 | use xtra::Mailbox; 8 | 9 | #[derive(xtra::Actor)] 10 | struct Printer { 11 | times: usize, 12 | id: usize, 13 | } 14 | 15 | impl Printer { 16 | fn new(id: usize) -> Self { 17 | Printer { 18 | times: 0, 19 | id: id + 1, 20 | } 21 | } 22 | } 23 | 24 | struct Print(String); 25 | 26 | impl Handler for Printer { 27 | type Return = (); 28 | 29 | async fn handle(&mut self, print: Print, ctx: &mut Context) { 30 | self.times += 1; 31 | println!( 32 | "Printing {} from printer {}. Printed {} times so far.", 33 | print.0, self.id, self.times 34 | ); 35 | 36 | if self.times == 10 { 37 | println!("Actor {} stopping!", self.id); 38 | ctx.stop_all(); 39 | } 40 | } 41 | } 42 | 43 | #[smol_potat::main] 44 | async fn main() { 45 | let (addr, mailbox) = Mailbox::bounded(32); 46 | smol::spawn(xtra::run(mailbox.clone(), Printer::new(0))).detach(); 47 | smol::spawn(xtra::run(mailbox.clone(), Printer::new(1))).detach(); 48 | smol::spawn(xtra::run(mailbox.clone(), Printer::new(2))).detach(); 49 | smol::spawn(xtra::run(mailbox, Printer::new(3))).detach(); 50 | 51 | while addr.send(Print("hello".to_string())).await.is_ok() {} 52 | println!("Stopping to send"); 53 | 54 | // Give a second for everything to shut down 55 | std::thread::sleep(Duration::from_secs(1)); 56 | } 57 | -------------------------------------------------------------------------------- /xtra/benches/throughput.rs: -------------------------------------------------------------------------------- 1 | use criterion::{criterion_group, criterion_main, BenchmarkId, Criterion}; 2 | use tokio::runtime::Runtime; 3 | use xtra::{Actor, Context, Handler, Mailbox}; 4 | 5 | struct Counter(u64); 6 | 7 | impl Actor for Counter { 8 | type Stop = (); 9 | async fn stopped(self) {} 10 | } 11 | 12 | struct IncrementZst; 13 | struct Finish; 14 | 15 | impl Handler for Counter { 16 | type Return = (); 17 | 18 | async fn handle(&mut self, _: IncrementZst, _ctx: &mut Context) { 19 | self.0 += 1; 20 | } 21 | } 22 | 23 | impl Handler for Counter { 24 | type Return = u64; 25 | 26 | async fn handle(&mut self, _: Finish, _ctx: &mut Context) -> u64 { 27 | self.0 28 | } 29 | } 30 | 31 | fn throughput(c: &mut Criterion) { 32 | let mut group = c.benchmark_group("send_zst"); 33 | let runtime = Runtime::new().unwrap(); 34 | let _g = runtime.enter(); 35 | 36 | for num_messages in [1, 10, 100, 1000] { 37 | let (address, mailbox) = Mailbox::bounded(num_messages); 38 | let _task = smol::spawn(xtra::run(mailbox, Counter(0))); 39 | 40 | group.bench_with_input( 41 | BenchmarkId::from_parameter(num_messages), 42 | &num_messages, 43 | |b, &num_messages| { 44 | b.to_async(&runtime).iter(|| async { 45 | for _ in 0..num_messages - 1 { 46 | let _ = address.send(IncrementZst).detach().await; 47 | } 48 | 49 | address.send(IncrementZst).await.unwrap() 50 | }); 51 | }, 52 | ); 53 | } 54 | } 55 | 56 | criterion_group!(benches, throughput); 57 | criterion_main!(benches); 58 | -------------------------------------------------------------------------------- /macros/src/lib.rs: -------------------------------------------------------------------------------- 1 | use proc_macro::TokenStream; 2 | use quote::quote; 3 | use syn::{parse_quote, DeriveInput, GenericParam, WherePredicate}; 4 | 5 | #[proc_macro_derive(Actor)] 6 | pub fn actor_derive(input: TokenStream) -> TokenStream { 7 | let derive_input = syn::parse::(input).expect("macro to be used as custom-derive"); 8 | 9 | let send_and_static_bounds = send_and_static_bounds(&derive_input); 10 | let actor_ident = derive_input.ident; 11 | let (impl_generics, type_generics, where_clause) = derive_input.generics.split_for_impl(); 12 | let where_clause = match where_clause.cloned() { 13 | None => parse_quote! { where #(#send_and_static_bounds),* }, 14 | Some(mut existing) => { 15 | existing.predicates.extend(send_and_static_bounds); 16 | 17 | existing 18 | } 19 | }; 20 | 21 | quote! { 22 | impl #impl_generics xtra::Actor for #actor_ident #type_generics #where_clause { 23 | type Stop = (); 24 | 25 | async fn stopped(self) { } 26 | } 27 | } 28 | .into() 29 | } 30 | 31 | /// Generics a `: Send + 'static` predicate for each type parameter present in the generics. 32 | fn send_and_static_bounds(input: &DeriveInput) -> Vec { 33 | input 34 | .generics 35 | .params 36 | .iter() 37 | .filter_map(|gp| match gp { 38 | GenericParam::Type(tp) => Some(&tp.ident), 39 | GenericParam::Lifetime(_) => None, 40 | GenericParam::Const(_) => None, 41 | }) 42 | .map(|ident| { 43 | parse_quote! { 44 | #ident: Send + 'static 45 | } 46 | }) 47 | .collect::>() 48 | } 49 | -------------------------------------------------------------------------------- /xtra/src/scoped_task.rs: -------------------------------------------------------------------------------- 1 | use std::future::Future; 2 | use std::pin::Pin; 3 | use std::task::{Context, Poll}; 4 | 5 | use futures_util::FutureExt; 6 | 7 | use crate::address::{ActorJoinHandle, Address}; 8 | use crate::chan::RefCounter; 9 | 10 | /// Scope a given task to the lifecycle of an actor - see [`ScopedTask`]. 11 | pub fn scoped(address: &Address, task: F) -> ScopedTask 12 | where 13 | Rc: RefCounter, 14 | F: Future, 15 | { 16 | ScopedTask { 17 | join_handle: address.join(), 18 | fut: task, 19 | } 20 | } 21 | 22 | pin_project_lite::pin_project! { 23 | /// A task that is scoped to the lifecycle of an actor. This means that when the associated 24 | /// actor stops, the task will stop too. This future will either complete when the inner future 25 | /// completes, or when the actor is dropped, whichever comes first. If the inner future completes 26 | /// successfully, `Some(result)` will be returned, else `None` will be returned if the actor 27 | /// is stopped before it could be polled to completion. 28 | #[must_use = "Futures do nothing unless polled"] 29 | pub struct ScopedTask { 30 | join_handle: ActorJoinHandle, 31 | #[pin] 32 | fut: F, 33 | } 34 | } 35 | 36 | impl Future for ScopedTask 37 | where 38 | F: Future, 39 | { 40 | type Output = Option; 41 | 42 | fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { 43 | let this = self.project(); 44 | 45 | match this.join_handle.poll_unpin(cx) { 46 | Poll::Ready(()) => Poll::Ready(None), 47 | Poll::Pending => match this.fut.poll(cx) { 48 | Poll::Ready(v) => Poll::Ready(Some(v)), 49 | Poll::Pending => Poll::Pending, 50 | }, 51 | } 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /xtra/examples/custom_event_loop.rs: -------------------------------------------------------------------------------- 1 | use std::ops::ControlFlow; 2 | use std::time::Duration; 3 | 4 | use tokio::time::Instant; 5 | use xtra::prelude::*; 6 | 7 | #[derive(Default, xtra::Actor)] 8 | struct Counter { 9 | count: usize, 10 | } 11 | 12 | struct Inc; 13 | 14 | impl Handler for Counter { 15 | type Return = (); 16 | 17 | async fn handle(&mut self, _inc: Inc, _ctx: &mut Context) { 18 | // Do some "work" 19 | tokio::time::sleep(Duration::from_millis(50)).await; 20 | self.count += 1; 21 | } 22 | } 23 | 24 | #[tokio::main] 25 | async fn main() { 26 | let (address, mailbox) = Mailbox::unbounded(); 27 | let mut actor = Counter::default(); 28 | 29 | tokio::spawn(async move { 30 | if let Err(()) = actor.started(&mailbox).await { 31 | return; 32 | } 33 | 34 | loop { 35 | let start = Instant::now(); 36 | let msg = mailbox.next().await; 37 | println!("Got message in {}us", start.elapsed().as_micros()); 38 | 39 | let before = actor.count; 40 | let start = Instant::now(); 41 | 42 | let ctrl = msg.dispatch_to(&mut actor).await; 43 | 44 | if let ControlFlow::Break(_) = ctrl { 45 | println!("Goodbye!"); 46 | break; 47 | } 48 | 49 | println!( 50 | "Count changed from {} to {} in {:.2}ms\n", 51 | before, 52 | actor.count, 53 | start.elapsed().as_secs_f32() * 1000.0 54 | ); 55 | } 56 | }); 57 | 58 | for _ in 0..100 { 59 | address 60 | .send(Inc) 61 | .await 62 | .expect("Counter should not be dropped"); 63 | } 64 | 65 | // Wait for the actor to stop 66 | drop(address); 67 | tokio::time::sleep(Duration::from_secs(1)).await; 68 | } 69 | -------------------------------------------------------------------------------- /xtra/src/spawn.rs: -------------------------------------------------------------------------------- 1 | /// Spawns the given actor into the tokio runtime, returning an [`Address`](crate::Address) to it. 2 | #[cfg(feature = "tokio")] 3 | #[cfg_attr(docsrs, doc(cfg(feature = "tokio")))] 4 | pub fn spawn_tokio( 5 | actor: A, 6 | (address, mailbox): (crate::Address, crate::Mailbox), 7 | ) -> crate::Address 8 | where 9 | A: crate::Actor, 10 | { 11 | tokio::spawn(crate::run(mailbox, actor)); 12 | 13 | address 14 | } 15 | 16 | /// Spawns the given actor into the async_std runtime, returning an [`Address`](crate::Address) to it. 17 | #[cfg(feature = "async_std")] 18 | #[cfg_attr(docsrs, doc(cfg(feature = "async_std")))] 19 | pub fn spawn_async_std( 20 | actor: A, 21 | (address, mailbox): (crate::Address, crate::Mailbox), 22 | ) -> crate::Address 23 | where 24 | A: crate::Actor, 25 | { 26 | async_std::task::spawn(crate::run(mailbox, actor)); 27 | 28 | address 29 | } 30 | 31 | /// Spawns the given actor into the smol runtime, returning an [`Address`](crate::Address) to it. 32 | #[cfg(feature = "smol")] 33 | #[cfg_attr(docsrs, doc(cfg(feature = "smol")))] 34 | pub fn spawn_smol( 35 | actor: A, 36 | (address, mailbox): (crate::Address, crate::Mailbox), 37 | ) -> crate::Address 38 | where 39 | A: crate::Actor, 40 | { 41 | smol::spawn(crate::run(mailbox, actor)).detach(); 42 | 43 | address 44 | } 45 | 46 | /// Spawns the given actor onto the thread-local runtime via `wasm_bindgen_futures`, returning an [`Address`](crate::Address) to it. 47 | #[cfg(feature = "wasm_bindgen")] 48 | #[cfg_attr(docsrs, doc(cfg(feature = "wasm_bindgen")))] 49 | pub fn spawn_wasm_bindgen( 50 | actor: A, 51 | (address, mailbox): (crate::Address, crate::Mailbox), 52 | ) -> crate::Address 53 | where 54 | A: crate::Actor, 55 | { 56 | wasm_bindgen_futures::spawn_local(crate::run(mailbox, actor)); 57 | 58 | address 59 | } 60 | -------------------------------------------------------------------------------- /xtra/src/context.rs: -------------------------------------------------------------------------------- 1 | use crate::{Actor, Mailbox}; 2 | 3 | /// `Context` is used to control how the actor is managed and to get the actor's address from inside 4 | /// of a message handler. 5 | pub struct Context { 6 | pub(crate) running: bool, 7 | pub(crate) mailbox: Mailbox, 8 | } 9 | 10 | impl Context { 11 | /// Stop this actor as soon as it has finished processing current message. This means that the 12 | /// [`Actor::stopped`] method will be called. This will not stop all actors on the address. 13 | pub fn stop_self(&mut self) { 14 | self.running = false; 15 | } 16 | 17 | /// Stop all actors on this address. 18 | /// 19 | /// This bypasses the message queue, so it will always be handled as soon as possible by all actors. 20 | /// It will not wait for other messages to be enqueued if the queue is full. 21 | /// In other words, it will not wait for an actor which is lagging behind on broadcast messages 22 | /// to catch up before other actors can receive the shutdown message. 23 | /// Therefore, each actor is guaranteed to shut down as its next action immediately after it 24 | /// finishes processing its current message, or as soon as its task is woken if it is currently idle. 25 | /// 26 | /// This is similar to calling [`Context::stop_self`] on all actors active on this address, but 27 | /// a broadcast message that would cause [`Context::stop_self`] to be called may have to wait 28 | /// for other broadcast messages, during which time other messages may be handled by actors (i.e 29 | /// the shutdown may be delayed by a lagging actor). 30 | pub fn stop_all(&self) { 31 | // We only need to shut down if there are still any strong senders left 32 | if let Some(address) = self.mailbox.address().try_upgrade() { 33 | address.0.shutdown_all_receivers(); 34 | } 35 | } 36 | 37 | /// Get a reference to the [`Mailbox`] of this actor. 38 | pub fn mailbox(&self) -> &Mailbox { 39 | &self.mailbox 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /xtra/src/mailbox.rs: -------------------------------------------------------------------------------- 1 | use std::sync::Arc; 2 | 3 | use crate::chan::{self, BroadcastQueue, Rx}; 4 | use crate::recv_future::ReceiveFuture; 5 | use crate::{Address, WeakAddress}; 6 | 7 | /// A [`Mailbox`] is the counter-part to an [`Address`]. 8 | /// 9 | /// Messages sent into an [`Address`] will be received in an actor's [`Mailbox`]. 10 | /// Think of [`Address`] and [`Mailbox`] as an MPMC channel. 11 | pub struct Mailbox { 12 | inner: chan::Ptr, 13 | broadcast_mailbox: Arc>, 14 | } 15 | 16 | impl Mailbox { 17 | /// Creates a new [`Mailbox`] with the given capacity. 18 | pub fn bounded(capacity: usize) -> (Address, Mailbox) { 19 | let (sender, receiver) = chan::new(Some(capacity)); 20 | 21 | let address = Address(sender); 22 | let mailbox = Mailbox { 23 | broadcast_mailbox: receiver.new_broadcast_mailbox(), 24 | inner: receiver, 25 | }; 26 | 27 | (address, mailbox) 28 | } 29 | 30 | /// Creates a new, unbounded [`Mailbox`]. 31 | /// 32 | /// Unbounded mailboxes will not perform an back-pressure and can result in potentially unbounded memory growth. Use with care. 33 | pub fn unbounded() -> (Address, Mailbox) { 34 | let (sender, receiver) = crate::chan::new(None); 35 | 36 | let address = Address(sender); 37 | let mailbox = Mailbox { 38 | broadcast_mailbox: receiver.new_broadcast_mailbox(), 39 | inner: receiver, 40 | }; 41 | 42 | (address, mailbox) 43 | } 44 | 45 | /// Obtain a [`WeakAddress`] to this [`Mailbox`]. 46 | /// 47 | /// Obtaining a [`WeakAddress`] is always successful even if there are no more strong addresses 48 | /// around. Use [`WeakAddress::try_upgrade`] to get a strong address. 49 | pub fn address(&self) -> WeakAddress { 50 | Address(self.inner.to_tx_weak()) 51 | } 52 | 53 | /// Take the next message out of the [`Mailbox`]. 54 | pub fn next(&self) -> ReceiveFuture { 55 | ReceiveFuture::new(self.inner.clone(), self.broadcast_mailbox.clone()) 56 | } 57 | 58 | pub(crate) fn from_parts( 59 | chan: chan::Ptr, 60 | broadcast_mailbox: Arc>, 61 | ) -> Self { 62 | Self { 63 | inner: chan, 64 | broadcast_mailbox, 65 | } 66 | } 67 | } 68 | 69 | impl Clone for Mailbox { 70 | fn clone(&self) -> Self { 71 | Mailbox { 72 | inner: self.inner.clone(), 73 | broadcast_mailbox: self.inner.new_broadcast_mailbox(), 74 | } 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /xtra/examples/backpressure.rs: -------------------------------------------------------------------------------- 1 | use xtra::prelude::*; 2 | 3 | #[derive(xtra::Actor)] 4 | struct Greeter; 5 | 6 | struct Hello(String); 7 | 8 | impl Handler for Greeter { 9 | type Return = (); 10 | 11 | async fn handle(&mut self, Hello(name): Hello, _: &mut Context) -> Self::Return { 12 | println!("Hello {}", name) 13 | } 14 | } 15 | 16 | /// This examples demonstrates `xtra`'s feature of backpressure when waiting for the result of a handler asynchronously. 17 | /// 18 | /// Backpressure allows an actor to throttle the sending of new messages by putting a limit on how many messages can be queued in the mailbox at once. 19 | /// To demonstrate backpressure we set up the following environment: 20 | /// 21 | /// 1. Single-threaded tokio executor: This ensures that only one task can run at any time. 22 | /// 2. Call `detach` on the [`SendFuture`](xtra::SendFuture) returned by [`Address::send`]: The actor needs to be busy working off messages and thus we cannot synchronously wait for the result. 23 | /// 3. Print "Greeting world!" to stdout before we dispatch a message. 24 | /// 4. Print "Hello world!" upon executing the handler. 25 | /// 26 | /// By varying the `mailbox_capacity` and observing the output on stdout, we can see the effects of backpressure: 27 | /// 28 | /// ## `mailbox_capacity = Some(0)` 29 | /// 30 | /// A `mailbox_capacity` of `Some(0)` will yield `Pending` on the `SendFuture` until the actor is actively requesting the next message from its event-loop. 31 | /// We will thus see a fairly **interleaved** pattern of: 32 | /// 33 | /// - "Greeting world!" 34 | /// - "Hello world!" 35 | /// 36 | /// This makes sense because the next "Greeting world!" can only be printed once the `SendFuture` is complete which only happens as soon as the actor is ready to take another message which in turn means it is done with processing the current message. 37 | /// 38 | /// ## `mailbox_capacity = Some(N)` 39 | /// 40 | /// Setting `mailbox_capacity` to `Some(N)` allows us to dispatch up to `N` message to the actor before the returned `SendFuture` returns `Pending`. 41 | /// We can observe this by seeing N+1 blocks of "Greeting world!". 42 | /// 43 | /// The task for dispatching messages can dispatch N messages without yielding `Pending`. Due to the single-threaded executor, nothing else is executing during that time. 44 | /// Once the dispatching task yields `Pending`, the runtime switches to the actor's task and processes all queued messages. An empty mailbox will yield `Pending` and the 45 | /// entire dance starts again. 46 | /// 47 | /// ## `mailbox_capacity = None` 48 | /// 49 | /// A `mailbox_capacity` of `None` creates an interesting output: We only see "Greeting world!" messages. 50 | /// This is easily explained though. `None` creates an unbounded mailbox, meaning there is no artificial upper limit to how many messages we can queue. 51 | /// 52 | /// The example ends after the loop and thus, the runtime is immediately destroyed after which means none of the queue handlers ever get to actually execute. 53 | #[tokio::main(flavor = "current_thread")] 54 | async fn main() { 55 | let address = xtra::spawn_tokio(Greeter, Mailbox::unbounded()); 56 | 57 | for _ in 0..100 { 58 | let name = "world!".to_owned(); 59 | 60 | println!("Greeting {}", name); 61 | let _ = address.send(Hello(name)).detach().await; 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /xtra/src/chan/waiting_sender.rs: -------------------------------------------------------------------------------- 1 | use std::future::Future; 2 | use std::mem; 3 | use std::pin::Pin; 4 | use std::sync::{Arc, Weak}; 5 | use std::task::{Context, Poll, Waker}; 6 | 7 | use crate::chan::{HasPriority, Priority}; 8 | use crate::Error; 9 | 10 | #[must_use = "Futures do nothing unless polled"] 11 | pub struct WaitingSender(Arc>>); 12 | 13 | pub struct Handle(Weak>>); 14 | 15 | impl WaitingSender { 16 | pub fn new(msg: M) -> (Handle, WaitingSender) { 17 | let inner = Arc::new(spin::Mutex::new(Inner::new(msg))); 18 | 19 | (Handle(Arc::downgrade(&inner)), WaitingSender(inner)) 20 | } 21 | } 22 | 23 | impl Handle { 24 | pub fn is_active(&self) -> bool { 25 | Weak::strong_count(&self.0) > 0 26 | } 27 | 28 | /// Take the message out of the paired [`WaitingSender`]. 29 | /// 30 | /// This may return `None` in case the [`WaitingSender`] is no longer active, has already been closed or the message was already taken. 31 | pub fn take_message(self) -> Option { 32 | let inner = self.0.upgrade()?; 33 | let mut this = inner.lock(); 34 | 35 | match mem::replace(&mut *this, Inner::Delivered) { 36 | Inner::Active { mut waker, message } => { 37 | if let Some(waker) = waker.take() { 38 | waker.wake(); 39 | } 40 | 41 | Some(message) 42 | } 43 | Inner::Delivered | Inner::Closed => None, 44 | } 45 | } 46 | } 47 | 48 | impl Drop for Handle { 49 | fn drop(&mut self) { 50 | if let Some(inner) = self.0.upgrade() { 51 | let mut this = inner.lock(); 52 | 53 | match &*this { 54 | Inner::Active { waker, .. } => { 55 | if let Some(waker) = waker { 56 | waker.wake_by_ref(); 57 | } 58 | *this = Inner::Closed; 59 | } 60 | Inner::Delivered => {} 61 | Inner::Closed => {} 62 | } 63 | }; 64 | } 65 | } 66 | 67 | impl Handle 68 | where 69 | M: HasPriority, 70 | { 71 | pub fn priority(&self) -> Option { 72 | let inner = self.0.upgrade()?; 73 | let this = inner.lock(); 74 | 75 | match &*this { 76 | Inner::Active { message, .. } => Some(message.priority()), 77 | Inner::Closed | Inner::Delivered => None, 78 | } 79 | } 80 | } 81 | 82 | impl Future for WaitingSender { 83 | type Output = Result<(), Error>; 84 | 85 | fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { 86 | let mut this = self.get_mut().0.lock(); 87 | 88 | match &mut *this { 89 | Inner::Active { waker, .. } => { 90 | *waker = Some(cx.waker().clone()); 91 | Poll::Pending 92 | } 93 | Inner::Delivered => Poll::Ready(Ok(())), 94 | Inner::Closed => Poll::Ready(Err(Error::Disconnected)), 95 | } 96 | } 97 | } 98 | 99 | enum Inner { 100 | Active { waker: Option, message: M }, 101 | Delivered, 102 | Closed, 103 | } 104 | 105 | impl Inner { 106 | fn new(message: M) -> Self { 107 | Inner::Active { 108 | waker: None, 109 | message, 110 | } 111 | } 112 | } 113 | -------------------------------------------------------------------------------- /xtra/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "xtra" 3 | version = "0.6.0" 4 | description = "A tiny actor framework" 5 | authors = ["Restioson "] 6 | edition = "2021" 7 | license = "MPL-2.0" 8 | repository = "https://github.com/Restioson/xtra" 9 | documentation = "https://docs.rs/xtra" 10 | readme = "../README.md" 11 | keywords = ["async", "actor", "futures", "xtra", "async-await"] 12 | categories = ["asynchronous", "concurrency"] 13 | rust-version = "1.75.0" 14 | 15 | [dependencies] 16 | catty = "0.1.5" 17 | futures-core = "0.3.21" # alloc is the only default feature and we need it. 18 | futures-sink = { version = "0.3.21", default-features = false, optional = true } 19 | futures-util = { version = "0.3.21", default-features = false } 20 | pin-project-lite = "0.2.9" 21 | event-listener = "2.4.0" 22 | spin = { version = "0.9.3", default-features = false, features = ["spin_mutex"] } 23 | 24 | async-std = { version = "1.0", features = ["unstable"], optional = true } 25 | smol = { version = "1.1", optional = true } 26 | tokio = { version = "1.0", features = ["rt", "time"], optional = true } 27 | wasm-bindgen = { version = "0.2", optional = true, default-features = false } 28 | wasm-bindgen-futures = { version = "0.4", optional = true, default-features = false } 29 | 30 | # Feature `instrumentation` 31 | tracing = { version = "0.1.35", optional = true, default-features = false } 32 | 33 | macros = { package = "xtra-macros", version = "0.6.0", optional = true } 34 | 35 | [dev-dependencies] 36 | rand = "0.8" 37 | smol = "1.1" 38 | smol-potat = "1.1" 39 | smol-timeout = "0.6" 40 | waker-fn = "1.1" 41 | criterion = { version = "0.3", features = ["async_tokio"] } 42 | tokio = { version = "1.21", features = ["full"] } 43 | async-std = { version = "1.0", features = ["attributes"] } 44 | tracing = { version = "0.1.35", features = ["std"] } 45 | tracing-subscriber = { version = "0.3.17", features = ["env-filter"] } 46 | futures-util = "0.3.21" 47 | 48 | [features] 49 | default = [] 50 | macros = ["dep:macros"] 51 | instrumentation = ["dep:tracing"] 52 | async_std = ["dep:async-std"] 53 | smol = ["dep:smol"] 54 | tokio = ["dep:tokio"] 55 | wasm_bindgen = ["dep:wasm-bindgen", "dep:wasm-bindgen-futures"] 56 | sink = ["dep:futures-sink", "futures-util/sink"] 57 | 58 | [[example]] 59 | name = "basic_tokio" 60 | required-features = ["tokio", "macros"] 61 | 62 | [[example]] 63 | name = "basic_async_std" 64 | required-features = ["async_std", "macros"] 65 | 66 | [[example]] 67 | name = "basic_smol" 68 | path = "examples/basic_smol.rs" 69 | required-features = ["smol", "macros"] 70 | 71 | [[example]] 72 | name = "interleaved_messages" 73 | required-features = ["smol", "macros"] 74 | 75 | [[example]] 76 | name = "message_stealing_multiple_actors" 77 | required-features = ["smol", "macros"] 78 | 79 | [[example]] 80 | name = "crude_bench" 81 | required-features = ["tokio", "macros"] 82 | 83 | [[example]] 84 | name = "backpressure" 85 | required-features = ["tokio", "macros"] 86 | 87 | [[example]] 88 | name = "address_sink" 89 | required-features = ["tokio", "tokio/full", "sink", "macros"] 90 | 91 | [[example]] 92 | name = "send_interval" 93 | required-features = ["tokio", "tokio/full", "macros"] 94 | 95 | [[example]] 96 | name = "scoped_actor_task" 97 | required-features = ["tokio", "macros"] 98 | 99 | [[example]] 100 | name = "custom_event_loop" 101 | required-features = ["macros"] 102 | 103 | [[example]] 104 | name = "manual_actor_impl" 105 | required-features = ["tokio"] 106 | 107 | [[test]] 108 | name = "basic" 109 | required-features = ["tokio", "macros"] 110 | 111 | [[test]] 112 | name = "public_api" 113 | required-features = ["tokio", "macros"] 114 | 115 | [[test]] 116 | name = "instrumentation" 117 | required-features = ["tokio", "instrumentation", "macros"] 118 | 119 | [package.metadata.docs.rs] 120 | features = ["async_std", "smol", "tokio", "wasm_bindgen"] 121 | rustdoc-args = ["--cfg", "docsrs"] 122 | 123 | [[bench]] 124 | name = "throughput" 125 | harness = false 126 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![Continuous integration](https://github.com/Restioson/xtra/actions/workflows/ci.yml/badge.svg)](https://github.com/Restioson/xtra/actions/workflows/ci.yml) 2 | ![docs.rs](https://img.shields.io/docsrs/xtra) 3 | ![Matrix](https://img.shields.io/matrix/xtra-community:matrix.org) 4 | 5 | # xtra 6 | 7 | A tiny, fast, and safe actor framework. It is modelled around Actix (copyright and license [here](https://github.com/Restioson/xtra/blob/master/LICENSE-ACTIX)). 8 | 9 | ## Features 10 | 11 | - **Safe:** there is no unsafe code in xtra. 12 | - **Tiny:** xtra is only around 2000 LoC. 13 | - **Lightweight:** xtra has few dependencies, most of which are lightweight (except `futures`). 14 | - Asynchronous `Handler` interface which allows `async`/`await` syntax with `&mut self`. 15 | - Does not depend on its own runtime and can be run with any futures executor. Convenience `spawn` functions are provided 16 | for [Tokio](https://tokio.rs/), [async-std](https://async.rs/), [smol](https://github.com/stjepang/smol), and 17 | [wasm-bindgen-futures](https://rustwasm.github.io/wasm-bindgen/api/wasm_bindgen_futures/). 18 | - Quite fast. Running on Tokio, <170ns time from sending a message to it being processed for sending without waiting for a 19 | result on my development machine with an AMD Ryzen 3 3200G. 20 | 21 | ## Example 22 | 23 | This is an example to use `xtra` with `tokio`. To compile this example it is needed to add the features `tokio` and `macros` in `Cargo.toml`. 24 | 25 | ```toml 26 | [dependencies] 27 | xtra = { version = "0.6.0", features = ["tokio", "macros"] } 28 | ``` 29 | 30 | ```rust 31 | use xtra::prelude::*; 32 | 33 | #[derive(Default, xtra::Actor)] 34 | struct Printer { 35 | times: usize, 36 | } 37 | 38 | struct Print(String); 39 | 40 | impl Handler for Printer { 41 | type Return = (); 42 | 43 | async fn handle(&mut self, print: Print, _ctx: &mut Context) { 44 | self.times += 1; 45 | println!("Printing {}. Printed {} times so far.", print.0, self.times); 46 | } 47 | } 48 | 49 | #[tokio::main] 50 | async fn main() { 51 | let addr = xtra::spawn_tokio(Printer::default(), Mailbox::unbounded()); 52 | loop { 53 | addr.send(Print("hello".to_string())) 54 | .await 55 | .expect("Printer should not be dropped"); 56 | } 57 | } 58 | 59 | ``` 60 | 61 | For a longer example, check out [Vertex](https://github.com/Restioson/vertex/tree/development), a chat application written with xtra and spaad on the server. 62 | 63 | ## Okay, sounds great! How do I use it? 64 | 65 | Check out the [docs](https://docs.rs/xtra) and the [examples](https://github.com/Restioson/xtra/tree/master/xtra/examples) to get started! 66 | Enabling the `tokio`, `macros`, `async_std`, `smol`, or `wasm_bindgen` features is recommended in order to enable some convenience methods (such as `xtra::spawn_tokio`). 67 | Which you enable will depend on which executor you want to use (check out their docs to learn more about each). 68 | If you have any questions, feel free to [open an issue](https://github.com/Restioson/xtra/issues/new) or message me on the [Rust discord](https://bit.ly/rust-community). 69 | 70 | Keep in mind that `xtra` has a MSRV of 1.60.0. 71 | 72 | ## Cargo features 73 | 74 | - `async_std`: enables integration with [async-std](https://async.rs/). 75 | - `smol`: enables integration with [smol](https://github.com/smol-rs/smol). 76 | Note that this requires smol 1.1 as 1.1 had a minor breaking change from 1.0 which leads to xtra no longer compiling on 1.0 and 1.1 simultaneously. 77 | - `tokio`: enables integration with [tokio](https://tokio.rs). 78 | - `wasm_bindgen`: enables integration with [wasm-bindgen](https://github.com/rustwasm/wasm-bindgen), and particularly its futures crate. 79 | - `instrumentation`: Adds a dependency on `tracing` and creates spans for message sending and handling on actors. 80 | - `sink`: Adds `Address::into_sink` and `MessageChannel::into_sink`. 81 | - `macros`: Enables the `Actor` custom derive macro. 82 | 83 | ## Latest Breaking Changes 84 | 85 | To see the breaking changes for each version, see [here](https://github.com/Restioson/xtra/blob/master/BREAKING-CHANGES.md). 86 | The latest version is 0.6.0. 87 | -------------------------------------------------------------------------------- /xtra/src/chan/waiting_receiver.rs: -------------------------------------------------------------------------------- 1 | use std::task::{Context, Poll}; 2 | 3 | use futures_util::FutureExt; 4 | 5 | use crate::chan::{self, ActorMessage, BroadcastQueue, MessageToOne, Rx}; 6 | 7 | /// A [`WaitingReceiver`] is handed out by the channel any time [`Chan::try_recv`](crate::chan::Chan::try_recv) is called on an empty mailbox. 8 | /// 9 | /// [`WaitingReceiver`] implements [`Future`](std::future::Future) which will resolve once a message lands in the mailbox. 10 | pub struct WaitingReceiver(catty::Receiver>); 11 | 12 | /// A [`Handle`] is the counter-part to a [`WaitingReceiver`]. 13 | /// 14 | /// It is stored internally in the channel and used by the channel implementation to notify a 15 | /// [`WaitingReceiver`] once a new message hits the mailbox. 16 | pub struct Handle(catty::Sender>); 17 | 18 | impl Handle { 19 | /// Notify the connected [`WaitingReceiver`] that the channel is shutting down. 20 | pub fn notify_channel_shutdown(self) { 21 | let _ = self.0.send(CtrlMsg::Shutdown); 22 | } 23 | 24 | /// Notify the connected [`WaitingReceiver`] about a new broadcast message. 25 | /// 26 | /// Broadcast mailboxes are stored outside of the main channel implementation which is why this 27 | /// messages does not take any arguments. 28 | pub fn notify_new_broadcast(self) -> Result<(), ()> { 29 | self.0.send(CtrlMsg::NewBroadcast).map_err(|_| ()) 30 | } 31 | 32 | /// Notify the connected [`WaitingReceiver`] about a new message. 33 | /// 34 | /// A new message was sent into the channel and the connected [`WaitingReceiver`] is the chosen 35 | /// one to handle it, likely because it has been waiting the longest. 36 | /// 37 | /// This function will return the message in an `Err` if the [`WaitingReceiver`] has since called 38 | /// [`cancel`](WaitingReceiver::cancel) and is therefore unable to handle the message. 39 | pub fn notify_new_message(self, msg: MessageToOne) -> Result<(), MessageToOne> { 40 | self.0 41 | .send(CtrlMsg::NewMessage(msg)) 42 | .map_err(|reason| match reason { 43 | CtrlMsg::NewMessage(msg) => msg, 44 | _ => unreachable!(), 45 | }) 46 | } 47 | } 48 | 49 | impl WaitingReceiver { 50 | pub fn new() -> (WaitingReceiver, Handle) { 51 | let (sender, receiver) = catty::oneshot(); 52 | 53 | (WaitingReceiver(receiver), Handle(sender)) 54 | } 55 | 56 | /// Cancel this [`WaitingReceiver`]. 57 | /// 58 | /// This may return a message in case the underlying state has been fulfilled with one but this 59 | /// receiver has not been polled since. 60 | /// 61 | /// It is important to call this message over just dropping the [`WaitingReceiver`] as this 62 | /// message would otherwise be dropped. 63 | pub fn cancel(&mut self) -> Option> { 64 | match self.0.try_recv() { 65 | Ok(Some(CtrlMsg::NewMessage(msg))) => Some(msg), 66 | _ => None, 67 | } 68 | } 69 | 70 | /// Tell the [`WaitingReceiver`] to make progress. 71 | /// 72 | /// In case we have been woken with a reason, we will attempt to produce an [`ActorMessage`]. 73 | /// Wake-ups can be false-positives in the case of a broadcast message which is why this 74 | /// function returns only [`Option`]. 75 | pub fn poll( 76 | &mut self, 77 | chan: &chan::Ptr, 78 | broadcast_mailbox: &BroadcastQueue, 79 | cx: &mut Context<'_>, 80 | ) -> Poll>> { 81 | let ctrl_msg = match futures_util::ready!(self.0.poll_unpin(cx)) { 82 | Ok(reason) => reason, 83 | Err(_) => return Poll::Ready(None), // TODO: Not sure if this is correct. 84 | }; 85 | 86 | let actor_message = match ctrl_msg { 87 | CtrlMsg::NewMessage(msg) => ActorMessage::ToOneActor(msg), 88 | CtrlMsg::Shutdown => ActorMessage::Shutdown, 89 | CtrlMsg::NewBroadcast => match chan.next_broadcast_message(broadcast_mailbox) { 90 | Some(msg) => ActorMessage::ToAllActors(msg), 91 | None => return Poll::Ready(None), 92 | }, 93 | }; 94 | 95 | Poll::Ready(Some(actor_message)) 96 | } 97 | } 98 | 99 | enum CtrlMsg { 100 | NewMessage(MessageToOne), 101 | NewBroadcast, 102 | Shutdown, 103 | } 104 | -------------------------------------------------------------------------------- /xtra/src/dispatch_future.rs: -------------------------------------------------------------------------------- 1 | use std::future::Future; 2 | use std::marker::PhantomData; 3 | use std::mem; 4 | use std::ops::ControlFlow; 5 | use std::pin::Pin; 6 | use std::task::{Context, Poll}; 7 | 8 | use futures_core::future::BoxFuture; 9 | use futures_util::FutureExt; 10 | 11 | use crate::chan::ActorMessage; 12 | use crate::envelope::Shutdown; 13 | use crate::instrumentation::Span; 14 | use crate::mailbox::Mailbox; 15 | use crate::Message; 16 | 17 | impl Message { 18 | /// Dispatches this message to the given actor. 19 | pub fn dispatch_to(self, actor: &mut A) -> DispatchFuture<'_, A> { 20 | DispatchFuture::new( 21 | self.inner, 22 | actor, 23 | Mailbox::from_parts(self.channel, self.broadcast_mailbox), 24 | ) 25 | } 26 | } 27 | 28 | /// Represents the dispatch of a message to an actor. 29 | /// 30 | /// This future is **not** cancellation-safe. Dropping it will interrupt the execution of 31 | /// [`Handler::handle`](crate::Handler::handle) which may leave the actor in an inconsistent state. 32 | #[must_use = "Futures do nothing unless polled"] 33 | pub struct DispatchFuture<'a, A> { 34 | state: State<'a, A>, 35 | span: Span, 36 | } 37 | 38 | impl<'a, A> DispatchFuture<'a, A> { 39 | /// Returns a [`Span`] that covers the entire dispatching and handling of the message to the actor. 40 | /// 41 | /// This can be used to log messages into the span when required, such as if it is cancelled later due to a timeout. 42 | /// 43 | /// In case this future has not yet been polled, a new span will be created which is why this function takes `&mut self`. 44 | /// 45 | /// ```rust 46 | 47 | /// # use std::ops::ControlFlow; 48 | /// # use std::time::Duration; 49 | /// # use tokio::time::timeout; 50 | /// # use xtra::prelude::*; 51 | /// # 52 | /// # struct MyActor; 53 | /// # impl Actor for MyActor { type Stop = (); async fn stopped(self) {} } 54 | /// # 55 | /// # let mut actor = MyActor; 56 | /// # let (addr, mut mailbox) = Mailbox::unbounded(); 57 | /// # drop(addr); 58 | /// # tokio::runtime::Runtime::new().unwrap().block_on(async { 59 | /// # actor.started(&mut mailbox).await; 60 | /// # 61 | /// # loop { 62 | /// # let msg = mailbox.next().await; 63 | /// let mut fut = msg.dispatch_to(&mut actor); 64 | /// let span = fut.span().clone(); 65 | /// match timeout(Duration::from_secs(1), fut).await { 66 | /// Ok(ControlFlow::Continue(())) => (), 67 | /// Ok(ControlFlow::Break(())) => break actor.stopped().await, 68 | /// Err(_elapsed) => { 69 | /// let _entered = span.enter(); 70 | /// span.record("interrupted", &"timed_out"); 71 | /// tracing::warn!(timeout_seconds = 1, "Handler execution timed out"); 72 | /// } 73 | /// } 74 | /// # } }) 75 | /// ``` 76 | /// 77 | #[cfg(feature = "instrumentation")] 78 | pub fn span(&mut self) -> &Span { 79 | let span = mem::replace(&mut self.span, Span::none()); 80 | *self = match mem::replace(&mut self.state, State::Done) { 81 | State::New { msg, act, mailbox } => DispatchFuture::running(msg, act, mailbox), 82 | state => DispatchFuture { state, span }, 83 | }; 84 | 85 | &self.span 86 | } 87 | 88 | fn running(msg: ActorMessage, act: &'a mut A, mailbox: Mailbox) -> DispatchFuture<'a, A> { 89 | let (fut, span) = match msg { 90 | ActorMessage::ToOneActor(msg) => msg.handle(act, mailbox), 91 | ActorMessage::ToAllActors(msg) => msg.handle(act, mailbox), 92 | ActorMessage::Shutdown => Shutdown::::handle(), 93 | }; 94 | 95 | DispatchFuture { 96 | state: State::Running { 97 | fut, 98 | phantom: PhantomData, 99 | }, 100 | span, 101 | } 102 | } 103 | } 104 | 105 | enum State<'a, A> { 106 | New { 107 | msg: ActorMessage, 108 | act: &'a mut A, 109 | mailbox: Mailbox, 110 | }, 111 | Running { 112 | fut: BoxFuture<'a, ControlFlow<()>>, 113 | phantom: PhantomData, 114 | }, 115 | Done, 116 | } 117 | 118 | impl<'a, A> DispatchFuture<'a, A> { 119 | pub fn new(msg: ActorMessage, act: &'a mut A, mailbox: Mailbox) -> Self { 120 | DispatchFuture { 121 | state: State::New { msg, act, mailbox }, 122 | span: Span::none(), 123 | } 124 | } 125 | } 126 | 127 | impl<'a, A> Future for DispatchFuture<'a, A> { 128 | type Output = ControlFlow<()>; 129 | 130 | fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { 131 | match mem::replace(&mut self.state, State::Done) { 132 | State::New { msg, act, mailbox } => { 133 | *self = DispatchFuture::running(msg, act, mailbox); 134 | self.poll(cx) 135 | } 136 | State::Running { mut fut, phantom } => { 137 | match self.span.in_scope(|| fut.poll_unpin(cx)) { 138 | Poll::Ready(flow) => Poll::Ready(flow), 139 | Poll::Pending => { 140 | self.state = State::Running { fut, phantom }; 141 | Poll::Pending 142 | } 143 | } 144 | } 145 | State::Done => panic!("Polled after completion"), 146 | } 147 | } 148 | } 149 | -------------------------------------------------------------------------------- /xtra/examples/crude_bench.rs: -------------------------------------------------------------------------------- 1 | use std::future::Future; 2 | use std::time::Instant; 3 | 4 | use futures_util::FutureExt; 5 | use xtra::prelude::*; 6 | use xtra::refcount::Strong; 7 | use xtra::{ActorErasedSending, ActorNamedSending, SendFuture}; 8 | 9 | #[derive(xtra::Actor)] 10 | struct Counter { 11 | count: usize, 12 | } 13 | 14 | struct Increment; 15 | #[allow(dead_code)] 16 | struct IncrementWithData(usize); 17 | struct GetCount; 18 | 19 | impl Handler for Counter { 20 | type Return = (); 21 | 22 | async fn handle(&mut self, _: Increment, _ctx: &mut Context) { 23 | self.count += 1; 24 | } 25 | } 26 | 27 | impl Handler for Counter { 28 | type Return = (); 29 | 30 | async fn handle(&mut self, _: IncrementWithData, _ctx: &mut Context) { 31 | self.count += 1; 32 | } 33 | } 34 | 35 | impl Handler for Counter { 36 | type Return = usize; 37 | 38 | async fn handle(&mut self, _: GetCount, _ctx: &mut Context) -> usize { 39 | let count = self.count; 40 | self.count = 0; 41 | count 42 | } 43 | } 44 | 45 | const COUNT: usize = 10_000_000; // May take a while on some machines 46 | 47 | async fn do_address_benchmark( 48 | name: &str, 49 | f: impl Fn(&Address) -> SendFuture, R>, 50 | ) where 51 | SendFuture, R>: Future, 52 | { 53 | let addr = xtra::spawn_tokio(Counter { count: 0 }, Mailbox::unbounded()); 54 | 55 | let start = Instant::now(); 56 | 57 | // rounding overflow 58 | for _ in 0..COUNT { 59 | let _ = f(&addr).now_or_never(); 60 | } 61 | 62 | // awaiting on GetCount will make sure all previous messages are processed first BUT introduces 63 | // future tokio reschedule time because of the .await 64 | let total_count = addr.send(GetCount).await.unwrap(); 65 | 66 | let duration = Instant::now() - start; 67 | let average_ns = duration.as_nanos() / COUNT as u128; // <120-170ns on my machine 68 | println!("{} avg time of processing: {}ns", name, average_ns); 69 | assert_eq!(total_count, COUNT, "total_count should equal COUNT!"); 70 | } 71 | 72 | async fn do_parallel_address_benchmark( 73 | name: &str, 74 | workers: usize, 75 | f: impl Fn(&Address) -> SendFuture, R>, 76 | ) where 77 | SendFuture, R>: Future, 78 | { 79 | let (addr, mailbox) = Mailbox::unbounded(); 80 | let start = Instant::now(); 81 | for _ in 0..workers { 82 | tokio::spawn(xtra::run(mailbox.clone(), Counter { count: 0 })); 83 | } 84 | 85 | for _ in 0..COUNT { 86 | let _ = f(&addr).await; 87 | } 88 | 89 | // awaiting on GetCount will make sure all previous messages are processed first BUT introduces 90 | // future tokio reschedule time because of the .await 91 | let _ = addr.send(GetCount).await.unwrap(); 92 | 93 | let duration = Instant::now() - start; 94 | let average_ns = duration.as_nanos() / COUNT as u128; // <120-170ns on my machine 95 | println!("{} avg time of processing: {}ns", name, average_ns); 96 | } 97 | 98 | async fn do_channel_benchmark( 99 | name: &str, 100 | f: impl Fn(&MessageChannel) -> SendFuture, 101 | ) where 102 | Counter: Handler + Send, 103 | M: Send + 'static, 104 | SendFuture: Future, 105 | { 106 | let addr = xtra::spawn_tokio(Counter { count: 0 }, Mailbox::unbounded()); 107 | let chan = MessageChannel::new(addr.clone()); 108 | 109 | let start = Instant::now(); 110 | for _ in 0..COUNT { 111 | let _ = f(&chan).await; 112 | } 113 | 114 | // awaiting on GetCount will make sure all previous messages are processed first BUT introduces 115 | // future tokio reschedule time because of the .await 116 | let total_count = addr.send::(GetCount).await.unwrap(); 117 | 118 | let duration = Instant::now() - start; 119 | let average_ns = duration.as_nanos() / total_count as u128; // <120-170ns on my machine 120 | println!("{} avg time of processing: {}ns", name, average_ns); 121 | assert_eq!(total_count, COUNT, "total_count should equal COUNT!"); 122 | } 123 | 124 | #[tokio::main] 125 | async fn main() { 126 | do_address_benchmark("address detach (ZST message)", |addr| { 127 | addr.send(Increment).detach() 128 | }) 129 | .await; 130 | 131 | do_address_benchmark("address detach (8-byte message)", |addr| { 132 | addr.send(IncrementWithData(0)).detach() 133 | }) 134 | .await; 135 | 136 | do_parallel_address_benchmark("address detach 2 workers (ZST message)", 2, |addr| { 137 | addr.send(Increment).detach() 138 | }) 139 | .await; 140 | 141 | do_parallel_address_benchmark("address detach 2 workers (8-byte message)", 2, |addr| { 142 | addr.send(IncrementWithData(0)).detach() 143 | }) 144 | .await; 145 | 146 | do_channel_benchmark("channel detach (ZST message)", |chan| { 147 | chan.send(Increment).detach() 148 | }) 149 | .await; 150 | 151 | do_channel_benchmark("channel detach (8-byte message)", |chan| { 152 | chan.send(IncrementWithData(0)).detach() 153 | }) 154 | .await; 155 | 156 | do_channel_benchmark("channel send (ZST message)", |chan| chan.send(Increment)).await; 157 | 158 | do_channel_benchmark("channel send (8-byte message)", |chan| { 159 | chan.send(IncrementWithData(0)) 160 | }) 161 | .await; 162 | } 163 | -------------------------------------------------------------------------------- /xtra/tests/instrumentation.rs: -------------------------------------------------------------------------------- 1 | //! Much of this code is taken from https://github.com/dbrgn/tracing-test// 2 | //! 3 | //! 4 | //! # tracing_test license 5 | //! 6 | //! Copyright (C) 2020-2022 Threema GmbH, Danilo Bargen 7 | //! 8 | //! Permission is hereby granted, free of charge, to any person obtaining a copy of 9 | //! this software and associated documentation files (the "Software"), to deal in 10 | //! the Software without restriction, including without limitation the rights to 11 | //! use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies 12 | //! of the Software, and to permit persons to whom the Software is furnished to do 13 | //! so, subject to the following conditions: 14 | //! 15 | //! The above copyright notice and this permission notice shall be included in all 16 | //! copies or substantial portions of the Software. 17 | //! 18 | //! THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 19 | //! IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 20 | //! FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 21 | //! AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 22 | //! LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 23 | //! OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 24 | //! SOFTWARE. 25 | 26 | use std::sync::{Arc, Mutex, MutexGuard}; 27 | use std::{fmt, io}; 28 | 29 | use tracing::{Dispatch, Instrument}; 30 | use tracing_subscriber::fmt::MakeWriter; 31 | use tracing_subscriber::FmtSubscriber; 32 | use xtra::prelude::*; 33 | 34 | #[tokio::test] 35 | async fn assert_send_is_child_of_span() { 36 | let (subscriber, buf) = get_subscriber("instrumentation=trace,xtra=trace"); 37 | let _g = tracing::dispatcher::set_default(&subscriber); 38 | 39 | let addr = xtra::spawn_tokio(Tracer, Mailbox::unbounded()); 40 | let _ = addr 41 | .send(Hello("world")) 42 | .instrument(tracing::info_span!("user_span")) 43 | .await; 44 | 45 | assert_eq!( 46 | buf, 47 | [" INFO user_span:xtra_actor_request\ 48 | {actor_type=instrumentation::Tracer message_type=instrumentation::Hello}:\ 49 | xtra_message_handler: instrumentation: Hello world"] 50 | ); 51 | } 52 | 53 | #[tokio::test] 54 | async fn assert_handler_span_is_child_of_caller_span_with_min_level_info() { 55 | let (subscriber, buf) = get_subscriber("instrumentation=info,xtra=info"); 56 | let _g = tracing::dispatcher::set_default(&subscriber); 57 | 58 | let addr = xtra::spawn_tokio(Tracer, Mailbox::unbounded()); 59 | let _ = addr 60 | .send(CreateInfoSpan) 61 | .instrument(tracing::info_span!("sender_span")) 62 | .await; 63 | 64 | assert_eq!(buf, [" INFO sender_span:info_span: instrumentation: Test!"]); 65 | } 66 | 67 | #[derive(xtra::Actor)] 68 | struct Tracer; 69 | 70 | struct Hello(&'static str); 71 | 72 | impl Handler for Tracer { 73 | type Return = (); 74 | 75 | async fn handle(&mut self, message: Hello, _ctx: &mut Context) { 76 | tracing::info!("Hello {}", message.0) 77 | } 78 | } 79 | 80 | struct CreateInfoSpan; 81 | 82 | impl Handler for Tracer { 83 | type Return = (); 84 | 85 | async fn handle(&mut self, _msg: CreateInfoSpan, _ctx: &mut Context) { 86 | tracing::info_span!("info_span").in_scope(|| tracing::info!("Test!")); 87 | } 88 | } 89 | 90 | #[derive(Debug, Default)] 91 | struct BufferWriter { 92 | buf: Buffer, 93 | } 94 | 95 | #[derive(Default, Clone)] 96 | struct Buffer(Arc>>); 97 | 98 | impl Buffer { 99 | fn as_str(&self) -> String { 100 | let buf = self.0.lock().unwrap().clone(); 101 | 102 | String::from_utf8(buf).expect("Logs contain invalid UTF8") 103 | } 104 | } 105 | 106 | impl PartialEq<[&str; N]> for Buffer { 107 | fn eq(&self, other: &[&str; N]) -> bool { 108 | self.as_str().lines().collect::>().eq(other) 109 | } 110 | } 111 | 112 | impl fmt::Debug for Buffer { 113 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 114 | self.as_str().lines().collect::>().fmt(f) 115 | } 116 | } 117 | 118 | impl BufferWriter { 119 | /// Give access to the internal buffer (behind a `MutexGuard`). 120 | fn buf(&self) -> io::Result>> { 121 | // Note: The `lock` will block. This would be a problem in production code, 122 | // but is fine in tests. 123 | self.buf 124 | .0 125 | .lock() 126 | .map_err(|_| io::Error::from(io::ErrorKind::Other)) 127 | } 128 | } 129 | 130 | impl io::Write for BufferWriter { 131 | fn write(&mut self, buf: &[u8]) -> io::Result { 132 | // Lock target buffer 133 | let mut target = self.buf()?; 134 | 135 | // Write to stdout in order to show up in tests 136 | print!("{}", String::from_utf8(buf.to_vec()).unwrap()); 137 | 138 | // Write to buffer 139 | target.write(buf) 140 | } 141 | 142 | fn flush(&mut self) -> io::Result<()> { 143 | self.buf()?.flush() 144 | } 145 | } 146 | 147 | impl MakeWriter<'_> for BufferWriter { 148 | type Writer = Self; 149 | 150 | fn make_writer(&self) -> Self::Writer { 151 | BufferWriter { 152 | buf: self.buf.clone(), 153 | } 154 | } 155 | } 156 | 157 | /// Return a new subscriber with the [`Buffer`] that all logs will be written to. 158 | fn get_subscriber(env_filter: &str) -> (Dispatch, Buffer) { 159 | let writer = BufferWriter::default(); 160 | let buffer = writer.buf.clone(); 161 | 162 | let dispatch = FmtSubscriber::builder() 163 | .with_env_filter(env_filter) 164 | .with_writer(writer) 165 | .with_level(true) 166 | .with_ansi(false) 167 | .without_time() 168 | .into(); 169 | 170 | (dispatch, buffer) 171 | } 172 | -------------------------------------------------------------------------------- /xtra/src/recv_future.rs: -------------------------------------------------------------------------------- 1 | use std::future::Future; 2 | use std::mem; 3 | use std::pin::Pin; 4 | use std::sync::Arc; 5 | use std::task::{Context, Poll}; 6 | 7 | use futures_core::FusedFuture; 8 | use futures_util::FutureExt; 9 | 10 | use crate::chan::{self, ActorMessage, BroadcastQueue, Rx, WaitingReceiver}; 11 | 12 | /// A future which will resolve to the next message to be handled by the actor. 13 | /// 14 | /// # Cancellation safety 15 | /// 16 | /// This future is cancellation-safe in that no messages will ever be lost, even if this future is 17 | /// dropped half-way through. However, reinserting the message into the mailbox may mess with the 18 | /// ordering of messages and they may be handled by the actor out of order. 19 | /// 20 | /// If the order in which your actors process messages is not important to you, you can consider this 21 | /// future to be fully cancellation-safe. 22 | /// 23 | /// If you wish to maintain message ordering, you can use [`FutureExt::now_or_never`] to do a final 24 | /// poll on the future. [`ReceiveFuture`] is guaranteed to complete in a single poll if it has 25 | /// remaining work to do. 26 | #[must_use = "Futures do nothing unless polled"] 27 | pub struct ReceiveFuture(Receiving); 28 | 29 | /// A message sent to a given actor, or a notification that it should shut down. 30 | pub struct Message { 31 | pub(crate) inner: ActorMessage, 32 | 33 | pub(crate) channel: chan::Ptr, 34 | pub(crate) broadcast_mailbox: Arc>, 35 | } 36 | 37 | impl ReceiveFuture { 38 | pub(crate) fn new( 39 | channel: chan::Ptr, 40 | broadcast_mailbox: Arc>, 41 | ) -> Self { 42 | Self(Receiving::New { 43 | channel, 44 | broadcast_mailbox, 45 | }) 46 | } 47 | } 48 | 49 | impl Future for ReceiveFuture { 50 | type Output = Message; 51 | 52 | fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { 53 | self.0.poll_unpin(cx) 54 | } 55 | } 56 | 57 | /// Module-private type modelling the actual state machine of receiving a message. 58 | /// 59 | /// This type only exists because the variants of an enum are public and we would leak 60 | /// implementation details like the variant names into the public API. 61 | #[must_use = "Futures do nothing unless polled"] 62 | enum Receiving { 63 | New { 64 | channel: chan::Ptr, 65 | broadcast_mailbox: Arc>, 66 | }, 67 | Waiting(Waiting), 68 | Done, 69 | } 70 | 71 | /// Dedicated "waiting" state for the [`ReceiveFuture`]. 72 | /// 73 | /// This type encapsulates the waiting for a notification from the channel about a new message that 74 | /// can be received. This notification may arrive in the [`WaitingReceiver`] before we poll it again. 75 | /// 76 | /// To avoid losing a message, this type implements [`Drop`] and re-queues the message into the 77 | /// mailbox in such a scenario. 78 | #[must_use = "Futures do nothing unless polled"] 79 | pub struct Waiting { 80 | channel: Option>, 81 | broadcast_mailbox: Option>>, 82 | waiting_receiver: WaitingReceiver, 83 | } 84 | 85 | impl Future for Waiting { 86 | type Output = Result< 87 | (ActorMessage, chan::Ptr, Arc>), 88 | (chan::Ptr, Arc>), 89 | >; 90 | 91 | fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { 92 | let this = self.get_mut(); 93 | 94 | let maybe_message = futures_util::ready!(this.waiting_receiver.poll( 95 | this.channel 96 | .as_mut() 97 | .expect("to not be polled after completion"), 98 | this.broadcast_mailbox 99 | .as_mut() 100 | .expect("to not be polled after completion"), 101 | cx 102 | )); 103 | 104 | let channel = this 105 | .channel 106 | .take() 107 | .expect("to not be polled after completion"); 108 | let mailbox = this 109 | .broadcast_mailbox 110 | .take() 111 | .expect("to not be polled after completion"); 112 | 113 | let result = match maybe_message { 114 | None => Err((channel, mailbox)), 115 | Some(msg) => Ok((msg, channel, mailbox)), 116 | }; 117 | 118 | Poll::Ready(result) 119 | } 120 | } 121 | 122 | impl Drop for Waiting { 123 | fn drop(&mut self) { 124 | if let Some(msg) = self.waiting_receiver.cancel() { 125 | self.channel 126 | .as_mut() 127 | .expect("to not have message on drop but channel is gone") 128 | .requeue_message(msg); 129 | } 130 | } 131 | } 132 | 133 | impl Future for Receiving { 134 | type Output = Message; 135 | 136 | fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { 137 | let this = self.get_mut(); 138 | 139 | loop { 140 | match mem::replace(this, Receiving::Done) { 141 | Receiving::New { 142 | channel, 143 | broadcast_mailbox, 144 | } => match channel.try_recv(broadcast_mailbox.as_ref()) { 145 | Ok(inner) => { 146 | return Poll::Ready(Message { 147 | inner, 148 | channel, 149 | broadcast_mailbox, 150 | }) 151 | } 152 | Err(waiting) => { 153 | *this = Receiving::Waiting(Waiting { 154 | channel: Some(channel), 155 | broadcast_mailbox: Some(broadcast_mailbox), 156 | waiting_receiver: waiting, 157 | }); 158 | } 159 | }, 160 | Receiving::Waiting(mut inner) => match inner.poll_unpin(cx) { 161 | Poll::Ready(Ok((msg, channel, broadcast_mailbox))) => { 162 | return Poll::Ready(Message { 163 | inner: msg, 164 | channel, 165 | broadcast_mailbox, 166 | }) 167 | } 168 | Poll::Ready(Err((channel, broadcast_mailbox))) => { 169 | // False positive wake up, try receive again. 170 | *this = Receiving::New { 171 | channel, 172 | broadcast_mailbox, 173 | }; 174 | } 175 | Poll::Pending => { 176 | *this = Receiving::Waiting(inner); 177 | return Poll::Pending; 178 | } 179 | }, 180 | Receiving::Done => panic!("polled after completion"), 181 | } 182 | } 183 | } 184 | } 185 | 186 | impl FusedFuture for Receiving { 187 | fn is_terminated(&self) -> bool { 188 | matches!(self, Receiving::Done) 189 | } 190 | } 191 | 192 | impl FusedFuture for ReceiveFuture { 193 | fn is_terminated(&self) -> bool { 194 | self.0.is_terminated() 195 | } 196 | } 197 | -------------------------------------------------------------------------------- /BREAKING-CHANGES.md: -------------------------------------------------------------------------------- 1 | # Breaking Changes by Version 2 | 3 | ## 0.6.0 4 | 5 | ### Added 6 | 7 | - `xtra::Actor` custom-derive when the `macros` features is enabled. 8 | 9 | ### Changed 10 | 11 | - Remove `async_trait` macro in favor of async functions in traits (AFIT). 12 | This bumps xtra's MSRV to `1.75`. 13 | - `MessageChannel` is now a `struct` that can be constructed from an `Address` via `MessageChannel::new` or using `From`/`Into`. 14 | - Move event-loop related functions from `Context` to xtra's top-level scope. 15 | `Context` is now only used within an actor's `Handler`. 16 | The default event-loop now lives at `xtra::run`, next to `xtra::select`, `xtra::join`, `xtra::yield`. 17 | - Redesign "spawn" interface: 18 | Remove `Actor::create`, `ActorManager` and extension traits for spawning. 19 | Introduce `xtra::spawn_tokio`, `xtra::spawn_smol`, `xtra::spawn_async_std` and `xtra::spawn_wasm_bindgen`. 20 | - Previously, `stop_all` would immediately disconnect the address. 21 | However, `stop_self` done on every actor would actually not do this in one case - if there were a free-floating (not executing an actor event loop) Context. 22 | This change brings `stop_all` in line with `stop_self`. 23 | - `stop_all` now does not drain all messages when called, and acts just like `stop_self` on all active actors. 24 | - Rename features from `with-crate-version` to just `crate`. For example, `with-tokio-1` has been renamed to `tokio`. 25 | - Sealed `RefCounter` trait. 26 | 27 | ### Removed 28 | 29 | - `AddressSink` was removed in favor of using `impl Trait` for the `Address::into_sink` method. 30 | - `Context::attach_stream` was removed in favor of composing `Stream::forward` and `Address::into_sink`. 31 | - `KeepRunning` was removed as `Context::attach_stream` was its last usage. 32 | - `InstrumentedExt` was removed. 33 | All messages are now instrumented automatically when `instrumentation` is enabled. 34 | - `Message` no longer exists: `Return` is now specified on the `Handler` trait itself. 35 | - `stopping` has been removed in favour of `stop_self` and `stop_all`. 36 | If logic to determine if the actor should stop must be executed, it should be done rather at the point of calling `stop_{self,all}`. 37 | - `Context::attach` is removed in favor of implementing `Clone` for `Context`. 38 | If you want to run multiple actors on a `Context`, simply clone it before calling `run`. 39 | - Remove `Context::notify_after` without a direct replacement. 40 | To delay the sending of a message, users are encouraged to use the `sleep` function of their executor of choice and combine it with `Address::send` into a new future. 41 | To cancel the sleeping early in case the actor stops, use `xtra::scoped`. 42 | - Remove `Context::notify_interval` without a direct replacement. 43 | Users are encouraged to write their own loop within which they call `Address:send`. 44 | 45 | ## 0.5.0 46 | 47 | - **The `SyncHandler` trait has been removed.** This simplifies the API and should not change the performance on stable. 48 | - *How to upgrade:* change all implementations of the `SyncHandler` trait to the normal `Handler` trait. 49 | - **All `Actor` lifecycle messages are now async.** This allows to do more kinds of things in lifecycle methods, 50 | while adding no restrictions. 51 | - *How to upgrade:* add `async` to the function definition of all actor lifecycle methods, add `#[async_trait::async_trait]` 52 | to the `impl Actor` block. 53 | - `Actor` now requires `Send` to implement. Previously, the trait itself did not, but using it did require `Send`. 54 | - *How to upgrade:* you probably never had a non-`Send` actor in the first place. 55 | - The `{Weak}{Address|MessageChannel}::attach_stream` methods now require that the actor implements `Handler` where 56 | `M: Into + Send`. This is automatically implemented for `()`, returning `KeepRunning::Yes`. This allows 57 | the user more control over the future spawned by `attach_stream`, but is breaking if the message returned did not 58 | implement `Into`. 59 | - *How to upgrade:* implement `Into` for all message types used in `attach_stream`. To mimic previous 60 | behaviour, return `KeepRunning::Yes` in the implementation. 61 | - `Address` and `WeakAddress` lost their `Sink` implementations. They can now be turned into `Sink`s by calling 62 | `.into_sink()`. 63 | - *How to upgrade:* convert any addresses to be used as sinks into sinks with `.into_sink()`, cloning where necessary. 64 | - `{Address|MessageChannel}Ext` were removed in favour of inherent implementations, 65 | - *How to upgrade:* in most cases, this will not have broken anything. If it is directly imported, remove the import. 66 | If you need to be generic over weak and strong addresses, be generic over `Address` where `Rc: RefCounter` for 67 | addresses and use `MessageChannel` trait objects. 68 | - `{Weak}MessageChannel` became traits rather than concrete types. In order to use them, simply cast an address to 69 | the correct trait object (e.g `&addr as &dyn MessageChannel` or `Box::new(addr)`). The `into_channel` and `channel` 70 | methods were also removed. 71 | - *How to upgrade:* replace `{into_}channel` calls with casts to trait objects, and replace references to the old 72 | types with trait objects, boxed if necessary. If you were using the `Sink` implementations of these types, first 73 | create an `AddressSink` through `.into_sink()`, and then cast it to a `MessageSink` trait object. 74 | - `Address::into_downgraded` was removed. This did nothing different to `downgrade`, except dropping the address after 75 | the call. 76 | - *How to upgrade:* Simply call `Address::downgrade`, dropping the strong address afterwards if needed. 77 | - Some types were moved out of the root crate and into modules. 78 | - *How to upgrade:* search for the type's name in the documentation and refer to it by its new path. 79 | - `Actor::spawn` and `Actor::create` now take an`Option` for the mailbox size. 80 | - *How to upgrade:* choose a suitable size of mailbox for each spawn call, or pass `None` to give them unbounded 81 | mailboxes. 82 | - Many context methods now return `Result<..., ActorShutdown>` to represent failures due to the actor having been shut 83 | down. 84 | 85 | ## 0.4.0 86 | 87 | - The `stable` feature was removed. ~~In order to enable the nightly API, enable the new `nightly` feature.~~ *Edit: as 88 | of 0.5.0, the nightly API has been removed.* 89 | 90 | ## 0.3.0 91 | 92 | - The default API of the `Handler` trait has now changed to an `async_trait` so that xtra can compile on stable. 93 | - *How to upgrade, alternative 1:* change the implementations by annotating the implementation with `#[async_trait]`, 94 | removing `Responder` and making `handle` an `async fn` which directly returns the message's result. 95 | - *How to upgrade, alternative 2:* if you want to avoid the extra box, you can disable the default `stable` feature 96 | in your `Cargo.toml` to keep the old API. 97 | 98 | ## 0.2.0 99 | 100 | - Removal of the `with-runtime` feature 101 | - *How to upgrade:* you probably weren't using this anyway, but rather use `with-tokio-*` or `with-async_std-*` 102 | instead. 103 | - `Address` methods were moved to `AddressExt` to accommodate new `Address` types 104 | - *How to upgrade:* add `use xtra::AddressExt` to wherever address methods are used (or, better yet, 105 | `use xtra::prelude::*`) 106 | - All `*_async` methods were removed. Asynchronous and synchronous messages now use the same method for everything. 107 | - *How to upgrade:* simply switch from the `[x]_async` method to the `[x]` method. 108 | - `AsyncHandler` was renamed to `Handler`, and the old `Handler` to `SyncHandler`. Also, a `Handler` and `SyncHandler` implementation can no longer coexist. 109 | - *How to upgrade:* rename all `Handler` implementations to `SyncHandler`, and all `AsyncHandler` implementations to `Handler`. 110 | -------------------------------------------------------------------------------- /xtra/src/envelope.rs: -------------------------------------------------------------------------------- 1 | use std::marker::PhantomData; 2 | use std::ops::ControlFlow; 3 | use std::sync::Arc; 4 | 5 | use catty::{Receiver, Sender}; 6 | use futures_core::future::BoxFuture; 7 | use futures_util::FutureExt; 8 | 9 | use crate::chan::{HasPriority, MessageToAll, MessageToOne, Priority}; 10 | use crate::context::Context; 11 | use crate::instrumentation::{Instrumentation, Span}; 12 | use crate::{Actor, Handler, Mailbox}; 13 | 14 | /// A message envelope is a struct that encapsulates a message and its return channel sender (if applicable). 15 | /// Firstly, this allows us to be generic over returning and non-returning messages (as all use the 16 | /// same `handle` method and return the same pinned & boxed future), but almost more importantly it 17 | /// allows us to erase the type of the message when this is in dyn Trait format, thereby being able to 18 | /// use only one channel to send all the kinds of messages that the actor can receives. This does, 19 | /// however, induce a bit of allocation (as envelopes have to be boxed). 20 | pub trait MessageEnvelope: HasPriority + Send { 21 | /// The type of actor that this envelope carries a message for 22 | type Actor; 23 | 24 | fn set_priority(&mut self, new_priority: u32); 25 | 26 | /// Starts the instrumentation of this message request. This will create the request span. 27 | fn start_span(&mut self); 28 | 29 | /// Handle the message inside of the box by calling the relevant [`Handler::handle`] method, 30 | /// returning its result over a return channel if applicable. This also takes `Box` as the 31 | /// `self` parameter because `Envelope`s always appear as `Box>`, 32 | /// and this allows us to consume the envelope. 33 | fn handle( 34 | self: Box, 35 | act: &mut Self::Actor, 36 | mailbox: Mailbox, 37 | ) -> (BoxFuture>, Span); 38 | } 39 | 40 | /// An envelope that returns a result from a message. Constructed by the `AddressExt::do_send` method. 41 | pub struct ReturningEnvelope { 42 | message: M, 43 | result_sender: Sender, 44 | priority: u32, 45 | phantom: PhantomData fn(&'a A)>, 46 | instrumentation: Instrumentation, 47 | } 48 | 49 | impl ReturningEnvelope { 50 | pub fn new(message: M, priority: u32) -> (Self, Receiver) { 51 | let (tx, rx) = catty::oneshot(); 52 | let envelope = ReturningEnvelope { 53 | message, 54 | result_sender: tx, 55 | priority, 56 | phantom: PhantomData, 57 | instrumentation: Instrumentation::empty(), 58 | }; 59 | 60 | (envelope, rx) 61 | } 62 | } 63 | 64 | impl HasPriority for ReturningEnvelope { 65 | fn priority(&self) -> Priority { 66 | Priority::Valued(self.priority) 67 | } 68 | } 69 | 70 | impl HasPriority for MessageToOne { 71 | fn priority(&self) -> Priority { 72 | self.as_ref().priority() 73 | } 74 | } 75 | 76 | impl MessageEnvelope for ReturningEnvelope 77 | where 78 | A: Handler, 79 | M: Send + 'static, 80 | R: Send + 'static, 81 | { 82 | type Actor = A; 83 | 84 | fn set_priority(&mut self, new_priority: u32) { 85 | self.priority = new_priority; 86 | } 87 | 88 | fn start_span(&mut self) { 89 | assert!(self.instrumentation.is_parent_none()); 90 | self.instrumentation = Instrumentation::started::(); 91 | } 92 | 93 | fn handle( 94 | self: Box, 95 | act: &mut Self::Actor, 96 | mailbox: Mailbox, 97 | ) -> (BoxFuture>, Span) { 98 | let Self { 99 | message, 100 | result_sender, 101 | instrumentation, 102 | .. 103 | } = *self; 104 | 105 | let fut = async move { 106 | let mut ctx = Context { 107 | running: true, 108 | mailbox, 109 | }; 110 | let r = act.handle(message, &mut ctx).await; 111 | 112 | if ctx.running { 113 | (r, ControlFlow::Continue(())) 114 | } else { 115 | (r, ControlFlow::Break(())) 116 | } 117 | }; 118 | 119 | let (fut, span) = instrumentation.apply::<_>(fut); 120 | 121 | let fut = Box::pin(fut.map(move |(r, flow)| { 122 | // We don't actually care if the receiver is listening 123 | let _ = result_sender.send(r); 124 | flow 125 | })); 126 | 127 | (fut, span) 128 | } 129 | } 130 | 131 | /// Like MessageEnvelope, but with an Arc instead of Box 132 | pub trait BroadcastEnvelope: HasPriority + Send + Sync { 133 | type Actor; 134 | 135 | fn set_priority(&mut self, new_priority: u32); 136 | 137 | /// Starts the instrumentation of this message request, if this arc is unique. This will create 138 | /// the request span 139 | fn start_span(&mut self); 140 | 141 | fn handle( 142 | self: Arc, 143 | act: &mut Self::Actor, 144 | mailbox: Mailbox, 145 | ) -> (BoxFuture>, Span); 146 | } 147 | 148 | impl HasPriority for MessageToAll { 149 | fn priority(&self) -> Priority { 150 | self.as_ref().priority() 151 | } 152 | } 153 | 154 | pub struct BroadcastEnvelopeConcrete { 155 | message: M, 156 | priority: u32, 157 | phantom: PhantomData fn(&'a A)>, 158 | instrumentation: Instrumentation, 159 | } 160 | 161 | impl BroadcastEnvelopeConcrete { 162 | pub fn new(message: M, priority: u32) -> Self { 163 | BroadcastEnvelopeConcrete { 164 | message, 165 | priority, 166 | phantom: PhantomData, 167 | instrumentation: Instrumentation::empty(), 168 | } 169 | } 170 | } 171 | 172 | impl BroadcastEnvelope for BroadcastEnvelopeConcrete 173 | where 174 | A: Handler, 175 | M: Clone + Send + Sync + 'static, 176 | { 177 | type Actor = A; 178 | 179 | fn set_priority(&mut self, new_priority: u32) { 180 | self.priority = new_priority; 181 | } 182 | 183 | fn start_span(&mut self) { 184 | assert!(self.instrumentation.is_parent_none()); 185 | self.instrumentation = Instrumentation::started::(); 186 | } 187 | 188 | fn handle( 189 | self: Arc, 190 | act: &mut Self::Actor, 191 | mailbox: Mailbox, 192 | ) -> (BoxFuture>, Span) { 193 | let (msg, instrumentation) = (self.message.clone(), self.instrumentation.clone()); 194 | drop(self); // Drop ASAP to end the message waiting for actor span 195 | let fut = async move { 196 | let mut ctx = Context { 197 | running: true, 198 | mailbox, 199 | }; 200 | act.handle(msg, &mut ctx).await; 201 | 202 | if ctx.running { 203 | ControlFlow::Continue(()) 204 | } else { 205 | ControlFlow::Break(()) 206 | } 207 | }; 208 | let (fut, span) = instrumentation.apply::<_>(fut); 209 | (Box::pin(fut), span) 210 | } 211 | } 212 | 213 | impl HasPriority for BroadcastEnvelopeConcrete { 214 | fn priority(&self) -> Priority { 215 | Priority::Valued(self.priority) 216 | } 217 | } 218 | 219 | #[derive(Copy, Clone, Default)] 220 | pub struct Shutdown(PhantomData fn(&'a A)>); 221 | 222 | impl Shutdown { 223 | pub fn new() -> Self { 224 | Shutdown(PhantomData) 225 | } 226 | 227 | pub fn handle() -> (BoxFuture<'static, ControlFlow<()>>, Span) { 228 | let fut = Box::pin(async { ControlFlow::Break(()) }); 229 | 230 | (fut, Span::none()) 231 | } 232 | } 233 | 234 | impl HasPriority for Shutdown { 235 | fn priority(&self) -> Priority { 236 | Priority::Shutdown 237 | } 238 | } 239 | 240 | impl BroadcastEnvelope for Shutdown 241 | where 242 | A: Actor, 243 | { 244 | type Actor = A; 245 | 246 | fn set_priority(&mut self, _: u32) {} 247 | 248 | // This message is not instrumented 249 | fn start_span(&mut self) {} 250 | 251 | fn handle( 252 | self: Arc, 253 | _act: &mut Self::Actor, 254 | _mailbox: Mailbox, 255 | ) -> (BoxFuture>, Span) { 256 | Self::handle() 257 | } 258 | } 259 | -------------------------------------------------------------------------------- /xtra/src/chan/ptr.rs: -------------------------------------------------------------------------------- 1 | use std::ops::Deref; 2 | use std::sync::{atomic, Arc}; 3 | 4 | use private::RefCounter as _; 5 | 6 | use crate::chan::Chan; 7 | 8 | /// A reference-counted pointer to the channel that is generic over its reference counting policy. 9 | /// 10 | /// Apart from [`TxEither`], all reference-counting policies are zero-sized types and the actual channel 11 | /// is stored in an `Arc`, meaning this pointer type is exactly as wide as an `Arc`, i.e. 8 bytes. 12 | /// 13 | /// This is possible because the actual reference counting is done within [`Chan`]. 14 | pub struct Ptr 15 | where 16 | Rc: RefCounter, 17 | { 18 | inner: Arc>, 19 | ref_counter: Rc, 20 | } 21 | 22 | impl Ptr { 23 | pub fn new(inner: Arc>) -> Self { 24 | let policy = TxStrong(()).make_new(inner.as_ref()); 25 | 26 | Self { 27 | ref_counter: policy, 28 | inner, 29 | } 30 | } 31 | } 32 | 33 | impl Ptr { 34 | pub fn new(inner: Arc>) -> Self { 35 | let ref_counter = Rx(()).make_new(inner.as_ref()); 36 | 37 | Self { ref_counter, inner } 38 | } 39 | } 40 | 41 | impl Ptr 42 | where 43 | Rc: RefCounter, 44 | { 45 | pub fn is_strong(&self) -> bool { 46 | self.ref_counter.is_strong() 47 | } 48 | 49 | pub fn to_tx_weak(&self) -> Ptr { 50 | Ptr { 51 | inner: self.inner.clone(), 52 | ref_counter: TxWeak(()), 53 | } 54 | } 55 | 56 | pub fn try_to_tx_strong(&self) -> Option> { 57 | Some(Ptr { 58 | inner: self.inner.clone(), 59 | ref_counter: TxStrong::try_new(self.inner.as_ref())?, 60 | }) 61 | } 62 | 63 | pub fn inner_ptr(&self) -> *const () { 64 | Arc::as_ptr(&self.inner) as *const () 65 | } 66 | 67 | pub fn sender_count(&self) -> usize { 68 | self.inner.sender_count.load(atomic::Ordering::SeqCst) 69 | } 70 | 71 | pub fn receiver_count(&self) -> usize { 72 | self.inner.receiver_count.load(atomic::Ordering::SeqCst) 73 | } 74 | } 75 | 76 | impl Ptr 77 | where 78 | Rc: RefCounter + Into, 79 | { 80 | pub fn to_tx_either(&self) -> Ptr { 81 | Ptr { 82 | inner: self.inner.clone(), 83 | ref_counter: self.ref_counter.make_new(&self.inner).into(), 84 | } 85 | } 86 | } 87 | 88 | impl Clone for Ptr 89 | where 90 | Rc: RefCounter, 91 | { 92 | fn clone(&self) -> Self { 93 | Self { 94 | inner: self.inner.clone(), 95 | ref_counter: self.ref_counter.make_new(self.inner.as_ref()), 96 | } 97 | } 98 | } 99 | 100 | impl Drop for Ptr 101 | where 102 | Rc: RefCounter, 103 | { 104 | fn drop(&mut self) { 105 | self.ref_counter.destroy(self.inner.as_ref()) 106 | } 107 | } 108 | 109 | impl Deref for Ptr 110 | where 111 | Rc: RefCounter, 112 | { 113 | type Target = Chan; 114 | 115 | fn deref(&self) -> &Self::Target { 116 | &self.inner 117 | } 118 | } 119 | 120 | /// The reference count of a strong address. Strong addresses will prevent the actor from being 121 | /// dropped as long as they live. Read the docs of [`Address`](crate::Address) to find 122 | /// out more. 123 | #[derive(Debug)] 124 | pub struct TxStrong(()); 125 | 126 | impl TxStrong { 127 | /// Attempt to construct a new `TxStrong` pointing to the given `inner` if there are existing 128 | /// strong references to `inner`. This will return `None` if there were 0 strong references to 129 | /// the inner. 130 | fn try_new(inner: &Chan) -> Option { 131 | // All code taken from Weak::upgrade in std 132 | use std::sync::atomic::Ordering::*; 133 | 134 | // Relaxed load because any write of 0 that we can observe leaves the field in a permanently 135 | // zero state (so a "stale" read of 0 is fine), and any other value is confirmed via the 136 | // CAS below. 137 | let mut n = inner.sender_count.load(Relaxed); 138 | 139 | loop { 140 | if n == 0 { 141 | return None; 142 | } 143 | 144 | // Relaxed is fine for the failure case because we don't have any expectations about the new state. 145 | // Acquire is necessary for the success case to synchronise with `Arc::new_cyclic`, when the inner 146 | // value can be initialized after `Weak` references have already been created. In that case, we 147 | // expect to observe the fully initialized value. 148 | match inner 149 | .sender_count 150 | .compare_exchange_weak(n, n + 1, Acquire, Relaxed) 151 | { 152 | Ok(_) => return Some(TxStrong(())), // 0-case checked above 153 | Err(old) => n = old, 154 | } 155 | } 156 | } 157 | } 158 | 159 | /// The reference count of a weak address. Weak addresses will bit prevent the actor from being 160 | /// dropped. Read the docs of [`Address`](crate::Address) to find out more. 161 | #[derive(Debug)] 162 | pub struct TxWeak(()); 163 | 164 | /// A reference counter that can be dynamically either strong or weak. 165 | #[derive(Debug)] 166 | pub enum TxEither { 167 | /// A strong reference counter. 168 | Strong(TxStrong), 169 | /// A weak reference counter. 170 | Weak(TxWeak), 171 | } 172 | 173 | /// A reference counter for the receiving end of the channel or in actor terminology, the mailbox 174 | /// of an actor. 175 | pub struct Rx(()); 176 | 177 | /// Defines a reference counting policy for a channel pointer. 178 | /// 179 | /// # Implementation note 180 | /// 181 | /// This trait partially exists because we cannot specialise `Drop` impls in Rust, otherwise, we could 182 | /// write: 183 | /// 184 | /// - `impl Drop for ChanPtr { }` 185 | /// - `impl Drop for ChanPtr { }` 186 | /// - `impl Drop for ChanPtr { }` 187 | /// 188 | /// and call the appropriate functions on `Chan`. 189 | /// 190 | /// It can also be used to generalise over the reference counter type in extension trait implementations on `Address`. For example: 191 | /// ``` 192 | /// # use xtra::{Actor, Address, refcount::RefCounter}; 193 | /// trait MyExtension { 194 | /// fn say_hi(&self) { 195 | /// println!("Hi!"); // Presumably, you would do something useful here 196 | /// } 197 | /// } 198 | /// 199 | /// impl MyExtension for Address 200 | /// where A: Actor, 201 | /// Rc: RefCounter 202 | /// {} 203 | /// ``` 204 | pub trait RefCounter: Send + Sync + 'static + Unpin + private::RefCounter {} 205 | 206 | impl RefCounter for TxStrong {} 207 | impl RefCounter for TxWeak {} 208 | impl RefCounter for TxEither {} 209 | impl RefCounter for Rx {} 210 | 211 | impl From for TxEither { 212 | fn from(strong: TxStrong) -> Self { 213 | TxEither::Strong(strong) 214 | } 215 | } 216 | 217 | impl From for TxEither { 218 | fn from(weak: TxWeak) -> Self { 219 | TxEither::Weak(weak) 220 | } 221 | } 222 | 223 | /// Private module to ensure [`RefCounter`] is sealed and can neither be implemented on other types 224 | /// nor can a user outside of this crate call functions from [`RefCounter`]. 225 | mod private { 226 | use super::*; 227 | 228 | pub trait RefCounter { 229 | /// Make a new instance of this reference counting policy. 230 | fn make_new(&self, chan: &Chan) -> Self; 231 | /// Destroy an instance of this reference counting policy. 232 | fn destroy(&self, chan: &Chan); 233 | /// Whether or not the given policy is strong. 234 | fn is_strong(&self) -> bool; 235 | } 236 | 237 | impl RefCounter for TxStrong { 238 | fn make_new(&self, inner: &Chan) -> Self { 239 | inner.on_sender_created(); 240 | 241 | TxStrong(()) 242 | } 243 | 244 | fn destroy(&self, inner: &Chan) { 245 | inner.on_sender_dropped(); 246 | } 247 | 248 | fn is_strong(&self) -> bool { 249 | true 250 | } 251 | } 252 | 253 | impl RefCounter for TxWeak { 254 | fn make_new(&self, _: &Chan) -> Self { 255 | TxWeak(()) 256 | } 257 | 258 | fn destroy(&self, _: &Chan) {} 259 | 260 | fn is_strong(&self) -> bool { 261 | false 262 | } 263 | } 264 | 265 | impl RefCounter for TxEither { 266 | fn make_new(&self, chan: &Chan) -> Self { 267 | match self { 268 | TxEither::Strong(strong) => TxEither::Strong(strong.make_new(chan)), 269 | TxEither::Weak(weak) => TxEither::Weak(weak.make_new(chan)), 270 | } 271 | } 272 | 273 | fn destroy(&self, chan: &Chan) { 274 | match self { 275 | TxEither::Strong(strong) => strong.destroy(chan), 276 | TxEither::Weak(weak) => weak.destroy(chan), 277 | } 278 | } 279 | 280 | fn is_strong(&self) -> bool { 281 | match self { 282 | TxEither::Strong(_) => true, 283 | TxEither::Weak(_) => false, 284 | } 285 | } 286 | } 287 | 288 | impl RefCounter for Rx { 289 | fn make_new(&self, inner: &Chan) -> Self { 290 | inner.on_receiver_created(); 291 | 292 | Rx(()) 293 | } 294 | 295 | fn destroy(&self, inner: &Chan) { 296 | inner.on_receiver_dropped(); 297 | } 298 | 299 | fn is_strong(&self) -> bool { 300 | true 301 | } 302 | } 303 | } 304 | 305 | #[cfg(test)] 306 | mod tests { 307 | use std::mem::size_of; 308 | 309 | use super::*; 310 | 311 | #[test] 312 | fn size_of_ptr() { 313 | assert_eq!(size_of::>(), 8); 314 | assert_eq!(size_of::>(), 8); 315 | assert_eq!(size_of::>(), 8); 316 | assert_eq!(size_of::>(), 16); 317 | } 318 | 319 | #[test] 320 | fn starts_with_rc_count_one() { 321 | let inner = Arc::new(Chan::new(None)); 322 | 323 | let _ptr1 = Ptr::::new(inner.clone()); 324 | 325 | assert_eq!(inner.sender_count.load(atomic::Ordering::SeqCst), 1) 326 | } 327 | 328 | #[test] 329 | fn clone_increments_count() { 330 | let inner = Arc::new(Chan::new(None)); 331 | 332 | let ptr1 = Ptr::::new(inner.clone()); 333 | #[allow(clippy::redundant_clone)] 334 | let _ptr2 = ptr1.clone(); 335 | 336 | assert_eq!(inner.sender_count.load(atomic::Ordering::SeqCst), 2) 337 | } 338 | 339 | #[test] 340 | fn dropping_last_reference_calls_on_last_drop() { 341 | let inner = Arc::new(Chan::new(None)); 342 | 343 | let ptr1 = Ptr::::new(inner.clone()); 344 | std::mem::drop(ptr1); 345 | 346 | assert_eq!(inner.sender_count.load(atomic::Ordering::SeqCst), 0); 347 | } 348 | 349 | #[test] 350 | fn can_convert_tx_strong_into_weak() { 351 | let inner = Arc::new(Chan::new(None)); 352 | 353 | let strong_ptr = Ptr::::new(inner.clone()); 354 | let _weak_ptr = strong_ptr.to_tx_weak(); 355 | 356 | assert_eq!(inner.sender_count.load(atomic::Ordering::SeqCst), 1); 357 | } 358 | 359 | #[test] 360 | fn can_clone_either() { 361 | let inner = Arc::new(Chan::new(None)); 362 | 363 | let strong_ptr = Ptr::::new(inner.clone()); 364 | let either_ptr_1 = strong_ptr.to_tx_either(); 365 | #[allow(clippy::redundant_clone)] 366 | let _either_ptr_2 = either_ptr_1.clone(); 367 | 368 | assert_eq!(inner.sender_count.load(atomic::Ordering::SeqCst), 3); 369 | } 370 | 371 | #[test] 372 | fn either_is_strong() { 373 | let inner = Arc::new(Chan::new(None)); 374 | 375 | let strong_ptr = Ptr::::new(inner); 376 | let either_ptr = strong_ptr.to_tx_either(); 377 | 378 | assert!(either_ptr.is_strong()); 379 | } 380 | 381 | struct Foo; 382 | 383 | impl crate::Actor for Foo { 384 | type Stop = (); 385 | 386 | async fn stopped(self) -> Self::Stop {} 387 | } 388 | } 389 | -------------------------------------------------------------------------------- /xtra/src/lib.rs: -------------------------------------------------------------------------------- 1 | //! xtra is a tiny, fast, and safe actor system. 2 | 3 | #![cfg_attr(docsrs, feature(doc_cfg))] 4 | #![deny(unsafe_code, missing_docs)] 5 | 6 | use std::fmt; 7 | use std::future::Future; 8 | use std::ops::ControlFlow; 9 | 10 | use futures_util::future::Either; 11 | use futures_util::{future, FutureExt}; 12 | 13 | pub use self::address::{Address, WeakAddress}; 14 | pub use self::context::Context; 15 | pub use self::mailbox::Mailbox; 16 | pub use self::scoped_task::scoped; 17 | pub use self::send_future::{ActorErasedSending, ActorNamedSending, Receiver, SendFuture}; 18 | #[allow(unused_imports)] 19 | pub use self::spawn::*; // Star export so we don't have to write `cfg` attributes here. 20 | 21 | pub mod address; 22 | mod chan; 23 | mod context; 24 | mod dispatch_future; 25 | mod envelope; 26 | mod instrumentation; 27 | mod mailbox; 28 | pub mod message_channel; 29 | mod recv_future; 30 | /// This module contains a way to scope a future to the lifetime of an actor, stopping it before it 31 | /// completes if the actor it is associated with stops too. 32 | pub mod scoped_task; 33 | mod send_future; 34 | mod spawn; 35 | 36 | /// Commonly used types from xtra 37 | pub mod prelude { 38 | pub use crate::address::Address; 39 | pub use crate::context::Context; 40 | pub use crate::message_channel::MessageChannel; 41 | #[doc(no_inline)] 42 | pub use crate::{Actor, Handler, Mailbox}; 43 | } 44 | 45 | /// This module contains types representing the strength of an address's reference counting, which 46 | /// influences whether the address will keep the actor alive for as long as it lives. 47 | pub mod refcount { 48 | pub use crate::chan::{RefCounter, TxEither as Either, TxStrong as Strong, TxWeak as Weak}; 49 | } 50 | 51 | /// Provides a default implementation of the [`Actor`] trait for the given type with a [`Stop`](Actor::Stop) type of `()` and empty lifecycle functions. 52 | /// 53 | /// The [`Actor`] custom derive takes away some boilerplate for a standard actor: 54 | /// 55 | /// ```rust 56 | /// #[derive(xtra::Actor)] 57 | /// pub struct MyActor; 58 | /// # 59 | /// # fn assert_actor() { } 60 | /// # 61 | /// # fn main() { 62 | /// # assert_actor::() 63 | /// # } 64 | /// ``` 65 | /// This macro will generate the following [`Actor`] implementation: 66 | /// 67 | /// ```rust,no_run 68 | /// # use xtra::prelude::*; 69 | /// pub struct MyActor; 70 | /// 71 | /// 72 | /// impl xtra::Actor for MyActor { 73 | /// type Stop = (); 74 | /// 75 | /// async fn stopped(self) { } 76 | /// } 77 | /// ``` 78 | /// 79 | /// Please note that implementing the [`Actor`] trait is still very easy and this macro purposely does not support a plethora of usecases but is meant to handle the most common ones. 80 | /// For example, whilst it does support actors with type parameters, lifetimes are entirely unsupported. 81 | #[cfg(feature = "macros")] 82 | pub use macros::Actor; 83 | 84 | use crate::recv_future::Message; 85 | 86 | /// Defines that an [`Actor`] can handle a given message `M`. 87 | /// 88 | /// # Example 89 | /// 90 | /// ```rust 91 | /// # use xtra::prelude::*; 92 | /// # struct MyActor; 93 | /// # impl Actor for MyActor {type Stop = (); async fn stopped(self) -> Self::Stop {} } 94 | /// struct Msg; 95 | /// 96 | /// 97 | /// impl Handler for MyActor { 98 | /// type Return = u32; 99 | /// 100 | /// async fn handle(&mut self, message: Msg, ctx: &mut Context) -> u32 { 101 | /// 20 102 | /// } 103 | /// } 104 | /// 105 | /// fn main() { 106 | /// # #[cfg(feature = "smol")] 107 | /// smol::block_on(async { 108 | /// let addr = xtra::spawn_smol(MyActor, Mailbox::unbounded()); 109 | /// assert_eq!(addr.send(Msg).await, Ok(20)); 110 | /// }) 111 | /// } 112 | /// ``` 113 | pub trait Handler: Actor { 114 | /// The return value of this handler. 115 | type Return: Send + 'static; 116 | 117 | /// Handle a given message, returning its result. 118 | fn handle( 119 | &mut self, 120 | message: M, 121 | ctx: &mut Context, 122 | ) -> impl Future + Send; 123 | } 124 | 125 | /// An actor which can handle message one at a time. Actors can only be 126 | /// communicated with by sending messages through their [`Address`]es. 127 | /// They can modify their private state, respond to messages, and spawn other actors. They can also 128 | /// stop themselves through their [`Context`] by calling [`Context::stop_self`]. 129 | /// This will result in any attempt to send messages to the actor in future failing. 130 | /// 131 | /// # Example 132 | /// 133 | /// ```rust 134 | /// # use xtra::prelude::*; 135 | /// # use std::time::Duration; 136 | /// struct MyActor; 137 | /// 138 | /// 139 | /// impl Actor for MyActor { 140 | /// type Stop = (); 141 | /// async fn started(&mut self, ctx: &Mailbox) -> Result<(), Self::Stop> { 142 | /// println!("Started!"); 143 | /// 144 | /// Ok(()) 145 | /// } 146 | /// 147 | /// async fn stopped(self) -> Self::Stop { 148 | /// println!("Finally stopping."); 149 | /// } 150 | /// } 151 | /// 152 | /// struct Goodbye; 153 | /// 154 | /// 155 | /// impl Handler for MyActor { 156 | /// type Return = (); 157 | /// 158 | /// async fn handle(&mut self, _: Goodbye, ctx: &mut Context) { 159 | /// println!("Goodbye!"); 160 | /// ctx.stop_all(); 161 | /// } 162 | /// } 163 | /// 164 | /// // Will print "Started!", "Goodbye!", and then "Finally stopping." 165 | /// # #[cfg(feature = "smol")] 166 | /// smol::block_on(async { 167 | /// let addr = xtra::spawn_smol(MyActor, Mailbox::unbounded()); 168 | /// addr.send(Goodbye).await; 169 | /// 170 | /// smol::Timer::after(Duration::from_secs(1)).await; // Give it time to run 171 | /// }) 172 | /// ``` 173 | /// 174 | /// For longer examples, see the `examples` directory. 175 | pub trait Actor: 'static + Send + Sized { 176 | /// Value returned from the actor when [`Actor::stopped`] is called. 177 | type Stop: Send + 'static; 178 | 179 | /// Called as soon as the actor has been started. 180 | #[allow(unused_variables)] 181 | fn started( 182 | &mut self, 183 | mailbox: &Mailbox, 184 | ) -> impl Future> + Send { 185 | async { Ok(()) } 186 | } 187 | 188 | /// Called at the end of an actor's event loop. 189 | /// 190 | /// An actor's event loop can stop for several reasons: 191 | /// 192 | /// - The actor called [`Context::stop_self`]. 193 | /// - An actor called [`Context::stop_all`]. 194 | /// - The last [`Address`] with a [`Strong`](crate::refcount::Strong) reference count was dropped. 195 | fn stopped(self) -> impl Future + Send; 196 | } 197 | 198 | /// An error related to the actor system 199 | #[derive(Clone, Eq, PartialEq, Debug)] 200 | pub enum Error { 201 | /// The actor is no longer running and disconnected from the sending address. 202 | Disconnected, 203 | /// The message request operation was interrupted. This happens when the message result sender 204 | /// is dropped. Therefore, it should never be returned from [`detached`](SendFuture::detach) [`SendFuture`]s 205 | /// This could be due to the actor's event loop being shut down, or due to a custom timeout. 206 | /// Unlike [`Error::Disconnected`], it does not necessarily imply that any retries or further 207 | /// attempts to interact with the actor will result in an error. 208 | Interrupted, 209 | } 210 | 211 | impl fmt::Display for Error { 212 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 213 | match self { 214 | Error::Disconnected => f.write_str("Actor address disconnected"), 215 | Error::Interrupted => f.write_str("Message request interrupted"), 216 | } 217 | } 218 | } 219 | 220 | impl std::error::Error for Error {} 221 | 222 | /// Run the provided actor. 223 | /// 224 | /// This is the primary event loop of an actor which takes messages out of the mailbox and hands 225 | /// them to the actor. 226 | pub async fn run(mailbox: Mailbox, mut actor: A) -> A::Stop 227 | where 228 | A: Actor, 229 | { 230 | if let Err(stop) = actor.started(&mailbox).await { 231 | return stop; 232 | } 233 | 234 | while let ControlFlow::Continue(()) = yield_once(&mailbox, &mut actor).await {} 235 | 236 | actor.stopped().await 237 | } 238 | 239 | /// Yields to the manager to handle one message, returning the actor should be shut down or not. 240 | pub async fn yield_once(mailbox: &Mailbox, actor: &mut A) -> ControlFlow<(), ()> 241 | where 242 | A: Actor, 243 | { 244 | mailbox.next().await.dispatch_to(actor).await 245 | } 246 | 247 | /// Handle any incoming messages for the actor while running a given future. This is similar to 248 | /// [`join`], but will exit if the actor is stopped, returning the future. Returns 249 | /// `Ok` with the result of the future if it was successfully completed, or `Err` with the 250 | /// future if the actor was stopped before it could complete. It is analagous to 251 | /// [`futures::select`](futures_util::future::select). 252 | /// 253 | /// ## Example 254 | /// 255 | /// ```rust 256 | /// # use std::time::Duration; 257 | /// use futures_util::future::Either; 258 | /// # use xtra::prelude::*; 259 | /// # use smol::future; 260 | /// # struct MyActor; 261 | /// # impl Actor for MyActor { type Stop = (); async fn stopped(self) {} } 262 | /// 263 | /// struct Stop; 264 | /// struct Selecting; 265 | /// 266 | /// impl Handler for MyActor { 267 | /// type Return = (); 268 | /// 269 | /// async fn handle(&mut self, _msg: Stop, ctx: &mut Context) { 270 | /// ctx.stop_self(); 271 | /// } 272 | /// } 273 | /// 274 | /// impl Handler for MyActor { 275 | /// type Return = bool; 276 | /// 277 | /// async fn handle(&mut self, _msg: Selecting, ctx: &mut Context) -> bool { 278 | /// // Actor is still running, so this will return Either::Left 279 | /// match xtra::select(ctx.mailbox(), self, future::ready(1)).await { 280 | /// Either::Left(ans) => println!("Answer is: {}", ans), 281 | /// Either::Right(_) => panic!("How did we get here?"), 282 | /// }; 283 | /// 284 | /// let addr = ctx.mailbox().address(); 285 | /// let select = xtra::select(ctx.mailbox(), self, future::pending::<()>()); 286 | /// let _ = addr.send(Stop).detach().await; 287 | /// 288 | /// // Actor is stopping, so this will return Err, even though the future will 289 | /// // usually never complete. 290 | /// matches!(select.await, Either::Right(_)) 291 | /// } 292 | /// } 293 | /// 294 | /// # #[cfg(feature = "smol")] 295 | /// smol::block_on(async { 296 | /// let addr = xtra::spawn_smol(MyActor, Mailbox::unbounded()); 297 | /// assert!(addr.is_connected()); 298 | /// assert_eq!(addr.send(Selecting).await, Ok(true)); // Assert that the select did end early 299 | /// }) 300 | /// ``` 301 | pub async fn select(mailbox: &Mailbox, actor: &mut A, mut fut: F) -> Either 302 | where 303 | F: Future + Unpin, 304 | A: Actor, 305 | { 306 | let mut control_flow = ControlFlow::Continue(()); 307 | 308 | while control_flow.is_continue() { 309 | let (msg, unfinished) = { 310 | let mut next_msg = mailbox.next(); 311 | match future::select(fut, &mut next_msg).await { 312 | Either::Left((future_res, _)) => { 313 | if let Some(msg) = next_msg.now_or_never() { 314 | msg.dispatch_to(actor).await; 315 | } 316 | 317 | return Either::Left(future_res); 318 | } 319 | Either::Right(tuple) => tuple, 320 | } 321 | }; 322 | 323 | control_flow = msg.dispatch_to(actor).await; 324 | fut = unfinished; 325 | } 326 | 327 | Either::Right(fut) 328 | } 329 | 330 | /// Joins on a future by handling all incoming messages whilst polling it. The future will 331 | /// always be polled to completion, even if the actor is stopped. If the actor is stopped, 332 | /// handling of messages will cease, and only the future will be polled. It is somewhat 333 | /// analagous to [`futures::join`](futures_util::future::join), but it will not wait for the incoming stream of messages 334 | /// from addresses to end before returning - it will return as soon as the provided future does. 335 | /// 336 | /// ## Example 337 | /// 338 | /// ```rust 339 | /// # use std::time::Duration; 340 | /// use futures_util::FutureExt; 341 | /// # use xtra::prelude::*; 342 | /// # use smol::future; 343 | /// # struct MyActor; 344 | /// # impl Actor for MyActor { type Stop = (); async fn stopped(self) {} } 345 | /// 346 | /// struct Stop; 347 | /// struct Joining; 348 | /// 349 | /// impl Handler for MyActor { 350 | /// type Return = (); 351 | /// 352 | /// async fn handle(&mut self, _msg: Stop, ctx: &mut Context) { 353 | /// ctx.stop_self(); 354 | /// } 355 | /// } 356 | /// 357 | /// impl Handler for MyActor { 358 | /// type Return = bool; 359 | /// 360 | /// async fn handle(&mut self, _msg: Joining, ctx: &mut Context) -> bool { 361 | /// let addr = ctx.mailbox().address(); 362 | /// let join = xtra::join(ctx.mailbox(), self, future::ready::<()>(())); 363 | /// let _ = addr.send(Stop).detach().await; 364 | /// 365 | /// // Actor is stopping, but the join should still evaluate correctly 366 | /// join.now_or_never().is_some() 367 | /// } 368 | /// } 369 | /// 370 | /// # #[cfg(feature = "smol")] 371 | /// smol::block_on(async { 372 | /// let addr = xtra::spawn_smol(MyActor, Mailbox::unbounded()); 373 | /// assert!(addr.is_connected()); 374 | /// assert_eq!(addr.send(Joining).await, Ok(true)); // Assert that the join did evaluate the future 375 | /// }) 376 | /// ``` 377 | pub async fn join(mailbox: &Mailbox, actor: &mut A, fut: F) -> R 378 | where 379 | F: Future, 380 | A: Actor, 381 | { 382 | futures_util::pin_mut!(fut); 383 | match select(mailbox, actor, fut).await { 384 | Either::Left(res) => res, 385 | Either::Right(fut) => fut.await, 386 | } 387 | } 388 | -------------------------------------------------------------------------------- /xtra/src/address.rs: -------------------------------------------------------------------------------- 1 | //! An address to an actor is a way to send it a message. An address allows an actor to be sent any 2 | //! kind of message that it can receive. 3 | 4 | use std::cmp::Ordering; 5 | use std::fmt::{self, Debug, Formatter}; 6 | use std::future::Future; 7 | use std::hash::{Hash, Hasher}; 8 | use std::pin::Pin; 9 | use std::task::{Context, Poll}; 10 | 11 | use event_listener::EventListener; 12 | use futures_util::FutureExt; 13 | 14 | use crate::refcount::{Either, RefCounter, Strong, Weak}; 15 | use crate::send_future::{ActorNamedBroadcasting, Broadcast, ResolveToHandlerReturn}; 16 | use crate::{chan, ActorNamedSending, Handler, SendFuture}; 17 | 18 | /// An [`Address`] is a reference to an actor through which messages can be sent. 19 | /// 20 | /// [`Address`]es can be cloned to obtain more addresses to the same actor. 21 | /// By default (i.e without specifying the second type parameter, `Rc`, to be 22 | /// [`Weak`], [`Address`]es are strong. Therefore, when all [`Address`]es 23 | /// are dropped, the actor will be stopped. In other words, any existing [`Address`]es will inhibit 24 | /// the dropping of an actor. If this is undesirable, then a [`WeakAddress`] 25 | /// should be used instead. 26 | /// 27 | /// The initial [`Address`] of an actor is returned when you construct a new [`Mailbox`](crate::Mailbox). 28 | /// 29 | /// ## Mailboxes 30 | /// 31 | /// Internally, a mailbox has three, more specific mailboxes, each for a specific kind of message: 32 | /// 1. The default priority, or ordered mailbox. 33 | /// 2. The priority mailbox. 34 | /// 3. The broadcast mailbox. 35 | /// 36 | /// The first two mailboxes are shared between all actors on the same address, whilst each actor 37 | /// has its own broadcast mailbox. 38 | /// 39 | /// The actor's mailbox capacity applies severally to each mailbox. This means that an actor can 40 | /// have a total of `cap` messages in every mailbox before it is totally full. However, it must only 41 | /// have `cap` in a given mailbox for any sends to that mailbox to be caused to wait for free space 42 | /// and thus exercise backpressure on senders. 43 | /// 44 | /// ### Default priority 45 | /// 46 | /// The default priority mailbox contains messages which will be handled in order of sending. This is 47 | /// a special property, as the other two mailboxes do not preserve send order! 48 | /// The vast majority of actor messages will probably be sent to this mailbox. They have default 49 | /// priority - a message will be taken from this mailbox next only if the other two mailboxes are empty. 50 | /// 51 | /// ### Priority 52 | /// 53 | /// The priority mailbox contains messages which will be handled in order of their priority.This 54 | /// can be used to make sure that critical maintenance tasks such as pings are handled as soon as 55 | /// possible. Keep in mind that if this becomes full, attempting to send in a higher priority message 56 | /// than the current highest will still result in waiting for at least one priority message 57 | /// to be handled. 58 | /// 59 | /// ### Broadcast 60 | /// 61 | /// The broadcast mailbox contains messages which will be handled by every single actor, in order 62 | /// of their priority. All actors must handle a message for it to be removed from the mailbox and 63 | /// the length to decrease. This means that the backpressure provided by [`Address::broadcast`] will 64 | /// wait for the slowest actor. 65 | pub struct Address(pub(crate) chan::Ptr); 66 | 67 | impl Debug for Address { 68 | fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { 69 | let actor_type = std::any::type_name::(); 70 | let rc_type = std::any::type_name::() 71 | .replace("xtra::chan::ptr::", "") 72 | .replace("Tx", ""); 73 | 74 | f.debug_struct(&format!("Address<{}, {}>", actor_type, rc_type)) 75 | .field("addresses", &self.0.sender_count()) 76 | .field("mailboxes", &self.0.receiver_count()) 77 | .finish() 78 | } 79 | } 80 | 81 | /// A [`WeakAddress`] is a reference to an actor through which messages can be 82 | /// sent. It can be cloned. Unlike [`Address`], a [`WeakAddress`] will not inhibit 83 | /// the dropping of an actor. It is created by the [`Address::downgrade`] 84 | /// method. 85 | pub type WeakAddress = Address; 86 | 87 | impl WeakAddress { 88 | /// Try to upgrade this [`WeakAddress`] to a strong one. 89 | /// 90 | /// This will yield `None` if there are no more other strong addresses around. 91 | pub fn try_upgrade(&self) -> Option> { 92 | Some(Address(self.0.try_to_tx_strong()?)) 93 | } 94 | } 95 | 96 | /// Functions which apply only to strong addresses (the default kind). 97 | impl Address { 98 | /// Create a weak address to the actor. Unlike with the strong variety of address (this kind), 99 | /// an actor will not be prevented from being dropped if only weak sinks, channels, and 100 | /// addresses exist. 101 | pub fn downgrade(&self) -> WeakAddress { 102 | Address(self.0.to_tx_weak()) 103 | } 104 | } 105 | 106 | /// Functions which apply only to addresses which can either be strong or weak. 107 | impl Address { 108 | /// Converts this address into a weak address. 109 | pub fn downgrade(&self) -> WeakAddress { 110 | Address(self.0.to_tx_weak()) 111 | } 112 | } 113 | 114 | /// Functions which apply to any kind of address, be they strong or weak. 115 | impl Address 116 | where 117 | Rc: RefCounter + Into, 118 | { 119 | /// Convert this address into a generic address which can be weak or strong. 120 | pub fn as_either(&self) -> Address { 121 | Address(self.0.to_tx_either()) 122 | } 123 | } 124 | 125 | /// Functions which apply to any kind of address, be they strong or weak. 126 | impl Address { 127 | /// Returns whether the actors referred to by this address are running and accepting messages. 128 | /// 129 | /// ```rust 130 | /// # use xtra::prelude::*; 131 | /// # use std::time::Duration; 132 | /// # struct MyActor; 133 | /// # impl Actor for MyActor {type Stop = (); async fn stopped(self) -> Self::Stop {} } 134 | /// struct Shutdown; 135 | /// 136 | /// 137 | /// impl Handler for MyActor { 138 | /// type Return = (); 139 | /// 140 | /// async fn handle(&mut self, _: Shutdown, ctx: &mut Context) { 141 | /// ctx.stop_all(); 142 | /// } 143 | /// } 144 | /// 145 | /// # #[cfg(feature = "smol")] 146 | /// smol::block_on(async { 147 | /// let addr = xtra::spawn_smol(MyActor, Mailbox::unbounded()); 148 | /// assert!(addr.is_connected()); 149 | /// addr.send(Shutdown).await; 150 | /// smol::Timer::after(Duration::from_secs(1)).await; // Give it time to shut down 151 | /// assert!(!addr.is_connected()); 152 | /// }) 153 | /// ``` 154 | pub fn is_connected(&self) -> bool { 155 | self.0.is_connected() 156 | } 157 | 158 | /// Returns the number of messages in the actor's mailbox. This will be the sum of broadcast 159 | /// messages, priority messages, and ordered messages. It can be up to three times the capacity, 160 | /// as the capacity is for each send type (broadcast, priority, and ordered). 161 | pub fn len(&self) -> usize { 162 | self.0.len() 163 | } 164 | 165 | /// The capacity of the actor's mailbox per send type (broadcast, priority, and ordered). 166 | pub fn capacity(&self) -> Option { 167 | self.0.capacity() 168 | } 169 | 170 | /// Returns whether the actor's mailbox is empty. 171 | pub fn is_empty(&self) -> bool { 172 | self.len() == 0 173 | } 174 | 175 | /// Send a message to the actor. The message will, by default, have a priority of 0 and be sent 176 | /// into the ordered queue. This can be configured through [`SendFuture::priority`]. 177 | /// 178 | /// The actor must implement [`Handler`] for this to work. 179 | /// 180 | /// This function returns a [`Future`](SendFuture) that resolves to the [`Return`](crate::Handler::Return) value of the handler. 181 | /// The [`SendFuture`] will resolve to [`Err(Disconnected)`] in case the actor is stopped and not accepting messages. 182 | #[allow(clippy::type_complexity)] 183 | pub fn send( 184 | &self, 185 | message: M, 186 | ) -> SendFuture, ResolveToHandlerReturn<>::Return>> 187 | where 188 | M: Send + 'static, 189 | A: Handler, 190 | { 191 | SendFuture::sending_named(message, self.0.clone()) 192 | } 193 | 194 | /// Send a message to all actors on this address. The message will, by default, have a priority 195 | /// of 0. This can be configured through [`SendFuture::priority`]. 196 | /// 197 | /// The actor must implement [`Handler`] for this to work where [`Handler::Return`] is 198 | /// set to `()`. 199 | pub fn broadcast(&self, msg: M) -> SendFuture, Broadcast> 200 | where 201 | M: Clone + Send + Sync + 'static, 202 | A: Handler, 203 | { 204 | SendFuture::broadcast_named(msg, self.0.clone()) 205 | } 206 | 207 | /// Waits until this address becomes disconnected. Note that if this is called on a strong 208 | /// address, it will only ever trigger if the actor calls [`Context::stop_self`](crate::Context::stop_self), 209 | /// as the address would prevent the actor being dropped due to too few strong addresses. 210 | pub fn join(&self) -> ActorJoinHandle { 211 | ActorJoinHandle(self.0.disconnect_listener()) 212 | } 213 | 214 | /// Returns true if this address and the other address point to the same actor. This is 215 | /// distinct from the implementation of `PartialEq` as it ignores reference count type, which 216 | /// must be the same for `PartialEq` to return `true`. 217 | pub fn same_actor(&self, other: &Address) -> bool { 218 | self.0.inner_ptr() == other.0.inner_ptr() 219 | } 220 | 221 | /// Converts this address into a sink that can be used to send messages to the actor. These 222 | /// messages will have default priority and will be handled in send order. 223 | /// 224 | /// When converting an [`Address`] into a [`Sink`], it is important to think about the address' 225 | /// reference counts. By default [`Address`]es are [`Strong`]. The [`Sink`] wraps the [`Address`] 226 | /// for its entire lifetime and will thus inherit the reference count type. 227 | /// 228 | /// If you are going to use [`Address::into_sink`] in combination with things like 229 | /// [`Stream::forward`](futures_util::stream::StreamExt::forward), bear in mind that a 230 | /// strong [`Address`] will keep the actor alive for as long as that 231 | /// [`Stream`](futures_util::stream::Stream) is being polled. Depending on your usecase, you 232 | /// may want to use a [`WeakAddress`] instead. 233 | /// 234 | /// Because [`Sink`]s do not return anything, this function is only available for messages with 235 | /// a [`Handler`] implementation that sets [`Return`](Handler::Return) to `()`. 236 | /// 237 | /// [`Sink`]: futures_sink::Sink 238 | #[cfg(feature = "sink")] 239 | pub fn into_sink(self) -> impl futures_sink::Sink 240 | where 241 | A: Handler, 242 | M: Send + 'static, 243 | { 244 | futures_util::sink::unfold((), move |(), message| self.send(message)) 245 | } 246 | } 247 | 248 | /// A future which will complete when the corresponding actor stops and its address becomes 249 | /// disconnected. 250 | #[must_use = "Futures do nothing unless polled"] 251 | pub struct ActorJoinHandle(Option); 252 | 253 | impl Future for ActorJoinHandle { 254 | type Output = (); 255 | 256 | fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { 257 | match self.0.take() { 258 | Some(mut listener) => match listener.poll_unpin(cx) { 259 | Poll::Ready(()) => Poll::Ready(()), 260 | Poll::Pending => { 261 | self.0 = Some(listener); 262 | Poll::Pending 263 | } 264 | }, 265 | None => Poll::Ready(()), 266 | } 267 | } 268 | } 269 | 270 | // Required because #[derive] adds an A: Clone bound 271 | impl Clone for Address { 272 | fn clone(&self) -> Self { 273 | Address(self.0.clone()) 274 | } 275 | } 276 | 277 | /// Determines whether this and the other address point to the same actor mailbox **and** 278 | /// they have reference count type equality. This means that this will only return true if 279 | /// [`Address::same_actor`] returns true **and** if they both have weak or strong reference 280 | /// counts. [`Either`](crate::refcount::Either) will compare as whichever reference count type 281 | /// it wraps. 282 | impl PartialEq> for Address { 283 | fn eq(&self, other: &Address) -> bool { 284 | (self.same_actor(other)) && (self.0.is_strong() == other.0.is_strong()) 285 | } 286 | } 287 | 288 | impl Eq for Address {} 289 | 290 | /// Compare this address to another. This comparison has little semantic meaning, and is intended 291 | /// to be used for comparison-based indexing only (e.g to allow addresses to be keys in binary search 292 | /// trees). The pointer of the actors' mailboxes will be compared, and if they are equal, a strong 293 | /// address will compare as greater than a weak one. 294 | impl PartialOrd> for Address { 295 | fn partial_cmp(&self, other: &Address) -> Option { 296 | Some(match self.0.inner_ptr().cmp(&other.0.inner_ptr()) { 297 | Ordering::Equal => self.0.is_strong().cmp(&other.0.is_strong()), 298 | ord => ord, 299 | }) 300 | } 301 | } 302 | 303 | impl Ord for Address { 304 | fn cmp(&self, other: &Self) -> Ordering { 305 | self.0.inner_ptr().cmp(&other.0.inner_ptr()) 306 | } 307 | } 308 | 309 | impl Hash for Address { 310 | fn hash(&self, state: &mut H) { 311 | state.write_usize(self.0.inner_ptr() as *const _ as usize); 312 | state.write_u8(self.0.is_strong() as u8); 313 | state.finish(); 314 | } 315 | } 316 | -------------------------------------------------------------------------------- /xtra/src/send_future.rs: -------------------------------------------------------------------------------- 1 | use std::future::Future; 2 | use std::mem; 3 | use std::pin::Pin; 4 | use std::sync::Arc; 5 | use std::task::{Context, Poll}; 6 | 7 | use futures_core::FusedFuture; 8 | use futures_util::FutureExt; 9 | 10 | use crate::chan::{MailboxFull, MessageToAll, MessageToOne, RefCounter, WaitingSender}; 11 | use crate::envelope::{BroadcastEnvelopeConcrete, ReturningEnvelope}; 12 | use crate::{chan, Error, Handler}; 13 | 14 | /// A [`Future`] that represents the state of sending a message to an actor. 15 | /// 16 | /// By default, a [`SendFuture`] will resolve to the return value of the handler (see [`Handler::Return`](crate::Handler::Return)). 17 | /// This behaviour can be changed by calling [`detach`](SendFuture::detach). 18 | /// 19 | /// A detached [`SendFuture`] will resolve once the message is successfully queued into the actor's mailbox and resolve to the [`Receiver`]. 20 | /// The [`Receiver`] itself is a future that will resolve to the return value of the [`Handler`](crate::Handler). 21 | /// 22 | /// In other words, detaching a [`SendFuture`] allows the current task to continue while the corresponding [`Handler`] of the actor processes the message. 23 | /// 24 | /// In case an actor's mailbox is bounded, [`SendFuture`] will yield `Pending` until the message is queued successfully. 25 | /// This allows an actor to exercise backpressure on its users. 26 | #[must_use = "Futures do nothing unless polled"] 27 | pub struct SendFuture { 28 | sending: F, 29 | state: S, 30 | } 31 | 32 | /// State-type for [`SendFuture`] to declare that it should resolve to the return value of the [`Handler`](crate::Handler). 33 | pub struct ResolveToHandlerReturn(Receiver); 34 | 35 | /// State-type for [`SendFuture`] to declare that it should resolve to a [`Receiver`] once the message is queued into the actor's mailbox. 36 | /// 37 | /// The [`Receiver`] can be used to await the completion of the handler separately. 38 | pub struct ResolveToReceiver(Option>); 39 | 40 | /// State-type for [`SendFuture`] to declare that it is a broadcast. 41 | pub struct Broadcast(()); 42 | 43 | impl SendFuture> 44 | where 45 | F: Future, 46 | { 47 | /// Detaches this future from receiving the response of the handler. 48 | /// 49 | /// Awaiting a detached [`SendFuture`] will queue the message in the actor's mailbox and return you _another_ [`Future`] for receiving the response. 50 | pub fn detach(self) -> SendFuture> { 51 | SendFuture { 52 | sending: self.sending, 53 | state: self.state.resolve_to_receiver(), 54 | } 55 | } 56 | } 57 | 58 | impl SendFuture 59 | where 60 | F: private::SetPriority, 61 | { 62 | /// Set the priority of a given message. See [`Address`](crate::Address) documentation for more info. 63 | /// 64 | /// Panics if this future has already been polled. 65 | pub fn priority(mut self, new_priority: u32) -> Self { 66 | self.sending.set_priority(new_priority); 67 | 68 | self 69 | } 70 | } 71 | 72 | /// "Sending" state of [`SendFuture`] for cases where the actor type is named and we sent a single message. 73 | #[must_use = "Futures do nothing unless polled"] 74 | pub struct ActorNamedSending(Sending, Rc>); 75 | 76 | /// "Sending" state of [`SendFuture`] for cases where the actor type is named and we broadcast a message. 77 | #[must_use = "Futures do nothing unless polled"] 78 | pub struct ActorNamedBroadcasting(Sending, Rc>); 79 | 80 | /// "Sending" state of [`SendFuture`] for cases where the actor type is erased. 81 | #[must_use = "Futures do nothing unless polled"] 82 | pub struct ActorErasedSending(Box); 83 | 84 | impl SendFuture, ResolveToHandlerReturn> 85 | where 86 | R: Send + 'static, 87 | Rc: RefCounter, 88 | { 89 | /// Construct a [`SendFuture`] that contains the actor's name in its type. 90 | /// 91 | /// Compared to [`SendFuture::sending_erased`], this function avoids one allocation. 92 | pub(crate) fn sending_named(message: M, sender: chan::Ptr) -> Self 93 | where 94 | A: Handler, 95 | M: Send + 'static, 96 | { 97 | let (envelope, receiver) = ReturningEnvelope::::new(message, 0); 98 | 99 | Self { 100 | sending: ActorNamedSending(Sending::New { 101 | msg: Box::new(envelope) as MessageToOne, 102 | sender, 103 | }), 104 | state: ResolveToHandlerReturn::new(receiver), 105 | } 106 | } 107 | } 108 | 109 | impl SendFuture> { 110 | pub(crate) fn sending_erased(message: M, sender: chan::Ptr) -> Self 111 | where 112 | Rc: RefCounter, 113 | A: Handler, 114 | M: Send + 'static, 115 | R: Send + 'static, 116 | { 117 | let (envelope, receiver) = ReturningEnvelope::::new(message, 0); 118 | 119 | Self { 120 | sending: ActorErasedSending(Box::new(Sending::New { 121 | msg: Box::new(envelope) as MessageToOne, 122 | sender, 123 | })), 124 | state: ResolveToHandlerReturn::new(receiver), 125 | } 126 | } 127 | } 128 | 129 | impl SendFuture, Broadcast> 130 | where 131 | Rc: RefCounter, 132 | { 133 | pub(crate) fn broadcast_named(msg: M, sender: chan::Ptr) -> Self 134 | where 135 | A: Handler, 136 | M: Clone + Send + Sync + 'static, 137 | { 138 | let envelope = BroadcastEnvelopeConcrete::new(msg, 0); 139 | 140 | Self { 141 | sending: ActorNamedBroadcasting(Sending::New { 142 | msg: Arc::new(envelope) as MessageToAll, 143 | sender, 144 | }), 145 | state: Broadcast(()), 146 | } 147 | } 148 | } 149 | 150 | #[allow(dead_code)] // This will useful later. 151 | impl SendFuture { 152 | pub(crate) fn broadcast_erased(msg: M, sender: chan::Ptr) -> Self 153 | where 154 | Rc: RefCounter, 155 | A: Handler, 156 | M: Clone + Send + Sync + 'static, 157 | { 158 | let envelope = BroadcastEnvelopeConcrete::new(msg, 0); 159 | 160 | Self { 161 | sending: ActorErasedSending(Box::new(Sending::New { 162 | msg: Arc::new(envelope) as MessageToAll, 163 | sender, 164 | })), 165 | state: Broadcast(()), 166 | } 167 | } 168 | } 169 | 170 | /// The core state machine around sending a message to an actor's mailbox. 171 | #[must_use = "Futures do nothing unless polled"] 172 | enum Sending { 173 | New { msg: M, sender: chan::Ptr }, 174 | WaitingToSend(WaitingSender), 175 | Done, 176 | } 177 | 178 | impl Future for Sending, Rc> 179 | where 180 | Rc: RefCounter, 181 | { 182 | type Output = Result<(), Error>; 183 | 184 | fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { 185 | let this = self.get_mut(); 186 | 187 | loop { 188 | match mem::replace(this, Sending::Done) { 189 | Sending::New { msg, sender } => match sender.try_send_to_one(msg)? { 190 | Ok(()) => return Poll::Ready(Ok(())), 191 | Err(MailboxFull(waiting)) => { 192 | *this = Sending::WaitingToSend(waiting); 193 | } 194 | }, 195 | Sending::WaitingToSend(mut waiting) => { 196 | return match waiting.poll_unpin(cx)? { 197 | Poll::Ready(()) => Poll::Ready(Ok(())), 198 | Poll::Pending => { 199 | *this = Sending::WaitingToSend(waiting); 200 | Poll::Pending 201 | } 202 | }; 203 | } 204 | Sending::Done => panic!("Polled after completion"), 205 | } 206 | } 207 | } 208 | } 209 | 210 | impl Future for Sending, Rc> 211 | where 212 | Rc: RefCounter, 213 | { 214 | type Output = Result<(), Error>; 215 | 216 | fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { 217 | let this = self.get_mut(); 218 | 219 | loop { 220 | match mem::replace(this, Sending::Done) { 221 | Sending::New { msg, sender } => match sender.try_send_to_all(msg)? { 222 | Ok(()) => return Poll::Ready(Ok(())), 223 | Err(MailboxFull(waiting)) => { 224 | *this = Sending::WaitingToSend(waiting); 225 | } 226 | }, 227 | Sending::WaitingToSend(mut waiting) => { 228 | return match waiting.poll_unpin(cx)? { 229 | Poll::Ready(()) => Poll::Ready(Ok(())), 230 | Poll::Pending => { 231 | *this = Sending::WaitingToSend(waiting); 232 | Poll::Pending 233 | } 234 | }; 235 | } 236 | Sending::Done => panic!("Polled after completion"), 237 | } 238 | } 239 | } 240 | } 241 | 242 | impl FusedFuture for Sending 243 | where 244 | Self: Future, 245 | Rc: RefCounter, 246 | { 247 | fn is_terminated(&self) -> bool { 248 | matches!(self, Sending::Done) 249 | } 250 | } 251 | 252 | impl Future for ActorNamedSending { 253 | type Output = Result<(), Error>; 254 | 255 | fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { 256 | self.get_mut().0.poll_unpin(cx) 257 | } 258 | } 259 | 260 | impl FusedFuture for ActorNamedSending 261 | where 262 | Self: Future, 263 | Rc: RefCounter, 264 | { 265 | fn is_terminated(&self) -> bool { 266 | self.0.is_terminated() 267 | } 268 | } 269 | 270 | impl Future for ActorNamedBroadcasting { 271 | type Output = Result<(), Error>; 272 | 273 | fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { 274 | self.get_mut().0.poll_unpin(cx) 275 | } 276 | } 277 | 278 | impl FusedFuture for ActorNamedBroadcasting 279 | where 280 | Self: Future, 281 | Rc: RefCounter, 282 | { 283 | fn is_terminated(&self) -> bool { 284 | self.0.is_terminated() 285 | } 286 | } 287 | 288 | impl Future for ActorErasedSending { 289 | type Output = Result<(), Error>; 290 | 291 | fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { 292 | self.get_mut().0.poll_unpin(cx) 293 | } 294 | } 295 | 296 | impl FusedFuture for ActorErasedSending { 297 | fn is_terminated(&self) -> bool { 298 | self.0.is_terminated() 299 | } 300 | } 301 | 302 | impl Future for SendFuture> 303 | where 304 | F: Future> + FusedFuture + Unpin, 305 | { 306 | type Output = Result, Error>; 307 | 308 | fn poll(self: Pin<&mut Self>, ctx: &mut Context) -> Poll { 309 | let this = self.get_mut(); 310 | 311 | if !this.sending.is_terminated() { 312 | futures_util::ready!(this.sending.poll_unpin(ctx))?; 313 | } 314 | 315 | let receiver = this.state.0.take().expect("polled after completion"); 316 | 317 | Poll::Ready(Ok(receiver)) 318 | } 319 | } 320 | 321 | impl Future for SendFuture> 322 | where 323 | F: Future> + FusedFuture + Unpin, 324 | { 325 | type Output = Result; 326 | 327 | fn poll(self: Pin<&mut Self>, ctx: &mut Context) -> Poll { 328 | let this = self.get_mut(); 329 | 330 | if !this.sending.is_terminated() { 331 | futures_util::ready!(this.sending.poll_unpin(ctx))?; 332 | } 333 | 334 | this.state.0.poll_unpin(ctx) 335 | } 336 | } 337 | impl Future for SendFuture 338 | where 339 | F: Future> + Unpin, 340 | { 341 | type Output = Result<(), Error>; 342 | 343 | fn poll(self: Pin<&mut Self>, ctx: &mut Context) -> Poll { 344 | self.get_mut().sending.poll_unpin(ctx) 345 | } 346 | } 347 | 348 | /// A [`Future`] that resolves to the [`Return`](crate::Handler::Return) value of a [`Handler`](crate::Handler). 349 | /// 350 | /// In case the actor becomes disconnected during the execution of the handler, this future will resolve to [`Error::Interrupted`]. 351 | #[must_use = "Futures do nothing unless polled"] 352 | pub struct Receiver(catty::Receiver); 353 | 354 | impl Future for Receiver { 355 | type Output = Result; 356 | 357 | fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { 358 | self.get_mut() 359 | .0 360 | .poll_unpin(cx) 361 | .map_err(|_| Error::Interrupted) 362 | } 363 | } 364 | 365 | impl ResolveToHandlerReturn { 366 | fn new(receiver: catty::Receiver) -> Self { 367 | Self(Receiver(receiver)) 368 | } 369 | 370 | fn resolve_to_receiver(self) -> ResolveToReceiver { 371 | ResolveToReceiver(Some(self.0)) 372 | } 373 | } 374 | 375 | mod private { 376 | use super::*; 377 | 378 | pub trait SetPriority { 379 | fn set_priority(&mut self, priority: u32); 380 | } 381 | 382 | impl SetPriority for Sending, Rc> 383 | where 384 | Rc: RefCounter, 385 | { 386 | fn set_priority(&mut self, new_priority: u32) { 387 | match self { 388 | Sending::New { msg, .. } => msg.set_priority(new_priority), 389 | _ => panic!("Cannot set priority after first poll"), 390 | } 391 | } 392 | } 393 | 394 | impl SetPriority for Sending, Rc> 395 | where 396 | Rc: RefCounter, 397 | { 398 | fn set_priority(&mut self, new_priority: u32) { 399 | match self { 400 | Sending::New { msg, .. } => Arc::get_mut(msg) 401 | .expect("envelope is not cloned until here") 402 | .set_priority(new_priority), 403 | _ => panic!("Cannot set priority after first poll"), 404 | } 405 | } 406 | } 407 | 408 | impl SetPriority for ActorNamedSending 409 | where 410 | Rc: RefCounter, 411 | { 412 | fn set_priority(&mut self, priority: u32) { 413 | self.0.set_priority(priority) 414 | } 415 | } 416 | 417 | impl SetPriority for ActorNamedBroadcasting 418 | where 419 | Rc: RefCounter, 420 | { 421 | fn set_priority(&mut self, priority: u32) { 422 | self.0.set_priority(priority) 423 | } 424 | } 425 | 426 | impl SetPriority for ActorErasedSending { 427 | fn set_priority(&mut self, priority: u32) { 428 | self.0.set_priority(priority) 429 | } 430 | } 431 | 432 | /// Helper trait because Rust does not allow to `+` non-auto traits in trait objects. 433 | pub trait ErasedSending: 434 | Future> + FusedFuture + SetPriority + Send + 'static + Unpin 435 | { 436 | } 437 | 438 | impl ErasedSending for F where 439 | F: Future> + FusedFuture + SetPriority + Send + 'static + Unpin 440 | { 441 | } 442 | } 443 | -------------------------------------------------------------------------------- /xtra/src/message_channel.rs: -------------------------------------------------------------------------------- 1 | //! A message channel is a channel through which you can send only one kind of message, but to 2 | //! any actor that can handle it. It is like [`Address`], but associated with 3 | //! the message type rather than the actor type. 4 | 5 | use std::fmt; 6 | use std::hash::{Hash, Hasher}; 7 | 8 | use crate::address::{ActorJoinHandle, Address}; 9 | use crate::chan::RefCounter; 10 | use crate::refcount::{Either, Strong, Weak}; 11 | use crate::send_future::{ActorErasedSending, ResolveToHandlerReturn, SendFuture}; 12 | use crate::Handler; 13 | 14 | /// A message channel is a channel through which you can send only one kind of message, but to 15 | /// any actor that can handle it. It is like [`Address`], but associated with the message type rather 16 | /// than the actor type. 17 | /// 18 | /// # Example 19 | /// 20 | /// ```rust 21 | /// # use xtra::prelude::*; 22 | /// struct WhatsYourName; 23 | /// 24 | /// struct Alice; 25 | /// struct Bob; 26 | /// 27 | /// impl Actor for Alice { 28 | /// type Stop = (); 29 | /// async fn stopped(self) { 30 | /// println!("Oh no"); 31 | /// } 32 | /// } 33 | /// # impl Actor for Bob {type Stop = (); async fn stopped(self) -> Self::Stop {} } 34 | /// 35 | /// impl Handler for Alice { 36 | /// type Return = &'static str; 37 | /// 38 | /// async fn handle(&mut self, _: WhatsYourName, _ctx: &mut Context) -> Self::Return { 39 | /// "Alice" 40 | /// } 41 | /// } 42 | /// 43 | /// impl Handler for Bob { 44 | /// type Return = &'static str; 45 | /// 46 | /// async fn handle(&mut self, _: WhatsYourName, _ctx: &mut Context) -> Self::Return { 47 | /// "Bob" 48 | /// } 49 | /// } 50 | /// 51 | /// fn main() { 52 | /// # #[cfg(feature = "smol")] 53 | /// smol::block_on(async { 54 | /// let alice = xtra::spawn_smol(Alice, Mailbox::unbounded()); 55 | /// let bob = xtra::spawn_smol(Bob, Mailbox::unbounded()); 56 | /// 57 | /// let channels = [ 58 | /// MessageChannel::new(alice), 59 | /// MessageChannel::new(bob) 60 | /// ]; 61 | /// let name = ["Alice", "Bob"]; 62 | /// 63 | /// for (channel, name) in channels.iter().zip(&name) { 64 | /// assert_eq!(*name, channel.send(WhatsYourName).await.unwrap()); 65 | /// } 66 | /// }) 67 | /// } 68 | /// ``` 69 | pub struct MessageChannel { 70 | inner: Box + Send + Sync + 'static>, 71 | } 72 | 73 | impl MessageChannel 74 | where 75 | M: Send + 'static, 76 | R: Send + 'static, 77 | { 78 | /// Construct a new [`MessageChannel`] from the given [`Address`]. 79 | /// 80 | /// The actor behind the [`Address`] must implement the [`Handler`] trait for the message type. 81 | pub fn new(address: Address) -> Self 82 | where 83 | A: Handler, 84 | Rc: RefCounter + Into, 85 | { 86 | Self { 87 | inner: Box::new(address), 88 | } 89 | } 90 | 91 | /// Returns whether the actor referred to by this message channel is running and accepting messages. 92 | pub fn is_connected(&self) -> bool { 93 | self.inner.is_connected() 94 | } 95 | 96 | /// Returns the number of messages in the actor's mailbox. 97 | /// 98 | /// Note that this does **not** differentiate between types of messages; it will return the 99 | /// count of all messages in the actor's mailbox, not only the messages sent by this 100 | /// [`MessageChannel`]. 101 | pub fn len(&self) -> usize { 102 | self.inner.len() 103 | } 104 | 105 | /// The total capacity of the actor's mailbox. 106 | /// 107 | /// Note that this does **not** differentiate between types of messages; it will return the 108 | /// total capacity of actor's mailbox, not only the messages sent by this [`MessageChannel`]. 109 | pub fn capacity(&self) -> Option { 110 | self.inner.capacity() 111 | } 112 | 113 | /// Returns whether the actor's mailbox is empty. 114 | pub fn is_empty(&self) -> bool { 115 | self.len() == 0 116 | } 117 | 118 | /// Send a message to the actor. 119 | /// 120 | /// This function returns a [`Future`](SendFuture) that resolves to the [`Return`](crate::Handler::Return) value of the handler. 121 | /// The [`SendFuture`] will resolve to [`Err(Disconnected)`] in case the actor is stopped and not accepting messages. 122 | pub fn send(&self, message: M) -> SendFuture> { 123 | self.inner.send(message) 124 | } 125 | 126 | /// Waits until this [`MessageChannel`] becomes disconnected. 127 | pub fn join(&self) -> ActorJoinHandle { 128 | self.inner.join() 129 | } 130 | 131 | /// Determines whether this and the other [`MessageChannel`] address the same actor mailbox. 132 | pub fn same_actor(&self, other: &MessageChannel) -> bool 133 | where 134 | Rc2: Send + 'static, 135 | { 136 | self.inner.to_inner_ptr() == other.inner.to_inner_ptr() 137 | } 138 | } 139 | 140 | #[cfg(feature = "sink")] 141 | impl MessageChannel 142 | where 143 | M: Send + 'static, 144 | { 145 | /// Construct a [`Sink`] from this [`MessageChannel`]. 146 | /// 147 | /// Sending an item into a [`Sink`]s does not return a value. Consequently, this function is 148 | /// only available on [`MessageChannel`]s with a return value of `()`. 149 | /// 150 | /// To create such a [`MessageChannel`] use an [`Address`] that points to an actor where the 151 | /// [`Handler`] of a given message has [`Return`](Handler::Return) set to `()`. 152 | /// 153 | /// The provided [`Sink`] will process one message at a time completely and thus enforces 154 | /// back-pressure according to the bounds of the actor's mailbox. 155 | /// 156 | /// [`Sink`]: futures_sink::Sink 157 | pub fn into_sink(self) -> impl futures_sink::Sink { 158 | futures_util::sink::unfold((), move |(), message| self.send(message)) 159 | } 160 | } 161 | 162 | impl From> for MessageChannel 163 | where 164 | A: Handler, 165 | R: Send + 'static, 166 | M: Send + 'static, 167 | Rc: RefCounter + Into, 168 | { 169 | fn from(address: Address) -> Self { 170 | MessageChannel::new(address) 171 | } 172 | } 173 | 174 | impl fmt::Debug for MessageChannel 175 | where 176 | R: Send + 'static, 177 | { 178 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 179 | let actor_type = self.inner.actor_type(); 180 | let message_type = &std::any::type_name::(); 181 | let return_type = &std::any::type_name::(); 182 | let rc_type = &std::any::type_name::() 183 | .replace("xtra::chan::ptr::", "") 184 | .replace("Tx", ""); 185 | 186 | f.debug_struct(&format!( 187 | "MessageChannel<{}, {}, {}, {}>", 188 | actor_type, message_type, return_type, rc_type 189 | )) 190 | .field("addresses", &self.inner.sender_count()) 191 | .field("mailboxes", &self.inner.receiver_count()) 192 | .finish() 193 | } 194 | } 195 | 196 | /// Determines whether this and the other message channel address the same actor mailbox **and** 197 | /// they have reference count type equality. This means that this will only return true if 198 | /// [`MessageChannel::same_actor`] returns true **and** if they both have weak or strong reference 199 | /// counts. [`Either`] will compare as whichever reference count type it wraps. 200 | impl PartialEq for MessageChannel 201 | where 202 | M: Send + 'static, 203 | R: Send + 'static, 204 | Rc: Send + 'static, 205 | { 206 | fn eq(&self, other: &Self) -> bool { 207 | self.same_actor(other) && (self.inner.is_strong() == other.inner.is_strong()) 208 | } 209 | } 210 | 211 | impl Hash for MessageChannel 212 | where 213 | M: Send + 'static, 214 | R: Send + 'static, 215 | Rc: Send + 'static, 216 | { 217 | fn hash(&self, state: &mut H) { 218 | self.inner.hash(state) 219 | } 220 | } 221 | 222 | impl Clone for MessageChannel 223 | where 224 | R: Send + 'static, 225 | { 226 | fn clone(&self) -> Self { 227 | Self { 228 | inner: self.inner.clone_channel(), 229 | } 230 | } 231 | } 232 | 233 | impl MessageChannel 234 | where 235 | M: Send + 'static, 236 | R: Send + 'static, 237 | { 238 | /// Downgrade this [`MessageChannel`] to a [`Weak`] reference count. 239 | pub fn downgrade(&self) -> MessageChannel { 240 | MessageChannel { 241 | inner: self.inner.to_weak(), 242 | } 243 | } 244 | } 245 | 246 | impl MessageChannel 247 | where 248 | M: Send + 'static, 249 | R: Send + 'static, 250 | { 251 | /// Downgrade this [`MessageChannel`] to a [`Weak`] reference count. 252 | pub fn downgrade(&self) -> MessageChannel { 253 | MessageChannel { 254 | inner: self.inner.to_weak(), 255 | } 256 | } 257 | } 258 | 259 | /// Functions which apply to any kind of [`MessageChannel`], be they strong or weak. 260 | impl MessageChannel 261 | where 262 | M: Send + 'static, 263 | R: Send + 'static, 264 | { 265 | /// Convert this [`MessageChannel`] to allow [`Either`] reference counts. 266 | pub fn as_either(&self) -> MessageChannel { 267 | MessageChannel { 268 | inner: self.inner.to_either(), 269 | } 270 | } 271 | } 272 | 273 | trait MessageChannelTrait { 274 | type Return: Send + 'static; 275 | 276 | fn is_connected(&self) -> bool; 277 | 278 | fn len(&self) -> usize; 279 | 280 | fn capacity(&self) -> Option; 281 | 282 | fn send( 283 | &self, 284 | message: M, 285 | ) -> SendFuture>; 286 | 287 | fn clone_channel( 288 | &self, 289 | ) -> Box + Send + Sync + 'static>; 290 | 291 | fn join(&self) -> ActorJoinHandle; 292 | 293 | fn to_inner_ptr(&self) -> *const (); 294 | 295 | fn is_strong(&self) -> bool; 296 | 297 | fn to_weak( 298 | &self, 299 | ) -> Box + Send + Sync + 'static>; 300 | 301 | fn sender_count(&self) -> usize; 302 | 303 | fn receiver_count(&self) -> usize; 304 | 305 | fn actor_type(&self) -> &str; 306 | 307 | fn to_either( 308 | &self, 309 | ) -> Box + Send + Sync + 'static>; 310 | 311 | fn hash(&self, state: &mut dyn Hasher); 312 | } 313 | 314 | impl MessageChannelTrait for Address 315 | where 316 | A: Handler, 317 | M: Send + 'static, 318 | R: Send + 'static, 319 | Rc: Into, 320 | { 321 | type Return = R; 322 | 323 | fn is_connected(&self) -> bool { 324 | self.is_connected() 325 | } 326 | 327 | fn len(&self) -> usize { 328 | self.len() 329 | } 330 | 331 | fn capacity(&self) -> Option { 332 | self.capacity() 333 | } 334 | 335 | fn send(&self, message: M) -> SendFuture> { 336 | SendFuture::sending_erased(message, self.0.clone()) 337 | } 338 | 339 | fn clone_channel( 340 | &self, 341 | ) -> Box + Send + Sync + 'static> { 342 | Box::new(self.clone()) 343 | } 344 | 345 | fn join(&self) -> ActorJoinHandle { 346 | self.join() 347 | } 348 | 349 | fn to_inner_ptr(&self) -> *const () { 350 | self.0.inner_ptr() 351 | } 352 | 353 | fn is_strong(&self) -> bool { 354 | self.0.is_strong() 355 | } 356 | 357 | fn to_weak( 358 | &self, 359 | ) -> Box + Send + Sync + 'static> { 360 | Box::new(Address(self.0.to_tx_weak())) 361 | } 362 | 363 | fn sender_count(&self) -> usize { 364 | self.0.sender_count() 365 | } 366 | 367 | fn receiver_count(&self) -> usize { 368 | self.0.receiver_count() 369 | } 370 | 371 | fn actor_type(&self) -> &str { 372 | std::any::type_name::() 373 | } 374 | 375 | fn to_either( 376 | &self, 377 | ) -> Box + Send + Sync + 'static> 378 | where 379 | Rc: RefCounter + Into, 380 | { 381 | Box::new(Address(self.0.to_tx_either())) 382 | } 383 | 384 | fn hash(&self, state: &mut dyn Hasher) { 385 | state.write_usize(self.0.inner_ptr() as *const _ as usize); 386 | state.write_u8(self.0.is_strong() as u8); 387 | state.finish(); 388 | } 389 | } 390 | 391 | #[cfg(test)] 392 | mod test { 393 | use std::hash::{Hash, Hasher}; 394 | 395 | use crate::{Actor, Handler, Mailbox}; 396 | 397 | type TestMessageChannel = super::MessageChannel; 398 | 399 | struct TestActor; 400 | struct TestMessage; 401 | 402 | impl Actor for TestActor { 403 | type Stop = (); 404 | 405 | async fn stopped(self) -> Self::Stop {} 406 | } 407 | 408 | impl Handler for TestActor { 409 | type Return = (); 410 | 411 | async fn handle(&mut self, _: TestMessage, _: &mut crate::Context) -> Self::Return {} 412 | } 413 | 414 | struct RecordingHasher(Vec); 415 | 416 | impl RecordingHasher { 417 | fn record_hash(value: &H) -> Vec { 418 | let mut h = Self(Vec::new()); 419 | value.hash(&mut h); 420 | assert!(!h.0.is_empty(), "the hash data not be empty"); 421 | h.0 422 | } 423 | } 424 | 425 | impl Hasher for RecordingHasher { 426 | fn finish(&self) -> u64 { 427 | 0 428 | } 429 | 430 | fn write(&mut self, bytes: &[u8]) { 431 | self.0.extend_from_slice(bytes) 432 | } 433 | } 434 | 435 | #[test] 436 | fn hashcode() { 437 | let (a1, _) = Mailbox::::unbounded(); 438 | let c1 = TestMessageChannel::new(a1.clone()); 439 | 440 | let h1 = RecordingHasher::record_hash(&c1); 441 | let h2 = RecordingHasher::record_hash(&c1.clone()); 442 | let h3 = RecordingHasher::record_hash(&TestMessageChannel::new(a1)); 443 | 444 | assert_eq!(h1, h2, "hashes from cloned channels should match"); 445 | assert_eq!( 446 | h1, h3, 447 | "hashes channels created against the same address should match" 448 | ); 449 | 450 | let h4 = RecordingHasher::record_hash(&TestMessageChannel::new( 451 | Mailbox::::unbounded().0, 452 | )); 453 | 454 | assert_ne!( 455 | h1, h4, 456 | "hashes from channels created against different addresses should differ" 457 | ); 458 | } 459 | 460 | #[test] 461 | fn partial_eq() { 462 | let (a1, _) = Mailbox::::unbounded(); 463 | let c1 = TestMessageChannel::new(a1.clone()); 464 | let c2 = c1.clone(); 465 | let c3 = TestMessageChannel::new(a1); 466 | 467 | assert_eq!(c1, c2, "cloned channels should match"); 468 | assert_eq!( 469 | c1, c3, 470 | "channels created against the same address should match" 471 | ); 472 | 473 | let c4 = TestMessageChannel::new(Mailbox::::unbounded().0); 474 | 475 | assert_ne!( 476 | c1, c4, 477 | "channels created against different addresses should differ" 478 | ); 479 | } 480 | } 481 | -------------------------------------------------------------------------------- /xtra/src/chan.rs: -------------------------------------------------------------------------------- 1 | //! Latency is prioritised over most accurate prioritisation. Specifically, at most one low priority 2 | //! message may be handled before piled-up higher priority messages will be handled. 3 | 4 | mod priority; 5 | mod ptr; 6 | mod waiting_receiver; 7 | mod waiting_sender; 8 | 9 | use std::cmp::Ordering; 10 | use std::collections::{BinaryHeap, VecDeque}; 11 | use std::sync::atomic::AtomicUsize; 12 | use std::sync::{atomic, Arc, Mutex, Weak}; 13 | use std::{cmp, mem}; 14 | 15 | use event_listener::{Event, EventListener}; 16 | pub use priority::{ByPriority, HasPriority, Priority}; 17 | pub use ptr::{Ptr, RefCounter, Rx, TxEither, TxStrong, TxWeak}; 18 | pub use waiting_receiver::WaitingReceiver; 19 | pub use waiting_sender::WaitingSender; 20 | 21 | use crate::envelope::{BroadcastEnvelope, MessageEnvelope, Shutdown}; 22 | use crate::{Actor, Error}; 23 | 24 | pub type MessageToOne = Box>; 25 | pub type MessageToAll = Arc>; 26 | pub type BroadcastQueue = spin::Mutex>>>; 27 | 28 | /// Create an actor mailbox, returning a sender and receiver for it. 29 | /// 30 | /// The given capacity is applied separately for unicast and broadcast messages. 31 | pub fn new(capacity: Option) -> (Ptr, Ptr) { 32 | let inner = Arc::new(Chan::new(capacity)); 33 | 34 | let tx = Ptr::::new(inner.clone()); 35 | let rx = Ptr::::new(inner); 36 | 37 | (tx, rx) 38 | } 39 | 40 | // Public because of private::RefCounterInner. This should never actually be exported, though. 41 | pub struct Chan { 42 | chan: Mutex>, 43 | on_shutdown: Event, 44 | sender_count: AtomicUsize, 45 | receiver_count: AtomicUsize, 46 | } 47 | 48 | impl Chan { 49 | pub fn new(capacity: Option) -> Self { 50 | Self { 51 | chan: Mutex::new(Inner::new(capacity)), 52 | on_shutdown: Event::new(), 53 | sender_count: AtomicUsize::new(0), 54 | receiver_count: AtomicUsize::new(0), 55 | } 56 | } 57 | 58 | /// Callback to be invoked every time a receiver is created 59 | pub fn on_receiver_created(&self) { 60 | self.receiver_count.fetch_add(1, atomic::Ordering::Relaxed); 61 | } 62 | 63 | /// Callback to be invoked every time a receiver is destroyed. 64 | pub fn on_receiver_dropped(&self) { 65 | // Memory orderings copied from Arc::drop 66 | if self.receiver_count.fetch_sub(1, atomic::Ordering::Release) != 1 { 67 | return; 68 | } 69 | 70 | atomic::fence(atomic::Ordering::Acquire); 71 | 72 | self.shutdown_waiting_senders(); 73 | } 74 | 75 | /// Callback to be invoked every time a sender is created. 76 | pub fn on_sender_created(&self) { 77 | // Memory orderings copied from Arc::clone 78 | self.sender_count.fetch_add(1, atomic::Ordering::Relaxed); 79 | } 80 | 81 | /// Callback to be invoked every time a sender is destroyed (i.e. dropped). 82 | pub fn on_sender_dropped(&self) { 83 | // Memory orderings copied from Arc::drop 84 | if self.sender_count.fetch_sub(1, atomic::Ordering::Release) != 1 { 85 | return; 86 | } 87 | 88 | atomic::fence(atomic::Ordering::Acquire); 89 | 90 | self.shutdown_waiting_receivers(); 91 | } 92 | 93 | /// Creates a new broadcast mailbox on this channel. 94 | pub fn new_broadcast_mailbox(&self) -> Arc> { 95 | let mailbox = Arc::new(spin::Mutex::new(BinaryHeap::new())); 96 | self.chan 97 | .lock() 98 | .unwrap() 99 | .broadcast_queues 100 | .push(Arc::downgrade(&mailbox)); 101 | 102 | mailbox 103 | } 104 | 105 | pub fn try_send_to_one( 106 | &self, 107 | mut message: MessageToOne, 108 | ) -> Result>>, Error> { 109 | if !self.is_connected() { 110 | return Err(Error::Disconnected); 111 | } 112 | 113 | message.start_span(); 114 | 115 | let mut inner = self.chan.lock().unwrap(); 116 | 117 | let unfulfilled_msg = if let Err(msg) = inner.try_fulfill_receiver(message) { 118 | msg 119 | } else { 120 | return Ok(Ok(())); 121 | }; 122 | 123 | if inner.is_unicast_full() { 124 | let (handle, waiting) = WaitingSender::new(unfulfilled_msg); 125 | inner.waiting_send_to_one.push_back(handle); 126 | 127 | return Ok(Err(MailboxFull(waiting))); 128 | } 129 | 130 | inner.unicast_queue.push(ByPriority(unfulfilled_msg)); 131 | 132 | Ok(Ok(())) 133 | } 134 | 135 | pub fn try_send_to_all( 136 | &self, 137 | mut message: MessageToAll, 138 | ) -> Result>>, Error> { 139 | if !self.is_connected() { 140 | return Err(Error::Disconnected); 141 | } 142 | 143 | Arc::get_mut(&mut message) 144 | .expect("calling after try_send not supported") 145 | .start_span(); 146 | 147 | let mut inner = self.chan.lock().unwrap(); 148 | 149 | if inner.is_broadcast_full() { 150 | let (handle, waiting) = WaitingSender::new(message); 151 | inner.waiting_send_to_all.push_back(handle); 152 | 153 | return Ok(Err(MailboxFull(waiting))); 154 | } 155 | 156 | inner.send_broadcast(message); 157 | 158 | Ok(Ok(())) 159 | } 160 | 161 | pub fn try_recv( 162 | &self, 163 | broadcast_mailbox: &BroadcastQueue, 164 | ) -> Result, WaitingReceiver> { 165 | // Lock `ChanInner` as the first thing. This avoids race conditions in modifying the broadcast mailbox. 166 | let mut inner = self.chan.lock().unwrap(); 167 | 168 | // lock broadcast mailbox for as short as possible 169 | let broadcast_priority = { 170 | // Peek priorities in order to figure out which channel should be taken from 171 | broadcast_mailbox.lock().peek().map(|it| it.priority()) 172 | }; 173 | 174 | let shared_priority: Option = inner.unicast_queue.peek().map(|it| it.priority()); 175 | 176 | // Choose which priority channel to take from 177 | match shared_priority.cmp(&broadcast_priority) { 178 | // Shared priority is greater or equal (and it is not empty) 179 | Ordering::Greater | Ordering::Equal if shared_priority.is_some() => { 180 | Ok(inner.pop_unicast().unwrap().into()) 181 | } 182 | // Shared priority is less - take from broadcast 183 | Ordering::Less => Ok(inner.pop_broadcast(broadcast_mailbox).unwrap().into()), 184 | // Equal, but both are empty, so wait or exit if shutdown 185 | _ => { 186 | // on_shutdown is only notified with inner locked, and it's locked here, so no race 187 | if self.sender_count.load(atomic::Ordering::SeqCst) == 0 { 188 | return Ok(ActorMessage::Shutdown); 189 | } 190 | 191 | let (receiver, handle) = WaitingReceiver::new(); 192 | 193 | inner.waiting_receivers_handles.push_back(handle); 194 | Err(receiver) 195 | } 196 | } 197 | } 198 | 199 | pub fn is_connected(&self) -> bool { 200 | self.receiver_count.load(atomic::Ordering::SeqCst) > 0 201 | && self.sender_count.load(atomic::Ordering::SeqCst) > 0 202 | } 203 | 204 | pub fn len(&self) -> usize { 205 | let inner = self.chan.lock().unwrap(); 206 | inner.broadcast_tail + inner.unicast_queue.len() 207 | } 208 | 209 | pub fn capacity(&self) -> Option { 210 | self.chan.lock().unwrap().capacity 211 | } 212 | 213 | /// Shutdown all [`WaitingReceiver`]s in this channel. 214 | fn shutdown_waiting_receivers(&self) { 215 | let waiting_rx = { 216 | let mut inner = match self.chan.lock() { 217 | Ok(lock) => lock, 218 | Err(_) => return, // Poisoned, ignore 219 | }; 220 | 221 | // We don't need to notify on_shutdown here, as that is only used by senders 222 | // Receivers will be woken with the fulfills below, or they will realise there are 223 | // no senders when they check the tx refcount 224 | 225 | mem::take(&mut inner.waiting_receivers_handles) 226 | }; 227 | 228 | for rx in waiting_rx { 229 | rx.notify_channel_shutdown(); 230 | } 231 | } 232 | 233 | pub fn shutdown_all_receivers(&self) 234 | where 235 | A: Actor, 236 | { 237 | self.chan 238 | .lock() 239 | .unwrap() 240 | .send_broadcast(Arc::new(Shutdown::new())); 241 | } 242 | 243 | /// Shutdown all [`WaitingSender`]s in this channel. 244 | fn shutdown_waiting_senders(&self) { 245 | let mut inner = match self.chan.lock() { 246 | Ok(lock) => lock, 247 | Err(_) => return, // Poisoned, ignore 248 | }; 249 | 250 | self.on_shutdown.notify(usize::MAX); 251 | 252 | // Let any outstanding messages drop 253 | inner.unicast_queue.clear(); 254 | inner.broadcast_queues.clear(); 255 | 256 | // Close (and potentially wake) outstanding waiting senders 257 | inner.waiting_send_to_one.clear(); 258 | inner.waiting_send_to_all.clear(); 259 | } 260 | 261 | pub fn disconnect_listener(&self) -> Option { 262 | // Listener is created before checking connectivity to avoid the following race scenario: 263 | // 264 | // 1. is_connected returns true 265 | // 2. on_shutdown is notified 266 | // 3. listener is registered 267 | // 268 | // The listener would never be woken in this scenario, as the notification preceded its 269 | // creation. 270 | let listener = self.on_shutdown.listen(); 271 | 272 | if self.is_connected() { 273 | Some(listener) 274 | } else { 275 | None 276 | } 277 | } 278 | 279 | /// Re-queue the given message. 280 | /// 281 | /// Normally, messages are delivered from the inbox straight to the actor. It can however happen 282 | /// that this process gets cancelled. In that case, this function can be used to re-queue the 283 | /// given message so it does not get lost. 284 | /// 285 | /// Note that the ordering of messages in the queues may be slightly off with this function. 286 | pub fn requeue_message(&self, msg: MessageToOne) { 287 | let mut inner = match self.chan.lock() { 288 | Ok(lock) => lock, 289 | Err(_) => return, // If we can't lock the inner channel, there is nothing we can do. 290 | }; 291 | 292 | if let Err(msg) = inner.try_fulfill_receiver(msg) { 293 | inner.unicast_queue.push(ByPriority(msg)); 294 | } 295 | } 296 | 297 | pub fn next_broadcast_message( 298 | &self, 299 | broadcast_mailbox: &BroadcastQueue, 300 | ) -> Option>> { 301 | self.chan.lock().unwrap().pop_broadcast(broadcast_mailbox) 302 | } 303 | } 304 | 305 | struct Inner { 306 | capacity: Option, 307 | waiting_send_to_one: VecDeque>>, 308 | waiting_send_to_all: VecDeque>>, 309 | waiting_receivers_handles: VecDeque>, 310 | unicast_queue: BinaryHeap>>, 311 | broadcast_queues: Vec>>, 312 | broadcast_tail: usize, 313 | } 314 | 315 | impl Inner { 316 | fn new(capacity: Option) -> Self { 317 | Self { 318 | capacity, 319 | waiting_send_to_one: VecDeque::default(), 320 | waiting_send_to_all: VecDeque::default(), 321 | waiting_receivers_handles: VecDeque::default(), 322 | unicast_queue: BinaryHeap::default(), 323 | broadcast_queues: Vec::default(), 324 | broadcast_tail: 0, 325 | } 326 | } 327 | 328 | fn pop_unicast(&mut self) -> Option>> { 329 | let msg = self.unicast_queue.pop()?.0; 330 | 331 | if !self.is_unicast_full() { 332 | if let Some(msg) = self.try_take_waiting_unicast_message() { 333 | self.unicast_queue.push(ByPriority(msg)) 334 | } 335 | } 336 | 337 | Some(msg) 338 | } 339 | 340 | pub fn pop_broadcast( 341 | &mut self, 342 | broadcast_mailbox: &BroadcastQueue, 343 | ) -> Option>> { 344 | let message = broadcast_mailbox.lock().pop()?.0; 345 | 346 | self.broadcast_tail = self.longest_broadcast_queue(); 347 | 348 | if !self.is_broadcast_full() { 349 | if let Some(m) = self.try_take_waiting_broadcast_message() { 350 | self.send_broadcast(m) 351 | } 352 | } 353 | 354 | Some(message) 355 | } 356 | 357 | fn longest_broadcast_queue(&self) -> usize { 358 | let mut longest = 0; 359 | 360 | for queue in &self.broadcast_queues { 361 | if let Some(queue) = queue.upgrade() { 362 | longest = cmp::max(longest, queue.lock().len()); 363 | } 364 | } 365 | 366 | longest 367 | } 368 | 369 | fn send_broadcast(&mut self, m: MessageToAll) { 370 | self.broadcast_queues.retain(|queue| match queue.upgrade() { 371 | Some(q) => { 372 | q.lock().push(ByPriority(m.clone())); 373 | true 374 | } 375 | None => false, // The corresponding receiver has been dropped - remove it 376 | }); 377 | 378 | for rx in mem::take(&mut self.waiting_receivers_handles) { 379 | let _ = rx.notify_new_broadcast(); 380 | } 381 | 382 | self.broadcast_tail += 1; 383 | } 384 | 385 | fn try_fulfill_receiver(&mut self, mut msg: MessageToOne) -> Result<(), MessageToOne> { 386 | while let Some(rx) = self.waiting_receivers_handles.pop_front() { 387 | match rx.notify_new_message(msg) { 388 | Ok(()) => return Ok(()), 389 | Err(unfulfilled_msg) => msg = unfulfilled_msg, 390 | } 391 | } 392 | 393 | Err(msg) 394 | } 395 | 396 | fn try_take_waiting_unicast_message(&mut self) -> Option> { 397 | loop { 398 | if let Some(msg) = 399 | find_remove_highest_priority(&mut self.waiting_send_to_one)?.take_message() 400 | { 401 | return Some(msg); 402 | } 403 | } 404 | } 405 | 406 | fn try_take_waiting_broadcast_message(&mut self) -> Option> { 407 | loop { 408 | if let Some(msg) = 409 | find_remove_highest_priority(&mut self.waiting_send_to_all)?.take_message() 410 | { 411 | return Some(msg); 412 | } 413 | } 414 | } 415 | 416 | fn is_broadcast_full(&self) -> bool { 417 | self.capacity 418 | .map_or(false, |cap| self.broadcast_tail >= cap) 419 | } 420 | 421 | fn is_unicast_full(&self) -> bool { 422 | self.capacity 423 | .map_or(false, |cap| self.unicast_queue.len() >= cap) 424 | } 425 | } 426 | 427 | fn find_remove_highest_priority( 428 | queue: &mut VecDeque>, 429 | ) -> Option> 430 | where 431 | M: HasPriority, 432 | { 433 | queue.retain(|handle| handle.is_active()); // Only process handles which are still active. 434 | 435 | let pos = queue 436 | .iter() 437 | .enumerate() 438 | .max_by_key(|(_, handle)| handle.priority())? 439 | .0; 440 | 441 | queue.remove(pos) 442 | } 443 | 444 | /// An error returned in case the mailbox of an actor is full. 445 | pub struct MailboxFull(pub WaitingSender); 446 | 447 | pub enum ActorMessage { 448 | ToOneActor(MessageToOne), 449 | ToAllActors(MessageToAll), 450 | Shutdown, 451 | } 452 | 453 | impl From> for ActorMessage { 454 | fn from(msg: MessageToOne) -> Self { 455 | ActorMessage::ToOneActor(msg) 456 | } 457 | } 458 | 459 | impl From> for ActorMessage { 460 | fn from(msg: MessageToAll) -> Self { 461 | ActorMessage::ToAllActors(msg) 462 | } 463 | } 464 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Mozilla Public License Version 2.0 2 | ================================== 3 | 4 | 1. Definitions 5 | -------------- 6 | 7 | 1.1. "Contributor" 8 | means each individual or legal entity that creates, contributes to 9 | the creation of, or owns Covered Software. 10 | 11 | 1.2. "Contributor Version" 12 | means the combination of the Contributions of others (if any) used 13 | by a Contributor and that particular Contributor's Contribution. 14 | 15 | 1.3. "Contribution" 16 | means Covered Software of a particular Contributor. 17 | 18 | 1.4. "Covered Software" 19 | means Source Code Form to which the initial Contributor has attached 20 | the notice in Exhibit A, the Executable Form of such Source Code 21 | Form, and Modifications of such Source Code Form, in each case 22 | including portions thereof. 23 | 24 | 1.5. "Incompatible With Secondary Licenses" 25 | means 26 | 27 | (a) that the initial Contributor has attached the notice described 28 | in Exhibit B to the Covered Software; or 29 | 30 | (b) that the Covered Software was made available under the terms of 31 | version 1.1 or earlier of the License, but not also under the 32 | terms of a Secondary License. 33 | 34 | 1.6. "Executable Form" 35 | means any form of the work other than Source Code Form. 36 | 37 | 1.7. "Larger Work" 38 | means a work that combines Covered Software with other material, in 39 | a separate file or files, that is not Covered Software. 40 | 41 | 1.8. "License" 42 | means this document. 43 | 44 | 1.9. "Licensable" 45 | means having the right to grant, to the maximum extent possible, 46 | whether at the time of the initial grant or subsequently, any and 47 | all of the rights conveyed by this License. 48 | 49 | 1.10. "Modifications" 50 | means any of the following: 51 | 52 | (a) any file in Source Code Form that results from an addition to, 53 | deletion from, or modification of the contents of Covered 54 | Software; or 55 | 56 | (b) any new file in Source Code Form that contains any Covered 57 | Software. 58 | 59 | 1.11. "Patent Claims" of a Contributor 60 | means any patent claim(s), including without limitation, method, 61 | process, and apparatus claims, in any patent Licensable by such 62 | Contributor that would be infringed, but for the grant of the 63 | License, by the making, using, selling, offering for sale, having 64 | made, import, or transfer of either its Contributions or its 65 | Contributor Version. 66 | 67 | 1.12. "Secondary License" 68 | means either the GNU General Public License, Version 2.0, the GNU 69 | Lesser General Public License, Version 2.1, the GNU Affero General 70 | Public License, Version 3.0, or any later versions of those 71 | licenses. 72 | 73 | 1.13. "Source Code Form" 74 | means the form of the work preferred for making modifications. 75 | 76 | 1.14. "You" (or "Your") 77 | means an individual or a legal entity exercising rights under this 78 | License. For legal entities, "You" includes any entity that 79 | controls, is controlled by, or is under common control with You. For 80 | purposes of this definition, "control" means (a) the power, direct 81 | or indirect, to cause the direction or management of such entity, 82 | whether by contract or otherwise, or (b) ownership of more than 83 | fifty percent (50%) of the outstanding shares or beneficial 84 | ownership of such entity. 85 | 86 | 2. License Grants and Conditions 87 | -------------------------------- 88 | 89 | 2.1. Grants 90 | 91 | Each Contributor hereby grants You a world-wide, royalty-free, 92 | non-exclusive license: 93 | 94 | (a) under intellectual property rights (other than patent or trademark) 95 | Licensable by such Contributor to use, reproduce, make available, 96 | modify, display, perform, distribute, and otherwise exploit its 97 | Contributions, either on an unmodified basis, with Modifications, or 98 | as part of a Larger Work; and 99 | 100 | (b) under Patent Claims of such Contributor to make, use, sell, offer 101 | for sale, have made, import, and otherwise transfer either its 102 | Contributions or its Contributor Version. 103 | 104 | 2.2. Effective Date 105 | 106 | The licenses granted in Section 2.1 with respect to any Contribution 107 | become effective for each Contribution on the date the Contributor first 108 | distributes such Contribution. 109 | 110 | 2.3. Limitations on Grant Scope 111 | 112 | The licenses granted in this Section 2 are the only rights granted under 113 | this License. No additional rights or licenses will be implied from the 114 | distribution or licensing of Covered Software under this License. 115 | Notwithstanding Section 2.1(b) above, no patent license is granted by a 116 | Contributor: 117 | 118 | (a) for any code that a Contributor has removed from Covered Software; 119 | or 120 | 121 | (b) for infringements caused by: (i) Your and any other third party's 122 | modifications of Covered Software, or (ii) the combination of its 123 | Contributions with other software (except as part of its Contributor 124 | Version); or 125 | 126 | (c) under Patent Claims infringed by Covered Software in the absence of 127 | its Contributions. 128 | 129 | This License does not grant any rights in the trademarks, service marks, 130 | or logos of any Contributor (except as may be necessary to comply with 131 | the notice requirements in Section 3.4). 132 | 133 | 2.4. Subsequent Licenses 134 | 135 | No Contributor makes additional grants as a result of Your choice to 136 | distribute the Covered Software under a subsequent version of this 137 | License (see Section 10.2) or under the terms of a Secondary License (if 138 | permitted under the terms of Section 3.3). 139 | 140 | 2.5. Representation 141 | 142 | Each Contributor represents that the Contributor believes its 143 | Contributions are its original creation(s) or it has sufficient rights 144 | to grant the rights to its Contributions conveyed by this License. 145 | 146 | 2.6. Fair Use 147 | 148 | This License is not intended to limit any rights You have under 149 | applicable copyright doctrines of fair use, fair dealing, or other 150 | equivalents. 151 | 152 | 2.7. Conditions 153 | 154 | Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted 155 | in Section 2.1. 156 | 157 | 3. Responsibilities 158 | ------------------- 159 | 160 | 3.1. Distribution of Source Form 161 | 162 | All distribution of Covered Software in Source Code Form, including any 163 | Modifications that You create or to which You contribute, must be under 164 | the terms of this License. You must inform recipients that the Source 165 | Code Form of the Covered Software is governed by the terms of this 166 | License, and how they can obtain a copy of this License. You may not 167 | attempt to alter or restrict the recipients' rights in the Source Code 168 | Form. 169 | 170 | 3.2. Distribution of Executable Form 171 | 172 | If You distribute Covered Software in Executable Form then: 173 | 174 | (a) such Covered Software must also be made available in Source Code 175 | Form, as described in Section 3.1, and You must inform recipients of 176 | the Executable Form how they can obtain a copy of such Source Code 177 | Form by reasonable means in a timely manner, at a charge no more 178 | than the cost of distribution to the recipient; and 179 | 180 | (b) You may distribute such Executable Form under the terms of this 181 | License, or sublicense it under different terms, provided that the 182 | license for the Executable Form does not attempt to limit or alter 183 | the recipients' rights in the Source Code Form under this License. 184 | 185 | 3.3. Distribution of a Larger Work 186 | 187 | You may create and distribute a Larger Work under terms of Your choice, 188 | provided that You also comply with the requirements of this License for 189 | the Covered Software. If the Larger Work is a combination of Covered 190 | Software with a work governed by one or more Secondary Licenses, and the 191 | Covered Software is not Incompatible With Secondary Licenses, this 192 | License permits You to additionally distribute such Covered Software 193 | under the terms of such Secondary License(s), so that the recipient of 194 | the Larger Work may, at their option, further distribute the Covered 195 | Software under the terms of either this License or such Secondary 196 | License(s). 197 | 198 | 3.4. Notices 199 | 200 | You may not remove or alter the substance of any license notices 201 | (including copyright notices, patent notices, disclaimers of warranty, 202 | or limitations of liability) contained within the Source Code Form of 203 | the Covered Software, except that You may alter any license notices to 204 | the extent required to remedy known factual inaccuracies. 205 | 206 | 3.5. Application of Additional Terms 207 | 208 | You may choose to offer, and to charge a fee for, warranty, support, 209 | indemnity or liability obligations to one or more recipients of Covered 210 | Software. However, You may do so only on Your own behalf, and not on 211 | behalf of any Contributor. You must make it absolutely clear that any 212 | such warranty, support, indemnity, or liability obligation is offered by 213 | You alone, and You hereby agree to indemnify every Contributor for any 214 | liability incurred by such Contributor as a result of warranty, support, 215 | indemnity or liability terms You offer. You may include additional 216 | disclaimers of warranty and limitations of liability specific to any 217 | jurisdiction. 218 | 219 | 4. Inability to Comply Due to Statute or Regulation 220 | --------------------------------------------------- 221 | 222 | If it is impossible for You to comply with any of the terms of this 223 | License with respect to some or all of the Covered Software due to 224 | statute, judicial order, or regulation then You must: (a) comply with 225 | the terms of this License to the maximum extent possible; and (b) 226 | describe the limitations and the code they affect. Such description must 227 | be placed in a text file included with all distributions of the Covered 228 | Software under this License. Except to the extent prohibited by statute 229 | or regulation, such description must be sufficiently detailed for a 230 | recipient of ordinary skill to be able to understand it. 231 | 232 | 5. Termination 233 | -------------- 234 | 235 | 5.1. The rights granted under this License will terminate automatically 236 | if You fail to comply with any of its terms. However, if You become 237 | compliant, then the rights granted under this License from a particular 238 | Contributor are reinstated (a) provisionally, unless and until such 239 | Contributor explicitly and finally terminates Your grants, and (b) on an 240 | ongoing basis, if such Contributor fails to notify You of the 241 | non-compliance by some reasonable means prior to 60 days after You have 242 | come back into compliance. Moreover, Your grants from a particular 243 | Contributor are reinstated on an ongoing basis if such Contributor 244 | notifies You of the non-compliance by some reasonable means, this is the 245 | first time You have received notice of non-compliance with this License 246 | from such Contributor, and You become compliant prior to 30 days after 247 | Your receipt of the notice. 248 | 249 | 5.2. If You initiate litigation against any entity by asserting a patent 250 | infringement claim (excluding declaratory judgment actions, 251 | counter-claims, and cross-claims) alleging that a Contributor Version 252 | directly or indirectly infringes any patent, then the rights granted to 253 | You by any and all Contributors for the Covered Software under Section 254 | 2.1 of this License shall terminate. 255 | 256 | 5.3. In the event of termination under Sections 5.1 or 5.2 above, all 257 | end user license agreements (excluding distributors and resellers) which 258 | have been validly granted by You or Your distributors under this License 259 | prior to termination shall survive termination. 260 | 261 | ************************************************************************ 262 | * * 263 | * 6. Disclaimer of Warranty * 264 | * ------------------------- * 265 | * * 266 | * Covered Software is provided under this License on an "as is" * 267 | * basis, without warranty of any kind, either expressed, implied, or * 268 | * statutory, including, without limitation, warranties that the * 269 | * Covered Software is free of defects, merchantable, fit for a * 270 | * particular purpose or non-infringing. The entire risk as to the * 271 | * quality and performance of the Covered Software is with You. * 272 | * Should any Covered Software prove defective in any respect, You * 273 | * (not any Contributor) assume the cost of any necessary servicing, * 274 | * repair, or correction. This disclaimer of warranty constitutes an * 275 | * essential part of this License. No use of any Covered Software is * 276 | * authorized under this License except under this disclaimer. * 277 | * * 278 | ************************************************************************ 279 | 280 | ************************************************************************ 281 | * * 282 | * 7. Limitation of Liability * 283 | * -------------------------- * 284 | * * 285 | * Under no circumstances and under no legal theory, whether tort * 286 | * (including negligence), contract, or otherwise, shall any * 287 | * Contributor, or anyone who distributes Covered Software as * 288 | * permitted above, be liable to You for any direct, indirect, * 289 | * special, incidental, or consequential damages of any character * 290 | * including, without limitation, damages for lost profits, loss of * 291 | * goodwill, work stoppage, computer failure or malfunction, or any * 292 | * and all other commercial damages or losses, even if such party * 293 | * shall have been informed of the possibility of such damages. This * 294 | * limitation of liability shall not apply to liability for death or * 295 | * personal injury resulting from such party's negligence to the * 296 | * extent applicable law prohibits such limitation. Some * 297 | * jurisdictions do not allow the exclusion or limitation of * 298 | * incidental or consequential damages, so this exclusion and * 299 | * limitation may not apply to You. * 300 | * * 301 | ************************************************************************ 302 | 303 | 8. Litigation 304 | ------------- 305 | 306 | Any litigation relating to this License may be brought only in the 307 | courts of a jurisdiction where the defendant maintains its principal 308 | place of business and such litigation shall be governed by laws of that 309 | jurisdiction, without reference to its conflict-of-law provisions. 310 | Nothing in this Section shall prevent a party's ability to bring 311 | cross-claims or counter-claims. 312 | 313 | 9. Miscellaneous 314 | ---------------- 315 | 316 | This License represents the complete agreement concerning the subject 317 | matter hereof. If any provision of this License is held to be 318 | unenforceable, such provision shall be reformed only to the extent 319 | necessary to make it enforceable. Any law or regulation which provides 320 | that the language of a contract shall be construed against the drafter 321 | shall not be used to construe this License against a Contributor. 322 | 323 | 10. Versions of the License 324 | --------------------------- 325 | 326 | 10.1. New Versions 327 | 328 | Mozilla Foundation is the license steward. Except as provided in Section 329 | 10.3, no one other than the license steward has the right to modify or 330 | publish new versions of this License. Each version will be given a 331 | distinguishing version number. 332 | 333 | 10.2. Effect of New Versions 334 | 335 | You may distribute the Covered Software under the terms of the version 336 | of the License under which You originally received the Covered Software, 337 | or under the terms of any subsequent version published by the license 338 | steward. 339 | 340 | 10.3. Modified Versions 341 | 342 | If you create software not governed by this License, and you want to 343 | create a new license for such software, you may create and use a 344 | modified version of this License if you rename the license and remove 345 | any references to the name of the license steward (except to note that 346 | such modified license differs from this License). 347 | 348 | 10.4. Distributing Source Code Form that is Incompatible With Secondary 349 | Licenses 350 | 351 | If You choose to distribute Source Code Form that is Incompatible With 352 | Secondary Licenses under the terms of this version of the License, the 353 | notice described in Exhibit B of this License must be attached. 354 | 355 | Exhibit A - Source Code Form License Notice 356 | ------------------------------------------- 357 | 358 | This Source Code Form is subject to the terms of the Mozilla Public 359 | License, v. 2.0. If a copy of the MPL was not distributed with this 360 | file, You can obtain one at http://mozilla.org/MPL/2.0/. 361 | 362 | If it is not possible or desirable to put the notice in a particular 363 | file, then You may include the notice in a location (such as a LICENSE 364 | file in a relevant directory) where a recipient would be likely to look 365 | for such a notice. 366 | 367 | You may add additional accurate notices of copyright ownership. 368 | 369 | Exhibit B - "Incompatible With Secondary Licenses" Notice 370 | --------------------------------------------------------- 371 | 372 | This Source Code Form is "Incompatible With Secondary Licenses", as 373 | defined by the Mozilla Public License, v. 2.0. 374 | --------------------------------------------------------------------------------