murmer 0.4.1

A distributed actor framework for Rust
Documentation
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
//! Router — distribute messages across a pool of actor endpoints.
//!
//! A [`Router<A>`] holds multiple [`Endpoint<A>`] handles and distributes
//! messages according to a [`RoutingStrategy`]:
//!
//! - **RoundRobin** — cycles through endpoints sequentially (default)
//! - **Random** — picks a random endpoint per message
//! - **Broadcast** — via [`Router::broadcast`], sends to all endpoints
//!
//! # Example
//!
//! ```rust,ignore
//! let router = Router::new(
//!     vec![ep1, ep2, ep3],
//!     RoutingStrategy::RoundRobin,
//! );
//!
//! // Each send goes to the next endpoint in sequence
//! router.send(Increment { amount: 1 }).await?;
//!
//! // Or send to all at once
//! let results = router.broadcast(GetCount).await;
//! ```

use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, RwLock};

use futures_util::stream::{FuturesUnordered, StreamExt};
use serde::Serialize;
use serde::de::DeserializeOwned;

use crate::actor::{Actor, AsyncHandler, Handler, RemoteMessage};
use crate::endpoint::Endpoint;
use crate::listing::{ListingEvent, ReceptionKey, WatchedListing};
use crate::receptionist::Receptionist;
use crate::runtime::{Runtime, TokioRuntime};
use crate::wire::SendError;

/// Strategy for how a Router distributes messages across its endpoints.
#[derive(Debug, Clone, Default)]
pub enum RoutingStrategy {
    #[default]
    RoundRobin,
    Random,
    Broadcast,
}

/// A router distributes messages across a group of endpoints for the same actor type.
///
/// Useful for load balancing, fan-out, and work distribution patterns.
pub struct Router<A: Actor> {
    endpoints: Vec<Endpoint<A>>,
    strategy: RoutingStrategy,
    counter: AtomicUsize,
    /// Runtime seam for Random selection, timers, and spawns — so a router can
    /// run deterministically under the sim runtime.
    runtime: Arc<dyn Runtime>,
}

impl<A: Actor + 'static> Router<A> {
    /// Create a router on the default (Tokio) runtime. For a deterministic sim,
    /// use [`with_runtime`](Self::with_runtime) and pass the sim runtime.
    pub fn new(endpoints: Vec<Endpoint<A>>, strategy: RoutingStrategy) -> Self {
        Self::with_runtime(endpoints, strategy, Arc::new(TokioRuntime))
    }

    /// Create a router on a specific runtime (e.g. a `SimWorld`'s runtime), so
    /// Random selection, `scatter_gather` timeouts, and `fan_out` spawns are
    /// deterministic.
    pub fn with_runtime(
        endpoints: Vec<Endpoint<A>>,
        strategy: RoutingStrategy,
        runtime: Arc<dyn Runtime>,
    ) -> Self {
        Self {
            endpoints,
            strategy,
            counter: AtomicUsize::new(0),
            runtime,
        }
    }

    /// Pick the endpoint index for the current strategy. Callers must guard
    /// `len > 0` first (the empty case is a `MailboxClosed` error). Broadcast via
    /// the single-send paths targets index 0; the real fan-out is `broadcast()`.
    fn pick_index(&self, len: usize) -> usize {
        match self.strategy {
            RoutingStrategy::RoundRobin => self.counter.fetch_add(1, Ordering::Relaxed) % len,
            RoutingStrategy::Random => (self.runtime.rng_u64() % len as u64) as usize,
            RoutingStrategy::Broadcast => 0,
        }
    }

    /// Send a message to one endpoint based on the routing strategy.
    pub async fn send<M>(&self, msg: M) -> Result<M::Result, SendError>
    where
        A: Handler<M>,
        M: RemoteMessage + Clone,
        M::Result: Serialize + DeserializeOwned,
    {
        if self.endpoints.is_empty() {
            return Err(SendError::MailboxClosed);
        }

        let idx = self.pick_index(self.endpoints.len());
        self.endpoints[idx].send(msg).await
    }

    /// Like [`send`](Self::send) but routes to an [`AsyncHandler<M>`] — the
    /// `.await`-capable handler the `#[handlers]` macro emits for an `async fn`.
    ///
    /// `send` is bound `A: Handler<M>` (the sync handler), and the macro emits
    /// exactly one of `Handler`/`AsyncHandler` per message, so an actor whose
    /// handler is `async` can only be routed through this method.
    pub async fn send_async<M>(&self, msg: M) -> Result<M::Result, SendError>
    where
        A: AsyncHandler<M>,
        M: RemoteMessage,
        M::Result: Serialize + DeserializeOwned,
    {
        if self.endpoints.is_empty() {
            return Err(SendError::MailboxClosed);
        }

        let idx = self.pick_index(self.endpoints.len());
        self.endpoints[idx].send_async(msg).await
    }

    /// Send a message to ALL endpoints. Returns a Vec of results.
    pub async fn broadcast<M>(&self, msg: M) -> Vec<Result<M::Result, SendError>>
    where
        A: Handler<M>,
        M: RemoteMessage + Clone,
        M::Result: Serialize + DeserializeOwned,
    {
        let mut results = Vec::with_capacity(self.endpoints.len());
        for ep in &self.endpoints {
            results.push(ep.send(msg.clone()).await);
        }
        results
    }

    /// Send a message to ALL endpoints concurrently and return when `k` respond
    /// successfully (or all have completed).
    ///
    /// This enables quorum patterns like "write to 3 replicas, succeed when 2
    /// acknowledge." Results are returned in completion order, not endpoint order.
    ///
    /// # Panics
    ///
    /// Does not panic if `k` exceeds the number of endpoints — returns all
    /// available results instead.
    pub async fn send_quorum<M>(&self, msg: M, k: usize) -> Vec<Result<M::Result, SendError>>
    where
        A: Handler<M>,
        M: RemoteMessage + Clone,
        M::Result: Serialize + DeserializeOwned,
    {
        if self.endpoints.is_empty() {
            return vec![Err(SendError::MailboxClosed)];
        }

        // FuturesUnordered (not JoinSet): polls all sends concurrently within
        // this task without spawning, so it runs under any executor including
        // the deterministic sim runtime.
        let mut inflight = FuturesUnordered::new();
        for ep in &self.endpoints {
            let ep = ep.clone();
            let msg = msg.clone();
            inflight.push(async move { ep.send(msg).await });
        }

        let target = k.min(self.endpoints.len());
        let mut results = Vec::with_capacity(target);
        let mut successes = 0;

        while let Some(result) = inflight.next().await {
            if result.is_ok() {
                successes += 1;
            }
            results.push(result);

            if successes >= target {
                // Quorum reached — drop the rest (cancels remaining sends).
                break;
            }
        }

        results
    }

    /// Send a message to ALL endpoints concurrently and collect all results
    /// within a timeout. Returns partial results if the timeout expires.
    ///
    /// Unlike `broadcast()` which sends sequentially, this fires all sends
    /// concurrently and returns results in completion order.
    pub async fn scatter_gather<M>(
        &self,
        msg: M,
        timeout: std::time::Duration,
    ) -> Vec<Result<M::Result, SendError>>
    where
        A: Handler<M>,
        M: RemoteMessage + Clone,
        M::Result: Serialize + DeserializeOwned,
    {
        if self.endpoints.is_empty() {
            return vec![Err(SendError::MailboxClosed)];
        }

        let mut inflight = FuturesUnordered::new();
        for ep in &self.endpoints {
            let ep = ep.clone();
            let msg = msg.clone();
            inflight.push(async move { ep.send(msg).await });
        }

        let mut results = Vec::with_capacity(self.endpoints.len());
        // Timer on the runtime seam (virtual time under sim). Created once so the
        // deadline is stable across loop iterations.
        let mut timeout_fut = self.runtime.sleep(timeout);

        loop {
            tokio::select! {
                biased;
                Some(result) = inflight.next() => {
                    results.push(result);
                    if results.len() == self.endpoints.len() {
                        break;
                    }
                }
                _ = &mut timeout_fut => {
                    break; // dropping `inflight` cancels remaining sends
                }
            }
        }

        results
    }

    /// Send a message to ALL endpoints concurrently and return the first
    /// successful response. Remaining in-flight sends are cancelled.
    ///
    /// Returns `Err` only if ALL endpoints fail.
    pub async fn first_response<M>(&self, msg: M) -> Result<M::Result, SendError>
    where
        A: Handler<M>,
        M: RemoteMessage + Clone,
        M::Result: Serialize + DeserializeOwned,
    {
        if self.endpoints.is_empty() {
            return Err(SendError::MailboxClosed);
        }

        let mut inflight = FuturesUnordered::new();
        for ep in &self.endpoints {
            let ep = ep.clone();
            let msg = msg.clone();
            inflight.push(async move { ep.send(msg).await });
        }

        let mut last_error = SendError::MailboxClosed;
        while let Some(result) = inflight.next().await {
            match result {
                Ok(result) => {
                    // First success — drop the rest (cancels remaining sends).
                    return Ok(result);
                }
                Err(e) => last_error = e,
            }
        }

        Err(last_error)
    }

    /// Send a message to ALL endpoints concurrently without waiting for responses.
    ///
    /// Fire-and-forget pattern. The sends are spawned as background tasks.
    /// Errors are silently dropped.
    pub fn fan_out<M>(&self, msg: M)
    where
        A: Handler<M>,
        M: RemoteMessage + Clone + 'static,
        M::Result: Serialize + DeserializeOwned,
    {
        for ep in &self.endpoints {
            let ep = ep.clone();
            let msg = msg.clone();
            self.runtime.spawn(Box::pin(async move {
                let _ = ep.send(msg).await;
            }));
        }
    }

    pub fn add(&mut self, endpoint: Endpoint<A>) {
        self.endpoints.push(endpoint);
    }

    pub fn remove(&mut self, index: usize) {
        if index < self.endpoints.len() {
            self.endpoints.remove(index);
        }
    }

    pub fn len(&self) -> usize {
        self.endpoints.len()
    }

    pub fn is_empty(&self) -> bool {
        self.endpoints.is_empty()
    }
}

// =============================================================================
// POOL ROUTER — reactive router that auto-tracks membership via WatchedListing
// =============================================================================

/// A reactive router that automatically maintains its endpoint pool from a
/// [`WatchedListing`]. As actors check in or deregister, the pool updates
/// in the background.
///
/// # Example
///
/// ```rust,ignore
/// let worker_key = ReceptionKey::<Worker>::new("workers");
///
/// // Pool auto-fills with existing workers and tracks changes
/// let pool = PoolRouter::new(&receptionist, worker_key, RoutingStrategy::RoundRobin);
///
/// // Send routes to a live worker — pool shrinks/grows automatically
/// let result = pool.send(DoWork { task: "hello".into() }).await?;
/// ```
/// Shared pool state: label → endpoint pairs, protected by RwLock.
type Pool<A> = Arc<RwLock<Vec<(String, Endpoint<A>)>>>;

pub struct PoolRouter<A: Actor> {
    pool: Pool<A>,
    strategy: RoutingStrategy,
    counter: AtomicUsize,
    runtime: Arc<dyn Runtime>,
}

impl<A: Actor + 'static> PoolRouter<A> {
    /// Create a reactive pool router that tracks all actors checked in with the
    /// given key. Runs a background task (on the receptionist's runtime) to
    /// consume the watched listing — so under a sim runtime the pool updates
    /// deterministically.
    pub fn new(
        receptionist: &Receptionist,
        key: ReceptionKey<A>,
        strategy: RoutingStrategy,
    ) -> Self {
        let watched = receptionist.watched_listing(key);
        Self::build(watched, strategy, receptionist.runtime().clone())
    }

    /// Create a pool router from an already-obtained watched listing, on the
    /// default (Tokio) runtime. Prefer [`new`](Self::new) for sim — it picks up
    /// the receptionist's runtime automatically.
    pub fn from_watched_listing(watched: WatchedListing<A>, strategy: RoutingStrategy) -> Self {
        Self::build(watched, strategy, Arc::new(TokioRuntime))
    }

    fn build(
        watched: WatchedListing<A>,
        strategy: RoutingStrategy,
        runtime: Arc<dyn Runtime>,
    ) -> Self {
        let pool: Pool<A> = Arc::new(RwLock::new(Vec::new()));

        // Background task to consume the watched listing, on the runtime seam.
        let pool_clone = Arc::clone(&pool);
        runtime.spawn(Box::pin(Self::run_watcher(pool_clone, watched)));

        Self {
            pool,
            strategy,
            counter: AtomicUsize::new(0),
            runtime,
        }
    }

    async fn run_watcher(pool: Pool<A>, mut watched: WatchedListing<A>) {
        while let Some(event) = watched.next().await {
            match event {
                ListingEvent::Added { label, endpoint } => {
                    let mut pool = pool.write().unwrap();
                    // Avoid duplicates (same label)
                    if !pool.iter().any(|(l, _)| l == &label) {
                        pool.push((label, endpoint));
                    }
                }
                ListingEvent::Removed { label } => {
                    let mut pool = pool.write().unwrap();
                    pool.retain(|(l, _)| l != &label);
                }
            }
        }
    }

    /// Pick the endpoint index for the current strategy. Callers hold the pool
    /// read-lock and must have guarded `len > 0` (empty is a `MailboxClosed`
    /// error). Broadcast via the single-send paths targets index 0; the real
    /// fan-out is `broadcast()`.
    fn pick_index(&self, len: usize) -> usize {
        match self.strategy {
            RoutingStrategy::RoundRobin => self.counter.fetch_add(1, Ordering::Relaxed) % len,
            RoutingStrategy::Random => (self.runtime.rng_u64() % len as u64) as usize,
            RoutingStrategy::Broadcast => 0,
        }
    }

    /// Send a message to one endpoint based on the routing strategy.
    pub async fn send<M>(&self, msg: M) -> Result<M::Result, SendError>
    where
        A: Handler<M>,
        M: RemoteMessage + Clone,
        M::Result: Serialize + DeserializeOwned,
    {
        let endpoint = {
            let pool = self.pool.read().unwrap();
            if pool.is_empty() {
                return Err(SendError::MailboxClosed);
            }

            let idx = self.pick_index(pool.len());
            pool[idx].1.clone()
        }; // lock released here

        endpoint.send(msg).await
    }

    /// Like [`send`](Self::send) but routes to an [`AsyncHandler<M>`] — the
    /// `.await`-capable handler the `#[handlers]` macro emits for an `async fn`.
    /// Same pool/strategy selection; only the per-endpoint dispatch differs.
    pub async fn send_async<M>(&self, msg: M) -> Result<M::Result, SendError>
    where
        A: AsyncHandler<M>,
        M: RemoteMessage,
        M::Result: Serialize + DeserializeOwned,
    {
        let endpoint = {
            let pool = self.pool.read().unwrap();
            if pool.is_empty() {
                return Err(SendError::MailboxClosed);
            }

            let idx = self.pick_index(pool.len());
            pool[idx].1.clone()
        }; // lock released here

        endpoint.send_async(msg).await
    }

    /// Send a message to ALL endpoints concurrently and collect results.
    pub async fn broadcast<M>(&self, msg: M) -> Vec<Result<M::Result, SendError>>
    where
        A: Handler<M>,
        M: RemoteMessage + Clone,
        M::Result: Serialize + DeserializeOwned,
    {
        let endpoints: Vec<_> = {
            let pool = self.pool.read().unwrap();
            pool.iter().map(|(_, ep)| ep.clone()).collect()
        };

        let mut inflight = FuturesUnordered::new();
        for ep in endpoints {
            let msg = msg.clone();
            inflight.push(async move { ep.send(msg).await });
        }

        let mut results = Vec::new();
        while let Some(result) = inflight.next().await {
            results.push(result);
        }
        results
    }

    /// Number of endpoints currently in the pool.
    pub fn len(&self) -> usize {
        self.pool.read().unwrap().len()
    }

    /// Whether the pool is currently empty.
    pub fn is_empty(&self) -> bool {
        self.pool.read().unwrap().is_empty()
    }

    /// Get a snapshot of current labels in the pool.
    pub fn labels(&self) -> Vec<String> {
        self.pool
            .read()
            .unwrap()
            .iter()
            .map(|(l, _)| l.clone())
            .collect()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::actor::ActorContext;
    use crate::prelude::*;
    use crate::receptionist::Receptionist;
    use serde::{Deserialize, Serialize};

    // An actor whose handler is `async` — so the `#[handlers]` macro emits
    // `AsyncHandler<AsyncAdd>` and NOT `Handler<AsyncAdd>`. That is exactly the
    // shape `send` cannot route to and `send_async` must.
    struct AsyncWorker;

    #[derive(Default)]
    struct WorkerState {
        seen: i64,
    }

    impl Actor for AsyncWorker {
        type State = WorkerState;
    }

    #[derive(Debug, Clone, Serialize, Deserialize, Message)]
    #[message(result = i64, remote = "router::AsyncAdd")]
    struct AsyncAdd {
        amount: i64,
    }

    #[handlers]
    impl AsyncWorker {
        #[handler]
        async fn async_add(
            &mut self,
            _ctx: &ActorContext<Self>,
            state: &mut WorkerState,
            msg: AsyncAdd,
        ) -> i64 {
            state.seen += msg.amount;
            state.seen
        }
    }

    #[tokio::test]
    async fn router_send_async_round_robins_to_async_handlers() {
        let recep = Receptionist::new();
        let ep1 = recep.start("w/1", AsyncWorker, WorkerState::default());
        let ep2 = recep.start("w/2", AsyncWorker, WorkerState::default());
        let router = Router::new(vec![ep1, ep2], RoutingStrategy::RoundRobin);

        // Round-robin over 2 endpoints: msgs 0,2 → w/1; msgs 1,3 → w/2. Each
        // endpoint sees 2 increments; the 4th reply is w/2's running total (2).
        let mut last = 0;
        for _ in 0..4 {
            last = router
                .send_async(AsyncAdd { amount: 1 })
                .await
                .expect("send_async routes to the AsyncHandler");
        }
        assert_eq!(
            last, 2,
            "round-robin spread the 4 sends evenly across 2 async actors"
        );
    }

    #[tokio::test]
    async fn router_send_async_empty_pool_errors() {
        let router: Router<AsyncWorker> = Router::new(vec![], RoutingStrategy::RoundRobin);
        assert!(matches!(
            router.send_async(AsyncAdd { amount: 1 }).await,
            Err(SendError::MailboxClosed)
        ));
    }
}