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   19 use strict;
  3         5  
  3         77  
4 3     3   13 use warnings;
  3         5  
  3         2938  
5              
6 3     3   17 use Mojo::Base 'Mojo::EventEmitter';
  3         5  
  3         103  
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 41 my ($self) = @_;
16             # we have jobs and can run them:
17 18   66     44 while ($self->active < $self->max_active
18 27         7568 and my $job = shift @{$self->jobs})
19             {
20 9         54 $self->active($self->active + 1);
21 9         64 my $tx = shift @$job;
22 9         16 my $cb = shift @$job;
23 9         34 weaken $self;
24 9     9   44 $tx->on(finish => sub { $self->tx_finish(); });
  9         6477709  
25 9         55 $self->callback->( $tx, $cb );
26             }
27 18 100 66     132 if (scalar @{$self->jobs} == 0 && $self->active == 0) {
  18         37  
28 5         69 $self->emit('queue_empty');
29             }
30             }
31              
32             sub tx_finish {
33 9     9 0 25 my ($self) = @_;
34 9         45 $self->active($self->active - 1);
35 9         101 $self->process();
36             }
37              
38             sub enqueue {
39 9     9 0 57 my ($self, $tx, $cb) = @_;
40 9         20 my $job = [$tx, $cb];
41 9         12 push @{$self->jobs}, $job;
  9         23  
42 9         37 $self->process();
43             }
44              
45             1;