blib/lib/PAGI/FastAPI/RateLimit/Driver/CHI.pm

filter: Statementstmt 94.8% 37 / 39 Branchbran 66.6% 4 / 6 Conditioncond 80.0% 4 / 5 MC/DCmcdc 66.6% 2 / 3 Subroutinesub 100% 8 / 8 Podpod 100% 3 / 3 totaltotal 90.6% 58 / 64 CC 6 SCAR 9.0
CC
6
Cov
90%
increment_async
4.2
get_async
3.0
BEGIN
1.0
CRAP 2.5
↑ Summary
1 package PAGI::FastAPI::RateLimit::Driver::CHI;
2  
3 2 ▶use v5.38;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 2 ▶use experimental 'class';
Subroutine BEGIN: called CC=1 SCAR=0.0
5 2 ▶use version;
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7 2 our $VERSION = qv('v0.0.1');
8 2 our $AUTHORITY = 'cpan:MANWAR';
9  
10 2 ▶use PAGI::FastAPI::RateLimit::Driver;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 2 ▶use Future;
Subroutine BEGIN: called CC=1 SCAR=0.0
12  
13 2 class PAGI::FastAPI::RateLimit::Driver::CHI :isa(PAGI::FastAPI::RateLimit::Driver) {
14 2 field $chi :param; # Any CHI instance (e.g. Memcached, File, FastMmap)
15 2 field $key_prefix :param = 'pagi_rl:';
16  
17 2 ▶ method increment_async ($key, $ttl) {
Subroutine increment_async: called CC=4 SCAR=14.4
Pod documented
18 2 my $chi_key = $key_prefix . $key;
19 2 my $now = time();
20  
21 2 ▶ my $record = $chi->get($chi_key) // { count => 0, reset_at => $now + $ttl };
Condition100%2/2
$chi->get($chi_key) // {"count", 0, "reset_at", $now + $ttl}
l!l
11
MC/DC100%1/1
$chi->get($chi_key) // {"count", 0, "reset_at", $now + $ttl}
$chi->get($chi_key)
Truth table100%2/2
A
A= $chi->get($chi_key)
Aresult
11
00
22  
23 # Reset bucket if window expired
24 2 ▶ if ($now >= $record->{reset_at}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($now >= $record->{"reset_at"}) 0 2 2
25 0 $record->{count} = 0;
26 0 $record->{reset_at} = $now + $ttl;
27 }
28  
29 2 $record->{count}++;
30  
31 # Calculate remaining duration for CHI TTL
32 2 my $expires_in = $record->{reset_at} - $now;
33 2 ▶ $expires_in = 1 if $expires_in <= 0;
Branch: 1 branch
BranchTrueFalseTotal
if $expires_in <= 0 0 2 2
34  
35 2 $chi->set($chi_key, $record, "${expires_in}s");
36  
37 2 return Future->done($record->{count});
38 }
39  
40 2 ▶ method get_async ($key) {
Subroutine get_async: called CC=3 SCAR=11.0
Pod documented
41 2 my $chi_key = $key_prefix . $key;
42 2 my $record = $chi->get($chi_key);
43  
44 2 ▶ if ($record && time() < $record->{reset_at}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($record and time < $record->{"reset_at"}) 1 1 2
Condition66%2/3
$record and time < $record->{"reset_at"}
!ll&&!rl&&r
101
MC/DC50%1/2
$record and time < $record->{"reset_at"}
$record time < $record->{"reset_at"}
Truth table66%2/3
A and B
A= $recordB= time < $record->{"reset_at"}
ABresult
0X0
100
111
45 1 return Future->done($record->{count});
46 }
47  
48 1 return Future->done(0);
49 }
50  
51 1 ▶ method reset_async ($key) {
Subroutine reset_async: called CC=1 SCAR=0.0
Pod documented
52 1 my $chi_key = $key_prefix . $key;
53 1 $chi->remove($chi_key);
54 1 return Future->done(1);
55 }
56 }
57  
58 2 1;
59  
60 __END__
↑ Summary