Skip to main content

djs_rs/sharding/
manager.rs

1//! The manager process: starts the cluster processes, accepts their connections and waits
2//! for them (D-296, D-297).
3
4use core::{
5    future::Future,
6    net::{Ipv4Addr, SocketAddr},
7    ops::Range,
8    pin::Pin,
9    task::{Context as TaskContext, Poll},
10    time::Duration,
11};
12use std::{
13    collections::HashMap,
14    ffi::OsString,
15    io,
16    path::PathBuf,
17    process::{ExitStatus, Stdio},
18    sync::{
19        Arc, Mutex,
20        atomic::{AtomicBool, AtomicU64, Ordering},
21    },
22};
23
24use djs_gateway::{IdentifyQueue, LocalIdentifyQueue};
25use djs_model::gateway::ShardId;
26use djs_rest::Rest;
27use futures_core::Stream;
28use serde_json::Value;
29use tokio::{
30    net::{TcpListener, TcpStream},
31    process::Command,
32    sync::{mpsc, oneshot, watch},
33    task::JoinSet,
34};
35
36use super::{
37    ClusterCommand, ClusterError, ClusterReply,
38    cluster::{CLUSTER_ENV, ClusterAssignment, Gateway},
39    command::{Failure, Replies, decode_one, decode_replies, encode},
40    ipc::{
41        MAX_HELLO, TOO_LARGE, ToCluster, ToManager, Token, read_frame, read_frame_within,
42        too_large, write_frame,
43    },
44    lock,
45};
46use crate::Shards;
47
48/// How long a new connection has to introduce itself.
49const HELLO_TIMEOUT: Duration = Duration::from_secs(10);
50
51/// The default time clusters get to stop after [`ClusterManager::shutdown`] before they are
52/// killed.
53const SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(30);
54
55/// The default time a cluster has to answer a command.
56const COMMAND_TIMEOUT: Duration = Duration::from_secs(30);
57
58/// The default first and largest delays before a process is restarted (D-306).
59const RESTART_DELAY: (Duration, Duration) = (Duration::from_secs(1), Duration::from_secs(60));
60
61/// How a cluster process ended: its ID, its exit status and how long it ran.
62type Exit = (u32, io::Result<ExitStatus>, Duration);
63
64type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
65
66/// Runs a bot's shards in several processes of the same executable, `shards_per_process`
67/// shards each (D-296, D-297).
68///
69/// Cheap to clone (a reference count increment). Build it with [`ClusterManager::builder`]
70/// in the process that was not started by a manager ([`process`](super::process) returned
71/// `None`), then [`spawn`](Self::spawn) it.
72///
73/// discord.js counterpart: `ShardingManager` (and discord-hybrid-sharding's
74/// `ClusterManager`).
75///
76/// # Examples
77///
78/// ```no_run
79/// use djs_rs::{prelude::*, sharding::{self, ClusterManager}};
80///
81/// # async fn run() -> Result<(), Box<dyn std::error::Error>> {
82/// let token = std::env::var("DISCORD_TOKEN")?;
83/// match sharding::process()? {
84///     // A process started by the manager: an ordinary client, given its shards.
85///     Some(assignment) => {
86///         let client = Client::builder(token).cluster(assignment).build();
87///         client.on(Events::MessageCreate, |ctx, msg| async move {
88///             if msg.content == "!ping" {
89///                 msg.reply(&ctx, "Pong!").await?;
90///             }
91///             Ok(())
92///         });
93///         client.login().await?;
94///     }
95///     // The first process: it starts one process per shard and waits for them.
96///     None => ClusterManager::builder(token).build().spawn().await?,
97/// }
98/// # Ok(())
99/// # }
100/// ```
101#[derive(Clone, Debug)]
102pub struct ClusterManager {
103    inner: Arc<Inner>,
104}
105
106#[derive(Debug)]
107struct Inner {
108    rest: Rest,
109    shards: Shards,
110    shards_per_process: u32,
111    executable: Option<PathBuf>,
112    args: Option<Vec<OsString>>,
113    envs: Vec<(OsString, OsString)>,
114    shutdown_timeout: Duration,
115    restart: Restart,
116    restart_delay: (Duration, Duration),
117    command_timeout: Duration,
118    /// The ID of the next request sent to a cluster.
119    next_request: AtomicU64,
120    running: AtomicBool,
121    shutdown: watch::Sender<bool>,
122    subscribers: Mutex<Vec<mpsc::UnboundedSender<ClusterEvent>>>,
123    clusters: Mutex<Vec<State>>,
124}
125
126/// What the manager knows of one cluster process.
127#[derive(Debug)]
128struct State {
129    shards: Range<u32>,
130    pid: Option<u32>,
131    /// The frames to send, while the process is connected.
132    sender: Option<mpsc::UnboundedSender<ToCluster>>,
133    /// The delay before the next restart, unless the process ran long enough (D-306).
134    delay: Duration,
135    /// The requests sent to the connected process, waiting for its reply.
136    pending: HashMap<u64, oneshot::Sender<Result<Value, Failure>>>,
137}
138
139impl ClusterManager {
140    /// Starts building a manager for the bot with `token`, which it uses only for one
141    /// [Get Gateway Bot] request when it starts (D-305). The processes read their own token.
142    ///
143    /// [Get Gateway Bot]: https://docs.discord.com/developers/events/gateway#get-gateway-bot
144    ///
145    /// discord.js counterpart: `new ShardingManager(file, { token })`.
146    pub fn builder(token: impl Into<String>) -> ClusterManagerBuilder {
147        ClusterManagerBuilder {
148            token: token.into(),
149            rest: None,
150            shards: Shards::Auto,
151            shards_per_process: 1,
152            executable: None,
153            args: None,
154            envs: Vec::new(),
155            shutdown_timeout: SHUTDOWN_TIMEOUT,
156            restart: Restart::OnFailure,
157            restart_delay: RESTART_DELAY,
158            command_timeout: COMMAND_TIMEOUT,
159        }
160    }
161
162    /// Starts the cluster processes and runs until every one of them has stopped (after
163    /// [`shutdown`](Self::shutdown), or on its own without being restarted).
164    ///
165    /// The manager first asks Discord for the gateway's details once, for every process
166    /// ([Get Gateway Bot], D-305): the gateway URL, the recommended shard count (used with
167    /// the default [`Shards::Auto`], see [`ClusterManagerBuilder::shards`]), the session
168    /// starts left (enough for every shard, or nothing is started) and `max_concurrency`.
169    /// The shards are split into processes of
170    /// [`shards_per_process`](ClusterManagerBuilder::shards_per_process) each, numbered from
171    /// cluster 0. Each process is the same executable with the same arguments (unless
172    /// configured otherwise), its standard output and error shared with the manager's and
173    /// its standard input closed; it learns its shards and the gateway from the environment
174    /// ([`process`](super::process)) and connects back to the manager over `127.0.0.1`
175    /// with a secret token (D-285). A process the manager did not start cannot connect.
176    ///
177    /// The manager is the IDENTIFY queue of every process (D-299): a shard asks it for a
178    /// turn before identifying, and it grants one per rate-limit bucket
179    /// (`shard % max_concurrency`) every 5 seconds over all the processes, so the shards
180    /// start as fast as Discord allows and none is refused for identifying too fast.
181    ///
182    /// A process that fails is started again with the same shards, after a delay that grows
183    /// while it keeps failing ([`ClusterManagerBuilder::restart`] and
184    /// [`restart_delay`](ClusterManagerBuilder::restart_delay), D-306). `spawn` returns once
185    /// every process has exited and none is waiting for a restart.
186    ///
187    /// [Get Gateway Bot]: https://docs.discord.com/developers/events/gateway#get-gateway-bot
188    ///
189    /// discord.js counterpart: `ShardingManager#spawn` (which returns once the shards are
190    /// started).
191    ///
192    /// # Errors
193    ///
194    /// [`ClusterError::Rest`] if Get Gateway Bot fails, [`ClusterError::SessionStartLimit`]
195    /// if too few session starts are left for the shards, [`ClusterError::Io`] if the manager
196    /// cannot listen or start the first processes (a restart that cannot start is tried
197    /// again after the next delay), [`ClusterError::AlreadyRunning`] if the manager is
198    /// already running.
199    pub fn spawn(&self) -> impl Future<Output = Result<(), ClusterError>> + Send + '_ {
200        boxed(self.run())
201    }
202
203    /// Asks every cluster to shut down; [`spawn`](Self::spawn) returns once they have
204    /// exited. Processes still running after the
205    /// [`shutdown_timeout`](ClusterManagerBuilder::shutdown_timeout) are killed. Has no effect
206    /// when the manager is not running.
207    ///
208    /// discord.js counterpart: none (discord.js kills the shards with `Shard#kill`).
209    pub fn shutdown(&self) {
210        self.inner.shutdown.send_replace(true);
211    }
212
213    /// Returns a stream of the manager's events: processes started, connected and exited.
214    ///
215    /// discord.js counterpart: `ShardingManager#on('shardCreate')` and the `Shard` events.
216    #[must_use]
217    pub fn events(&self) -> ClusterEvents {
218        let (tx, rx) = mpsc::unbounded_channel();
219        lock(&self.inner.subscribers).push(tx);
220        ClusterEvents { rx }
221    }
222
223    /// The clusters of the current [`spawn`](Self::spawn) (empty before it).
224    ///
225    /// discord.js counterpart: `ShardingManager#shards`.
226    #[must_use]
227    pub fn clusters(&self) -> Vec<Cluster> {
228        lock(&self.inner.clusters)
229            .iter()
230            .enumerate()
231            .map(|(id, state)| Cluster {
232                id: u32::try_from(id).unwrap_or(u32::MAX),
233                shards: state.shards.clone(),
234                pid: state.pid,
235                connected: state.sender.is_some(),
236            })
237            .collect()
238    }
239
240    /// Sends the command `C` to every cluster and returns each one's result, by cluster ID
241    /// (D-307–D-309). A cluster that is not connected (down, restarting, or the manager is
242    /// not running), does not handle `C`, fails or does not answer within the
243    /// [`command_timeout`](ClusterManagerBuilder::command_timeout) has an error in its
244    /// [`ClusterReply`]; the others still have their results.
245    ///
246    /// discord.js counterpart: `ShardingManager#broadcastEval`.
247    ///
248    /// # Errors
249    ///
250    /// [`ClusterError::Encoding`] if `input` cannot be converted to JSON.
251    ///
252    /// # Examples
253    ///
254    /// ```no_run
255    /// use djs_rs::sharding::{ClusterCommand, ClusterManager};
256    ///
257    /// struct GuildCount;
258    ///
259    /// impl ClusterCommand for GuildCount {
260    ///     const NAME: &'static str = "guild_count";
261    ///     type Input = ();
262    ///     type Output = usize;
263    /// }
264    ///
265    /// # async fn run(manager: ClusterManager) -> Result<(), djs_rs::sharding::ClusterError> {
266    /// let total: usize = manager
267    ///     .broadcast::<GuildCount>(())
268    ///     .await?
269    ///     .into_iter()
270    ///     .filter_map(|reply| reply.result.ok())
271    ///     .sum();
272    /// println!("{total} guilds");
273    /// # Ok(())
274    /// # }
275    /// ```
276    pub async fn broadcast<C: ClusterCommand>(
277        &self,
278        input: C::Input,
279    ) -> Result<Vec<ClusterReply<C::Output>>, ClusterError> {
280        let input = encode(&input)?;
281        Ok(decode_replies(self.ask(None, C::NAME, input).await))
282    }
283
284    /// Asks every cluster for its [`ClusterStats`](super::ClusterStats) (D-310): the built-in
285    /// [`Stats`](super::Stats) command, broadcast.
286    ///
287    /// discord.js counterpart: `ShardingManager#fetchClientValues`.
288    ///
289    /// # Errors
290    ///
291    /// None for now: a cluster that does not answer has an error in its [`ClusterReply`].
292    pub async fn stats(&self) -> Result<Vec<ClusterReply<super::ClusterStats>>, ClusterError> {
293        self.broadcast::<super::Stats>(()).await
294    }
295
296    /// Sends the command `C` to cluster `cluster` and returns its result.
297    ///
298    /// discord.js counterpart: `broadcastEval` with the `shard` option.
299    ///
300    /// # Errors
301    ///
302    /// [`ClusterError::NotConnected`] if the cluster is not connected (or does not exist),
303    /// [`ClusterError::UnknownCommand`] if it does not handle `C`,
304    /// [`ClusterError::CommandFailed`] if its handler fails, [`ClusterError::Timeout`] if it
305    /// does not answer in time, [`ClusterError::Encoding`] if the input or output cannot be
306    /// converted.
307    pub async fn send<C: ClusterCommand>(
308        &self,
309        cluster: u32,
310        input: C::Input,
311    ) -> Result<C::Output, ClusterError> {
312        let input = encode(&input)?;
313        decode_one(self.ask(Some(cluster), C::NAME, input).await)
314    }
315
316    /// Sends `command` to every cluster (`to: None`) or one, and waits for each one's result
317    /// until the command timeout. Boxed here so that its code is compiled in djs-rs (D-287).
318    pub(crate) fn ask<'a>(
319        &'a self,
320        to: Option<u32>,
321        command: &'a str,
322        input: Value,
323    ) -> BoxFuture<'a, Replies> {
324        Box::pin(async move {
325            let inner = &*self.inner;
326            let mut waiting = Vec::new();
327            {
328                let mut clusters = lock(&inner.clusters);
329                let targets = match to {
330                    Some(cluster) => cluster..cluster.saturating_add(1),
331                    None => 0..u32::try_from(clusters.len()).unwrap_or(u32::MAX),
332                };
333                for cluster in targets {
334                    let state = clusters.get_mut(cluster as usize);
335                    let Some((state, sender)) =
336                        state.and_then(|state| state.sender.clone().map(|sender| (state, sender)))
337                    else {
338                        waiting.push((cluster, 0, None));
339                        continue;
340                    };
341                    let id = inner.next_request.fetch_add(1, Ordering::Relaxed);
342                    let (tx, rx) = oneshot::channel();
343                    state.pending.insert(id, tx);
344                    let request = ToCluster::Request {
345                        id,
346                        command: command.to_owned(),
347                        input: input.clone(),
348                    };
349                    let sent = sender.send(request).is_ok();
350                    waiting.push((cluster, id, sent.then_some(rx)));
351                }
352            }
353            let deadline = tokio::time::Instant::now() + inner.command_timeout;
354            let mut replies = Vec::with_capacity(waiting.len());
355            for (cluster, id, reply) in waiting {
356                let result = match reply {
357                    None => Err(Failure::NotConnected),
358                    Some(reply) => match tokio::time::timeout_at(deadline, reply).await {
359                        Ok(Ok(result)) => result,
360                        Ok(Err(_)) => Err(Failure::NotConnected),
361                        Err(_) => {
362                            if let Some(state) = lock(&inner.clusters).get_mut(cluster as usize) {
363                                state.pending.remove(&id);
364                            }
365                            Err(Failure::Timeout)
366                        }
367                    },
368                };
369                replies.push((cluster, result));
370            }
371            replies
372        })
373    }
374
375    /// Answers for a message to cluster `cluster` that did not fit in a frame: its request
376    /// fails here, and the replies it carried are replaced by errors (sent instead).
377    fn too_large(&self, cluster: u32, message: ToCluster) -> Option<ToCluster> {
378        let failure = || Failure::Encoding {
379            message: TOO_LARGE.into(),
380        };
381        match message {
382            ToCluster::Request { id, .. } => {
383                tracing::warn!(cluster, "a command for a cluster is too large to send");
384                let waiting = lock(&self.inner.clusters)
385                    .get_mut(cluster as usize)
386                    .and_then(|state| state.pending.remove(&id));
387                if let Some(waiting) = waiting {
388                    let _ = waiting.send(Err(failure()));
389                }
390                None
391            }
392            ToCluster::Replies { id, replies } => {
393                tracing::warn!(cluster, "the results of a command are too large to send");
394                let replies = replies
395                    .into_iter()
396                    .map(|(cluster, _)| (cluster, Err(failure())))
397                    .collect();
398                Some(ToCluster::Replies { id, replies })
399            }
400            _ => None,
401        }
402    }
403
404    fn emit(&self, event: &ClusterEvent) {
405        lock(&self.inner.subscribers).retain(|tx| tx.send(event.clone()).is_ok());
406    }
407
408    async fn run(&self) -> Result<(), ClusterError> {
409        let inner = &*self.inner;
410        if inner.running.swap(true, Ordering::AcqRel) {
411            return Err(ClusterError::AlreadyRunning);
412        }
413        let result = self.supervise().await;
414        inner.running.store(false, Ordering::Release);
415        result
416    }
417
418    async fn supervise(&self) -> Result<(), ClusterError> {
419        let inner = &*self.inner;
420        inner.shutdown.send_replace(false);
421        let shutdown = inner.shutdown.subscribe();
422
423        // One request for every process (D-305).
424        let bot = inner.rest.get_gateway_bot().await?;
425        let (range, total) = match &inner.shards {
426            Shards::Count(count) => (0..*count, *count),
427            Shards::Range { range, total } => (range.clone(), *total),
428            Shards::Auto => {
429                let total = bot.shards.max(1);
430                (0..total, total)
431            }
432        };
433        let limit = &bot.session_start_limit;
434        let required = range.end - range.start;
435        if limit.remaining < required {
436            return Err(ClusterError::SessionStartLimit {
437                required,
438                remaining: limit.remaining,
439                reset_after: Duration::from_millis(limit.reset_after),
440            });
441        }
442        let gateway = Gateway {
443            url: bot.url.into(),
444            total,
445            max_concurrency: limit.max_concurrency.max(1),
446        };
447        let groups = split(range, inner.shards_per_process);
448        let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0))
449            .await
450            .map_err(ClusterError::Io)?;
451        let session = Arc::new(Session {
452            token: Token::generate(),
453            identify: LocalIdentifyQueue::new(gateway.max_concurrency),
454            gateway,
455        });
456        let launch = Launch {
457            executable: match &inner.executable {
458                Some(path) => path.clone(),
459                None => std::env::current_exe().map_err(ClusterError::Io)?,
460            },
461            args: inner
462                .args
463                .clone()
464                .unwrap_or_else(|| std::env::args_os().skip(1).collect()),
465            address: listener.local_addr().map_err(ClusterError::Io)?,
466        };
467        *lock(&inner.clusters) = groups
468            .iter()
469            .map(|shards| State {
470                shards: shards.clone(),
471                pid: None,
472                sender: None,
473                delay: inner.restart_delay.0,
474                pending: HashMap::new(),
475            })
476            .collect();
477        tracing::info!(
478            clusters = groups.len(),
479            total,
480            max_concurrency = session.gateway.max_concurrency,
481            "starting the cluster processes"
482        );
483
484        let accepting = tokio::spawn(accept(self.clone(), listener, Arc::clone(&session)));
485        let mut run = Run {
486            manager: self,
487            launch,
488            session,
489            kill: watch::channel(false).0,
490            processes: JoinSet::new(),
491            restarts: JoinSet::new(),
492        };
493        let mut started = Ok(());
494        for id in (0_u32..).take(groups.len()) {
495            if let Err(error) = run.start(id) {
496                // Stop what was started and report the error.
497                tracing::error!(cluster = id, %error, "could not start a cluster process");
498                inner.shutdown.send_replace(true);
499                started = Err(ClusterError::Io(error));
500                break;
501            }
502        }
503        let waited = run.wait(shutdown).await;
504        accepting.abort();
505        started.and(waited)
506    }
507}
508
509/// One [`ClusterManager::spawn`] once its processes can start: their processes and
510/// restarts.
511struct Run<'a> {
512    manager: &'a ClusterManager,
513    launch: Launch,
514    session: Arc<Session>,
515    /// Set once the processes still running after the grace period must be killed.
516    kill: watch::Sender<bool>,
517    processes: JoinSet<Exit>,
518    /// The clusters waiting for their restart delay.
519    restarts: JoinSet<u32>,
520}
521
522impl Run<'_> {
523    /// Starts cluster `id`'s process.
524    fn start(&mut self, id: u32) -> io::Result<()> {
525        let inner = &*self.manager.inner;
526        let Some(shards) = lock(&inner.clusters)
527            .get(id as usize)
528            .map(|state| state.shards.clone())
529        else {
530            return Ok(());
531        };
532        let assignment = ClusterAssignment::new(
533            id,
534            shards,
535            &self.session.gateway,
536            self.launch.address,
537            self.session.token.as_str().into(),
538        );
539        let mut command = Command::new(&self.launch.executable);
540        command
541            .args(&self.launch.args)
542            .envs(inner.envs.iter().map(|(key, value)| (key, value)))
543            .env(CLUSTER_ENV, assignment.to_env())
544            .stdin(Stdio::null())
545            .kill_on_drop(true);
546        let mut child = command.spawn()?;
547        let pid = child.id();
548        if let Some(state) = lock(&inner.clusters).get_mut(id as usize) {
549            state.pid = pid;
550        }
551        self.manager
552            .emit(&ClusterEvent::Spawned { cluster: id, pid });
553        let mut kill = self.kill.subscribe();
554        let started = tokio::time::Instant::now();
555        self.processes.spawn(async move {
556            let status = tokio::select! {
557                status = child.wait() => status,
558                () = async { let _ = kill.wait_for(|kill| *kill).await; } => {
559                    let _ = child.start_kill();
560                    child.wait().await
561                }
562            };
563            (id, status, started.elapsed())
564        });
565        Ok(())
566    }
567
568    /// Waits for every process to exit, restarting those the policy says (D-306). On a
569    /// shutdown, cancels the restarts, asks the connected processes to stop, then kills
570    /// those still running after the grace period.
571    async fn wait(&mut self, mut shutdown: watch::Receiver<bool>) -> Result<(), ClusterError> {
572        let inner = &*self.manager.inner;
573        let mut deadline: Option<tokio::time::Instant> = None;
574        loop {
575            if self.processes.is_empty() && self.restarts.is_empty() {
576                return Ok(());
577            }
578            let grace = async {
579                match deadline {
580                    Some(deadline) => tokio::time::sleep_until(deadline).await,
581                    None => core::future::pending().await,
582                }
583            };
584            tokio::select! {
585                changed = shutdown.changed(), if deadline.is_none() => {
586                    if changed.is_ok() && !*shutdown.borrow() {
587                        continue;
588                    }
589                    tracing::info!("asking the clusters to shut down");
590                    // Dropping the set cancels the restarts still waiting.
591                    self.restarts = JoinSet::new();
592                    for state in lock(&inner.clusters).iter() {
593                        if let Some(sender) = &state.sender {
594                            let _ = sender.send(ToCluster::Shutdown);
595                        }
596                    }
597                    deadline = Some(tokio::time::Instant::now() + inner.shutdown_timeout);
598                }
599                () = grace => {
600                    tracing::warn!("killing the clusters that did not shut down in time");
601                    self.kill.send_replace(true);
602                    deadline = None;
603                }
604                Some(finished) = self.processes.join_next() => {
605                    let (id, status, ran) = finished.map_err(|error| {
606                        ClusterError::Io(io::Error::other(error))
607                    })?;
608                    let failed = !matches!(&status, Ok(status) if status.success());
609                    self.exited(id, status);
610                    let restart = match inner.restart {
611                        Restart::OnFailure => failed,
612                        Restart::Always => true,
613                        Restart::Never => false,
614                    };
615                    if restart && !*shutdown.borrow() {
616                        self.restart_later(id, ran);
617                    }
618                }
619                Some(restart) = self.restarts.join_next() => {
620                    let Ok(id) = restart else { continue };
621                    if let Err(error) = self.start(id) {
622                        tracing::error!(cluster = id, %error, "could not restart a cluster process");
623                        self.restart_later(id, Duration::ZERO);
624                    }
625                }
626            }
627        }
628    }
629
630    /// Records that cluster `id`'s process has exited.
631    fn exited(&self, id: u32, status: io::Result<ExitStatus>) {
632        if let Some(state) = lock(&self.manager.inner.clusters).get_mut(id as usize) {
633            state.sender = None;
634            state.pid = None;
635            // Its requests still waiting fail as not connected.
636            state.pending.clear();
637        }
638        match status {
639            Ok(status) => {
640                if status.success() {
641                    tracing::info!(cluster = id, "cluster process exited");
642                } else {
643                    tracing::warn!(cluster = id, %status, "cluster process failed");
644                }
645                self.manager.emit(&ClusterEvent::Exited {
646                    cluster: id,
647                    status,
648                });
649            }
650            Err(error) => {
651                tracing::error!(cluster = id, %error, "lost a cluster process");
652            }
653        }
654    }
655
656    /// Restarts cluster `id` after its delay, which grows while it keeps exiting before
657    /// running for the largest delay (D-306).
658    fn restart_later(&mut self, id: u32, ran: Duration) {
659        let (first, max) = self.manager.inner.restart_delay;
660        let delay = {
661            let mut clusters = lock(&self.manager.inner.clusters);
662            let Some(state) = clusters.get_mut(id as usize) else {
663                return;
664            };
665            let (delay, next) = restart_delay(state.delay, ran, first, max);
666            state.delay = next;
667            delay
668        };
669        tracing::info!(cluster = id, ?delay, "restarting a cluster process");
670        self.manager
671            .emit(&ClusterEvent::Restarting { cluster: id, delay });
672        self.restarts.spawn(async move {
673            tokio::time::sleep(delay).await;
674            id
675        });
676    }
677}
678
679/// The delay before a restart, and the one after it: `current` doubles up to `max`, and a
680/// process that ran for at least `max` starts again from `first`.
681fn restart_delay(
682    current: Duration,
683    ran: Duration,
684    first: Duration,
685    max: Duration,
686) -> (Duration, Duration) {
687    let delay = if ran >= max { first } else { current };
688    (delay, delay.saturating_mul(2).min(max))
689}
690
691/// What one [`ClusterManager::spawn`] starts its processes with.
692struct Launch {
693    executable: PathBuf,
694    args: Vec<OsString>,
695    address: SocketAddr,
696}
697
698/// What the connections of one [`ClusterManager::spawn`] share.
699#[derive(Debug)]
700struct Session {
701    /// The secret the processes present.
702    token: Token,
703    gateway: Gateway,
704    /// The IDENTIFY turns of every process, by rate-limit bucket (D-299).
705    identify: LocalIdentifyQueue,
706}
707
708/// Boxes the manager's loop here, so that its code is compiled in djs-rs (D-287).
709fn boxed<'a, T>(future: impl Future<Output = T> + Send + 'a) -> BoxFuture<'a, T> {
710    Box::pin(future)
711}
712
713/// Splits `range` into groups of `size` shards (the last may be smaller).
714fn split(range: Range<u32>, size: u32) -> Vec<Range<u32>> {
715    let size = size.max(1);
716    let mut groups = Vec::new();
717    let mut start = range.start;
718    while start < range.end {
719        let end = start.saturating_add(size).min(range.end);
720        groups.push(start..end);
721        start = end;
722    }
723    groups
724}
725
726/// Accepts the processes' connections until aborted.
727async fn accept(manager: ClusterManager, listener: TcpListener, session: Arc<Session>) {
728    loop {
729        let Ok((stream, _)) = listener.accept().await else {
730            // Out of file descriptors, say: try again a little later.
731            tokio::time::sleep(Duration::from_millis(100)).await;
732            continue;
733        };
734        tokio::spawn(handshake(manager.clone(), stream, Arc::clone(&session)));
735    }
736}
737
738/// Checks a connection's [`ToManager::Hello`], then serves it.
739async fn handshake(manager: ClusterManager, stream: TcpStream, session: Arc<Session>) {
740    let _ = stream.set_nodelay(true);
741    let (mut reader, mut writer) = stream.into_split();
742    let hello = tokio::time::timeout(
743        HELLO_TIMEOUT,
744        read_frame_within::<_, ToManager>(&mut reader, MAX_HELLO),
745    )
746    .await;
747    let Ok(Ok(Some(ToManager::Hello {
748        cluster,
749        token: presented,
750    }))) = hello
751    else {
752        tracing::warn!("refused a connection that did not introduce itself");
753        return;
754    };
755    if !session.token.matches(&presented) {
756        tracing::warn!(cluster, "refused a connection with a wrong token");
757        return;
758    }
759    let (tx, mut rx) = mpsc::unbounded_channel();
760    // Queued before the cluster is registered: a shutdown sent to it cannot come first.
761    let _ = tx.send(ToCluster::Welcome);
762    let shards = {
763        let mut clusters = lock(&manager.inner.clusters);
764        let Some(state) = clusters.get_mut(cluster as usize) else {
765            tracing::warn!(cluster, "refused a connection for an unknown cluster");
766            return;
767        };
768        if state.sender.is_some() {
769            tracing::warn!(cluster, "refused a second connection for a cluster");
770            return;
771        }
772        state.sender = Some(tx.clone());
773        state.shards.clone()
774    };
775    manager.emit(&ClusterEvent::Connected { cluster });
776    // Connected after a shutdown was asked: it stops at once.
777    if *manager.inner.shutdown.borrow() {
778        let _ = tx.send(ToCluster::Shutdown);
779    }
780    let writing = tokio::spawn({
781        let manager = manager.clone();
782        async move {
783            while let Some(message) = rx.recv().await {
784                match write_frame(&mut writer, &message).await {
785                    Ok(()) => {}
786                    // Nothing was written: answer for the message instead, and go on.
787                    Err(error) if too_large(&error) => {
788                        let Some(instead) = manager.too_large(cluster, message) else {
789                            continue;
790                        };
791                        if write_frame(&mut writer, &instead).await.is_err() {
792                            break;
793                        }
794                    }
795                    Err(_) => break,
796                }
797            }
798        }
799    });
800    serve(&manager, cluster, &shards, reader, &tx, &session).await;
801    writing.abort();
802    let mut clusters = lock(&manager.inner.clusters);
803    if let Some(state) = clusters.get_mut(cluster as usize)
804        && state
805            .sender
806            .as_ref()
807            .is_some_and(|sender| sender.same_channel(&tx))
808    {
809        state.sender = None;
810        state.pending.clear();
811    }
812}
813
814/// Answers a connected process's requests until its connection ends: IDENTIFY turns, its
815/// commands for the clusters, and its replies to the manager's. Its turns still waiting in
816/// the IDENTIFY queue are then dropped, so they do not hold up the others.
817async fn serve(
818    manager: &ClusterManager,
819    cluster: u32,
820    shards: &Range<u32>,
821    mut reader: tokio::net::tcp::OwnedReadHalf,
822    tx: &mpsc::UnboundedSender<ToCluster>,
823    session: &Session,
824) {
825    // Frames are read in their own task: reading one is not cancel-safe, and the turns are
826    // awaited next to it.
827    let (frames_tx, mut frames) = mpsc::unbounded_channel();
828    let reading = tokio::spawn(async move {
829        while let Ok(Some(frame)) = read_frame::<_, ToManager>(&mut reader).await {
830            if frames_tx.send(frame).is_err() {
831                break;
832            }
833        }
834    });
835    let mut tasks = JoinSet::new();
836    loop {
837        tokio::select! {
838            frame = frames.recv() => match frame {
839                Some(ToManager::Identify { shard }) if shards.contains(&shard) => {
840                    let turn = session
841                        .identify
842                        .wait_turn(ShardId::new(shard, session.gateway.total));
843                    let tx = tx.clone();
844                    tasks.spawn(async move {
845                        turn.await;
846                        let _ = tx.send(ToCluster::Identify { shard });
847                    });
848                }
849                Some(ToManager::Request { id, to, command, input }) => {
850                    let (manager, tx) = (manager.clone(), tx.clone());
851                    tasks.spawn(async move {
852                        let replies = manager.ask(to, &command, input).await;
853                        let _ = tx.send(ToCluster::Replies { id, replies });
854                    });
855                }
856                Some(ToManager::Reply { id, result }) => {
857                    let waiting = lock(&manager.inner.clusters)
858                        .get_mut(cluster as usize)
859                        .and_then(|state| state.pending.remove(&id));
860                    if let Some(waiting) = waiting {
861                        let _ = waiting.send(result);
862                    }
863                }
864                Some(ToManager::Identify { shard }) => {
865                    tracing::warn!(cluster, shard, "ignored a turn asked for another cluster's shard");
866                }
867                Some(ToManager::Hello { .. }) => {}
868                None => break,
869            },
870            Some(_) = tasks.join_next(), if !tasks.is_empty() => {}
871        }
872    }
873    reading.abort();
874}
875
876/// Configures a [`ClusterManager`]. Created by [`ClusterManager::builder`].
877///
878/// discord.js counterpart: `ShardingManagerOptions`.
879#[derive(Debug)]
880#[must_use = "a builder does nothing until `build` is called"]
881pub struct ClusterManagerBuilder {
882    token: String,
883    rest: Option<Rest>,
884    shards: Shards,
885    shards_per_process: u32,
886    executable: Option<PathBuf>,
887    args: Option<Vec<OsString>>,
888    envs: Vec<(OsString, OsString)>,
889    shutdown_timeout: Duration,
890    restart: Restart,
891    restart_delay: (Duration, Duration),
892    command_timeout: Duration,
893}
894
895impl ClusterManagerBuilder {
896    /// Uses a preconfigured REST client to ask Discord for the shard count.
897    ///
898    /// discord.js counterpart: none (`ShardingManager` asks Get Gateway Bot with its own client).
899    pub fn rest(mut self, rest: Rest) -> Self {
900        self.rest = Some(rest);
901        self
902    }
903
904    /// Sets which shards the processes run (default [`Shards::Auto`]: as many as Discord
905    /// recommends); a [`Shards::Range`] runs part of the bot here (the rest elsewhere).
906    ///
907    /// discord.js counterpart: the `totalShards` and `shardList` options.
908    ///
909    /// # Panics
910    ///
911    /// Panics on a shard count of `0`, or a range that is empty or reaches past `total`.
912    #[track_caller]
913    pub fn shards(mut self, shards: Shards) -> Self {
914        match &shards {
915            Shards::Auto => {}
916            Shards::Count(count) => assert!(*count > 0, "the shard count must not be zero"),
917            Shards::Range { range, total } => assert!(
918                range.start < range.end && range.end <= *total,
919                "shard range {range:?} must be non-empty and within the total of {total}"
920            ),
921        }
922        self.shards = shards;
923        self
924    }
925
926    /// Sets how many shards each process runs (default 1, as discord.js, D-297): with more,
927    /// a large bot runs fewer processes, each with one cache, runtime and REST client for its
928    /// shards. The last process may get fewer.
929    ///
930    /// discord.js counterpart: discord-hybrid-sharding's `shardsPerClusters`.
931    ///
932    /// # Panics
933    ///
934    /// Panics on `0`.
935    #[track_caller]
936    pub fn shards_per_process(mut self, shards: u32) -> Self {
937        assert!(shards > 0, "a process must run at least one shard");
938        self.shards_per_process = shards;
939        self
940    }
941
942    /// Starts this executable instead of the manager's own (D-296).
943    ///
944    /// discord.js counterpart: the `file` argument of `ShardingManager`.
945    pub fn executable(mut self, path: impl Into<PathBuf>) -> Self {
946        self.executable = Some(path.into());
947        self
948    }
949
950    /// Gives the processes these arguments instead of the manager's own.
951    ///
952    /// discord.js counterpart: the `shardArgs` option.
953    pub fn args<A: Into<OsString>>(mut self, args: impl IntoIterator<Item = A>) -> Self {
954        self.args = Some(args.into_iter().map(Into::into).collect());
955        self
956    }
957
958    /// Adds an environment variable for the processes (they inherit the manager's
959    /// environment too).
960    ///
961    /// discord.js counterpart: the `execArgv` and environment of `ShardingManagerOptions`.
962    pub fn env(mut self, key: impl Into<OsString>, value: impl Into<OsString>) -> Self {
963        self.envs.push((key.into(), value.into()));
964        self
965    }
966
967    /// Sets how long the clusters get to stop after [`ClusterManager::shutdown`] before they
968    /// are killed (default 30 seconds).
969    ///
970    /// discord.js counterpart: none (discord.js kills the shards with `Shard#kill`).
971    pub const fn shutdown_timeout(mut self, timeout: Duration) -> Self {
972        self.shutdown_timeout = timeout;
973        self
974    }
975
976    /// Sets which exits of a process restart it (default [`Restart::OnFailure`], D-306).
977    /// Processes stopped by [`ClusterManager::shutdown`] are never restarted.
978    ///
979    /// discord.js counterpart: the `respawn` option (which restarts every exit).
980    pub const fn restart(mut self, restart: Restart) -> Self {
981        self.restart = restart;
982        self
983    }
984
985    /// Sets the delays before a process is restarted (default 1 second, up to 60): the first
986    /// restart waits `first`, each next one twice as long up to `max`, and a process that ran
987    /// for at least `max` before exiting starts again from `first` (D-306). A failing bot so
988    /// does not restart in a loop.
989    ///
990    /// discord.js counterpart: the `respawnDelay` of `Shard#respawn` (a fixed delay).
991    ///
992    /// # Panics
993    ///
994    /// Panics if `first` is zero or longer than `max`.
995    #[track_caller]
996    pub const fn restart_delay(mut self, first: Duration, max: Duration) -> Self {
997        assert!(!first.is_zero(), "the first restart delay must not be zero");
998        assert!(
999            first.as_nanos() <= max.as_nanos(),
1000            "the first restart delay must not be longer than the largest"
1001        );
1002        self.restart_delay = (first, max);
1003        self
1004    }
1005
1006    /// Sets how long a cluster has to answer a command
1007    /// ([`ClusterManager::broadcast`], [`ClusterClient::broadcast`](super::ClusterClient::broadcast), …)
1008    /// before its result is [`ClusterError::Timeout`] (default 30 seconds).
1009    ///
1010    /// discord.js counterpart: the `timeout` option of `broadcastEval`.
1011    pub const fn command_timeout(mut self, timeout: Duration) -> Self {
1012        self.command_timeout = timeout;
1013        self
1014    }
1015
1016    /// Builds the manager.
1017    ///
1018    /// discord.js counterpart: `new ShardingManager(file, options)`.
1019    #[must_use]
1020    pub fn build(self) -> ClusterManager {
1021        ClusterManager {
1022            inner: Arc::new(Inner {
1023                rest: self
1024                    .rest
1025                    .unwrap_or_else(|| Rest::builder().token(self.token).build()),
1026                shards: self.shards,
1027                shards_per_process: self.shards_per_process,
1028                executable: self.executable,
1029                args: self.args,
1030                envs: self.envs,
1031                shutdown_timeout: self.shutdown_timeout,
1032                restart: self.restart,
1033                restart_delay: self.restart_delay,
1034                command_timeout: self.command_timeout,
1035                next_request: AtomicU64::new(0),
1036                running: AtomicBool::new(false),
1037                shutdown: watch::channel(false).0,
1038                subscribers: Mutex::new(Vec::new()),
1039                clusters: Mutex::new(Vec::new()),
1040            }),
1041        }
1042    }
1043}
1044
1045/// Which exits of a cluster process make the manager restart it (D-306): see
1046/// [`ClusterManagerBuilder::restart`]. A process stopped by [`ClusterManager::shutdown`] is
1047/// never restarted.
1048///
1049/// discord.js counterpart: the `respawn` option.
1050#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1051#[non_exhaustive]
1052pub enum Restart {
1053    /// Restart a process that failed: a non-zero exit code, or killed by a signal (a panic,
1054    /// an error from `login`, out of memory). A clean exit (code 0, for example after
1055    /// [`Context::shutdown`](crate::Context::shutdown) in the process) ends that cluster.
1056    #[default]
1057    OnFailure,
1058    /// Restart every exit, clean ones included (as discord.js's `respawn: true`).
1059    Always,
1060    /// Never restart: an exited cluster stays stopped.
1061    Never,
1062}
1063
1064/// One cluster process as the manager last saw it: its ID, shards and process. Returned by
1065/// [`ClusterManager::clusters`].
1066///
1067/// discord.js counterpart: `Shard` (one process per shard there).
1068#[derive(Clone, Debug, PartialEq, Eq)]
1069#[non_exhaustive]
1070pub struct Cluster {
1071    /// The cluster's ID, from 0.
1072    pub id: u32,
1073    /// The shards it runs.
1074    pub shards: Range<u32>,
1075    /// Its process ID while it runs.
1076    pub pid: Option<u32>,
1077    /// Whether it is connected to the manager.
1078    pub connected: bool,
1079}
1080
1081/// An event of a [`ClusterManager`]: see [`ClusterManager::events`].
1082///
1083/// discord.js counterpart: the events of `ShardingManager` and `Shard` (`shardCreate`, `spawn`, `death`, …).
1084#[derive(Clone, Debug, PartialEq, Eq)]
1085#[non_exhaustive]
1086pub enum ClusterEvent {
1087    /// A cluster's process was started.
1088    ///
1089    /// discord.js counterpart: `ShardingManager#shardCreate` / `Shard#spawn`.
1090    Spawned {
1091        /// The cluster's ID.
1092        cluster: u32,
1093        /// Its process ID, if the system gave one.
1094        pid: Option<u32>,
1095    },
1096    /// A cluster's process connected to the manager.
1097    Connected {
1098        /// The cluster's ID.
1099        cluster: u32,
1100    },
1101    /// A cluster's process exited.
1102    ///
1103    /// discord.js counterpart: `Shard#death`.
1104    Exited {
1105        /// The cluster's ID.
1106        cluster: u32,
1107        /// How it exited.
1108        status: ExitStatus,
1109    },
1110    /// A cluster's process will be started again after `delay` ([`Restart`], D-306); a
1111    /// [`Spawned`](Self::Spawned) follows, unless the manager shuts down first.
1112    Restarting {
1113        /// The cluster's ID.
1114        cluster: u32,
1115        /// How long the manager waits before starting it.
1116        delay: Duration,
1117    },
1118}
1119
1120/// The stream of a [`ClusterManager`]'s events. Created by [`ClusterManager::events`].
1121///
1122/// Implements [`Stream`]; [`next`](Self::next) is provided so no extension trait is needed.
1123///
1124/// discord.js counterpart: `ShardingManager#on`.
1125#[derive(Debug)]
1126pub struct ClusterEvents {
1127    rx: mpsc::UnboundedReceiver<ClusterEvent>,
1128}
1129
1130impl ClusterEvents {
1131    /// Waits for the next event. Returns `None` once the manager has been dropped.
1132    ///
1133    /// discord.js counterpart: `ShardingManager#on`.
1134    pub async fn next(&mut self) -> Option<ClusterEvent> {
1135        self.rx.recv().await
1136    }
1137}
1138
1139impl Stream for ClusterEvents {
1140    type Item = ClusterEvent;
1141
1142    fn poll_next(mut self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<Option<ClusterEvent>> {
1143        self.rx.poll_recv(cx)
1144    }
1145}
1146
1147#[cfg(test)]
1148mod tests {
1149    use core::{ops::Range, time::Duration};
1150    use std::{net::SocketAddr, sync::Arc};
1151
1152    use tokio::net::TcpListener;
1153
1154    use djs_gateway::LocalIdentifyQueue;
1155    use djs_model::gateway::ShardId;
1156
1157    use std::collections::HashMap;
1158
1159    use serde_json::{Value, json};
1160
1161    use super::{
1162        ClusterEvent, ClusterManager, Session, State, Token, accept, lock, restart_delay, split,
1163    };
1164    use crate::{
1165        Shards,
1166        context::Shared,
1167        sharding::{
1168            ClusterAssignment, ClusterError,
1169            cluster::Gateway,
1170            command::{BoxFuture, Commands, Failure},
1171            ipc::{ToCluster, ToManager, read_frame, write_frame},
1172        },
1173    };
1174
1175    const STEP: Duration = Duration::from_secs(5);
1176
1177    #[test]
1178    fn shards_are_split_into_processes() {
1179        assert_eq!(split(0..4, 1), vec![0..1, 1..2, 2..3, 3..4]);
1180        assert_eq!(split(0..10, 4), vec![0..4, 4..8, 8..10]);
1181        assert_eq!(split(8..16, 8), vec![8..16]);
1182        assert_eq!(split(0..3, 10), vec![0..3]);
1183    }
1184
1185    /// The commands of the test clusters: `echo` returns its input, `hang` never answers.
1186    struct Echo;
1187
1188    impl Commands for Echo {
1189        fn call(&self, name: &str, input: Value) -> BoxFuture<'static, Result<Value, Failure>> {
1190            match name {
1191                "echo" => Box::pin(async move { Ok(input) }),
1192                "hang" => Box::pin(core::future::pending()),
1193                _ => Box::pin(async { Err(Failure::UnknownCommand) }),
1194            }
1195        }
1196    }
1197
1198    fn commands() -> Arc<dyn Commands> {
1199        Arc::new(Echo)
1200    }
1201
1202    fn gateway() -> Gateway {
1203        Gateway {
1204            url: "ws://127.0.0.1:9".into(),
1205            total: 2,
1206            max_concurrency: 1,
1207        }
1208    }
1209
1210    #[test]
1211    fn restart_delays_grow_until_a_process_runs_long_enough() {
1212        let (first, max) = (Duration::from_secs(1), Duration::from_secs(8));
1213        let quick = Duration::from_millis(10);
1214        let mut current = first;
1215        let mut delays = Vec::new();
1216        for _ in 0..6 {
1217            let (delay, next) = restart_delay(current, quick, first, max);
1218            delays.push(delay.as_secs());
1219            current = next;
1220        }
1221        assert_eq!(delays, [1, 2, 4, 8, 8, 8]);
1222        // A process that ran for the largest delay starts again from the first.
1223        assert_eq!(restart_delay(current, max, first, max), (first, first * 2));
1224    }
1225
1226    /// A manager with two clusters that accepts connections, without starting processes.
1227    async fn listening() -> (ClusterManager, SocketAddr, Token) {
1228        let manager = ClusterManager::builder("tok")
1229            .shards(Shards::Count(2))
1230            .command_timeout(Duration::from_millis(200))
1231            .build();
1232        *lock(&manager.inner.clusters) = [0..1, 1..2]
1233            .into_iter()
1234            .map(|shards: Range<u32>| State {
1235                shards,
1236                pid: None,
1237                sender: None,
1238                delay: Duration::from_secs(1),
1239                pending: HashMap::new(),
1240            })
1241            .collect();
1242        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
1243        let address = listener.local_addr().unwrap();
1244        let token = Token::generate();
1245        let session = Arc::new(Session {
1246            token: token.clone(),
1247            gateway: gateway(),
1248            identify: LocalIdentifyQueue::new(1),
1249        });
1250        tokio::spawn(accept(manager.clone(), listener, session));
1251        (manager, address, token)
1252    }
1253
1254    fn assignment(cluster: u32, address: SocketAddr, token: &str) -> ClusterAssignment {
1255        ClusterAssignment::new(
1256            cluster,
1257            cluster..cluster + 1,
1258            &gateway(),
1259            address,
1260            token.into(),
1261        )
1262    }
1263
1264    #[tokio::test]
1265    async fn only_the_processes_the_manager_started_connect() {
1266        let (manager, address, token) = listening().await;
1267        let mut events = manager.events();
1268        let shared = Arc::new(Shared::default());
1269
1270        // A wrong token, or a cluster the manager does not have, is refused.
1271        let refused = assignment(0, address, "not-the-token")
1272            .connect(Arc::clone(&shared), commands())
1273            .await;
1274        assert!(matches!(refused, Err(ClusterError::Refused)), "{refused:?}");
1275        let unknown = assignment(7, address, token.as_str())
1276            .connect(Arc::clone(&shared), commands())
1277            .await;
1278        assert!(matches!(unknown, Err(ClusterError::Refused)), "{unknown:?}");
1279        assert!(manager.clusters().iter().all(|cluster| !cluster.connected));
1280
1281        // The right token is welcomed, once per cluster.
1282        let connection = assignment(0, address, token.as_str())
1283            .connect(Arc::clone(&shared), commands())
1284            .await
1285            .unwrap();
1286        assert_eq!(
1287            events.next().await,
1288            Some(ClusterEvent::Connected { cluster: 0 })
1289        );
1290        let clusters = manager.clusters();
1291        assert!(clusters[0].connected && !clusters[1].connected);
1292        let second = assignment(0, address, token.as_str())
1293            .connect(Arc::new(Shared::default()), commands())
1294            .await;
1295        assert!(matches!(second, Err(ClusterError::Refused)), "{second:?}");
1296        assert!(!*shared.shutdown.borrow());
1297
1298        // A shutdown from the manager shuts the process's client down…
1299        let sender = lock(&manager.inner.clusters)[0].sender.clone().unwrap();
1300        sender.send(ToCluster::Shutdown).unwrap();
1301        let mut shutdown = shared.shutdown.subscribe();
1302        tokio::time::timeout(STEP, shutdown.wait_for(|stop| *stop))
1303            .await
1304            .unwrap()
1305            .unwrap();
1306        // …and once the process has gone, the cluster may connect again.
1307        drop(connection);
1308        tokio::time::timeout(STEP, async {
1309            while manager.clusters()[0].connected {
1310                tokio::time::sleep(Duration::from_millis(10)).await;
1311            }
1312        })
1313        .await
1314        .unwrap();
1315        let again = assignment(0, address, token.as_str())
1316            .connect(Arc::new(Shared::default()), commands())
1317            .await;
1318        assert!(again.is_ok(), "{again:?}");
1319    }
1320
1321    #[tokio::test]
1322    async fn turns_are_granted_for_the_clusters_own_shards() {
1323        let (_manager, address, token) = listening().await;
1324        let connection = assignment(1, address, token.as_str())
1325            .connect(Arc::new(Shared::default()), commands())
1326            .await
1327            .unwrap();
1328        let queue = connection.identify_queue();
1329        // Shard 0 is cluster 0's: the manager does not answer.
1330        let other = queue.wait_turn(ShardId::new(0, 2));
1331        assert!(
1332            tokio::time::timeout(Duration::from_millis(100), other)
1333                .await
1334                .is_err()
1335        );
1336        // Its own shard gets a turn at once: nothing has identified yet.
1337        tokio::time::timeout(STEP, queue.wait_turn(ShardId::new(1, 2)))
1338            .await
1339            .unwrap();
1340    }
1341
1342    #[tokio::test]
1343    async fn commands_reach_every_connected_cluster() {
1344        let (manager, address, token) = listening().await;
1345        let shared = Arc::new(Shared::default());
1346        let _connection = assignment(0, address, token.as_str())
1347            .connect(Arc::clone(&shared), commands())
1348            .await
1349            .unwrap();
1350        // Cluster 1 is not connected; the others' results stay usable.
1351        assert_eq!(
1352            manager.ask(None, "echo", json!({"n": 1})).await,
1353            [(0, Ok(json!({"n": 1}))), (1, Err(Failure::NotConnected))]
1354        );
1355        assert_eq!(
1356            manager.ask(Some(0), "nope", Value::Null).await,
1357            [(0, Err(Failure::UnknownCommand))]
1358        );
1359        assert_eq!(
1360            manager.ask(Some(9), "echo", Value::Null).await,
1361            [(9, Err(Failure::NotConnected))]
1362        );
1363        // No answer within the command timeout; the request is forgotten.
1364        assert_eq!(
1365            manager.ask(Some(0), "hang", Value::Null).await,
1366            [(0, Err(Failure::Timeout))]
1367        );
1368        assert!(lock(&manager.inner.clusters)[0].pending.is_empty());
1369
1370        // A cluster's own request goes through the manager to every cluster, itself too.
1371        let link = lock(&shared.link).clone().unwrap();
1372        assert_eq!(
1373            link.ask(None, "echo", json!(2)).await.unwrap(),
1374            [(0, Ok(json!(2))), (1, Err(Failure::NotConnected))]
1375        );
1376        assert_eq!(
1377            link.ask(Some(0), "echo", json!("one")).await.unwrap(),
1378            [(0, Ok(json!("one")))]
1379        );
1380    }
1381
1382    #[tokio::test]
1383    async fn losing_the_manager_shuts_the_client_down() {
1384        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
1385        let address = listener.local_addr().unwrap();
1386        let manager = tokio::spawn(async move {
1387            let (mut stream, _) = listener.accept().await.unwrap();
1388            let hello = read_frame::<_, ToManager>(&mut stream).await.unwrap();
1389            assert_eq!(
1390                hello,
1391                Some(ToManager::Hello {
1392                    cluster: 1,
1393                    token: "t".into()
1394                })
1395            );
1396            write_frame(&mut stream, &ToCluster::Welcome).await.unwrap();
1397            // Then the manager's process dies: its end of the connection closes.
1398        });
1399        let shared = Arc::new(Shared::default());
1400        let _connection = assignment(1, address, "t")
1401            .connect(Arc::clone(&shared), commands())
1402            .await
1403            .unwrap();
1404        manager.await.unwrap();
1405        let mut shutdown = shared.shutdown.subscribe();
1406        tokio::time::timeout(STEP, shutdown.wait_for(|stop| *stop))
1407            .await
1408            .unwrap()
1409            .unwrap();
1410    }
1411}