Skip to main content

zaun_community_protocol/envelope/
idempotency.rs

1//! Request correlation and idempotency (§7.3).
2
3use std::fmt;
4
5use serde_json::value::RawValue;
6use sha3::{Digest, Sha3_256};
7
8use super::ResponseEnvelope;
9use crate::b64;
10use crate::ids::{CommunityId, MemberId, RequestId};
11
12/// Whether a command `type` is mutating, hence idempotent and recorded (§7.3): every command
13/// except `session.hello`, `*.get`, `*.list`, `message.history`, `audit.list`, `member.bans`,
14/// `membership.pending`, `invite.uses`, `community.rotations`, `attachment.download`,
15/// `voice.signal`, `voice.keys`, `sync.*` and `signal.*`. `voice.signal` and `voice.keys`
16/// change nothing at the host: they are relayed live, and a retry is relayed again.
17#[must_use]
18pub fn is_mutating(kind: &str) -> bool {
19    let read_only = matches!(
20        kind,
21        "session.hello"
22            | "message.history"
23            | "audit.list"
24            | "member.bans"
25            | "membership.pending"
26            | "invite.uses"
27            | "community.rotations"
28            | "attachment.download"
29            | "voice.signal"
30            | "voice.keys"
31    ) || kind.ends_with(".get")
32        || kind.ends_with(".list")
33        || kind.starts_with("sync.")
34        || kind.starts_with("signal.");
35    !read_only
36}
37
38/// Whether `response` is stored in the idempotency record (§7.3); see
39/// [`ResponseEnvelope::is_recorded`].
40#[must_use]
41pub fn is_recorded(response: &ResponseEnvelope) -> bool {
42    response.is_recorded()
43}
44
45/// The key an idempotency record is stored under (§7.3). `C` is the host's opaque connection
46/// id, used only for unbound connections.
47#[derive(Debug, Clone, PartialEq, Eq, Hash)]
48pub enum IdempotencyKey<C> {
49    /// A bound connection: `(community_id, member_id, request_id)`.
50    Bound {
51        /// The binding's community.
52        community_id: CommunityId,
53        /// The binding's member.
54        member_id: MemberId,
55        /// The command's id.
56        request_id: RequestId,
57    },
58    /// An unbound connection: `(connection, request_id)`.
59    Unbound {
60        /// The host's connection id.
61        connection: C,
62        /// The command's id.
63        request_id: RequestId,
64    },
65}
66
67/// SHA3-256 of a command's `body` JSON text **exactly as received** (§7.3): reformatting the
68/// same JSON gives a different hash, which is why retries must resend byte-identical bodies.
69#[derive(Clone, Copy, PartialEq, Eq, Hash)]
70pub struct BodyHash([u8; 32]);
71
72impl BodyHash {
73    /// Hashes a received body.
74    #[must_use]
75    pub fn of(body: &RawValue) -> Self {
76        Self::of_text(body.get())
77    }
78
79    /// Hashes body JSON text.
80    #[must_use]
81    pub fn of_text(text: &str) -> Self {
82        Self(Sha3_256::digest(text.as_bytes()).into())
83    }
84
85    /// Wraps a stored hash.
86    #[must_use]
87    pub const fn from_bytes(bytes: [u8; 32]) -> Self {
88        Self(bytes)
89    }
90
91    /// The digest bytes, for storage.
92    #[must_use]
93    pub const fn as_bytes(&self) -> &[u8; 32] {
94        &self.0
95    }
96}
97
98impl fmt::Debug for BodyHash {
99    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
100        write!(f, "BodyHash({})", b64::encode(&self.0))
101    }
102}
103
104/// What to do with a command whose key matches a stored record (§7.3).
105#[derive(Debug, Clone, Copy, PartialEq, Eq)]
106pub enum Replay {
107    /// Same `type` and body hash: send the stored response again; execute nothing.
108    Resend,
109    /// Different `type` or body hash: answer `CONFLICT{reason: "request_id_reused"}`
110    /// (`ErrorBody::conflict(Reason::RequestIdReused)`).
111    Conflict,
112}
113
114/// Compares a retried command with the stored record for its key.
115#[must_use]
116pub fn replay(stored_kind: &str, stored_hash: &BodyHash, kind: &str, hash: &BodyHash) -> Replay {
117    if stored_kind == kind && stored_hash == hash {
118        Replay::Resend
119    } else {
120        Replay::Conflict
121    }
122}