pub trait RocketGovernable<'r> {
    fn quota(method: Method, route_name: &str) -> Quota;

    fn limit_info_allow(
        method: Option<Method>,
        route_name: Option<&str>,
        state: &ReqState
    ) -> bool { ... } fn nonzero(n: u32) -> NonZeroU32 { ... } }
Expand description

The RocketGovernable guard trait.

rocket-governor is a rocket guard implementation of the governor rate limiter.

Declare a struct and use it with the generic RocketGovernor guard. This requires to implement RocketGovernable for your struct.

See the top level crate documentation.

Required Methods

Returns the Quota of the RocketGovernable.

This is called only once per method/route_name combination. So it makes only sense to return always the same Quota for equal parameter combinations and no dynamic calculation.

This is also the requirement to have correct information set in HTTP headers by registered rocket_governor_catcher().

Provided Methods

Returns true if HTTP rate limit info headers should be set in requests.

Implement limit_info_allow() to change to your preference.

The trait implementation enables info headers only just the request before any further request would be rate limited. This is because of speed, bandwidth and safety.

In draft-ietf-httpapi-ratelimit-headers#section-6.2 you can read the following information about…

Information disclosure

Servers should not disclose to untrusted parties operational capacity information that can be used to saturate its infrastructural resources.

While this specification does not mandate whether non 2xx responses consume quota, if 401 and 403 responses count on quota a malicious client could probe the endpoint to get traffic information of another user.

As intermediaries might retransmit requests and consume quota-units without prior knowledge of the User Agent, RateLimit fields might reveal the existence of an intermediary to the User Agent.

Feature availability

limit_info_allow() is only available when feature limit_info is enabled.

Example
use rocket_governor::{Method, Quota, ReqState, RocketGovernable};

pub struct RateLimitGuard;

impl<'r> RocketGovernable<'r> for RateLimitGuard {
    fn quota(_method: Method, _route_name: &str) -> Quota {
        Quota::per_second(Self::nonzero(1u32))
    }

    fn limit_info_allow(
        method: Option<Method>,
        route_name: Option<&str>,
        state: &ReqState,
    ) -> bool {
        let mut cap = 1;
        if let Some(m) = method {
            if m == Method::Post {
                if let Some(route) = route_name {
                    if route == "admin_action" {
                        cap = 20;
                    }
                }
            }
        }
        state.request_capacity() <= cap
    }
}

Converts a non-zero number u32 to NonZeroU32.

Number zero/0 becomes 1.

Implementors