Skip to main content

repe_core/
constants.rs

1//! Protocol constants and enums derived from the REPE spec.
2
3/// Magic spec value to denote the REPE specification (0x1507)
4pub const REPE_SPEC: u16 = 0x1507;
5
6/// Current REPE version (1)
7pub const REPE_VERSION: u8 = 1;
8
9/// Fixed header size in bytes
10pub const HEADER_SIZE: usize = 48;
11
12/// REPE high-level error codes.
13#[repr(u32)]
14#[derive(Debug, Clone, Copy, PartialEq, Eq)]
15#[non_exhaustive]
16pub enum ErrorCode {
17    /// Success. The response carries a normal result, not an error.
18    Ok = 0,
19    /// The request's REPE version is not supported by this server.
20    VersionMismatch = 1,
21    /// The fixed header was malformed: bad spec magic, wrong length, or a
22    /// length that disagrees with the body.
23    InvalidHeader = 2,
24    /// The query was malformed or used a query format this server does not
25    /// accept (e.g. a raw-binary query against a JSON-pointer router).
26    InvalidQuery = 3,
27    /// The body could not be interpreted for the target method (wrong
28    /// shape or type for what the handler expected).
29    InvalidBody = 4,
30    /// The message could not be parsed: a framing, header-decode, or
31    /// body-decode failure below the application level.
32    ParseError = 5,
33    /// No handler is registered for the requested query path.
34    MethodNotFound = 6,
35    /// The request did not produce a response within the allotted time.
36    Timeout = 7,
37    /// The server is temporarily unable to service the request and the
38    /// client should retry. Distinct from an application error: it
39    /// signals transient saturation, not a failed result. The built-in
40    /// `WebSocketServer` returns this when an off-reader request is
41    /// rejected because the per-connection `with_offreader_limit` cap is
42    /// reached. Occupies the REPE-reserved `8..4095` range (between
43    /// `Timeout` and `ApplicationErrorBase`).
44    ResourceExhausted = 8,
45    /// The server hit an unexpected internal failure while handling the
46    /// request; the result is not a normal application-level outcome.
47    /// The built-in `WebSocketServer` returns this for a caught
48    /// off-reader handler panic. Also in the REPE-reserved `8..4095`
49    /// range.
50    InternalError = 9,
51    /// Base of the application-defined error range. A handler returns this
52    /// (or any value at or above it) for an ordinary application-level
53    /// failure, as distinct from the protocol-level codes above and from
54    /// the `ResourceExhausted` / `InternalError` server conditions.
55    ApplicationErrorBase = 4096,
56}
57
58impl From<ErrorCode> for u32 {
59    fn from(v: ErrorCode) -> Self {
60        v as u32
61    }
62}
63
64impl core::convert::TryFrom<u32> for ErrorCode {
65    type Error = u32;
66    fn try_from(value: u32) -> Result<Self, Self::Error> {
67        let res = match value {
68            0 => ErrorCode::Ok,
69            1 => ErrorCode::VersionMismatch,
70            2 => ErrorCode::InvalidHeader,
71            3 => ErrorCode::InvalidQuery,
72            4 => ErrorCode::InvalidBody,
73            5 => ErrorCode::ParseError,
74            6 => ErrorCode::MethodNotFound,
75            7 => ErrorCode::Timeout,
76            8 => ErrorCode::ResourceExhausted,
77            9 => ErrorCode::InternalError,
78            4096 => ErrorCode::ApplicationErrorBase,
79            _ => return Err(value),
80        };
81        Ok(res)
82    }
83}
84
85/// Reserved Query formats (0..=4095 reserved for REPE)
86#[repr(u16)]
87#[derive(Debug, Clone, Copy, PartialEq, Eq)]
88#[non_exhaustive]
89pub enum QueryFormat {
90    RawBinary = 0,
91    JsonPointer = 1,
92}
93
94impl From<QueryFormat> for u16 {
95    fn from(v: QueryFormat) -> Self {
96        v as u16
97    }
98}
99
100impl core::convert::TryFrom<u16> for QueryFormat {
101    type Error = u16;
102    fn try_from(value: u16) -> Result<Self, Self::Error> {
103        Ok(match value {
104            0 => QueryFormat::RawBinary,
105            1 => QueryFormat::JsonPointer,
106            other => return Err(other),
107        })
108    }
109}
110
111/// Reserved Body formats (0..=4095 reserved for REPE)
112#[repr(u16)]
113#[derive(Debug, Clone, Copy, PartialEq, Eq)]
114#[non_exhaustive]
115pub enum BodyFormat {
116    RawBinary = 0,
117    Beve = 1, // BEVE binary body
118    Json = 2,
119    Utf8 = 3,
120}
121
122impl From<BodyFormat> for u16 {
123    fn from(v: BodyFormat) -> Self {
124        v as u16
125    }
126}
127
128impl core::convert::TryFrom<u16> for BodyFormat {
129    type Error = u16;
130    fn try_from(value: u16) -> Result<Self, Self::Error> {
131        Ok(match value {
132            0 => BodyFormat::RawBinary,
133            1 => BodyFormat::Beve,
134            2 => BodyFormat::Json,
135            3 => BodyFormat::Utf8,
136            other => return Err(other),
137        })
138    }
139}
140
141impl std::fmt::Display for ErrorCode {
142    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
143        let s = match self {
144            ErrorCode::Ok => "OK",
145            ErrorCode::VersionMismatch => "Version mismatch",
146            ErrorCode::InvalidHeader => "Invalid header",
147            ErrorCode::InvalidQuery => "Invalid query",
148            ErrorCode::InvalidBody => "Invalid body",
149            ErrorCode::ParseError => "Parse error",
150            ErrorCode::MethodNotFound => "Method not found",
151            ErrorCode::Timeout => "Timeout",
152            ErrorCode::ResourceExhausted => "Resource exhausted",
153            ErrorCode::InternalError => "Internal error",
154            ErrorCode::ApplicationErrorBase => "Application error",
155        };
156        f.write_str(s)
157    }
158}
159
160// The three protocol enums cross the wire as their variant names, in both
161// formats, which is what `#[derive(Serialize, Deserialize)]` gave them and what
162// `unit_enum!` gives them now. Declared here rather than beside each enum so the
163// `#[non_exhaustive]` attribute and the explicit discriminants stay legible.
164//
165// `#[non_exhaustive]` is about downstream `match`, not about the wire: an
166// unknown name is `UnknownVariant`, exactly as an out-of-range integer is an
167// `Err` from the `TryFrom` impls above.
168structio::unit_enum!(ErrorCode {
169    Ok,
170    VersionMismatch,
171    InvalidHeader,
172    InvalidQuery,
173    InvalidBody,
174    ParseError,
175    MethodNotFound,
176    Timeout,
177    ResourceExhausted,
178    InternalError,
179    ApplicationErrorBase,
180});
181
182structio::unit_enum!(QueryFormat {
183    RawBinary,
184    JsonPointer
185});
186
187structio::unit_enum!(BodyFormat {
188    RawBinary,
189    Beve,
190    Json,
191    Utf8,
192});