Skip to content

kolbma/rocket-governor

Repository files navigation

Rust crates.io docs

Description

Implementation of the Governor rate limiter for Rocket web framework.

Rate limiting is used to control the rate requests are received and handled by an endpoint of the web application or web service.

Rocket specific features

Define as many rate limits with Quota of Governor as you like and need in your Rocket web application/service.
It is implemented as a Rocket Request Guard and provides also an implementation of an Error Catcher.
The Error Catcher can be registered on any path to handle Status::TooManyRequests and provide HTTP headers in the response.

Usage

Add dependencies to rocket-governor crate to your Cargo.toml.

Implement RocketGovernable for a guard struct as you like:

use rocket_governor::{Method, Quota, RocketGovernable, RocketGovernor};

pub struct RateLimitGuard;

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

This requires to implement the method fn quota(_: Method, _: &str) -> Quota.
You can vary your Quota on any combination of method and route_name, but the returned Quota should be a static-like. It should not change between invocations of the quota()-method with equal parameters.

There is a small helper function nonzero(u32) for creating Quotas in your quota()-implementation e.g.:

    Quota::per_second(Self::nonzero(1u32))

After implementing the minimal requirements of trait RocketGovernable you can add your Guard to your route-methods like:

#[get("/")]
fn route_test(_limitguard: RocketGovernor<RateLimitGuard>) -> Status {
    Status::Ok
}

Register Catcher

To handle HTTP Status 429 TooManyRequests there is an catcher-function implementation.

It is called rocket_governor_catcher.

Register it with register(<path>, <catchers>)-method of Rocket:

use rocket_governor::rocket_governor_catcher;

#[launch]
fn launch_rocket() -> _ {
    rocket::build()
        .mount("/", routes![route_test])
        .register("/", catchers!(rocket_governor_catcher))
}

Optional feature limit_info

There is the optional feature limit_info which enables reporting about rate limits in HTTP headers of requests.

The implementation is based on headers of https://datatracker.ietf.org/doc/html/draft-ietf-httpapi-ratelimit-headers

The feature provides a default implementation of a Rocket fairing which need to be used to get the HTTP headers set.

See API documentation for LimitHeaderGen.

For usage depend on it in Cargo.toml

[dependencies]
rocket-governor = { version = "...", features = ["limit_info"] }

Optional feature logger

There is the optional feature logger which enables some logging output.

For usage depend on it in Cargo.toml

[dependencies]
rocket-governor = { version = "...", features = ["logger"] }

Additional information

To understand the basics of Rocket, please visit the Rocket Guide:

Licenses

You can choose between MIT License or Apache License 2.0.

MIT License

Copyright (c) 2023 Markus Kolb

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice (including the next paragraph) shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Apache License 2.0

Copyright 2023 Markus Kolb

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.