Skip to main content

zaun_community_protocol/envelope/
error_body.rs

1//! The `error` object of a failed response (§7.2, §11).
2
3use serde::{Deserialize, Serialize};
4
5use super::{RateCategory, RateScope, Reason, Stream, VersionRange};
6use crate::error_code::ErrorCode;
7use crate::ids::ChannelId;
8
9/// An error object: `code`, `message`, and the code's extra fields placed next to `code`
10/// (§7.2, §11). Build it with the constructors (one per [`ErrorCode`], see `errors.rs`); they
11/// use fixed messages so no secret, connection detail, member key or other member's data can
12/// reach the wire (§11). The extras are boxed to keep `Result<_, ErrorBody>` small.
13#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
14pub struct ErrorBody {
15    /// What went wrong; clients branch on this only.
16    pub code: ErrorCode,
17    /// Human-readable English text; informative, never branched on.
18    pub message: String,
19    /// The code's extra fields, serialised next to `code` (absent ones are omitted).
20    #[serde(flatten)]
21    pub extras: Box<ErrorExtras>,
22}
23
24/// The extra fields of §11. Each applies to the codes named on it.
25#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
26pub struct ErrorExtras {
27    /// `BAD_REQUEST`: the offending field, when known (`"body.content"`, `"request_id"`).
28    #[serde(default, skip_serializing_if = "Option::is_none")]
29    pub field: Option<String>,
30    /// `PAYLOAD_TOO_LARGE`: the limit exceeded.
31    #[serde(default, skip_serializing_if = "Option::is_none")]
32    pub limit: Option<u64>,
33    /// `UNSUPPORTED_VERSION`: the host's range.
34    #[serde(default, skip_serializing_if = "Option::is_none")]
35    pub supported: Option<VersionRange>,
36    /// `UNSUPPORTED_FEATURE`: the feature.
37    #[serde(default, skip_serializing_if = "Option::is_none")]
38    pub feature: Option<String>,
39    /// `FORBIDDEN`: the missing permission bits, as a JSON decimal string.
40    #[serde(default, skip_serializing_if = "Option::is_none", with = "opt_decimal")]
41    pub missing: Option<u64>,
42    /// `FORBIDDEN` (`hierarchy`, `probation`, `lockdown`) or `CONFLICT` reason.
43    #[serde(default, skip_serializing_if = "Option::is_none")]
44    pub reason: Option<Reason>,
45    /// `SUSPENDED` / `TIMED_OUT`: end of the restriction, ms since the Unix epoch.
46    #[serde(default, skip_serializing_if = "Option::is_none")]
47    pub until: Option<u64>,
48    /// `SLOWMODE_ACTIVE`, `RATE_LIMITED`, `BUSY`: milliseconds to wait.
49    #[serde(default, skip_serializing_if = "Option::is_none")]
50    pub retry_after_ms: Option<u64>,
51    /// `RATE_LIMITED`: the scope whose limit was hit.
52    #[serde(default, skip_serializing_if = "Option::is_none")]
53    pub scope: Option<RateScope>,
54    /// `RATE_LIMITED`: the category, when one applies.
55    #[serde(default, skip_serializing_if = "Option::is_none")]
56    pub category: Option<RateCategory>,
57    /// `RESYNC_REQUIRED`: the stream to resynchronise.
58    #[serde(default, skip_serializing_if = "Option::is_none")]
59    pub stream: Option<Stream>,
60    /// `RESYNC_REQUIRED`: the channel, for a channel stream.
61    #[serde(default, skip_serializing_if = "Option::is_none")]
62    pub channel_id: Option<ChannelId>,
63    /// `INVALID_SIGNATURE`: which signed object failed (`"descriptor"`, `"delegation"`, …).
64    #[serde(default, skip_serializing_if = "Option::is_none")]
65    pub object: Option<String>,
66}
67
68/// `Option<u64>` as an optional canonical decimal string (`json::u64_decimal` takes `u64`).
69mod opt_decimal {
70    use serde::{Deserialize, Deserializer, Serializer, de::Error as _};
71
72    use crate::json::u64_decimal;
73
74    // serde's `with` calls `serialize(&Option<u64>, _)`, so the reference is required.
75    #[allow(clippy::ref_option, clippy::trivially_copy_pass_by_ref)]
76    pub(super) fn serialize<S: Serializer>(value: &Option<u64>, s: S) -> Result<S::Ok, S::Error> {
77        match value {
78            Some(v) => u64_decimal::serialize(v, s),
79            None => s.serialize_none(),
80        }
81    }
82
83    pub(super) fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Option<u64>, D::Error> {
84        let text = Option::<std::borrow::Cow<'de, str>>::deserialize(d)?;
85        text.map(|t| {
86            u64_decimal::parse(&t)
87                .ok_or_else(|| D::Error::custom("expected a canonical decimal string"))
88        })
89        .transpose()
90    }
91}