Run fmt, fix dep route (#312)

This commit is contained in:
Geometrically
2022-02-27 21:44:00 -07:00
committed by GitHub
parent 725f8571bb
commit 459e36c027
53 changed files with 1798 additions and 867 deletions

View File

@@ -34,12 +34,20 @@ impl ResponseError for ARError {
reset,
} => {
let mut response = actix_web::HttpResponse::TooManyRequests();
response.insert_header(("x-ratelimit-limit", max_requests.to_string()));
response.insert_header(("x-ratelimit-remaining", remaining.to_string()));
response.insert_header(("x-ratelimit-reset", reset.to_string()));
response.insert_header((
"x-ratelimit-limit",
max_requests.to_string(),
));
response.insert_header((
"x-ratelimit-remaining",
remaining.to_string(),
));
response
.insert_header(("x-ratelimit-reset", reset.to_string()));
response.body(self.to_string())
}
_ => actix_web::HttpResponse::build(self.status_code()).body(self.to_string()),
_ => actix_web::HttpResponse::build(self.status_code())
.body(self.to_string()),
}
}
}

View File

@@ -36,9 +36,9 @@ impl MemoryStore {
pub fn with_capacity(capacity: usize) -> Self {
debug!("Creating new MemoryStore");
MemoryStore {
inner: Arc::new(DashMap::<String, (usize, Duration)>::with_capacity(
capacity,
)),
inner: Arc::new(
DashMap::<String, (usize, Duration)>::with_capacity(capacity),
),
}
}
}
@@ -74,10 +74,18 @@ impl Supervised for MemoryStoreActor {
impl Handler<ActorMessage> for MemoryStoreActor {
type Result = ActorResponse;
fn handle(&mut self, msg: ActorMessage, ctx: &mut Self::Context) -> Self::Result {
fn handle(
&mut self,
msg: ActorMessage,
ctx: &mut Self::Context,
) -> Self::Result {
match msg {
ActorMessage::Set { key, value, expiry } => {
debug!("Inserting key {} with expiry {}", &key, &expiry.as_secs());
debug!(
"Inserting key {} with expiry {}",
&key,
&expiry.as_secs()
);
let future_key = String::from(&key);
let now = SystemTime::now();
let now = now.duration_since(UNIX_EPOCH).unwrap();
@@ -85,7 +93,10 @@ impl Handler<ActorMessage> for MemoryStoreActor {
ctx.notify_later(ActorMessage::Remove(future_key), expiry);
ActorResponse::Set(Box::pin(future::ready(Ok(()))))
}
ActorMessage::Update { key, value } => match self.inner.get_mut(&key) {
ActorMessage::Update { key, value } => match self
.inner
.get_mut(&key)
{
Some(mut c) => {
let val_mut: &mut (usize, Duration) = c.value_mut();
if val_mut.0 > value {
@@ -98,7 +109,9 @@ impl Handler<ActorMessage> for MemoryStoreActor {
}
None => {
return ActorResponse::Update(Box::pin(future::ready(Err(
ARError::ReadWriteError("memory store: read failed!".to_string()),
ARError::ReadWriteError(
"memory store: read failed!".to_string(),
),
))))
}
},
@@ -107,9 +120,11 @@ impl Handler<ActorMessage> for MemoryStoreActor {
let val = match self.inner.get(&key) {
Some(c) => c,
None => {
return ActorResponse::Get(Box::pin(future::ready(Err(
ARError::ReadWriteError("memory store: read failed!".to_string()),
))))
return ActorResponse::Get(Box::pin(future::ready(
Err(ARError::ReadWriteError(
"memory store: read failed!".to_string(),
)),
)))
}
};
let val = val.value().0;
@@ -122,14 +137,17 @@ impl Handler<ActorMessage> for MemoryStoreActor {
let c = match self.inner.get(&key) {
Some(d) => d,
None => {
return ActorResponse::Expire(Box::pin(future::ready(Err(
ARError::ReadWriteError("memory store: read failed!".to_string()),
))))
return ActorResponse::Expire(Box::pin(future::ready(
Err(ARError::ReadWriteError(
"memory store: read failed!".to_string(),
)),
)))
}
};
let dur = c.value().1;
let now = SystemTime::now().duration_since(UNIX_EPOCH).unwrap();
let res = dur.checked_sub(now).unwrap_or_else(|| Duration::new(0, 0));
let res =
dur.checked_sub(now).unwrap_or_else(|| Duration::new(0, 0));
ActorResponse::Expire(Box::pin(future::ready(Ok(res))))
}
ActorMessage::Remove(key) => {
@@ -137,9 +155,11 @@ impl Handler<ActorMessage> for MemoryStoreActor {
let val = match self.inner.remove::<String>(&key) {
Some(c) => c,
None => {
return ActorResponse::Remove(Box::pin(future::ready(Err(
ARError::ReadWriteError("memory store: remove failed!".to_string()),
))))
return ActorResponse::Remove(Box::pin(future::ready(
Err(ARError::ReadWriteError(
"memory store: remove failed!".to_string(),
)),
)))
}
};
let val = val.1;

View File

@@ -95,7 +95,9 @@ where
}
/// Function to get the identifier for the client request
pub fn with_identifier<F: Fn(&ServiceRequest) -> Result<String, ARError> + 'static>(
pub fn with_identifier<
F: Fn(&ServiceRequest) -> Result<String, ARError> + 'static,
>(
mut self,
identifier: F,
) -> Self {
@@ -108,7 +110,8 @@ impl<T, S, B> Transform<S, ServiceRequest> for RateLimiter<T>
where
T: Handler<ActorMessage> + Send + Sync + 'static,
T::Context: ToEnvelope<T, ActorMessage>,
S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = AWError> + 'static,
S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = AWError>
+ 'static,
S::Future: 'static,
B: 'static,
{
@@ -141,23 +144,29 @@ where
// Exists here for the sole purpose of knowing the max_requests and interval from RateLimiter
max_requests: usize,
interval: u64,
identifier: Rc<Box<dyn Fn(&ServiceRequest) -> Result<String, ARError> + 'static>>,
identifier:
Rc<Box<dyn Fn(&ServiceRequest) -> Result<String, ARError> + 'static>>,
ignore_ips: Vec<String>,
}
impl<T, S, B> Service<ServiceRequest> for RateLimitMiddleware<S, T>
where
T: Handler<ActorMessage> + 'static,
S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = AWError> + 'static,
S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = AWError>
+ 'static,
S::Future: 'static,
B: 'static,
T::Context: ToEnvelope<T, ActorMessage>,
{
type Response = ServiceResponse<B>;
type Error = S::Error;
type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>>>>;
type Future =
Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>>>>;
fn poll_ready(&self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
fn poll_ready(
&self,
cx: &mut Context<'_>,
) -> Poll<Result<(), Self::Error>> {
self.service.borrow_mut().poll_ready(cx)
}
@@ -185,9 +194,15 @@ where
if let Some(c) = opt {
// Existing entry in store
let expiry = store
.send(ActorMessage::Expire(String::from(&identifier)))
.send(ActorMessage::Expire(String::from(
&identifier,
)))
.await
.map_err(|_| ARError::ReadWriteError("Setting timeout".to_string()))?;
.map_err(|_| {
ARError::ReadWriteError(
"Setting timeout".to_string(),
)
})?;
let reset: Duration = match expiry {
ActorResponse::Expire(dur) => dur.await?,
_ => unreachable!(),
@@ -209,7 +224,9 @@ where
})
.await
.map_err(|_| {
ARError::ReadWriteError("Decrementing ratelimit".to_string())
ARError::ReadWriteError(
"Decrementing ratelimit".to_string(),
)
})?;
let updated_value: usize = match res {
ActorResponse::Update(c) => c.await?,
@@ -222,15 +239,23 @@ where
// Safe unwraps, since usize is always convertible to string
headers.insert(
HeaderName::from_static("x-ratelimit-limit"),
HeaderValue::from_str(max_requests.to_string().as_str())?,
HeaderValue::from_str(
max_requests.to_string().as_str(),
)?,
);
headers.insert(
HeaderName::from_static("x-ratelimit-remaining"),
HeaderValue::from_str(updated_value.to_string().as_str())?,
HeaderName::from_static(
"x-ratelimit-remaining",
),
HeaderValue::from_str(
updated_value.to_string().as_str(),
)?,
);
headers.insert(
HeaderName::from_static("x-ratelimit-reset"),
HeaderValue::from_str(reset.as_secs().to_string().as_str())?,
HeaderValue::from_str(
reset.as_secs().to_string().as_str(),
)?,
);
Ok(res)
}
@@ -245,7 +270,9 @@ where
})
.await
.map_err(|_| {
ARError::ReadWriteError("Creating store entry".to_string())
ARError::ReadWriteError(
"Creating store entry".to_string(),
)
})?;
match res {
ActorResponse::Set(c) => c.await?,
@@ -257,15 +284,24 @@ where
// Safe unwraps, since usize is always convertible to string
headers.insert(
HeaderName::from_static("x-ratelimit-limit"),
HeaderValue::from_str(max_requests.to_string().as_str()).unwrap(),
HeaderValue::from_str(
max_requests.to_string().as_str(),
)
.unwrap(),
);
headers.insert(
HeaderName::from_static("x-ratelimit-remaining"),
HeaderValue::from_str(current_value.to_string().as_str()).unwrap(),
HeaderValue::from_str(
current_value.to_string().as_str(),
)
.unwrap(),
);
headers.insert(
HeaderName::from_static("x-ratelimit-reset"),
HeaderValue::from_str(interval.as_secs().to_string().as_str()).unwrap(),
HeaderValue::from_str(
interval.as_secs().to_string().as_str(),
)
.unwrap(),
);
Ok(res)
}