| 1 | package PAGI::FastAPI::Middleware::RateLimit; | ||||||||||||||||||||
| 2 | |||||||||||||||||||||
| 3 | 22 | ▶ | use v5.38; | ||||||||||||||||||
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||||||||||||||||||||
| 4 | 22 | ▶ | use experimental 'class'; | ||||||||||||||||||
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||||||||||||||||||||
| 5 | 22 | ▶ | use version; | ||||||||||||||||||
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||||||||||||||||||||
| 6 | |||||||||||||||||||||
| 7 | 22 | our $VERSION = qv('v1.7.3'); | |||||||||||||||||||
| 8 | 22 | our $AUTHORITY = 'cpan:MANWAR'; | |||||||||||||||||||
| 9 | |||||||||||||||||||||
| 10 | 22 | ▶ | use Future::AsyncAwait; | ||||||||||||||||||
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||||||||||||||||||||
| 11 | 22 | ▶ | use PAGI::FastAPI::RateLimit::Driver::Memory; | ||||||||||||||||||
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||||||||||||||||||||
| 12 | |||||||||||||||||||||
| 13 | 22 | class PAGI::FastAPI::Middleware::RateLimit { | |||||||||||||||||||
| 14 | 22 | field $requests :param = 100; | |||||||||||||||||||
| 15 | 22 | field $window :param = 60; | |||||||||||||||||||
| 16 | 22 | field $key_cb :param = undef; | |||||||||||||||||||
| 17 | 22 | field $driver :param = undef; | |||||||||||||||||||
| 18 | 22 | field $trust_proxies :param = 0; | |||||||||||||||||||
| 19 | |||||||||||||||||||||
| 20 | 4 | ▶ | ADJUST { | ||||||||||||||||||
|
Subroutine
__ANON__: called CC=3 SCAR=11.4
| |||||||||||||||||||||
| 21 | 4 | ▶ | $driver //= PAGI::FastAPI::RateLimit::Driver::Memory->new(); | ||||||||||||||||||
|
Condition66%2/3
$driver //= "PAGI::FastAPI::RateLimit::Driver::Memory"->new
MC/DC0%0/2
$driver //= "PAGI::FastAPI::RateLimit::Driver::Memory"->new
$driver
"PAGI::FastAPI::RateLimit::Driver::Memory"->new
Truth table66%2/3
A //= B
A= $driverB= "PAGI::FastAPI::RateLimit::Driver::Memory"->new
| |||||||||||||||||||||
| 22 | $key_cb //= sub ($c) { | ||||||||||||||||||||
| 23 | # Rely on verified TCP peer socket by default | ||||||||||||||||||||
| 24 | return $c->scope->{client}[0] // '127.0.0.1' unless $trust_proxies; | ||||||||||||||||||||
| 25 | |||||||||||||||||||||
| 26 | # Only inspect headers if explicit opt-in is enabled | ||||||||||||||||||||
| 27 | return $c->header('X-API-Key') | ||||||||||||||||||||
| 28 | // $c->header('X-Forwarded-For') | ||||||||||||||||||||
| 29 | // $c->scope->{client}[0] | ||||||||||||||||||||
| 30 | // '127.0.0.1'; | ||||||||||||||||||||
| 31 | 4 | ▶ | }; | ||||||||||||||||||
|
Condition66%2/3
$key_cb //= sub ($c) {
return $c->scope->{"client"}[0] // "127.0.0.1" unless $trust_proxies;
return (($c->header("X-API-Key") // $c->header("X-Forwarded-For")) // $c->scope->{"client"}[0]) // "127.0.0.1";
}
MC/DC0%0/2
$key_cb //= sub ($c) {
return $c->scope->{"client"}[0] // "127.0.0.1" unless $trust_proxies;
return (($c->header("X-API-Key") // $c->header("X-Forwarded-For")) // $c->scope->{"client"}[0]) // "127.0.0.1";
}
$key_cb
sub ($c) {
return $c->scope->{"client"}[0] // "127.0.0.1" unless $trust_proxies;
return (($c->header("X-API-Key") // $c->header("X-Forwarded-For")) // $c->scope->{"client"}[0]) // "127.0.0.1";
}
Truth table66%2/3
A //= B
A= $key_cbB= sub ($c) {
return $c->scope->{"client"}[0] // "127.0.0.1" unless $trust_proxies;
return (($c->header("X-API-Key") // $c->header("X-Forwarded-For")) // $c->scope->{"client"}[0]) // "127.0.0.1";
}
| |||||||||||||||||||||
| 32 | } | ||||||||||||||||||||
| 33 | |||||||||||||||||||||
| 34 | 28 | ▶ | async method handle ($c, $next) { | ||||||||||||||||||
|
Subroutine
handle: called CC=6 SCAR=18.0
Pod
documented
| |||||||||||||||||||||
| 35 | 28 | my $key = $key_cb->($c); | |||||||||||||||||||
| 36 | |||||||||||||||||||||
| 37 | 28 | my ($count, $reset_at) = await $driver->increment_async($key, $window); | |||||||||||||||||||
| 38 | |||||||||||||||||||||
| 39 | 28 | my $remaining = $requests - $count; | |||||||||||||||||||
| 40 | 28 | ▶ | $remaining = 0 if $remaining < 0; | ||||||||||||||||||
|
Branch: 1 branch
| |||||||||||||||||||||
| 41 | |||||||||||||||||||||
| 42 | 28 | my $now = time(); | |||||||||||||||||||
| 43 | 28 | ▶ | my $retry_after = ($reset_at // ($now + $window)) - $now; | ||||||||||||||||||
|
Condition50%1/2
$reset_at // $now + $window
MC/DC0%0/1
$reset_at // $now + $window
$reset_at
Truth table50%1/2
A
A= $reset_at
| |||||||||||||||||||||
| 44 | 28 | ▶ | $retry_after = 1 if $retry_after <= 0; | ||||||||||||||||||
|
Branch: 1 branch
| |||||||||||||||||||||
| 45 | |||||||||||||||||||||
| 46 | 28 | $c->add_header('x-ratelimit-limit' => $requests); | |||||||||||||||||||
| 47 | 28 | $c->add_header('x-ratelimit-remaining' => $remaining); | |||||||||||||||||||
| 48 | 28 | ▶ | $c->add_header('x-ratelimit-reset' => $reset_at) if $reset_at; | ||||||||||||||||||
|
Branch: 1 branch
| |||||||||||||||||||||
| 49 | |||||||||||||||||||||
| 50 | 28 | ▶ | if ($count > $requests) { | ||||||||||||||||||
|
Branch: 1 branch
| |||||||||||||||||||||
| 51 | 5 | $c->status(429); | |||||||||||||||||||
| 52 | 5 | $c->set_header('retry-after' => $retry_after); | |||||||||||||||||||
| 53 | return { | ||||||||||||||||||||
| 54 | 5 | detail => 'Too Many Requests', | |||||||||||||||||||
| 55 | message => 'API rate limit exceeded. Please try again later.', | ||||||||||||||||||||
| 56 | retry_after => $retry_after, | ||||||||||||||||||||
| 57 | }; | ||||||||||||||||||||
| 58 | } | ||||||||||||||||||||
| 59 | |||||||||||||||||||||
| 60 | 23 | return await $next->($c); | |||||||||||||||||||
| 61 | 22 | } | |||||||||||||||||||
| 62 | } | ||||||||||||||||||||
| 63 | |||||||||||||||||||||
| 64 | =encoding utf-8 | ||||||||||||||||||||
| 65 | |||||||||||||||||||||
| 66 | =head1 NAME | ||||||||||||||||||||
| 67 | |||||||||||||||||||||
| 68 | PAGI::FastAPI::Middleware::RateLimit - Async Rate Limiting Middleware for PAGI::FastAPI | ||||||||||||||||||||
| 69 | |||||||||||||||||||||
| 70 | =head1 VERSION | ||||||||||||||||||||
| 71 | |||||||||||||||||||||
| 72 | Version v1.7.3 | ||||||||||||||||||||
| 73 | |||||||||||||||||||||
| 74 | =head1 SYNOPSIS | ||||||||||||||||||||
| 75 | |||||||||||||||||||||
| 76 | # Application-wide rate limiting | ||||||||||||||||||||
| 77 | use PAGI::FastAPI; | ||||||||||||||||||||
| 78 | |||||||||||||||||||||
| 79 | my $app = PAGI::FastAPI->new(); | ||||||||||||||||||||
| 80 | |||||||||||||||||||||
| 81 | $app->add_rate_limit( | ||||||||||||||||||||
| 82 | requests => 100, | ||||||||||||||||||||
| 83 | window => 60, # 100 requests per 60 seconds | ||||||||||||||||||||
| 84 | ); | ||||||||||||||||||||
| 85 | |||||||||||||||||||||
| 86 | # Custom rate-limiting key based on authenticated user | ||||||||||||||||||||
| 87 | $app->add_rate_limit( | ||||||||||||||||||||
| 88 | requests => 50, | ||||||||||||||||||||
| 89 | window => 30, | ||||||||||||||||||||
| 90 | key_cb => sub ($c) { | ||||||||||||||||||||
| 91 | return $c->stash->{user_id} // $c->header('X-API-Key') // 'anonymous'; | ||||||||||||||||||||
| 92 | }, | ||||||||||||||||||||
| 93 | ); | ||||||||||||||||||||
| 94 | |||||||||||||||||||||
| 95 | # Direct instantiation | ||||||||||||||||||||
| 96 | use PAGI::FastAPI::Middleware::RateLimit; | ||||||||||||||||||||
| 97 | |||||||||||||||||||||
| 98 | my $limiter = PAGI::FastAPI::Middleware::RateLimit->new( | ||||||||||||||||||||
| 99 | requests => 500, | ||||||||||||||||||||
| 100 | window => 3600, | ||||||||||||||||||||
| 101 | ); | ||||||||||||||||||||
| 102 | |||||||||||||||||||||
| 103 | $app->add_middleware(async sub ($c, $next) { | ||||||||||||||||||||
| 104 | return await $limiter->handle($c, $next); | ||||||||||||||||||||
| 105 | }); | ||||||||||||||||||||
| 106 | |||||||||||||||||||||
| 107 | =head1 DESCRIPTION | ||||||||||||||||||||
| 108 | |||||||||||||||||||||
| 109 | C<PAGI::FastAPI::Middleware::RateLimit> provides asynchronous, non-blocking rate | ||||||||||||||||||||
| 110 | limiting for L<PAGI::FastAPI> applications using fixed time-window counters. | ||||||||||||||||||||
| 111 | |||||||||||||||||||||
| 112 | When a client sends a request, the middleware evaluates a unique key identifying | ||||||||||||||||||||
| 113 | the client (e.g., API key or IP address), increments the tracking counter for the | ||||||||||||||||||||
| 114 | active window, and appends standard rate-limiting headers to the HTTP response. | ||||||||||||||||||||
| 115 | |||||||||||||||||||||
| 116 | If a client exceeds their allocated quota within the configured timeframe, the | ||||||||||||||||||||
| 117 | middleware short-circuits execution, sets the response status to C<HTTP 429 Too Many Requests>, | ||||||||||||||||||||
| 118 | and returns a standardized JSON error payload detailing the restriction. | ||||||||||||||||||||
| 119 | |||||||||||||||||||||
| 120 | =head1 HTTP HEADERS | ||||||||||||||||||||
| 121 | |||||||||||||||||||||
| 122 | The middleware injects the following response headers into all evaluated requests: | ||||||||||||||||||||
| 123 | |||||||||||||||||||||
| 124 | =over 4 | ||||||||||||||||||||
| 125 | |||||||||||||||||||||
| 126 | =item * C<x-ratelimit-limit> - Maximum number of allowed requests per window. | ||||||||||||||||||||
| 127 | |||||||||||||||||||||
| 128 | =item * C<x-ratelimit-remaining> - Remaining request quota in the current window. | ||||||||||||||||||||
| 129 | |||||||||||||||||||||
| 130 | =item * C<x-ratelimit-reset> - Unix timestamp indicating when the current window expires. | ||||||||||||||||||||
| 131 | |||||||||||||||||||||
| 132 | =back | ||||||||||||||||||||
| 133 | |||||||||||||||||||||
| 134 | When the limit is exceeded (HTTP 429), an additional header is included: | ||||||||||||||||||||
| 135 | |||||||||||||||||||||
| 136 | =over 4 | ||||||||||||||||||||
| 137 | |||||||||||||||||||||
| 138 | =item * C<retry-after> - Number of seconds the client must wait before retrying. | ||||||||||||||||||||
| 139 | |||||||||||||||||||||
| 140 | =back | ||||||||||||||||||||
| 141 | |||||||||||||||||||||
| 142 | =head1 METHODS | ||||||||||||||||||||
| 143 | |||||||||||||||||||||
| 144 | =head2 C<new(%options)> | ||||||||||||||||||||
| 145 | |||||||||||||||||||||
| 146 | Instantiates a new C<PAGI::FastAPI::Middleware::RateLimit> instance. Accepts | ||||||||||||||||||||
| 147 | the following named arguments: | ||||||||||||||||||||
| 148 | |||||||||||||||||||||
| 149 | =over 4 | ||||||||||||||||||||
| 150 | |||||||||||||||||||||
| 151 | =item * C<requests> - Optional integer. Maximum number of allowed requests | ||||||||||||||||||||
| 152 | per window. Default: C<100>. | ||||||||||||||||||||
| 153 | |||||||||||||||||||||
| 154 | =item * C<window> - Optional integer. Duration of the rate-limiting window | ||||||||||||||||||||
| 155 | in seconds. Default: C<60>. | ||||||||||||||||||||
| 156 | |||||||||||||||||||||
| 157 | =item * C<key_cb> - Optional C<CODE> reference accepting a | ||||||||||||||||||||
| 158 | L<PAGI::FastAPI::Context> instance (C<$c>) and returning a unique scalar | ||||||||||||||||||||
| 159 | string key identifying the client. By default, it falls back through: | ||||||||||||||||||||
| 160 | |||||||||||||||||||||
| 161 | 1. C<X-API-Key> request header | ||||||||||||||||||||
| 162 | 2. C<X-Forwarded-For> request header | ||||||||||||||||||||
| 163 | 3. Client connection remote IP address (C<< $c->scope->{client}[0] >>) | ||||||||||||||||||||
| 164 | 4. Fallback default string C<'127.0.0.1'> | ||||||||||||||||||||
| 165 | |||||||||||||||||||||
| 166 | =item * C<driver> - Optional storage object implementing | ||||||||||||||||||||
| 167 | C<increment_async($key, $window)>, C<get_async($key)> and C<reset_async($key)>. | ||||||||||||||||||||
| 168 | Defaults to an instance of L<PAGI::FastAPI::RateLimit::Driver::Memory>. | ||||||||||||||||||||
| 169 | |||||||||||||||||||||
| 170 | =item * C<trust_proxies> - Optional boolean. When set to false (default), | ||||||||||||||||||||
| 171 | the default identification key strictly uses the remote socket address | ||||||||||||||||||||
| 172 | (C<< $c->scope->{client}[0] >>) to prevent header spoofing bypasses. Set to | ||||||||||||||||||||
| 173 | true to allow fallback to C<X-API-Key> or C<X-Forwarded-For>. | ||||||||||||||||||||
| 174 | |||||||||||||||||||||
| 175 | =back | ||||||||||||||||||||
| 176 | |||||||||||||||||||||
| 177 | =head2 C<handle($c, $next)> | ||||||||||||||||||||
| 178 | |||||||||||||||||||||
| 179 | my $res = await $limiter->handle($c, $next); | ||||||||||||||||||||
| 180 | |||||||||||||||||||||
| 181 | Asynchronous method that executes the rate-limiting logic within the request | ||||||||||||||||||||
| 182 | pipeline: | ||||||||||||||||||||
| 183 | |||||||||||||||||||||
| 184 | =over 4 | ||||||||||||||||||||
| 185 | |||||||||||||||||||||
| 186 | =item 1. Evaluates the client key using C<key_cb>. | ||||||||||||||||||||
| 187 | |||||||||||||||||||||
| 188 | =item 2. Queries and increments the request count in the configured C<driver>. | ||||||||||||||||||||
| 189 | |||||||||||||||||||||
| 190 | =item 3. Appends standard rate limit HTTP headers (C<x-ratelimit-*>) to C<$c>. | ||||||||||||||||||||
| 191 | |||||||||||||||||||||
| 192 | =item 4. Returns an HTTP 429 JSON response if the request limit is exceeded. | ||||||||||||||||||||
| 193 | |||||||||||||||||||||
| 194 | =item 5. Awaits and returns C<< $next->($c) >> if the client is within quota. | ||||||||||||||||||||
| 195 | |||||||||||||||||||||
| 196 | =back | ||||||||||||||||||||
| 197 | |||||||||||||||||||||
| 198 | =head1 ERROR RESPONSE STRUCTURE | ||||||||||||||||||||
| 199 | |||||||||||||||||||||
| 200 | When a request is rate-limited (HTTP status 429), the returned JSON structure is: | ||||||||||||||||||||
| 201 | |||||||||||||||||||||
| 202 | { | ||||||||||||||||||||
| 203 | "detail": "Too Many Requests", | ||||||||||||||||||||
| 204 | "message": "API rate limit exceeded. Please try again later.", | ||||||||||||||||||||
| 205 | "retry_after": 45 | ||||||||||||||||||||
| 206 | } | ||||||||||||||||||||
| 207 | |||||||||||||||||||||
| 208 | =head1 AUTHOR | ||||||||||||||||||||
| 209 | |||||||||||||||||||||
| 210 | Mohammad Sajid Anwar, C<< <mohammad.anwar at yahoo.com> >> | ||||||||||||||||||||
| 211 | |||||||||||||||||||||
| 212 | =head1 REPOSITORY | ||||||||||||||||||||
| 213 | |||||||||||||||||||||
| 214 | L<https://github.com/manwar/PAGI-FastAPI> | ||||||||||||||||||||
| 215 | |||||||||||||||||||||
| 216 | =head1 BUGS | ||||||||||||||||||||
| 217 | |||||||||||||||||||||
| 218 | Please report any bugs or feature requests through the web interface at L<https://github.com/manwar/PAGI-FastAPI/issues>. | ||||||||||||||||||||
| 219 | I will be notified and then you'll automatically be notified of progress on your | ||||||||||||||||||||
| 220 | bug as I make changes. | ||||||||||||||||||||
| 221 | |||||||||||||||||||||
| 222 | =head1 SUPPORT | ||||||||||||||||||||
| 223 | |||||||||||||||||||||
| 224 | You can find documentation for this module with the perldoc command. | ||||||||||||||||||||
| 225 | |||||||||||||||||||||
| 226 | perldoc PAGI::FastAPI::Middleware::RateLimit | ||||||||||||||||||||
| 227 | |||||||||||||||||||||
| 228 | You can also look for information at: | ||||||||||||||||||||
| 229 | |||||||||||||||||||||
| 230 | =over 4 | ||||||||||||||||||||
| 231 | |||||||||||||||||||||
| 232 | =item * BUG Report | ||||||||||||||||||||
| 233 | |||||||||||||||||||||
| 234 | L<https://github.com/manwar/PAGI-FastAPI/issues> | ||||||||||||||||||||
| 235 | |||||||||||||||||||||
| 236 | =item * Search MetaCPAN | ||||||||||||||||||||
| 237 | |||||||||||||||||||||
| 238 | L<https://metacpan.org/dist/PAGI-FastAPI/> | ||||||||||||||||||||
| 239 | |||||||||||||||||||||
| 240 | =back | ||||||||||||||||||||
| 241 | |||||||||||||||||||||
| 242 | =head1 LICENSE AND COPYRIGHT | ||||||||||||||||||||
| 243 | |||||||||||||||||||||
| 244 | Copyright (C) 2026 Mohammad Sajid Anwar. | ||||||||||||||||||||
| 245 | |||||||||||||||||||||
| 246 | This program is free software; you can redistribute it and/or modify it under | ||||||||||||||||||||
| 247 | the terms of the Artistic License (2.0). | ||||||||||||||||||||
| 248 | |||||||||||||||||||||
| 249 | =cut | ||||||||||||||||||||
| 250 | |||||||||||||||||||||
| 251 | 22 | 1; # End of PAGI::FastAPI::Middleware::RateLimit | |||||||||||||||||||