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
impl ClusterManager
Sourcepub fn builder(token: impl Into<String>) -> ClusterManagerBuilder
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 }).
Sourcepub fn spawn(
&self,
) -> impl Future<Output = Result<(), ClusterError>> + Send + '_
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.
Sourcepub fn shutdown(&self)
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).
Sourcepub fn events(&self) -> ClusterEvents
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.
Sourcepub fn clusters(&self) -> Vec<Cluster>
pub fn clusters(&self) -> Vec<Cluster>
The clusters of the current spawn (empty before it).
discord.js counterpart: ShardingManager#shards.
Sourcepub async fn broadcast<C: ClusterCommand>(
&self,
input: C::Input,
) -> Result<Vec<ClusterReply<C::Output>>, ClusterError>
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");Sourcepub async fn stats(
&self,
) -> Result<Vec<ClusterReply<ClusterStats>>, ClusterError>
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.
Sourcepub async fn send<C: ClusterCommand>(
&self,
cluster: u32,
input: C::Input,
) -> Result<C::Output, ClusterError>
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
impl Clone for ClusterManager
Auto Trait Implementations§
impl !RefUnwindSafe for ClusterManager
impl !UnwindSafe for ClusterManager
impl Freeze for ClusterManager
impl Send for ClusterManager
impl Sync for ClusterManager
impl Unpin for ClusterManager
impl UnsafeUnpin for ClusterManager
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
§impl<T> Classify for T
impl<T> Classify for T
type Classified = T
fn classify(self) -> T
Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
§impl<T> Declassify for T
impl<T> Declassify for T
type Declassified = T
fn declassify(self) -> T
§impl<T> Instrument for T
impl<T> Instrument for T
§fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
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 moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
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