use std::{borrow::Cow, fmt};
use axum::http::Method;
use thiserror::Error;
use crate::http::{IdempotencyRequestPolicy, RateLimitRequestPolicy};
use crate::result::{ClassifyError, ErrorKind};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum EndpointMethod {
Delete,
Get,
Head,
Options,
Patch,
Post,
Put,
}
impl EndpointMethod {
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::Delete => "DELETE",
Self::Get => "GET",
Self::Head => "HEAD",
Self::Options => "OPTIONS",
Self::Patch => "PATCH",
Self::Post => "POST",
Self::Put => "PUT",
}
}
#[must_use]
pub const fn is_safe(self) -> bool {
matches!(self, Self::Get | Self::Head | Self::Options)
}
}
impl TryFrom<&Method> for EndpointMethod {
type Error = EndpointMethodError;
fn try_from(method: &Method) -> Result<Self, Self::Error> {
match method.as_str() {
"DELETE" => Ok(Self::Delete),
"GET" => Ok(Self::Get),
"HEAD" => Ok(Self::Head),
"OPTIONS" => Ok(Self::Options),
"PATCH" => Ok(Self::Patch),
"POST" => Ok(Self::Post),
"PUT" => Ok(Self::Put),
_ => Err(EndpointMethodError),
}
}
}
impl fmt::Display for EndpointMethod {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(self.as_str())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)]
#[error("HTTP method is not supported by endpoint contracts")]
pub struct EndpointMethodError;
impl ClassifyError for EndpointMethodError {
fn error_kind(&self) -> ErrorKind {
ErrorKind::Validation
}
fn error_code(&self) -> crate::result::ErrorCode {
crate::result::ErrorCode::internal("endpoint_method_unsupported")
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum EndpointPathPattern {
Exact(Cow<'static, str>),
Template(Cow<'static, str>),
}
impl EndpointPathPattern {
#[must_use]
pub const fn exact(path: &'static str) -> Self {
Self::Exact(Cow::Borrowed(path))
}
#[must_use]
pub const fn template(path: &'static str) -> Self {
Self::Template(Cow::Borrowed(path))
}
#[must_use]
pub fn as_str(&self) -> &str {
match self {
Self::Exact(path) | Self::Template(path) => path,
}
}
}
impl fmt::Display for EndpointPathPattern {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(self.as_str())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum EndpointAuth {
Public,
Authenticated,
User,
Client,
Admin,
Service,
}
impl EndpointAuth {
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::Public => "public",
Self::Authenticated => "authenticated",
Self::User => "user",
Self::Client => "client",
Self::Admin => "admin",
Self::Service => "service",
}
}
#[must_use]
pub const fn requires_identity(self) -> bool {
!matches!(self, Self::Public)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum EndpointPermissions<P: Copy + 'static = &'static str> {
None,
One(P),
Any(&'static [P]),
All(&'static [P]),
}
impl<P: Copy + 'static> EndpointPermissions<P> {
#[must_use]
pub const fn is_none(self) -> bool {
matches!(self, Self::None)
}
#[must_use]
pub fn is_granted_by(self, mut has_permission: impl FnMut(P) -> bool) -> bool {
match self {
Self::None => true,
Self::One(permission) => has_permission(permission),
Self::Any(permissions) => permissions.iter().copied().any(has_permission),
Self::All(permissions) => {
!permissions.is_empty() && permissions.iter().copied().all(has_permission)
}
}
}
#[must_use]
pub fn empty_requirement_mode(self) -> Option<&'static str> {
match self {
Self::Any([]) => Some("any"),
Self::All([]) => Some("all"),
Self::None | Self::One(_) | Self::Any(_) | Self::All(_) => None,
}
}
}
impl<P: Copy + Eq + 'static> EndpointPermissions<P> {
#[must_use]
pub fn contains(self, permission: P) -> bool {
match self {
Self::None => false,
Self::One(expected) => expected == permission,
Self::Any(permissions) | Self::All(permissions) => permissions.contains(&permission),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum EndpointRisk {
Low,
Medium,
High,
Critical,
}
impl EndpointRisk {
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::Low => "low",
Self::Medium => "medium",
Self::High => "high",
Self::Critical => "critical",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum EndpointPagination {
None,
Offset,
Cursor,
}
impl EndpointPagination {
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::None => "none",
Self::Offset => "offset",
Self::Cursor => "cursor",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum EndpointAudit {
None,
Optional,
Required,
}
impl EndpointAudit {
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::None => "none",
Self::Optional => "optional",
Self::Required => "required",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct EndpointPolicy<P: Copy + 'static = &'static str> {
auth: EndpointAuth,
permissions: EndpointPermissions<P>,
risk: EndpointRisk,
idempotency: IdempotencyRequestPolicy,
rate_limit: RateLimitRequestPolicy,
audit: EndpointAudit,
}
impl<P: Copy + 'static> Default for EndpointPolicy<P> {
fn default() -> Self {
EndpointPolicy::new().with_permissions(EndpointPermissions::None)
}
}
impl EndpointPolicy {
#[must_use]
pub const fn new() -> Self {
Self {
auth: EndpointAuth::Public,
permissions: EndpointPermissions::None,
risk: EndpointRisk::Low,
idempotency: IdempotencyRequestPolicy::Disabled,
rate_limit: RateLimitRequestPolicy::Disabled,
audit: EndpointAudit::None,
}
}
}
impl<P: Copy + 'static> EndpointPolicy<P> {
#[must_use]
pub const fn with_auth(mut self, auth: EndpointAuth) -> Self {
self.auth = auth;
self
}
#[must_use]
pub const fn with_permissions<Q: Copy + 'static>(
self,
permissions: EndpointPermissions<Q>,
) -> EndpointPolicy<Q> {
EndpointPolicy {
auth: self.auth,
permissions,
risk: self.risk,
idempotency: self.idempotency,
rate_limit: self.rate_limit,
audit: self.audit,
}
}
#[must_use]
pub const fn with_risk(mut self, risk: EndpointRisk) -> Self {
self.risk = risk;
self
}
#[must_use]
pub const fn with_idempotency(mut self, idempotency: IdempotencyRequestPolicy) -> Self {
self.idempotency = idempotency;
self
}
#[must_use]
pub const fn with_rate_limit(mut self, rate_limit: RateLimitRequestPolicy) -> Self {
self.rate_limit = rate_limit;
self
}
#[must_use]
pub const fn with_audit(mut self, audit: EndpointAudit) -> Self {
self.audit = audit;
self
}
#[must_use]
pub const fn auth(&self) -> EndpointAuth {
self.auth
}
#[must_use]
pub const fn permissions(&self) -> EndpointPermissions<P> {
self.permissions
}
#[must_use]
pub const fn risk(&self) -> EndpointRisk {
self.risk
}
#[must_use]
pub const fn idempotency(&self) -> IdempotencyRequestPolicy {
self.idempotency
}
#[must_use]
pub const fn rate_limit(&self) -> RateLimitRequestPolicy {
self.rate_limit
}
#[must_use]
pub const fn audit(&self) -> EndpointAudit {
self.audit
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct EndpointContract<P: Copy + 'static = &'static str> {
method: EndpointMethod,
path: EndpointPathPattern,
policy: EndpointPolicy<P>,
pagination: EndpointPagination,
}
impl EndpointContract {
#[must_use]
pub const fn new(method: EndpointMethod, path: EndpointPathPattern) -> Self {
Self::from_policy(method, path, EndpointPolicy::new())
}
}
impl<P: Copy + 'static> EndpointContract<P> {
#[must_use]
pub const fn from_policy(
method: EndpointMethod,
path: EndpointPathPattern,
policy: EndpointPolicy<P>,
) -> Self {
Self {
method,
path,
policy,
pagination: EndpointPagination::None,
}
}
#[must_use]
pub fn with_policy<Q: Copy + 'static>(self, policy: EndpointPolicy<Q>) -> EndpointContract<Q> {
EndpointContract {
method: self.method,
path: self.path,
policy,
pagination: self.pagination,
}
}
#[must_use]
pub const fn with_auth(mut self, auth: EndpointAuth) -> Self {
self.policy = self.policy.with_auth(auth);
self
}
#[must_use]
pub fn with_permissions<Q: Copy + 'static>(
self,
permissions: EndpointPermissions<Q>,
) -> EndpointContract<Q> {
let policy = self.policy.with_permissions(permissions);
self.with_policy(policy)
}
#[must_use]
pub const fn with_risk(mut self, risk: EndpointRisk) -> Self {
self.policy = self.policy.with_risk(risk);
self
}
#[must_use]
pub const fn with_idempotency(mut self, idempotency: IdempotencyRequestPolicy) -> Self {
self.policy = self.policy.with_idempotency(idempotency);
self
}
#[must_use]
pub const fn with_pagination(mut self, pagination: EndpointPagination) -> Self {
self.pagination = pagination;
self
}
#[must_use]
pub const fn with_rate_limit(mut self, rate_limit: RateLimitRequestPolicy) -> Self {
self.policy = self.policy.with_rate_limit(rate_limit);
self
}
#[must_use]
pub const fn with_audit(mut self, audit: EndpointAudit) -> Self {
self.policy = self.policy.with_audit(audit);
self
}
#[must_use]
pub const fn policy(&self) -> EndpointPolicy<P> {
self.policy
}
#[must_use]
pub const fn method(&self) -> EndpointMethod {
self.method
}
#[must_use]
pub const fn path(&self) -> &EndpointPathPattern {
&self.path
}
#[cfg(feature = "openapi")]
pub(crate) fn set_path(&mut self, path: String) {
self.path = match &self.path {
EndpointPathPattern::Exact(_) => EndpointPathPattern::Exact(path.into()),
EndpointPathPattern::Template(_) => EndpointPathPattern::Template(path.into()),
};
}
#[must_use]
pub const fn auth(&self) -> EndpointAuth {
self.policy.auth()
}
#[must_use]
pub const fn permissions(&self) -> EndpointPermissions<P> {
self.policy.permissions()
}
#[must_use]
pub const fn requires_authorization(&self) -> bool {
!matches!(
self.auth(),
EndpointAuth::Public | EndpointAuth::Authenticated
) || !self.permissions().is_none()
}
#[must_use]
pub const fn risk(&self) -> EndpointRisk {
self.policy.risk()
}
#[must_use]
pub const fn idempotency(&self) -> IdempotencyRequestPolicy {
self.policy.idempotency()
}
#[must_use]
pub const fn pagination(&self) -> EndpointPagination {
self.pagination
}
#[must_use]
pub const fn rate_limit(&self) -> RateLimitRequestPolicy {
self.policy.rate_limit()
}
#[must_use]
pub const fn audit(&self) -> EndpointAudit {
self.policy.audit()
}
}