1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
// Copyright 2022 Jeff Kim <hiking90@gmail.com>
// SPDX-License-Identifier: Apache-2.0
//! # rsActor
//! A Simple and Efficient In-Process Actor Model Implementation for Rust
//!
//! `rsActor` is a lightweight, Tokio-based actor framework in Rust focused on providing a simple
//! and efficient actor model for local, in-process systems. It emphasizes clean message-passing
//! semantics and straightforward actor lifecycle management while maintaining high performance for
//! Rust applications.
//!
//! ## Features
//!
//! - **Asynchronous Actors**: Actors run in their own asynchronous tasks.
//! - **Message Passing**: Actors communicate by sending and receiving messages.
//! - [`tell`](actor_ref::ActorRef::tell): Send a message without waiting for a reply (fire-and-forget).
//! - [`tell_with_timeout`](actor_ref::ActorRef::tell_with_timeout): Send a message without waiting for a reply, with a specified timeout.
//! - [`ask`](actor_ref::ActorRef::ask): Send a message and await a reply.
//! - [`ask_with_timeout`](actor_ref::ActorRef::ask_with_timeout): Send a message and await a reply, with a specified timeout.
//! - [`tell_blocking`](actor_ref::ActorRef::tell_blocking): Blocking version of `tell` for use in [`tokio::task::spawn_blocking`] tasks.
//! - [`ask_blocking`](actor_ref::ActorRef::ask_blocking): Blocking version of `ask` for use in [`tokio::task::spawn_blocking`] tasks.
//! - **Priority Channel** (opt-in via [`SpawnOptions::with_priority`]):
//! A dedicated mpsc channel of fixed capacity 1 that the runtime polls with
//! higher priority than the regular mailbox but lower priority than the
//! `kill()` (terminate signal). Use it for short, infrequent control messages
//! such as health checks and pause/resume. Send via
//! [`tell_priority`](actor_ref::ActorRef::tell_priority) /
//! [`ask_priority`](actor_ref::ActorRef::ask_priority). The priority channel
//! is **off by default**; calls on a non-priority actor return
//! [`Error::PriorityChannelNotEnabled`].
//! - **Straightforward Actor Lifecycle**: Actors have [`on_start`](Actor::on_start), [`on_idle`](Actor::on_idle),
//! and [`on_stop`](Actor::on_stop) lifecycle hooks. Idle work is driven by streams subscribed via
//! [`ActorRef::subscribe_idle`](actor_ref::ActorRef::subscribe_idle) — each yielded event is dispatched to
//! `on_idle` with `&mut self`, so timer / channel state never gets cancelled by a competing `select!` arm.
//! - **Graceful Shutdown & Kill**: Actors can be stopped gracefully or killed immediately.
//! - **Typed Messages**: Messages are strongly typed, and replies are also typed.
//! - **Macro for Message Handling**:
//! - [`message_handlers`] attribute macro with `#[handler]` method attributes for automatic message handling (recommended)
//! - **Type Safety Features**: [`ActorRef<T>`] provides compile-time type safety with zero runtime overhead
//! - **Optional Tracing Support**: Built-in observability using the [`tracing`](https://crates.io/crates/tracing) crate (enable with `tracing` feature):
//! - Actor lifecycle event tracing (start, stop, different termination scenarios)
//! - Message handling with timing and performance metrics
//! - Reply processing and error handling tracing
//! - Structured, non-redundant logs for easier debugging and monitoring
//! - **Dead Letter Tracking**: Automatic logging of undelivered messages via [`DeadLetterReason`]:
//! - All failed message deliveries are logged with actor and message type information
//! - Helps identify stopped actors, timeouts, and dropped replies
//! - Zero overhead on successful message delivery (hot path optimization)
//! - **Enhanced Error Debugging**: Rich error information via [`Error::debugging_tips()`](Error::debugging_tips) and [`Error::is_retryable()`](Error::is_retryable):
//! - Actionable debugging tips for each error type
//! - Retry classification for timeout errors
//!
//! ## Core Concepts
//!
//! - **[`Actor`]**: Trait defining actor behavior and lifecycle hooks ([`on_start`](Actor::on_start) required, [`on_idle`](Actor::on_idle) optional).
//! - **[`Message<M>`](actor::Message)**: Trait for handling a message type `M` and defining its reply type.
//! - **[`ActorRef`]**: Handle for sending messages to an actor.
//! - **[`spawn`]**: Function to create and start an actor, returning an [`ActorRef`] and a `JoinHandle`.
//! - **[`ActorResult`]**: Enum representing the outcome of an actor's lifecycle (e.g., completed, failed).
//!
//! ## Getting Started
//!
//! ### Message Handling with `#[message_handlers]`
//!
//! rsActor uses the `#[message_handlers]` attribute macro combined with `#[handler]` method attributes
//! for message handling. This is **required** for all actors and offers several advantages:
//!
//! - **Selective Processing**: Only methods marked with `#[handler]` are treated as message handlers.
//! - **Clean Separation**: Regular methods can coexist with message handlers within the same `impl` block.
//! - **Automatic Generation**: The macro automatically generates the necessary `Message` trait implementations and handler registrations.
//! - **Type Safety**: Message handler signatures are verified at compile time.
//! - **Reduced Boilerplate**: Eliminates the need to manually implement `Message` traits.
//!
//! ### Option A: Simple Actor with `#[derive(Actor)]`
//!
//! For simple actors that don't need complex initialization logic, use the `#[derive(Actor)]` macro:
//!
//! ```rust
//! use rsactor::{Actor, ActorRef, message_handlers, spawn};
//!
//! // 1. Define your actor struct and derive Actor
//! #[derive(Actor)]
//! struct MyActor {
//! name: String,
//! count: u32,
//! }
//!
//! // 2. Define message types
//! struct GetName;
//! struct Increment;
//!
//! // 3. Use message_handlers macro with handler attributes
//! #[message_handlers]
//! impl MyActor {
//! #[handler]
//! async fn handle_get_name(&mut self, _msg: GetName, _: &ActorRef<Self>) -> String {
//! self.name.clone()
//! }
//!
//! #[handler]
//! async fn handle_increment(&mut self, _msg: Increment, _: &ActorRef<Self>) -> () {
//! self.count += 1;
//! }
//!
//! // Regular methods can coexist without the #[handler] attribute
//! fn get_count(&self) -> u32 {
//! self.count
//! }
//! }
//!
//! // 4. Usage
//! # #[tokio::main]
//! # async fn main() -> Result<(), Box<dyn std::error::Error>> {
//! let actor_instance = MyActor { name: "Test".to_string(), count: 0 };
//! let (actor_ref, _join_handle) = spawn::<MyActor>(actor_instance);
//!
//! let name = actor_ref.ask(GetName).await?;
//! actor_ref.tell(Increment).await?;
//! # Ok(())
//! # }
//! ```
//!
//! ### Option B: Custom Actor Implementation with Manual Initialization
//!
//! For actors that need custom initialization logic, implement the `Actor` trait manually:
//!
//! ```rust
//! use rsactor::{Actor, ActorRef, message_handlers, spawn};
//! use anyhow::Result;
//!
//! // 1. Define your actor struct
//! #[derive(Debug)] // Added Debug for printing the actor in ActorResult
//! struct MyActor {
//! data: String,
//! count: u32,
//! }
//!
//! // 2. Implement the Actor trait manually
//! impl Actor for MyActor {
//! type Args = String;
//! type Error = anyhow::Error;
//! type IdleEvent = ();
//!
//! // on_start is required and must be implemented.
//! // on_idle and on_stop are optional and have default implementations.
//! async fn on_start(initial_data: Self::Args, actor_ref: &ActorRef<Self>) -> std::result::Result<Self, Self::Error> {
//! println!("MyActor (id: {}) started with data: '{}'", actor_ref.identity(), initial_data);
//! Ok(MyActor {
//! data: initial_data,
//! count: 0,
//! })
//! }
//! }
//!
//! // 3. Define message types
//! struct GetData;
//! struct IncrementMsg(u32);
//!
//! // 4. Use message_handlers macro for message handling
//! #[message_handlers]
//! impl MyActor {
//! #[handler]
//! async fn handle_get_data(&mut self, _msg: GetData, _actor_ref: &ActorRef<Self>) -> String {
//! self.data.clone()
//! }
//!
//! #[handler]
//! async fn handle_increment(&mut self, msg: IncrementMsg, _actor_ref: &ActorRef<Self>) -> u32 {
//! self.count += msg.0;
//! self.count
//! }
//! }
//!
//! // 5. Usage
//! # #[tokio::main]
//! # async fn main() -> Result<(), Box<dyn std::error::Error>> {
//! let (actor_ref, join_handle) = spawn::<MyActor>("initial data".to_string());
//!
//! let current_data: String = actor_ref.ask(GetData).await?;
//! let new_count: u32 = actor_ref.ask(IncrementMsg(5)).await?;
//!
//! actor_ref.stop().await;
//! let actor_result = join_handle.await?;
//! # Ok(())
//! # }
//! ```
//!
//! Both approaches also work with enums, making it easy to create state machine actors:
//!
//! ```rust
//! use rsactor::{Actor, ActorRef, message_handlers, spawn};
//!
//! // Using message_handlers macro approach
//! #[derive(Actor, Clone)]
//! enum StateActor {
//! Idle,
//! Processing(String),
//! Completed(i32),
//! }
//!
//! struct GetState;
//! struct StartProcessing(String);
//! struct Complete(i32);
//!
//! #[message_handlers]
//! impl StateActor {
//! #[handler]
//! async fn handle_get_state(&mut self, _msg: GetState, _: &ActorRef<Self>) -> StateActor {
//! self.clone()
//! }
//!
//! #[handler]
//! async fn handle_start_processing(&mut self, msg: StartProcessing, _: &ActorRef<Self>) -> () {
//! *self = StateActor::Processing(msg.0);
//! }
//!
//! #[handler]
//! async fn handle_complete(&mut self, msg: Complete, _: &ActorRef<Self>) -> () {
//! *self = StateActor::Completed(msg.0);
//! }
//! }
//! ```
//!
//! ## Tracing Support
//!
//! rsActor provides optional tracing support for comprehensive observability. Enable it with the `tracing` feature:
//!
//! ```toml
//! [dependencies]
//! rsactor = { version = "0.16", features = ["tracing"] }
//! tracing = "0.1"
//! tracing-subscriber = "0.3"
//! ```
//!
//! When enabled, rsActor emits structured trace events for:
//! - Actor lifecycle events (start, stop, termination scenarios)
//! - Message sending and handling with timing information
//! - Reply processing and error handling
//! - Performance metrics (message processing duration)
//!
//! All examples support tracing. Here's the integration pattern:
//!
//! ```rust,no_run
//! #[tokio::main]
//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
//! // Initialize tracing subscriber to see logs
//! // The `tracing` crate is always available for logging
//! tracing_subscriber::fmt()
//! .with_max_level(tracing::Level::DEBUG)
//! .with_target(false)
//! .init();
//!
//! // Your existing actor code here...
//! // Logs are automatically emitted via tracing::warn!, tracing::error!, etc.
//! Ok(())
//! }
//! ```
//!
//! Run any example with debug logging:
//! ```bash
//! RUST_LOG=debug cargo run --example basic
//! ```
//!
//! Enable instrumentation spans with the `tracing` feature:
//! ```bash
//! RUST_LOG=debug cargo run --example basic --features tracing
//! ```
//!
//! This crate-level documentation provides an overview of [`rsActor`](crate).
//! For more details on specific components, please refer to their individual
//! documentation.
pub use ;
pub use DeadLetterReason;
// Re-export test utilities when test-utils feature is enabled
pub use ;
pub use MetricsSnapshot;
pub use ;
pub use ;
pub use ;
pub use ;
pub use ;
use FutureExt;
// Re-export derive macros for convenient access
pub use ;
/// Internal function used by derive macros to log handler errors.
///
/// Surfaces a user handler's `Result::Err` value through `tracing::error!`. The
/// `tracing` crate is always a dependency — the `tracing` *feature* only gates
/// `#[tracing::instrument]` spans, not logging — so this routes through the user's
/// configured subscriber unconditionally, exactly like dead-letter logging. Keying
/// the channel on the `tracing` feature instead would be wrong: the feature is
/// unrelated to whether a subscriber exists, so it could send handler errors to
/// `eprintln!` even when the user has a subscriber wired up, or silently drop them
/// when they don't.
///
/// A handler returning `Err` is a genuine actor-side fault (unlike a dropped reply,
/// which is the caller's decision), so `error!` is the appropriate level.
use ;
use HashMap;
use Mutex;
use ;
// --- Deadlock Detection ---
task_local!
/// Global wait-for graph.
/// Key: waiting actor's ID, Value: target actor's Identity.
static WAIT_FOR: = new;
pub
pub u64);
/// Check if there is a path from `from` to `to` in the wait-for graph.
/// Self-ask (caller == callee) is checked by the caller before invoking this function,
/// so this only handles cycles of 2+ hops.
pub
/// Format the cycle path for panic messages.
pub
/// Type-erased payload handler trait for dynamic message dispatch.
///
/// This trait allows different message types to be handled uniformly within the actor system,
/// enabling storage of various message types in the same mailbox while preserving type safety
/// through the `Message` trait implementation.
/// A boxed future that is Send and can be stored in collections.
///
/// This type alias is used throughout the handler traits for object-safe async methods.
/// Identical to `futures::future::BoxFuture` but defined locally to avoid exposing
/// the `futures` crate in the public API surface.
pub type BoxFuture<'a, T> = Pin;
/// Represents messages that can be sent to an actor's mailbox.
///
/// This enum includes both user-defined messages (wrapped in `Envelope`)
/// and control messages like `StopGracefully`. The `Terminate` control signal
/// is handled through a separate dedicated channel.
pub
/// Control signals sent through a dedicated high-priority channel.
///
/// These signals are processed with higher priority than regular mailbox messages
/// to ensure timely actor termination even when the mailbox is full.
pub
/// Type alias for the sender side of an actor's mailbox channel.
///
/// This is used by `ActorRef` to send messages to the actor's mailbox.
pub type MailboxSender<T> = Sender;
/// Global configuration for the default mailbox capacity.
///
/// This value can be set once using `set_default_mailbox_capacity()` and will be used
/// by the `spawn()` function when no specific capacity is provided.
static CONFIGURED_DEFAULT_MAILBOX_CAPACITY: = new;
/// The default mailbox capacity for actors.
pub const DEFAULT_MAILBOX_CAPACITY: usize = 32;
/// The fixed capacity of the priority channel when it is enabled.
///
/// The priority channel is intentionally limited to a single in-flight slot. The slot is
/// released as soon as the actor's runtime loop calls `recv()`, so admission resumes
/// immediately after the actor reaches the next select! iteration. See
/// [`SpawnOptions::with_priority`] for the rationale.
pub const PRIORITY_CHANNEL_CAPACITY: usize = 1;
/// Capacity of the idle-subscribe channel used by
/// [`ActorRef::subscribe_idle`](crate::ActorRef::subscribe_idle).
///
/// Subscriptions are rare events (typically a handful per actor, established
/// during `on_start` or in response to occasional control messages), and the
/// runtime drains the channel on every loop iteration. The buffer absorbs
/// bursts that occur **before the runtime enters its select! loop** —
/// specifically, every subscription made inside `on_start` is queued here
/// because the receiver is not polled until `on_start` returns. A capacity of
/// 32 leaves comfortable headroom for fan-out patterns (e.g. one subscription
/// per item in a small config list) without resorting to an unbounded channel.
///
/// `subscribe_idle` uses `try_send` and returns [`Error::ChannelFull`] when the
/// buffer is full, so the failure mode is a loud, actionable error rather
/// than a silent hang — callers can batch or raise this constant if it is
/// ever hit in practice.
pub const IDLE_SUBSCRIBE_CHANNEL_CAPACITY: usize = 32;
/// Sets the global default buffer size for actor mailboxes.
///
/// This function can only be called successfully once. Subsequent calls
/// will return an error. This configured value is used by the `spawn` function
/// if no specific capacity is provided to `spawn_with_mailbox_capacity`.
/// Configuration options for spawning an actor.
///
/// `SpawnOptions` is a builder used by [`spawn_with_options`] to control aspects of the
/// actor's runtime that are not part of the actor's own definition: mailbox capacity and
/// optional activation of the priority channel.
///
/// # Examples
///
/// ```rust,no_run
/// use rsactor::{spawn_with_options, SpawnOptions, Actor, ActorRef, message_handlers};
///
/// #[derive(Actor)]
/// struct MyActor;
///
/// struct Ping;
///
/// #[message_handlers]
/// impl MyActor {
/// #[handler]
/// async fn handle_ping(&mut self, _: Ping, _: &ActorRef<Self>) -> () {}
/// }
///
/// # fn main() {
/// let opts = SpawnOptions::new().mailbox_capacity(64).with_priority();
/// let (actor_ref, _join) = spawn_with_options::<MyActor>(MyActor, opts);
/// assert!(actor_ref.has_priority_channel());
/// # }
/// ```
/// Spawns a new actor and returns an `ActorRef<T>` to it, along with a `JoinHandle`.
///
/// Takes initialization arguments that will be passed to the actor's [`on_start`](crate::Actor::on_start) method.
/// The `JoinHandle` can be used to await the actor's termination and retrieve
/// the actor result as an [`ActorResult<T>`](crate::ActorResult).
/// Spawns a new actor with a specified mailbox capacity and returns an `ActorRef<T>` to it, along with a `JoinHandle`.
///
/// Takes initialization arguments that will be passed to the actor's [`on_start`](crate::Actor::on_start) method.
/// The `JoinHandle` can be used to await the actor's termination and retrieve
/// the actor result as an [`ActorResult<T>`](crate::ActorResult). Use this version when you need
/// to control the actor's mailbox capacity.
/// Spawns a new actor with the given [`SpawnOptions`] and returns an `ActorRef<T>` along
/// with a `JoinHandle`.
///
/// This is the most general spawn entry point. Use it when you need to enable the
/// priority channel via [`SpawnOptions::with_priority`] or configure both mailbox
/// capacity and priority in a single call.