blib/lib/PAGI/App/Throttle.pm untested

filter: Statementstmt 0.0% 0 / 77 Branchbran 0.0% 0 / 16 Conditioncond 0.0% 0 / 15 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 8 Podpod 0.0% 0 / 5 totaltotal 0.0% 0 / 121 CC 9 SCAR 36.2
CC
9
Cov
0%
to_app
72.0
info
6.0
new
2.0
CRAP 37.5
1 package PAGI::App::Throttle;
2 $PAGI::App::Throttle::VERSION = '0.002001';
3 use strict;
4 use warnings;
5 use Future::AsyncAwait;
6  
7 =head1 NAME
8  
9 PAGI::App::Throttle - Rate-limited request processing
10  
11 =head1 SYNOPSIS
12  
13 use PAGI::App::Throttle;
14  
15 my $app = PAGI::App::Throttle->new(
16 app => $inner_app,
17 rate => 10, # requests per second
18 burst => 20, # max burst
19 key_for => sub { $_[0]->{client}[0] }, # key by IP
20 )->to_app;
21  
22 =cut
23  
24 # Token bucket state per key
25 my %buckets;
26  
27 sub new {
28 my ($class, %args) = @_;
29  
30 return bless {
31 app => $args{app},
32 rate => $args{rate} // 10,
33 burst => $args{burst} // ($args{rate} // 10),
34 key_for => $args{key_for},
35 on_limit => $args{on_limit},
36 headers => $args{headers} // 1,
37 }, $class;
38 }
39  
40 sub to_app {
41 my ($self) = @_;
42  
43 my $app = $self->{app};
44 my $rate = $self->{rate};
45 my $burst = $self->{burst};
46 my $key_for = $self->{key_for};
47 my $on_limit = $self->{on_limit};
48 my $add_headers = $self->{headers};
49  
50 return async sub {
51 my ($scope, $receive, $send) = @_;
52 my $key = $key_for ? $key_for->($scope) : 'global';
53 $key //= 'global';
54  
55 # Initialize bucket
56 $buckets{$key} //= {
57 tokens => $burst,
58 last_time => time(),
59 };
60  
61 my $bucket = $buckets{$key};
62  
63 # Refill tokens based on elapsed time
64 my $now = time();
65 my $elapsed = $now - $bucket->{last_time};
66 $bucket->{tokens} += $elapsed * $rate;
67 $bucket->{tokens} = $burst if $bucket->{tokens} > $burst;
68 $bucket->{last_time} = $now;
69  
70 # Check if request allowed
71 if ($bucket->{tokens} >= 1) {
72 $bucket->{tokens} -= 1;
73  
74 # Wrap send to add rate limit headers
75 my $wrapped_send = $send;
76 if ($add_headers) {
77 $wrapped_send = async sub {
78 my ($event) = @_;
79 if ($event->{type} eq 'http.response.start') {
80 my @headers = @{$event->{headers} // []};
81 push @headers, ['x-ratelimit-limit', $burst];
82 push @headers, ['x-ratelimit-remaining', int($bucket->{tokens})];
83 push @headers, ['x-ratelimit-reset', int($now + ($burst - $bucket->{tokens}) / $rate)];
84 $event = { %$event, headers => \@headers };
85 }
86 await $send->($event);
87 };
88 }
89  
90 await $app->($scope, $receive, $wrapped_send);
91 } else {
92 # Rate limited
93 my $retry_after = int((1 - $bucket->{tokens}) / $rate) + 1;
94  
95 if ($on_limit) {
96 await $on_limit->($scope, $receive, $send, $retry_after);
97 } else {
98 my @headers = (
99 ['content-type', 'text/plain'],
100 ['retry-after', $retry_after],
101 );
102  
103 if ($add_headers) {
104 push @headers, ['x-ratelimit-limit', $burst];
105 push @headers, ['x-ratelimit-remaining', 0];
106 push @headers, ['x-ratelimit-reset', int($now + $retry_after)];
107 }
108  
109 await $send->({
110 type => 'http.response.start',
111 status => 429,
112 headers => \@headers,
113 });
114 await $send->({
115 type => 'http.response.body',
116 body => 'Too Many Requests',
117 more => 0,
118 });
119 }
120 }
121 };
122 }
123  
124 # Class method to reset a key's bucket
125 sub reset {
126 my ($class, $key) = @_;
127  
128 delete $buckets{$key};
129 }
130  
131 # Class method to reset all buckets
132 sub reset_all {
133 my ($class) = @_;
134  
135 %buckets = ();
136 }
137  
138 # Class method to get bucket info
139 sub info {
140 my ($class, $key) = @_;
141  
142 return undef unless $buckets{$key};
143 return {
144 tokens => $buckets{$key}{tokens},
145 last_time => $buckets{$key}{last_time},
146 };
147 }
148  
149 1;
150  
151 __END__