blib/lib/App/Basis/Queue.pm

filter: Statementstmt 9.6% 69 / 719 Branchbran 0.0% 0 / 254 Conditioncond 0.0% 0 / 116 MC/DCmcdc 0.0% 0 / 69 Subroutinesub 19.1% 19 / 99 Podpod 96.1% 25 / 26 totaltotal 8.8% 113 / 1283 CC 188 SCAR 46.5
CC
188
Cov
6%
stats
420.0
listen
306.0
process
240.0
CRAP 104.7
↑ Summary
1 # ABSTRACT: Simple database backed FIFO queues
2  
3 # SELECT counter, queue_name, added, activates, expires,data
4 # FROM qsdb_queue
5 # WHERE queue_name LIKE '%'
6 # AND processed = 0
7 # AND process_failure = 0
8 # ORDER BY activates ASC, counter ASC
9 # ;
10  
11  
12 =head1 NAME
13  
14 App::Basis::Queue
15  
16 =head1 SYNOPSIS
17  
18 use App::Basis::Queue;
19  
20 my $dsn = "dbi:SQLite:/location/of/sqlite_db.sqlite3" ;
21 my $dbh = DBI->connect( $dsn, "", "",
22 { RaiseError => 1, PrintError => 0, } )
23 or die "Could not connect to DB $dsn" ;
24  
25 my $queue = App::Basis::Queue->new( dbh => $dbh) ;
26  
27 # save some application audit data for later processing
28 $queue->add(
29 queue => '/invoice/pay',
30 data => {
31 ip => 12.12.12.12,
32 session_id => 12324324345,
33 client_id => 248296432984,
34 amount => 250.45,
35 reply => '/payments/made'
36 },
37 ) ;
38  
39 # in another process, we want to process that data
40  
41 use App::Basis::Queue;
42  
43 # for the example this will be paying an invoice
44 sub processing_callback {
45 my ( $queue, $qname, $record, $params ) = @_;
46  
47 # call the payment system
48 # pay_money( $params->{auth}, $record->{client_id}, $record->{amount}) ;
49  
50 # chatter back that the payment has been made, assume it worked
51 $queue->pub( queue => $record->{reply},
52 data => {
53 client_id => $record->{ client_id},
54 success => 1,
55 }
56 ) ;
57 }
58  
59 my $dsn = "dbi:SQLite:/location/of/sqlite_db.sqlite3" ;
60 my $dbh = DBI->connect( $dsn, "", "",
61 { RaiseError => 1, PrintError => 0, } )
62 or die "Could not connect to DB $dsn" ;
63 my $queue = App::Basis::Queue->new( dbh => $dbh) ;
64 $queue->process(
65 queue => 'app_start',
66 count => 10,
67 callback => \&processing_callback,
68 callback_params => { auth => 'sometoken:12345'}
69 ) ;
70  
71 # for pubsub we do
72  
73 use App::Basis::Queue;
74  
75 my $dsn = "dbi:SQLite:/location/of/sqlite_db.sqlite3" ;
76 my $dbh = DBI->connect( $dsn, "", "",
77 { RaiseError => 1, PrintError => 0, } )
78 or die "Could not connect to DB $dsn" ;
79 my $queue = App::Basis::Queue->new( dbh => $dbh) ;
80 # for a system that wants to know when servers have started
81 $queue->publish( queue => '/chat/helo', data => { host => 'abc, msg => 'helo world') ;
82  
83 # in another process
84  
85 use App::Basis::Queue;
86 my $dsn = "dbi:SQLite:/location/of/sqlite_db.sqlite3" ;
87 my $dbh = DBI->connect( $dsn, "", "",
88 { RaiseError => 1, PrintError => 0, } )
89 or die "Could not connect to DB $dsn" ;
90 my $queue = App::Basis::Queue->new( dbh => $dbh) ;
91  
92 =head1 DESCRIPTION
93  
94 Why have another queuing system? Well for me I wanted a queuing system that did not mean
95 I needed to install and maintain another server (ie RabbitMQ). Something that could run
96 against existing DBs (eg PostgreSQL). PGQ was an option, but as it throws away queued items
97 if there is not a listener, then this was useless! Some of the Job/Worker systems required you to create
98 classes and plugins to process the queue. Queue::DBI almost made the grade but only has one queue. Minon
99 maybe could do what was needed but I did not find it in time.
100  
101 I need multiple queues plus new requirement queue wildcards!
102  
103 So I created this simple/basic system. You need to expire items, clean the queue and do things like that by hand,
104 there is no automation. You process items in the queue in chunks, not via a nice iterator.
105  
106 There is no queue polling per se you need to process the queue and try again when all are done,
107 there can only be one consumer of a record which is a good thing, if you cannot process an item it can be marked as
108 failed to be handled by a cleanup function you will need to create.
109  
110 =head1 End of Life
111  
112 I created this project mostly as a learning project, my requirements for what it does are changing which will
113 involve client/server operations, a shared cache and locking system for the task clients, so I am going to leave this
114 project parked and start something new
115  
116 =head1 AUTHOR
117  
118 kmulholland, moodfarm@cpan.org
119  
120 =head1 See Also
121  
122 L<Queue::DBI>, L<AnyMQ::Queue>, L<Minion>
123  
124 =head1 API
125  
126 =cut
127  
128 package App::Basis::Queue ;
129 3 $App::Basis::Queue::VERSION = '000.600.100';
130 3 ▶use 5.10.0 ;
Subroutine BEGIN: called CC=1 SCAR=0.0
131 3 ▶use feature 'state' ;
Subroutine BEGIN: called CC=1 SCAR=0.0
132 3 ▶use strict ;
Subroutine BEGIN: called CC=1 SCAR=0.0
133 3 ▶use warnings ;
Subroutine BEGIN: called CC=1 SCAR=0.0
134 3 ▶use Moo ;
Subroutine BEGIN: called CC=1 SCAR=0.0
135 3 ▶use MooX::Types::MooseLike::Base qw/InstanceOf HashRef Str/ ;
Subroutine BEGIN: called CC=1 SCAR=0.0
136 3 ▶use JSON ;
Subroutine BEGIN: called CC=1 SCAR=0.0
137 3 ▶use Data::UUID ;
Subroutine BEGIN: called CC=1 SCAR=0.0
138 3 ▶use Try::Tiny ;
Subroutine BEGIN: called CC=1 SCAR=0.0
139 3 ▶use POSIX qw( strftime) ;
Subroutine BEGIN: called CC=1 SCAR=0.0
140 3 ▶use Time::HiRes qw(gettimeofday tv_interval ) ;
Subroutine BEGIN: called CC=1 SCAR=0.0
141 3 ▶use Date::Manip ;
Subroutine BEGIN: called CC=1 SCAR=0.0
142  
143 # use Data::Printer ;
144  
145 # extends "App::Basis::QueueBase" ;
146  
147 # -----------------------------------------------------------------------------
148  
149 3 ▶use constant MSG_TASK => 'task' ;
Subroutine BEGIN: called CC=1 SCAR=0.0
150 3 ▶use constant MSG_CHATTER => 'chatter' ;
Subroutine BEGIN: called CC=1 SCAR=0.0
151 3 ▶use constant MSG_SIMPLE => 'simple' ;
Subroutine BEGIN: called CC=1 SCAR=0.0
152 3 ▶use constant MAX_PROCESS_ITEMS => 100 ;
Subroutine BEGIN: called CC=1 SCAR=0.0
153 3 ▶use constant FIVE_DAYS => 5 * 24 * 3600 ;
Subroutine BEGIN: called CC=1 SCAR=0.0
154 3 ▶use constant MAX_EXPIRY_DATETIME => "3000-01-01 12:00 UTC" ;
Subroutine BEGIN: called CC=1 SCAR=0.0
155 3 ▶use constant PEEK_MAX => 100 ;
Subroutine BEGIN: called CC=1 SCAR=0.0
156  
157 # -----------------------------------------------------------------------------
158 ## class initialisation
159 ## instancation variables
160 # -----------------------------------------------------------------------------
161  
162 3 has 'dbh' => (
163 is => 'ro',
164 isa => InstanceOf ['DBI::db']
165 ) ;
166  
167 has 'prefix' => (
168 is => 'ro',
169 isa => Str,
170 0 ▶ default => sub { 'qsdb' ; },
Subroutine __ANON__: not called CC=1 SCAR=6.9
171 3 ) ;
172  
173 has 'debug' => (
174 is => 'rw',
175 0 ▶ default => sub { 0 ; },
Subroutine __ANON__: not called CC=1 SCAR=6.9
176 3 writer => 'set_debug'
177 ) ;
178  
179 has 'skip_table_check' => (
180 is => 'ro',
181 0 ▶ default => sub { 0 ; },
Subroutine __ANON__: not called CC=1 SCAR=6.9
182 3 ) ;
183  
184 has 'subscriptions' => (
185 is => 'ro',
186 init_arg => 0,
187 0 ▶ default => sub { {} },
Subroutine __ANON__: not called CC=1 SCAR=6.9
188 3 ) ;
189  
190 # this is the number of events listened to
191 has 'ev_count' => (
192 is => 'ro',
193 init_arg => 0,
194 0 ▶ default => sub { {} },
Subroutine __ANON__: not called CC=1 SCAR=6.9
195 3 ) ;
196  
197 # when listening for chatter events we will wait for this many seconds
198 # before trying again
199 has 'listen_delay' => (
200 is => 'ro',
201 0 ▶ default => sub {1},
Subroutine __ANON__: not called CC=1 SCAR=6.9
202 3 ) ;
203  
204 has 'default_queue' => (
205 is => 'ro',
206 isa => Str,
207 0 ▶ default => sub {""},
Subroutine __ANON__: not called CC=1 SCAR=6.9
208 3 ) ;
209  
210 # -----------------------------------------------------------------------------
211 # once the class in instanciated then we need to ensure that we have the
212 # tables created
213  
214 =head2 new
215  
216 Create a new instance of a queue
217  
218 B<Parameters>
219  
220 Hash of
221  
222 =over
223  
224 =item dbh (required)
225  
226 DBI database handle of database previously connected to
227  
228 =item prefix
229  
230 set a prefix name of the tables, allows you to have dev/test/live versions in the same database
231  
232 =item debug (optional)
233  
234 set basic STDERR debugging on or off
235  
236 =item skip_table_check
237  
238 don't check to see if the tables need creating
239  
240 =item default_queue
241  
242 optionally provide a default queue to work with
243  
244 =back
245  
246 my $queue = App::Basis::Queue->new( dbh => $dbh ) ;
247  
248 =cut
249  
250 sub BUILD
251 0 ▶{
Subroutine BUILD: not called CC=4 SCAR=30.0
Pod undocumented
252 0 my $self = shift ;
253  
254 0 $self->_set_db_type( $self->{dbh}->{Driver}->{Name} ) ;
255 0 ▶ die("Valid Database connection required") if ( !$self->_db_type() ) ;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_db_type 0 0 0
256  
257 # if we are using sqlite then we need to set a pragma to allow
258 # cascading deletes on FOREIGN keys
259 0 ▶ if ( $self->_db_type() eq 'SQLite' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_db_type eq "SQLite") 0 0 0
260 0 $self->{dbh}->do("PRAGMA foreign_keys = ON") ;
261 }
262  
263 # ensure we have the tables created (if wanted)
264 0 ▶ $self->_create_tables() if ( !$self->skip_table_check ) ;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->skip_table_check 0 0 0
265  
266 # get the first list of queues we have
267 0 $self->list_queues() ;
268 }
269  
270 # -----------------------------------------------------------------------------
271 # TODO: add a DEMOLISH method to clean up unprocessed items when the object
272 # handle goes out of scope
273  
274 # -----------------------------------------------------------------------------
275 ## class private variables
276 # -----------------------------------------------------------------------------
277  
278 has _queue_list => (
279 is => 'rwp', # like ro, but creates _set_queue_list too
280 lazy => 1,
281 0 ▶ default => sub { {} },
Subroutine __ANON__: not called CC=1 SCAR=6.9
282 3 writer => '_set_queue_list',
283 init_arg => undef # dont allow setting in constructor ;
284 ) ;
285  
286 has _db_type => (
287 is => 'rwp', # like ro, but creates _set_queue_list too
288 lazy => 1,
289 0 ▶ default => sub {''},
Subroutine __ANON__: not called CC=1 SCAR=6.9
290 3 writer => '_set_db_type',
291 init_arg => undef # dont allow setting in constructor ;
292 ) ;
293  
294 has _processor => (
295 is => 'ro',
296 lazy => 1,
297 0 ▶ default => sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
298 0 my $hostname = `hostname` ;
299 0 $hostname =~ s/\s//g ;
300 0 $hostname . "::$ENV{USER}" . "::" . $$ ;
301 },
302 3 init_arg => undef # dont allow setting in constructor ;
303 ) ;
304  
305 # -----------------------------------------------------------------------------
306 ## class private methods
307 # -----------------------------------------------------------------------------
308  
309 sub _debug
310 0 ▶{
Subroutine _debug: not called CC=2 SCAR=17.9
311 0 my $self = shift ;
312  
313 0 ▶ return if ( !$self->{debug} ) ;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"debug"} 0 0 0
314  
315 0 my $msg = shift ;
316 0 $msg =~ s/^/ /gsm ;
317  
318 0 say STDERR $msg ;
319 }
320  
321 # -----------------------------------------------------------------------------
322 sub _build_sql_stmt
323 0 ▶{
Subroutine _build_sql_stmt: not called CC=5 SCAR=34.0
324 0 my ( $query, $p ) = @_ ;
325 0 ▶ our @params = $p ? @$p : () ;
Branch: 1 branch
BranchTrueFalseTotal
$p ? : 0 0 0
326 0 $query =~ s/\s+$// ;
327 0 ▶ $query .= ' ;' if ( $query !~ /;$/ ) ;
Branch: 1 branch
BranchTrueFalseTotal
unless $query =~ /;$/ 0 0 0
328  
329 # make sure we repesent NULL properly, do quoting - only basic its only for debug
330 0 our $i = 0 ;
331 {
332  
333 0 sub _repl
334 0 ▶ {
Subroutine _repl: not called CC=3 SCAR=24.8
335 0 my $out = 'NULL' ;
336  
337 # quote strings, leave numbers untouched, not doing floats
338 0 ▶ if ( defined $params[$i] ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $App::Basis::Queue::params[$App::Basis::Queue::i]) 0 0 0
339 0 ▶ $out
Branch: 1 branch
BranchTrueFalseTotal
$App::Basis::Queue::params[$App::Basis::Queue::i] =~ /^\d+$/ ? : 0 0 0
340 = $params[$i] =~ /^\d+$/ ? $params[$i] : "'$params[$i]'" ;
341 }
342 0 $i++ ;
343  
344 0 return $out ;
345 }
346 0 ▶ $query =~ s/\?/_repl/gex if ( @params && scalar(@params) ) ;
Branch: 1 branch
BranchTrueFalseTotal
if @App::Basis::Queue::params and scalar @App::Basis::Queue::params 0 0 0
Condition0%0/2
@App::Basis::Queue::params and scalar @App::Basis::Queue::params
!ll
00
MC/DC0%0/1
@App::Basis::Queue::params and scalar @App::Basis::Queue::params
@App::Basis::Queue::params
Truth table0%0/2
A
A= @App::Basis::Queue::params
Aresult
00
11
347 }
348  
349 0 return $query ;
350 }
351  
352 # -----------------------------------------------------------------------------
353 sub _query_db
354 0 ▶{
Subroutine _query_db: not called CC=4 SCAR=30.0
355 0 state $sth_map = {} ;
356 0 my $self = shift ;
357 0 my ( $query, $p, $no_results ) = @_ ;
358 0 ▶ my @params = $p ? @$p : () ;
Branch: 1 branch
BranchTrueFalseTotal
$p ? : 0 0 0
359 0 my %result ;
360  
361 0 $query =~ s/\s+$// ;
362 0 ▶ $query .= ' ;' if ( $query !~ /;$/ ) ;
Branch: 1 branch
BranchTrueFalseTotal
unless $query =~ /;$/ 0 0 0
363  
364 0 ▶ if ( $self->{debug} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"debug"}) 0 0 0
365  
366 0 $self->_debug(
367 "ACTUAL QUERY: $query\nQUERY PARAMS: " . to_json( \@params ) ) ;
368 0 my $sql = _build_sql_stmt( $query, $p ) ;
369 0 $self->_debug( 'BUILT QUERY : ' . $sql . "\n" ) ;
370 }
371  
372 0 ▶ try {
Subroutine __ANON__: not called CC=4 SCAR=30.0
373 0 my $sth ;
374  
375 # key based on query and fields we are using
376 0 my $key = "$query." . join( '.', @params ) ;
377 0 ▶ if ( $sth_map->{$key} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($sth_map->{$key}) { } 0 0 0
378 0 $sth = $sth_map->{$key} ;
379 } else {
380  
381 0 $sth = $self->{dbh}->prepare($query) ;
382  
383 # save the handle for next time
384 0 $sth_map->{$key} = $sth ;
385  
386 }
387 0 my $rv = $sth->execute(@params) ;
388 0 ▶ if ( !$no_results ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $no_results) { } 0 0 0
389  
390 # so as to get an array of hashes
391 0 $result{rows} = $sth->fetchall_arrayref( {} ) ;
392 0 $result{row_count} = scalar( @{ $result{rows} } ) ;
393 0 $result{success} = 1 ;
394  
395 $self->_debug(
396 0 'QUERY RESPONSE: ' . to_json( $result{rows} ) . "\n" ) ;
397 } else {
398 0 ▶ if ($rv) {
Branch: 1 branch
BranchTrueFalseTotal
if ($rv) 0 0 0
399 0 $result{row_count} = $sth->rows ;
400 0 $result{success} = 1 ;
401 }
402 }
403 }
404 0 ▶ catch {
Subroutine __ANON__: not called CC=1 SCAR=6.9
405 $result{error}
406 0 = "Failed to prepare/execute query: $query\nparams: "
407 . to_json($p)
408 . "\nerror: $@\n" ;
409  
410 0 warn $result{error} ;
411 # $self->_debug( $result{error} );
412 0 } ;
413 0 return \%result ;
414 }
415  
416 # -----------------------------------------------------------------------------
417 sub _update_db
418 0 ▶{
Subroutine _update_db: not called CC=1 SCAR=6.9
419 0 my $self = shift ;
420 0 my ( $table, $query, $params ) = @_ ;
421  
422 0 $query = "UPDATE $table $query" ;
423  
424 0 my $resp = $self->_query_db( $query, $params, 1 ) ;
425  
426 0 return $resp ;
427 }
428  
429 # -----------------------------------------------------------------------------
430 # we will hold onto statement handles to speed up inserts
431  
432 sub _insert_db
433 0 ▶{
Subroutine _insert_db: not called CC=3 SCAR=24.8
434 0 state $sth_map = {} ;
435 0 my $self = shift ;
436 0 my ( $table, $f, $p ) = @_ ;
437 0 ▶ my @params = $p ? @$p : () ;
Branch: 1 branch
BranchTrueFalseTotal
$p ? : 0 0 0
438  
439 # key based on table and fields we are inserting
440 0 my $key = "$table." . join( '.', @$f ) ;
441 0 my ( $query, $sql, $sth ) ;
442  
443 0 ▶ if ( $sth_map->{$key} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($sth_map->{$key}) { } 0 0 0
444 0 $sth = $sth_map->{$key} ;
445 } else {
446 $query
447 = "INSERT INTO $table ("
448 . join( ',', @$f )
449 . ") values ("
450 0 . join( ',', map {'?'} @$f )
451 . ") ;" ;
452  
453 0 $self->_debug($query) ;
454 0 $sth = $self->{dbh}->prepare($query) ;
455  
456 # cache the handle for next time
457 0 $sth_map->{$key} = $sth ;
458 }
459 0 my $rv = $sth->execute(@params) ;
460  
461 0 return { row_count => $rv, error => 0 } ;
462 }
463  
464 # -----------------------------------------------------------------------------
465  
466 sub _delete_db_record
467 0 ▶{
Subroutine _delete_db_record: not called CC=1 SCAR=6.9
468 0 my $self = shift ;
469 0 my ( $table, $q, $v ) = @_ ;
470 0 my $query = "DELETE FROM $table $q ;" ;
471  
472 # run the delete and don't fetch results
473 0 my $resp = $self->_query_db( $query, $v, 1 ) ;
474 0 return $resp ;
475 }
476  
477 # -----------------------------------------------------------------------------
478 # as all the indexes are constructued the same, lets have a helper
479 sub _create_index_str
480 0 ▶{
Subroutine _create_index_str: not called CC=1 SCAR=6.9
481 0 my ( $table, $field ) = @_ ;
482  
483 0 return sprintf( "CREATE INDEX %s_%s_idx on %s(%s) ;",
484 $table, $field, $table, $field ) ;
485 }
486  
487 # -----------------------------------------------------------------------------
488 sub _create_sqlite_table
489 0 ▶{
Subroutine _create_sqlite_table: not called CC=1 SCAR=6.9
490 0 my $self = shift ;
491 0 my ($table) = @_ ;
492 0 $self->_debug("Creating SQLite tables") ;
493  
494 # set WAL mode rather than the default DELETE as its faster
495 0 ▶ try { $self->{dbh}->do("PRAGMA journal mode = WAL;") ; } catch { } ;
Subroutine __ANON__: not called CC=1 SCAR=6.9
Subroutine __ANON__: not called CC=1 SCAR=6.9
496  
497 0 my $sql = "CREATE TABLE $table (
498 counter INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
499 id VARCHAR(128) NOT NULL UNIQUE,
500 queue_name VARCHAR(128) NOT NULL,
501 msg_type VARCHAR(8),
502 persist BOOLEAN DEFAULT 0,
503 added TIMESTAMP DEFAULT current_timestamp,
504 activates TIMESTAMP DEFAULT current_timestamp,
505 expires TIMESTAMP,
506 processed BOOLEAN DEFAULT 0,
507 processor VARCHAR(128),
508 process_start TIMESTAMP,
509 processing_time FLOAT,
510 process_failure SMALLINT DEFAULT 0,
511 data TEXT ) ;" ;
512  
513 0 $self->_debug($sql) ;
514 0 ▶ try { $self->{dbh}->do($sql) ; } catch { } ;
Subroutine __ANON__: not called CC=1 SCAR=6.9
Subroutine __ANON__: not called CC=1 SCAR=6.9
515 }
516  
517 # -----------------------------------------------------------------------------
518 sub _create_postgres_table
519 0 ▶{
Subroutine _create_postgres_table: not called CC=1 SCAR=6.9
520 0 my $self = shift ;
521 0 my ($table) = @_ ;
522 0 $self->_debug("Creating PostgreSQL tables") ;
523  
524 # big/serial creates an auto incrementing column in PostgreSQL
525 0 my $sql = "CREATE TABLE $table (
526 counter BIGSERIAL PRIMARY KEY UNIQUE,
527 id VARCHAR(128) NOT NULL UNIQUE,
528 queue_name VARCHAR(128) NOT NULL,
529 msg_type VARCHAR(8),
530 persist BOOLEAN DEFAULT 0,
531 added TIMESTAMP WITH TIME ZONE DEFAULT now(),
532 activates TIMESTAMP WITH TIME ZONE DEFAULT now(),
533 expires TIMESTAMP,
534 processed SMALLINT DEFAULT 0,
535 processor VARCHAR(128),
536 process_start TIMESTAMP,
537 processing_time FLOAT,
538 process_failure SMALLINT DEFAULT 0,
539 data TEXT ) ;" ;
540  
541 0 $self->_debug($sql) ;
542 0 ▶ try { $self->{dbh}->do($sql) ; } catch { } ;
Subroutine __ANON__: not called CC=1 SCAR=6.9
Subroutine __ANON__: not called CC=1 SCAR=6.9
543 }
544  
545 # -----------------------------------------------------------------------------
546 sub _create_mysql_table
547 0 ▶{
Subroutine _create_mysql_table: not called CC=1 SCAR=6.9
548 0 my $self = shift ;
549 0 my ($table) = @_ ;
550 0 $self->_debug("Creating MySQL tables") ;
551  
552 0 my $sql = "CREATE TABLE $table (
553 counter INT NOT NULL PRIMARY KEY AUTO_INCREMENT UNIQUE,
554 id VARCHAR(128) NOT NULL UNIQUE,
555 queue_name VARCHAR(128) NOT NULL,
556 msg_type VARCHAR(8),
557 persist BOOLEAN DEFAULT 0,
558 added TIMESTAMP DEFAULT current_timestamp,
559 activates TIMESTAMP DEFAULT current_timestamp,
560 expires TIMESTAMP,
561 processed SMALLINT DEFAULT 0,
562 processor VARCHAR(128),
563 process_start TIMESTAMP,
564 processing_time FLOAT,
565 process_failure SMALLINT DEFAULT 0,
566 data TEXT ) ;" ;
567  
568 0 $self->_debug($sql) ;
569 0 ▶ try { $self->{dbh}->do($sql) ; } catch { } ;
Subroutine __ANON__: not called CC=1 SCAR=6.9
Subroutine __ANON__: not called CC=1 SCAR=6.9
570 }
571  
572 # -----------------------------------------------------------------------------
573 # create all the tables and indexes
574 sub _create_tables
575 0 ▶{
Subroutine _create_tables: not called CC=5 SCAR=34.0
576 0 my $self = shift ;
577 0 my $sql ;
578 0 my $table = $self->{prefix} . '_queue' ;
579  
580 # as the checking for tables and indexes is fraught with issues
581 # over multiple databases its easier to not print the errors and
582 # catch the creation failures and ignore them!
583 0 my $p = $self->{dbh}->{PrintError} ;
584 0 $self->{dbh}->{PrintError} = 0 ;
585  
586 # I am assuming either table does not exist then nor does the
587 # other and we should create both
588 0 ▶ if ( $self->_db_type() eq 'SQLite' ) {
Branch: 3 branches
BranchTrueFalseTotal
if ($self->_db_type eq 'SQLite') { } 0 0 0
elsif ($self->_db_type eq 'Pg') { } 0 0 0
elsif ($self->_db_type eq 'mysql') { } 0 0 0
589 0 $self->_create_sqlite_table($table) ;
590 } elsif ( $self->_db_type() eq 'Pg' ) {
591 0 $self->_create_postgres_table($table) ;
592 } elsif ( $self->_db_type() eq 'mysql' ) {
593 0 $self->_create_mysql_table($table) ;
594 } else {
595 0 die "Unhandled database type " . $self->_db_type() ;
596 }
597  
598 0 foreach my $field (
599 qw/counter id added activates queue_name msg_type persist expires processed process_failure/
600 ) {
601 0 my $sql = _create_index_str( $table, $field ) ;
602  
603 0 $self->_debug($sql) ;
604 0 ▶ try { $self->{dbh}->do($sql) ; } catch { } ;
Subroutine __ANON__: not called CC=1 SCAR=6.9
Subroutine __ANON__: not called CC=1 SCAR=6.9
605 }
606  
607 # create views
608  
609 # restore the PrintError setting
610 0 $self->{dbh}->{PrintError} = $p ;
611 }
612  
613 # -----------------------------------------------------------------------------
614 # always create the datetime strings the same way
615 sub _std_datetime
616 0 ▶{
Subroutine _std_datetime: not called CC=2 SCAR=17.9
617 0 my ($secs) = @_ ;
618 0 ▶ $secs ||= time() ;
Condition0%0/2
$secs ||= time
l!l
00
MC/DC0%0/1
$secs ||= time
$secs
Truth table0%0/2
A
A= $secs
Aresult
11
00
619 0 return strftime( "%Y-%m-%d %H:%M:%S UTC", gmtime($secs) ) ;
620 }
621  
622 # -----------------------------------------------------------------------------
623 # convert something like a datetime string or an epoch value into a standardised
624 # datetime string and epoch value
625  
626 sub _parse_datetime
627 0 ▶{
Subroutine _parse_datetime: not called CC=6 SCAR=37.4
628 0 my ($datetime) = @_ ;
629 0 state $date = new Date::Manip::Date ;
630 0 my @ret ;
631  
632 0 ▶ if ( !$datetime ) {
Branch: 2 branches
BranchTrueFalseTotal
if (not $datetime) { } 0 0 0
elsif ($datetime =~ /^\d+$/) { } 0 0 0
633 0 ▶ return wantarray ? ( undef, undef ) : undef ;
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 0 0 0
634 } elsif ( $datetime =~ /^\d+$/ ) {
635 # assume anything less than five days is a time into the future
636 0 ▶ $datetime += time() if ( $datetime <= FIVE_DAYS ) ;
Branch: 1 branch
BranchTrueFalseTotal
if $datetime <= 432000 0 0 0
637 0 @ret = ( _std_datetime($datetime), $datetime ) ;
638 } else {
639 # so parse will parse in locale time not as UTC
640 0 $date->parse($datetime) ;
641 {
642 # if we get a warning about converting the date to a day, there
643 # must be a problem with parsing the input date string
644 0 ▶ local $SIG{__WARN__} = sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
645 0 die "Invalid date, could not parse" ;
646 0 } ;
647 0 my $day = $date->printf("%a") ;
648 }
649  
650 0 my $d2 = $date->printf("%O %Z") ;
651 # reparse the date to get it into UTC, best way I could think of :(
652 0 $date->parse($d2) ;
653  
654 # secs_since_1970_GMT is epoch
655 0 @ret = (
656 _std_datetime( $date->secs_since_1970_GMT() ),
657 $date->secs_since_1970_GMT()
658 ) ;
659 }
660  
661 0 ▶ return wantarray ? @ret : $ret[0] ;
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 0 0 0
662 }
663  
664 # -----------------------------------------------------------------------------
665 # _add
666 # Add some data into a named queue. Could be a task or a chatter mesg
667 # * This does not handle wildcard queues *
668  
669 sub _add
670 0 ▶{
Subroutine _add: not called CC=13 SCAR=52.0
671 0 state $uuid = Data::UUID->new() ;
672 0 my $self = shift ;
673 0 ▶ my $params = @_ % 2 ? shift : {@_} ;
Branch: 1 branch
BranchTrueFalseTotal
@_ % 2 ? : 0 0 0
674  
675 0 ▶ if ( ref($params) ne 'HASH' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $params ne "HASH") 0 0 0
676 0 warn "_add accepts a hash or a hashref of parameters" ;
677 0 return 0 ;
678 }
679  
680 0 ▶ $params->{queue} ||= $self->{default_queue} ;
Condition0%0/3
$params->{"queue"} ||= $self->{"default_queue"}
l!l&&r!l&&!r
000
MC/DC0%0/2
$params->{"queue"} ||= $self->{"default_queue"}
$params->{"queue"} $self->{"default_queue"}
Truth table0%0/3
A ||= B
A= $params->{"queue"}B= $self->{"default_queue"}
ABresult
1X1
011
000
681  
682 # to keep what was here before the change to the parameters
683 0 my $qname = $params->{queue} ;
684 0 my $msg_type = $params->{type} ;
685 # only TASK events can activate in the future
686 0 ▶ delete $params->{activates} if ( $msg_type ne MSG_TASK ) ;
Branch: 1 branch
BranchTrueFalseTotal
if $msg_type ne "task" 0 0 0
687 0 my $persist = $params->{persist} ;
688 0 my ( $expires, $when ) = _parse_datetime( $params->{expires} ) ;
689 0 my $activates = _parse_datetime( $params->{activates} ) ;
690 0 ▶ $activates ||= _std_datetime() ;
Condition0%0/3
$activates ||= _std_datetime()
l!l&&r!l&&!r
000
MC/DC0%0/2
$activates ||= _std_datetime()
$activates _std_datetime()
Truth table0%0/3
A ||= B
A= $activatesB= _std_datetime()
ABresult
1X1
011
000
691 0 my $data = $params->{data} ;
692  
693 0 ▶ if ( ref($data) ne 'HASH' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $data ne "HASH") 0 0 0
694 0 warn "_add data parameter must be a hashref" ;
695 0 return 0 ;
696 }
697  
698 0 ▶ if ( $params->{expires} && $when && $when < time() ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($params->{"expires"} and $when and $when < time) 0 0 0
Condition0%0/6
$params->{"expires"} and $when and $when < time
!ll&&!rl&&r
000
$params->{"expires"} and $when
!ll&&!rl&&r
000
MC/DC0%0/3
$params->{"expires"} and $when and $when < time
$params->{"expires"} $when $when < time
Truth table0%0/4
A and B and C
A= $params->{"expires"}B= $whenC= $when < time
ABCresult
0XX0
10X0
1100
1111
699 0 warn "_add not storing expired data" ;
700 0 return 0 ;
701 }
702  
703 0 my $status = 0 ;
704 0 my $resp ;
705 0 ▶ if ( !$qname || !$data ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($qname and $data) 0 0 0
Condition0%0/3
$qname and $data
!ll&&!rl&&r
000
MC/DC0%0/2
$qname and $data
$qname $data
Truth table0%0/3
A and B
A= $qnameB= $data
ABresult
0X0
100
111
706 0 my $err = "Missing queue name or data" ;
707 0 $self->_debug($err) ;
708 0 warn $err ;
709 0 return $status ;
710 }
711 0 ▶ if ( $qname =~ /\*/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($qname =~ /\*/) 0 0 0
712 0 my $err = "Bad queue name, cannot contain '*'" ;
713 0 $self->_debug($err) ;
714 0 warn $err ;
715 0 return $status ;
716 }
717  
718 0 ▶ try {
Subroutine __ANON__: not called CC=3 SCAR=24.8
719 0 my $json_data = encode_json($data) ;
720  
721 # we manage the id's for the queue entries as we cannot depend
722 # on a common SQL method of adding a record and getting its uniq ID back
723  
724 0 ▶ $expires ||= MAX_EXPIRY_DATETIME ;
Condition0%0/2
$expires ||= "3000-01-01 12:00 UTC"
l!l
00
MC/DC0%0/1
$expires ||= "3000-01-01 12:00 UTC"
$expires
Truth table0%0/2
A
A= $expires
Aresult
11
00
725  
726 0 my $message_id = $uuid->create_b64() ;
727 0 my $added = _std_datetime() ;
728 $resp = $self->_insert_db(
729 0 $self->{prefix} . '_queue',
730 [qw(id queue_name added data msg_type persist expires activates)],
731 [ $message_id, $qname, $added, $json_data,
732 $msg_type, $persist, $expires, $activates
733 ]
734 ) ;
735  
736 0 ▶ $status = $message_id if ( !$resp->{error} ) ;
Branch: 1 branch
BranchTrueFalseTotal
if not $resp->{"error"} 0 0 0
737 }
738 0 ▶ catch {
Subroutine __ANON__: not called CC=1 SCAR=6.9
739 0 my $e = $@ ;
740 0 warn $e ;
741 0 } ;
742  
743 0 return $status ;
744 }
745  
746 # -----------------------------------------------------------------------------
747 # get size of a queue, add _qtype parameter as MSG_TASK or MSG_SIMPLE
748 sub _queue_size
749 0 ▶{
Subroutine _queue_size: not called CC=5 SCAR=34.0
750 0 my $self = shift ;
751 0 ▶ my $params = @_ % 2 ? shift : {@_} ;
Branch: 1 branch
BranchTrueFalseTotal
@_ % 2 ? : 0 0 0
752  
753 0 ▶ if ( ref($params) ne 'HASH' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $params ne "HASH") 0 0 0
754 0 warn "queue_size accepts a hash or a hashref of parameters" ;
755 0 return 0 ;
756 }
757 0 ▶ $params->{queue} ||= $self->{default_queue} ;
Condition0%0/3
$params->{"queue"} ||= $self->{"default_queue"}
l!l&&r!l&&!r
000
MC/DC0%0/2
$params->{"queue"} ||= $self->{"default_queue"}
$params->{"queue"} $self->{"default_queue"}
Truth table0%0/3
A ||= B
A= $params->{"queue"}B= $self->{"default_queue"}
ABresult
1X1
011
000
758 0 my $qname = $params->{queue} ;
759  
760 # switch to SQL wildcard
761 0 $qname =~ s/\*/%/g ;
762  
763 my $sql = sprintf(
764 "SELECT count(*) as count FROM %s_queue
765 WHERE queue_name LIKE ?
766 AND msg_type = ?
767 AND expires > ?
768 AND processed = 0
769 AND process_failure = 0
770 ; ", $self->{prefix}
771 0 ) ;
772 # AND process_failure = 0
773 0 my $expires = _parse_datetime( time() ) ;
774 my $resp
775 0 = $self->_query_db( $sql, [ $qname, $params->{_qtype}, $expires ] ) ;
776  
777 0 ▶ return $resp->{row_count} ? $resp->{rows}->[0]->{count} : 0 ;
Branch: 1 branch
BranchTrueFalseTotal
$resp->{'row_count'} ? : 0 0 0
778 }
779  
780 # -----------------------------------------------------------------------------
781  
782 =head2 add
783  
784 Add task data into a named queue. This creates a 'task' that needs to be processed.
785  
786 B<Parameters>
787  
788 Hash of
789  
790 =over
791  
792 =item queue
793  
794 Name of the queue, wildcard B<NOT allowed>
795  
796 =item data
797  
798 Data to store against the queue, can be a scalar, hashref or arrayref
799  
800 =back
801  
802 B<Example usage>
803  
804 my $queue = App::Basis::Queue->new( dbh => $dbh) ;
805  
806 # save some application audit data
807 $queue->add(
808 queue => 'app_start',
809 data => {
810 ip => 12.12.12.12, session_id => 12324324345, client_id => 248296432984,
811 appid => 2, app_name => 'twitter'
812 },
813 ) ;
814  
815 =cut
816  
817 sub add
818 0 ▶{
Subroutine add: not called CC=3 SCAR=24.8
Pod documented
819 0 my $self = shift ;
820 0 ▶ my $params = @_ % 2 ? shift : {@_} ;
Branch: 1 branch
BranchTrueFalseTotal
@_ % 2 ? : 0 0 0
821  
822 0 ▶ if ( ref($params) ne 'HASH' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $params ne "HASH") 0 0 0
823 0 warn "add accepts a hash or a hashref of parameters" ;
824 0 return 0 ;
825 }
826 0 $params->{type} = MSG_TASK ;
827 0 $params->{persist} = 0 ;
828  
829 0 return $self->_add($params) ;
830 }
831  
832 # -----------------------------------------------------------------------------
833  
834 =head2 push
835  
836 Push simple data onto the end of a named queue.
837  
838 B<Parameters>
839  
840 Hash of
841  
842 =over
843  
844 =item queue
845  
846 Name of the queue, wildcard B<NOT allowed>
847  
848 =item data
849  
850 Data to store against the queue, can be a scalar, hashref or arrayref
851  
852 =back
853  
854 B<Example usage>
855  
856 my $queue = App::Basis::Queue->new( dbh => $dbh) ;
857  
858 # save some application audit data
859 $queue->push(
860 queue => 'app_start',
861 data => {
862 ip => 12.12.12.12, session_id => 12324324345, client_id => 248296432984,
863 appid => 2, app_name => 'twitter'
864 },
865 ) ;
866  
867 =cut
868  
869 sub push
870 0 ▶{
Subroutine push: not called CC=3 SCAR=24.8
Pod documented
871 0 my $self = shift ;
872 0 ▶ my $params = @_ % 2 ? shift : {@_} ;
Branch: 1 branch
BranchTrueFalseTotal
@_ % 2 ? : 0 0 0
873  
874 0 ▶ if ( ref($params) ne 'HASH' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $params ne "HASH") 0 0 0
875 0 warn "add accepts a hash or a hashref of parameters" ;
876 0 return 0 ;
877 }
878 0 $params->{type} = MSG_SIMPLE ;
879  
880 0 return $self->_add($params) ;
881 }
882  
883  
884 # -----------------------------------------------------------------------------
885  
886 # pop could possibly be done in a transaction, find the item, mark it as processed
887  
888 # -----------------------------------------------------------------------------
889  
890 =head2 pop
891  
892 Remove the top item from the named queue - the oldest item on the queue
893  
894 B<Parameters>
895  
896 Hash of
897  
898 =over
899  
900 =item queue
901  
902 Name of the queue, wildcards allowed
903  
904 =back
905  
906 B<Returns>
907  
908 The message data only
909  
910 B<Example usage>
911  
912 my $data = $queue->pop( queue => 'queue_name') ;
913  
914 =cut
915  
916 sub pop
917 0 ▶{
Subroutine pop: not called CC=7 SCAR=40.3
Pod documented
918 0 my $self = shift ;
919 0 ▶ my $params = @_ % 2 ? shift : {@_} ;
Branch: 1 branch
BranchTrueFalseTotal
@_ % 2 ? : 0 0 0
920 0 my $popped ;
921  
922 0 ▶ if ( ref($params) ne 'HASH' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $params ne "HASH") 0 0 0
923 0 warn "process accepts a hash or a hashref of parameters" ;
924 0 return 0 ;
925 }
926  
927 0 my $processed_count = 0 ;
928 0 ▶ $params->{queue} ||= $self->{default_queue} ;
Condition0%0/3
$params->{"queue"} ||= $self->{"default_queue"}
l!l&&r!l&&!r
000
MC/DC0%0/2
$params->{"queue"} ||= $self->{"default_queue"}
$params->{"queue"} $self->{"default_queue"}
Truth table0%0/3
A ||= B
A= $params->{"queue"}B= $self->{"default_queue"}
ABresult
1X1
011
000
929 0 my $qname = $params->{queue} ;
930  
931 # if the queue does not exist
932 0 ▶ return 0 if ( !$self->_valid_qname($qname) ) ;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_valid_qname($qname) 0 0 0
933  
934 # switch to SQL wildcard
935 0 $qname =~ s/\*/%/g ;
936  
937 # get list of IDs we can process, as SQLite has an issue
938 # with ORDER BY and LIMIT in an UPDATE call so we have to do things
939 # in 2 stages, which means it is not easy to mark lots of records
940 # to be processed but that its possibly a good thing
941 my $sql = sprintf(
942 "SELECT * FROM %s_queue
943 WHERE queue_name LIKE ?
944 AND processed = 0
945 AND msg_type = ?
946 ORDER BY counter ASC
947 LIMIT 1;", $self->{prefix}
948 0 ) ;
949 0 my $expires = _parse_datetime( time() ) ;
950 0 my $info = $self->_query_db( $sql, [ $qname, MSG_SIMPLE ] ) ;
951  
952 # if there are no items to update, return
953 # return if ( !scalar( $info->{rows} ) ) ;
954 0 ▶ return if ( !$info->{row_count} ) ;
Branch: 1 branch
BranchTrueFalseTotal
unless $info->{"row_count"} 0 0 0
955  
956 0 my $row = $info->{rows}->[0] ;
957 0 my $id = $row->{id} ;
958  
959 # mark item that I have popped
960 0 my $update
961 = "SET processed=1, processor=?, process_start=?, processing_time=?, process_failure=0
962 WHERE id = ? ;" ;
963 0 my $resp = $self->_update_db( $self->{prefix} . "_queue",
964 $update, [ $self->_processor(), _std_datetime(), 0.0, $id ] ) ;
965 0 ▶ if ( !$resp->{row_count} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($resp->{"row_count"}) 0 0 0
966 0 return ;
967 }
968 # return unpacked data
969 0 return decode_json( $row->{data} ) ;
970 }
971  
972 # -----------------------------------------------------------------------------
973  
974 =head2 size
975  
976  
977 Get size of a SIMPLE queue
978  
979 B<Parameters>
980  
981 Hash of
982  
983 =over
984  
985 =item queue
986  
987 Name of the queue, wildcards allowed
988  
989 =back
990  
991 B<Example usage>
992  
993 my $count = $queue->size( queue => 'queue_name') ;
994 say "there are $count items in the queue" ;
995  
996 # size can manage wildcards
997 $queue->size( queue => '/celestial/*') ;
998  
999 =cut
1000  
1001 sub size
1002 0 ▶{
Subroutine size: not called CC=3 SCAR=24.8
Pod documented
1003 0 my $self = shift ;
1004 0 ▶ my $params = @_ % 2 ? shift : {@_} ;
Branch: 1 branch
BranchTrueFalseTotal
@_ % 2 ? : 0 0 0
1005  
1006 0 ▶ if ( ref($params) ne 'HASH' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $params ne "HASH") 0 0 0
1007 0 warn "size accepts a hash or a hashref of parameters" ;
1008 0 return 0 ;
1009 }
1010 0 $params->{_qtype} = MSG_SIMPLE ;
1011 0 return $self->_queue_size($params) ;
1012 }
1013  
1014  
1015 # -----------------------------------------------------------------------------
1016 # try and find a match for the qname, replace SQL wildcard with perl ones
1017  
1018 sub _valid_qname
1019 0 ▶{
Subroutine _valid_qname: not called CC=6 SCAR=37.4
1020 0 my $self = shift ;
1021 0 my ($qname) = @_ ;
1022  
1023 # update queue list
1024 0 $self->list_queues() ;
1025  
1026 0 $qname =~ s/%/*/g ;
1027 0 ▶ my $wild = ( $qname =~ /\*/ ) ? 1 : 0 ;
Branch: 1 branch
BranchTrueFalseTotal
$qname =~ /\*/ ? : 0 0 0
1028  
1029 0 my $match = 0 ;
1030 0 foreach my $q ( keys %{ $self->{_queue_list} } ) {
1031 0 ▶ if ( ( $wild && $q =~ $qname ) || $self->{_queue_list}->{$qname} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($wild and $q =~ /$qname/ or $self->{"_queue_list"}{$qname}) 0 0 0
Condition0%0/6
$wild and $q =~ /$qname/ or $self->{"_queue_list"}{$qname}
l!l&&r!l&&!r
000
$wild and $q =~ /$qname/
!ll&&!rl&&r
000
MC/DC0%0/3
$wild and $q =~ /$qname/ or $self->{"_queue_list"}{$qname}
$wild $q =~ /$qname/ $self->{"_queue_list"}{$qname}
Truth table0%0/5
A and B or C
A= $wildB= $q =~ /$qname/C= $self->{"_queue_list"}{$qname}
ABCresult
11X1
0X11
1011
0X00
1000
1032 0 $match++ ;
1033 0 last ;
1034 }
1035 }
1036  
1037 0 return $match ;
1038 }
1039  
1040 # -----------------------------------------------------------------------------
1041  
1042 =head2 process
1043  
1044 Process up to 100 tasks from the named queue(s)
1045  
1046 B<Parameters>
1047  
1048 Hash of
1049  
1050 =over
1051  
1052 =item queue
1053  
1054 Name of the queue, wildcards allowed
1055  
1056 =item count
1057  
1058 Number of items to process from the queue
1059  
1060 =item callback
1061  
1062 coderef to be called to each queue item, expects queue (object), queue_name and the data of the queue item (record)
1063  
1064 =back
1065  
1066 A reference to the queue object is passed to the callback along with the name of
1067 the queue and the record that is to be procssed.
1068  
1069 If the callback returns a non-zero value then the record will be marked as processed.
1070 If the callback returns a zero value, then the processing is assumed to have failed
1071 and the failure count will be incremented by 1. If the failue count matches our
1072 maximum allowed limit then the item will not be available for any further processing.
1073  
1074 B<Example usage>
1075  
1076 sub processing_callback {
1077 my ( $queue, $qname, $record, $params ) = @_;
1078 # $params = { something => 'data'} ; from the process call
1079  
1080 return 1;
1081 }
1082  
1083 $queue->process(
1084 queue => 'queue_name',
1085 count => 5,
1086 callback => \&processing_callback
1087 ) ;
1088  
1089 qname can contain wildcards and all matching queues will be scanned
1090  
1091 # add things to different queues, but with a common root
1092 $queue->add( queue => '/celestial/stars', data => { list: [ "sun", "alpha centuri"]}) ;
1093 $queue->add( queue => '/celestial/planets', data => { list: [ "earth", "pluto", "mars"]}) ;
1094  
1095 # process all the 'celestial' bodies queues
1096 $queue->process( queue => '/celestial/*', count => 5,
1097 callback => \&processing_callback,
1098 callback_params => { something => 'data'}
1099 ) ;
1100  
1101 =cut
1102  
1103 sub process
1104 0 ▶{
Subroutine process: not called CC=15 SCAR=54.8
Pod documented
1105 0 my $self = shift ;
1106 0 ▶ my $params = @_ % 2 ? shift : {@_} ;
Branch: 1 branch
BranchTrueFalseTotal
@_ % 2 ? : 0 0 0
1107  
1108 0 ▶ if ( ref($params) ne 'HASH' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $params ne "HASH") 0 0 0
1109 0 warn "process accepts a hash or a hashref of parameters" ;
1110 0 return 0 ;
1111 }
1112  
1113 0 my $processed_count = 0 ;
1114 0 ▶ $params->{queue} ||= $self->{default_queue} ;
Condition0%0/3
$params->{"queue"} ||= $self->{"default_queue"}
l!l&&r!l&&!r
000
MC/DC0%0/2
$params->{"queue"} ||= $self->{"default_queue"}
$params->{"queue"} $self->{"default_queue"}
Truth table0%0/3
A ||= B
A= $params->{"queue"}B= $self->{"default_queue"}
ABresult
1X1
011
000
1115 0 my $qname = $params->{queue} ;
1116  
1117 # if the queue does not exist
1118 0 ▶ return 0 if ( !$self->_valid_qname($qname) ) ;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_valid_qname($qname) 0 0 0
1119  
1120 # switch to SQL wildcard
1121 0 $qname =~ s/\*/%/g ;
1122  
1123 0 ▶ $params->{count} ||= 1 ;
Condition0%0/2
$params->{"count"} ||= 1
l!l
00
MC/DC0%0/1
$params->{"count"} ||= 1
$params->{"count"}
Truth table0%0/2
A
A= $params->{"count"}
Aresult
11
00
1124 die __PACKAGE__ . " process requires a callback function"
1125 0 ▶ if ( !$params->{callback} || ref( $params->{callback} ) ne 'CODE' ) ;
Branch: 1 branch
BranchTrueFalseTotal
if not $params->{"callback"} or ref $params->{"callback"} ne "CODE" 0 0 0
Condition0%0/3
not $params->{"callback"} or ref $params->{"callback"} ne "CODE"
l!l&&r!l&&!r
000
MC/DC0%0/2
not $params->{"callback"} or ref $params->{"callback"} ne "CODE"
not $params->{"callback"} ref $params->{"callback"} ne "CODE"
Truth table0%0/3
not(A) or B
A= not $params->{"callback"}B= ref $params->{"callback"} ne "CODE"
ABresult
1X1
011
000
1126  
1127 0 ▶ if ( $params->{count} > MAX_PROCESS_ITEMS ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($params->{"count"} > 100) 0 0 0
1128 0 warn "Reducing process count from $params->{count} to "
1129 . MAX_PROCESS_ITEMS ;
1130 0 $params->{count} = MAX_PROCESS_ITEMS ;
1131 }
1132  
1133 0 my $now = _std_datetime() ;
1134  
1135 # get list of IDs we can process, as SQLite has an issue
1136 # with ORDER BY and LIMIT in an UPDATE call so we have to do things
1137 # in 2 stages, which means it is not easy to mark lots of records
1138 # to be processed but that its possibly a good thing
1139 my $sql = sprintf(
1140 "SELECT id FROM %s_queue
1141 WHERE queue_name LIKE ?
1142 AND processed = 0
1143 AND process_failure = 0
1144 AND msg_type = ?
1145 AND expires > ?
1146 AND activates <= ?
1147 ORDER BY added ASC
1148 LIMIT ?;", $self->{prefix}
1149 0 ) ;
1150 0 my $expires = _parse_datetime( time() ) ;
1151 my $ids = $self->_query_db( $sql,
1152 0 [ $qname, MSG_TASK, $expires, $now, $params->{count} ] ) ;
1153 0 my @t ;
1154 0 foreach my $row ( @{ $ids->{rows} } ) {
1155 0 CORE::push @t, "'$row->{id}'" ;
1156 }
1157  
1158 # if there are no items to update, return
1159 0 ▶ return $processed_count if ( !scalar(@t) ) ;
Branch: 1 branch
BranchTrueFalseTotal
unless scalar @t 0 0 0
1160 0 my $id_list = join( ',', @t ) ;
1161  
1162 # mark items that I am going to process
1163 0 my $update = "SET processor=?
1164 WHERE id IN ( $id_list) AND processed = 0 ;" ;
1165 0 my $resp = $self->_update_db( $self->{prefix} . "_queue",
1166 $update, [ $self->_processor() ] ) ;
1167 0 ▶ return $processed_count if ( !$resp->{row_count} ) ;
Branch: 1 branch
BranchTrueFalseTotal
unless $resp->{"row_count"} 0 0 0
1168  
1169 # refetch the list to find out which ones we are going to process,
1170 # in case another system was doing things at the same time
1171 $sql = sprintf(
1172 "SELECT * FROM %s_queue
1173 WHERE queue_name LIKE ?
1174 AND processed = 0
1175 AND processor = ?
1176 AND process_failure = 0
1177 AND msg_type = ?
1178 AND expires > ?
1179 AND activates <= ?
1180 ORDER BY added ASC
1181 LIMIT ?;", $self->{prefix}
1182 0 ) ;
1183  
1184 my $info = $self->_query_db(
1185 $sql,
1186 [ $qname, $self->_processor(), MSG_TASK, $expires,
1187 $now, $params->{count}
1188 0 ]
1189 ) ;
1190  
1191 0 foreach my $row ( @{ $info->{rows} } ) {
1192  
1193 # unpack the data
1194 0 $row->{data} = decode_json( $row->{data} ) ;
1195 0 my $state = 0 ;
1196 0 my $start = _std_datetime() ;
1197 0 my $st = [gettimeofday] ;
1198 0 my $invalid = 0 ;
1199 0 my $elapsed ;
1200 0 ▶ try {
Subroutine __ANON__: not called CC=1 SCAR=6.9
1201 $state = $params->{callback}
1202 0 ->( $self, $qname, $row, $params->{callback_params} ) ;
1203 }
1204 0 ▶ catch {
Subroutine __ANON__: not called CC=1 SCAR=6.9
1205 0 warn "process: error in callback $@" ;
1206 0 $invalid++ ;
1207 0 } ;
1208 0 $elapsed = tv_interval($st) ;
1209  
1210 0 ▶ if ($invalid) {
Branch: 2 branches
BranchTrueFalseTotal
if ($invalid) { } 0 0 0
elsif ($state) { } 0 0 0
1211  
1212 # if the callback was invalid then we should not mark this
1213 # as a process failure just clear the processor
1214 0 $update = "SET processor=?, WHERE id = ? AND processed = 0 ;" ;
1215 $info = $self->_update_db( $self->{prefix} . "_queue",
1216 0 $update, [ '', $row->{id} ] ) ;
1217 } elsif ($state) {
1218  
1219 # show we have processed it
1220 0 $update
1221 = "SET processed=1, process_start=?, processing_time=? WHERE id = ? AND processed = 0 ;"
1222 ;
1223 $info = $self->_update_db( $self->{prefix} . "_queue",
1224 0 $update, [ $start, $elapsed, $row->{id} ] ) ;
1225 0 $processed_count++ ;
1226 } else {
1227 # mark the failure
1228 0 $update
1229 = "SET process_failure=1, processing_time=? WHERE id = ? AND processed = 0 ;"
1230 ;
1231 $info = $self->_update_db( $self->{prefix} . "_queue",
1232 0 $update, [ $elapsed, $row->{id} ] ) ;
1233 }
1234 }
1235  
1236 0 return $processed_count ;
1237 }
1238  
1239 # -----------------------------------------------------------------------------
1240  
1241 =head2 process_failures, process_deadletters
1242  
1243 Process up to 100 failed tasks from the queue
1244  
1245 B<Parameters>
1246  
1247 Hash of
1248  
1249 =over
1250  
1251 =item queue
1252  
1253 Name of the queue, wildcards allowed
1254  
1255 =item count
1256  
1257 Number of items to process from the queue
1258  
1259 =item callback
1260  
1261 Coderef to be called to each queue item, expects queue (object), queue_name and the data of the queue item (record)
1262  
1263 =back
1264  
1265 a refrence to the queue object is passed to the callback along with the name of the queue
1266 and the record that is to be procssed. As these are failures we are not interested
1267 in an value of the callback function.
1268  
1269 B<Example usage>
1270  
1271 sub processing_failure_callback {
1272 my ( $queue, $qname, $record, $params ) = @_;
1273 # $params = { something => 'data'} ; from the process call
1274  
1275 # items before 2013 were completely wrong so we can delete
1276 if( $record->{added} < '2013-01-01') {
1277 $queue->delete_record( $record) ;
1278 } else {
1279 # failures in 2013 was down to a bad processing function
1280 $queue->reset_record( $record) ;
1281 }
1282 }
1283  
1284 $queue->process(
1285 queue => 'queue_name',
1286 count => 5,
1287 callback => \&processing_failure_callback,
1288 callback_params => { something => 'data'}
1289 ) ;
1290  
1291 # again we can use wildcards here for queue names
1292  
1293 # add things to different queues, but with a common root
1294 $queue->add( queue => '/celestial/stars', data => { list: [ "sun", "alpha centuri"]}) ;
1295 $queue->add( queue => '/celestial/planets', data => { list: [ "moon", "pluto", "mars"]}) ;
1296 # process, obviously 'moon' will fail our planet processing
1297 $queue->process(
1298 queue => 'queue_name',
1299 count => 5,
1300 callback => \&processing_callback,
1301 callback_params => { something => 'data'}
1302  
1303 ) ;
1304  
1305 # process all the 'celestial' bodies queues for failures - probably will just have the moon in it
1306 $queue->process_failures(
1307 queue => '/celestial/*',
1308 count => 5,
1309 callback => \&processing_failure_callback,
1310 callback_params => { something => 'data'}
1311 ) ;
1312  
1313 =cut
1314  
1315 sub process_failures
1316 0 ▶{
Subroutine process_failures: not called CC=13 SCAR=52.0
Pod documented
1317 0 my $self = shift ;
1318 0 ▶ my $params = @_ % 2 ? shift : {@_} ;
Branch: 1 branch
BranchTrueFalseTotal
@_ % 2 ? : 0 0 0
1319  
1320 0 ▶ if ( ref($params) ne 'HASH' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $params ne "HASH") 0 0 0
1321 0 warn "process_failures accepts a hash or a hashref of parameters" ;
1322 0 return 0 ;
1323 }
1324  
1325 0 ▶ $params->{queue} ||= $self->{default_queue} ;
Condition0%0/3
$params->{"queue"} ||= $self->{"default_queue"}
l!l&&r!l&&!r
000
MC/DC0%0/2
$params->{"queue"} ||= $self->{"default_queue"}
$params->{"queue"} $self->{"default_queue"}
Truth table0%0/3
A ||= B
A= $params->{"queue"}B= $self->{"default_queue"}
ABresult
1X1
011
000
1326 0 my $qname = $params->{queue} ;
1327  
1328 0 my $processed_count = 0 ;
1329  
1330 # switch to SQL wildcard
1331 0 $qname =~ s/\*/%/g ;
1332  
1333 0 ▶ return 0 if ( !$self->_valid_qname($qname) ) ;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_valid_qname($qname) 0 0 0
1334  
1335 0 ▶ $params->{count} ||= 1 ;
Condition0%0/2
$params->{"count"} ||= 1
l!l
00
MC/DC0%0/1
$params->{"count"} ||= 1
$params->{"count"}
Truth table0%0/2
A
A= $params->{"count"}
Aresult
11
00
1336 die __PACKAGE__ . " process requires a callback function"
1337 0 ▶ if ( !$params->{callback} || ref( $params->{callback} ) ne 'CODE' ) ;
Branch: 1 branch
BranchTrueFalseTotal
if not $params->{"callback"} or ref $params->{"callback"} ne "CODE" 0 0 0
Condition0%0/3
not $params->{"callback"} or ref $params->{"callback"} ne "CODE"
l!l&&r!l&&!r
000
MC/DC0%0/2
not $params->{"callback"} or ref $params->{"callback"} ne "CODE"
not $params->{"callback"} ref $params->{"callback"} ne "CODE"
Truth table0%0/3
not(A) or B
A= not $params->{"callback"}B= ref $params->{"callback"} ne "CODE"
ABresult
1X1
011
000
1338  
1339 0 ▶ if ( $params->{count} > MAX_PROCESS_ITEMS ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($params->{"count"} > 100) 0 0 0
1340 0 warn "Reducing process_failures count from $params->{count} to"
1341 . MAX_PROCESS_ITEMS ;
1342 0 $params->{count} = MAX_PROCESS_ITEMS ;
1343 }
1344  
1345 0 my $now = _std_datetime() ;
1346 # get list of IDs we can process
1347 my $sql = sprintf(
1348 "SELECT id FROM %s_queue
1349 WHERE queue_name LIKE ?
1350 AND processed = 0
1351 AND process_failure = 1
1352 AND msg_type = ?
1353 AND expires > ?
1354 AND activates <= ?
1355 ORDER BY added ASC
1356 LIMIT ?;", $self->{prefix}
1357 0 ) ;
1358 0 my $expires = _parse_datetime( time() ) ;
1359 0 $expires |= "" ;
1360  
1361 my $ids = $self->_query_db( $sql,
1362 0 [ $qname, MSG_TASK, $expires, $now, $params->{count} ] ) ;
1363 0 my @t ;
1364 0 foreach my $row ( @{ $ids->{rows} } ) {
1365 0 CORE::push @t, "'$row->{id}'" ;
1366 }
1367  
1368 # if there are no items to update, return
1369 0 ▶ return $processed_count if ( !scalar(@t) ) ;
Branch: 1 branch
BranchTrueFalseTotal
unless scalar @t 0 0 0
1370 0 my $id_list = join( ',', @t ) ;
1371  
1372 # mark items that I am going to process
1373 0 my $update = "SET processor=?
1374 WHERE id IN ( $id_list) AND processed = 0 ;" ;
1375 0 my $resp = $self->_update_db( $self->{prefix} . "_queue",
1376 $update, [ $self->_processor() ] ) ;
1377 0 ▶ return $processed_count if ( !$resp->{row_count} ) ;
Branch: 1 branch
BranchTrueFalseTotal
unless $resp->{"row_count"} 0 0 0
1378  
1379 # refetch the list to find out which ones we are going to process,
1380 # in case another system was doing things at the same time
1381 $sql = sprintf(
1382 "SELECT * FROM %s_queue
1383 WHERE queue_name LIKE ?
1384 AND processed = 0
1385 AND processor = ?
1386 AND process_failure = 1
1387 AND msg_type = ?
1388 AND expires > ?
1389 AND activates <= ?
1390 ORDER BY added ASC
1391 LIMIT ?;", $self->{prefix},
1392 0 ) ;
1393 my $info = $self->_query_db( $sql,
1394 0 [ $qname, $self->_processor(), MSG_TASK, $expires, $now, $params->{count} ] ) ;
1395 0 $self->{debug} = 0 ;
1396  
1397 0 foreach my $row ( @{ $info->{rows} } ) {
1398  
1399 # unpack the data
1400 0 $row->{data} = decode_json( $row->{data} ) ;
1401  
1402 0 my $state = 0 ;
1403 0 ▶ try {
Subroutine __ANON__: not called CC=1 SCAR=6.9
1404 $state = $params->{callback}
1405 0 ->( $self, $qname, $row, $params->{callback_params} ) ;
1406 }
1407 0 ▶ catch {
Subroutine __ANON__: not called CC=1 SCAR=6.9
1408 0 warn "process_failures: error in callback $@" ;
1409 0 } ;
1410  
1411 # we don't do anything else with the record, we assume that the callback
1412 # function will have done something like delete it or re-write it
1413 }
1414  
1415 0 return $processed_count ;
1416 }
1417  
1418 0 ▶sub process_deadletters{
Subroutine process_deadletters: not called CC=1 SCAR=6.9
Pod documented
1419 0 my $self = shift ;
1420 0 return $self->process_failures( $self, @_) ;
1421 }
1422  
1423 # -----------------------------------------------------------------------------
1424  
1425 =head2 queue_size
1426  
1427 Get the count of unprocessed TASK items in the queue
1428  
1429 B<Parameters>
1430  
1431 Hash of
1432  
1433 =over
1434  
1435 =item queue
1436  
1437 Name of the queue, wildcards allowed
1438  
1439 =back
1440  
1441 B<Example usage>
1442  
1443 my $count = $queue->queue_size( queue => 'queue_name') ;
1444 say "there are $count unprocessed items in the queue" ;
1445  
1446 # queue size can manage wildcards
1447 $queue->queue_size( queue => '/celestial/*') ;
1448  
1449 =cut
1450  
1451 sub queue_size
1452 0 ▶{
Subroutine queue_size: not called CC=3 SCAR=24.8
Pod documented
1453 0 my $self = shift ;
1454 0 ▶ my $params = @_ % 2 ? shift : {@_} ;
Branch: 1 branch
BranchTrueFalseTotal
@_ % 2 ? : 0 0 0
1455  
1456 0 ▶ if ( ref($params) ne 'HASH' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $params ne "HASH") 0 0 0
1457 0 warn "queue_size accepts a hash or a hashref of parameters" ;
1458 0 return 0 ;
1459 }
1460 0 $params->{_qtype} = MSG_TASK ;
1461 0 return $self->_queue_size($params) ;
1462 }
1463  
1464 # -----------------------------------------------------------------------------
1465  
1466 =head2 list_queues
1467  
1468 Qbtains a list of all the queues used by this database
1469  
1470 B<Example usage>
1471  
1472 my $qlist = $queue->list_queues() ;
1473 foreach my $q (@$qlist) {
1474 say $q ;
1475 }
1476  
1477 =cut
1478  
1479 sub list_queues
1480 0 ▶{
Subroutine list_queues: not called CC=2 SCAR=17.9
Pod documented
1481 0 my $self = shift ;
1482 0 my %ques ;
1483  
1484 my $result = $self->_query_db(
1485 sprintf( 'SELECT DISTINCT queue_name FROM %s_queue;',
1486 $self->{prefix} )
1487 0 ) ;
1488  
1489 0 ▶ if ( !$result->{error} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($result->{"error"}) 0 0 0
1490 0 %ques = map { $_->{queue_name} => 1 } @{ $result->{rows} } ;
1491 }
1492  
1493 0 $self->_set_queue_list( \%ques ) ;
1494  
1495 0 return [ keys %ques ] ;
1496 }
1497  
1498 # -----------------------------------------------------------------------------
1499  
1500 =head2 peek
1501  
1502 Have a look at an unprocessed item in a TASK queue
1503  
1504 B<Parameters>
1505  
1506 Hash of
1507  
1508 =over
1509  
1510 =item queue
1511  
1512 Name of the queue, wildcards allowed
1513  
1514 =item position
1515  
1516 position in the queue you want to peek at (head/start) or (tail/end) - defaults to head
1517  
1518 =item count
1519  
1520 number of items to peek, defaults to 1, max is 100 (PEEK_MAX)
1521  
1522 =back
1523  
1524 B<Returns>
1525  
1526 Hashref with the following fields queue_name added activates expires data
1527  
1528 B<Example usage>
1529  
1530 my $data = $queue->peek( queue => 'queue_name', position => 'head') ;
1531  
1532 =cut
1533  
1534 sub peek
1535 0 ▶{
Subroutine peek: not called CC=15 SCAR=54.8
Pod documented
1536 0 my $self = shift ;
1537 0 ▶ my $params = @_ % 2 ? shift : {@_} ;
Branch: 1 branch
BranchTrueFalseTotal
@_ % 2 ? : 0 0 0
1538 0 my $popped ;
1539  
1540 0 ▶ if ( ref($params) ne 'HASH' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $params ne "HASH") 0 0 0
1541 0 warn "process accepts a hash or a hashref of parameters" ;
1542 0 return 0 ;
1543 }
1544  
1545 0 ▶ $params->{queue} ||= $self->{default_queue} ;
Condition0%0/3
$params->{"queue"} ||= $self->{"default_queue"}
l!l&&r!l&&!r
000
MC/DC0%0/2
$params->{"queue"} ||= $self->{"default_queue"}
$params->{"queue"} $self->{"default_queue"}
Truth table0%0/3
A ||= B
A= $params->{"queue"}B= $self->{"default_queue"}
ABresult
1X1
011
000
1546 0 my $qname = $params->{queue} ;
1547  
1548 # if the queue does not exist
1549 0 ▶ return 0 if ( !$self->_valid_qname($qname) ) ;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_valid_qname($qname) 0 0 0
1550  
1551 # switch to SQL wildcard
1552 0 $qname =~ s/\*/%/g ;
1553  
1554 0 my $direction = 'ASC' ;
1555 0 ▶ $params->{position} ||= 'head' ;
Condition0%0/2
$params->{"position"} ||= "head"
l!l
00
MC/DC0%0/1
$params->{"position"} ||= "head"
$params->{"position"}
Truth table0%0/2
A
A= $params->{"position"}
Aresult
11
00
1556 0 ▶ $params->{count} ||= 1 ;
Condition0%0/2
$params->{"count"} ||= 1
l!l
00
MC/DC0%0/1
$params->{"count"} ||= 1
$params->{"count"}
Truth table0%0/2
A
A= $params->{"count"}
Aresult
11
00
1557 0 ▶ $params->{count} = PEEK_MAX if( $params->{count} > PEEK_MAX) ;
Branch: 1 branch
BranchTrueFalseTotal
if $params->{"count"} > 100 0 0 0
1558  
1559 0 ▶ if ( $params->{position} =~ /(end|tail|last)/i ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($params->{'position'} =~ /(end|tail|last)/i) { } 0 0 0
elsif (not $params->{'position'} =~ /(start|head|first)/i) { } 0 0 0
1560 0 $direction = 'DESC' ;
1561 } elsif ( $params->{position} !~ /(start|head|first)/i ) {
1562 0 warn(
1563 "peek position '$params->{position}' is not valid, defaulting to head"
1564 ) ;
1565 }
1566  
1567 # find some unprocessed items
1568 my $sql = sprintf(
1569 "SELECT * FROM %s_queue
1570 WHERE queue_name LIKE ?
1571 AND processed = 0
1572 AND process_failure = 0
1573 AND msg_type = ?
1574 AND expires > ?
1575 ORDER BY counter $direction
1576 LIMIT ?;", $self->{prefix}
1577 0 ) ;
1578 0 my $expires = _parse_datetime( time() ) ;
1579 my $info
1580 0 = $self->_query_db( $sql, [ $qname, MSG_TASK, $expires, $params->{count} ] ) ;
1581  
1582 # if there are no items found return
1583 # if ( !scalar( $info->{rows} ) ) {
1584 0 ▶ if ( !$info->{row_count} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($info->{"row_count"}) 0 0 0
1585 0 ▶ return wantarray ? () : undef ;
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 0 0 0
1586 }
1587  
1588 0 my @data ;
1589 0 foreach my $row ( @{ $info->{rows} } ) {
1590 0 $row->{data} = decode_json( $row->{data} ) ;
1591 # remove things we do not want to share
1592 0 foreach my $f (
1593 qw(counter id msg_type persist processed processor process_start processing_time process_failure)
1594 ) {
1595 0 delete $row->{$f} ;
1596 }
1597 0 CORE::push @data, $row ;
1598 }
1599  
1600 0 ▶ return wantarray ? @data : $data[0] ;
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 0 0 0
1601 }
1602  
1603 # -----------------------------------------------------------------------------
1604  
1605 =head2 stats
1606  
1607 Obtains stats about the task data in the queue, this may be time/processor intensive
1608 so use with care!
1609  
1610 B<Parameters>
1611  
1612 Hash of
1613  
1614 =over
1615  
1616 =item queue
1617  
1618 Name of the queue, wildcards allowed
1619  
1620 =back
1621  
1622 provides counts of unprocessed, processed, failures
1623 max process_failure, avg process_failure, earliest_added, latest_added,
1624 min_data_size, max_data_size, avg_data_size, total_records
1625 avg_elapsed, max_elapsed, min_elapsed
1626  
1627 B<Example usage>
1628  
1629 my $stats = $queue->stats( queue => 'queue_name') ;
1630 say "processed $stats->{processed}, failures $stats->{failure}, unprocessed $stats->{unprocessed}" ;
1631  
1632 # for all matching wildcard queues
1633 my $all_stats = $queue->stats( queue => '/celestial/*') ;
1634  
1635 =cut
1636  
1637 sub stats
1638 0 ▶{
Subroutine stats: not called CC=20 SCAR=60.4
Pod documented
1639 0 my $self = shift ;
1640 0 ▶ my $params = @_ % 2 ? shift : {@_} ;
Branch: 1 branch
BranchTrueFalseTotal
@_ % 2 ? : 0 0 0
1641 0 my $expires = _parse_datetime( time() ) ;
1642  
1643 0 ▶ if ( ref($params) ne 'HASH' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $params ne "HASH") 0 0 0
1644 0 warn "stats accepts a hash or a hashref of parameters" ;
1645 0 return {} ;
1646 }
1647 0 ▶ $params->{queue} ||= $self->{default_queue} ;
Condition0%0/3
$params->{"queue"} ||= $self->{"default_queue"}
l!l&&r!l&&!r
000
MC/DC0%0/2
$params->{"queue"} ||= $self->{"default_queue"}
$params->{"queue"} $self->{"default_queue"}
Truth table0%0/3
A ||= B
A= $params->{"queue"}B= $self->{"default_queue"}
ABresult
1X1
011
000
1648 0 my $qname = $params->{queue} ;
1649 0 my %all_stats = () ;
1650  
1651 # update queue list
1652 0 $self->list_queues() ;
1653  
1654 # switch to SQL wildcard
1655 0 $qname =~ s/%/*/g ;
1656  
1657 # work through all the queues and only count that match our qname
1658 0 foreach my $q ( keys %{ $self->{_queue_list} } ) {
1659 0 ▶ next if ( !$self->_valid_qname($q) ) ;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_valid_qname($q) 0 0 0
1660 0 ▶ next if ( ( $qname =~ /\*/ && $qname !~ $q ) || $qname ne $q ) ;
Branch: 1 branch
BranchTrueFalseTotal
if $qname =~ /\*/ and not $qname =~ /$q/ or $qname ne $q 0 0 0
Condition0%0/6
$qname =~ /\*/ and not $qname =~ /$q/ or $qname ne $q
l!l&&r!l&&!r
000
$qname =~ /\*/ and not $qname =~ /$q/
!ll&&!rl&&r
000
MC/DC0%0/3
$qname =~ /\*/ and not $qname =~ /$q/ or $qname ne $q
$qname =~ /\*/ not $qname =~ /$q/ $qname ne $q
Truth table0%0/5
A and not(B) or C
A= $qname =~ /\*/B= not $qname =~ /$q/C= $qname ne $q
ABCresult
11X1
0X11
1011
0X00
1000
1661  
1662 # queue_size also calls list_queues, so we don't need to do it!
1663 0 $all_stats{unprocessed} += $self->queue_size( queue => $q ) ;
1664  
1665 my $sql = sprintf(
1666 "SELECT count(*) as count
1667 FROM %s_queue
1668 WHERE queue_name = ?
1669 AND msg_type = ?
1670 AND expires > ?
1671 AND processed = 1 ;", $self->{prefix}
1672 0 ) ;
1673 0 my $resp = $self->_query_db( $sql, [ $q, MSG_TASK, $expires ] ) ;
1674 0 ▶ $all_stats{processed} += $resp->{rows}->[0]->{count} || 0 ;
Condition0%0/2
$resp->{'rows'}[0]{'count'} || 0
l!l
00
MC/DC0%0/1
$resp->{'rows'}[0]{'count'} || 0
$resp->{'rows'}[0]{'count'}
Truth table0%0/2
A
A= $resp->{'rows'}[0]{'count'}
Aresult
11
00
1675  
1676 $sql = sprintf(
1677 "SELECT count(*) as count FROM %s_queue
1678 WHERE queue_name = ?
1679 AND processed = 0
1680 AND msg_type = ?
1681 AND expires > ?
1682 AND process_failure = 1 ;", $self->{prefix}
1683 0 ) ;
1684 0 $resp = $self->_query_db( $sql, [ $q, MSG_TASK, $expires ] ) ;
1685 0 ▶ $all_stats{failures} += $resp->{rows}->[0]->{count} || 0 ;
Condition0%0/2
$resp->{'rows'}[0]{'count'} || 0
l!l
00
MC/DC0%0/1
$resp->{'rows'}[0]{'count'} || 0
$resp->{'rows'}[0]{'count'}
Truth table0%0/2
A
A= $resp->{'rows'}[0]{'count'}
Aresult
11
00
1686 }
1687  
1688 # get all the stats for all matching queues
1689 my $sql = sprintf(
1690 "SELECT
1691 min(process_failure) as min_process_failure,
1692 max(process_failure) as max_process_failure,
1693 avg(process_failure) as avg_process_failure,
1694 min(added) as earliest_added,
1695 max(added) as latest_added,
1696 min( length(data)) as min_data_size,
1697 max( length(data)) as max_data_size,
1698 avg( length(data)) as avg_data_size,
1699 min( processing_time) as min_elapsed,
1700 max( processing_time) as max_elapsed,
1701 avg( processing_time) as avg_elapsed
1702 FROM %s_queue
1703 WHERE queue_name LIKE ?
1704 AND msg_type = ?
1705 AND expires > ?
1706 ;", $self->{prefix}
1707 0 ) ;
1708 0 my $resp = $self->_query_db( $sql, [ $qname, MSG_TASK, $expires ] ) ;
1709  
1710 0 foreach my $k ( keys %{ $resp->{rows}->[0] } ) {
1711 0 ▶ if ( $k =~ /_added/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($k =~ /_added/) { } 0 0 0
1712  
1713 } else {
1714 0 ▶ $all_stats{$k} += $resp->{rows}->[0]->{$k} || "0" ;
Condition0%0/2
$resp->{'rows'}[0]{$k} || '0'
l!l
00
MC/DC0%0/1
$resp->{'rows'}[0]{$k} || '0'
$resp->{'rows'}[0]{$k}
Truth table0%0/2
A
A= $resp->{'rows'}[0]{$k}
Aresult
11
00
1715 }
1716 }
1717  
1718 # number of records in the table
1719 $all_stats{total_records}
1720 = ( $all_stats{processed} // 0 )
1721 + ( $all_stats{unprocessed} // 0 )
1722 0 ▶ + ( $all_stats{failures} // 0 ) ;
Condition0%0/6
$all_stats{"processed"} // 0
l!l
00
$all_stats{"unprocessed"} // 0
l!l
00
$all_stats{"failures"} // 0
l!l
00
MC/DC0%0/1
$all_stats{"processed"} // 0
$all_stats{"processed"}
MC/DC0%0/1
$all_stats{"unprocessed"} // 0
$all_stats{"unprocessed"}
MC/DC0%0/1
$all_stats{"failures"} // 0
$all_stats{"failures"}
Truth table0%0/2
A
A= $all_stats{"processed"}
Aresult
11
00
Truth table0%0/2
A
A= $all_stats{"unprocessed"}
Aresult
11
00
Truth table0%0/2
A
A= $all_stats{"failures"}
Aresult
11
00
1723 0 ▶ $all_stats{total_records} ||= '0' ;
Condition0%0/2
$all_stats{"total_records"} ||= 0
l!l
00
MC/DC0%0/1
$all_stats{"total_records"} ||= 0
$all_stats{"total_records"}
Truth table0%0/2
A
A= $all_stats{"total_records"}
Aresult
11
00
1724  
1725 # make sure these things have a zero value so calculations don't fail
1726 0 foreach my $f (
1727 qw( unprocessed processed failures
1728 max process_failure avg earliest_added latest_added
1729 min_data_size max_data_size avg_data_size total_records
1730 total_records min_proc max_proc avg_proc)
1731 ) {
1732 0 ▶ $all_stats{$f} ||= '0' ;
Condition0%0/2
$all_stats{$f} ||= 0
l!l
00
MC/DC0%0/1
$all_stats{$f} ||= 0
$all_stats{$f}
Truth table0%0/2
A
A= $all_stats{$f}
Aresult
11
00
1733 }
1734 # $all_stats{dead_letters} = $all_stats{process_failure} ;
1735  
1736 0 return \%all_stats ;
1737 }
1738  
1739 # -----------------------------------------------------------------------------
1740  
1741 =head2 delete_record
1742  
1743 Delete a single task record from the queue
1744  
1745 B<Parameters>
1746  
1747 =over
1748  
1749 =item record
1750  
1751 Hashref to a record fetched with process or process_failures/deadletters
1752  
1753 =back
1754  
1755 Requires a data record which contains infomation we will use to determine the record
1756  
1757 May be used in processing callback functions
1758  
1759 B<Example usage>
1760  
1761 sub processing_callback {
1762 my ( $queue, $qname, $record, $params ) = @_;
1763  
1764 # lets remove records before 2013
1765 if( $record->{added) < '2013-01-01') {
1766 $queue->delete_record( $record) ;
1767 }
1768 return 1 ;
1769 }
1770  
1771 =cut
1772  
1773 sub delete_record
1774 0 ▶{
Subroutine delete_record: not called CC=1 SCAR=6.9
Pod documented
1775 0 my $self = shift ;
1776 0 my ($data) = @_ ;
1777  
1778 0 my $sql = "WHERE id = ?
1779 AND queue_name = ?
1780 AND msg_type = ?" ;
1781 my $resp = $self->_delete_db_record( $self->{prefix} . "_queue",
1782 0 $sql, [ $data->{id}, $data->{queue_name}, MSG_TASK ] ) ;
1783  
1784 0 return $resp->{row_count} ;
1785 }
1786  
1787 # -----------------------------------------------------------------------------
1788  
1789 =head2 reset_record
1790  
1791 Clear the failure flag from a failed task record
1792  
1793 B<Parameters>
1794  
1795 =over
1796  
1797 =item record
1798  
1799 Hashref of data fetched with process or process_failure/deadletters
1800  
1801 =back
1802  
1803 Requires a data record which contains infomation we will use to determine the record
1804  
1805 may be used in processing callback functions
1806  
1807 B<Example usage>
1808  
1809 sub processing_callback {
1810 my ( $queue, $qname, $record, $params ) = @_;
1811  
1812 # allow partially failed (and failed) records to be processed
1813 if( $record->{process_failure) {
1814 $queue->reset_record( $record) ;
1815 }
1816 return 1 ;
1817 }
1818  
1819 =cut
1820  
1821 sub reset_record
1822 0 ▶{
Subroutine reset_record: not called CC=1 SCAR=6.9
Pod documented
1823 0 my $self = shift ;
1824 0 my ($data) = @_ ;
1825  
1826 0 my $sql = "SET process_failure=0
1827 WHERE id = ?
1828 AND queue_name = ?
1829 AND processed=0
1830 AND process_failure > 0
1831 AND msg_type = ?" ;
1832 my $resp = $self->_update_db( $self->{prefix} . "_queue",
1833 0 $sql, [ $data->{id}, $data->{queue_name}, MSG_TASK ] ) ;
1834  
1835 0 return $resp->{row_count} ;
1836 }
1837  
1838 # -----------------------------------------------------------------------------
1839  
1840 =head2 publish
1841  
1842 Publish some chatter data into a named queue.
1843  
1844 B<Parameters>
1845  
1846 Hash of
1847  
1848 =over
1849  
1850 =item queue
1851  
1852 Name of the queue to publish to, wildcards B<NOT allowed>
1853  
1854 =item data
1855  
1856 Hashref of the data to be published
1857  
1858 =item persist (optional)
1859  
1860 Flag to show that this data data should be persisited (0 or 1).
1861 This will become the only persistent record available until either it is replaced or expires.
1862  
1863 =item expires (optional)
1864  
1865 Time after which this data should be ignored. Accepts unix epoch time or parsable datetime string
1866  
1867 =back
1868  
1869 B<Example usage>
1870  
1871 my $queue = App::Basis::Queue->new( dbh => $dbh) ;
1872  
1873 # keep track of a bit of info
1874 $queue->publish( queue => 'app_log',
1875 data => {
1876 ip => 12.12.12.12, session_id => 12324324345, client_id => 248296432984,
1877 appid => 2, app_name => 'twitter'
1878 }
1879 ) ;
1880  
1881 =cut
1882  
1883 sub publish
1884 0 ▶{
Subroutine publish: not called CC=3 SCAR=24.8
Pod documented
1885 0 my $self = shift ;
1886 0 ▶ my $params = @_ % 2 ? shift : {@_} ;
Branch: 1 branch
BranchTrueFalseTotal
@_ % 2 ? : 0 0 0
1887  
1888 0 ▶ if ( ref($params) ne 'HASH' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $params ne "HASH") 0 0 0
1889 0 warn "publish accepts a hash or a hashref of parameters" ;
1890 0 return 0 ;
1891 }
1892 0 $params->{type} = MSG_CHATTER ;
1893  
1894 # make sure this is a zero or one value
1895 0 $params->{persist} = defined $params->{persist} ;
1896  
1897 0 return $self->_add($params) ;
1898 }
1899  
1900 # -----------------------------------------------------------------------------
1901 # find the most recent persistent item
1902 # queue is the only parameter, returns arrayref of items
1903  
1904 sub _recent_persist
1905 0 ▶{
Subroutine _recent_persist: not called CC=5 SCAR=34.0
1906 0 my $self = shift ;
1907 0 ▶ my $params = @_ % 2 ? shift : {@_} ;
Branch: 1 branch
BranchTrueFalseTotal
@_ % 2 ? : 0 0 0
1908  
1909 0 ▶ if ( ref($params) ne 'HASH' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $params ne "HASH") 0 0 0
1910 0 warn "_recent_persist accepts a hash or a hashref of parameters" ;
1911 0 return [] ;
1912 }
1913 0 my $qname = $params->{queue} ;
1914 0 my @data ;
1915  
1916 # if the queue does not exist
1917 0 ▶ return [] if ( !$self->_valid_qname($qname) ) ;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_valid_qname($qname) 0 0 0
1918  
1919 # switch to SQL wildcard
1920 0 $qname =~ s/\*/%/g ;
1921  
1922 # find the most recent persistent items for each matching queue
1923 my $sql = sprintf(
1924 "SELECT * FROM %s_queue a
1925 WHERE a.queue_name LIKE ?
1926 AND a.msg_type = ?
1927 AND a.persist = ?
1928 AND a.counter NOT IN ( SELECT counter from %s_queue b
1929 WHERE b.queue_name = a.queue_name
1930 AND b.msg_type = a.msg_type
1931 AND b.persist = a.persist
1932 AND b.added > a.added
1933 )
1934 AND a.expires > ?
1935 GROUP BY queue_name
1936 ORDER BY queue_name;", $self->{prefix}, $self->{prefix}
1937 0 ) ;
1938  
1939 # there should only be one persist item
1940 0 my $expires = _parse_datetime( time() ) ;
1941  
1942 0 my $result
1943 = $self->_query_db( $sql, [ $qname, MSG_CHATTER, 1, $expires ] ) ;
1944  
1945 0 foreach my $row ( @{ $result->{rows} } ) {
1946 0 $row->{data} = decode_json( $row->{data} ) ; # unpack the data
1947 0 CORE::push @data, $row ;
1948 }
1949  
1950 0 return \@data ;
1951 }
1952  
1953 # -----------------------------------------------------------------------------
1954 # get chatter data (ordered by datetime added) after a unix time
1955 # queue is the only parameter,
1956 # returns arrayref of items
1957  
1958 sub _recent_chatter
1959 0 ▶{
Subroutine _recent_chatter: not called CC=7 SCAR=40.3
1960 0 my $self = shift ;
1961 0 ▶ my $params = @_ % 2 ? shift : {@_} ;
Branch: 1 branch
BranchTrueFalseTotal
@_ % 2 ? : 0 0 0
1962  
1963 0 ▶ if ( ref($params) ne 'HASH' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $params ne "HASH") 0 0 0
1964 0 warn "_recent_chatter accepts a hash or a hashref of parameters" ;
1965 0 return [] ;
1966 }
1967  
1968 0 my $qname = $params->{queue} ;
1969 0 my @data ;
1970  
1971 # if the queue does not exist
1972 0 ▶ return [] if ( !$self->_valid_qname($qname) ) ;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_valid_qname($qname) 0 0 0
1973  
1974 # switch to SQL wildcard
1975 0 $qname =~ s/\*/%/g ;
1976  
1977 0 my $result ;
1978 my $sql ;
1979  
1980 0 ▶ if ( $params->{counter} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($params->{'counter'}) { } 0 0 0
1981 $sql = sprintf(
1982 "SELECT * FROM %s_queue
1983 WHERE queue_name LIKE ?
1984 AND msg_type = ?
1985 AND counter > ?
1986 AND expires > ?
1987 GROUP BY queue_name
1988 ORDER BY counter;", $self->{prefix}
1989 0 ) ;
1990  
1991 0 my $expires = _parse_datetime( time() ) ;
1992 0 $expires |= "" ;
1993  
1994 $result = $self->_query_db( $sql,
1995 0 [ $qname, MSG_CHATTER, $params->{counter}, $expires ] ) ;
1996  
1997 } else {
1998 # check by date
1999 $sql = sprintf(
2000 "SELECT * FROM %s_queue
2001 WHERE queue_name LIKE ?
2002 AND msg_type = ?
2003 AND added >= ?
2004 AND expires > ?
2005 ORDER BY counter;", $self->{prefix}
2006 0 ) ;
2007  
2008 0 my $expires = _parse_datetime( time() ) ;
2009 $result = $self->_query_db( $sql,
2010 0 ▶ [ $qname, MSG_CHATTER, $params->{after} // 0, $expires ] ) ;
Condition0%0/2
$params->{"after"} // 0
l!l
00
MC/DC0%0/1
$params->{"after"} // 0
$params->{"after"}
Truth table0%0/2
A
A= $params->{"after"}
Aresult
11
00
2011 }
2012  
2013 0 foreach my $row ( @{ $result->{rows} } ) {
2014 0 $row->{data} = decode_json( $row->{data} ) ; # unpack the data
2015 0 CORE::push @data, $row ;
2016 }
2017  
2018 0 return \@data ;
2019 }
2020  
2021 # -----------------------------------------------------------------------------
2022  
2023 =head2 subscribe
2024  
2025 Subscribe to a named queue with a callback.
2026  
2027 B<Parameters>
2028  
2029 Hash of
2030  
2031 =over
2032  
2033 =item queue
2034  
2035 Name of the queue, wildcard allowed
2036  
2037 =item callback
2038  
2039 Coderef to handle any matched events
2040  
2041 =item after (optional)
2042  
2043 Unix time after which to listen for events, defaults to now, if set will skip persistent item checks
2044  
2045 =item persist (optional)
2046  
2047 Include the most recent persistent item, if using a wild card, this will match all the queues and could find multiple persistent items
2048  
2049 =back
2050  
2051 B<Example usage>
2052  
2053 my $queue = App::Basis::Queue->new( dbh => $dbh) ;
2054  
2055 # keep track of a bit of info
2056 $queue->subscribe( queue => 'app_logs/*', callback => \&handler) ;
2057 $queue->listen() ;
2058  
2059 =cut
2060  
2061 sub subscribe
2062 0 ▶{
Subroutine subscribe: not called CC=10 SCAR=47.0
Pod documented
2063 0 my $self = shift ;
2064 0 ▶ my $params = @_ % 2 ? shift : {@_} ;
Branch: 1 branch
BranchTrueFalseTotal
@_ % 2 ? : 0 0 0
2065  
2066 0 ▶ if ( ref($params) ne 'HASH' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $params ne "HASH") 0 0 0
2067 0 warn "subscribe accepts a hash or a hashref of parameters" ;
2068 0 return 0 ;
2069 }
2070  
2071 0 ▶ $params->{queue} ||= $self->{default_queue} ;
Condition0%0/3
$params->{"queue"} ||= $self->{"default_queue"}
l!l&&r!l&&!r
000
MC/DC0%0/2
$params->{"queue"} ||= $self->{"default_queue"}
$params->{"queue"} $self->{"default_queue"}
Truth table0%0/3
A ||= B
A= $params->{"queue"}B= $self->{"default_queue"}
ABresult
1X1
011
000
2072 0 ▶ if ( !$params->{queue} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($params->{"queue"}) 0 0 0
2073 0 warn "subscribe needs a queue name to listen to" ;
2074 0 return 0 ;
2075 }
2076  
2077 0 ▶ if ( ref( $params->{callback} ) ne 'CODE' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $params->{"callback"} ne "CODE") 0 0 0
2078 0 warn "subscribe needs a callback handler to send events to" ;
2079 0 return 0 ;
2080 }
2081  
2082 # add to our current subscriptions
2083  
2084 0 ▶ if ( $params->{after} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($params->{"after"}) 0 0 0
2085  
2086 # we cannot get recent persist item if they want to check after a date
2087 0 $params->{persist} = 0 ;
2088 }
2089  
2090 0 ▶ if ( !defined $params->{after} ) {
Branch: 3 branches
BranchTrueFalseTotal
if (not defined $params->{'after'}) { } 0 0 0
elsif ($params->{'after'} =~ /^\d+$/) { } 0 0 0
elsif (not $params->{'after'} =~ /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/) { } 0 0 0
2091 0 $params->{after} = _std_datetime() ;
2092 } elsif ( $params->{after} =~ /^\d+$/ ) {
2093 0 $params->{after} = _std_datetime( gmtime( $params->{after} ) ) ;
2094 } elsif ( $params->{after} !~ /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/ ) {
2095 0 warn(
2096 "this does not look like a datetime value I can use: '$params->{after}'"
2097 ) ;
2098 0 $params->{after} = _std_datetime() ;
2099 }
2100  
2101 $self->{subscriptions}->{ $params->{queue} } = {
2102 callback => $params->{callback},
2103  
2104 # when do we want events from
2105 after => $params->{after},
2106 persist => $params->{persist},
2107 0 ev_count => 0,
2108 counter => 0
2109 } ;
2110 }
2111  
2112 # -----------------------------------------------------------------------------
2113  
2114 =head2 listen
2115  
2116 Listen to all subcribed channels. Loops forever unless told to stop.
2117 If there is a persistent message in a queue, this will be passed to the callback before the other records.
2118  
2119 B<Parameters>
2120  
2121 Hash of
2122  
2123 =over
2124  
2125 =item events (optional)
2126  
2127 Minimum number of events to listen for, stop after this many, may stop after more - this is across ALL the subscriptions
2128  
2129 =item datetime (optional)
2130  
2131 Unix epoch time or parsable datetime when to stop listening
2132  
2133 =item persist (optional)
2134  
2135 Include the most recent persistent item, if subscribed using using a wild card,
2136 this will match all the queues and could find multiple persistent items
2137  
2138 =item listen_delay (optional)
2139  
2140 Override the class delay, obtain events at this rate
2141  
2142 =back
2143  
2144 B<returns>
2145  
2146 Number of chatter events actually passed to ALL the handlers
2147  
2148 B<Example usage>
2149  
2150 my $queue = App::Basis::Queue->new( dbh => $dbh) ;
2151 $queue->subscribe( '/logs/*', \&handler) ;
2152 $queue->listen() ; # listening forever
2153  
2154 # or listen until christmas, checking every 30s
2155 $queue->subscribe( '/presents/*', \&handler) ;
2156 $queue->listen( datetime => '2015-12-25', listen_delay => 30) ;
2157  
2158 =cut
2159  
2160 sub listen
2161 0 ▶{
Subroutine listen: not called CC=17 SCAR=57.2
Pod documented
2162 0 my $self = shift ;
2163 0 ▶ my $params = @_ % 2 ? shift : {@_} ;
Branch: 1 branch
BranchTrueFalseTotal
@_ % 2 ? : 0 0 0
2164 # decide where the delay comes from
2165 0 ▶ my $delay = $params->{listen_delay} || $self->{listen_delay} ;
Condition0%0/3
$params->{'listen_delay'} || $self->{'listen_delay'}
l!l&&r!l&&!r
000
MC/DC0%0/2
$params->{'listen_delay'} || $self->{'listen_delay'}
$params->{'listen_delay'} $self->{'listen_delay'}
Truth table0%0/3
A || B
A= $params->{'listen_delay'}B= $self->{'listen_delay'}
ABresult
1X1
011
000
2166  
2167 0 ▶ if ( ref($params) ne 'HASH' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $params ne "HASH") 0 0 0
2168 0 warn "listen accepts a hash or a hashref of parameters" ;
2169 0 return 0 ;
2170 }
2171  
2172 0 ▶ if ( $params->{datetime} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($params->{"datetime"}) 0 0 0
2173 0 my (@dt) = _parse_datetime( $params->{datetime} ) ;
2174 0 ▶ if ( $dt[1] ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($dt[1]) 0 0 0
2175 # used to check against time() later
2176 0 $params->{datetime} = $dt[1] ;
2177 }
2178 }
2179  
2180 0 ▶ if ( !keys %{ $self->{subscriptions} } ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (keys %{$$self{"subscriptions"};}) 0 0 0
2181 0 warn "you have not subscribed to any queues" ;
2182 0 return 0 ;
2183 }
2184  
2185 0 $self->{ev_count} = 0 ;
2186  
2187 # clean things up before we listen
2188 0 foreach my $qmatch ( sort keys %{ $self->{subscriptions} } ) {
2189 0 my $subs = $self->{subscriptions}->{$qmatch} ;
2190 0 $subs->{counter} = 0 ;
2191 0 $subs->{ev_count} = 0 ;
2192 }
2193  
2194 # loop forever unless there is a reason to stop
2195 0 my $started = 0 ;
2196 0 while (1) {
2197  
2198 0 foreach my $qmatch ( sort keys %{ $self->{subscriptions} } ) {
2199 0 my $subs = $self->{subscriptions}->{$qmatch} ;
2200  
2201 # we may not want the most recent persistent record
2202 0 ▶ next if ( !$started && !$subs->{persist} ) ;
Branch: 1 branch
BranchTrueFalseTotal
unless $started or $subs->{"persist"} 0 0 0
Condition0%0/3
$started or $subs->{"persist"}
l!l&&r!l&&!r
000
MC/DC0%0/2
$started or $subs->{"persist"}
$started $subs->{"persist"}
Truth table0%0/3
A or B
A= $startedB= $subs->{"persist"}
ABresult
1X1
011
000
2203  
2204 0 my $items ;
2205 0 ▶ if ( !$started ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $started) { } 0 0 0
2206 0 $items = $self->_recent_persist( queue => $qmatch ) ;
2207 } else {
2208 $items = $self->_recent_chatter(
2209 queue => $qmatch,
2210 after => $subs->{after},
2211 counter => $subs->{counter},
2212 0 ) ;
2213 }
2214  
2215 0 my $state ;
2216 0 foreach my $row ( @{$items} ) {
2217  
2218 0 $subs->{ev_count}++ ; # count matches for this queue
2219 0 $self->{ev_count}++ ; # and overall
2220 0 ▶ try {
Subroutine __ANON__: not called CC=3 SCAR=24.8
2221 # qmatch is the name of the queue matcher
2222 $state = $subs->{callback}
2223 0 ->( $self, $row->{queue_name}, $row ) ;
2224 0 ▶ if ( $row->{added} gt $subs->{after} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($row->{"added"} gt $subs->{"after"}) 0 0 0
2225 0 $subs->{after} = $row->{added} ;
2226 }
2227 0 ▶ if ( $row->{counter} > $subs->{counter} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($row->{"counter"} > $subs->{"counter"}) 0 0 0
2228 0 $subs->{counter} = $row->{counter} ;
2229 }
2230 }
2231 0 ▶ catch {
Subroutine __ANON__: not called CC=1 SCAR=6.9
2232 0 warn "listen: error in callback $@" ;
2233 0 } ;
2234 }
2235 }
2236 0 $started = 1 ;
2237 last
2238 if ( $params->{events}
2239 0 ▶ && $self->{ev_count} > $params->{events} ) ;
Branch: 1 branch
BranchTrueFalseTotal
if $params->{"events"} and $self->{"ev_count"} > $params->{"events"} 0 0 0
Condition0%0/3
$params->{"events"} and $self->{"ev_count"} > $params->{"events"}
!ll&&!rl&&r
000
MC/DC0%0/2
$params->{"events"} and $self->{"ev_count"} > $params->{"events"}
$params->{"events"} $self->{"ev_count"} > $params->{"events"}
Truth table0%0/3
A and B
A= $params->{"events"}B= $self->{"ev_count"} > $params->{"events"}
ABresult
0X0
100
111
2240 last
2241 if ( $params->{datetime}
2242 0 ▶ && time() > $params->{datetime} ) ;
Branch: 1 branch
BranchTrueFalseTotal
if $params->{"datetime"} and time > $params->{"datetime"} 0 0 0
Condition0%0/3
$params->{"datetime"} and time > $params->{"datetime"}
!ll&&!rl&&r
000
MC/DC0%0/2
$params->{"datetime"} and time > $params->{"datetime"}
$params->{"datetime"} time > $params->{"datetime"}
Truth table0%0/3
A and B
A= $params->{"datetime"}B= time > $params->{"datetime"}
ABresult
0X0
100
111
2243  
2244 # wait a bit to allow the queues to fillup
2245 0 sleep($delay) ;
2246 }
2247  
2248 0 return $self->{ev_count} ;
2249 }
2250  
2251 # -----------------------------------------------------------------------------
2252  
2253 =head2 unsubscribe
2254  
2255 Unsubscribe from a named queue.
2256  
2257 B<Parameters>
2258  
2259 Hash of
2260  
2261 =over
2262  
2263 =item queue
2264  
2265 Name of the queue, wildcard allowed
2266  
2267 =back
2268  
2269 B<Example usage>
2270  
2271 sub handler {
2272 state $counter = 0 ;
2273 my $q = shift ; # we get the queue object
2274 # the queue trigger that matched, the actual queue name and the data
2275 my ($qmatch, $queue, $data) = @_ ;
2276  
2277 # we are only interested in 10 messages
2278 if( ++$counter > 10) {
2279 $q->unsubscribe( queue => $queue) ;
2280 } else {
2281 say Data::Dumper( $data) ;
2282 }
2283 }
2284  
2285 my $queue = App::Basis::Queue->new( dbh => $dbh) ;
2286 $queue->subscribe( queue => '/logs/*', callback => \&handler) ;
2287 $queue->listen() ;
2288  
2289 =cut
2290  
2291 sub unsubscribe
2292 0 ▶{
Subroutine unsubscribe: not called CC=5 SCAR=34.0
Pod documented
2293 0 my $self = shift ;
2294 0 ▶ my $params = @_ % 2 ? shift : {@_} ;
Branch: 1 branch
BranchTrueFalseTotal
@_ % 2 ? : 0 0 0
2295  
2296 0 ▶ if ( ref($params) ne 'HASH' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $params ne "HASH") 0 0 0
2297 0 warn "unsubscribe accepts a hash or a hashref of parameters" ;
2298 0 return 0 ;
2299 }
2300  
2301 0 ▶ $params->{queue} ||= $self->{default_queue} ;
Condition0%0/3
$params->{"queue"} ||= $self->{"default_queue"}
l!l&&r!l&&!r
000
MC/DC0%0/2
$params->{"queue"} ||= $self->{"default_queue"}
$params->{"queue"} $self->{"default_queue"}
Truth table0%0/3
A ||= B
A= $params->{"queue"}B= $self->{"default_queue"}
ABresult
1X1
011
000
2302 0 ▶ if ( $params->{queue} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($params->{"queue"}) 0 0 0
2303  
2304 # does not matter if the queue name does not exist!
2305 0 delete $self->{subscriptions}->{ $params->{queue} } ;
2306 }
2307 }
2308  
2309 # -----------------------------------------------------------------------------
2310  
2311 =head2 purge_tasks
2312  
2313 Purge will remove all processed task items and failures/deadletters (process_failure >= 5).
2314 These are completely removed from the database
2315  
2316 B<Parameters>
2317  
2318 Hash of
2319  
2320 =over
2321  
2322 =item queue
2323  
2324 Name of the queue, wildcard allowed
2325  
2326 =item before (optional)
2327  
2328 Unix epoch or parsable datetime before which items should be purged
2329  
2330 defaults to 'now'
2331  
2332 =back
2333  
2334 B<Example usage>
2335  
2336 my $before = $queue->stats( queue => 'queue_name', before => '2015-11-24') ;
2337 $queue->purge_tasks( queue => 'queue_name') ;
2338 my $after = $queue->stats( queue => 'queue_name') ;
2339  
2340 say "removed " .( $before->{total_records} - $after->{total_records}) ;
2341  
2342 =cut
2343  
2344 sub purge_tasks
2345 0 ▶{
Subroutine purge_tasks: not called CC=4 SCAR=30.0
Pod documented
2346 0 my $self = shift ;
2347 0 ▶ my $params = @_ % 2 ? shift : {@_} ;
Branch: 1 branch
BranchTrueFalseTotal
@_ % 2 ? : 0 0 0
2348  
2349 0 ▶ if ( ref($params) ne 'HASH' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $params ne "HASH") 0 0 0
2350 0 warn "purge_tasks accepts a hash or a hashref of parameters" ;
2351 0 return 0 ;
2352 }
2353  
2354 0 ▶ $params->{queue} ||= $self->{default_queue} ;
Condition0%0/3
$params->{"queue"} ||= $self->{"default_queue"}
l!l&&r!l&&!r
000
MC/DC0%0/2
$params->{"queue"} ||= $self->{"default_queue"}
$params->{"queue"} $self->{"default_queue"}
Truth table0%0/3
A ||= B
A= $params->{"queue"}B= $self->{"default_queue"}
ABresult
1X1
011
000
2355 0 my $qname = $params->{queue} ;
2356  
2357 # SQL wildcard replace
2358 0 $qname =~ s/\*/%/g ;
2359  
2360 0 ▶ try {
Subroutine __ANON__: not called CC=2 SCAR=17.9
2361 0 ▶ if ( !defined $params->{before} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $params->{'before'}) { } 0 0 0
2362 0 $params->{before} = _parse_datetime( time() ) ;
2363 } else {
2364 0 $params->{before} = _parse_datetime( $params->{before} ) ;
2365 }
2366 }
2367 0 ▶ catch {
Subroutine __ANON__: not called CC=1 SCAR=6.9
2368 0 warn(
2369 "this does not look like a datetime value I can use: '$params->{before}'"
2370 ) ;
2371 0 $params->{before} = _parse_datetime( time() ) ;
2372 0 } ;
2373  
2374 # TODO: add in expired items too, plus the and processed=1 or process_failure =1 looks a bit wrong
2375 0 my $sql = "WHERE queue_name LIKE ?
2376 AND processed = 1
2377 OR process_failure = 1
2378 AND msg_type = ?
2379 AND added <= ?" ;
2380  
2381 my $resp = $self->_delete_db_record( $self->{prefix} . "_queue",
2382 0 $sql, [ $qname, MSG_TASK, $params->{before} ] ) ;
2383  
2384 # return the number of items deleted
2385 0 return $resp->{row_count} ;
2386 }
2387  
2388 # -----------------------------------------------------------------------------
2389  
2390 =head2 purge_chatter
2391  
2392 purge will remove all chatter messages.
2393 These are completely removed from the database
2394  
2395 B<Parameters>
2396  
2397 Hash of
2398  
2399 =over
2400  
2401 =item queue
2402  
2403 Name of the queue, wildcard allowed
2404  
2405 =item before (optional)
2406  
2407 Unix epoch or parsable datetime before which items should be purged
2408  
2409 defaults to 'now'
2410  
2411 =back
2412  
2413 B<Example usage>
2414  
2415 my $del = $queue->purge_chatter( queue => 'queue_name', before => '2015-11-24') ;
2416  
2417 say "removed $del messages" ;
2418  
2419 =cut
2420  
2421 sub purge_chatter
2422 0 ▶{
Subroutine purge_chatter: not called CC=5 SCAR=34.0
Pod documented
2423 0 my $self = shift ;
2424 0 ▶ my $params = @_ % 2 ? shift : {@_} ;
Branch: 1 branch
BranchTrueFalseTotal
@_ % 2 ? : 0 0 0
2425  
2426 0 ▶ if ( ref($params) ne 'HASH' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $params ne "HASH") 0 0 0
2427 0 warn "purge_chatter accepts a hash or a hashref of parameters" ;
2428 0 return 0 ;
2429 }
2430  
2431 0 ▶ $params->{queue} ||= $self->{default_queue} ;
Condition0%0/3
$params->{"queue"} ||= $self->{"default_queue"}
l!l&&r!l&&!r
000
MC/DC0%0/2
$params->{"queue"} ||= $self->{"default_queue"}
$params->{"queue"} $self->{"default_queue"}
Truth table0%0/3
A ||= B
A= $params->{"queue"}B= $self->{"default_queue"}
ABresult
1X1
011
000
2432 0 my $qname = $params->{queue} ;
2433  
2434 # SQL wildcard replace
2435 0 $qname =~ s/\*/%/g ;
2436  
2437 0 my $sql = "WHERE queue_name LIKE ?
2438 AND processed = 1
2439 OR process_failure = 1
2440 AND msg_type = ?
2441 AND added <= ?" ;
2442 0 my $sql_args = [ $qname, MSG_CHATTER, $params->{before} ] ;
2443  
2444 0 ▶ if ( defined $params->{counter} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $params->{'counter'}) { } 0 0 0
2445 0 my $sql = "WHERE queue_name LIKE ?
2446 AND processed = 1
2447 OR process_failure = 1
2448 AND msg_type = ?
2449 AND counter <= ?" ;
2450 0 my $sql_args = [ $qname, MSG_CHATTER, $params->{counter} ] ;
2451  
2452 } else {
2453 0 ▶ try {
Subroutine __ANON__: not called CC=2 SCAR=17.9
2454 0 ▶ if ( !defined $params->{before} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $params->{'before'}) { } 0 0 0
2455 0 $params->{before} = _parse_datetime( time() ) ;
2456 } else {
2457 0 $params->{before} = _parse_datetime( $params->{before} ) ;
2458 }
2459 }
2460 0 ▶ catch {
Subroutine __ANON__: not called CC=1 SCAR=6.9
2461 0 warn(
2462 "this does not look like a datetime value I can use: '$params->{before}'"
2463 ) ;
2464 0 $params->{before} = _parse_datetime( time() ) ;
2465 0 } ;
2466 }
2467  
2468 0 my $resp = $self->_delete_db_record( $self->{prefix} . "_queue",
2469 $sql, $sql_args ) ;
2470  
2471 # return the number of items deleted
2472 0 return $resp->{row_count} ;
2473 }
2474  
2475 # -----------------------------------------------------------------------------
2476  
2477 =head2 remove_queue
2478  
2479 Remove a queue and all of its records (task and chatter)
2480  
2481 B<Parameters>
2482  
2483 Takes a hash of
2484  
2485 =over
2486  
2487 =item queue
2488  
2489 Name of the queue, wildcards allowed
2490  
2491 =back
2492  
2493 B<Example usage>
2494  
2495 $queue->remove_queue( queue => 'queue_name') ;
2496 my $after = $queue->list_queues() ;
2497 # convert list into a hash for easier checking
2498 my %a = map { $_ => 1} @after ;
2499 say "queue removed" if( !$q->{queue_name}) ;
2500  
2501 =cut
2502  
2503 sub remove_queue
2504 0 ▶{
Subroutine remove_queue: not called CC=4 SCAR=30.0
Pod documented
2505 0 my $self = shift ;
2506 0 ▶ my $params = @_ % 2 ? shift : {@_} ;
Branch: 1 branch
BranchTrueFalseTotal
@_ % 2 ? : 0 0 0
2507  
2508 0 ▶ if ( ref($params) ne 'HASH' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $params ne "HASH") 0 0 0
2509 0 warn "remove_queue accepts a hash or a hashref of parameters" ;
2510 0 return 0 ;
2511 }
2512  
2513 0 ▶ $params->{queue} ||= $self->{default_queue} ;
Condition0%0/3
$params->{"queue"} ||= $self->{"default_queue"}
l!l&&r!l&&!r
000
MC/DC0%0/2
$params->{"queue"} ||= $self->{"default_queue"}
$params->{"queue"} $self->{"default_queue"}
Truth table0%0/3
A ||= B
A= $params->{"queue"}B= $self->{"default_queue"}
ABresult
1X1
011
000
2514 0 my $qname = $params->{queue} ;
2515  
2516 # SQL wildcard replace
2517 0 $qname =~ s/\*/%/g ;
2518  
2519 0 my $resp = $self->_delete_db_record( $self->{prefix} . "_queue",
2520 "WHERE queue_name LIKE ?", [$qname] ) ;
2521 0 return $resp->{success} ;
2522 }
2523  
2524 # -----------------------------------------------------------------------------
2525  
2526 =head2 reset_failures, reset_deadletters
2527  
2528 Clear any process_failure values from all unprocessed task items
2529  
2530 B<Parameters>
2531  
2532 Hash of
2533  
2534 =over
2535  
2536 =item queue
2537  
2538 Name of the queue, wildcard allowed
2539  
2540 =back
2541  
2542 B<Example usage>
2543  
2544 my $before = $queue->stats( queue => 'queue_name') ;
2545 $queue->reset_failures( queue => 'queue_name') ;
2546 my $after = $queue->stats( queue => 'queue_name') ;
2547  
2548 say "reset " .( $after->{unprocessed} - $before->{unprocessed}) ;
2549  
2550 =cut
2551  
2552 sub reset_failures
2553 0 ▶{
Subroutine reset_failures: not called CC=5 SCAR=34.0
Pod documented
2554 0 my $self = shift ;
2555 0 ▶ my $params = @_ % 2 ? shift : {@_} ;
Branch: 1 branch
BranchTrueFalseTotal
@_ % 2 ? : 0 0 0
2556  
2557 0 ▶ if ( ref($params) ne 'HASH' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $params ne "HASH") 0 0 0
2558 0 warn "reset_failures accepts a hash or a hashref of parameters" ;
2559 0 return 0 ;
2560 }
2561  
2562 0 ▶ $params->{queue} ||= $self->{default_queue} ;
Condition0%0/3
$params->{"queue"} ||= $self->{"default_queue"}
l!l&&r!l&&!r
000
MC/DC0%0/2
$params->{"queue"} ||= $self->{"default_queue"}
$params->{"queue"} $self->{"default_queue"}
Truth table0%0/3
A ||= B
A= $params->{"queue"}B= $self->{"default_queue"}
ABresult
1X1
011
000
2563 0 my $qname = $params->{queue} ;
2564  
2565 # SQL wildcard replace
2566 0 $qname =~ s/\*/%/g ;
2567  
2568 0 my $sql = "SET process_failure=0" ;
2569 0 $sql .= " WHERE queue_name LIKE ?
2570 AND process_failure = 1
2571 AND msg_type = ?" ;
2572 0 my $resp = $self->_update_db( $self->{prefix} . "_queue",
2573 $sql, [ $qname, MSG_TASK ] ) ;
2574  
2575 0 ▶ return $resp->{row_count} ? $resp->{row_count} : 0 ;
Branch: 1 branch
BranchTrueFalseTotal
$resp->{'row_count'} ? : 0 0 0
2576 }
2577  
2578 0 ▶sub reset_deadletters {
Subroutine reset_deadletters: not called CC=1 SCAR=6.9
Pod documented
2579 0 my $self = shift ;
2580 0 return $self->reset_failures( $self, @_) ;
2581 }
2582  
2583 # -----------------------------------------------------------------------------
2584  
2585 =head2 remove_failures, remove_deadletters
2586  
2587 Permanently delete task failures from the database
2588  
2589 B<Parameters>
2590  
2591 Hash of
2592  
2593 =over
2594  
2595 =item queue
2596  
2597 Name of the queue, wildcard allowed
2598  
2599 =back
2600  
2601 B<Example usage>
2602  
2603 $queue->remove_failues( queue => 'queue_name') ;
2604 my $stats = $queue->stats( queue => 'queue_name') ;
2605 say "failues left " .( $stats->{failures}) ;
2606  
2607 =cut
2608  
2609 sub remove_failures
2610 0 ▶{
Subroutine remove_failures: not called CC=4 SCAR=30.0
Pod documented
2611 0 my $self = shift ;
2612 0 ▶ my $params = @_ % 2 ? shift : {@_} ;
Branch: 1 branch
BranchTrueFalseTotal
@_ % 2 ? : 0 0 0
2613  
2614 0 ▶ if ( ref($params) ne 'HASH' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $params ne "HASH") 0 0 0
2615 0 warn "remove_failures accepts a hash or a hashref of parameters" ;
2616 0 return 0 ;
2617 }
2618  
2619 0 ▶ $params->{queue} ||= $self->{default_queue} ;
Condition0%0/3
$params->{"queue"} ||= $self->{"default_queue"}
l!l&&r!l&&!r
000
MC/DC0%0/2
$params->{"queue"} ||= $self->{"default_queue"}
$params->{"queue"} $self->{"default_queue"}
Truth table0%0/3
A ||= B
A= $params->{"queue"}B= $self->{"default_queue"}
ABresult
1X1
011
000
2620 0 my $qname = $params->{queue} ;
2621  
2622 # SQL wildcard replace
2623 0 $qname =~ s/\*/%/g ;
2624  
2625 0 my $sql = "WHERE process_failure = 1 AND msg_type = ?" ;
2626 0 my $resp = $self->_delete_db_record( $self->{prefix} . "_queue",
2627 $sql, [MSG_TASK] ) ;
2628  
2629 0 return $resp->{row_count} ;
2630 }
2631  
2632 0 ▶sub remove_deadletters {
Subroutine remove_deadletters: not called CC=1 SCAR=6.9
Pod documented
2633 0 my $self = shift ;
2634 0 return $self->reset_failures( $self, @_) ;
2635 }
2636  
2637 # -----------------------------------------------------------------------------
2638  
2639 =head2 remove_tables
2640  
2641 If you never need to use the database again, it can be completely removed
2642  
2643 B<Example usage>
2644  
2645 $queue_>remove_tables() ;
2646  
2647 =cut
2648  
2649 sub remove_tables
2650 0 ▶{
Subroutine remove_tables: not called CC=1 SCAR=6.9
Pod documented
2651 0 my $self = shift ;
2652  
2653 0 my $sql = sprintf( 'DROP TABLE %s_queue;', $self->{prefix} ) ;
2654 0 $self->_debug($sql) ;
2655 0 $self->{dbh}->do($sql) ;
2656 }
2657  
2658 # -----------------------------------------------------------------------------
2659  
2660 3 1 ;
↑ Summary