use std::fmt::Display;
use percent_encoding::{AsciiSet, NON_ALPHANUMERIC, utf8_percent_encode};
use crate::http::Method;
#[derive(Debug)]
#[non_exhaustive]
pub struct Route {
pub id: &'static str,
pub service: &'static str,
pub method: Method,
pub path: &'static str,
pub pattern: &'static str,
pub resource_type: &'static str,
pub params: &'static [RouteParam],
pub body: BodyKind,
pub response: Representation,
pub pagination: Pagination,
pub write: Option<&'static WriteSemantics>,
pub deprecated: bool,
pub metadata: &'static OperationMetadata,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct RouteParam {
pub name: &'static str,
pub kind: ParamKind,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum ParamKind {
String,
Bool,
Int32,
Int64,
StringList,
Int64List,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum BodyKind {
None,
Json,
Octet,
Multipart {
field: &'static str,
},
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum Representation {
Empty,
Json,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum Pagination {
None,
Link {
key: Option<&'static str>,
total_count_header: Option<&'static str>,
},
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct WriteSemantics {
pub clears_omitted: bool,
pub preserved_on_omission: &'static [&'static str],
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct OperationMetadata {
pub operation: &'static str,
pub idempotent: bool,
pub readonly: bool,
pub retry: RetryConfig,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct RetryConfig {
pub max_attempts: u32,
pub base_delay_ms: u64,
pub backoff: Backoff,
pub retry_on: &'static [u16],
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum Backoff {
Exponential,
Linear,
Constant,
}
const PATH_SEGMENT: &AsciiSet = &NON_ALPHANUMERIC
.remove(b'-')
.remove(b'_')
.remove(b'.')
.remove(b'~');
impl Route {
pub fn retry_eligible(&self) -> bool {
matches!(
self.method,
Method::GET | Method::HEAD | Method::PUT | Method::DELETE
) || self.metadata.idempotent
}
pub fn fill(&self, values: &[&dyn Display]) -> String {
assert_eq!(
values.len(),
self.params.len(),
"{} takes {} path parameters",
self.id,
self.params.len()
);
let mut path = self.path.to_string();
for (param, value) in self.params.iter().zip(values) {
let encoded = utf8_percent_encode(&value.to_string(), PATH_SEGMENT).to_string();
path = path.replace(&format!("{{{}}}", param.name), &encoded);
}
path
}
pub fn recognize(&self, path: &str) -> Option<Vec<(&'static str, String)>> {
let pattern_segments: Vec<&str> = self.pattern.split('/').collect();
let path_segments: Vec<&str> = path.split('/').collect();
if pattern_segments.len() != path_segments.len() {
return None;
}
let mut params = Vec::new();
for (pattern, actual) in pattern_segments.iter().zip(&path_segments) {
if let Some(name) = pattern
.strip_prefix('{')
.and_then(|rest| rest.strip_suffix('}'))
{
if actual.is_empty() {
return None;
}
let param = self.params.iter().find(|param| param.name == name)?;
params.push((param.name, (*actual).to_string()));
} else if pattern != actual {
return None;
}
}
Some(params)
}
}