1use std::collections::HashMap;
4use std::sync::{Arc, Mutex, MutexGuard};
5
6use axum::Router;
7use axum::body::Body;
8use http::Request;
9use tonic::Status;
10
11#[async_trait::async_trait]
17pub trait CallGuard: Send + Sync {
18 async fn guard(&self, request: &mut Request<Body>) -> Result<(), Status>;
20}
21
22#[derive(Clone, Default)]
24pub(crate) struct CallGuards {
25 inner: Arc<Mutex<Vec<Arc<dyn CallGuard>>>>,
26}
27
28impl CallGuards {
29 pub(crate) fn register(&self, guard: Arc<dyn CallGuard>) {
31 lock(&self.inner).push(guard);
32 }
33
34 pub(crate) fn all(&self) -> Vec<Arc<dyn CallGuard>> {
36 lock(&self.inner).clone()
37 }
38}
39
40pub trait SurfaceGuard: Send + Sync {
46 fn enforces(&self) -> bool;
49
50 fn protect(&self, router: Router) -> Router;
52}
53
54#[derive(Clone, Default)]
56pub(crate) struct SurfaceGuards {
57 inner: Arc<Mutex<HashMap<&'static str, Arc<dyn SurfaceGuard>>>>,
58}
59
60impl SurfaceGuards {
61 pub(crate) fn register(
67 &self,
68 name: &'static str,
69 guard: Arc<dyn SurfaceGuard>,
70 ) -> Result<(), SurfaceGuardError> {
71 let mut guards = lock(&self.inner);
72 if guards.contains_key(name) {
73 return Err(SurfaceGuardError::Duplicate(name));
74 }
75 guards.insert(name, guard);
76 Ok(())
77 }
78
79 pub(crate) fn get(&self, name: &str) -> Option<Arc<dyn SurfaceGuard>> {
81 lock(&self.inner).get(name).cloned()
82 }
83}
84
85#[derive(Debug, Clone, Copy, PartialEq, Eq)]
87pub enum SurfaceGuardError {
88 Duplicate(&'static str),
90}
91
92impl std::fmt::Display for SurfaceGuardError {
93 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
94 match self {
95 Self::Duplicate(name) => {
96 write!(formatter, "the surface guard '{name}' is registered twice")
97 }
98 }
99 }
100}
101
102impl std::error::Error for SurfaceGuardError {}
103
104fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
105 mutex
106 .lock()
107 .unwrap_or_else(|poisoned| poisoned.into_inner())
108}