djs_rs/sharding/cluster_client.rs
1//! The cluster side of a [`Client`]: [`ClusterClient`] (D-301, D-307, D-308).
2
3use core::{fmt, future::Future, ops::Range};
4use std::time::Instant;
5
6use djs_cache::{Backend, DashMapBackend};
7use serde_json::Value;
8
9use super::{
10 ClusterAssignment, ClusterCommand, ClusterError, ClusterReply, ClusterStats, Stats,
11 command::{BoxFuture, Commands, Failure, decode_one, decode_replies, encode, erase},
12 stats::resident_memory,
13};
14use crate::{Client, HandlerError};
15
16/// A cluster process's view of its cluster: its assignment, the commands it handles and the
17/// requests it sends to the other clusters (D-301, D-307). Returned by
18/// [`Client::cluster`] for a client built with
19/// [`ClientBuilder::cluster`](crate::ClientBuilder::cluster).
20///
21/// Cheap to clone (a [`Client`] clone). Requests go through the manager, so they need the
22/// client to be logged in; handlers can be registered at any time.
23///
24/// discord.js counterpart: `ShardClientUtil` (`client.shard`), and discord-hybrid-sharding's
25/// `ClusterClient`.
26///
27/// # Examples
28///
29/// ```no_run
30/// use djs_rs::{
31/// prelude::*,
32/// sharding::{self, ClusterCommand},
33/// };
34///
35/// /// How many guilds a cluster has in its cache.
36/// struct GuildCount;
37///
38/// impl ClusterCommand for GuildCount {
39/// const NAME: &'static str = "guild_count";
40/// type Input = ();
41/// type Output = usize;
42/// }
43///
44/// # async fn run(token: String) -> Result<(), Box<dyn std::error::Error>> {
45/// let assignment = sharding::process()?.expect("started by a ClusterManager");
46/// let client = Client::builder(token)
47/// .intents(Intents::GUILDS | Intents::GUILD_MESSAGES | Intents::MESSAGE_CONTENT)
48/// .cluster(assignment)
49/// .build();
50/// let cluster = client.cluster().expect("built with `cluster`");
51/// cluster.handle::<GuildCount, _, _>(|client, ()| async move {
52/// Ok(client.cache().map_or(0, |cache| cache.guilds().len()))
53/// });
54/// client.on(Events::MessageCreate, move |ctx, msg| {
55/// let cluster = cluster.clone();
56/// async move {
57/// if msg.content == "!guilds" {
58/// let total: usize = cluster
59/// .broadcast::<GuildCount>(())
60/// .await?
61/// .into_iter()
62/// .filter_map(|reply| reply.result.ok())
63/// .sum();
64/// msg.reply(&ctx, format!("{total} guilds")).await?;
65/// }
66/// Ok(())
67/// }
68/// });
69/// client.login().await?;
70/// # Ok(())
71/// # }
72/// ```
73pub struct ClusterClient<B: Backend = DashMapBackend> {
74 client: Client<B>,
75}
76
77impl<B: Backend> ClusterClient<B> {
78 pub(crate) const fn new(client: Client<B>) -> Self {
79 Self { client }
80 }
81
82 fn assignment(&self) -> &ClusterAssignment {
83 self.client
84 .assignment()
85 .expect("a cluster client is only made for a cluster process")
86 }
87
88 /// This process's cluster ID.
89 ///
90 /// discord.js counterpart: `ShardClientUtil#ids` (the shards there).
91 #[must_use]
92 pub fn id(&self) -> u32 {
93 self.assignment().cluster_id()
94 }
95
96 /// The shards this process runs.
97 ///
98 /// discord.js counterpart: `ShardClientUtil#ids`.
99 #[must_use]
100 pub fn shards(&self) -> Range<u32> {
101 self.assignment().shards()
102 }
103
104 /// The bot's shard count, over every process.
105 ///
106 /// discord.js counterpart: `ShardClientUtil#count`.
107 #[must_use]
108 pub fn total_shards(&self) -> u32 {
109 self.assignment().total_shards()
110 }
111
112 /// Handles the command `C` in this cluster (D-308): `handler` gets a [`Client`] clone and
113 /// the sender's input, and returns the output or an error (sent back as text, a
114 /// [`ClusterError::CommandFailed`]). Replaces an earlier handler of the same command.
115 /// Each request runs in its own task, so a slow handler holds up nothing else; a
116 /// handler that panics is reported as failed.
117 ///
118 /// discord.js counterpart: the function given to `broadcastEval`, which runs in every
119 /// shard.
120 pub fn handle<C, F, Fut>(&self, handler: F) -> &Self
121 where
122 C: ClusterCommand,
123 F: Fn(Client<B>, C::Input) -> Fut + Send + Sync + 'static,
124 Fut: Future<Output = Result<C::Output, HandlerError>> + Send + 'static,
125 {
126 self.client
127 .add_cluster_command(C::NAME, erase::<C, _, _, _>(handler));
128 self
129 }
130
131 /// Sends the command `C` to every cluster, this one included, and returns each one's
132 /// result by cluster ID (D-309); see [`ClusterManager::broadcast`](super::ClusterManager::broadcast).
133 ///
134 /// discord.js counterpart: `ShardClientUtil#broadcastEval`.
135 ///
136 /// # Errors
137 ///
138 /// [`ClusterError::NotConnected`] if this process is not connected to its manager (the
139 /// client is not logged in), [`ClusterError::Encoding`] if `input` cannot be converted
140 /// to JSON.
141 pub async fn broadcast<C: ClusterCommand>(
142 &self,
143 input: C::Input,
144 ) -> Result<Vec<ClusterReply<C::Output>>, ClusterError> {
145 let link = self.client.link().ok_or(ClusterError::NotConnected)?;
146 let input = encode(&input)?;
147 Ok(decode_replies(link.ask(None, C::NAME, input).await?))
148 }
149
150 /// Sends the command `C` to cluster `cluster` (this one too) and returns its result.
151 ///
152 /// discord.js counterpart: `ShardClientUtil#broadcastEval` with the `shard` option.
153 ///
154 /// # Errors
155 ///
156 /// As [`ClusterManager::send`](super::ClusterManager::send), and
157 /// [`ClusterError::NotConnected`] if this process is not connected to its manager.
158 pub async fn send<C: ClusterCommand>(
159 &self,
160 cluster: u32,
161 input: C::Input,
162 ) -> Result<C::Output, ClusterError> {
163 let link = self.client.link().ok_or(ClusterError::NotConnected)?;
164 let input = encode(&input)?;
165 decode_one(link.ask(Some(cluster), C::NAME, input).await?)
166 }
167
168 /// Asks every cluster, this one included, for its [`ClusterStats`] (D-310): the built-in
169 /// [`Stats`] command, broadcast.
170 ///
171 /// discord.js counterpart: `ShardClientUtil#fetchClientValues`.
172 ///
173 /// # Errors
174 ///
175 /// [`ClusterError::NotConnected`] if this process is not connected to its manager.
176 ///
177 /// # Examples
178 ///
179 /// ```no_run
180 /// # async fn run(cluster: djs_rs::sharding::ClusterClient) -> Result<(), djs_rs::sharding::ClusterError> {
181 /// let guilds: u64 = cluster
182 /// .stats()
183 /// .await?
184 /// .into_iter()
185 /// .filter_map(|reply| reply.result.ok()?.guilds)
186 /// .sum();
187 /// println!("{guilds} guilds over every cluster");
188 /// # Ok(())
189 /// # }
190 /// ```
191 pub async fn stats(&self) -> Result<Vec<ClusterReply<ClusterStats>>, ClusterError> {
192 self.broadcast::<Stats>(()).await
193 }
194}
195
196impl<B: Backend> Clone for ClusterClient<B> {
197 fn clone(&self) -> Self {
198 Self {
199 client: self.client.clone(),
200 }
201 }
202}
203
204impl<B: Backend> fmt::Debug for ClusterClient<B> {
205 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
206 f.debug_struct("ClusterClient")
207 .field("assignment", self.assignment())
208 .finish_non_exhaustive()
209 }
210}
211
212/// The commands a cluster's connection runs: the built-in [`Stats`], then the client's
213/// handlers.
214pub(crate) struct Table<B: Backend> {
215 pub(crate) client: Client<B>,
216 /// When the client logged in.
217 pub(crate) started: Instant,
218}
219
220impl<B: Backend> Table<B> {
221 fn stats(&self) -> ClusterStats {
222 let client = &self.client;
223 let cache = client.cache();
224 ClusterStats {
225 cluster: client.assignment().map_or(0, ClusterAssignment::cluster_id),
226 shards: client.shard_stats(),
227 guilds: cache.map(|cache| cache.guilds().len() as u64),
228 users: cache.map(|cache| cache.users().len() as u64),
229 uptime: self.started.elapsed(),
230 memory: resident_memory(),
231 }
232 }
233}
234
235impl<B: Backend> Commands for Table<B> {
236 fn call(&self, name: &str, input: Value) -> BoxFuture<'static, Result<Value, Failure>> {
237 if name == Stats::NAME {
238 let stats = serde_json::to_value(self.stats()).map_err(|error| Failure::Encoding {
239 message: error.to_string(),
240 });
241 return Box::pin(async move { stats });
242 }
243 match self.client.cluster_command(name) {
244 Some(handler) => handler(self.client.clone(), input),
245 None => Box::pin(async { Err(Failure::UnknownCommand) }),
246 }
247 }
248}