Skip to main content

nk_core/message/
relay.rs

1//! Relay → client messages.
2
3use alloc::borrow::Cow;
4use alloc::string::String;
5use core::fmt;
6
7use serde::de::{Error as DeError, SeqAccess, Visitor};
8use serde::ser::SerializeSeq;
9use serde::{Deserialize, Deserializer, Serialize, Serializer};
10
11use super::{
12    CountResult, Error, Result, SubscriptionId, end, event_item, parse_neg_hex, read_type,
13    string_item, sub_id,
14};
15use crate::event::{Event, EventId, canonical};
16
17/// Relay → client messages.
18#[non_exhaustive]
19#[derive(Clone, Debug, PartialEq, Eq)]
20pub enum RelayMessage<'a> {
21    /// `["EVENT", <id>, <event>]` — an event matching a subscription.
22    Event {
23        /// Subscription id.
24        subscription_id: Cow<'a, SubscriptionId>,
25        /// The signed event.
26        event: Cow<'a, Event>,
27    },
28    /// `["OK", <event id>, <accepted>, <message>]`.
29    Ok {
30        /// The acknowledged event id (64 lowercase hex on the wire).
31        event_id: EventId,
32        /// Whether the relay stored the event.
33        accepted: bool,
34        /// The machine-readable prefix + human-readable detail.
35        message: Cow<'a, str>,
36    },
37    /// `["EOSE", <id>]` — end of stored events.
38    Eose(Cow<'a, SubscriptionId>),
39    /// `["CLOSED", <id>, <message>]` — subscription closed by the relay.
40    Closed {
41        /// Subscription id.
42        subscription_id: Cow<'a, SubscriptionId>,
43        /// The machine-readable prefix + human-readable detail.
44        message: Cow<'a, str>,
45    },
46    /// `["NOTICE", <message>]` — a free-form notice.
47    Notice(Cow<'a, str>),
48    /// `["AUTH", <challenge>]` — a NIP-42 auth challenge.
49    Auth {
50        /// The challenge string.
51        challenge: Cow<'a, str>,
52    },
53    /// `["COUNT", <id>, <result>]` — a NIP-45 count reply.
54    Count {
55        /// Subscription id.
56        subscription_id: Cow<'a, SubscriptionId>,
57        /// The count payload.
58        result: CountResult,
59    },
60    /// `["NEG-MSG", <id>, <hex>]` — a NIP-77 sync answer.
61    NegMsg {
62        /// Subscription id.
63        subscription_id: Cow<'a, SubscriptionId>,
64        /// The negentropy message (non-empty, even-length hex).
65        message: Cow<'a, str>,
66    },
67    /// `["NEG-ERR", <id>, <message>]` — a NIP-77 sync failure.
68    NegErr {
69        /// Subscription id.
70        subscription_id: Cow<'a, SubscriptionId>,
71        /// The error detail.
72        message: Cow<'a, str>,
73    },
74}
75
76const TYPES: &[&str] = &[
77    "EVENT", "OK", "EOSE", "CLOSED", "NOTICE", "AUTH", "COUNT", "NEG-MSG", "NEG-ERR",
78];
79
80const fn bool_str(value: bool) -> &'static str {
81    if value { "true" } else { "false" }
82}
83
84impl RelayMessage<'_> {
85    /// The canonical NIP-01 JSON wire form.
86    #[must_use]
87    pub fn to_json(&self) -> String {
88        let mut out = String::new();
89        match self {
90            Self::Event {
91                subscription_id,
92                event,
93            } => {
94                out.push_str("[\"EVENT\",");
95                canonical::push_json_string(subscription_id.as_str(), &mut out);
96                out.push(',');
97                canonical::write_signed(event, &mut out);
98                out.push(']');
99            }
100            Self::Ok {
101                event_id,
102                accepted,
103                message,
104            } => {
105                out.push_str("[\"OK\",\"");
106                canonical::push_hex(event_id.as_bytes(), &mut out);
107                out.push_str("\",");
108                out.push_str(bool_str(*accepted));
109                out.push(',');
110                canonical::push_json_string(message, &mut out);
111                out.push(']');
112            }
113            Self::Eose(subscription_id) => {
114                out.push_str("[\"EOSE\",");
115                canonical::push_json_string(subscription_id.as_str(), &mut out);
116                out.push(']');
117            }
118            Self::Closed {
119                subscription_id,
120                message,
121            } => {
122                out.push_str("[\"CLOSED\",");
123                canonical::push_json_string(subscription_id.as_str(), &mut out);
124                out.push(',');
125                canonical::push_json_string(message, &mut out);
126                out.push(']');
127            }
128            Self::Notice(message) => {
129                out.push_str("[\"NOTICE\",");
130                canonical::push_json_string(message, &mut out);
131                out.push(']');
132            }
133            Self::Auth { challenge } => {
134                out.push_str("[\"AUTH\",");
135                canonical::push_json_string(challenge, &mut out);
136                out.push(']');
137            }
138            Self::Count {
139                subscription_id,
140                result,
141            } => {
142                out.push_str("[\"COUNT\",");
143                canonical::push_json_string(subscription_id.as_str(), &mut out);
144                out.push_str(",{\"count\":");
145                canonical::push_u64(result.count, &mut out);
146                if let Some(approximate) = result.approximate {
147                    out.push_str(",\"approximate\":");
148                    out.push_str(bool_str(approximate));
149                }
150                if let Some(hll) = &result.hll {
151                    out.push_str(",\"hll\":\"");
152                    canonical::push_hex(&hll.0, &mut out);
153                    out.push('"');
154                }
155                out.push_str("}]");
156            }
157            Self::NegMsg {
158                subscription_id,
159                message,
160            } => {
161                out.push_str("[\"NEG-MSG\",");
162                canonical::push_json_string(subscription_id.as_str(), &mut out);
163                out.push(',');
164                canonical::push_json_string(message, &mut out);
165                out.push(']');
166            }
167            Self::NegErr {
168                subscription_id,
169                message,
170            } => {
171                out.push_str("[\"NEG-ERR\",");
172                canonical::push_json_string(subscription_id.as_str(), &mut out);
173                out.push(',');
174                canonical::push_json_string(message, &mut out);
175                out.push(']');
176            }
177        }
178        out
179    }
180
181    /// Parses a relay → client JSON message.
182    ///
183    /// # Errors
184    ///
185    /// The same errors as [`crate::message::ClientMessage::from_json`]
186    /// except [`Error::ObsoleteNegOpen`]. `OK` requires a 64-char lowercase
187    /// hex event id; `COUNT` ignores non-bool `approximate` and non-512-hex
188    /// `hll` instead of failing.
189    pub fn from_json(raw: &str) -> Result<RelayMessage<'static>> {
190        serde_json::from_str(raw).map_err(|e| Error::InvalidJson {
191            source: crate::json::JsonError::from(e),
192        })
193    }
194
195    /// Converts every borrowed field to owned, giving a `'static` message.
196    #[must_use]
197    pub fn into_owned(self) -> RelayMessage<'static> {
198        match self {
199            Self::Event {
200                subscription_id,
201                event,
202            } => RelayMessage::Event {
203                subscription_id: Cow::Owned(subscription_id.into_owned()),
204                event: Cow::Owned(event.into_owned()),
205            },
206            Self::Ok {
207                event_id,
208                accepted,
209                message,
210            } => RelayMessage::Ok {
211                event_id,
212                accepted,
213                message: Cow::Owned(message.into_owned()),
214            },
215            Self::Eose(id) => RelayMessage::Eose(Cow::Owned(id.into_owned())),
216            Self::Closed {
217                subscription_id,
218                message,
219            } => RelayMessage::Closed {
220                subscription_id: Cow::Owned(subscription_id.into_owned()),
221                message: Cow::Owned(message.into_owned()),
222            },
223            Self::Notice(message) => RelayMessage::Notice(Cow::Owned(message.into_owned())),
224            Self::Auth { challenge } => RelayMessage::Auth {
225                challenge: Cow::Owned(challenge.into_owned()),
226            },
227            Self::Count {
228                subscription_id,
229                result,
230            } => RelayMessage::Count {
231                subscription_id: Cow::Owned(subscription_id.into_owned()),
232                result,
233            },
234            Self::NegMsg {
235                subscription_id,
236                message,
237            } => RelayMessage::NegMsg {
238                subscription_id: Cow::Owned(subscription_id.into_owned()),
239                message: Cow::Owned(message.into_owned()),
240            },
241            Self::NegErr {
242                subscription_id,
243                message,
244            } => RelayMessage::NegErr {
245                subscription_id: Cow::Owned(subscription_id.into_owned()),
246                message: Cow::Owned(message.into_owned()),
247            },
248        }
249    }
250}
251
252impl Serialize for RelayMessage<'_> {
253    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
254    where
255        S: Serializer,
256    {
257        match self {
258            Self::Event {
259                subscription_id,
260                event,
261            } => {
262                let mut seq = serializer.serialize_seq(Some(3))?;
263                seq.serialize_element("EVENT")?;
264                seq.serialize_element(&**subscription_id)?;
265                seq.serialize_element(&**event)?;
266                seq.end()
267            }
268            Self::Ok {
269                event_id,
270                accepted,
271                message,
272            } => {
273                let mut seq = serializer.serialize_seq(Some(4))?;
274                seq.serialize_element("OK")?;
275                seq.serialize_element(event_id)?;
276                seq.serialize_element(accepted)?;
277                seq.serialize_element(&**message)?;
278                seq.end()
279            }
280            Self::Eose(subscription_id) => {
281                let mut seq = serializer.serialize_seq(Some(2))?;
282                seq.serialize_element("EOSE")?;
283                seq.serialize_element(&**subscription_id)?;
284                seq.end()
285            }
286            Self::Closed {
287                subscription_id,
288                message,
289            } => {
290                let mut seq = serializer.serialize_seq(Some(3))?;
291                seq.serialize_element("CLOSED")?;
292                seq.serialize_element(&**subscription_id)?;
293                seq.serialize_element(&**message)?;
294                seq.end()
295            }
296            Self::Notice(message) => {
297                let mut seq = serializer.serialize_seq(Some(2))?;
298                seq.serialize_element("NOTICE")?;
299                seq.serialize_element(&**message)?;
300                seq.end()
301            }
302            Self::Auth { challenge } => {
303                let mut seq = serializer.serialize_seq(Some(2))?;
304                seq.serialize_element("AUTH")?;
305                seq.serialize_element(&**challenge)?;
306                seq.end()
307            }
308            Self::Count {
309                subscription_id,
310                result,
311            } => {
312                let mut seq = serializer.serialize_seq(Some(3))?;
313                seq.serialize_element("COUNT")?;
314                seq.serialize_element(&**subscription_id)?;
315                seq.serialize_element(result)?;
316                seq.end()
317            }
318            Self::NegMsg {
319                subscription_id,
320                message,
321            } => {
322                let mut seq = serializer.serialize_seq(Some(3))?;
323                seq.serialize_element("NEG-MSG")?;
324                seq.serialize_element(&**subscription_id)?;
325                seq.serialize_element(&**message)?;
326                seq.end()
327            }
328            Self::NegErr {
329                subscription_id,
330                message,
331            } => {
332                let mut seq = serializer.serialize_seq(Some(3))?;
333                seq.serialize_element("NEG-ERR")?;
334                seq.serialize_element(&**subscription_id)?;
335                seq.serialize_element(&**message)?;
336                seq.end()
337            }
338        }
339    }
340}
341
342impl<'de> Deserialize<'de> for RelayMessage<'static> {
343    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
344    where
345        D: Deserializer<'de>,
346    {
347        struct MessageVisitor;
348
349        impl<'de> Visitor<'de> for MessageVisitor {
350            type Value = RelayMessage<'static>;
351
352            fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
353                f.write_str("a relay message array")
354            }
355
356            #[allow(
357                clippy::excessive_nesting,
358                reason = "a message is a labelled seq of variants"
359            )]
360            fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<Self::Value, A::Error> {
361                let ty = read_type(&mut seq, TYPES)?;
362                match ty {
363                    "EVENT" => {
364                        let subscription_id = sub_id(&mut seq, ty)?;
365                        let event = event_item(&mut seq, ty)?;
366                        end(&mut seq, ty)?;
367                        Ok(RelayMessage::Event {
368                            subscription_id: Cow::Owned(subscription_id),
369                            event: Cow::Owned(event),
370                        })
371                    }
372                    "OK" => {
373                        let event_id = seq
374                            .next_element::<EventId>()?
375                            .ok_or_else(|| DeError::custom(Error::InvalidMessage { ty }))?;
376                        let accepted = seq
377                            .next_element::<bool>()?
378                            .ok_or_else(|| DeError::custom(Error::InvalidMessage { ty }))?;
379                        let message = string_item(&mut seq, ty)?;
380                        end(&mut seq, ty)?;
381                        Ok(RelayMessage::Ok {
382                            event_id,
383                            accepted,
384                            message: Cow::Owned(message),
385                        })
386                    }
387                    "EOSE" => {
388                        let id = sub_id(&mut seq, ty)?;
389                        end(&mut seq, ty)?;
390                        Ok(RelayMessage::Eose(Cow::Owned(id)))
391                    }
392                    "CLOSED" => {
393                        let subscription_id = sub_id(&mut seq, ty)?;
394                        let message = string_item(&mut seq, ty)?;
395                        end(&mut seq, ty)?;
396                        Ok(RelayMessage::Closed {
397                            subscription_id: Cow::Owned(subscription_id),
398                            message: Cow::Owned(message),
399                        })
400                    }
401                    "NOTICE" => {
402                        let message = string_item(&mut seq, ty)?;
403                        end(&mut seq, ty)?;
404                        Ok(RelayMessage::Notice(Cow::Owned(message)))
405                    }
406                    "AUTH" => {
407                        let challenge = string_item(&mut seq, ty)?;
408                        end(&mut seq, ty)?;
409                        Ok(RelayMessage::Auth {
410                            challenge: Cow::Owned(challenge),
411                        })
412                    }
413                    "COUNT" => {
414                        let subscription_id = sub_id(&mut seq, ty)?;
415                        let result = seq
416                            .next_element::<CountResult>()?
417                            .ok_or_else(|| DeError::custom(Error::InvalidMessage { ty }))?;
418                        end(&mut seq, ty)?;
419                        Ok(RelayMessage::Count {
420                            subscription_id: Cow::Owned(subscription_id),
421                            result,
422                        })
423                    }
424                    "NEG-MSG" => {
425                        let subscription_id = sub_id(&mut seq, ty)?;
426                        let message =
427                            parse_neg_hex(&string_item(&mut seq, ty)?).map_err(DeError::custom)?;
428                        end(&mut seq, ty)?;
429                        Ok(RelayMessage::NegMsg {
430                            subscription_id: Cow::Owned(subscription_id),
431                            message: Cow::Owned(message),
432                        })
433                    }
434                    "NEG-ERR" => {
435                        let subscription_id = sub_id(&mut seq, ty)?;
436                        let message = string_item(&mut seq, ty)?;
437                        end(&mut seq, ty)?;
438                        Ok(RelayMessage::NegErr {
439                            subscription_id: Cow::Owned(subscription_id),
440                            message: Cow::Owned(message),
441                        })
442                    }
443                    _ => Err(DeError::custom(Error::InvalidMessage { ty })),
444                }
445            }
446        }
447
448        deserializer.deserialize_seq(MessageVisitor)
449    }
450}