thruster-rate-limit

A super simple rate limiting middleware for the thruster web framework.

Currently supports only the hyper backend of thruster, basically hyper_server feature must be enabled!

Table of Contents

Simple example

```rust struct ServerState { rate_limiter: RateLimiter, }

[context_state]

struct RequestState(RateLimiter, Box); type Ctx = TypedHyperContext;

struct RateLimiterConf; impl Configuration for RateLimiterConf {}

[middleware_fn]

async fn root(mut context: Ctx, next: MiddlewareNext) -> MiddlewareResult { context.body(BODYSTR); return Ok(context); }

fn generatecontext(request: HyperRequest, state: &ServerState, _path: &str) -> Ctx { return Ctx::new( request, RequestState(state.ratelimiter.clone(), Box::new(RateLimiterConf)), ); }

[tokio::test]

async fn helloworld() { let ratelimiter = RateLimiter { max: 100, per_s: 60, store: MapStore::new(), };

let app = App::<HyperRequest, Ctx, ServerState>::create(generate_context, ServerState { rate_limiter })
    .middleware("/", m![rate_limit_middleware])
    .get("/", m![root])
    .commit();

let response = Testable::get(&app, "/", vec![])
    .await
    .unwrap()
    .expect_status(200, "OK");

assert_eq!(response.body_string(), BODY_STR);

} ```

Options

```rust

[derive(Clone)]

pub struct RateLimiter { pub max: usize, pub per_s: usize, pub store: S, } ```

Configuration

This is currently pretty basic, but you can extend the functionality of the rate limiter based on your needs by implementing the Configuration trait

```rust pub trait Configuration { fn shouldlimit(&self, _context: &TypedHyperContext) -> bool { return true; } fn getkey(&self, context: &TypedHyperContext) -> String { if let Some(request) = context.hyperrequest.asref() { if let Some(ip) = request.ip { return ip.to_string(); } }

    return "".to_string();
}

} ```

Stores

Simple in-memory store: ```rust

[derive(Clone)]

pub struct MapStore { hash_map: Arc>>, } ```

Redis store: ```rust

[derive(Clone)]

pub struct RedisStore { connection_manager: ConnectionManager, } ```