Skip to main content

djs_rs/sharding/
command.rs

1//! Named commands between clusters (D-286, D-307–D-309): the [`ClusterCommand`] trait, the
2//! per-cluster [`ClusterReply`], and how requests and results cross the processes.
3
4use core::{future::Future, pin::Pin};
5use std::sync::Arc;
6
7use serde::{Deserialize, Serialize, de::DeserializeOwned};
8use serde_json::Value;
9
10use super::ClusterError;
11
12/// A future boxed inside this crate (D-287).
13pub(crate) type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
14
15/// A command that clusters handle by name, with typed input and output (D-286, D-308): the
16/// typed replacement for discord.js's `broadcastEval`, which Rust cannot do (there is no
17/// code to evaluate at run time).
18///
19/// Implement it on a type of your own, in the code that both the manager and the cluster
20/// processes run (D-296: they are the same executable), so the name and the types cannot
21/// disagree. A cluster handles it with
22/// [`ClusterClient::handle`](super::ClusterClient::handle); the manager and the clusters send
23/// it with [`broadcast`](super::ClusterClient::broadcast) (every cluster) or
24/// [`send`](super::ClusterClient::send) (one), and the same methods on
25/// [`ClusterManager`](super::ClusterManager). The input and output cross the processes as
26/// JSON.
27///
28/// discord.js counterpart: the function given to `broadcastEval`.
29///
30/// # Examples
31///
32/// ```
33/// use djs_rs::sharding::ClusterCommand;
34///
35/// /// How many guilds a cluster has in its cache.
36/// struct GuildCount;
37///
38/// impl ClusterCommand for GuildCount {
39///     const NAME: &'static str = "guild_count";
40///     type Input = ();
41///     type Output = usize;
42/// }
43/// ```
44pub trait ClusterCommand: Send + Sync + 'static {
45    /// The name the command is sent and handled under; unique among a bot's commands. Names
46    /// starting with `djs-rs:` are reserved for the library's own.
47    const NAME: &'static str;
48    /// What the sender gives the handler.
49    type Input: Serialize + DeserializeOwned + Send + 'static;
50    /// What the handler returns to the sender.
51    type Output: Serialize + DeserializeOwned + Send + 'static;
52}
53
54/// One cluster's answer to a broadcast (D-309): its ID and its result, or why it gave none.
55///
56/// A broadcast returns one per cluster, by cluster ID; a cluster that is down or restarting
57/// fails alone. For all-or-nothing, collect the results:
58/// `replies.into_iter().map(|reply| reply.result).collect::<Result<Vec<_>, _>>()`.
59///
60/// discord.js counterpart: one element of the array `broadcastEval` resolves to.
61#[derive(Debug)]
62#[non_exhaustive]
63pub struct ClusterReply<T> {
64    /// The cluster that answered (or should have).
65    pub cluster: u32,
66    /// What its handler returned, or why there is no result.
67    pub result: Result<T, ClusterError>,
68}
69
70/// Why a cluster gave no result, as it crosses the processes.
71#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
72#[serde(tag = "error", rename_all = "snake_case")]
73pub(crate) enum Failure {
74    UnknownCommand,
75    Failed { message: String },
76    Timeout,
77    NotConnected,
78    Encoding { message: String },
79}
80
81impl From<Failure> for ClusterError {
82    fn from(failure: Failure) -> Self {
83        match failure {
84            Failure::UnknownCommand => Self::UnknownCommand,
85            Failure::Failed { message } => Self::CommandFailed(message),
86            Failure::Timeout => Self::Timeout,
87            Failure::NotConnected => Self::NotConnected,
88            Failure::Encoding { message } => Self::Encoding(message),
89        }
90    }
91}
92
93/// The results of one request, by cluster.
94pub(crate) type Replies = Vec<(u32, Result<Value, Failure>)>;
95
96/// What a cluster's connection calls for each request it receives: the client's handlers,
97/// behind a non-generic interface.
98pub(crate) trait Commands: Send + Sync {
99    /// Runs the handler of `name` on `input`.
100    fn call(&self, name: &str, input: Value) -> BoxFuture<'static, Result<Value, Failure>>;
101}
102
103/// A cluster's handler of one command, with its input and output still in JSON.
104pub(crate) type Handler<C> =
105    Arc<dyn Fn(C, Value) -> BoxFuture<'static, Result<Value, Failure>> + Send + Sync>;
106
107pub(crate) fn encode<T: Serialize>(value: &T) -> Result<Value, ClusterError> {
108    serde_json::to_value(value).map_err(|error| ClusterError::Encoding(error.to_string()))
109}
110
111fn decode<T: DeserializeOwned>(result: Result<Value, Failure>) -> Result<T, ClusterError> {
112    let value = result.map_err(ClusterError::from)?;
113    serde_json::from_value(value).map_err(|error| ClusterError::Encoding(error.to_string()))
114}
115
116/// The typed replies of a broadcast.
117pub(crate) fn decode_replies<T: DeserializeOwned>(replies: Replies) -> Vec<ClusterReply<T>> {
118    replies
119        .into_iter()
120        .map(|(cluster, result)| ClusterReply {
121            cluster,
122            result: decode(result),
123        })
124        .collect()
125}
126
127/// The typed reply of a request to one cluster.
128pub(crate) fn decode_one<T: DeserializeOwned>(replies: Replies) -> Result<T, ClusterError> {
129    replies
130        .into_iter()
131        .next()
132        .map_or(Err(ClusterError::NotConnected), |(_, result)| {
133            decode(result)
134        })
135}
136
137/// Wraps a typed handler into a [`Handler`]: decodes the input, runs it, encodes the output.
138pub(crate) fn erase<Cmd, C, F, Fut>(handler: F) -> Handler<C>
139where
140    Cmd: ClusterCommand,
141    C: Send + 'static,
142    F: Fn(C, Cmd::Input) -> Fut + Send + Sync + 'static,
143    Fut: Future<Output = Result<Cmd::Output, crate::HandlerError>> + Send + 'static,
144{
145    Arc::new(move |context: C, input: Value| {
146        let decoded = serde_json::from_value::<Cmd::Input>(input);
147        let future = decoded.map(|input| handler(context, input));
148        Box::pin(async move {
149            let future = future.map_err(|error| Failure::Encoding {
150                message: error.to_string(),
151            })?;
152            let output = future.await.map_err(|error| Failure::Failed {
153                message: error.to_string(),
154            })?;
155            serde_json::to_value(output).map_err(|error| Failure::Encoding {
156                message: error.to_string(),
157            })
158        })
159    })
160}
161
162#[cfg(test)]
163mod tests {
164    use serde_json::json;
165
166    use super::{ClusterCommand, Failure, decode_one, decode_replies, erase};
167    use crate::sharding::ClusterError;
168
169    struct Double;
170
171    impl ClusterCommand for Double {
172        const NAME: &'static str = "double";
173        type Input = u32;
174        type Output = u64;
175    }
176
177    #[tokio::test]
178    async fn handlers_decode_run_and_encode() {
179        let handler = erase::<Double, (), _, _>(|(), input| async move {
180            if input == 0 {
181                return Err("zero".into());
182            }
183            Ok(u64::from(input) * 2)
184        });
185        assert_eq!(handler((), json!(21)).await, Ok(json!(42)));
186        assert_eq!(
187            handler((), json!(0)).await,
188            Err(Failure::Failed {
189                message: "zero".into()
190            })
191        );
192        assert!(matches!(
193            handler((), json!("not a number")).await,
194            Err(Failure::Encoding { .. })
195        ));
196    }
197
198    #[test]
199    fn replies_keep_each_clusters_result() {
200        let replies = decode_replies::<u64>(vec![
201            (0, Ok(json!(2))),
202            (1, Err(Failure::Timeout)),
203            (2, Ok(json!("two"))),
204            (3, Err(Failure::UnknownCommand)),
205        ]);
206        assert_eq!(
207            replies
208                .iter()
209                .map(|reply| reply.cluster)
210                .collect::<Vec<_>>(),
211            [0, 1, 2, 3]
212        );
213        assert_eq!(replies[0].result.as_ref().unwrap(), &2);
214        assert!(matches!(replies[1].result, Err(ClusterError::Timeout)));
215        assert!(matches!(replies[2].result, Err(ClusterError::Encoding(_))));
216        assert!(matches!(
217            replies[3].result,
218            Err(ClusterError::UnknownCommand)
219        ));
220        assert_eq!(decode_one::<u64>(vec![(5, Ok(json!(7)))]).unwrap(), 7);
221        assert!(matches!(
222            decode_one::<u64>(Vec::new()),
223            Err(ClusterError::NotConnected)
224        ));
225    }
226
227    #[test]
228    fn failures_have_a_stable_wire_format() {
229        assert_eq!(
230            serde_json::to_value(Failure::Failed {
231                message: "m".into()
232            })
233            .unwrap(),
234            json!({"error": "failed", "message": "m"})
235        );
236        assert_eq!(
237            serde_json::to_value(Failure::NotConnected).unwrap(),
238            json!({"error": "not_connected"})
239        );
240    }
241}