Skip to main content

zaun_community_protocol/command/
error.rs

1//! Why a command or event body was refused, in the terms the envelope layer answers with
2//! (specification §11).
3
4use crate::error_code::ErrorCode;
5
6/// A body that cannot be accepted. Each variant maps to one error code of §11; the envelope
7/// layer adds `request_id`, the message text and the extra fields.
8///
9/// SPEC: §11 lets an over-limit field be either `BAD_REQUEST` ("value out of range") or
10/// `PAYLOAD_TOO_LARGE` ("an envelope or field exceeds §12"). This crate applies one rule: a
11/// text, byte string or list **longer** than a §12 maximum is [`BodyError::PayloadTooLarge`];
12/// every other violation (missing, ill-typed, below a minimum, numeric range, rule) is
13/// [`BodyError::BadRequest`].
14#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
15pub enum BodyError {
16    /// `BAD_REQUEST{field?}`: malformed, missing, ill-typed or out-of-range value.
17    #[error("bad request{}: {detail}", field.as_deref().map(|f| format!(" ({f})")).unwrap_or_default())]
18    BadRequest {
19        /// The top-level body field at fault (dotted for nested checks), when known.
20        field: Option<String>,
21        /// A human-readable explanation; never contains secrets.
22        detail: String,
23    },
24    /// `UNSUPPORTED_COMMAND`: unknown `type`, or a reserved namespace (§13).
25    #[error("unsupported command")]
26    UnsupportedCommand,
27    /// `UNSUPPORTED_FEATURE{feature}`: a known name or value not implemented in v1 (§8.11).
28    #[error("unsupported feature {feature}")]
29    UnsupportedFeature {
30        /// The feature: a reserved command name, `kind.voice`, `attachments`, ….
31        feature: String,
32    },
33    /// `PAYLOAD_TOO_LARGE{limit}`: a field longer than its §12 maximum.
34    #[error("{field} exceeds the limit {limit}")]
35    PayloadTooLarge {
36        /// The field at fault.
37        field: String,
38        /// The limit, in the field's unit (scalars, bytes or entries).
39        limit: u64,
40    },
41}
42
43impl BodyError {
44    /// The §11 error code to answer with.
45    #[must_use]
46    pub const fn code(&self) -> ErrorCode {
47        match self {
48            Self::BadRequest { .. } => ErrorCode::BadRequest,
49            Self::UnsupportedCommand => ErrorCode::UnsupportedCommand,
50            Self::UnsupportedFeature { .. } => ErrorCode::UnsupportedFeature,
51            Self::PayloadTooLarge { .. } => ErrorCode::PayloadTooLarge,
52        }
53    }
54
55    /// The field at fault, when one is known.
56    #[must_use]
57    pub fn field(&self) -> Option<&str> {
58        match self {
59            Self::BadRequest { field, .. } => field.as_deref(),
60            Self::PayloadTooLarge { field, .. } => Some(field),
61            Self::UnsupportedCommand | Self::UnsupportedFeature { .. } => None,
62        }
63    }
64
65    /// `BAD_REQUEST` blaming `field`.
66    #[must_use]
67    pub fn bad(field: &str, detail: impl Into<String>) -> Self {
68        Self::BadRequest {
69            field: Some(field.to_owned()),
70            detail: detail.into(),
71        }
72    }
73
74    /// `PAYLOAD_TOO_LARGE` for `field` with `limit`.
75    #[must_use]
76    pub fn too_large(field: &str, limit: usize) -> Self {
77        Self::PayloadTooLarge {
78            field: field.to_owned(),
79            limit: u64::try_from(limit).unwrap_or(u64::MAX),
80        }
81    }
82
83    /// `UNSUPPORTED_FEATURE` for `feature`.
84    #[must_use]
85    pub fn unsupported(feature: &str) -> Self {
86        Self::UnsupportedFeature {
87            feature: feature.to_owned(),
88        }
89    }
90}