Skip to main content

djs_gateway/
sharding.rs

1//! Creating the shards of a bot (D-141, D-145).
2
3use core::ops::Range;
4
5use djs_model::gateway::ShardId;
6
7use crate::{Config, Shard};
8
9/// Creates the shards numbered `range` of a bot that runs `total` shards.
10///
11/// Every shard gets a clone of `config`, so they all share its [IDENTIFY
12/// queue](crate::ConfigBuilder::identify_queue) and take turns identifying. Pass `0..total` to
13/// run every shard in this process, or a part of it to split the bot over several processes
14/// (each process then needs a queue shared with the others, see
15/// [`IdentifyQueue`](crate::IdentifyQueue)).
16///
17/// The shards do not connect until polled: run each one in its own task, calling
18/// [`Shard::next_event`] in a loop. Discord recommends a shard count in Get Gateway Bot
19/// (`shards`), together with the `max_concurrency` to create the queue with; Discord requires
20/// sharding from 2 500 guilds on.
21///
22/// discord.js counterpart: the `shardCount` and `shardIds` options of `WebSocketManager` from
23/// `@discordjs/ws`.
24///
25/// # Panics
26///
27/// Panics if `total` is `0` or `range` reaches past `total` (`range.end > total`).
28///
29/// # Examples
30///
31/// ```no_run
32/// use std::sync::Arc;
33///
34/// use djs_gateway::{Config, LocalIdentifyQueue, create_shards};
35/// use djs_model::gateway::{GatewayEvent, Intents};
36///
37/// # async fn run() {
38/// let token = std::env::var("DISCORD_TOKEN").unwrap();
39/// // `shards` and `max_concurrency` as returned by Get Gateway Bot.
40/// let (total, max_concurrency) = (16, 16);
41/// let config = Config::builder(token, Intents::GUILDS)
42///     .identify_queue(Arc::new(LocalIdentifyQueue::new(max_concurrency)))
43///     .build();
44///
45/// let mut tasks = Vec::new();
46/// for mut shard in create_shards(0..total, total, config) {
47///     tasks.push(tokio::spawn(async move {
48///         while let Some(event) = shard.next_event().await {
49///             match event {
50///                 Ok(GatewayEvent::Dispatch(_, event)) => println!("{}: {}", shard.id(), event.name()),
51///                 Ok(_) => {}
52///                 Err(error) if error.is_fatal() => break,
53///                 Err(error) => eprintln!("{}: {error}", shard.id()),
54///             }
55///         }
56///     }));
57/// }
58/// for task in tasks {
59///     task.await.unwrap();
60/// }
61/// # }
62/// ```
63#[track_caller]
64pub fn create_shards(
65    range: Range<u32>,
66    total: u32,
67    config: Config,
68) -> impl ExactSizeIterator<Item = Shard> + DoubleEndedIterator {
69    assert!(total > 0, "the shard total must not be zero");
70    assert!(
71        range.end <= total,
72        "shard range {range:?} reaches past the total of {total}"
73    );
74    range.map(move |number| Shard::with_config(ShardId::new(number, total), config.clone()))
75}