blib/lib/RateLimitations/Pluggable.pm

filter: Statementstmt 98.4% 64 / 65 Branchbran 60.0% 18 / 30 Conditioncond 63.6% 7 / 11 MC/DCmcdc 33.3% 2 / 6 Subroutinesub 100% 9 / 9 Podpod 50.0% 1 / 2 totaltotal 82.1% 101 / 123 CC 24 SCAR 19.4
CC
24
Cov
84%
within_rate_limits
10.1
BUILD
9.3
__ANON__
4.1
CRAP 7.0
↑ Summary
1 package RateLimitations::Pluggable;
2  
3 2 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 2 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5  
6 2 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 2 ▶use Moo;
Subroutine BEGIN: called CC=1 SCAR=0.0
8  
9 2 our $VERSION = '0.02';
10  
11 =head1 NAME
12  
13 RateLimitations::Pluggable - pluggabe manager of per-service rate limitations
14  
15 =head1 STATUS
16  
17 =begin HTML
18  
19 <p>
20 <a href="https://travis-ci.org/binary-com/perl-RateLimitations-Pluggable"><img src="https://travis-ci.org/binary-com/perl-RateLimitations-Pluggable.svg" /></a>
21 </p>
22  
23 =end HTML
24  
25 =head1 SYNOPSIS
26  
27 my $storage = {};
28  
29 my $rl = RateLimitations::Pluggable->new({
30 limits => {
31 sample_service => {
32 60 => 2, # per minute limits
33 3600 => 5, # per hour limits
34 }
35 },
36 # define an subroutine where hits are stored: redis, db, file, in-memory, cookies
37 getter => sub {
38 my ($service, $consumer) = @_;
39 return $storage->{$service}->{$consumer};
40 },
41 # optional, notify back when hits are updated
42 setter => sub {
43 my ($service, $consumer, $hits) = @_;
44 $storage->{$service}->{$consumer} = $hits;
45 },
46 });
47  
48 $rl->within_rate_limits('sample_service', 'some_client_id'); # true!
49 $rl->within_rate_limits('sample_service', 'some_client_id'); # true!
50 $rl->within_rate_limits('sample_service', 'some_client_id'), # false!
51  
52  
53 =head1 DESCRIPTION
54  
55 The module access to build-in C<time> function every time you invoke
56 C<within_rate_limits> method, and checks whether limits are hits or not.
57  
58 Each time the method C<within_rate_limits> is invoked it appends
59 to the array of hit current time. It check that array will not
60 grow endlessly, and holds in per $service (or per $service/$consumer)
61 upto max_time integers.
62  
63 The array can be stored anywhere (disk, redis, DB, in-memory), hence the module
64 name is.
65  
66 =cut
67  
68 =head1 ATTRIBUTES
69  
70 =head2 limits
71  
72 Defines per-service limits. Below
73  
74 {
75 service_1 => {
76 60 => 20, # up to 20 service_1 invocations per 1 minute
77 3600 => 50, # OR up to 50 service_1 invocations per 1 hour
78 },
79  
80 service_2 => {
81 60 => 25,
82 3600 => 60,
83 }
84  
85 }
86  
87 Mandatory.
88  
89 =head2 getter->($service, $consumer)
90  
91 Mandatory coderef which returns an array of hits for the service and some
92 C<consumer>.
93  
94  
95 =head2 setter->($service, $consumer, $hits)
96  
97 Optional callback for storing per service/consumer array of hits.
98  
99 =cut
100  
101 has limits => (
102 is => 'ro',
103 required => 1,
104 1 ▶ isa => sub {
Subroutine __ANON__: called CC=3 SCAR=12.7
105 1 ▶ croak "limits must be a hashref"
Branch: 1 branch
BranchTrueFalseTotal
unless (ref $_[0] // "") eq "HASH" 0 1 1
Condition50%1/2
ref $_[0] // ""
l!l
10
MC/DC0%0/1
ref $_[0] // ""
ref $_[0]
Truth table50%1/2
A
A= ref $_[0]
Aresult
11
00
106 unless (ref($_[0]) // '') eq 'HASH';
107 },
108 2 );
109 has getter => (
110 is => 'ro',
111 required => 1,
112 1 ▶ isa => sub {
Subroutine __ANON__: called CC=3 SCAR=12.7
113 1 ▶ croak "limits must be a coderef"
Branch: 1 branch
BranchTrueFalseTotal
unless (ref $_[0] // "") eq "CODE" 0 1 1
Condition50%1/2
ref $_[0] // ""
l!l
10
MC/DC0%0/1
ref $_[0] // ""
ref $_[0]
Truth table50%1/2
A
A= ref $_[0]
Aresult
11
00
114 unless (ref($_[0]) // '') eq 'CODE';
115 },
116 2 );
117  
118 has setter => (
119 is => 'ro',
120 required => 0,
121 1 ▶ isa => sub {
Subroutine __ANON__: called CC=3 SCAR=14.2
122 1 ▶ croak "limits must be a coderef"
Branch: 1 branch
BranchTrueFalseTotal
if defined $_[0] and ref($_[0] ne "CODE") 0 1 1
Condition33%1/3
defined $_[0] and ref($_[0] ne "CODE")
!ll&&!rl&&r
010
MC/DC0%0/2
defined $_[0] and ref($_[0] ne "CODE")
defined $_[0] ref($_[0] ne "CODE")
Truth table33%1/3
A and B
A= defined $_[0]B= ref($_[0] ne "CODE")
ABresult
0X0
100
111
123 if defined($_[0]) && (ref($_[0] ne 'CODE'));
124 },
125 2 );
126  
127 # key: service name
128 # value: sorted by $seconds array of pairs [$seconds, $rate]
129 2 has _limits_for => (is => 'rw');
130  
131 =for Pod::Coverage BUILD getter setter
132  
133 =cut
134  
135 1 ▶sub BUILD {
Subroutine BUILD: called CC=9 SCAR=22.3
Pod undocumented
136 1 my $self = shift;
137 1 my %limits_for;
138 1 for my $service (keys %{$self->limits}) {
139 my @service_limits =
140 1 sort { $a->[0] <=> $b->[0] }
141 map {
142 2 my $seconds = $_;
143 2 my $limit = $self->limits->{$service}->{$seconds};
144 2 [$seconds, $limit];
145 1 } keys %{$self->limits->{$service}};
146  
147 # do various validations
148 1 for my $idx (0 .. @service_limits - 1) {
149 2 my $pair = $service_limits[$idx];
150 2 my ($seconds, $limit) = @$pair;
151  
152 # validate: seconds should be natural number
153 2 ▶ croak("'$seconds' seconds is not integer for service $service")
Branch: 1 branch
BranchTrueFalseTotal
if $seconds != int $seconds 0 2 2
154 if $seconds != int($seconds);
155 2 ▶ croak("'$seconds' seconds is not positive for service $service")
Branch: 1 branch
BranchTrueFalseTotal
if $seconds <= 0 0 2 2
156 if $seconds <= 0;
157  
158 # validate: limit should be natural number
159 2 ▶ croak("limit '$limit' is not integer for service $service")
Branch: 1 branch
BranchTrueFalseTotal
if $limit != int $limit 0 2 2
160 if $limit != int($limit);
161 2 ▶ croak("limit '$limit' is not positive for service $service")
Branch: 1 branch
BranchTrueFalseTotal
if $limit <= 0 0 2 2
162 if $limit <= 0;
163  
164 # validate: limit for greater time interval should be greater
165 2 ▶ if ($idx > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($idx > 0) 1 1 2
166 1 my $prev_pair = $service_limits[$idx - 1];
167 1 my $lesser_limit = $prev_pair->[1];
168 1 my $current_limit = $limit;
169 1 ▶ if ($current_limit <= $lesser_limit) {
Branch: 1 branch
BranchTrueFalseTotal
if ($current_limit <= $lesser_limit) 0 1 1
170 0 croak "limit ($current_limit) for "
171 . $seconds
172 . " seconds"
173 . " should be greater then limit ($lesser_limit) for "
174 . $prev_pair->[0]
175 . "seconds";
176 }
177 }
178 }
179 1 $limits_for{$service} = \@service_limits;
180 }
181 1 return $self->_limits_for(\%limits_for);
182 }
183  
184 =head1 METHODS
185  
186 =head2 within_rate_limits
187  
188 within_rate_limits($service, $consumer)
189  
190 Appends service/consumer hits array with additional hit.
191  
192 Returns true if the service limits aren't exhausted.
193  
194 The C<$service> string must be defined in the C<limits> attribute;
195 the C<$consumer> string is arbitrary object defined by application
196 logic. Cannot be C<undef>
197  
198 =cut
199  
200 4029 ▶sub within_rate_limits {
Subroutine within_rate_limits: called CC=10 SCAR=23.2
Pod documented
201 4029 my ($self, $service, $consumer) = @_;
202 4029 ▶ croak "service should be defined" unless defined $service;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $service 0 4029 4029
203 4029 ▶ croak "consumer should be defined" unless defined $consumer;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $consumer 0 4029 4029
204  
205 4029 my $limits = $self->_limits_for->{$service};
206 4029 ▶ croak "unknown service: '$service'" unless defined $limits;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $limits 0 4029 4029
207  
208 4029 ▶ my $hits = $self->getter->($service, $consumer) // [];
Condition100%2/2
$self->getter->($service, $consumer) // []
l!l
40272
MC/DC100%1/1
$self->getter->($service, $consumer) // []
$self->getter->($service, $consumer)
Truth table100%2/2
A
A= $self->getter->($service, $consumer)
Aresult
11
00
209 4029 my $within_limits = 1;
210 4029 my $now = time;
211 # We push first so that we hit limits more often in heavy (DoS) conditions
212 4029 push @$hits, $now;
213 # Remove extra oldest hits, as they do not participate it checks anyway
214 4029 ▶ shift @$hits while (@$hits > $limits->[-1]->[0]);
Branch: 1 branch
BranchTrueFalseTotal
@$hits > $limits->[-1][0] and do { shift @$hits } 420 4029 4449
215  
216 # optionally notify updated service hits
217 4029 my $setter = $self->setter;
218 4029 ▶ $setter->($service, $consumer, $hits) if $setter;
Branch: 1 branch
BranchTrueFalseTotal
if $setter 4029 0 4029
219  
220 4029 for my $rate (@$limits) {
221 # take the service time hit which occur exactly $max_rate times ago
222 # might be undefined.
223 # +1 is added because we already inserted $now hit above, which
224 # should be out of the consideration
225 4041 ▶ my $past_hit_time = $hits->[($rate->[1] + 1) * -1] // 0;
Condition100%2/2
$$hits[($rate->[1] + 1) * -1] // 0
l!l
403110
MC/DC100%1/1
$$hits[($rate->[1] + 1) * -1] // 0
$$hits[($rate->[1] + 1) * -1]
Truth table100%2/2
A
A= $$hits[($rate->[1] + 1) * -1]
Aresult
11
00
226 4041 my $allowed_past_hit_time = $now - $rate->[0];
227 4041 ▶ if ($past_hit_time > $allowed_past_hit_time) {
Branch: 1 branch
BranchTrueFalseTotal
if ($past_hit_time > $allowed_past_hit_time) 4019 22 4041
228 4019 $within_limits = 0;
229 4019 last;
230 }
231 }
232  
233 4029 return $within_limits;
234 }
235  
236 =head1 SOURCE CODE
237  
238 L<GitHub|https://github.com/binary-com/perl-RateLimitations-Pluggable>
239  
240  
241 =head1 AUTHOR
242  
243 binary.com, C<< <perl at binary.com> >>
244  
245 =head1 BUGS
246  
247 Please report any bugs or feature requests to
248 L<https://github.com/binary-com/perl-RateLimitations-Pluggable/issues>.
249  
250  
251 =cut
252  
253 2 1;
↑ Summary