Skip to main content

zaun_community_protocol/envelope/
response.rs

1//! Response envelope (host → client, §7.2).
2
3use serde::{Deserialize, Deserializer, Serialize, Serializer, de::Error as _};
4use serde_json::value::RawValue;
5
6use super::{ErrorBody, RESPONSE_TYPE, raw};
7use crate::ids::RequestId;
8use crate::limits::PROTOCOL_VERSION;
9
10/// The result carried by a response.
11#[derive(Debug, Clone)]
12pub enum Outcome {
13    /// `"ok": true` with the command's response body.
14    Ok(Box<RawValue>),
15    /// `"ok": false` with an error object.
16    Err(ErrorBody),
17}
18
19/// `{ "v", "type": "response", "request_id", "ok", "body" | "error" }` (§7.2).
20///
21/// `request_id` is `null` when the command's id could not be read (§5.3).
22#[derive(Debug, Clone)]
23pub struct ResponseEnvelope {
24    /// Envelope version.
25    pub v: u16,
26    /// The command's `request_id`, or `None` (`null`).
27    pub request_id: Option<RequestId>,
28    /// Success body or error.
29    pub outcome: Outcome,
30}
31
32impl ResponseEnvelope {
33    /// A success response at [`PROTOCOL_VERSION`].
34    #[must_use]
35    pub fn ok(request_id: RequestId, body: Box<RawValue>) -> Self {
36        Self {
37            v: PROTOCOL_VERSION,
38            request_id: Some(request_id),
39            outcome: Outcome::Ok(body),
40        }
41    }
42
43    /// A success response whose body is serialised from `body`.
44    ///
45    /// # Errors
46    /// `body` fails to serialise as JSON.
47    pub fn ok_json<T: Serialize>(request_id: RequestId, body: &T) -> serde_json::Result<Self> {
48        serde_json::value::to_raw_value(body).map(|raw| Self::ok(request_id, raw))
49    }
50
51    /// An error response at [`PROTOCOL_VERSION`].
52    #[must_use]
53    pub fn error(request_id: Option<RequestId>, error: ErrorBody) -> Self {
54        Self {
55            v: PROTOCOL_VERSION,
56            request_id,
57            outcome: Outcome::Err(error),
58        }
59    }
60
61    /// The error, if this is a failure.
62    #[must_use]
63    pub fn error_body(&self) -> Option<&ErrorBody> {
64        match &self.outcome {
65            Outcome::Ok(_) => None,
66            Outcome::Err(e) => Some(e),
67        }
68    }
69
70    /// Whether this response is stored as the idempotency record (§7.3): every success and
71    /// every error except `BUSY`, `RATE_LIMITED`, `INTERNAL` and `SLOWMODE_ACTIVE`.
72    #[must_use]
73    pub fn is_recorded(&self) -> bool {
74        self.error_body().is_none_or(ErrorBody::is_recorded)
75    }
76}
77
78#[derive(Serialize)]
79struct WireOut<'a> {
80    v: u16,
81    #[serde(rename = "type")]
82    kind: &'static str,
83    request_id: Option<&'a RequestId>,
84    ok: bool,
85    #[serde(skip_serializing_if = "Option::is_none")]
86    body: Option<&'a RawValue>,
87    #[serde(skip_serializing_if = "Option::is_none")]
88    error: Option<&'a ErrorBody>,
89}
90
91impl Serialize for ResponseEnvelope {
92    fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
93        let (body, error) = match &self.outcome {
94            Outcome::Ok(body) => (Some(&**body), None),
95            Outcome::Err(e) => (None, Some(e)),
96        };
97        WireOut {
98            v: self.v,
99            kind: RESPONSE_TYPE,
100            request_id: self.request_id.as_ref(),
101            ok: error.is_none(),
102            body,
103            error,
104        }
105        .serialize(s)
106    }
107}
108
109impl<'de> Deserialize<'de> for ResponseEnvelope {
110    fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
111        let wire: Wire = raw::object_only(d)?;
112        Self::try_from(wire).map_err(D::Error::custom)
113    }
114}
115
116#[derive(Deserialize)]
117struct Wire {
118    v: u16,
119    #[serde(rename = "type")]
120    kind: String,
121    #[serde(deserialize_with = "raw::nullable")]
122    request_id: Option<RequestId>,
123    ok: bool,
124    #[serde(default)]
125    body: Option<Box<RawValue>>,
126    #[serde(default)]
127    error: Option<ErrorBody>,
128}
129
130impl TryFrom<Wire> for ResponseEnvelope {
131    type Error = &'static str;
132
133    fn try_from(w: Wire) -> Result<Self, Self::Error> {
134        if w.kind != RESPONSE_TYPE {
135            return Err("not a response envelope");
136        }
137        let outcome = match (w.ok, w.body, w.error) {
138            (true, Some(body), _) if body.get().starts_with('{') => Outcome::Ok(body),
139            (false, _, Some(error)) => Outcome::Err(error),
140            _ => return Err("response without a matching body or error"),
141        };
142        Ok(Self {
143            v: w.v,
144            request_id: w.request_id,
145            outcome,
146        })
147    }
148}