Skip to main content

ClusterManager

Struct ClusterManager 

Source
pub struct ClusterManager { /* private fields */ }
Expand description

Runs a bot’s shards in several processes of the same executable, shards_per_process shards each (D-296, D-297).

Cheap to clone (a reference count increment). Build it with ClusterManager::builder in the process that was not started by a manager (process returned None), then spawn it.

discord.js counterpart: ShardingManager (and discord-hybrid-sharding’s ClusterManager).

§Examples

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

let token = std::env::var("DISCORD_TOKEN")?;
match sharding::process()? {
    // A process started by the manager: an ordinary client, given its shards.
    Some(assignment) => {
        let client = Client::builder(token).cluster(assignment).build();
        client.on(Events::MessageCreate, |ctx, msg| async move {
            if msg.content == "!ping" {
                msg.reply(&ctx, "Pong!").await?;
            }
            Ok(())
        });
        client.login().await?;
    }
    // The first process: it starts one process per shard and waits for them.
    None => ClusterManager::builder(token).build().spawn().await?,
}

Implementations§

Source§

impl ClusterManager

Source

pub fn builder(token: impl Into<String>) -> ClusterManagerBuilder

Starts building a manager for the bot with token, which it uses only for one Get Gateway Bot request when it starts (D-305). The processes read their own token.

discord.js counterpart: new ShardingManager(file, { token }).

Source

pub fn spawn( &self, ) -> impl Future<Output = Result<(), ClusterError>> + Send + '_

Starts the cluster processes and runs until every one of them has stopped (after shutdown, or on its own without being restarted).

The manager first asks Discord for the gateway’s details once, for every process (Get Gateway Bot, D-305): the gateway URL, the recommended shard count (used with the default Shards::Auto, see ClusterManagerBuilder::shards), the session starts left (enough for every shard, or nothing is started) and max_concurrency. The shards are split into processes of shards_per_process each, numbered from cluster 0. Each process is the same executable with the same arguments (unless configured otherwise), its standard output and error shared with the manager’s and its standard input closed; it learns its shards and the gateway from the environment (process) and connects back to the manager over 127.0.0.1 with a secret token (D-285). A process the manager did not start cannot connect.

The manager is the IDENTIFY queue of every process (D-299): a shard asks it for a turn before identifying, and it grants one per rate-limit bucket (shard % max_concurrency) every 5 seconds over all the processes, so the shards start as fast as Discord allows and none is refused for identifying too fast.

A process that fails is started again with the same shards, after a delay that grows while it keeps failing (ClusterManagerBuilder::restart and restart_delay, D-306). spawn returns once every process has exited and none is waiting for a restart.

discord.js counterpart: ShardingManager#spawn (which returns once the shards are started).

§Errors

ClusterError::Rest if Get Gateway Bot fails, ClusterError::SessionStartLimit if too few session starts are left for the shards, ClusterError::Io if the manager cannot listen or start the first processes (a restart that cannot start is tried again after the next delay), ClusterError::AlreadyRunning if the manager is already running.

Source

pub fn shutdown(&self)

Asks every cluster to shut down; spawn returns once they have exited. Processes still running after the shutdown_timeout are killed. Has no effect when the manager is not running.

discord.js counterpart: none (discord.js kills the shards with Shard#kill).

Source

pub fn events(&self) -> ClusterEvents

Returns a stream of the manager’s events: processes started, connected and exited.

discord.js counterpart: ShardingManager#on('shardCreate') and the Shard events.

Source

pub fn clusters(&self) -> Vec<Cluster>

The clusters of the current spawn (empty before it).

discord.js counterpart: ShardingManager#shards.

Source

pub async fn broadcast<C: ClusterCommand>( &self, input: C::Input, ) -> Result<Vec<ClusterReply<C::Output>>, ClusterError>

Sends the command C to every cluster and returns each one’s result, by cluster ID (D-307–D-309). A cluster that is not connected (down, restarting, or the manager is not running), does not handle C, fails or does not answer within the command_timeout has an error in its ClusterReply; the others still have their results.

discord.js counterpart: ShardingManager#broadcastEval.

§Errors

ClusterError::Encoding if input cannot be converted to JSON.

§Examples
use djs_rs::sharding::{ClusterCommand, ClusterManager};

struct GuildCount;

impl ClusterCommand for GuildCount {
    const NAME: &'static str = "guild_count";
    type Input = ();
    type Output = usize;
}

let total: usize = manager
    .broadcast::<GuildCount>(())
    .await?
    .into_iter()
    .filter_map(|reply| reply.result.ok())
    .sum();
println!("{total} guilds");
Source

pub async fn stats( &self, ) -> Result<Vec<ClusterReply<ClusterStats>>, ClusterError>

Asks every cluster for its ClusterStats (D-310): the built-in Stats command, broadcast.

discord.js counterpart: ShardingManager#fetchClientValues.

§Errors

None for now: a cluster that does not answer has an error in its ClusterReply.

Source

pub async fn send<C: ClusterCommand>( &self, cluster: u32, input: C::Input, ) -> Result<C::Output, ClusterError>

Sends the command C to cluster cluster and returns its result.

discord.js counterpart: broadcastEval with the shard option.

§Errors

ClusterError::NotConnected if the cluster is not connected (or does not exist), ClusterError::UnknownCommand if it does not handle C, ClusterError::CommandFailed if its handler fails, ClusterError::Timeout if it does not answer in time, ClusterError::Encoding if the input or output cannot be converted.

Trait Implementations§

Source§

impl Clone for ClusterManager

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for ClusterManager

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

§

impl<T> Classify for T

§

type Classified = T

§

fn classify(self) -> T

Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
§

impl<T> Declassify for T

§

type Declassified = T

§

fn declassify(self) -> T

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided [Span], returning an Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
§

impl<T> Pointable for T

§

const ALIGN: usize

The alignment of pointer.
§

type Init = T

The type for initializers.
§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a [WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a [WithDispatch] wrapper. Read more