Skip to main content

Module sharding

Module sharding 

Source
Expand description

Multi-process sharding (D-284): a ClusterManager runs a bot’s shards in several processes of the same executable (D-296), shards_per_process shards each (D-297).

Behind the sharding feature. The bot has one entry point (D-300): process tells a process the manager started (it gets its ClusterAssignment, given to ClientBuilder::cluster) from the first process, which builds the manager.

use djs_rs::{prelude::*, sharding::{self, ClusterManager}};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let token = std::env::var("DISCORD_TOKEN")?;
    match sharding::process()? {
        Some(assignment) => {
            let client = Client::builder(token)
                .intents(Intents::GUILDS)
                .cluster(assignment)
                .build();
            client.on(Events::ClientReady, |ctx, _| async move {
                println!("shard {} is ready", ctx.shard_id());
                Ok(())
            });
            client.login().await?;
        }
        None => {
            let manager = ClusterManager::builder(token).shards_per_process(2).build();
            manager.spawn().await?;
        }
    }
    Ok(())
}

§How the processes talk

Each process connects back to the manager over TCP on 127.0.0.1, with frames of a length and JSON, and presents a secret token the manager put in its environment (D-285): a process the manager did not start cannot connect. The bot keeps its standard output. When the manager asks a process to stop, or the manager goes away, the process’s client shuts down and Client::login returns.

The manager asks Discord for the gateway’s details once and passes them to the processes (D-305), and it is their IDENTIFY queue (D-299): shards in different processes never identify faster than Discord’s max_concurrency allows.

§Commands between clusters

Rust cannot evaluate code sent at run time, so instead of discord.js’s broadcastEval a bot declares commands (D-286, D-308): a type implementing ClusterCommand names one and gives its input and output types; a cluster handles it with ClusterClient::handle (from Client::cluster), and the manager or any cluster sends it to every cluster (ClusterManager::broadcast, ClusterClient::broadcast) or to one (send), through the manager (D-307). A broadcast returns a ClusterReply per cluster (D-309), so a cluster that is down or restarting does not spoil the others’ results.

Each process has its own REST client, so the REST rate limits are not shared between processes (D-302): what goes over Discord’s limits ends in a 429, which the client waits out and retries.

discord.js counterpart: ShardingManager, Shard and ShardClientUtil; the names follow discord-hybrid-sharding’s clusters (D-301).

Structs§

Cluster
One cluster process as the manager last saw it: its ID, shards and process. Returned by ClusterManager::clusters.
ClusterAssignment
What the manager assigned to this process: its cluster ID and shards, the gateway to connect to, and how to reach the manager. Returned by process in a process the manager started, and given to ClientBuilder::cluster.
ClusterClient
A cluster process’s view of its cluster: its assignment, the commands it handles and the requests it sends to the other clusters (D-301, D-307). Returned by Client::cluster for a client built with ClientBuilder::cluster.
ClusterEvents
The stream of a ClusterManager’s events. Created by ClusterManager::events.
ClusterManager
Runs a bot’s shards in several processes of the same executable, shards_per_process shards each (D-296, D-297).
ClusterManagerBuilder
Configures a ClusterManager. Created by ClusterManager::builder.
ClusterReply
One cluster’s answer to a broadcast (D-309): its ID and its result, or why it gave none.
ClusterStats
What a cluster reports about itself (D-310). Returned by stats().
ShardStats
One shard of a ClusterStats.
Stats
The built-in command that returns a cluster’s ClusterStats; every cluster process handles it. ClusterManager::stats and ClusterClient::stats broadcast it; send::<Stats>(id, ()) asks one cluster.

Enums§

ClusterError
An error of multi-process sharding.
ClusterEvent
An event of a ClusterManager: see ClusterManager::events.
Restart
Which exits of a cluster process make the manager restart it (D-306): see ClusterManagerBuilder::restart. A process stopped by ClusterManager::shutdown is never restarted.
ShardStatus
The connection state of a shard in a ShardStats: its ShardState, which crosses the processes.

Traits§

ClusterCommand
A command that clusters handle by name, with typed input and output (D-286, D-308): the typed replacement for discord.js’s broadcastEval, which Rust cannot do (there is no code to evaluate at run time).

Functions§

process
Tells whether this process was started by a ClusterManager (D-300): its assignment (cluster ID, shards, the way to the manager) if it was, None in the first process.