blib/lib/Bot/Cobalt/IRC/FloodChk.pm

filter: Statementstmt 77.7% 7 / 9 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 3 / 3 Podpod n/a totaltotal 83.3% 10 / 12 SCAR 0.1
CC
1
Cov
78%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.0
« blib/lib/Bot/Cobalt/IRC/Event/Mode.pm ↑ Summary blib/lib/Bot/Cobalt/Logger.pm »
1 package Bot::Cobalt::IRC::FloodChk;
2 $Bot::Cobalt::IRC::FloodChk::VERSION = '0.021002';
3 1 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 1 ▶use strictures 2;
Subroutine BEGIN: called CC=1 SCAR=0.0
5  
6 1 ▶use Bot::Cobalt::Common ':types';
Subroutine BEGIN: called CC=1 SCAR=2.6
7  
8 use List::Objects::WithUtils;
9 use Time::HiRes ();
10  
11 use Moo;
12  
13 ## _fqueue->{$context}->{$key} = array()
14 ## FIXME Should probably be an obj ...
15 has _fqueue => (
16 is => 'rw',
17 lazy => 1,
18 default => sub { +{} },
19 );
20  
21 has count => ( is => 'rw', isa => Num, required => 1 );
22 has in => ( is => 'rw', isa => Num, required => 1 );
23  
24 sub check {
25 my ($self, $context, $key) = @_;
26 return unless defined $context and defined $key;
27
28 my $thisq = $self->_fqueue->{$context}->{$key} //= array;
29
30 if ((my $pending = $thisq->count) >= $self->count) {
31  
32 my $oldest_ts = $thisq->head;
33 my $ev_c = $self->count;
34 my $ev_sec = $self->in;
35  
36 my $delayed =
37 ($oldest_ts + ($pending * $ev_sec / $ev_c) )
38 - Time::HiRes::time();
39
40 ## Too many events in this time window:
41 return $delayed if $delayed > 0;
42  
43 ## ...otherwise shift and continue:
44 $thisq->shift;
45 }
46  
47 ## Safe to push this ev, no delay:
48 $thisq->push( Time::HiRes::time() );
49 return 0
50 }
51  
52 sub clear {
53 my ($self, $context, $key) = @_;
54 confess "clear() needs a context specified"
55 unless defined $context;
56
57 return unless exists $self->_fqueue->{$context};
58
59 return delete $self->_fqueue->{$context}->{$key}
60 if defined $key;
61
62 delete $self->_fqueue->{$context}
63 }
64  
65 sub expire {
66 ## Clear keys when recent_event_time - time > $self->in
67 my ($self) = @_;
68  
69 CONTEXT: for my $context (keys %{ $self->_fqueue } ) {
70  
71 KEY: for my $key (keys %{ $self->_fqueue->{$context} } ) {
72  
73 my $events = $self->_fqueue->{$context}->{$key};
74 my $latest_time = $events->get(-1) // next KEY;
75
76 if (Time::HiRes::time() - $latest_time > $self->in) {
77 ## It's been more than ->in seconds since latest event was
78 ## noted. We can clear() this entry.
79 $self->clear($context, $key);
80 }
81 } # KEY
82
83 unless (keys %{ $self->_fqueue->{$context} }) {
84 ## Nothing left for this context.
85 $self->clear($context);
86 }
87 }
88 }
89  
90 1;
91 __END__
« blib/lib/Bot/Cobalt/IRC/Event/Mode.pm ↑ Summary blib/lib/Bot/Cobalt/Logger.pm »