]> Untitled Git - lemmy.git/blob - crates/utils/src/rate_limit/mod.rs
Removing check_only
[lemmy.git] / crates / utils / src / rate_limit / mod.rs
1 use crate::{settings::structs::RateLimitConfig, utils::get_ip, IpAddr, LemmyError};
2 use actix_web::dev::{Service, ServiceRequest, ServiceResponse, Transform};
3 use futures::future::{ok, Ready};
4 use rate_limiter::{RateLimitType, RateLimiter};
5 use std::{
6   future::Future,
7   pin::Pin,
8   sync::Arc,
9   task::{Context, Poll},
10 };
11 use tokio::sync::Mutex;
12
13 pub mod rate_limiter;
14
15 #[derive(Debug, Clone)]
16 pub struct RateLimit {
17   // it might be reasonable to use a std::sync::Mutex here, since we don't need to lock this
18   // across await points
19   pub rate_limiter: Arc<Mutex<RateLimiter>>,
20   pub rate_limit_config: RateLimitConfig,
21 }
22
23 #[derive(Debug, Clone)]
24 pub struct RateLimited {
25   rate_limiter: Arc<Mutex<RateLimiter>>,
26   rate_limit_config: RateLimitConfig,
27   type_: RateLimitType,
28 }
29
30 pub struct RateLimitedMiddleware<S> {
31   rate_limited: RateLimited,
32   service: S,
33 }
34
35 impl RateLimit {
36   pub fn message(&self) -> RateLimited {
37     self.kind(RateLimitType::Message)
38   }
39
40   pub fn post(&self) -> RateLimited {
41     self.kind(RateLimitType::Post)
42   }
43
44   pub fn register(&self) -> RateLimited {
45     self.kind(RateLimitType::Register)
46   }
47
48   pub fn image(&self) -> RateLimited {
49     self.kind(RateLimitType::Image)
50   }
51
52   pub fn comment(&self) -> RateLimited {
53     self.kind(RateLimitType::Comment)
54   }
55
56   fn kind(&self, type_: RateLimitType) -> RateLimited {
57     RateLimited {
58       rate_limiter: self.rate_limiter.clone(),
59       rate_limit_config: self.rate_limit_config.clone(),
60       type_,
61     }
62   }
63 }
64
65 impl RateLimited {
66   pub async fn wrap<T, E>(
67     self,
68     ip_addr: IpAddr,
69     fut: impl Future<Output = Result<T, E>>,
70   ) -> Result<T, E>
71   where
72     E: From<LemmyError>,
73   {
74     // Does not need to be blocking because the RwLock in settings never held across await points,
75     // and the operation here locks only long enough to clone
76     let rate_limit = self.rate_limit_config;
77
78     // before
79     {
80       let mut limiter = self.rate_limiter.lock().await;
81
82       match self.type_ {
83         RateLimitType::Message => {
84           limiter.check_rate_limit_full(
85             self.type_,
86             &ip_addr,
87             rate_limit.message,
88             rate_limit.message_per_second,
89           )?;
90
91           drop(limiter);
92           return fut.await;
93         }
94         RateLimitType::Post => {
95           limiter.check_rate_limit_full(
96             self.type_,
97             &ip_addr,
98             rate_limit.post,
99             rate_limit.post_per_second,
100           )?;
101         }
102         RateLimitType::Register => {
103           limiter.check_rate_limit_full(
104             self.type_,
105             &ip_addr,
106             rate_limit.register,
107             rate_limit.register_per_second,
108           )?;
109         }
110         RateLimitType::Image => {
111           limiter.check_rate_limit_full(
112             self.type_,
113             &ip_addr,
114             rate_limit.image,
115             rate_limit.image_per_second,
116           )?;
117         }
118         RateLimitType::Comment => {
119           limiter.check_rate_limit_full(
120             self.type_,
121             &ip_addr,
122             rate_limit.comment,
123             rate_limit.comment_per_second,
124           )?;
125         }
126       };
127     }
128
129     let res = fut.await;
130
131     res
132   }
133 }
134
135 impl<S> Transform<S, ServiceRequest> for RateLimited
136 where
137   S: Service<ServiceRequest, Response = ServiceResponse, Error = actix_web::Error>,
138   S::Future: 'static,
139 {
140   type Response = S::Response;
141   type Error = actix_web::Error;
142   type InitError = ();
143   type Transform = RateLimitedMiddleware<S>;
144   type Future = Ready<Result<Self::Transform, Self::InitError>>;
145
146   fn new_transform(&self, service: S) -> Self::Future {
147     ok(RateLimitedMiddleware {
148       rate_limited: self.clone(),
149       service,
150     })
151   }
152 }
153
154 type FutResult<T, E> = dyn Future<Output = Result<T, E>>;
155
156 impl<S> Service<ServiceRequest> for RateLimitedMiddleware<S>
157 where
158   S: Service<ServiceRequest, Response = ServiceResponse, Error = actix_web::Error>,
159   S::Future: 'static,
160 {
161   type Response = S::Response;
162   type Error = actix_web::Error;
163   type Future = Pin<Box<FutResult<Self::Response, Self::Error>>>;
164
165   fn poll_ready(&self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
166     self.service.poll_ready(cx)
167   }
168
169   fn call(&self, req: ServiceRequest) -> Self::Future {
170     let ip_addr = get_ip(&req.connection_info());
171
172     let fut = self
173       .rate_limited
174       .clone()
175       .wrap(ip_addr, self.service.call(req));
176
177     Box::pin(async move { fut.await.map_err(actix_web::Error::from) })
178   }
179 }