Skip to main content

zaun_community_protocol/envelope/
command_envelope.rs

1//! Command envelope (client → host, §7.1).
2
3use serde::Serialize;
4use serde_json::value::RawValue;
5
6use super::{BodyHash, is_mutating};
7use crate::ids::{ChannelId, CommunityId, RequestId};
8use crate::limits::PROTOCOL_VERSION;
9
10/// Prefix of ephemeral signal commands, which carry `request_id: null` and get no response
11/// (§10.5).
12pub(super) const SIGNAL_PREFIX: &str = "signal.";
13
14/// `{ "v", "type", "request_id", "community_id", "channel_id"?, "body" }` (§7.1).
15///
16/// Parse received text with [`super::parse_command`]; serialise with serde (client side).
17/// `body` is the command's body object exactly as received, for the `command` module to parse
18/// by `type` and for the idempotency hash (§7.3).
19#[derive(Debug, Clone, Serialize)]
20pub struct CommandEnvelope {
21    /// Envelope version.
22    pub v: u16,
23    /// Command name (§8).
24    #[serde(rename = "type")]
25    pub kind: String,
26    /// Correlation id; `None` (`null`) only for `signal.*` commands.
27    pub request_id: Option<RequestId>,
28    /// The bound community, or the target of `community.create` / `invite.redeem`; else `null`.
29    pub community_id: Option<CommunityId>,
30    /// Present for channel-scoped commands.
31    #[serde(skip_serializing_if = "Option::is_none")]
32    pub channel_id: Option<ChannelId>,
33    /// The body object, `{}` when empty.
34    pub body: Box<RawValue>,
35}
36
37impl CommandEnvelope {
38    /// A command at [`PROTOCOL_VERSION`].
39    #[must_use]
40    pub fn new(
41        kind: impl Into<String>,
42        request_id: Option<RequestId>,
43        community_id: Option<CommunityId>,
44        channel_id: Option<ChannelId>,
45        body: Box<RawValue>,
46    ) -> Self {
47        Self {
48            v: PROTOCOL_VERSION,
49            kind: kind.into(),
50            request_id,
51            community_id,
52            channel_id,
53            body,
54        }
55    }
56
57    /// Whether this is an ephemeral signal (`signal.*`): no response, no idempotency record.
58    #[must_use]
59    pub fn is_signal(&self) -> bool {
60        self.kind.starts_with(SIGNAL_PREFIX)
61    }
62
63    /// Whether the command is mutating, hence idempotency-recorded (§7.3).
64    #[must_use]
65    pub fn is_mutating(&self) -> bool {
66        is_mutating(&self.kind)
67    }
68
69    /// SHA3-256 of the body JSON text as received (§7.3).
70    #[must_use]
71    pub fn body_hash(&self) -> BodyHash {
72        BodyHash::of(&self.body)
73    }
74}