1use 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
17pub const IDEMPOTENCY_KEY: &str = "Idempotency-Key";
19pub const IDEMPOTENT_REPLAYED: &str = "Idempotent-Replayed";
21pub const RATE_LIMIT_LIMIT: &str = "X-RateLimit-Limit";
23pub const RATE_LIMIT_REMAINING: &str = "X-RateLimit-Remaining";
25pub const RATE_LIMIT_RESET_MS: &str = "X-RateLimit-Reset-Ms";
27pub const RETRY_AFTER: &str = "Retry-After";
29pub const IF_NONE_MATCH: &str = "If-None-Match";
31pub const ETAG: &str = "ETag";
33pub const SEW_ACT_AS: &str = "Sew-Act-As";
35pub const SEW_VIA: &str = "Sew-Via";
37pub const SEW_ACTOR: &str = "Sew-Actor";
40pub const SEW_ON_BEHALF_OF: &str = "Sew-On-Behalf-Of";
43
44#[derive(Debug, Clone, PartialEq, Eq, Hash)]
46pub struct IdempotencyKey(String);
47
48#[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 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#[derive(Debug, Clone, PartialEq, Eq, Hash)]
126pub struct Nonce(String);
127
128impl Nonce {
129 pub fn new(s: impl Into<String>) -> Self {
131 Nonce(s.into())
132 }
133
134 pub fn as_str(&self) -> &str {
136 &self.0
137 }
138
139 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#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
185#[serde(deny_unknown_fields)]
186pub struct PageQuery {
187 #[serde(default, skip_serializing_if = "Option::is_none")]
189 pub before: Option<Id>,
190 #[serde(default, skip_serializing_if = "Option::is_none")]
192 pub after: Option<Id>,
193 #[serde(default, skip_serializing_if = "Option::is_none")]
195 pub around: Option<Id>,
196 #[serde(default, skip_serializing_if = "Option::is_none")]
198 pub limit: Option<u32>,
199}
200
201#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
203pub enum Cursor {
204 Newest,
206 Before(Id),
208 After(Id),
210 Around(Id),
212}
213
214impl PageQuery {
215 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 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#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
257pub struct Page<T> {
258 pub items: Vec<T>,
260 pub has_more: bool,
262}
263
264#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
266#[serde(deny_unknown_fields)]
267pub struct ChangesQuery {
268 pub since: u64,
270 #[serde(default, skip_serializing_if = "Option::is_none")]
272 pub limit: Option<u32>,
273}
274
275impl ChangesQuery {
276 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#[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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
309pub struct OkResponse {
310 pub ok: bool,
312}
313
314impl Default for OkResponse {
315 fn default() -> Self {
316 OkResponse { ok: true }
317 }
318}
319
320#[derive(Debug, Clone, Default, PartialEq, Eq, Hash)]
323pub enum Patch<T> {
324 #[default]
326 Keep,
327 Clear,
329 Set(T),
331}
332
333impl<T> Patch<T> {
334 pub fn is_keep(&self) -> bool {
336 matches!(self, Patch::Keep)
337 }
338
339 pub fn as_set(&self) -> Option<&T> {
341 match self {
342 Patch::Set(v) => Some(v),
343 _ => None,
344 }
345 }
346
347 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}