use std::borrow::Cow;
use std::fmt;
use std::str::FromStr;
use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use crate::error::{Validate, ValidationError};
use crate::id::Id;
use crate::limits::{
CHANGES_LIMIT_DEFAULT, CHANGES_LIMIT_MAX, IDEMPOTENCY_KEY_MAX_LEN, IDEMPOTENCY_KEY_MIN_LEN,
NONCE_MAX_CHARS, PAGE_LIMIT_DEFAULT, PAGE_LIMIT_MAX,
};
pub const IDEMPOTENCY_KEY: &str = "Idempotency-Key";
pub const IDEMPOTENT_REPLAYED: &str = "Idempotent-Replayed";
pub const RATE_LIMIT_LIMIT: &str = "X-RateLimit-Limit";
pub const RATE_LIMIT_REMAINING: &str = "X-RateLimit-Remaining";
pub const RATE_LIMIT_RESET_MS: &str = "X-RateLimit-Reset-Ms";
pub const RETRY_AFTER: &str = "Retry-After";
pub const IF_NONE_MATCH: &str = "If-None-Match";
pub const ETAG: &str = "ETag";
pub const SEW_ACT_AS: &str = "Sew-Act-As";
pub const SEW_VIA: &str = "Sew-Via";
pub const SEW_ACTOR: &str = "Sew-Actor";
pub const SEW_ON_BEHALF_OF: &str = "Sew-On-Behalf-Of";
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct IdempotencyKey(String);
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct IdempotencyKeyError(String);
impl fmt::Display for IdempotencyKeyError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"invalid Idempotency-Key {:?}: expected 1–64 chars of [A-Za-z0-9_-]",
self.0
)
}
}
impl std::error::Error for IdempotencyKeyError {}
impl IdempotencyKey {
pub fn as_str(&self) -> &str {
&self.0
}
}
impl FromStr for IdempotencyKey {
type Err = IdempotencyKeyError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let ok = (IDEMPOTENCY_KEY_MIN_LEN..=IDEMPOTENCY_KEY_MAX_LEN).contains(&s.len())
&& s.bytes()
.all(|c| c.is_ascii_alphanumeric() || c == b'_' || c == b'-');
if ok {
Ok(IdempotencyKey(s.to_owned()))
} else {
Err(IdempotencyKeyError(s.to_owned()))
}
}
}
impl fmt::Display for IdempotencyKey {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0)
}
}
impl Serialize for IdempotencyKey {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.serialize_str(&self.0)
}
}
impl<'de> Deserialize<'de> for IdempotencyKey {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let s = Cow::<'de, str>::deserialize(deserializer)?;
s.parse().map_err(serde::de::Error::custom)
}
}
impl JsonSchema for IdempotencyKey {
fn inline_schema() -> bool {
true
}
fn schema_name() -> Cow<'static, str> {
"IdempotencyKey".into()
}
fn json_schema(_: &mut SchemaGenerator) -> Schema {
json_schema!({
"type": "string",
"pattern": "^[A-Za-z0-9_-]{1,64}$",
"description": "An idempotency key."
})
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Nonce(String);
impl Nonce {
pub fn new(s: impl Into<String>) -> Self {
Nonce(s.into())
}
pub fn as_str(&self) -> &str {
&self.0
}
pub fn check(&self, field: &str) -> Result<(), ValidationError> {
let n = self.0.chars().count();
if n == 0 || n > NONCE_MAX_CHARS {
return Err(ValidationError::invalid(
field,
format!("{field} must be 1–{NONCE_MAX_CHARS} characters, got {n}"),
));
}
Ok(())
}
}
impl Serialize for Nonce {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.serialize_str(&self.0)
}
}
impl<'de> Deserialize<'de> for Nonce {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
String::deserialize(deserializer).map(Nonce)
}
}
impl JsonSchema for Nonce {
fn inline_schema() -> bool {
true
}
fn schema_name() -> Cow<'static, str> {
"Nonce".into()
}
fn json_schema(_: &mut SchemaGenerator) -> Schema {
json_schema!({
"type": "string",
"minLength": 1,
"maxLength": 64,
"description": "A client nonce, 1–64 characters."
})
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct PageQuery {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub before: Option<Id>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub after: Option<Id>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub around: Option<Id>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub limit: Option<u32>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Cursor {
Newest,
Before(Id),
After(Id),
Around(Id),
}
impl PageQuery {
pub fn cursor(&self) -> Cursor {
match (self.before, self.after, self.around) {
(Some(id), _, _) => Cursor::Before(id),
(None, Some(id), _) => Cursor::After(id),
(None, None, Some(id)) => Cursor::Around(id),
(None, None, None) => Cursor::Newest,
}
}
pub fn limit(&self) -> u32 {
self.limit.unwrap_or(PAGE_LIMIT_DEFAULT)
}
}
impl Validate for PageQuery {
fn validate(&self) -> Result<(), ValidationError> {
let set = [self.before, self.after, self.around]
.iter()
.filter(|c| c.is_some())
.count();
if set > 1 {
return Err(ValidationError::invalid(
"before",
"at most one of before, after, around",
));
}
if let Some(l) = self.limit
&& !(1..=PAGE_LIMIT_MAX).contains(&l)
{
return Err(ValidationError::invalid(
"limit",
format!("limit must be 1–{PAGE_LIMIT_MAX}"),
));
}
Ok(())
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct Page<T> {
pub items: Vec<T>,
pub has_more: bool,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct ChangesQuery {
pub since: u64,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub limit: Option<u32>,
}
impl ChangesQuery {
pub fn limit(&self) -> u32 {
self.limit.unwrap_or(CHANGES_LIMIT_DEFAULT)
}
}
impl Validate for ChangesQuery {
fn validate(&self) -> Result<(), ValidationError> {
if let Some(l) = self.limit
&& !(1..=CHANGES_LIMIT_MAX).contains(&l)
{
return Err(ValidationError::invalid(
"limit",
format!("limit must be 1–{CHANGES_LIMIT_MAX}"),
));
}
Ok(())
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct EmptyRequest {}
impl Validate for EmptyRequest {
fn validate(&self) -> Result<(), ValidationError> {
Ok(())
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct OkResponse {
pub ok: bool,
}
impl Default for OkResponse {
fn default() -> Self {
OkResponse { ok: true }
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Hash)]
pub enum Patch<T> {
#[default]
Keep,
Clear,
Set(T),
}
impl<T> Patch<T> {
pub fn is_keep(&self) -> bool {
matches!(self, Patch::Keep)
}
pub fn as_set(&self) -> Option<&T> {
match self {
Patch::Set(v) => Some(v),
_ => None,
}
}
pub fn apply(self, current: Option<T>) -> Option<T> {
match self {
Patch::Keep => current,
Patch::Clear => None,
Patch::Set(v) => Some(v),
}
}
}
impl<T: Serialize> Serialize for Patch<T> {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
match self {
Patch::Keep | Patch::Clear => serializer.serialize_none(),
Patch::Set(v) => serializer.serialize_some(v),
}
}
}
impl<'de, T: Deserialize<'de>> Deserialize<'de> for Patch<T> {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
Ok(match Option::<T>::deserialize(deserializer)? {
Some(v) => Patch::Set(v),
None => Patch::Clear,
})
}
}
impl<T: JsonSchema> JsonSchema for Patch<T> {
fn inline_schema() -> bool {
true
}
fn schema_name() -> Cow<'static, str> {
format!("Patch_{}", T::schema_name()).into()
}
fn json_schema(generator: &mut SchemaGenerator) -> Schema {
let mut schema = generator.subschema_for::<Option<T>>();
schema.insert(
"description".to_owned(),
"Absent keeps the value, null clears it, a value replaces it.".into(),
);
schema
}
}