Skip to content

Commit

Permalink
feat: Send additional info on rate limit
Browse files Browse the repository at this point in the history
  • Loading branch information
abdulrahman1s committed Jul 15, 2022
1 parent 73b37e0 commit 4564a1b
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 3 deletions.
2 changes: 1 addition & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ async fn main() {
let app = routes::mount(Router::new())
.route("/ws", axum::routing::get(gateway::upgrade))
.layer(middleware::from_fn(auth::handle))
.layer(middleware::from_fn(ratelimit::handle!(50, 1000 * 60)))
.layer(middleware::from_fn(ratelimit::handle!(3, 1000 * 60)))
.layer(cors::handle())
.fallback((|| async { StatusCode::NOT_FOUND }).into_service());

Expand Down
12 changes: 10 additions & 2 deletions src/utils/error.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use crate::middlewares::ratelimit::RateLimitInfo;
use axum::{
extract::rejection::JsonRejection,
http::StatusCode,
http::{HeaderMap, StatusCode},
response::{IntoResponse, Json, Response},
};
use quick_error::quick_error;
Expand Down Expand Up @@ -85,16 +85,24 @@ impl IntoResponse for Error {
let status = match self {
Error::RateLimited { .. } => StatusCode::TOO_MANY_REQUESTS,
Error::InvalidToken => StatusCode::UNAUTHORIZED,
Error::InvalidBody => StatusCode::UNPROCESSABLE_ENTITY,
_ => StatusCode::BAD_REQUEST,
};

let mut headers = HeaderMap::new();
let mut body = serde_json::json!({ "type": self });
let msg = self.to_string();

if msg.contains(' ') {
body["message"] = serde_json::json!(msg);
}

(status, Json(body)).into_response()
if let Error::RateLimited(info) = self {
headers.insert("X-RateLimit-Remaining", info.remaining.into());
headers.insert("X-RateLimit-Limit", info.limit.into());
headers.insert("Retry-After", info.retry_after.into());
}

(status, headers, Json(body)).into_response()
}
}

0 comments on commit 4564a1b

Please sign in to comment.