Skip to main content

azalea/swarm/
builder.rs

1use std::{
2    collections::{HashMap, hash_map},
3    mem,
4    sync::{
5        Arc,
6        atomic::{self, AtomicBool},
7    },
8    time::Duration,
9};
10
11use azalea_client::{DefaultPlugins, account::Account, start_ecs_runner};
12use azalea_protocol::address::{ResolvableAddr, ResolvedAddr};
13use azalea_world::Worlds;
14use bevy_app::{App, AppExit, Plugins, SubApp};
15use bevy_ecs::{component::Component, resource::Resource};
16use futures::future::join_all;
17use parking_lot::RwLock;
18use tokio::{sync::mpsc, task};
19use tracing::{debug, error, warn};
20
21use crate::{
22    BoxHandleFn, HandleFn, JoinOpts, NoState, TokioRuntimeHandle,
23    auto_reconnect::{AutoReconnectDelay, DEFAULT_RECONNECT_DELAY},
24    bot::DefaultBotPlugins,
25    swarm::{
26        BoxSwarmHandleFn, DefaultSwarmPlugins, NoSwarmState, Swarm, SwarmEvent, SwarmHandleFn,
27    },
28};
29
30/// Create a new [`Swarm`].
31///
32/// The generics of this struct stand for the following:
33/// - S: State
34/// - SS: Swarm State
35/// - R: Return type of the handler
36/// - SR: Return type of the swarm handler
37///
38/// You shouldn't have to manually set them though, they'll be inferred for you.
39pub struct SwarmBuilder<S, SS, R, SR>
40where
41    S: Send + Sync + Clone + Component + 'static,
42    SS: Default + Send + Sync + Clone + Resource + 'static,
43    Self: Send,
44{
45    // SubApp is used instead of App to make it Send
46    pub(crate) app: SubApp,
47    /// The accounts and proxies that are going to join the server.
48    pub(crate) accounts: Vec<(Account, JoinOpts)>,
49    /// The individual bot states.
50    ///
51    /// This must be the same length as `accounts`, since each bot gets one
52    /// state.
53    pub(crate) states: Vec<S>,
54    /// The state for the overall swarm.
55    pub(crate) swarm_state: SS,
56    /// The function that's called every time a bot receives an [`Event`].
57    pub(crate) handler: Option<BoxHandleFn<S, R>>,
58    /// The function that's called every time the swarm receives a
59    /// [`SwarmEvent`].
60    pub(crate) swarm_handler: Option<BoxSwarmHandleFn<SS, SR>>,
61
62    /// How long we should wait between each bot joining the server.
63    ///
64    /// If this is None, every bot will connect at the same time. None is
65    /// different than a duration of 0, since if a duration is present the
66    /// bots will wait for the previous one to be ready.
67    pub(crate) join_delay: Option<Duration>,
68
69    /// The default reconnection delay for our bots.
70    ///
71    /// This will change the value of the [`AutoReconnectDelay`] resource.
72    pub(crate) reconnect_after: Option<Duration>,
73}
74impl SwarmBuilder<NoState, NoSwarmState, (), ()> {
75    /// Start creating the swarm.
76    #[must_use]
77    pub fn new() -> Self {
78        Self::new_without_plugins().add_plugins((
79            DefaultPlugins,
80            DefaultBotPlugins,
81            DefaultSwarmPlugins,
82        ))
83    }
84
85    /// [`Self::new`] but without adding the plugins by default.
86    ///
87    /// This is useful if you want to disable a default plugin. This also exists
88    /// for `ClientBuilder`, see [`ClientBuilder::new_without_plugins`].
89    ///
90    /// You **must** add [`DefaultPlugins`], [`DefaultBotPlugins`], and
91    /// [`DefaultSwarmPlugins`] to this.
92    ///
93    /// ```
94    /// # use azalea::{prelude::*, swarm::{prelude::*, DefaultSwarmPlugins}, bot::DefaultBotPlugins};
95    /// use azalea::app::PluginGroup;
96    ///
97    /// let swarm_builder = SwarmBuilder::new_without_plugins()
98    ///     .add_plugins((
99    ///         DefaultBotPlugins,
100    ///         DefaultSwarmPlugins,
101    ///         azalea::DefaultPlugins
102    ///             .build()
103    ///             .disable::<azalea::chat_signing::ChatSigningPlugin>(),
104    /// ));
105    /// # swarm_builder.set_handler(handle).set_swarm_handler(swarm_handle);
106    /// # #[derive(Clone, Component, Default)]
107    /// # pub struct State;
108    /// # #[derive(Clone, Resource, Default)]
109    /// # pub struct SwarmState;
110    /// # async fn handle(mut bot: Client, event: Event, state: State) -> eyre::Result<()> {
111    /// #     Ok(())
112    /// # }
113    /// # async fn swarm_handle(swarm: Swarm, event: SwarmEvent, state: SwarmState) -> eyre::Result<()> {
114    /// #     Ok(())
115    /// # }
116    /// ```
117    ///
118    /// [`ClientBuilder::new_without_plugins`]: crate::ClientBuilder::new_without_plugins
119    #[must_use]
120    pub fn new_without_plugins() -> Self {
121        SwarmBuilder {
122            // we create the app here so plugins can add onto it.
123            // the schedules won't run until [`Self::start`] is called.
124
125            // `App::new()` is used instead of `SubApp::new()` so the necessary
126            // resources are initialized
127            app: mem::take(App::new().main_mut()),
128            accounts: Vec::new(),
129            states: Vec::new(),
130            swarm_state: NoSwarmState,
131            handler: None,
132            swarm_handler: None,
133            join_delay: None,
134            reconnect_after: Some(DEFAULT_RECONNECT_DELAY),
135        }
136    }
137}
138
139impl<SS, SR> SwarmBuilder<NoState, SS, (), SR>
140where
141    SS: Default + Send + Sync + Clone + Resource + 'static,
142{
143    /// Set the function that's called every time a bot receives an
144    /// [`Event`](crate::Event). This is the intended way to handle
145    /// normal per-bot events.
146    ///
147    /// Currently you can have up to one handler.
148    ///
149    /// Note that if you're creating clients directly from the ECS using
150    /// [`StartJoinServerEvent`] and the client wasn't already in the ECS, then
151    /// the handler function won't be called for that client. This also applies
152    /// to [`SwarmBuilder::set_swarm_handler`]. This shouldn't be a concern for
153    /// most bots, though.
154    ///
155    /// ```
156    /// # use azalea::{prelude::*, swarm::prelude::*};
157    /// # let swarm_builder = SwarmBuilder::new().set_swarm_handler(swarm_handle);
158    /// swarm_builder.set_handler(handle);
159    ///
160    /// #[derive(Clone, Component, Default)]
161    /// struct State {}
162    /// async fn handle(mut bot: Client, event: Event, state: State) -> eyre::Result<()> {
163    ///     Ok(())
164    /// }
165    ///
166    /// # #[derive(Clone, Default, Resource)]
167    /// # struct SwarmState {}
168    /// # async fn swarm_handle(
169    /// #     mut swarm: Swarm,
170    /// #     event: SwarmEvent,
171    /// #     state: SwarmState,
172    /// # ) -> eyre::Result<()> {
173    /// #     Ok(())
174    /// # }
175    /// ```
176    ///
177    /// [`StartJoinServerEvent`]: azalea_client::join::StartJoinServerEvent
178    #[must_use]
179    pub fn set_handler<S, Fut, R>(self, handler: HandleFn<S, Fut>) -> SwarmBuilder<S, SS, R, SR>
180    where
181        Fut: Future<Output = R> + Send + 'static,
182        S: Send + Sync + Clone + Component + Default + 'static,
183    {
184        SwarmBuilder {
185            handler: Some(Box::new(move |bot, event, state: S| {
186                Box::pin(handler(bot, event, state))
187            })),
188            // if we added accounts before the State was set, we've gotta set it
189            // to the default now
190            states: vec![S::default(); self.accounts.len()],
191            app: self.app,
192            ..self
193        }
194    }
195}
196
197impl<S, R> SwarmBuilder<S, NoSwarmState, R, ()>
198where
199    S: Send + Sync + Clone + Component + 'static,
200{
201    /// Set the function that's called every time the swarm receives a
202    /// [`SwarmEvent`]. This is the intended way to handle global swarm events.
203    ///
204    /// Currently you can have up to one swarm handler.
205    ///
206    /// Note that if you're creating clients directly from the ECS using
207    /// [`StartJoinServerEvent`] and the client wasn't already in the ECS, then
208    /// this handler function won't be called for that client. This also applies
209    /// to [`SwarmBuilder::set_handler`]. This shouldn't be a concern for
210    /// most bots, though.
211    ///
212    /// ```
213    /// # use azalea::{prelude::*, swarm::prelude::*};
214    /// # let swarm_builder = SwarmBuilder::new().set_handler(handle);
215    /// swarm_builder.set_swarm_handler(swarm_handle);
216    ///
217    /// # #[derive(Clone, Component, Default)]
218    /// # struct State {}
219    ///
220    /// # async fn handle(mut bot: Client, event: Event, state: State) -> eyre::Result<()> {
221    /// #     Ok(())
222    /// # }
223    ///
224    /// #[derive(Clone, Default, Resource)]
225    /// struct SwarmState {}
226    /// async fn swarm_handle(
227    ///     mut swarm: Swarm,
228    ///     event: SwarmEvent,
229    ///     state: SwarmState,
230    /// ) -> eyre::Result<()> {
231    ///     Ok(())
232    /// }
233    /// ```
234    ///
235    /// [`StartJoinServerEvent`]: azalea_client::join::StartJoinServerEvent
236    #[must_use]
237    pub fn set_swarm_handler<SS, Fut, SR>(
238        self,
239        handler: SwarmHandleFn<SS, Fut>,
240    ) -> SwarmBuilder<S, SS, R, SR>
241    where
242        SS: Default + Send + Sync + Clone + Resource + 'static,
243        Fut: Future<Output = SR> + Send + 'static,
244    {
245        SwarmBuilder {
246            handler: self.handler,
247            app: self.app,
248            accounts: self.accounts,
249            states: self.states,
250            swarm_state: SS::default(),
251            swarm_handler: Some(Box::new(move |swarm, event, state| {
252                Box::pin(handler(swarm, event, state))
253            })),
254            join_delay: self.join_delay,
255            reconnect_after: self.reconnect_after,
256        }
257    }
258}
259
260impl<S, SS, R, SR> SwarmBuilder<S, SS, R, SR>
261where
262    S: Send + Sync + Clone + Component + 'static,
263    SS: Default + Send + Sync + Clone + Resource + 'static,
264    R: Send + 'static,
265    SR: Send + 'static,
266{
267    /// Add a vec of [`Account`]s to the swarm.
268    ///
269    /// Use [`Self::add_account`] to only add one account. If you want the
270    /// clients to have different default states, add them one at a time with
271    /// [`Self::add_account_with_state`].
272    ///
273    /// By default, every account will join at the same time, you can add a
274    /// delay with [`Self::join_delay`].
275    #[must_use]
276    pub fn add_accounts(mut self, accounts: Vec<Account>) -> Self
277    where
278        S: Default,
279    {
280        for account in accounts {
281            self = self.add_account(account);
282        }
283
284        self
285    }
286
287    /// Add a single new [`Account`] to the swarm.
288    ///
289    /// Use [`Self::add_accounts`] to add multiple accounts at a time.
290    ///
291    /// This will make the state for this client be the default, use
292    /// [`Self::add_account_with_state`] to avoid that.
293    #[must_use]
294    pub fn add_account(self, account: Account) -> Self
295    where
296        S: Default,
297    {
298        self.add_account_with_state_and_opts(account, S::default(), JoinOpts::default())
299    }
300
301    /// Add an account with a custom initial state.
302    ///
303    /// Use just [`Self::add_account`] to use the `Default` implementation for
304    /// the state.
305    #[must_use]
306    pub fn add_account_with_state(self, account: Account, state: S) -> Self {
307        self.add_account_with_state_and_opts(account, state, JoinOpts::default())
308    }
309
310    /// Add an account with a custom initial state.
311    ///
312    /// Use just [`Self::add_account`] to use the `Default` implementation for
313    /// the state.
314    #[must_use]
315    pub fn add_account_with_opts(self, account: Account, opts: JoinOpts) -> Self
316    where
317        S: Default,
318    {
319        self.add_account_with_state_and_opts(account, S::default(), opts)
320    }
321
322    /// Same as [`Self::add_account_with_state`], but allow passing in custom
323    /// join options.
324    #[must_use]
325    pub fn add_account_with_state_and_opts(
326        mut self,
327        account: Account,
328        state: S,
329        join_opts: JoinOpts,
330    ) -> Self {
331        self.accounts.push((account, join_opts));
332        self.states.push(state);
333        self
334    }
335
336    /// Set the swarm state instead of initializing defaults.
337    #[must_use]
338    pub fn set_swarm_state(mut self, swarm_state: SS) -> Self {
339        self.swarm_state = swarm_state;
340        self
341    }
342
343    /// Add one or more plugins to this swarm.
344    ///
345    /// See [`Self::new_without_plugins`] to learn how to disable default
346    /// plugins.
347    #[must_use]
348    pub fn add_plugins<M>(mut self, plugins: impl Plugins<M>) -> Self {
349        self.app.add_plugins(plugins);
350        self
351    }
352
353    /// Set how long we should wait between each bot joining the server.
354    ///
355    /// By default, every bot will connect at the same time. If you set this
356    /// field, however, the bots will wait for the previous one to have
357    /// connected and *then* they'll wait the given duration.
358    #[must_use]
359    pub fn join_delay(mut self, delay: Duration) -> Self {
360        self.join_delay = Some(delay);
361        self
362    }
363
364    /// Configures the auto-reconnection behavior for our bots.
365    ///
366    /// If this is `Some`, then it'll set the default reconnection delay for our
367    /// bots (how long they'll wait after being kicked before they try
368    /// rejoining). if it's `None`, then auto-reconnecting will be disabled.
369    ///
370    /// If this function isn't called, then our clients will reconnect after
371    /// [`DEFAULT_RECONNECT_DELAY`].
372    #[must_use]
373    pub fn reconnect_after(mut self, delay: impl Into<Option<Duration>>) -> Self {
374        self.reconnect_after = delay.into();
375        self
376    }
377
378    /// Build this `SwarmBuilder` into an actual [`Swarm`] and join the given
379    /// server.
380    ///
381    /// The `address` argument can be a `&str`, [`ServerAddr`],
382    /// [`ResolvedAddr`], or anything else that implements [`ResolvableAddr`].
383    ///
384    /// [`ServerAddr`]: ../../azalea_protocol/address/struct.ServerAddr.html
385    /// [`ResolvedAddr`]: ../../azalea_protocol/address/struct.ResolvedAddr.html
386    /// [`ResolvableAddr`]: ../../azalea_protocol/address/trait.ResolvableAddr.html
387    pub async fn start(self, address: impl ResolvableAddr) -> AppExit {
388        self.start_with_opts(address, JoinOpts::default()).await
389    }
390
391    #[doc(hidden)]
392    #[deprecated = "renamed to `start_with_opts`."]
393    pub async fn start_with_default_opts(
394        self,
395        address: impl ResolvableAddr,
396        default_join_opts: JoinOpts,
397    ) -> AppExit {
398        self.start_with_opts(address, default_join_opts).await
399    }
400
401    /// Do the same as [`Self::start`], but allow passing in default join
402    /// options for the bots.
403    pub async fn start_with_opts(
404        mut self,
405        address: impl ResolvableAddr,
406        join_opts: JoinOpts,
407    ) -> AppExit {
408        assert_eq!(
409            self.accounts.len(),
410            self.states.len(),
411            "There must be exactly one state per bot."
412        );
413
414        debug!("Starting Azalea {}", env!("CARGO_PKG_VERSION"));
415
416        let address = if let Some(socket_addr) = join_opts.custom_socket_addr {
417            let server_addr = if let Some(server_addr) = join_opts
418                .custom_server_addr
419                .clone()
420                .or_else(|| address.clone().server_addr().ok())
421            {
422                server_addr
423            } else {
424                error!(
425                    "Failed to parse address: {address:?}. If this was expected, consider passing in a `ServerAddr` instead."
426                );
427                return AppExit::error();
428            };
429
430            ResolvedAddr {
431                server: server_addr,
432                socket: socket_addr,
433            }
434        } else {
435            let Ok(addr) = address.clone().resolve().await else {
436                error!(
437                    "Failed to resolve address: {address:?}. If this was expected, consider resolving the address earlier with `ResolvableAddr::resolve`."
438                );
439                return AppExit::error();
440            };
441            addr
442        };
443
444        let worlds = Arc::new(RwLock::new(Worlds::default()));
445
446        // we can't modify the swarm plugins after this
447        let (bots_tx, mut bots_rx) = mpsc::unbounded_channel();
448        let (swarm_tx, mut swarm_rx) = mpsc::unbounded_channel();
449
450        swarm_tx.send(SwarmEvent::Init).unwrap();
451
452        let main_schedule_label = self.app.update_schedule.unwrap();
453
454        let local_set = task::LocalSet::new();
455
456        local_set.run_until(async move {
457            // start_ecs_runner must be run inside of the LocalSet
458            let (ecs_lock, start_running_systems, appexit_rx) = start_ecs_runner(&mut self.app);
459
460            let swarm = Swarm {
461                ecs: ecs_lock.clone(),
462
463                address: Arc::new(RwLock::new(address)),
464                worlds,
465
466                bots_tx,
467
468                swarm_tx: swarm_tx.clone(),
469            };
470
471            // run the main schedule so the startup systems run
472            {
473                let mut ecs = ecs_lock.write();
474                ecs.insert_resource(TokioRuntimeHandle(tokio::runtime::Handle::current()));
475                ecs.insert_resource(swarm.clone());
476                ecs.insert_resource(self.swarm_state.clone());
477                if let Some(reconnect_after) = self.reconnect_after {
478                    ecs.insert_resource(AutoReconnectDelay {
479                        delay: reconnect_after,
480                    });
481                } else {
482                    ecs.remove_resource::<AutoReconnectDelay>();
483                }
484                ecs.run_schedule(main_schedule_label);
485                ecs.clear_trackers();
486            }
487
488            // only do this after we inserted the Swarm and state resources to avoid errors
489            // where Res<Swarm> is inaccessible
490            start_running_systems();
491
492            // SwarmBuilder (self) isn't Send so we have to take all the things we need out
493            // of it
494            let swarm_clone = swarm.clone();
495            let join_delay = self.join_delay;
496            let accounts = self.accounts.clone();
497            let states = self.states.clone();
498
499            task::spawn_local(async move {
500                if let Some(join_delay) = join_delay {
501                    // if there's a join delay, then join one by one
502                    for ((account, bot_join_opts), state) in accounts.iter().zip(states) {
503                        let mut join_opts = join_opts.clone();
504                        join_opts.update(bot_join_opts);
505                        let _ = swarm_clone.add_with_opts(account, state, &join_opts).await;
506                        tokio::time::sleep(join_delay).await;
507                    }
508                } else {
509                    // otherwise, join all at once
510                    let swarm_borrow = &swarm_clone;
511                    join_all(accounts.iter().zip(states).map(
512                        |((account, bot_join_opts), state)| async {
513                            let mut join_opts = join_opts.clone();
514                            join_opts.update(bot_join_opts);
515                            let _ = swarm_borrow
516                                .clone()
517                                .add_with_opts(account, state, &join_opts)
518                                .await;
519                        },
520                    ))
521                    .await;
522                }
523
524                swarm_tx.send(SwarmEvent::Login).unwrap();
525            });
526
527            let swarm_state = self.swarm_state;
528
529            // Watch swarm_rx and send those events to the swarm_handle.
530            let swarm_clone = swarm.clone();
531            let swarm_handler_task = task::spawn_local(async move {
532                while let Some(event) = swarm_rx.recv().await {
533                    if let Some(swarm_handler) = &self.swarm_handler {
534                        task::spawn_local((swarm_handler)(
535                            swarm_clone.clone(),
536                            event,
537                            swarm_state.clone(),
538                        ));
539                    }
540                }
541
542                unreachable!(
543                    "The `Swarm` here contains a sender for the `SwarmEvent`s, so swarm_rx.recv() will never fail"
544                );
545            });
546
547            // bot events
548            let client_handler_task = task::spawn_local(async move {
549                while let Some((Some(first_event), first_bot)) = bots_rx.recv().await {
550                    if bots_rx.len() > 1_000 {
551                        static WARNED: AtomicBool = AtomicBool::new(false);
552                        if !WARNED.swap(true, atomic::Ordering::Relaxed) {
553                            warn!("the Client Event channel has more than 1000 items!")
554                        }
555                    }
556
557                    if let Some(handler) = &self.handler {
558                        let ecs_mutex = first_bot.ecs.clone();
559                        let mut ecs = ecs_mutex.write();
560                        let mut query = ecs.query::<Option<&S>>();
561                        let Ok(Some(first_bot_state)) = query.get(&ecs, first_bot.entity) else {
562                            error!(
563                                "the first bot ({} / {}) is missing the required state component! none of the client handler functions will be called.",
564                                first_bot.username(),
565                                first_bot.entity
566                            );
567                            continue;
568                        };
569                        let first_bot_entity = first_bot.entity;
570                        let first_bot_state = first_bot_state.clone();
571
572                        task::spawn_local((handler)(first_bot, first_event, first_bot_state.clone()));
573
574                        // this makes it not have to keep locking the ecs
575                        let mut states = HashMap::new();
576                        states.insert(first_bot_entity, first_bot_state);
577                        while let Ok((Some(event), bot)) = bots_rx.try_recv() {
578                            let state = match states.entry(bot.entity) {
579                                hash_map::Entry::Occupied(e) => e.into_mut(),
580                                hash_map::Entry::Vacant(e) => {
581                                    let Ok(Some(state)) = query.get(&ecs, bot.entity) else {
582                                        error!(
583                                            "one of our bots ({} / {}) is missing the required state component! its client handler function will not be called.",
584                                            bot.username(),
585                                            bot.entity
586                                        );
587                                        continue;
588                                    };
589                                    let state = state.clone();
590                                    e.insert(state)
591                                }
592                            };
593                            task::spawn_local((handler)(bot, event, state.clone()));
594                        }
595                    }
596                }
597            });
598
599            let app_exit = appexit_rx
600                .await
601                .expect("appexit_tx shouldn't be dropped by the ECS runner before sending");
602
603            swarm_handler_task.abort();
604            client_handler_task.abort();
605
606            app_exit
607        }).await
608    }
609}
610
611impl Default for SwarmBuilder<NoState, NoSwarmState, (), ()> {
612    fn default() -> Self {
613        Self::new()
614    }
615}