blib/lib/Punk/Plugin/Queue.pm

filter: Statementstmt 88.2% 407 / 461 Branchbran 66.6% 136 / 204 Conditioncond 53.8% 70 / 130 MC/DCmcdc 26.0% 19 / 73 Subroutinesub 88.4% 61 / 69 Podpod 100% 3 / 3 totaltotal 74.0% 696 / 940 CC 173 SCAR 23.3
CC
173
Cov
77%
_live_push
25.1
__ANON__
24.9
__ANON__
21.5
CRAP 10.3
« blib/lib/Punk/Queue/Command.pm ↑ Summary blib/lib/Punk/Queue/Backend/Pg.pm »
1 package Punk::Plugin::Queue;
2  
3 10 ▶use 5.010;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 10 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 10 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 10 ▶use Carp ();
Subroutine BEGIN: called CC=1 SCAR=0.0
7 10 ▶use File::Basename ();
Subroutine BEGIN: called CC=1 SCAR=0.0
8 10 ▶use File::Spec ();
Subroutine BEGIN: called CC=1 SCAR=0.0
9 10 ▶use File::Raw::JSON ();
Subroutine BEGIN: called CC=1 SCAR=0.0
10 10 ▶use Punk::Queue ();
Subroutine BEGIN: called CC=1 SCAR=0.0
11  
12 10 our $VERSION = '0.11';
13  
14 10 my %STATE;
15  
16 67 ▶sub _state {
Subroutine _state: called CC=2 SCAR=6.9
17 67 my ($pkg) = @_;
18 67 ▶ return $STATE{$pkg} //= {
Condition100%2/2
$STATE{$pkg} //= {"queues", {}, "tasks", [], "crons", [], "registered", 0, "compiled", 0, "keywords_used", 0}
l!l
3829
MC/DC100%1/1
$STATE{$pkg} //= {"queues", {}, "tasks", [], "crons", [], "registered", 0, "compiled", 0, "keywords_used", 0}
$STATE{$pkg}
Truth table100%2/2
A
A= $STATE{$pkg}
Aresult
11
00
19 queues => {}, tasks => [], crons => [],
20 registered => 0, compiled => 0, keywords_used => 0,
21 };
22 }
23  
24 6 ▶sub state_for { $STATE{ $_[1] // $_[0] } } # test/introspection seam
Subroutine state_for: called CC=2 SCAR=9.2
Pod documented
Condition33%1/3
$_[1] // $_[0]
l!l&&r!l&&!r
600
MC/DC0%0/2
$_[1] // $_[0]
$_[1] $_[0]
Truth table33%1/3
A // B
A= $_[1]B= $_[0]
ABresult
1X1
011
000
25  
26 # ---- import: the keywords ---------------------------------------------------
27  
28 11 ▶sub import {
Subroutine import: called CC=3 SCAR=11.8
29 11 my ($class) = @_;
30 11 my $caller = caller;
31 11 ▶ return if $caller->can('cron') && $caller->can('task');
Branch: 1 branch
BranchTrueFalseTotal
if $caller->can("cron") and $caller->can("task") 0 11 11
Condition33%1/3
$caller->can("cron") and $caller->can("task")
!ll&&!rl&&r
1100
MC/DC0%0/2
$caller->can("cron") and $caller->can("task")
$caller->can("cron") $caller->can("task")
Truth table33%1/3
A and B
A= $caller->can("cron")B= $caller->can("task")
ABresult
0X0
100
111
32 11 _install_keywords($caller);
33 11 return;
34 }
35  
36 39 ▶sub _install_keywords {
Subroutine _install_keywords: called CC=5 SCAR=16.5
37 39 my ($pkg, $app) = @_;
38 39 my $st = _state($pkg);
39  
40 39 ▶ $app ||= $pkg->can('punk_app') ? $pkg->punk_app
Branch: 1 branch
BranchTrueFalseTotal
$pkg->can('punk_app') ? : 11 0 11
Condition66%2/3
$app ||= $pkg->can("punk_app") ? $pkg->punk_app : Carp::croak("Punk::Plugin::Queue: $pkg is not a Punk application " . '- `use Punk` before `use Punk::Plugin::Queue`')
l!l&&r!l&&!r
28110
MC/DC0%0/2
$app ||= $pkg->can("punk_app") ? $pkg->punk_app : Carp::croak("Punk::Plugin::Queue: $pkg is not a Punk application " . '- `use Punk` before `use Punk::Plugin::Queue`')
$app $pkg->can("punk_app") ? $pkg->punk_app : Carp::croak("Punk::Plugin::Queue: $pkg is not a Punk application " . '- `use Punk` before `use Punk::Plugin::Queue`')
Truth table66%2/3
A ||= B
A= $appB= $pkg->can("punk_app") ? $pkg->punk_app : Carp::croak("Punk::Plugin::Queue: $pkg is not a Punk application " . '- `use Punk` before `use Punk::Plugin::Queue`')
ABresult
1X1
011
000
41 : Carp::croak("Punk::Plugin::Queue: $pkg is not a Punk application "
42 . "- `use Punk` before `use Punk::Plugin::Queue`");
43  
44 # a to_app-time tripwire: if keywords recorded declarations but the
45 # plugin never registered, compiling the app is the moment to say so
46 39 ▶ if (!$st->{tripwire}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($st->{"tripwire"}) 29 10 39
47 29 $st->{tripwire} = 1;
48 21 ▶ _at_compile($app, sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
49 21 ▶ if ($st->{keywords_used} && !$st->{registered}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($st->{"keywords_used"} and not $st->{"registered"}) 1 20 21
Condition100%3/3
$st->{"keywords_used"} and not $st->{"registered"}
!ll&&!rl&&r
9111
MC/DC100%2/2
$st->{"keywords_used"} and not $st->{"registered"}
$st->{"keywords_used"} not $st->{"registered"}
Truth table100%3/3
A and not(B)
A= $st->{"keywords_used"}B= not $st->{"registered"}
ABresult
0X0
100
111
50 1 require Carp;
51 1 Carp::croak("cron used but plugin 'Queue' was never "
52 . "registered (add plugin 'Queue' => {...})");
53 }
54 29 });
55 }
56  
57 # `use` then `plugin` reaches here twice. Punk would ignore the second
58 # install anyway - same name, same owner - but there is no reason to
59 # build three closures for it to drop.
60 39 ▶ return if $st->{keywords_installed};
Branch: 1 branch
BranchTrueFalseTotal
if $st->{"keywords_installed"} 10 29 39
61 29 $st->{keywords_installed} = 1;
62  
63 # queue NAME => \%defaults records; queue() with no args returns the
64 # queue object - the class-level accessor controllers use at boot
65 6 ▶ $app->install_kw(queue => sub {
Subroutine __ANON__: called CC=6 SCAR=19.1
66 6 my ($name, $defaults) = @_;
67 6 ▶ if (!defined $name) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $name) 5 1 6
68 my $q = $st->{queue}
69 5 ▶ or Carp::croak("Punk::Plugin::Queue: plugin 'Queue' has "
Branch: 1 branch
BranchTrueFalseTotal
my $q = $st->{"queue"} or Carp::croak("Punk::Plugin::Queue: plugin 'Queue' has not been registered yet") 5 0 5
70 . "not been registered yet");
71 5 return $q;
72 }
73 1 $st->{keywords_used}++;
74 1 ▶ $st->{queues}{$name} = $defaults // {};
Condition50%1/2
$defaults // {}
l!l
10
MC/DC0%0/1
$defaults // {}
$defaults
Truth table50%1/2
A
A= $defaults
Aresult
11
00
75 $st->{queue}->queue_defaults($name, $defaults // {})
76 1 ▶ if $st->{queue};
Branch: 1 branch
BranchTrueFalseTotal
if $st->{"queue"} 0 1 1
Condition0%0/2
$defaults // {}
l!l
00
MC/DC0%0/1
$defaults // {}
$defaults
Truth table0%0/2
A
A= $defaults
Aresult
11
00
77 1 return;
78 29 }, __PACKAGE__);
79  
80 12 ▶ $app->install_kw(task => sub {
Subroutine __ANON__: called CC=2 SCAR=7.0
81 12 my ($name, $target, $defaults) = @_;
82 12 $st->{keywords_used}++;
83 12 ▶ push @{ $st->{tasks} }, {
Branch: 1 branch
BranchTrueFalseTotal
$defaults ? : 0 12 12
84 name => $name, target => $target,
85 ($defaults ? (defaults => $defaults) : ()),
86 };
87 12 return;
88 29 }, __PACKAGE__);
89  
90 8 ▶ $app->install_kw(cron => sub {
Subroutine __ANON__: called CC=10 SCAR=25.2
91 8 my ($expr, $target, $opts) = @_;
92 8 $st->{keywords_used}++;
93 8 ▶ $opts //= {};
Condition100%2/2
$opts //= {}
l!l
17
MC/DC100%1/1
$opts //= {}
$opts
Truth table100%2/2
A
A= $opts
Aresult
11
00
94 # the default name is the target string SANITISED to the queue
95 # name rule ('Reports#nightly' -> 'Reports-nightly'): the same
96 # name lands in pq_crons at reconcile, where the name rule has
97 # no sense of humour about '#'
98 8 my $name = $opts->{name};
99 8 ▶ if (!defined $name) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $name) 8 0 8
100 0 ▶ if (ref $target) { $name = 'cron-' . scalar @{ $st->{crons} } }
Branch: 1 branch
BranchTrueFalseTotal
if (ref $target) { } 0 8 8
101 else {
102 8 ($name = $target) =~ s/[^A-Za-z0-9_.:-]/-/g;
103 8 $name = substr $name, 0, 64;
104 }
105 }
106 8 ▶ push @{ $st->{crons} }, {
Condition58%7/12
$opts->{"args"} // []
l!l
08
$opts->{"queue"} // "default"
l!l
17
$opts->{"priority"} // 0
l!l
08
$opts->{"attempts"} // 1
l!l
08
$opts->{"tz"} // "UTC"
l!l
08
$opts->{"catchup"} // "once"
l!l
08
MC/DC0%0/1
$opts->{"args"} // []
$opts->{"args"}
MC/DC100%1/1
$opts->{"queue"} // "default"
$opts->{"queue"}
MC/DC0%0/1
$opts->{"priority"} // 0
$opts->{"priority"}
MC/DC0%0/1
$opts->{"attempts"} // 1
$opts->{"attempts"}
MC/DC0%0/1
$opts->{"tz"} // "UTC"
$opts->{"tz"}
MC/DC0%0/1
$opts->{"catchup"} // "once"
$opts->{"catchup"}
Truth table50%1/2
A
A= $opts->{"args"}
Aresult
11
00
Truth table100%2/2
A
A= $opts->{"queue"}
Aresult
11
00
Truth table50%1/2
A
A= $opts->{"priority"}
Aresult
11
00
Truth table50%1/2
A
A= $opts->{"attempts"}
Aresult
11
00
Truth table50%1/2
A
A= $opts->{"tz"}
Aresult
11
00
Truth table50%1/2
A
A= $opts->{"catchup"}
Aresult
11
00
107 expr => $expr,
108 target => $target,
109 name => $name,
110 task => $opts->{task},
111 args => $opts->{args} // [],
112 queue => $opts->{queue} // 'default',
113 priority=> $opts->{priority} // 0,
114 attempts=> $opts->{attempts} // 1,
115 tz => $opts->{tz} // 'UTC',
116 8 catchup => $opts->{catchup} // 'once',
117 };
118 8 return;
119 29 }, __PACKAGE__);
120 29 return;
121 }
122  
123 # ---- register: the plugin ---------------------------------------------------
124  
125 28 ▶sub new { bless {}, $_[0] }
Subroutine new: called CC=1 SCAR=0.0
Pod documented
126  
127 28 ▶sub register {
Subroutine register: called CC=15 SCAR=27.7
Pod documented
128 28 my ($self, $app, $opts) = @_;
129 28 ▶ $opts //= {};
Condition50%1/2
$opts //= {}
l!l
280
MC/DC0%0/1
$opts //= {}
$opts
Truth table50%1/2
A
A= $opts
Aresult
11
00
130 28 ▶ my $pkg = $app->caller_class
Branch: 1 branch
BranchTrueFalseTotal
my $pkg = $app->caller_class or Carp::croak("Punk::Plugin::Queue: the app has no caller class") 28 0 28
131 or Carp::croak('Punk::Plugin::Queue: the app has no caller class');
132 28 my $st = _state($pkg);
133  
134 # the terser form: plugin first, keywords after - install them now
135 28 _install_keywords($pkg, $app);
136 28 $st->{app} = $app;
137 28 $st->{opts} = $opts;
138  
139 # backend: explicit dsn, else the app's database keyword/config
140 28 my %qopts;
141 28 ▶ if ($opts->{dsn}) {
Branch: 2 branches
BranchTrueFalseTotal
if ($opts->{'dsn'}) { } 26 2 28
elsif (my $db = +($app->{'databases'} || {})->{'default'}) { } 1 1 2
142 $qopts{$_} = $opts->{$_}
143 26 for grep { defined $opts->{$_} }
144 qw(dsn user password attr attempts_delay max_backoff
145 missing_after remove_after auto_migrate);
146 }
147 ▶ elsif (my $db = ($app->{databases} || {})->{default}) {
Condition50%1/2
$app->{'databases'} || {}
l!l
20
MC/DC0%0/1
$app->{'databases'} || {}
$app->{'databases'}
Truth table50%1/2
A
A= $app->{'databases'}
Aresult
11
00
148 $qopts{dsn} = $db->{dsn}
149 1 ▶ or Carp::croak("Punk::Plugin::Queue: the app's database has "
Branch: 1 branch
BranchTrueFalseTotal
$qopts{"dsn"} = $db->{"dsn"} or Carp::croak("Punk::Plugin::Queue: the app's database has no dsn") 1 0 1
150 . "no dsn");
151 1 ▶ $qopts{user} = $db->{user} if defined $db->{user};
Branch: 1 branch
BranchTrueFalseTotal
if defined $db->{"user"} 0 1 1
152 1 ▶ $qopts{password} = $db->{password} if defined $db->{password};
Branch: 1 branch
BranchTrueFalseTotal
if defined $db->{"password"} 0 1 1
153 }
154 else {
155 1 Carp::croak("Punk::Plugin::Queue: no dsn - pass dsn => ... to the "
156 . "plugin, or add a database keyword to the app");
157 }
158 27 my $q = Punk::Queue->new(%qopts);
159 $q->migrate unless exists $opts->{auto_migrate}
160 27 ▶ && !$opts->{auto_migrate};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $opts->{"auto_migrate"} and not $opts->{"auto_migrate"} 27 0 27
Condition33%1/3
exists $opts->{"auto_migrate"} and not $opts->{"auto_migrate"}
!ll&&!rl&&r
2700
MC/DC0%0/2
exists $opts->{"auto_migrate"} and not $opts->{"auto_migrate"}
exists $opts->{"auto_migrate"} not $opts->{"auto_migrate"}
Truth table33%1/3
A and not(B)
A= exists $opts->{"auto_migrate"}B= not $opts->{"auto_migrate"}
ABresult
0X0
100
111
161 27 $st->{queue} = $q;
162  
163 # queue defaults recorded before we existed
164 27 $q->queue_defaults($_, $st->{queues}{$_}) for keys %{ $st->{queues} };
165  
166 # helpers: real methods on the per-app context subclass at to_app;
167 # collisions croak here, naming both owners - Punk's behaviour, wanted
168 27 ▶ $app->helper(queue => sub { $q }, __PACKAGE__);
Subroutine __ANON__: called CC=1 SCAR=0.0
169 1 ▶ $app->helper(enqueue => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
170 1 my ($c, $task, $args, @rest) = @_;
171 1 my $id = $q->enqueue($task, $args, @rest);
172 1 _live_push($st, job => create => $id);
173 1 return $id;
174 26 }, __PACKAGE__);
175 26 ▶ $app->helper(job => sub { $q->job_info($_[1]) }, __PACKAGE__);
Subroutine __ANON__: called CC=1 SCAR=0.0
176  
177 # the compile point: to_app, after every keyword has recorded - resolve
178 # targets there so a typo croaks at boot, matching Punk's compile-at-boot
179 # promise
180 26 ▶ _at_compile($app, sub { _compile($st) unless $st->{compiled} });
Subroutine __ANON__: called CC=2 SCAR=7.2
Branch: 1 branch
BranchTrueFalseTotal
unless $st->{"compiled"} 20 0 20
181  
182 26 $st->{registered} = 1;
183  
184 26 ▶ _register_admin($st) if $opts->{admin};
Branch: 1 branch
BranchTrueFalseTotal
if $opts->{"admin"} 13 13 26
185 23 ▶ _register_inserver($st) if $opts->{in_server};
Branch: 1 branch
BranchTrueFalseTotal
if $opts->{"in_server"} 2 21 23
186 22 return;
187 }
188  
189 # Run $code once at to_app. Punk 0.31 has $app->on_compile for exactly this;
190 # before it the one moment a plugin could reach was the construction of a
191 # middleware, which happens once at compile - a middleware that wraps
192 # nothing, kept only for the older Punk.
193 55 ▶sub _at_compile {
Subroutine _at_compile: called CC=2 SCAR=9.2
194 55 my ($app, $code) = @_;
195 55 ▶ if ($app->can('on_compile')) {
Branch: 1 branch
BranchTrueFalseTotal
if ($app->can("on_compile")) 55 0 55
196 55 ▶ $app->on_compile(sub { $code->() }, __PACKAGE__);
Subroutine __ANON__: called CC=1 SCAR=0.0
197 55 return;
198 }
199 0 ▶ $app->middleware(sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
200 0 my ($inner) = @_;
201 0 $code->();
202 0 return $inner;
203 0 });
204 0 return;
205 }
206  
207 # 'Job::Mail#send' -> the coderef, resolved relative to the app class's
208 # controller namespace exactly as Punk's router resolves route targets;
209 # '+Full::Class#method' escapes the namespace.
210 13 ▶sub _resolve_target {
Subroutine _resolve_target: called CC=9 SCAR=23.4
211 13 my ($st, $target, $what) = @_;
212 13 ▶ return $target if ref $target eq 'CODE';
Branch: 1 branch
BranchTrueFalseTotal
if ref $target eq "CODE" 11 2 13
213 2 ▶ my ($cls, $method) = ($target // '') =~ /\A(.+)#(\w+)\z/
Branch: 1 branch
BranchTrueFalseTotal
() = ($target // "") =~ /\A(.+)#(\w+)\z/ or Carp::croak("Punk::Plugin::Queue: $what target '" . ($target // "undef") . q[' is neither a coderef nor 'Class#method']) 2 0 2
Condition25%1/4
$target // ""
l!l
20
$target // "undef"
l!l
00
MC/DC0%0/1
$target // ""
$target
MC/DC0%0/1
$target // "undef"
$target
Truth table50%1/2
A
A= $target
Aresult
11
00
Truth table0%0/2
A
A= $target
Aresult
11
00
214 or Carp::croak("Punk::Plugin::Queue: $what target '"
215 . ($target // 'undef')
216 . "' is neither a coderef nor 'Class#method'");
217 2 ▶ unless ($cls =~ s/\A\+//) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($cls =~ s/\A\+//) 2 0 2
218 2 $cls = $st->{app}->caller_class . '::Controller::' . $cls;
219 }
220 2 (my $file = "$cls.pm") =~ s{::}{/}g;
221 2 ▶ eval { require $file } or do {
Branch: 1 branch
BranchTrueFalseTotal
eval { do { require $file } } or do { Carp::croak("Punk::Plugin::Queue: cannot load $cls for $what '" . "${target}': $@") unless $cls->can($method) } 0 2 2
222 2 ▶ Carp::croak("Punk::Plugin::Queue: cannot load $cls for $what '"
Branch: 1 branch
BranchTrueFalseTotal
unless $cls->can($method) 1 1 2
223 . "$target': $@") unless $cls->can($method);
224 };
225 1 ▶ my $code = $cls->can($method)
Branch: 1 branch
BranchTrueFalseTotal
my $code = $cls->can($method) or Carp::croak("Punk::Plugin::Queue: $cls has no method '${method}' " . "(from $what '${target}')") 1 0 1
226 or Carp::croak("Punk::Plugin::Queue: $cls has no method '$method' "
227 . "(from $what '$target')");
228 1 return $code;
229 }
230  
231 20 ▶sub _compile {
Subroutine _compile: called CC=9 SCAR=22.3
232 20 my ($st) = @_;
233 20 my $q = $st->{queue};
234 20 for my $t (@{ $st->{tasks} }) {
235 12 $q->task($t->{name}, _resolve_target($st, $t->{target}, 'task'));
236 11 ▶ $q->task_defaults($t->{name}, $t->{defaults}) if $t->{defaults};
Branch: 1 branch
BranchTrueFalseTotal
if $t->{"defaults"} 0 11 11
237 }
238 19 for my $c (@{ $st->{crons} }) {
239 # a cron whose target is a bare task name refers to a registered
240 # task; anything else resolves like a route target and registers
241 # under a derived name
242 7 ▶ if (!ref $c->{target} && $c->{target} !~ /#/) {
Branch: 1 branch
BranchTrueFalseTotal
if (not ref $c->{'target'} || $c->{'target'} =~ /#/) { } 6 1 7
Condition66%2/3
ref $c->{'target'} || $c->{'target'} =~ /#/
l!l&&r!l&&!r
016
MC/DC50%1/2
ref $c->{'target'} || $c->{'target'} =~ /#/
ref $c->{'target'} $c->{'target'} =~ /#/
Truth table66%2/3
A || B
A= ref $c->{'target'}B= $c->{'target'} =~ /#/
ABresult
1X1
011
000
243 6 $c->{task} = $c->{target};
244 Carp::croak("Punk::Plugin::Queue: cron '$c->{name}' names "
245 . "task '$c->{task}', which is not registered")
246 6 ▶ unless $q->task($c->{task});
Branch: 1 branch
BranchTrueFalseTotal
unless $q->task($c->{"task"}) 0 6 6
247 }
248 else {
249 1 ▶ $c->{task} //= substr "cron.$c->{name}", 0, 64;
Condition33%1/3
$c->{"task"} //= substr(qq[cron.$c->{"name"}], 0, 64)
l!l&&r!l&&!r
010
MC/DC0%0/2
$c->{"task"} //= substr(qq[cron.$c->{"name"}], 0, 64)
$c->{"task"} substr(qq[cron.$c->{"name"}], 0, 64)
Truth table33%1/3
A //= B
A= $c->{"task"}B= substr(qq[cron.$c->{"name"}], 0, 64)
ABresult
1X1
011
000
250 $q->task($c->{task},
251 1 _resolve_target($st, $c->{target}, 'cron'));
252 }
253 }
254  
255 # reconcile the declarations into the cron store: upsert each (which
256 # validates the expression - a bad cron croaks the boot), then retire
257 # whatever this app no longer declares. upsert never touches an
258 # operator's enabled flag, so a paused cron stays paused across
259 # deploys; disable-not-delete keeps identity and history.
260 19 for my $c (@{ $st->{crons} }) {
261 $q->upsert_cron({
262 name => $c->{name}, expr => $c->{expr},
263 task => $c->{task}, args => $c->{args},
264 queue => $c->{queue}, priority => $c->{priority},
265 attempts => $c->{attempts},
266 tz => $c->{tz}, catchup => $c->{catchup},
267 7 });
268 }
269 18 $q->disable_missing_crons([ map { $_->{name} } @{ $st->{crons} } ]);
270  
271 18 $st->{compiled} = 1;
272 18 return;
273 }
274  
275 # ---- admin ------------------------------------------------------------------
276  
277 # Ordered, because it is also the nav: a template override that wants a
278 # different nav gets the same list as `nav` and can ignore it.
279 10 my @PAGES = (
280 { path => '', tmpl => 'overview', id => 'pq-overview', title => 'Overview' },
281 { path => 'jobs', tmpl => 'jobs', id => 'pq-jobs', title => 'Jobs' },
282 { path => 'workers', tmpl => 'workers', id => 'pq-workers', title => 'Workers' },
283 { path => 'locks', tmpl => 'locks', id => 'pq-locks', title => 'Locks' },
284 { path => 'crons', tmpl => 'crons', id => 'pq-crons', title => 'Crons' },
285 );
286  
287 # every template the admin UI renders: the pages, the job detail page and
288 # the layout they go into
289 10 my @TEMPLATES = ((map { $_->{tmpl} } @PAGES), 'job', 'layout');
290  
291 22 ▶sub _asset_dir {
Subroutine _asset_dir: called CC=2 SCAR=7.2
292 22 ▶ my $pm = $INC{'Punk/Plugin/Queue.pm'}
Branch: 1 branch
BranchTrueFalseTotal
my $pm = $INC{"Punk/Plugin/Queue.pm"} or Carp::croak("Punk::Plugin::Queue: cannot self-locate") 22 0 22
293 or Carp::croak('Punk::Plugin::Queue: cannot self-locate');
294 22 return File::Spec->catdir(File::Basename::dirname($pm),
295 'Queue', 'assets');
296 }
297  
298 651 ▶sub _slurp {
Subroutine _slurp: called CC=2 SCAR=7.0
299 651 my ($path) = @_;
300 651 ▶ open my $fh, '<:raw', $path
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, "<:raw", $path or Carp::croak("Punk::Plugin::Queue: cannot read ${path}: $!") 651 0 651
301 or Carp::croak("Punk::Plugin::Queue: cannot read $path: $!");
302 651 local $/;
303 651 return scalar <$fh>;
304 }
305  
306 # A list option that may be given as one value or several.
307 23 ▶sub _list { my ($v) = @_; return !defined $v ? () : ref $v eq 'ARRAY' ? @$v : ($v) }
Subroutine _list: called CC=3 SCAR=11.0
Branch: 2 branches
BranchTrueFalseTotal
!defined($v) ? : 20 3 23
ref $v eq 'ARRAY' ? : 1 2 3
308  
309 # The bundles: slurped ONCE at register, concatenated in lexical order -
310 # which IS the dependency order, the numeric prefixes exist for exactly
311 # this - and served from memory. No per-request file IO; after boot there
312 # is nothing on disk to misconfigure.
313 #
314 # An app's own sheets and scripts land at the END of the bundle they join,
315 # which is what makes them overrides: last declaration wins in CSS, and a
316 # script that runs after app.js sees everything it set up.
317 12 ▶sub _build_assets {
Subroutine _build_assets: called CC=8 SCAR=20.8
318 12 my ($st, $a) = @_;
319 12 my $dir = _asset_dir();
320 12 my (%bundle, @order);
321  
322 12 for my $kind (['js', 'funky.js'], ['css', 'funky.css']) {
323 24 my ($sub, $name) = @$kind;
324 24 my $d = File::Spec->catdir($dir, 'funky', $sub);
325 24 ▶ opendir my $dh, $d
Branch: 1 branch
BranchTrueFalseTotal
opendir my $dh, $d or Carp::croak("Punk::Plugin::Queue: cannot read ${d}: $!") 24 0 24
326 or Carp::croak("Punk::Plugin::Queue: cannot read $d: $!");
327 24 my @files = sort grep { /\.(?:js|css)\z/ } readdir $dh;
328 24 closedir $dh;
329 24 ▶ Carp::croak("Punk::Plugin::Queue: the vendored funky/$sub "
Branch: 1 branch
BranchTrueFalseTotal
unless @files 0 24 24
330 . "directory is empty") unless @files;
331 $bundle{$name} = join "\n",
332 24 map { _slurp(File::Spec->catfile($d, $_)) } @files;
333 24 push @order, [$name, \@files];
334 }
335 # FontAwesome's solid face, then our override layer. Order matters
336 # twice over: the icon rules must beat the vendored css that assumes
337 # an icon font, and punk-queue.css must still be able to beat both.
338 12 $bundle{'funky.css'} .= "\n"
339 . _slurp(File::Spec->catfile($dir, 'fontawesome', 'fontawesome.css'));
340 12 $bundle{'funky.css'} .= "\n"
341 . _slurp(File::Spec->catfile($dir, 'punk-queue.css'));
342 12 $bundle{'app.js'} = _slurp(File::Spec->catfile($dir, 'app.js'));
343  
344 # The webfont itself: bytes, not text, and served under its own name
345 # because the @font-face url() is relative to the stylesheet. _slurp
346 # reads :raw, so length() below is a byte count and the ETag hashes
347 # the real octets.
348 12 $bundle{'fa-solid-900.woff2'} =
349 _slurp(File::Spec->catfile($dir, 'fontawesome', 'fa-solid-900.woff2'));
350  
351 12 for my $ext ([css => 'funky.css'], [js => 'app.js']) {
352 23 my ($opt, $name) = @$ext;
353 23 for my $f (_list($a->{$opt})) {
354 4 ▶ Carp::croak("Punk::Plugin::Queue: admin $opt override '$f' "
Branch: 1 branch
BranchTrueFalseTotal
unless -f $f and -r _ 1 3 4
Condition66%2/3
-f $f and -r _
!ll&&!rl&&r
103
MC/DC50%1/2
-f $f and -r _
-f $f -r _
Truth table66%2/3
A and B
A= -f $fB= -r _
ABresult
0X0
100
111
355 . "is not a readable file") unless -f $f && -r _;
356 3 $bundle{$name} .= "\n/* $opt: $f */\n" . _slurp($f);
357 3 push @{ $st->{overrides}{$opt} }, $f;
358 }
359 }
360  
361 11 $st->{assets} = \%bundle;
362 11 $st->{asset_order} = \@order;
363 # the ETag is over the bytes, not the version: two deploys of the same
364 # release with different override files must not share a cache entry
365 $st->{etags} = { map {
366 11 $_ => sprintf '"pq-%s-%x-%x"', $VERSION, length $bundle{$_},
367 44 unpack '%32C*', $bundle{$_}
368 } keys %bundle };
369 11 return;
370 }
371  
372 # The templates. Two roots at most - the app's, then ours - and a name
373 # resolves to the first root that has it, so an override directory holds
374 # only the templates it actually changes. Which root serves which name is
375 # decided HERE, at boot: a typo in an override directory is a boot croak,
376 # and the request path never stats anything.
377 11 ▶sub _build_templates {
Subroutine _build_templates: called CC=6 SCAR=17.9
378 11 my ($st, $a) = @_;
379 11 ▶ eval { require Template::Stencil; 1 }
Branch: 1 branch
BranchTrueFalseTotal
eval { do { require Template::Stencil; 1 } } or Carp::croak('Punk::Plugin::Queue: the admin UI renders through ' . "Template::Stencil, which is not installed: $@") 11 0 11
380 or Carp::croak("Punk::Plugin::Queue: the admin UI renders through "
381 . "Template::Stencil, which is not installed: $@");
382  
383 11 my @dirs;
384 11 ▶ if (defined(my $d = $a->{templates})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $d = $a->{"templates"})) 3 8 11
385 3 ▶ Carp::croak("Punk::Plugin::Queue: admin templates => '$d' is not "
Branch: 1 branch
BranchTrueFalseTotal
unless -d $d 1 2 3
386 . "a directory") unless -d $d;
387 2 push @dirs, $d;
388 }
389 10 push @dirs, File::Spec->catdir(_asset_dir(), 'templates');
390  
391 # stat_ttl => -1: never re-stat. The rendered pages are cached anyway
392 # (below), so a template edit needs a restart either way - and this is
393 # a Punk app, where everything is compiled at boot.
394 my @engines = map {
395 10 Template::Stencil->new(template_dir => $_, stat_ttl => -1)
396 } @dirs;
397  
398 10 for my $name (@TEMPLATES) {
399 70 my ($i) = grep { -f File::Spec->catfile($dirs[$_], "$name.tmpl") }
400 0 .. $#dirs;
401 70 ▶ Carp::croak("Punk::Plugin::Queue: no template '$name.tmpl' in "
Branch: 1 branch
BranchTrueFalseTotal
unless defined $i 0 70 70
402 . join(' or ', @dirs)) unless defined $i;
403 70 $st->{templates}{$name} = $engines[$i];
404 70 $st->{template_dir}{$name} = $dirs[$i];
405 }
406 10 $st->{template_dirs} = \@dirs;
407 10 return;
408 }
409  
410 # Everything every page renders with. Built at register, so a custom
411 # layout sees the same names the shipped one does.
412 10 ▶sub _template_data {
Subroutine _template_data: called CC=2 SCAR=6.9
413 10 my ($st) = @_;
414 10 my $p = $st->{prefix};
415 return {
416 prefix => $p,
417 version => $VERSION,
418 styles => ["$p/assets/funky.css"],
419 scripts => ["$p/assets/funky.js", "$p/assets/app.js"],
420 10 nav => [ map { { href => $p . ($_->{path} ? "/$_->{path}" : ''),
421 50 ▶ label => $_->{title}, id => $_->{id} } } @PAGES ],
Branch: 1 branch
BranchTrueFalseTotal
$_->{'path'} ? : 40 10 50
422 };
423 }
424  
425 # A page, rendered lazily on first serve: the csrf cookie name is read off
426 # the app then, not at register, because `csrf` may legitimately run after
427 # `plugin` in the app class. Two renders - the page, then the layout with
428 # it as `content` - rather than Stencil's wrapper, because page and layout
429 # may come from different roots and a wrapper renders in one engine.
430 12 ▶sub _page {
Subroutine _page: called CC=5 SCAR=16.3
431 12 my ($st, $name, $id, $title, %extra) = @_;
432 0 my $key = "$name:" . join(',', map { "$_=$extra{$_}" } sort keys %extra);
433 12 ▶ return $st->{page_cache}{$key} //= do {
Condition66%2/3
$st->{"page_cache"}{$key} //= do { my $csrf = $st->{"app"}{"csrf"}; my $data = {%{$st->{"tmpl_data"};}, "page", $id, "title", $title, "csrf_cookie", $csrf ? $csrf->{"cookie"} // "csrf" : "", "live", $st->{"live"} ? "true" : "false", %extra}; $data->{"content"} = $st->{"templates"}{$name}->render($name, $data); $st->{"templates"}{"layout"}->render("layout", $data) }
l!l&&r!l&&!r
1110
MC/DC0%0/2
$st->{"page_cache"}{$key} //= do { my $csrf = $st->{"app"}{"csrf"}; my $data = {%{$st->{"tmpl_data"};}, "page", $id, "title", $title, "csrf_cookie", $csrf ? $csrf->{"cookie"} // "csrf" : "", "live", $st->{"live"} ? "true" : "false", %extra}; $data->{"content"} = $st->{"templates"}{$name}->render($name, $data); $st->{"templates"}{"layout"}->render("layout", $data) }
$st->{"page_cache"}{$key} do { my $csrf = $st->{"app"}{"csrf"}; my $data = {%{$st->{"tmpl_data"};}, "page", $id, "title", $title, "csrf_cookie", $csrf ? $csrf->{"cookie"} // "csrf" : "", "live", $st->{"live"} ? "true" : "false", %extra}; $data->{"content"} = $st->{"templates"}{$name}->render($name, $data); $st->{"templates"}{"layout"}->render("layout", $data) }
Truth table66%2/3
A //= B
A= $st->{"page_cache"}{$key}B= do { my $csrf = $st->{"app"}{"csrf"}; my $data = {%{$st->{"tmpl_data"};}, "page", $id, "title", $title, "csrf_cookie", $csrf ? $csrf->{"cookie"} // "csrf" : "", "live", $st->{"live"} ? "true" : "false", %extra}; $data->{"content"} = $st->{"templates"}{$name}->render($name, $data); $st->{"templates"}{"layout"}->render("layout", $data) }
ABresult
1X1
011
000
434 11 my $csrf = $st->{app}{csrf};
435 my $data = {
436 11 ▶ %{ $st->{tmpl_data} },
Branch: 2 branches
BranchTrueFalseTotal
$csrf ? : 1 10 11
$st->{'live'} ? : 1 10 11
Condition50%1/2
$csrf->{"cookie"} // "csrf"
l!l
10
MC/DC0%0/1
$csrf->{"cookie"} // "csrf"
$csrf->{"cookie"}
Truth table50%1/2
A
A= $csrf->{"cookie"}
Aresult
11
00
437 page => $id,
438 title => $title,
439 csrf_cookie => $csrf ? ($csrf->{cookie} // 'csrf') : '',
440 11 live => $st->{live} ? 'true' : 'false',
441 %extra,
442 };
443 11 $data->{content} = $st->{templates}{$name}->render($name, $data);
444 11 $st->{templates}{layout}->render('layout', $data);
445 };
446 }
447  
448 23 ▶sub _bytes {
Subroutine _bytes: called CC=4 SCAR=13.9
449 23 my ($c, $type, $body, $etag) = @_;
450 23 ▶ if ($etag) {
Branch: 1 branch
BranchTrueFalseTotal
if ($etag) 11 12 23
451 11 ▶ my $inm = $c->req->header('If-None-Match') // '';
Condition100%2/2
$c->req->header("If-None-Match") // ""
l!l
29
MC/DC100%1/1
$c->req->header("If-None-Match") // ""
$c->req->header("If-None-Match")
Truth table100%2/2
A
A= $c->req->header("If-None-Match")
Aresult
11
00
452 11 ▶ return [304, ['ETag' => $etag], []] if $inm eq $etag;
Branch: 1 branch
BranchTrueFalseTotal
if $inm eq $etag 2 9 11
453 9 return [200, ['Content-Type' => $type,
454 'Content-Length' => length $body,
455 'ETag' => $etag], [$body]];
456 }
457 12 return [200, ['Content-Type' => $type,
458 'Content-Length' => length $body], [$body]];
459 }
460  
461 13 ▶sub _register_admin {
Subroutine _register_admin: called CC=13 SCAR=27.2
462 13 my ($st) = @_;
463 13 my $app = $st->{app};
464 13 my $a = $st->{opts}{admin};
465 13 ▶ $a = {} unless ref $a;
Branch: 1 branch
BranchTrueFalseTotal
unless ref $a 0 13 13
466  
467 # A loud failure beats a silent hole: an admin UI that retries and
468 # removes jobs without a guard is an unauthenticated control plane.
469 Carp::croak("Punk::Plugin::Queue: admin needs a guard - "
470 . "admin => { guard => sub {...} } (or set "
471 . "PUNK_QUEUE_ADMIN_INSECURE to mean it)")
472 13 ▶ unless $a->{guard} or $ENV{PUNK_QUEUE_ADMIN_INSECURE};
Branch: 1 branch
BranchTrueFalseTotal
unless $a->{"guard"} or $ENV{"PUNK_QUEUE_ADMIN_INSECURE"} 1 12 13
Condition100%3/3
$a->{"guard"} or $ENV{"PUNK_QUEUE_ADMIN_INSECURE"}
l!l&&r!l&&!r
1111
MC/DC100%2/2
$a->{"guard"} or $ENV{"PUNK_QUEUE_ADMIN_INSECURE"}
$a->{"guard"} $ENV{"PUNK_QUEUE_ADMIN_INSECURE"}
Truth table100%3/3
A or B
A= $a->{"guard"}B= $ENV{"PUNK_QUEUE_ADMIN_INSECURE"}
ABresult
1X1
011
000
473  
474 12 ▶ my $prefix = $a->{prefix} // '/queue';
Condition100%2/2
$a->{"prefix"} // "/queue"
l!l
93
MC/DC100%1/1
$a->{"prefix"} // "/queue"
$a->{"prefix"}
Truth table100%2/2
A
A= $a->{"prefix"}
Aresult
11
00
475 12 $prefix =~ s{/\z}{};
476 12 $st->{prefix} = $prefix;
477 12 $st->{live} = 0;
478  
479 12 ▶ if ($a->{api}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($a->{"api"}) 0 12 12
480 0 warn "Punk::Plugin::Queue: admin => { api => 1 } (Open::API "
481 . "registration) is not implemented in this release; using "
482 . "the native routes\n";
483 }
484  
485 12 _build_assets($st, $a);
486 11 _build_templates($st, $a);
487 10 $st->{tmpl_data} = _template_data($st);
488  
489 my $gcode = ref $a->{guard} eq 'CODE' ? $a->{guard}
490 : $a->{guard} ? _resolve_target($st, $a->{guard},
491 'admin guard')
492 0 ▶ : sub { return }; # PUNK_QUEUE_ADMIN_INSECURE
Subroutine __ANON__: not called CC=1 SCAR=0.4
Branch: 2 branches
BranchTrueFalseTotal
ref $a->{'guard'} eq 'CODE' ? : 9 1 10
$a->{'guard'} ? : 0 1 1
493 10 my $s = $app->under($prefix => $gcode);
494 10 my $q = $st->{queue};
495  
496 # ---- pages ----
497 # A page GET touches $c->csrf_token when the app has csrf configured:
498 # the mint writes the script-readable mirror cookie for this response,
499 # which the layout's bridge copies into the cookie Funky hardcodes -
500 # without the touch, the browser never holds a token to submit.
501 12 ▶ my $mint = sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
502 12 my ($c) = @_;
503 12 ▶ $c->csrf_token if $st->{app}{csrf};
Branch: 1 branch
BranchTrueFalseTotal
if $st->{"app"}{"csrf"} 2 10 12
504 12 return;
505 10 };
506 10 for my $p (@PAGES) {
507 12 ▶ $s->get(($p->{path} eq '' ? '/' : "/$p->{path}") => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
508 12 my ($c) = @_;
509 12 $mint->($c);
510 return _bytes($c, 'text/html; charset=utf-8',
511 12 _page($st, $p->{tmpl}, $p->{id}, $p->{title}));
512 50 ▶ });
Branch: 1 branch
BranchTrueFalseTotal
$p->{'path'} eq '' ? : 10 40 50
513 }
514 0 ▶ $s->get('/jobs/:id' => sub {
Subroutine __ANON__: not called CC=3 SCAR=24.8
515 0 my ($c) = @_;
516 0 my $id = $c->param('id');
517 0 ▶ return $c->not_found unless ($id // '') =~ /\A\d+\z/;
Branch: 1 branch
BranchTrueFalseTotal
unless ($id // "") =~ /\A\d+\z/ 0 0 0
Condition0%0/2
$id // ""
l!l
00
MC/DC0%0/1
$id // ""
$id
Truth table0%0/2
A
A= $id
Aresult
11
00
518 0 $mint->($c);
519 0 return _bytes($c, 'text/html; charset=utf-8',
520 _page($st, 'job', 'pq-job', "Job $id", id => $id));
521 10 });
522  
523 # ---- assets (memory-served, ETagged) ----
524 # no charset on the webfont: it is not text, and a charset parameter
525 # on a binary type is what makes a proxy think it may transcode it
526 10 for my $asset (['funky.js', 'application/javascript; charset=utf-8'],
527 ['funky.css', 'text/css; charset=utf-8'],
528 ['app.js', 'application/javascript; charset=utf-8'],
529 ['fa-solid-900.woff2', 'font/woff2']) {
530 40 my ($name, $type) = @$asset;
531 11 ▶ $s->get("/assets/$name" => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
532 11 my ($c) = @_;
533 return _bytes($c, $type, $st->{assets}{$name},
534 11 $st->{etags}{$name});
535 40 });
536 }
537  
538 # ---- the api ----
539 8 ▶ my $json_err = sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
540 8 my ($c, $status, $msg) = @_;
541 8 return $c->json({ error => $msg }, $status);
542 10 };
543  
544 10 ▶ $s->get('/api/stats' => sub { $_[0]->json($q->stats) });
Subroutine __ANON__: called CC=1 SCAR=0.0
545 10 ▶ $s->get('/api/history' => sub { $_[0]->json($q->history) });
Subroutine __ANON__: called CC=1 SCAR=0.0
546  
547 # Funky.Table's server-side wire: draw/page/limit/search/sort(JSON
548 # [{column,dir}]) + the filter vocabulary; response { data, total,
549 # draw }. page/limit map onto phase 6's offset/limit; sortable
550 # columns are whitelisted in C exactly as filterable ones are.
551 13 ▶ my $table = sub {
Subroutine __ANON__: called CC=16 SCAR=28.2
552 13 my ($c, $lister, $key) = @_;
553 13 ▶ my $page = int($c->param('page') // 1); $page = 1 if $page < 1;
Branch: 1 branch
BranchTrueFalseTotal
if $page < 1 0 13 13
Condition100%2/2
$c->param("page") // 1
l!l
211
MC/DC100%1/1
$c->param("page") // 1
$c->param("page")
Truth table100%2/2
A
A= $c->param("page")
Aresult
11
00
554 13 ▶ my $limit = int($c->param('limit') // 25);
Condition100%2/2
$c->param("limit") // 25
l!l
211
MC/DC100%1/1
$c->param("limit") // 25
$c->param("limit")
Truth table100%2/2
A
A= $c->param("limit")
Aresult
11
00
555 13 ▶ $limit = 25 if $limit < 1; $limit = 100 if $limit > 100;
Branch: 2 branches
BranchTrueFalseTotal
if $limit < 1 0 13 13
if $limit > 100 0 13 13
556  
557 13 my %f;
558 13 for my $k (qw(state queue task worker search)) {
559 65 my $v = $c->param($k);
560 65 ▶ $f{$k} = $v if defined $v && length $v;
Branch: 1 branch
BranchTrueFalseTotal
if defined $v and length $v 8 57 65
Condition66%2/3
defined $v and length $v
!ll&&!rl&&r
5708
MC/DC50%1/2
defined $v and length $v
defined $v length $v
Truth table66%2/3
A and B
A= defined $vB= length $v
ABresult
0X0
100
111
561 }
562 13 my ($sc, $sd);
563 13 ▶ if (my $sort = $c->param('sort')) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $sort = $c->param("sort")) 2 11 13
564 2 my $list = eval {
565 2 File::Raw::JSON::file_json_decode($sort) };
566 2 ▶ if (ref $list eq 'ARRAY' && @$list) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $list eq "ARRAY" and @$list) 2 0 2
Condition33%1/3
ref $list eq "ARRAY" and @$list
!ll&&!rl&&r
002
MC/DC0%0/2
ref $list eq "ARRAY" and @$list
ref $list eq "ARRAY" @$list
Truth table33%1/3
A and B
A= ref $list eq "ARRAY"B= @$list
ABresult
0X0
100
111
567 2 $sc = $list->[0]{column};
568 2 ▶ $sd = ($list->[0]{dir} // '') eq 'asc' ? 'asc' : 'desc';
Branch: 1 branch
BranchTrueFalseTotal
($list->[0]{'dir'} // '') eq 'asc' ? : 1 1 2
Condition50%1/2
$list->[0]{"dir"} // ""
l!l
20
MC/DC0%0/1
$list->[0]{"dir"} // ""
$list->[0]{"dir"}
Truth table50%1/2
A
A= $list->[0]{"dir"}
Aresult
11
00
569 }
570 }
571 13 my $r = eval { $lister->($page, $limit, \%f, $sc, $sd) };
572 13 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 1 12 13
573 1 my $why = "$@";
574 1 $why =~ s/ at .*//s;
575 1 return $json_err->($c, 400, $why);
576 }
577 return $c->json({
578 data => $r->{$key},
579 total => $r->{total},
580 12 ▶ draw => int($c->param('draw') // 0),
Condition100%2/2
$c->param("draw") // 0
l!l
111
MC/DC100%1/1
$c->param("draw") // 0
$c->param("draw")
Truth table100%2/2
A
A= $c->param("draw")
Aresult
11
00
581 });
582 10 };
583  
584 9 ▶ $s->get('/api/jobs' => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
585 9 my ($c) = @_;
586 9 ▶ return $table->($c, sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
587 9 my ($page, $limit, $f, $sc, $sd) = @_;
588 9 $q->list_jobs(($page - 1) * $limit, $limit, $f, $sc, $sd);
589 9 }, 'jobs');
590 10 });
591 3 ▶ $s->get('/api/workers' => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
592 3 my ($c) = @_;
593 3 ▶ return $table->($c, sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
594 3 my ($page, $limit, $f) = @_;
595 3 $q->list_workers(($page - 1) * $limit, $limit, $f);
596 3 }, 'workers');
597 10 });
598 1 ▶ $s->get('/api/locks' => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
599 1 my ($c) = @_;
600 1 ▶ return $table->($c, sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
601 1 my ($page, $limit, $f) = @_;
602 1 $q->list_locks(($page - 1) * $limit, $limit, $f);
603 1 }, 'locks');
604 10 });
605 2 ▶ $s->get('/api/crons' => sub {
Subroutine __ANON__: called CC=13 SCAR=32.2
606 2 my ($c) = @_;
607 2 ▶ my $page = int($c->param('page') // 1); $page = 1 if $page < 1;
Branch: 1 branch
BranchTrueFalseTotal
if $page < 1 0 2 2
Condition50%1/2
$c->param("page") // 1
l!l
02
MC/DC0%0/1
$c->param("page") // 1
$c->param("page")
Truth table50%1/2
A
A= $c->param("page")
Aresult
11
00
608 2 ▶ my $limit = int($c->param('limit') // 25);
Condition50%1/2
$c->param("limit") // 25
l!l
02
MC/DC0%0/1
$c->param("limit") // 25
$c->param("limit")
Truth table50%1/2
A
A= $c->param("limit")
Aresult
11
00
609 2 ▶ $limit = 25 if $limit < 1; $limit = 100 if $limit > 100;
Branch: 2 branches
BranchTrueFalseTotal
if $limit < 1 0 2 2
if $limit > 100 0 2 2
610 # crons are declarations - dozens, not millions - so search here
611 # greps the full set in Perl instead of growing the C lister,
612 # and paging slices afterwards so page 2 of a search is right
613 2 my $rows = $q->list_crons->{crons};
614 2 my $term = $c->param('search');
615 2 ▶ if (defined $term and length $term) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $term and length $term) 1 1 2
Condition66%2/3
defined $term and length $term
!ll&&!rl&&r
101
MC/DC50%1/2
defined $term and length $term
defined $term length $term
Truth table66%2/3
A and B
A= defined $termB= length $term
ABresult
0X0
100
111
616 1 my $t = lc $term;
617 $rows = [ grep {
618 1 index(lc $_->{name}, $t) >= 0
619 || index(lc $_->{task}, $t) >= 0
620 0 ▶ || index(lc $_->{expr}, $t) >= 0
Condition0%0/6
index(lc $_->{'name'}, $t) != -1 || index(lc $_->{'task'}, $t) != -1 || index(lc $_->{'expr'}, $t) != -1
l!l&&r!l&&!r
000
index(lc $_->{"name"}, $t) != -1 or index(lc $_->{"task"}, $t) != -1
l!l&&r!l&&!r
000
MC/DC0%0/3
index(lc $_->{'name'}, $t) != -1 || index(lc $_->{'task'}, $t) != -1 || index(lc $_->{'expr'}, $t) != -1
index(lc $_->{"name"}, $t) != -1 index(lc $_->{"task"}, $t) != -1 index(lc $_->{'expr'}, $t) != -1
Truth table0%0/4
A or B || C
A= index(lc $_->{"name"}, $t) != -1B= index(lc $_->{"task"}, $t) != -1C= index(lc $_->{'expr'}, $t) != -1
ABCresult
1XX1
01X1
0011
0000
621 } @$rows ];
622 }
623 2 my $total = @$rows;
624 2 my $off = ($page - 1) * $limit;
625 $rows = $off < $total
626 0 ▶ ? [ @{$rows}[$off .. ($off + $limit - 1 > $#$rows
Branch: 2 branches
BranchTrueFalseTotal
$off < $total ? : 0 2 2
$off + $limit - 1 > $rows->$#* ? : 0 0 0
627 ? $#$rows : $off + $limit - 1)] ]
628 : [];
629 # Funky selection/update keys off row.id; the name IS the identity
630 0 my @rows = map { { %$_, id => $_->{name} } } @$rows;
631 2 ▶ return $c->json({ data => \@rows, total => $total,
Condition50%1/2
$c->param("draw") // 0
l!l
02
MC/DC0%0/1
$c->param("draw") // 0
$c->param("draw")
Truth table50%1/2
A
A= $c->param("draw")
Aresult
11
00
632 draw => int($c->param('draw') // 0) });
633 10 });
634  
635 2 ▶ $s->get('/api/jobs/:id' => sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
636 2 my ($c) = @_;
637 2 my $j = $q->job_info(int($c->param('id')));
638 2 ▶ return $json_err->($c, 404, 'no such job') unless $j;
Branch: 1 branch
BranchTrueFalseTotal
unless $j 1 1 2
639 1 return $c->json($j);
640 10 });
641 # the job's log, oldest first - lifecycle rows plus whatever the
642 # task wrote through $job->log
643 2 ▶ $s->get('/api/jobs/:id/log' => sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
644 2 my ($c) = @_;
645 2 my $id = int($c->param('id'));
646 2 ▶ return $json_err->($c, 404, 'no such job')
Branch: 1 branch
BranchTrueFalseTotal
unless $q->job_info($id) 1 1 2
647 unless $q->job_info($id);
648 1 my $log = $q->job_log($id);
649 1 return $c->json({ log => $log, total => scalar @$log });
650 10 });
651 1 ▶ $s->post('/api/jobs/:id/retry' => sub {
Subroutine __ANON__: called CC=4 SCAR=14.5
652 1 my ($c) = @_;
653 1 my $id = int($c->param('id'));
654 1 ▶ my $j = $q->job_info($id)
Branch: 1 branch
BranchTrueFalseTotal
my $j = $q->job_info($id) or return &$json_err($c, 404, "no such job") 1 0 1
655 or return $json_err->($c, 404, 'no such job');
656 1 my $ok = $q->retry_job($id, $j->{retries});
657 1 ▶ _live_push($st, job => update => $id) if $ok;
Branch: 1 branch
BranchTrueFalseTotal
if $ok 1 0 1
658 1 ▶ return $ok ? $c->json({ ok => 1 })
Branch: 1 branch
BranchTrueFalseTotal
$ok ? : 1 0 1
659 : $json_err->($c, 409, 'job changed underneath; reload');
660 10 });
661 1 ▶ $s->post('/api/jobs/:id/remove' => sub {
Subroutine __ANON__: called CC=4 SCAR=14.5
662 1 my ($c) = @_;
663 1 my $id = int($c->param('id'));
664 1 ▶ my $j = $q->job_info($id)
Branch: 1 branch
BranchTrueFalseTotal
my $j = $q->job_info($id) or return &$json_err($c, 404, "no such job") 1 0 1
665 or return $json_err->($c, 404, 'no such job');
666 1 my $ok = $q->remove_job($id);
667 1 ▶ _live_push($st, job => delete => $id) if $ok;
Branch: 1 branch
BranchTrueFalseTotal
if $ok 0 1 1
668 1 ▶ return $ok ? $c->json({ ok => 1 })
Branch: 1 branch
BranchTrueFalseTotal
$ok ? : 0 1 1
669 : $json_err->($c, 409,
670 'an active job is refused; retry it first');
671 10 });
672  
673 # Bulk: SELECTION-ONLY, never filter-wide. Explicit ids, a hard cap,
674 # and a filter expression in the payload is rejected outright - the
675 # operator has looked at every row they are acting on, and "retry
676 # everything matching" remains excluded on purpose.
677 5 ▶ $s->post('/api/jobs/bulk' => sub {
Subroutine __ANON__: called CC=19 SCAR=30.7
678 5 my ($c) = @_;
679 5 ▶ my $body = eval { $c->req->json } // {};
Condition50%1/2
eval { do { $c->req->json } } // {}
l!l
50
MC/DC0%0/1
eval { do { $c->req->json } } // {}
eval { do { $c->req->json } }
Truth table50%1/2
A
A= eval { do { $c->req->json } }
Aresult
11
00
680 return $json_err->($c, 400, 'filter payloads are rejected: bulk '
681 . 'is selection-only, send explicit ids')
682 if exists $body->{filter} || exists $body->{query}
683 5 ▶ || exists $body->{where};
Branch: 1 branch
BranchTrueFalseTotal
if exists $body->{"filter"} or exists $body->{"query"} or exists $body->{"where"} 1 4 5
Condition66%4/6
exists $body->{"filter"} or exists $body->{"query"} or exists $body->{"where"}
l!l&&r!l&&!r
104
exists $body->{"filter"} or exists $body->{"query"}
l!l&&r!l&&!r
104
MC/DC33%1/3
exists $body->{"filter"} or exists $body->{"query"} or exists $body->{"where"}
exists $body->{"filter"} exists $body->{"query"} exists $body->{"where"}
Truth table50%2/4
A or B or C
A= exists $body->{"filter"}B= exists $body->{"query"}C= exists $body->{"where"}
ABCresult
1XX1
01X1
0011
0000
684 4 ▶ my $action = $body->{action} // '';
Condition50%1/2
$body->{"action"} // ""
l!l
40
MC/DC0%0/1
$body->{"action"} // ""
$body->{"action"}
Truth table50%1/2
A
A= $body->{"action"}
Aresult
11
00
685 4 ▶ return $json_err->($c, 400, "unknown bulk action '$action'")
Branch: 1 branch
BranchTrueFalseTotal
unless $action =~ /\A(?:retry|remove)\z/ 1 3 4
686 unless $action =~ /\A(?:retry|remove)\z/;
687 3 my $ids = $body->{ids};
688 3 ▶ return $json_err->($c, 400, 'ids must be a non-empty array')
Branch: 1 branch
BranchTrueFalseTotal
unless ref $ids eq "ARRAY" and @$ids 0 3 3
Condition33%1/3
ref $ids eq "ARRAY" and @$ids
!ll&&!rl&&r
003
MC/DC0%0/2
ref $ids eq "ARRAY" and @$ids
ref $ids eq "ARRAY" @$ids
Truth table33%1/3
A and B
A= ref $ids eq "ARRAY"B= @$ids
ABresult
0X0
100
111
689 unless ref $ids eq 'ARRAY' && @$ids;
690 3 ▶ return $json_err->($c, 400, 'bulk is capped at 500 ids')
Branch: 1 branch
BranchTrueFalseTotal
if @$ids > 500 1 2 3
691 if @$ids > 500;
692  
693 2 my (%out, $ok, $no);
694 2 for my $id (@$ids) {
695 3 ▶ next unless ($id // '') =~ /\A\d+\z/;
Branch: 1 branch
BranchTrueFalseTotal
unless ($id // "") =~ /\A\d+\z/ 0 3 3
Condition50%1/2
$id // ""
l!l
30
MC/DC0%0/1
$id // ""
$id
Truth table50%1/2
A
A= $id
Aresult
11
00
696 3 my $did = 0;
697 3 ▶ if ($action eq 'retry') {
Branch: 1 branch
BranchTrueFalseTotal
if ($action eq 'retry') { } 1 2 3
698 1 my $j = $q->job_info($id);
699 1 ▶ $did = $j ? $q->retry_job($id, $j->{retries}) : 0;
Branch: 1 branch
BranchTrueFalseTotal
$j ? : 0 1 1
700 }
701 2 else { $did = $q->remove_job($id) }
702 3 ▶ $out{$id} = $did ? 'ok' : 'skipped';
Branch: 1 branch
BranchTrueFalseTotal
$did ? : 1 2 3
703 3 ▶ $did ? $ok++ : $no++;
Branch: 1 branch
BranchTrueFalseTotal
$did ? : 1 2 3
704 }
705 2 _live_push($st, job => refresh => 0);
706 2 ▶ return $c->json({ succeeded => $ok // 0, failed => $no // 0,
Condition75%3/4
$ok // 0
l!l
11
$no // 0
l!l
20
MC/DC100%1/1
$ok // 0
$ok
MC/DC0%0/1
$no // 0
$no
Truth table100%2/2
A
A= $ok
Aresult
11
00
Truth table50%1/2
A
A= $no
Aresult
11
00
707 results => \%out });
708 10 });
709  
710 1 ▶ $s->post('/api/workers/:id/stop' => sub {
Subroutine __ANON__: called CC=3 SCAR=11.3
711 1 my ($c) = @_;
712 1 my $id = int($c->param('id'));
713 1 my $n = $q->broadcast('stop', [], [$id]);
714 1 ▶ _live_push($st, worker => update => $id) if $n;
Branch: 1 branch
BranchTrueFalseTotal
if $n 1 0 1
715 1 ▶ return $n ? $c->json({ ok => 1 })
Branch: 1 branch
BranchTrueFalseTotal
$n ? : 1 0 1
716 : $json_err->($c, 404, 'no such worker');
717 10 });
718 # run now: enqueue the cron's job immediately, ignoring the schedule
719 # and NOT advancing next_run - the "fire it while I watch" button
720 0 ▶ $s->post('/api/crons/:id/run' => sub {
Subroutine __ANON__: not called CC=2 SCAR=17.9
721 0 my ($c) = @_;
722 0 ▶ my $cron = $q->cron_info($c->param('id'))
Branch: 1 branch
BranchTrueFalseTotal
my $cron = $q->cron_info($c->param("id")) or return &$json_err($c, 404, "no such cron") 0 0 0
723 or return $json_err->($c, 404, 'no such cron');
724 my $id = $q->enqueue($cron->{task}, $cron->{args},
725 queue => $cron->{queue},
726 priority => $cron->{priority},
727 0 attempts => $cron->{attempts});
728 0 _live_push($st, job => create => $id);
729 0 return $c->json({ ok => 1, id => $id });
730 10 });
731 # the operational pause. Boot reconciliation never resets enabled, so
732 # a disable made here survives every deploy; re-enabling recomputes
733 # next_run from now (the disabled window behaves as catchup skip).
734 10 for my $flip (['enable', 1], ['disable', 0]) {
735 20 my ($verb, $on) = @$flip;
736 1 ▶ $s->post("/api/crons/:id/$verb" => sub {
Subroutine __ANON__: called CC=4 SCAR=21.7
737 1 my ($c) = @_;
738 1 my $name = $c->param('id');
739 1 ▶ return $json_err->($c, 404, 'no such cron')
Branch: 1 branch
BranchTrueFalseTotal
unless $q->cron_info($name) 1 0 1
740 unless $q->cron_info($name);
741 0 my $took = $q->enable_cron($name, $on);
742 0 ▶ _live_push($st, cron => update => 0) if $took;
Branch: 1 branch
BranchTrueFalseTotal
if $took 0 0 0
743 0 ▶ return $c->json({ ok => $took ? 1 : 0 });
Branch: 1 branch
BranchTrueFalseTotal
$took ? : 0 0 0
744 20 });
745 }
746  
747 10 ▶ _register_live($st, $s) if $a->{live};
Branch: 1 branch
BranchTrueFalseTotal
if $a->{"live"} 2 8 10
748 10 return;
749 }
750  
751 # ---- live mode --------------------------------------------------------------
752  
753 2 ▶sub _register_live {
Subroutine _register_live: called CC=2 SCAR=11.6
754 2 my ($st, $s) = @_;
755  
756 # a websocket route without the Hyperman detach path would croak the
757 # whole app at to_app; degrade to polling instead - the UI already
758 # treats live as an enhancement
759 2 require Punk::WebSocket;
760 2 ▶ unless (Punk::WebSocket::_hm_available()) {
Branch: 1 branch
BranchTrueFalseTotal
unless (Punk::WebSocket::_hm_available()) 1 1 2
761 1 warn "Punk::Plugin::Queue: admin live mode needs Hyperman's "
762 . "detach path; staying on polling\n";
763 1 return;
764 }
765 1 $st->{live} = 1;
766 1 $st->{live_conns} = [];
767  
768 0 ▶ $s->websocket('/ws' => sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
769 0 my ($c, $ws) = @_;
770 0 push @{ $st->{live_conns} }, $ws;
771 0 $ws->send(_encode_json({ type => 'connected' }));
772 0 ▶ $ws->on(message => sub {
Subroutine __ANON__: not called CC=4 SCAR=30.0
773 0 my ($conn, $text) = @_;
774 0 my $m = eval { File::Raw::JSON::file_json_decode($text) };
775 0 ▶ return unless ref $m eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $m eq "HASH" 0 0 0
776 $conn->send(_encode_json({ type => 'pong' }))
777 0 ▶ if ($m->{type} // '') eq 'ping';
Branch: 1 branch
BranchTrueFalseTotal
if ($m->{"type"} // "") eq "ping" 0 0 0
Condition0%0/2
$m->{"type"} // ""
l!l
00
MC/DC0%0/1
$m->{"type"} // ""
$m->{"type"}
Truth table0%0/2
A
A= $m->{"type"}
Aresult
11
00
778 0 });
779 0 ▶ $ws->on(close => sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
780 0 my ($conn) = @_;
781 0 @{ $st->{live_conns} } =
782 0 grep { $_ != $conn } @{ $st->{live_conns} };
783 0 });
784 1 });
785 1 return;
786 }
787  
788 0 ▶sub _encode_json {
Subroutine _encode_json: not called CC=1 SCAR=6.9
789 0 require File::Raw::JSON;
790 0 return File::Raw::JSON::file_json_encode($_[0]);
791 }
792  
793 # The entity envelope: { type: 'entity_change', entity, action, id }.
794 # Funky documents Pages.handleDataChange but ships no caller; app.js
795 # bridges this envelope into it. Actions performed through this app push
796 # immediately; external changes surface via the 5s stats poll (the boring
797 # path stays the fallback).
798 1 ▶sub _entity_envelope {
Subroutine _entity_envelope: called CC=1 SCAR=0.0
799 1 my ($entity, $action, $id) = @_;
800 1 return { type => 'entity_change', entity => $entity,
801 action => $action, id => $id };
802 }
803  
804 5 ▶sub _live_push {
Subroutine _live_push: called CC=6 SCAR=32.2
805 5 my ($st, $entity, $action, $id) = @_;
806 0 ▶ return unless $st->{live} && @{ $st->{live_conns} // [] };
Branch: 1 branch
BranchTrueFalseTotal
unless $st->{"live"} and @{$st->{"live_conns"} // [];} 5 0 5
Condition20%1/5
$st->{"live"} and @{$st->{"live_conns"} // [];}
!ll&&!rl&&r
500
$st->{"live_conns"} // []
l!l
00
MC/DC0%0/2
$st->{"live"} and @{$st->{"live_conns"} // [];}
$st->{"live"} @{$st->{"live_conns"} // [];}
MC/DC0%0/1
$st->{"live_conns"} // []
$st->{"live_conns"}
Truth table33%1/3
A and B
A= $st->{"live"}B= @{$st->{"live_conns"} // [];}
ABresult
0X0
100
111
Truth table0%0/2
A
A= $st->{"live_conns"}
Aresult
11
00
807 0 my $msg = _encode_json(_entity_envelope($entity, $action, $id));
808 0 my @alive;
809 0 for my $ws (@{ $st->{live_conns} }) {
810 0 ▶ push @alive, $ws if eval { $ws->send($msg); 1 };
Branch: 1 branch
BranchTrueFalseTotal
if eval { do { $ws->send($msg); 1 } } 0 0 0
811 }
812 0 $st->{live_conns} = \@alive;
813 0 return;
814 }
815  
816 # ---- in-server mode ---------------------------------------------------------
817  
818 2 ▶sub _register_inserver {
Subroutine _register_inserver: called CC=4 SCAR=14.2
819 2 my ($st) = @_;
820 2 my $is = $st->{opts}{in_server};
821 2 ▶ $is = {} unless ref $is;
Branch: 1 branch
BranchTrueFalseTotal
unless ref $is 0 2 2
822  
823 # rail 2: a task allowlist, never "all tasks" - boot croak
824 Carp::croak("Punk::Plugin::Queue: in_server needs an explicit task "
825 . "allowlist - in_server => { tasks => [...] }")
826 2 ▶ unless ref $is->{tasks} eq 'ARRAY' && @{ $is->{tasks} };
Branch: 1 branch
BranchTrueFalseTotal
unless ref $is->{"tasks"} eq "ARRAY" and @{$is->{"tasks"};} 1 1 2
Condition66%2/3
ref $is->{"tasks"} eq "ARRAY" and @{$is->{"tasks"};}
!ll&&!rl&&r
101
MC/DC50%1/2
ref $is->{"tasks"} eq "ARRAY" and @{$is->{"tasks"};}
ref $is->{"tasks"} eq "ARRAY" @{$is->{"tasks"};}
Truth table66%2/3
A and B
A= ref $is->{"tasks"} eq "ARRAY"B= @{$is->{"tasks"};}
ABresult
0X0
100
111
827  
828 1 my $q = $st->{queue};
829 1 my $attached = 0;
830  
831 # to_app runs in the Hyperman parent, before the fork, so there is no
832 # loop yet and hm_abi has no post-fork hook: attach lazily, one
833 # predictable branch per request
834 2 ▶ $st->{app}->hook(before_dispatch => sub {
Subroutine __ANON__: called CC=6 SCAR=19.2
835 2 ▶ return if $attached;
Branch: 1 branch
BranchTrueFalseTotal
if $attached 1 1 2
836 1 $attached = 1;
837 Punk::Queue::_inserver_attach($q, {
838 tasks => $is->{tasks},
839 queues => $is->{queues} // ['default'],
840 interval => $is->{interval} // 1,
841 1 ▶ cap => $is->{cap} // 5,
Branch: 1 branch
BranchTrueFalseTotal
Punk::Queue::_inserver_attach($q, {"tasks", $is->{"tasks"}, "queues", $is->{"queues"} // ["default"], "interval", $is->{"interval"} // 1, "cap", $is->{"cap"} // 5}) or warn "Punk::Plugin::Queue: in_server could not attach (no Hyperman loop); jobs will not run in-server\n" 0 1 1
Condition50%3/6
$is->{"queues"} // ["default"]
l!l
01
$is->{"interval"} // 1
l!l
10
$is->{"cap"} // 5
l!l
10
MC/DC0%0/1
$is->{"queues"} // ["default"]
$is->{"queues"}
MC/DC0%0/1
$is->{"interval"} // 1
$is->{"interval"}
MC/DC0%0/1
$is->{"cap"} // 5
$is->{"cap"}
Truth table50%1/2
A
A= $is->{"queues"}
Aresult
11
00
Truth table50%1/2
A
A= $is->{"interval"}
Aresult
11
00
Truth table50%1/2
A
A= $is->{"cap"}
Aresult
11
00
842 }) or warn "Punk::Plugin::Queue: in_server could not attach "
843 . "(no Hyperman loop); jobs will not run in-server\n";
844 1 return;
845 1 });
846 1 return;
847 }
848  
849 10 1;
850  
851 __END__
« blib/lib/Punk/Queue/Command.pm ↑ Summary blib/lib/Punk/Queue/Backend/Pg.pm »