Skip to main content

sew_proto/
http.rs

1//! HTTP conventions shared by the client and mgmt APIs.
2
3use std::borrow::Cow;
4use std::fmt;
5use std::str::FromStr;
6
7use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema};
8use serde::{Deserialize, Deserializer, Serialize, Serializer};
9
10use crate::error::{Validate, ValidationError};
11use crate::id::Id;
12use crate::limits::{
13    CHANGES_LIMIT_DEFAULT, CHANGES_LIMIT_MAX, IDEMPOTENCY_KEY_MAX_LEN, IDEMPOTENCY_KEY_MIN_LEN,
14    NONCE_MAX_CHARS, PAGE_LIMIT_DEFAULT, PAGE_LIMIT_MAX,
15};
16
17/// Request header: idempotency key for creating `POST`s (required on every mgmt `POST`).
18pub const IDEMPOTENCY_KEY: &str = "Idempotency-Key";
19/// Response header: `true` when the response is a stored replay.
20pub const IDEMPOTENT_REPLAYED: &str = "Idempotent-Replayed";
21/// Response header: the bucket size.
22pub const RATE_LIMIT_LIMIT: &str = "X-RateLimit-Limit";
23/// Response header: requests left in the bucket.
24pub const RATE_LIMIT_REMAINING: &str = "X-RateLimit-Remaining";
25/// Response header: milliseconds until the bucket refills.
26pub const RATE_LIMIT_RESET_MS: &str = "X-RateLimit-Reset-Ms";
27/// Response header on 429: seconds to wait.
28pub const RETRY_AFTER: &str = "Retry-After";
29/// Request header for conditional reads.
30pub const IF_NONE_MATCH: &str = "If-None-Match";
31/// Response header carrying a version tag.
32pub const ETAG: &str = "ETag";
33/// Mgmt act-as header: the member id or external id acted as.
34pub const SEW_ACT_AS: &str = "Sew-Act-As";
35/// Mgmt act-as header: `k2; agent=<uuid>; k2_session=<id>`.
36pub const SEW_VIA: &str = "Sew-Via";
37/// Optional mgmt header naming the K2 person behind a call, for audit only:
38/// 1–128 chars of `[A-Za-z0-9_.:@-]`, stored as `details.k2_actor`.
39pub const SEW_ACTOR: &str = "Sew-Actor";
40/// A relayed "on behalf of this person" claim. Routes that need the person's own session
41/// (answers to asks, the on-behalf approval) refuse any request that carries it.
42pub const SEW_ON_BEHALF_OF: &str = "Sew-On-Behalf-Of";
43
44/// An `Idempotency-Key` value: 1–64 chars of `[A-Za-z0-9_-]`.
45#[derive(Debug, Clone, PartialEq, Eq, Hash)]
46pub struct IdempotencyKey(String);
47
48/// Error parsing an [`IdempotencyKey`].
49#[derive(Debug, Clone, PartialEq, Eq)]
50pub struct IdempotencyKeyError(String);
51
52impl fmt::Display for IdempotencyKeyError {
53    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
54        write!(
55            f,
56            "invalid Idempotency-Key {:?}: expected 1–64 chars of [A-Za-z0-9_-]",
57            self.0
58        )
59    }
60}
61
62impl std::error::Error for IdempotencyKeyError {}
63
64impl IdempotencyKey {
65    /// The key text.
66    pub fn as_str(&self) -> &str {
67        &self.0
68    }
69}
70
71impl FromStr for IdempotencyKey {
72    type Err = IdempotencyKeyError;
73
74    fn from_str(s: &str) -> Result<Self, Self::Err> {
75        let ok = (IDEMPOTENCY_KEY_MIN_LEN..=IDEMPOTENCY_KEY_MAX_LEN).contains(&s.len())
76            && s.bytes()
77                .all(|c| c.is_ascii_alphanumeric() || c == b'_' || c == b'-');
78        if ok {
79            Ok(IdempotencyKey(s.to_owned()))
80        } else {
81            Err(IdempotencyKeyError(s.to_owned()))
82        }
83    }
84}
85
86impl fmt::Display for IdempotencyKey {
87    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
88        f.write_str(&self.0)
89    }
90}
91
92impl Serialize for IdempotencyKey {
93    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
94        serializer.serialize_str(&self.0)
95    }
96}
97
98impl<'de> Deserialize<'de> for IdempotencyKey {
99    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
100        let s = Cow::<'de, str>::deserialize(deserializer)?;
101        s.parse().map_err(serde::de::Error::custom)
102    }
103}
104
105impl JsonSchema for IdempotencyKey {
106    fn inline_schema() -> bool {
107        true
108    }
109    fn schema_name() -> Cow<'static, str> {
110        "IdempotencyKey".into()
111    }
112    fn json_schema(_: &mut SchemaGenerator) -> Schema {
113        json_schema!({
114            "type": "string",
115            "pattern": "^[A-Za-z0-9_-]{1,64}$",
116            "description": "An idempotency key."
117        })
118    }
119}
120
121/// A client-chosen message nonce, echoed back in the response and the `message_created` event.
122///
123/// Valid nonces are 1–64 Unicode scalar values. Deserialization accepts any string so the
124/// request validator can report `validation_failed` on the `nonce` field.
125#[derive(Debug, Clone, PartialEq, Eq, Hash)]
126pub struct Nonce(String);
127
128impl Nonce {
129    /// Wraps a string without checking it; see [`Nonce::check`].
130    pub fn new(s: impl Into<String>) -> Self {
131        Nonce(s.into())
132    }
133
134    /// The nonce text.
135    pub fn as_str(&self) -> &str {
136        &self.0
137    }
138
139    /// Checks the 1–64 character rule, reporting `field` on failure.
140    pub fn check(&self, field: &str) -> Result<(), ValidationError> {
141        let n = self.0.chars().count();
142        if n == 0 || n > NONCE_MAX_CHARS {
143            return Err(ValidationError::invalid(
144                field,
145                format!("{field} must be 1–{NONCE_MAX_CHARS} characters, got {n}"),
146            ));
147        }
148        Ok(())
149    }
150}
151
152impl Serialize for Nonce {
153    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
154        serializer.serialize_str(&self.0)
155    }
156}
157
158impl<'de> Deserialize<'de> for Nonce {
159    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
160        String::deserialize(deserializer).map(Nonce)
161    }
162}
163
164impl JsonSchema for Nonce {
165    fn inline_schema() -> bool {
166        true
167    }
168    fn schema_name() -> Cow<'static, str> {
169        "Nonce".into()
170    }
171    fn json_schema(_: &mut SchemaGenerator) -> Schema {
172        json_schema!({
173            "type": "string",
174            "minLength": 1,
175            "maxLength": 64,
176            "description": "A client nonce, 1–64 characters."
177        })
178    }
179}
180
181/// Query for id-keyed lists: at most one cursor and an optional `limit` (1–100,
182/// default 50). No cursor means the newest page, newest-first. `before` pages newest-first,
183/// `after` oldest-first, `around` centered.
184#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
185#[serde(deny_unknown_fields)]
186pub struct PageQuery {
187    /// Items older than this id.
188    #[serde(default, skip_serializing_if = "Option::is_none")]
189    pub before: Option<Id>,
190    /// Items newer than this id.
191    #[serde(default, skip_serializing_if = "Option::is_none")]
192    pub after: Option<Id>,
193    /// Items around this id.
194    #[serde(default, skip_serializing_if = "Option::is_none")]
195    pub around: Option<Id>,
196    /// Page size, 1–100 (default 50).
197    #[serde(default, skip_serializing_if = "Option::is_none")]
198    pub limit: Option<u32>,
199}
200
201/// Which page a [`PageQuery`] asks for.
202#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
203pub enum Cursor {
204    /// No cursor: the newest page, newest-first.
205    Newest,
206    /// Older than the id, newest-first.
207    Before(Id),
208    /// Newer than the id, oldest-first.
209    After(Id),
210    /// Centered on the id.
211    Around(Id),
212}
213
214impl PageQuery {
215    /// The cursor. With more than one set (invalid; see `validate`), `before` wins, then `after`.
216    pub fn cursor(&self) -> Cursor {
217        match (self.before, self.after, self.around) {
218            (Some(id), _, _) => Cursor::Before(id),
219            (None, Some(id), _) => Cursor::After(id),
220            (None, None, Some(id)) => Cursor::Around(id),
221            (None, None, None) => Cursor::Newest,
222        }
223    }
224
225    /// The page size, default 50.
226    pub fn limit(&self) -> u32 {
227        self.limit.unwrap_or(PAGE_LIMIT_DEFAULT)
228    }
229}
230
231impl Validate for PageQuery {
232    fn validate(&self) -> Result<(), ValidationError> {
233        let set = [self.before, self.after, self.around]
234            .iter()
235            .filter(|c| c.is_some())
236            .count();
237        if set > 1 {
238            return Err(ValidationError::invalid(
239                "before",
240                "at most one of before, after, around",
241            ));
242        }
243        if let Some(l) = self.limit
244            && !(1..=PAGE_LIMIT_MAX).contains(&l)
245        {
246            return Err(ValidationError::invalid(
247                "limit",
248                format!("limit must be 1–{PAGE_LIMIT_MAX}"),
249            ));
250        }
251        Ok(())
252    }
253}
254
255/// A page of an id-keyed list: `{"items": [...], "has_more": bool}`.
256#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
257pub struct Page<T> {
258    /// The items.
259    pub items: Vec<T>,
260    /// Whether more items exist past this page.
261    pub has_more: bool,
262}
263
264/// Query for change-log catch-up: `since` a seq, `limit` 1–500 (default 500).
265#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
266#[serde(deny_unknown_fields)]
267pub struct ChangesQuery {
268    /// Return entries with `seq > since`.
269    pub since: u64,
270    /// Page size, 1–500 (default 500).
271    #[serde(default, skip_serializing_if = "Option::is_none")]
272    pub limit: Option<u32>,
273}
274
275impl ChangesQuery {
276    /// The page size, default 500.
277    pub fn limit(&self) -> u32 {
278        self.limit.unwrap_or(CHANGES_LIMIT_DEFAULT)
279    }
280}
281
282impl Validate for ChangesQuery {
283    fn validate(&self) -> Result<(), ValidationError> {
284        if let Some(l) = self.limit
285            && !(1..=CHANGES_LIMIT_MAX).contains(&l)
286        {
287            return Err(ValidationError::invalid(
288                "limit",
289                format!("limit must be 1–{CHANGES_LIMIT_MAX}"),
290            ));
291        }
292        Ok(())
293    }
294}
295
296/// Body of a bodiless `POST`. The server accepts an empty body or `{}`.
297#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
298#[serde(deny_unknown_fields)]
299pub struct EmptyRequest {}
300
301impl Validate for EmptyRequest {
302    fn validate(&self) -> Result<(), ValidationError> {
303        Ok(())
304    }
305}
306
307/// Response for mutations with no canonical object: `{"ok": true}`.
308#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
309pub struct OkResponse {
310    /// Always `true`.
311    pub ok: bool,
312}
313
314impl Default for OkResponse {
315    fn default() -> Self {
316        OkResponse { ok: true }
317    }
318}
319
320/// A tri-state update field: absent = [`Patch::Keep`], `null` = [`Patch::Clear`], a value =
321/// [`Patch::Set`]. Fields use `#[serde(default, skip_serializing_if = "Patch::is_keep")]`.
322#[derive(Debug, Clone, Default, PartialEq, Eq, Hash)]
323pub enum Patch<T> {
324    /// Leave the value as it is.
325    #[default]
326    Keep,
327    /// Remove the value.
328    Clear,
329    /// Replace the value.
330    Set(T),
331}
332
333impl<T> Patch<T> {
334    /// Whether this is `Keep` (used by `skip_serializing_if`).
335    pub fn is_keep(&self) -> bool {
336        matches!(self, Patch::Keep)
337    }
338
339    /// The new value, if one is set.
340    pub fn as_set(&self) -> Option<&T> {
341        match self {
342            Patch::Set(v) => Some(v),
343            _ => None,
344        }
345    }
346
347    /// Applies the patch to a current optional value.
348    pub fn apply(self, current: Option<T>) -> Option<T> {
349        match self {
350            Patch::Keep => current,
351            Patch::Clear => None,
352            Patch::Set(v) => Some(v),
353        }
354    }
355}
356
357impl<T: Serialize> Serialize for Patch<T> {
358    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
359        match self {
360            Patch::Keep | Patch::Clear => serializer.serialize_none(),
361            Patch::Set(v) => serializer.serialize_some(v),
362        }
363    }
364}
365
366impl<'de, T: Deserialize<'de>> Deserialize<'de> for Patch<T> {
367    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
368        Ok(match Option::<T>::deserialize(deserializer)? {
369            Some(v) => Patch::Set(v),
370            None => Patch::Clear,
371        })
372    }
373}
374
375impl<T: JsonSchema> JsonSchema for Patch<T> {
376    fn inline_schema() -> bool {
377        true
378    }
379    fn schema_name() -> Cow<'static, str> {
380        format!("Patch_{}", T::schema_name()).into()
381    }
382    fn json_schema(generator: &mut SchemaGenerator) -> Schema {
383        let mut schema = generator.subschema_for::<Option<T>>();
384        schema.insert(
385            "description".to_owned(),
386            "Absent keeps the value, null clears it, a value replaces it.".into(),
387        );
388        schema
389    }
390}