Skip to main content

ghast_client/
swarm.rs

1//! Many bots in one process: [`Swarm`].
2//!
3//! A swarm is a small scheduler, nothing more: every bot is still an independent [`Client`]
4//! session. The swarm owns N worker OS threads, each with its own current-thread tokio
5//! runtime and a [`LocalSet`](tokio::task::LocalSet); a bot is placed on the least-loaded
6//! worker when it is spawned and stays there. Bots on one worker share that thread
7//! cooperatively, bots on different workers run in parallel. Nothing is shared between bots,
8//! so they may join different servers with different versions.
9//!
10//! [`Client`]: crate::Client
11
12use std::any::Any;
13use std::fmt;
14use std::future::Future;
15use std::pin::Pin;
16use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering};
17use std::sync::{Arc, Condvar, Mutex, PoisonError};
18use std::thread::{self, ThreadId};
19use std::time::{Duration, Instant};
20
21use tokio::sync::{Notify, mpsc, oneshot};
22
23/// One bot's start-up work, sent to its worker thread.
24type Job = Box<dyn FnOnce() -> Pin<Box<dyn Future<Output = ()>>> + Send>;
25
26/// Default thread name prefix of the workers (`ghast-swarm-0`, `ghast-swarm-1`, …).
27const DEFAULT_THREAD_NAME: &str = "ghast-swarm";
28
29/// Default time [`Drop`] gives the bots to end on their own before they are aborted.
30const DEFAULT_DROP_GRACE: Duration = Duration::from_secs(5);
31
32/// Minimum time a shutdown waits for the workers after aborting their bots.
33const ABORT_WAIT_MIN: Duration = Duration::from_secs(1);
34
35/// A one-way flag with async waiters.
36#[derive(Default)]
37struct Signal {
38    set: AtomicBool,
39    notify: Notify,
40}
41
42impl Signal {
43    fn fire(&self) {
44        self.set.store(true, Ordering::SeqCst);
45        self.notify.notify_waiters();
46    }
47
48    fn is_set(&self) -> bool {
49        self.set.load(Ordering::SeqCst)
50    }
51
52    async fn wait(&self) {
53        loop {
54            // A `Notified` receives `notify_waiters` from the moment it is created, so checking
55            // the flag after creating it cannot miss a `fire`.
56            let notified = self.notify.notified();
57            if self.is_set() {
58                return;
59            }
60            notified.await;
61        }
62    }
63}
64
65/// State shared by the swarm, its workers, its bots and their handles.
66struct Shared {
67    /// Soft stop of every bot (their [`BotContext::stopped`] completes).
68    stop: Signal,
69    /// Hard stop: the workers drop every bot that is still running.
70    abort: Signal,
71    /// Minimum spacing between bot starts.
72    join_delay: Duration,
73    /// When the most recently spawned bot is allowed to start.
74    last_start: Mutex<Option<Instant>>,
75    /// Worker threads still running.
76    alive: Mutex<usize>,
77    alive_changed: Condvar,
78    next_id: AtomicU64,
79}
80
81impl Shared {
82    /// The start slot of a bot spawned now: at least `join_delay` after the previous one.
83    fn start_slot(&self) -> Option<Instant> {
84        if self.join_delay.is_zero() {
85            return None;
86        }
87        let now = Instant::now();
88        let mut last = self
89            .last_start
90            .lock()
91            .unwrap_or_else(PoisonError::into_inner);
92        let at = match *last {
93            Some(prev) => (prev + self.join_delay).max(now),
94            None => now,
95        };
96        *last = Some(at);
97        Some(at)
98    }
99
100    /// Waits until at most `target` workers are alive or `deadline` passes; true if reached.
101    fn wait_alive(&self, target: usize, deadline: Instant) -> bool {
102        let mut alive = self.alive.lock().unwrap_or_else(PoisonError::into_inner);
103        while *alive > target {
104            let left = deadline.saturating_duration_since(Instant::now());
105            if left.is_zero() {
106                return false;
107            }
108            alive = self
109                .alive_changed
110                .wait_timeout(alive, left)
111                .unwrap_or_else(PoisonError::into_inner)
112                .0;
113        }
114        true
115    }
116}
117
118/// Builder of a [`Swarm`] ([`Swarm::builder`]).
119#[derive(Debug, Clone)]
120pub struct SwarmBuilder {
121    workers: Option<usize>,
122    join_delay: Duration,
123    thread_name: String,
124    drop_grace: Duration,
125}
126
127impl Default for SwarmBuilder {
128    fn default() -> Self {
129        SwarmBuilder {
130            workers: None,
131            join_delay: Duration::ZERO,
132            thread_name: DEFAULT_THREAD_NAME.to_owned(),
133            drop_grace: DEFAULT_DROP_GRACE,
134        }
135    }
136}
137
138impl SwarmBuilder {
139    /// Number of worker threads (default: 1; at least 1).
140    ///
141    /// One worker is the cheapest layout until its thread is close to a full core: a busy
142    /// thread handles many bots per wake-up, while bots spread thinly over many threads make
143    /// every thread sleep and wake for each small batch of packets. Add workers when one
144    /// thread is no longer enough (watch the CPU of the `ghast-swarm-<n>` threads), not before.
145    #[must_use]
146    pub fn workers(mut self, n: usize) -> Self {
147        self.workers = Some(n.max(1));
148        self
149    }
150
151    /// Minimum time between two bot starts across the whole swarm (default: none). Servers
152    /// often throttle logins per address; with a delay, `spawn` still returns at once and the
153    /// bot waits on its worker until its start slot. Slots are handed out at spawn time, in
154    /// spawn order, each at least `delay` after the previous one (and not before the spawn);
155    /// a bot never starts before its slot, but a busy worker may start it a little later.
156    #[must_use]
157    pub fn join_delay(mut self, delay: Duration) -> Self {
158        self.join_delay = delay;
159        self
160    }
161
162    /// Name prefix of the worker threads (default `ghast-swarm`; threads are `<prefix>-<n>`).
163    #[must_use]
164    pub fn thread_name(mut self, prefix: impl Into<String>) -> Self {
165        self.thread_name = prefix.into();
166        self
167    }
168
169    /// How long dropping the swarm waits for the bots to end on their own after the stop
170    /// signal, before the rest are aborted (default 5 s). See [`Swarm::shutdown`].
171    #[must_use]
172    pub fn drop_grace(mut self, grace: Duration) -> Self {
173        self.drop_grace = grace;
174        self
175    }
176
177    /// Starts the worker threads.
178    ///
179    /// # Errors
180    ///
181    /// Creating a runtime or a thread failed (the threads started so far are stopped again).
182    pub fn build(self) -> std::io::Result<Swarm> {
183        let n = self.workers.unwrap_or(1);
184        let shared = Arc::new(Shared {
185            stop: Signal::default(),
186            abort: Signal::default(),
187            join_delay: self.join_delay,
188            last_start: Mutex::new(None),
189            alive: Mutex::new(0),
190            alive_changed: Condvar::new(),
191            next_id: AtomicU64::new(0),
192        });
193        let mut swarm = Swarm {
194            shared: Arc::clone(&shared),
195            workers: Vec::with_capacity(n),
196            cursor: Mutex::new(0),
197            drop_grace: self.drop_grace,
198            done: false,
199        };
200        for i in 0..n {
201            // A failed start drops `swarm`, which stops the workers started so far.
202            let rt = tokio::runtime::Builder::new_current_thread()
203                .enable_all()
204                .build()?;
205            let (tx, rx) = mpsc::unbounded_channel();
206            *shared.alive.lock().unwrap_or_else(PoisonError::into_inner) += 1;
207            let worker_shared = Arc::clone(&shared);
208            let spawned = thread::Builder::new()
209                .name(format!("{}-{i}", self.thread_name))
210                .spawn(move || worker_main(rt, rx, worker_shared));
211            let thread = match spawned {
212                Ok(t) => t,
213                Err(e) => {
214                    *shared.alive.lock().unwrap_or_else(PoisonError::into_inner) -= 1;
215                    return Err(e);
216                }
217            };
218            swarm.workers.push(Worker {
219                tx: Some(tx),
220                load: Arc::new(AtomicUsize::new(0)),
221                thread_id: thread.thread().id(),
222                thread: Some(thread),
223            });
224        }
225        Ok(swarm)
226    }
227}
228
229/// Marks a worker thread as gone when it exits (also by a panic).
230struct AliveGuard(Arc<Shared>);
231
232impl Drop for AliveGuard {
233    fn drop(&mut self) {
234        let mut alive = self.0.alive.lock().unwrap_or_else(PoisonError::into_inner);
235        *alive -= 1;
236        self.0.alive_changed.notify_all();
237    }
238}
239
240fn worker_main(
241    rt: tokio::runtime::Runtime,
242    mut rx: mpsc::UnboundedReceiver<Job>,
243    shared: Arc<Shared>,
244) {
245    let _alive = AliveGuard(Arc::clone(&shared));
246    let local = tokio::task::LocalSet::new();
247    // Accept bots until the swarm closes the channel (shutdown / drop) or aborts.
248    let aborted = rt.block_on(local.run_until(async {
249        let accept = async {
250            while let Some(job) = rx.recv().await {
251                drop(tokio::task::spawn_local(job()));
252            }
253        };
254        tokio::select! {
255            () = accept => false,
256            () = shared.abort.wait() => true,
257        }
258    }));
259    if !aborted {
260        // Then run the remaining bots to their end, unless the swarm aborts them.
261        rt.block_on(async {
262            tokio::select! {
263                () = local => {}
264                () = shared.abort.wait() => {}
265            }
266        });
267    } else {
268        // Dropping the set drops every bot still in it; their handles report `Aborted`.
269        let _enter = rt.enter();
270        drop(local);
271    }
272    drop(rt);
273}
274
275/// One worker thread as the swarm sees it.
276struct Worker {
277    /// `None` once the swarm closed it.
278    tx: Option<mpsc::UnboundedSender<Job>>,
279    /// Bots assigned to this worker that have not ended yet.
280    load: Arc<AtomicUsize>,
281    thread_id: ThreadId,
282    thread: Option<thread::JoinHandle<()>>,
283}
284
285/// Decrements a worker's load when a bot ends (also when it is aborted).
286struct LoadGuard(Arc<AtomicUsize>);
287
288impl Drop for LoadGuard {
289    fn drop(&mut self) {
290        self.0.fetch_sub(1, Ordering::SeqCst);
291    }
292}
293
294/// Many bots in one process, on one or a few worker threads.
295///
296/// Each worker thread runs a current-thread tokio runtime, which is the cheap layout for many
297/// bots (a multi-thread runtime moves bots between threads and pays for the wake-ups). Each
298/// bot is still an independent [`Client`](crate::Client) session: the swarm only decides which
299/// thread runs it and when it starts.
300///
301/// [`Swarm::spawn`] takes a closure that is sent to the bot's worker thread and called there,
302/// so the future it returns does not need to be `Send` (behaviours may hold `Rc`s, for
303/// example). The bot gets a [`BotContext`] whose [`stopped`](BotContext::stopped) future is
304/// meant for [`Client::run_until`](crate::Client::run_until). A bot that panics only ends
305/// itself: its [`BotHandle`] reports [`BotError::Panicked`], the other bots and the worker go
306/// on.
307///
308/// ```no_run
309/// use std::time::Duration;
310/// use ghast_client::{Account, Behavior, Client, GameVersion, Swarm, TickContext};
311///
312/// struct Afk;
313/// impl Behavior for Afk {
314///     fn tick(&mut self, ctx: &mut TickContext<'_>) {
315///         if ctx.is_dead() {
316///             ctx.respawn();
317///         }
318///     }
319/// }
320///
321/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
322/// let swarm = Swarm::builder()
323///     .join_delay(Duration::from_millis(200))
324///     .build()?;
325/// let mut bots = Vec::new();
326/// for i in 0..100 {
327///     let client = Client::new(
328///         "localhost:25565".parse()?,
329///         GameVersion::V1_8_9,
330///         Account::offline(&format!("Bot{i}"))?,
331///     );
332///     bots.push(swarm.spawn(move |bot| async move {
333///         client.run_until(&mut Afk, bot.stopped()).await
334///     }));
335/// }
336/// // ... later: ask every bot to log out, give them 10 s, abort the rest.
337/// let report = swarm.shutdown(Duration::from_secs(10));
338/// for bot in bots {
339///     println!("{:?}", bot.join_blocking());
340/// }
341/// println!("{} bots had to be aborted", report.aborted);
342/// # Ok(())
343/// # }
344/// ```
345///
346/// Dropping the swarm does the same as [`shutdown`](Swarm::shutdown) with the builder's
347/// [`drop_grace`](SwarmBuilder::drop_grace), so it blocks for a bounded time. [`BotHandle`]s stay usable after the swarm is gone, and
348/// dropping a handle does not stop its bot.
349pub struct Swarm {
350    shared: Arc<Shared>,
351    workers: Vec<Worker>,
352    /// Round-robin start of the least-loaded search; the lock also makes picking a worker and
353    /// counting the bot on it one step.
354    cursor: Mutex<usize>,
355    drop_grace: Duration,
356    /// Set once the workers are shut down.
357    done: bool,
358}
359
360impl fmt::Debug for Swarm {
361    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
362        f.debug_struct("Swarm")
363            .field("workers", &self.workers.len())
364            .field("loads", &self.worker_loads())
365            .field("join_delay", &self.shared.join_delay)
366            .field("stopping", &self.shared.stop.is_set())
367            .finish()
368    }
369}
370
371impl Swarm {
372    /// A builder (worker count, join delay, thread names).
373    #[must_use]
374    pub fn builder() -> SwarmBuilder {
375        SwarmBuilder::default()
376    }
377
378    /// A swarm with the default settings: one worker thread, no join delay.
379    ///
380    /// # Errors
381    ///
382    /// See [`SwarmBuilder::build`].
383    pub fn new() -> std::io::Result<Swarm> {
384        SwarmBuilder::default().build()
385    }
386
387    /// Number of worker threads.
388    #[must_use]
389    pub fn workers(&self) -> usize {
390        self.workers.len()
391    }
392
393    /// Bots that were spawned and have not ended yet (including those waiting for their start
394    /// slot).
395    #[must_use]
396    pub fn bots(&self) -> usize {
397        self.worker_loads().iter().sum()
398    }
399
400    /// Live bots per worker thread.
401    #[must_use]
402    pub fn worker_loads(&self) -> Vec<usize> {
403        self.workers
404            .iter()
405            .map(|w| w.load.load(Ordering::SeqCst))
406            .collect()
407    }
408
409    /// Starts a bot. `bot` is sent to the least-loaded worker thread (ties: round-robin) and
410    /// called there once the bot's start slot (see [`SwarmBuilder::join_delay`]) has come; the
411    /// bot runs until the future it returns completes. Returns at once.
412    ///
413    /// A bot spawned after [`stop_all`](Swarm::stop_all) does not start; its handle reports
414    /// [`BotError::NotStarted`].
415    pub fn spawn<F, Fut>(&self, bot: F) -> BotHandle<Fut::Output>
416    where
417        F: FnOnce(BotContext) -> Fut + Send + 'static,
418        Fut: Future + 'static,
419        Fut::Output: Send + 'static,
420    {
421        let id = self.shared.next_id.fetch_add(1, Ordering::Relaxed);
422        let stop = Arc::new(Signal::default());
423        let (tx, rx) = oneshot::channel();
424        let handle = BotHandle {
425            id,
426            worker: 0,
427            stop: Arc::clone(&stop),
428            rx,
429        };
430        if self.done || self.workers.is_empty() {
431            let _ = tx.send(Err(BotError::NotStarted));
432            return handle;
433        }
434        let (worker, load) = self.pick_worker();
435        let start = self.shared.start_slot();
436        let ctx = BotContext {
437            id,
438            worker,
439            stop,
440            shared: Arc::clone(&self.shared),
441        };
442        let load = LoadGuard(load);
443        let job: Job = Box::new(move || Box::pin(run_bot(ctx, start, load, bot, tx)));
444        if let Some(sender) = &self.workers[worker].tx {
445            // A send only fails when the worker is gone; the dropped job (and its result
446            // sender) then makes the handle report `Aborted`.
447            let _ = sender.send(job);
448        }
449        BotHandle { worker, ..handle }
450    }
451
452    fn pick_worker(&self) -> (usize, Arc<AtomicUsize>) {
453        let mut cursor = self.cursor.lock().unwrap_or_else(PoisonError::into_inner);
454        let n = self.workers.len();
455        let mut best = *cursor % n;
456        let mut best_load = usize::MAX;
457        for k in 0..n {
458            let i = (*cursor + k) % n;
459            let load = self.workers[i].load.load(Ordering::SeqCst);
460            if load < best_load {
461                best = i;
462                best_load = load;
463            }
464        }
465        *cursor = (best + 1) % n;
466        let load = Arc::clone(&self.workers[best].load);
467        load.fetch_add(1, Ordering::SeqCst);
468        (best, load)
469    }
470
471    /// Asks every bot to stop: their [`BotContext::stopped`] futures complete (a bot running
472    /// [`Client::run_until`](crate::Client::run_until) with it logs out). Does not wait; bots
473    /// spawned afterwards do not start. Await the [`BotHandle`]s, or call
474    /// [`shutdown`](Swarm::shutdown), to wait for the bots.
475    pub fn stop_all(&self) {
476        self.shared.stop.fire();
477    }
478
479    /// Stops every bot and the worker threads: fires [`stop_all`](Swarm::stop_all), waits up to
480    /// `grace` for the bots to end on their own, then aborts the rest (their futures are
481    /// dropped and their handles report [`BotError::Aborted`]) and joins the threads.
482    ///
483    /// Blocks the calling thread for at most `grace` plus, if bots had to be aborted, up to
484    /// `max(grace, 1 s)` more; a worker still blocked then (a bot blocking its thread without
485    /// awaiting) is left running detached and counted in
486    /// [`ShutdownReport::stuck_workers`]. From async code,
487    /// call [`stop_all`](Swarm::stop_all) and await the handles instead, then drop the swarm.
488    pub fn shutdown(mut self, grace: Duration) -> ShutdownReport {
489        self.shutdown_inner(grace)
490    }
491
492    fn shutdown_inner(&mut self, grace: Duration) -> ShutdownReport {
493        if self.done {
494            return ShutdownReport {
495                aborted: 0,
496                stuck_workers: 0,
497            };
498        }
499        self.done = true;
500        self.shared.stop.fire();
501        for w in &mut self.workers {
502            // Closing the channel lets the worker exit once its bots have ended.
503            w.tx = None;
504        }
505        // Called from one of our own workers (a bot dropped the swarm): that worker cannot
506        // finish while we block it, so only wait for the others and leave it detached.
507        let me = thread::current().id();
508        let own = self.workers.iter().any(|w| w.thread_id == me);
509        let target = usize::from(own);
510        let deadline = Instant::now() + grace;
511        let mut aborted = 0;
512        if !self.shared.wait_alive(target, deadline) {
513            aborted = self.bots();
514            self.shared.abort.fire();
515            // The workers drop their bots at their next await point. A bot that blocks its
516            // thread never gets there: do not wait for it forever.
517            let again = grace.max(ABORT_WAIT_MIN);
518            self.shared.wait_alive(target, Instant::now() + again);
519        }
520        let mut stuck_workers = 0;
521        for w in &mut self.workers {
522            if let Some(t) = w.thread.take() {
523                if w.thread_id == me {
524                    continue;
525                }
526                if t.is_finished() {
527                    let _ = t.join();
528                } else {
529                    // Detached: it exits on its own once the blocking bot returns.
530                    stuck_workers += 1;
531                }
532            }
533        }
534        if stuck_workers > 0 {
535            log::warn!("swarm: {stuck_workers} worker thread(s) blocked by a bot, left detached");
536        }
537        ShutdownReport {
538            aborted,
539            stuck_workers,
540        }
541    }
542}
543
544impl Drop for Swarm {
545    fn drop(&mut self) {
546        let grace = self.drop_grace;
547        self.shutdown_inner(grace);
548    }
549}
550
551/// What [`Swarm::shutdown`] did.
552#[derive(Debug, Clone, Copy, PartialEq, Eq)]
553#[non_exhaustive]
554pub struct ShutdownReport {
555    /// Bots that had not ended within the grace time and were aborted.
556    pub aborted: usize,
557    /// Worker threads that were still blocked after the abort (a bot blocking its thread
558    /// without awaiting) and were left running detached; normally 0.
559    pub stuck_workers: usize,
560}
561
562async fn run_bot<F, Fut>(
563    ctx: BotContext,
564    start: Option<Instant>,
565    load: LoadGuard,
566    bot: F,
567    tx: oneshot::Sender<Result<Fut::Output, BotError>>,
568) where
569    F: FnOnce(BotContext) -> Fut + 'static,
570    Fut: Future + 'static,
571{
572    if let Some(at) = start {
573        tokio::select! {
574            () = tokio::time::sleep_until(at.into()) => {}
575            () = ctx.stopped() => {}
576        }
577    }
578    let result = if ctx.is_stopped() {
579        Err(BotError::NotStarted)
580    } else {
581        // Its own task, so a panic (also one in `bot` itself) is caught by tokio and only
582        // ends this bot.
583        match tokio::task::spawn_local(async move { bot(ctx).await }).await {
584            Ok(v) => Ok(v),
585            Err(e) => match e.try_into_panic() {
586                Ok(payload) => Err(BotError::Panicked(panic_message(payload.as_ref()))),
587                Err(_) => Err(BotError::Aborted),
588            },
589        }
590    };
591    // Load first, so a caller that saw the result also sees the lower load.
592    drop(load);
593    let _ = tx.send(result);
594}
595
596fn panic_message(payload: &(dyn Any + Send)) -> String {
597    if let Some(s) = payload.downcast_ref::<&str>() {
598        (*s).to_owned()
599    } else if let Some(s) = payload.downcast_ref::<String>() {
600        s.clone()
601    } else {
602        "a non-string panic payload".to_owned()
603    }
604}
605
606/// What a bot gets from the swarm when it starts.
607pub struct BotContext {
608    id: u64,
609    worker: usize,
610    stop: Arc<Signal>,
611    shared: Arc<Shared>,
612}
613
614impl fmt::Debug for BotContext {
615    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
616        f.debug_struct("BotContext")
617            .field("id", &self.id)
618            .field("worker", &self.worker)
619            .field("stopped", &self.is_stopped())
620            .finish()
621    }
622}
623
624impl BotContext {
625    /// The bot's number in the swarm (0, 1, … in spawn order).
626    #[must_use]
627    pub fn id(&self) -> u64 {
628        self.id
629    }
630
631    /// The worker thread the bot runs on (`0..Swarm::workers()`).
632    #[must_use]
633    pub fn worker(&self) -> usize {
634        self.worker
635    }
636
637    /// True once the bot was asked to stop ([`BotHandle::stop`], [`Swarm::stop_all`],
638    /// [`Swarm::shutdown`] or dropping the swarm).
639    #[must_use]
640    pub fn is_stopped(&self) -> bool {
641        self.stop.is_set() || self.shared.stop.is_set()
642    }
643
644    /// Completes once the bot is asked to stop; pass it to
645    /// [`Client::run_until`](crate::Client::run_until). Can be called any number of times
646    /// (e.g. once per reconnect).
647    pub fn stopped(&self) -> impl Future<Output = ()> + Send + 'static {
648        let own = Arc::clone(&self.stop);
649        let shared = Arc::clone(&self.shared);
650        async move {
651            tokio::select! {
652                () = own.wait() => {}
653                () = shared.stop.wait() => {}
654            }
655        }
656    }
657}
658
659/// Why a bot has no result.
660#[derive(Debug, Clone, PartialEq, Eq)]
661#[non_exhaustive]
662pub enum BotError {
663    /// The bot panicked (the panic message).
664    Panicked(String),
665    /// The bot was asked to stop before its start slot, or spawned after the swarm stopped.
666    NotStarted,
667    /// The bot was still running when the swarm aborted it (shutdown grace time over, or the
668    /// swarm dropped).
669    Aborted,
670}
671
672impl fmt::Display for BotError {
673    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
674        match self {
675            BotError::Panicked(m) => write!(f, "bot panicked: {m}"),
676            BotError::NotStarted => f.write_str("bot was stopped before it started"),
677            BotError::Aborted => f.write_str("bot was aborted by the swarm"),
678        }
679    }
680}
681
682impl std::error::Error for BotError {}
683
684/// A bot in a [`Swarm`]: stop it, wait for its result. Dropping the handle does not stop
685/// the bot. Works with any runtime (or none, see [`join_blocking`](BotHandle::join_blocking)),
686/// also after the swarm is gone.
687pub struct BotHandle<T> {
688    id: u64,
689    worker: usize,
690    stop: Arc<Signal>,
691    rx: oneshot::Receiver<Result<T, BotError>>,
692}
693
694impl<T> fmt::Debug for BotHandle<T> {
695    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
696        f.debug_struct("BotHandle")
697            .field("id", &self.id)
698            .field("worker", &self.worker)
699            .finish_non_exhaustive()
700    }
701}
702
703impl<T> BotHandle<T> {
704    /// The bot's number in the swarm ([`BotContext::id`]).
705    #[must_use]
706    pub fn id(&self) -> u64 {
707        self.id
708    }
709
710    /// The worker thread the bot was assigned to.
711    #[must_use]
712    pub fn worker(&self) -> usize {
713        self.worker
714    }
715
716    /// Asks this bot to stop (its [`BotContext::stopped`] completes). Does not wait.
717    pub fn stop(&self) {
718        self.stop.fire();
719    }
720
721    /// Waits for the bot's end and returns what its future returned.
722    ///
723    /// # Errors
724    ///
725    /// The bot panicked, never started or was aborted ([`BotError`]).
726    pub async fn join(self) -> Result<T, BotError> {
727        self.rx.await.unwrap_or(Err(BotError::Aborted))
728    }
729
730    /// [`join`](BotHandle::join) for synchronous code.
731    ///
732    /// # Errors
733    ///
734    /// See [`join`](BotHandle::join).
735    ///
736    /// # Panics
737    ///
738    /// When called from inside an async runtime (it blocks the thread).
739    pub fn join_blocking(self) -> Result<T, BotError> {
740        self.rx.blocking_recv().unwrap_or(Err(BotError::Aborted))
741    }
742}
743
744#[cfg(test)]
745mod tests {
746    use super::*;
747    use std::sync::mpsc as std_mpsc;
748
749    #[test]
750    fn assignment_spreads_over_workers() {
751        let swarm = Swarm::builder()
752            .workers(4)
753            .thread_name("spread")
754            .build()
755            .unwrap();
756        assert_eq!(swarm.workers(), 4);
757        let (started, wait_started) = std_mpsc::channel();
758        let handles: Vec<_> = (0..8)
759            .map(|_| {
760                let started = started.clone();
761                swarm.spawn(move |bot| async move {
762                    let name = thread::current().name().map(str::to_owned);
763                    started.send(()).unwrap();
764                    bot.stopped().await;
765                    (bot.worker(), name)
766                })
767            })
768            .collect();
769        let mut per_worker = [0; 4];
770        for h in &handles {
771            per_worker[h.worker()] += 1;
772        }
773        assert_eq!(per_worker, [2, 2, 2, 2]);
774        assert_eq!(swarm.bots(), 8);
775        assert_eq!(swarm.worker_loads(), vec![2, 2, 2, 2]);
776        for _ in 0..8 {
777            wait_started.recv().unwrap();
778        }
779        swarm.stop_all();
780        for h in handles {
781            let assigned = h.worker();
782            let (worker, name) = h.join_blocking().unwrap();
783            assert_eq!(worker, assigned);
784            assert_eq!(name.as_deref(), Some(format!("spread-{worker}").as_str()));
785        }
786        assert_eq!(swarm.bots(), 0);
787    }
788
789    #[test]
790    fn least_loaded_worker_is_picked() {
791        let swarm = Swarm::builder().workers(3).build().unwrap();
792        let (started, wait_started) = std_mpsc::channel();
793        let idle = |started: std_mpsc::Sender<()>| {
794            move |bot: BotContext| async move {
795                started.send(()).unwrap();
796                bot.stopped().await;
797            }
798        };
799        let a = swarm.spawn(idle(started.clone()));
800        let b = swarm.spawn(idle(started.clone()));
801        let c = swarm.spawn(idle(started.clone()));
802        assert_eq!((a.worker(), b.worker(), c.worker()), (0, 1, 2));
803        for _ in 0..3 {
804            wait_started.recv().unwrap();
805        }
806        b.stop();
807        b.join_blocking().unwrap();
808        // Worker 1 is now the only empty one.
809        let d = swarm.spawn(idle(started.clone()));
810        assert_eq!(d.worker(), 1);
811        wait_started.recv().unwrap();
812        assert_eq!(swarm.shutdown(Duration::from_secs(5)).aborted, 0);
813        for h in [a, c, d] {
814            h.join_blocking().unwrap();
815        }
816    }
817
818    #[test]
819    fn join_delay_is_respected() {
820        let delay = Duration::from_millis(60);
821        let swarm = Swarm::builder()
822            .workers(2)
823            .join_delay(delay)
824            .build()
825            .unwrap();
826        let t0 = Instant::now();
827        let handles: Vec<_> = (0..4)
828            .map(|_| swarm.spawn(|_| async { Instant::now() }))
829            .collect();
830        let starts: Vec<Instant> = handles
831            .into_iter()
832            .map(|h| h.join_blocking().unwrap())
833            .collect();
834        for (k, start) in starts.iter().enumerate() {
835            // Bot k never starts before its slot, k delays after the first spawn. (A busy
836            // worker may start it later, so the measured gaps between two bots can be shorter.)
837            // The timer wheel has 1 ms granularity and never fires early; allow 1 ms of rounding.
838            let after = start.duration_since(t0) + Duration::from_millis(1);
839            assert!(after >= delay * k as u32, "bot {k} started after {after:?}");
840        }
841        // And the slots do not drift: the last bot is not far behind its slot either.
842        let last = starts[3].duration_since(t0);
843        assert!(
844            last < delay * 3 + Duration::from_secs(2),
845            "last bot after {last:?}"
846        );
847    }
848
849    #[test]
850    fn panicking_bot_does_not_affect_others() {
851        let swarm = Swarm::builder().workers(1).build().unwrap();
852        let ok1 = swarm.spawn(|_| async {
853            tokio::time::sleep(Duration::from_millis(30)).await;
854            1
855        });
856        let bad = swarm.spawn(|_| async {
857            tokio::task::yield_now().await;
858            panic!("boom");
859        });
860        let bad_early = swarm.spawn(|_| -> std::future::Ready<i32> { panic!("in the factory") });
861        let ok2 = swarm.spawn(|_| async {
862            tokio::time::sleep(Duration::from_millis(30)).await;
863            2
864        });
865        assert_eq!(
866            bad.join_blocking(),
867            Err::<(), _>(BotError::Panicked("boom".into()))
868        );
869        assert_eq!(
870            bad_early.join_blocking(),
871            Err(BotError::Panicked("in the factory".into()))
872        );
873        assert_eq!(ok1.join_blocking(), Ok(1));
874        assert_eq!(ok2.join_blocking(), Ok(2));
875        // The worker is still alive.
876        assert_eq!(swarm.spawn(|_| async { 3 }).join_blocking(), Ok(3));
877    }
878
879    #[test]
880    fn shutdown_stops_everything() {
881        let swarm = Swarm::builder().workers(2).build().unwrap();
882        let (started, wait_started) = std_mpsc::channel();
883        let polite: Vec<_> = (0..4)
884            .map(|i| {
885                let started = started.clone();
886                swarm.spawn(move |bot| async move {
887                    started.send(()).unwrap();
888                    bot.stopped().await;
889                    i
890                })
891            })
892            .collect();
893        let stubborn = swarm.spawn(move |_| async move {
894            started.send(()).unwrap();
895            std::future::pending::<()>().await;
896        });
897        for _ in 0..5 {
898            wait_started.recv().unwrap();
899        }
900        let t0 = Instant::now();
901        let report = swarm.shutdown(Duration::from_millis(200));
902        let took = t0.elapsed();
903        assert_eq!(report.aborted, 1);
904        assert!(took < Duration::from_secs(2), "shutdown took {took:?}");
905        for (i, h) in polite.into_iter().enumerate() {
906            assert_eq!(h.join_blocking(), Ok(i));
907        }
908        assert_eq!(stubborn.join_blocking(), Err(BotError::Aborted));
909    }
910
911    #[test]
912    fn shutdown_does_not_hang_on_a_blocking_bot() {
913        let swarm = Swarm::builder().workers(2).build().unwrap();
914        let (started, wait_started) = std_mpsc::channel();
915        let started2 = started.clone();
916        let blocker = swarm.spawn(move |_| async move {
917            started.send(()).unwrap();
918            // Blocks its worker thread without ever awaiting.
919            thread::sleep(Duration::from_secs(3));
920        });
921        let other = swarm.spawn(move |bot| async move {
922            started2.send(()).unwrap();
923            bot.stopped().await;
924        });
925        wait_started.recv().unwrap();
926        wait_started.recv().unwrap();
927        let t0 = Instant::now();
928        let report = swarm.shutdown(Duration::from_millis(100));
929        let took = t0.elapsed();
930        assert_eq!(report.stuck_workers, 1);
931        assert!(took < Duration::from_millis(2500), "shutdown took {took:?}");
932        assert_eq!(other.join_blocking(), Ok(()));
933        // The blocked worker finishes the bot's synchronous part, then drops it at its next
934        // await point (its end): the handle reports the result or the abort, never hangs.
935        let _ = blocker.join_blocking();
936    }
937
938    #[test]
939    fn stop_before_start_slot() {
940        let swarm = Swarm::builder()
941            .workers(1)
942            .join_delay(Duration::from_secs(30))
943            .build()
944            .unwrap();
945        let first = swarm.spawn(|_| async { 1 });
946        let second = swarm.spawn(|_| async { 2 });
947        assert_eq!(first.join_blocking(), Ok(1));
948        second.stop();
949        assert_eq!(second.join_blocking(), Err(BotError::NotStarted));
950        swarm.stop_all();
951        assert_eq!(
952            swarm.spawn(|_| async { 3 }).join_blocking(),
953            Err(BotError::NotStarted)
954        );
955    }
956
957    #[test]
958    fn handles_outlive_the_swarm() {
959        let swarm = Swarm::builder()
960            .workers(2)
961            .drop_grace(Duration::from_secs(5))
962            .build()
963            .unwrap();
964        let (started, wait_started) = std_mpsc::channel();
965        let h = swarm.spawn(move |bot| async move {
966            started.send(()).unwrap();
967            bot.stopped().await;
968            "logged out"
969        });
970        wait_started.recv().unwrap();
971        drop(swarm);
972        assert_eq!(h.join_blocking(), Ok("logged out"));
973    }
974
975    #[test]
976    fn swarm_outlives_dropped_handles() {
977        let swarm = Swarm::builder().workers(2).build().unwrap();
978        let (tx, rx) = std_mpsc::channel();
979        let h = swarm.spawn(move |_| async move {
980            tokio::time::sleep(Duration::from_millis(50)).await;
981            tx.send("still ran").unwrap();
982        });
983        drop(h);
984        assert_eq!(rx.recv_timeout(Duration::from_secs(5)), Ok("still ran"));
985        assert_eq!(swarm.spawn(|_| async { 7 }).join_blocking(), Ok(7));
986    }
987
988    #[test]
989    fn async_join_from_another_runtime() {
990        let swarm = Swarm::builder().workers(1).build().unwrap();
991        let h = swarm.spawn(|bot| async move { bot.id() + 10 });
992        let rt = tokio::runtime::Builder::new_current_thread()
993            .build()
994            .unwrap();
995        assert_eq!(rt.block_on(h.join()), Ok(10));
996    }
997
998    #[test]
999    fn non_send_futures_run() {
1000        let swarm = Swarm::builder().workers(1).build().unwrap();
1001        let h = swarm.spawn(|_| async {
1002            let rc = std::rc::Rc::new(5);
1003            tokio::task::yield_now().await;
1004            *rc
1005        });
1006        assert_eq!(h.join_blocking(), Ok(5));
1007    }
1008
1009    #[test]
1010    fn swarm_dropped_inside_a_bot() {
1011        let swarm = Swarm::builder()
1012            .workers(2)
1013            .drop_grace(Duration::from_millis(100))
1014            .build()
1015            .unwrap();
1016        let (started, wait_started) = std_mpsc::channel();
1017        let other = swarm.spawn(move |bot| async move {
1018            started.send(()).unwrap();
1019            bot.stopped().await;
1020        });
1021        wait_started.recv().unwrap();
1022        let (tx, rx) = std_mpsc::channel::<Swarm>();
1023        let dropper = swarm.spawn(move |_| async move {
1024            let s = rx.recv().unwrap();
1025            drop(s);
1026            "dropped"
1027        });
1028        tx.send(swarm).unwrap();
1029        assert_eq!(dropper.join_blocking(), Ok("dropped"));
1030        assert_eq!(other.join_blocking(), Ok(()));
1031    }
1032}