Skip to main content

djs_rs/sharding/
cluster.rs

1//! The side of a cluster process: what the manager assigned it (D-296, D-300, D-305), its
2//! connection to the manager and the IDENTIFY queue that goes through it (D-299).
3
4use core::{fmt, future::Future, ops::Range, pin::Pin, time::Duration};
5use std::{
6    collections::{HashMap, VecDeque},
7    net::SocketAddr,
8    sync::{
9        Arc, Mutex,
10        atomic::{AtomicU64, Ordering},
11    },
12};
13
14use djs_gateway::IdentifyQueue;
15use djs_model::gateway::ShardId;
16use serde::{Deserialize, Serialize};
17use serde_json::Value;
18use tokio::{
19    net::TcpStream,
20    sync::{mpsc, oneshot},
21    task::JoinHandle,
22};
23
24use super::{
25    ClusterError,
26    command::{Commands, Failure, Replies},
27    ipc::{TOO_LARGE, ToCluster, ToManager, read_frame, too_large, write_frame},
28    lock,
29};
30use crate::context::Shared;
31
32/// The environment variable that carries a process's assignment (D-296).
33pub(crate) const CLUSTER_ENV: &str = "DJS_RS_CLUSTER";
34
35/// How long a process waits for the manager to accept it.
36const HELLO_TIMEOUT: Duration = Duration::from_secs(30);
37
38/// What the manager assigned to this process: its cluster ID and shards, the gateway to
39/// connect to, and how to reach the manager. Returned by [`process`](super::process) in a
40/// process the manager started, and given to
41/// [`ClientBuilder::cluster`](crate::ClientBuilder::cluster).
42///
43/// discord.js counterpart: what `ShardClientUtil` reads from the environment (`SHARDS`,
44/// `SHARD_COUNT`).
45#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
46pub struct ClusterAssignment {
47    cluster: u32,
48    shards: Range<u32>,
49    total: u32,
50    gateway_url: String,
51    max_concurrency: u32,
52    address: SocketAddr,
53    token: String,
54}
55
56impl ClusterAssignment {
57    pub(crate) fn new(
58        cluster: u32,
59        shards: Range<u32>,
60        gateway: &Gateway,
61        address: SocketAddr,
62        token: String,
63    ) -> Self {
64        Self {
65            cluster,
66            shards,
67            total: gateway.total,
68            gateway_url: gateway.url.clone(),
69            max_concurrency: gateway.max_concurrency,
70            address,
71            token,
72        }
73    }
74
75    /// This process's cluster ID (from 0).
76    ///
77    /// discord.js counterpart: `ShardClientUtil#ids` (one shard per process in discord.js).
78    #[must_use]
79    pub const fn cluster_id(&self) -> u32 {
80        self.cluster
81    }
82
83    /// The shards this process runs.
84    ///
85    /// discord.js counterpart: `ShardClientUtil#ids`.
86    #[must_use]
87    pub fn shards(&self) -> Range<u32> {
88        self.shards.clone()
89    }
90
91    /// The bot's shard count, over every process.
92    ///
93    /// discord.js counterpart: `ShardClientUtil#count`.
94    #[must_use]
95    pub const fn total_shards(&self) -> u32 {
96        self.total
97    }
98
99    /// The gateway URL the manager got from Discord (D-305).
100    pub(crate) fn gateway_url(&self) -> &str {
101        &self.gateway_url
102    }
103
104    /// The bot's `max_concurrency`, which the manager got from Discord (D-305).
105    pub(crate) const fn max_concurrency(&self) -> u32 {
106        self.max_concurrency
107    }
108
109    /// Reads the assignment from the environment: `Ok(None)` when the variable is absent.
110    pub(crate) fn from_env() -> Result<Option<Self>, ClusterError> {
111        match std::env::var_os(CLUSTER_ENV) {
112            Some(value) => value
113                .into_string()
114                .map_err(|_| ClusterError::Assignment)
115                .and_then(|value| Self::parse(&value))
116                .map(Some),
117            None => Ok(None),
118        }
119    }
120
121    /// Parses and checks the value of [`CLUSTER_ENV`].
122    fn parse(value: &str) -> Result<Self, ClusterError> {
123        let assignment: Self = serde_json::from_str(value).map_err(|_| ClusterError::Assignment)?;
124        let valid = assignment.shards.start < assignment.shards.end
125            && assignment.shards.end <= assignment.total
126            && assignment.max_concurrency > 0
127            && assignment.address.ip().is_loopback();
128        if valid {
129            Ok(assignment)
130        } else {
131            Err(ClusterError::Assignment)
132        }
133    }
134
135    pub(crate) fn to_env(&self) -> String {
136        serde_json::to_string(self).expect("an assignment always serializes")
137    }
138
139    /// Connects to the manager and introduces this process; then keeps the connection: a
140    /// shutdown asked by the manager, or the manager going away, shuts the client down. The
141    /// connection carries the shards' IDENTIFY requests ([`Connection::identify_queue`]),
142    /// runs the commands the manager sends with `commands`, and carries this process's own
143    /// requests ([`Link`], in `shared`).
144    pub(crate) async fn connect(
145        &self,
146        shared: Arc<Shared>,
147        commands: Arc<dyn Commands>,
148    ) -> Result<Connection, ClusterError> {
149        let stream = TcpStream::connect(self.address)
150            .await
151            .map_err(ClusterError::Io)?;
152        stream.set_nodelay(true).map_err(ClusterError::Io)?;
153        let (mut reader, mut writer) = stream.into_split();
154        let hello = ToManager::Hello {
155            cluster: self.cluster,
156            token: self.token.clone(),
157        };
158        write_frame(&mut writer, &hello)
159            .await
160            .map_err(ClusterError::Io)?;
161        match tokio::time::timeout(HELLO_TIMEOUT, read_frame(&mut reader)).await {
162            Ok(Ok(Some(ToCluster::Welcome))) => {}
163            Ok(Err(error)) => return Err(ClusterError::Io(error)),
164            Ok(Ok(_)) | Err(_) => return Err(ClusterError::Refused),
165        }
166
167        let (requests, mut outgoing) = mpsc::unbounded_channel();
168        let queue = Arc::new(ManagerQueue {
169            requests: requests.clone(),
170            waiting: Mutex::default(),
171        });
172        let link = Arc::new(Link {
173            requests,
174            next: AtomicU64::new(0),
175            pending: Mutex::default(),
176        });
177        *lock(&shared.link) = Some(Arc::clone(&link));
178        // Open until the connection is dropped: the manager then sees its end.
179        let writing = tokio::spawn({
180            let link = Arc::clone(&link);
181            async move {
182                while let Some(message) = outgoing.recv().await {
183                    match write_frame(&mut writer, &message).await {
184                        Ok(()) => {}
185                        // Nothing was written: answer for the message instead, and go on.
186                        Err(error) if too_large(&error) => {
187                            let Some(instead) = link.too_large(&message) else {
188                                continue;
189                            };
190                            if write_frame(&mut writer, &instead).await.is_err() {
191                                break;
192                            }
193                        }
194                        Err(_) => break,
195                    }
196                }
197            }
198        });
199        let cluster = self.cluster;
200        let granted = Arc::clone(&queue);
201        let (connected, reader_link) = (Arc::clone(&shared), Arc::clone(&link));
202        let reading = tokio::spawn(async move {
203            let (shared, link) = (connected, reader_link);
204            loop {
205                match read_frame::<_, ToCluster>(&mut reader).await {
206                    Ok(Some(ToCluster::Identify { shard })) => granted.grant(shard),
207                    Ok(Some(ToCluster::Request { id, command, input })) => {
208                        link.run(id, commands.call(&command, input));
209                    }
210                    Ok(Some(ToCluster::Replies { id, replies })) => link.replied(id, replies),
211                    Ok(Some(ToCluster::Shutdown)) => {
212                        tracing::info!(cluster, "the cluster manager asked to shut down");
213                        break;
214                    }
215                    Ok(Some(ToCluster::Welcome)) => {}
216                    Ok(None) | Err(_) => {
217                        tracing::warn!(cluster, "lost the connection to the cluster manager");
218                        break;
219                    }
220                }
221            }
222            disconnect(&shared, &link);
223            shared.shutdown.send_replace(true);
224        });
225        Ok(Connection {
226            queue,
227            shared,
228            link,
229            reading,
230            writing,
231        })
232    }
233}
234
235/// Forgets `link`: its requests still waiting fail with [`ClusterError::NotConnected`].
236fn disconnect(shared: &Shared, link: &Arc<Link>) {
237    let mut current = lock(&shared.link);
238    if current
239        .as_ref()
240        .is_some_and(|current| Arc::ptr_eq(current, link))
241    {
242        *current = None;
243    }
244    drop(current);
245    lock(&link.pending).clear();
246}
247
248impl fmt::Debug for ClusterAssignment {
249    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
250        f.debug_struct("ClusterAssignment")
251            .field("cluster", &self.cluster)
252            .field("shards", &self.shards)
253            .field("total", &self.total)
254            .field("gateway_url", &self.gateway_url)
255            .field("max_concurrency", &self.max_concurrency)
256            .field("address", &self.address)
257            .finish_non_exhaustive()
258    }
259}
260
261/// What the manager learned from Get Gateway Bot and passes to every process (D-305).
262#[derive(Clone, Debug, PartialEq, Eq)]
263pub(crate) struct Gateway {
264    pub(crate) url: String,
265    pub(crate) total: u32,
266    pub(crate) max_concurrency: u32,
267}
268
269/// A process's open connection to its manager; closed when dropped.
270#[derive(Debug)]
271pub(crate) struct Connection {
272    queue: Arc<ManagerQueue>,
273    shared: Arc<Shared>,
274    link: Arc<Link>,
275    reading: JoinHandle<()>,
276    writing: JoinHandle<()>,
277}
278
279impl Connection {
280    /// The IDENTIFY queue of this process's shards: every turn comes from the manager.
281    pub(crate) fn identify_queue(&self) -> Arc<dyn IdentifyQueue> {
282        Arc::clone(&self.queue) as Arc<dyn IdentifyQueue>
283    }
284}
285
286impl Drop for Connection {
287    fn drop(&mut self) {
288        self.reading.abort();
289        self.writing.abort();
290        // The requests still waiting fail instead of waiting forever.
291        disconnect(&self.shared, &self.link);
292    }
293}
294
295/// A cluster process's requests to the other clusters, through its manager (D-307).
296#[derive(Debug)]
297pub(crate) struct Link {
298    requests: mpsc::UnboundedSender<ToManager>,
299    next: AtomicU64,
300    /// The requests waiting for their replies, by ID.
301    pending: Mutex<HashMap<u64, oneshot::Sender<Result<Replies, ClusterError>>>>,
302}
303
304impl Link {
305    /// Sends `command` to every cluster (`to: None`) or one and waits for the results. The
306    /// manager answers each cluster within its command timeout. Boxed here so that its code
307    /// is compiled in djs-rs (D-287).
308    pub(crate) fn ask<'a>(
309        &'a self,
310        to: Option<u32>,
311        command: &'a str,
312        input: Value,
313    ) -> super::command::BoxFuture<'a, Result<Replies, ClusterError>> {
314        Box::pin(self.request(to, command, input))
315    }
316
317    async fn request(
318        &self,
319        to: Option<u32>,
320        command: &str,
321        input: Value,
322    ) -> Result<Replies, ClusterError> {
323        let id = self.next.fetch_add(1, Ordering::Relaxed);
324        let (tx, rx) = oneshot::channel();
325        lock(&self.pending).insert(id, tx);
326        let request = ToManager::Request {
327            id,
328            to,
329            command: command.to_owned(),
330            input,
331        };
332        if self.requests.send(request).is_err() {
333            lock(&self.pending).remove(&id);
334            return Err(ClusterError::NotConnected);
335        }
336        // Dropped unanswered when the connection ends.
337        rx.await.map_err(|_| ClusterError::NotConnected)?
338    }
339
340    fn replied(&self, id: u64, replies: Replies) {
341        if let Some(waiting) = lock(&self.pending).remove(&id) {
342            let _ = waiting.send(Ok(replies));
343        }
344    }
345
346    /// Answers for a message that did not fit in a frame: its own request fails here, and a
347    /// handler's result is replaced by an error (sent instead).
348    fn too_large(&self, message: &ToManager) -> Option<ToManager> {
349        match *message {
350            ToManager::Request { id, .. } => {
351                tracing::warn!("a command is too large to send to the cluster manager");
352                if let Some(waiting) = lock(&self.pending).remove(&id) {
353                    let _ = waiting.send(Err(ClusterError::Encoding(TOO_LARGE.into())));
354                }
355                None
356            }
357            ToManager::Reply { id, .. } => {
358                tracing::warn!("the result of a command is too large to send");
359                Some(ToManager::Reply {
360                    id,
361                    result: Err(Failure::Encoding {
362                        message: TOO_LARGE.into(),
363                    }),
364                })
365            }
366            _ => None,
367        }
368    }
369
370    /// Runs a handler for the manager's request `id` and sends its result back. A handler
371    /// that panics is reported as failed.
372    fn run(&self, id: u64, handler: super::command::BoxFuture<'static, Result<Value, Failure>>) {
373        let requests = self.requests.clone();
374        tokio::spawn(async move {
375            let result = tokio::spawn(handler).await.unwrap_or_else(|_| {
376                Err(Failure::Failed {
377                    message: "the command handler panicked".into(),
378                })
379            });
380            let _ = requests.send(ToManager::Reply { id, result });
381        });
382    }
383}
384
385/// The [`IdentifyQueue`] of a cluster process (D-299): each turn is asked from the manager,
386/// which grants them by rate-limit bucket over every process.
387#[derive(Debug)]
388pub(crate) struct ManagerQueue {
389    requests: mpsc::UnboundedSender<ToManager>,
390    /// Per shard, the shards waiting for a turn, oldest first.
391    waiting: Mutex<HashMap<u32, VecDeque<oneshot::Sender<()>>>>,
392}
393
394impl ManagerQueue {
395    /// Gives a turn the manager granted to the oldest waiter of `shard` still waiting. A
396    /// waiter that gave up (its connection closed) is skipped; a turn nobody waits for any
397    /// more is dropped, which only delays its bucket.
398    fn grant(&self, shard: u32) {
399        let mut waiting = lock(&self.waiting);
400        let Some(waiters) = waiting.get_mut(&shard) else {
401            return;
402        };
403        while let Some(waiter) = waiters.pop_front() {
404            if waiter.send(()).is_ok() {
405                break;
406            }
407        }
408        if waiters.is_empty() {
409            waiting.remove(&shard);
410        }
411    }
412}
413
414impl IdentifyQueue for ManagerQueue {
415    fn wait_turn(&self, shard: ShardId) -> Pin<Box<dyn Future<Output = ()> + Send>> {
416        let (tx, rx) = oneshot::channel();
417        lock(&self.waiting)
418            .entry(shard.number())
419            .or_default()
420            .push_back(tx);
421        let _ = self.requests.send(ToManager::Identify {
422            shard: shard.number(),
423        });
424        Box::pin(async move {
425            if rx.await.is_err() {
426                // The manager is gone and the client shuts down: never identify unthrottled.
427                core::future::pending::<()>().await;
428            }
429        })
430    }
431}
432
433#[cfg(test)]
434mod tests {
435    use core::time::Duration;
436    use std::sync::Mutex;
437
438    use djs_gateway::IdentifyQueue;
439    use djs_model::gateway::ShardId;
440    use tokio::{sync::mpsc, time::timeout};
441
442    use super::{ClusterAssignment, Gateway, ManagerQueue};
443    use crate::sharding::{ClusterError, ipc::ToManager, lock};
444
445    #[tokio::test]
446    async fn turns_go_to_the_shards_still_waiting() {
447        let (requests, mut sent) = mpsc::unbounded_channel();
448        let queue = ManagerQueue {
449            requests,
450            waiting: Mutex::default(),
451        };
452        let shard = ShardId::new(3, 4);
453        // A shard whose connection closed while it waited.
454        drop(queue.wait_turn(shard));
455        let mut waiting = queue.wait_turn(shard);
456        for _ in 0..2 {
457            assert_eq!(sent.recv().await, Some(ToManager::Identify { shard: 3 }));
458        }
459        // No turn without the manager's grant…
460        assert!(
461            timeout(Duration::from_millis(20), &mut waiting)
462                .await
463                .is_err()
464        );
465        // …and the first one skips the shard that gave up.
466        queue.grant(3);
467        timeout(Duration::from_secs(5), waiting).await.unwrap();
468        // A turn nobody waits for is dropped.
469        queue.grant(3);
470        queue.grant(9);
471        assert!(lock(&queue.waiting).is_empty());
472    }
473
474    #[test]
475    fn assignments_round_trip_through_the_environment() {
476        let gateway = Gateway {
477            url: "wss://gateway.example".into(),
478            total: 8,
479            max_concurrency: 16,
480        };
481        let assignment = ClusterAssignment::new(
482            2,
483            4..6,
484            &gateway,
485            "127.0.0.1:4000".parse().unwrap(),
486            "t".into(),
487        );
488        let value = assignment.to_env();
489        assert_eq!(
490            value,
491            r#"{"cluster":2,"shards":{"start":4,"end":6},"total":8,"gateway_url":"wss://gateway.example","max_concurrency":16,"address":"127.0.0.1:4000","token":"t"}"#
492        );
493        assert_eq!(assignment.gateway_url(), "wss://gateway.example");
494        assert_eq!(assignment.max_concurrency(), 16);
495        assert_eq!(ClusterAssignment::parse(&value).unwrap(), assignment);
496        assert_eq!(assignment.cluster_id(), 2);
497        assert_eq!(assignment.shards(), 4..6);
498        assert_eq!(assignment.total_shards(), 8);
499        // The token stays out of logs.
500        assert!(!format!("{assignment:?}").contains("token"));
501    }
502
503    #[test]
504    fn invalid_assignments_are_rejected() {
505        let with = |shards: &str, total: u32, max_concurrency: u32, address: &str| {
506            ClusterAssignment::parse(&format!(
507                r#"{{"cluster":0,"shards":{shards},"total":{total},"gateway_url":"wss://g","max_concurrency":{max_concurrency},"address":"{address}","token":"t"}}"#
508            ))
509        };
510        assert!(with(r#"{"start":0,"end":1}"#, 1, 1, "127.0.0.1:1").is_ok());
511        assert!(with(r#"{"start":0,"end":1}"#, 1, 1, "[::1]:1").is_ok());
512        for invalid in [
513            with(r#"{"start":1,"end":1}"#, 2, 1, "127.0.0.1:1"),
514            with(r#"{"start":0,"end":3}"#, 2, 1, "127.0.0.1:1"),
515            with(r#"{"start":0,"end":1}"#, 1, 0, "127.0.0.1:1"),
516            with(r#"{"start":0,"end":1}"#, 1, 1, "10.0.0.1:1"),
517            ClusterAssignment::parse("not json"),
518        ] {
519            assert!(
520                matches!(invalid, Err(ClusterError::Assignment)),
521                "{invalid:?}"
522            );
523        }
524    }
525}