1use 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
48const HELLO_TIMEOUT: Duration = Duration::from_secs(10);
50
51const SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(30);
54
55const COMMAND_TIMEOUT: Duration = Duration::from_secs(30);
57
58const RESTART_DELAY: (Duration, Duration) = (Duration::from_secs(1), Duration::from_secs(60));
60
61type Exit = (u32, io::Result<ExitStatus>, Duration);
63
64type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
65
66#[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 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#[derive(Debug)]
128struct State {
129 shards: Range<u32>,
130 pid: Option<u32>,
131 sender: Option<mpsc::UnboundedSender<ToCluster>>,
133 delay: Duration,
135 pending: HashMap<u64, oneshot::Sender<Result<Value, Failure>>>,
137}
138
139impl ClusterManager {
140 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 pub fn spawn(&self) -> impl Future<Output = Result<(), ClusterError>> + Send + '_ {
200 boxed(self.run())
201 }
202
203 pub fn shutdown(&self) {
210 self.inner.shutdown.send_replace(true);
211 }
212
213 #[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 #[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 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 pub async fn stats(&self) -> Result<Vec<ClusterReply<super::ClusterStats>>, ClusterError> {
293 self.broadcast::<super::Stats>(()).await
294 }
295
296 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 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 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 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 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
509struct Run<'a> {
512 manager: &'a ClusterManager,
513 launch: Launch,
514 session: Arc<Session>,
515 kill: watch::Sender<bool>,
517 processes: JoinSet<Exit>,
518 restarts: JoinSet<u32>,
520}
521
522impl Run<'_> {
523 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 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 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 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 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 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
679fn 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
691struct Launch {
693 executable: PathBuf,
694 args: Vec<OsString>,
695 address: SocketAddr,
696}
697
698#[derive(Debug)]
700struct Session {
701 token: Token,
703 gateway: Gateway,
704 identify: LocalIdentifyQueue,
706}
707
708fn boxed<'a, T>(future: impl Future<Output = T> + Send + 'a) -> BoxFuture<'a, T> {
710 Box::pin(future)
711}
712
713fn 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
726async fn accept(manager: ClusterManager, listener: TcpListener, session: Arc<Session>) {
728 loop {
729 let Ok((stream, _)) = listener.accept().await else {
730 tokio::time::sleep(Duration::from_millis(100)).await;
732 continue;
733 };
734 tokio::spawn(handshake(manager.clone(), stream, Arc::clone(&session)));
735 }
736}
737
738async 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 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 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 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
814async 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 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#[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 pub fn rest(mut self, rest: Rest) -> Self {
900 self.rest = Some(rest);
901 self
902 }
903
904 #[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 #[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 pub fn executable(mut self, path: impl Into<PathBuf>) -> Self {
946 self.executable = Some(path.into());
947 self
948 }
949
950 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 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 pub const fn shutdown_timeout(mut self, timeout: Duration) -> Self {
972 self.shutdown_timeout = timeout;
973 self
974 }
975
976 pub const fn restart(mut self, restart: Restart) -> Self {
981 self.restart = restart;
982 self
983 }
984
985 #[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 pub const fn command_timeout(mut self, timeout: Duration) -> Self {
1012 self.command_timeout = timeout;
1013 self
1014 }
1015
1016 #[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#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1051#[non_exhaustive]
1052pub enum Restart {
1053 #[default]
1057 OnFailure,
1058 Always,
1060 Never,
1062}
1063
1064#[derive(Clone, Debug, PartialEq, Eq)]
1069#[non_exhaustive]
1070pub struct Cluster {
1071 pub id: u32,
1073 pub shards: Range<u32>,
1075 pub pid: Option<u32>,
1077 pub connected: bool,
1079}
1080
1081#[derive(Clone, Debug, PartialEq, Eq)]
1085#[non_exhaustive]
1086pub enum ClusterEvent {
1087 Spawned {
1091 cluster: u32,
1093 pid: Option<u32>,
1095 },
1096 Connected {
1098 cluster: u32,
1100 },
1101 Exited {
1105 cluster: u32,
1107 status: ExitStatus,
1109 },
1110 Restarting {
1113 cluster: u32,
1115 delay: Duration,
1117 },
1118}
1119
1120#[derive(Debug)]
1126pub struct ClusterEvents {
1127 rx: mpsc::UnboundedReceiver<ClusterEvent>,
1128}
1129
1130impl ClusterEvents {
1131 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 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 assert_eq!(restart_delay(current, max, first, max), (first, first * 2));
1224 }
1225
1226 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 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 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 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 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 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 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 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 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 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 });
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}