File Coverage

blib/lib/Mojo/UserAgent/Role/Queued/Queue.pm
Criterion Covered Total %
statement 30 30 100.0
branch 2 2 100.0
condition 4 6 66.6
subroutine 7 7 100.0
pod 0 3 0.0
total 43 48 89.5


line stmt bran cond sub pod time code
1             package Mojo::UserAgent::Role::Queued::Queue;
2              
3 3     3   20 use strict;
  3         8  
  3         88  
4 3     3   15 use warnings;
  3         6  
  3         77  
5              
6 3     3   17 use Mojo::Base 'Mojo::EventEmitter';
  3         7  
  3         15  
7              
8             has jobs => sub { [] };
9             has active => 0;
10             has max_active => 4;
11             has callback => undef;
12              
13              
14             sub process {
15 18     18 0 50 my ($self) = @_;
16             # we have jobs and can run them:
17 18   66     55 while ($self->active < $self->max_active
18 27         8409 and my $job = shift @{$self->jobs})
19             {
20 9         65 $self->active($self->active + 1);
21 9         73 my $tx = shift @$job;
22 9         16 my $cb = shift @$job;
23 9         37 weaken $self;
24 9     9   60 $tx->on(finish => sub { $self->tx_finish(); });
  9         6484229  
25 9         67 $self->callback->( $tx, $cb );
26             }
27 18 100 66     148 if (scalar @{$self->jobs} == 0 && $self->active == 0) {
  18         46  
28 5         78 $self->emit('queue_empty');
29             }
30             }
31              
32             sub tx_finish {
33 9     9 0 28 my ($self) = @_;
34 9         48 $self->active($self->active - 1);
35 9         112 $self->process();
36             }
37              
38             sub enqueue {
39 9     9 0 57 my ($self, $tx, $cb) = @_;
40 9         22 my $job = [$tx, $cb];
41 9         19 push @{$self->jobs}, $job;
  9         26  
42 9         43 $self->process();
43             }
44              
45             1;