djs_rs/sharding/mod.rs
1//! Multi-process sharding (D-284): a [`ClusterManager`] runs a bot's shards in several
2//! processes of the same executable (D-296), `shards_per_process` shards each (D-297).
3//!
4//! Behind the `sharding` feature. The bot has one entry point (D-300): [`process`] tells a
5//! process the manager started (it gets its [`ClusterAssignment`], given to
6//! [`ClientBuilder::cluster`](crate::ClientBuilder::cluster)) from the first process, which
7//! builds the manager.
8//!
9//! ```no_run
10//! use djs_rs::{prelude::*, sharding::{self, ClusterManager}};
11//!
12//! #[tokio::main]
13//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
14//! let token = std::env::var("DISCORD_TOKEN")?;
15//! match sharding::process()? {
16//! Some(assignment) => {
17//! let client = Client::builder(token)
18//! .intents(Intents::GUILDS)
19//! .cluster(assignment)
20//! .build();
21//! client.on(Events::ClientReady, |ctx, _| async move {
22//! println!("shard {} is ready", ctx.shard_id());
23//! Ok(())
24//! });
25//! client.login().await?;
26//! }
27//! None => {
28//! let manager = ClusterManager::builder(token).shards_per_process(2).build();
29//! manager.spawn().await?;
30//! }
31//! }
32//! Ok(())
33//! }
34//! ```
35//!
36//! # How the processes talk
37//!
38//! Each process connects back to the manager over TCP on `127.0.0.1`, with frames of a
39//! length and JSON, and presents a secret token the manager put in its environment (D-285):
40//! a process the manager did not start cannot connect. The bot keeps its standard output.
41//! When the manager asks a process to stop, or the manager goes away, the process's client
42//! shuts down and [`Client::login`](crate::Client::login) returns.
43//!
44//! The manager asks Discord for the gateway's details once and passes them to the
45//! processes (D-305), and it is their IDENTIFY queue (D-299): shards in different processes
46//! never identify faster than Discord's `max_concurrency` allows.
47//!
48//! # Commands between clusters
49//!
50//! Rust cannot evaluate code sent at run time, so instead of discord.js's `broadcastEval`
51//! a bot declares commands (D-286, D-308): a type implementing [`ClusterCommand`] names one
52//! and gives its input and output types; a cluster handles it with
53//! [`ClusterClient::handle`] (from [`Client::cluster`](crate::Client::cluster)), and the
54//! manager or any cluster sends it to every cluster ([`ClusterManager::broadcast`],
55//! [`ClusterClient::broadcast`]) or to one (`send`), through the manager (D-307). A
56//! broadcast returns a [`ClusterReply`] per cluster (D-309), so a cluster that is down or
57//! restarting does not spoil the others' results.
58//!
59//! Each process has its own REST client, so the REST rate limits are not shared between
60//! processes (D-302): what goes over Discord's limits ends in a 429, which the client waits
61//! out and retries.
62//!
63//! discord.js counterpart: `ShardingManager`, `Shard` and `ShardClientUtil`; the names follow
64//! discord-hybrid-sharding's clusters (D-301).
65
66mod cluster;
67mod cluster_client;
68mod command;
69mod ipc;
70mod manager;
71mod stats;
72
73use std::sync::{Mutex, MutexGuard, PoisonError};
74
75pub use self::{
76 cluster::ClusterAssignment,
77 cluster_client::ClusterClient,
78 command::{ClusterCommand, ClusterReply},
79 manager::{
80 Cluster, ClusterEvent, ClusterEvents, ClusterManager, ClusterManagerBuilder, Restart,
81 },
82 stats::{ClusterStats, ShardStats, ShardStatus, Stats},
83};
84pub(crate) use self::{
85 cluster::{Connection, Link},
86 cluster_client::Table,
87 command::Handler,
88 stats::{Reporter, ShardSlot},
89};
90
91/// Tells whether this process was started by a [`ClusterManager`] (D-300): its assignment
92/// (cluster ID, shards, the way to the manager) if it was, `None` in the first process.
93///
94/// The assignment comes from an environment variable the manager sets; it is checked
95/// (shards within the total, the manager on a loopback address) but nothing is connected
96/// yet: the client connects when it logs in.
97///
98/// discord.js counterpart: the environment `ShardClientUtil` reads.
99///
100/// # Errors
101///
102/// [`ClusterError::Assignment`] if the variable is set but is not a valid assignment.
103pub fn process() -> Result<Option<ClusterAssignment>, ClusterError> {
104 ClusterAssignment::from_env()
105}
106
107/// Locks `mutex`, ignoring poisoning: nothing is left half-updated by a panic here.
108fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
109 mutex.lock().unwrap_or_else(PoisonError::into_inner)
110}
111
112/// An error of multi-process sharding.
113///
114/// discord.js counterpart: none (discord.js rejects with plain `Error`s).
115#[derive(Debug, thiserror::Error)]
116#[non_exhaustive]
117pub enum ClusterError {
118 /// The manager could not ask Discord for the gateway's details (Get Gateway Bot, D-305).
119 #[error("could not fetch the gateway's details")]
120 Rest(#[from] djs_rest::Error),
121 /// Discord's daily [session start limit] does not allow starting every shard; no process
122 /// was started.
123 ///
124 /// [session start limit]: https://docs.discord.com/developers/events/gateway#session-start-limit-object
125 #[error(
126 "not enough session starts left to start {required} shards ({remaining} remaining, \
127 reset in {reset_after:?})"
128 )]
129 SessionStartLimit {
130 /// The number of shards to start.
131 required: u32,
132 /// The session starts left until the reset.
133 remaining: u32,
134 /// The time until the limit resets.
135 reset_after: core::time::Duration,
136 },
137 /// Listening, connecting or starting a process failed.
138 #[error("a cluster process or connection failed")]
139 Io(#[source] std::io::Error),
140 /// The assignment in the environment is not valid.
141 #[error("the cluster assignment in the environment is not valid")]
142 Assignment,
143 /// The manager did not accept this process (a wrong token, an unknown or already
144 /// connected cluster, or no answer in time).
145 #[error("the cluster manager refused this process")]
146 Refused,
147 /// The manager is already running.
148 #[error("the cluster manager is already running")]
149 AlreadyRunning,
150 /// The cluster is not connected: it is down, restarting or does not exist; or, from a
151 /// cluster process, this process is not connected to its manager (not logged in).
152 #[error("the cluster is not connected")]
153 NotConnected,
154 /// The cluster has no handler for the command
155 /// ([`ClusterClient::handle`]).
156 #[error("the cluster does not handle this command")]
157 UnknownCommand,
158 /// The cluster's handler returned an error, given here as text.
159 #[error("the command failed: {0}")]
160 CommandFailed(String),
161 /// The cluster did not answer within the manager's
162 /// [`command_timeout`](ClusterManagerBuilder::command_timeout).
163 #[error("the cluster did not answer in time")]
164 Timeout,
165 /// A command's input or output could not be converted to or from JSON (as text).
166 #[error("could not encode or decode a command: {0}")]
167 Encoding(String),
168}