lib/POE/Component/MessageQueue/Storage/Complex.pm

filter: Statementstmt 79.2% 130 / 164 Branchbran 65.0% 26 / 40 Conditioncond n/a MC/DCmcdc n/a Subroutinesub 78.9% 30 / 38 Podpod 0.0% 0 / 5 totaltotal 75.3% 186 / 247 CC 29 SCAR 17.5
CC
29
Cov
76%
__ANON__
30.0
_activity
12.0
store
8.0
CRAP 5.7
« lib/POE/Component/MessageQueue/Storage/Remote.pm ↑ Summary script/mq.pl »
1 #
2 # Copyright 2007-2010 David Snopek <dsnopek@gmail.com>
3 #
4 # This program is free software: you can redistribute it and/or modify
5 # it under the terms of the GNU General Public License as published by
6 # the Free Software Foundation, either version 2 of the License, or
7 # (at your option) any later version.
8 #
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
13 #
14 # You should have received a copy of the GNU General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 #
17  
18 package POE::Component::MessageQueue::Storage::Complex::IdleElement;
19 4 ▶use Heap::Elem;
Subroutine BEGIN: called CC=1 SCAR=0.0
20 4 ▶use base qw(Heap::Elem);
Subroutine BEGIN: called CC=1 SCAR=0.0
21 4 ▶BEGIN {eval q(use Time::HiRes qw(time))}
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
22  
23 sub new
24 {
25 66 ▶ my ($class, $id) = @_;
Subroutine new: called CC=1 SCAR=0.0
26 66 my $self = bless([ @{ $class->SUPER::new($id) }, time() ], $class);
27 }
28  
29 sub cmp
30 {
31 301 ▶ my ($self, $other) = @_;
Subroutine cmp: called CC=1 SCAR=0.0
32 301 return $self->[2] <=> $other->[2];
33 }
34  
35 4 1;
36  
37 package POE::Component::MessageQueue::Storage::Complex;
38 4 ▶use Moose;
Subroutine BEGIN: called CC=1 SCAR=0.0
39 4 with qw(POE::Component::MessageQueue::Storage::Double);
40  
41 4 ▶use POE;
Subroutine BEGIN: called CC=1 SCAR=0.0
42 4 ▶use Heap::Fibonacci;
Subroutine BEGIN: called CC=1 SCAR=0.0
43 4 ▶BEGIN {eval q(use Time::HiRes qw(time))}
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
44  
45 4 has timeout => (
46 is => 'ro',
47 isa => 'Int',
48 required => 1,
49 );
50  
51 has granularity => (
52 is => 'ro',
53 isa => 'Int',
54 lazy => 1,
55 0 ▶ default => sub { $_[0]->timeout / 2 },
Subroutine __ANON__: not called CC=1 SCAR=6.9
56 4 );
57  
58 4 has alias => (
59 is => 'ro',
60 default => 'MQ-Expire-Timer',
61 required => 1,
62 );
63  
64 4 has front_size => (
65 is => 'rw',
66 isa => 'Int',
67 default => 0,
68 traits => ['Number'],
69 handles => {
70 'more_front' => 'add',
71 'less_front' => 'sub',
72 },
73 );
74  
75 4 has front_max => (
76 is => 'ro',
77 isa => 'Int',
78 required => 1,
79 );
80  
81 has front_expirations => (
82 is => 'ro',
83 isa => 'HashRef[Num]',
84 1 ▶ default => sub { {} },
Subroutine __ANON__: called CC=1 SCAR=0.0
85 4 traits => ['Hash'],
86 handles => {
87 'expire_from_front' => 'set',
88 'delete_front_expiration' => 'delete',
89 'clear_front_expirations' => 'clear',
90 'count_front_expirations' => 'count',
91 'front_expiration_pairs' => 'kv',
92 },
93 );
94  
95 has nonpersistent_expirations => (
96 is => 'ro',
97 isa => 'HashRef',
98 1 ▶ default => sub { {} },
Subroutine __ANON__: called CC=1 SCAR=0.0
99 4 traits => ['Hash'],
100 handles => {
101 'expire_nonpersistent' => 'set',
102 'delete_nonpersistent_expiration' => 'delete',
103 'clear_nonpersistent_expirations' => 'clear',
104 'count_nonpersistent_expirations' => 'count',
105 'nonpersistent_expiration_pairs' => 'kv',
106 },
107 );
108  
109 sub count_expirations
110 {
111 71 ▶ my $self = $_[0];
Subroutine count_expirations: called CC=1 SCAR=0.0
Pod undocumented
112 71 return $self->count_nonpersistent_expirations +
113 $self->count_front_expirations;
114 }
115  
116 has idle_hash => (
117 is => 'ro',
118 isa => 'HashRef',
119 1 ▶ default => sub { {} },
Subroutine __ANON__: called CC=1 SCAR=0.0
120 4 traits => ['Hash'],
121 handles => {
122 '_hashset_idle' => 'set',
123 'get_idle' => 'get',
124 'delete_idle' => 'delete',
125 'clear_idle' => 'clear',
126 },
127 );
128  
129 has idle_heap => (
130 is => 'ro',
131 isa => 'Heap::Fibonacci',
132 lazy => 1,
133 1 ▶ default => sub { Heap::Fibonacci->new },
Subroutine __ANON__: called CC=1 SCAR=0.0
134 4 clearer => 'reset_idle_heap',
135 );
136  
137 sub set_idle
138 {
139 66 ▶ my ($self, @ids) = @_;
Subroutine set_idle: called CC=2 SCAR=6.9
Pod undocumented
140  
141 66 my %idles = map {($_ =>
142 POE::Component::MessageQueue::Storage::Complex::IdleElement->new($_)
143 )} @ids;
144  
145 66 $self->_hashset_idle(%idles);
146 66 $self->idle_heap->add($_) foreach (values %idles);
147 }
148  
149 around delete_idle => sub {
150 58 ▶ my $original = shift;
Subroutine __ANON__: called CC=2 SCAR=6.9
151 58 $_[0]->idle_heap->delete($_) foreach ($original->(@_));
152 4 };
153  
154 0 ▶after clear_idle => sub {$_[0]->reset_idle_heap()};
Subroutine __ANON__: not called CC=1 SCAR=1.2
155  
156 4 has shutting_down => (
157 is => 'rw',
158 default => 0,
159 );
160  
161 after remove => sub {
162 0 ▶ my ($self, $arg, $callback) = @_;
Subroutine __ANON__: not called CC=5 SCAR=34.0
163 0 ▶ my $aref = (ref $arg eq 'ARRAY') ? $arg : [$arg];
Branch: 1 branch
BranchTrueFalseTotal
ref $arg eq 'ARRAY' ? : 0 0 0
164 0 ▶ my @ids = (grep $self->in_front($_), @$aref) or return;
Branch: 1 branch
BranchTrueFalseTotal
my(@ids) = grep($self->in_front($_), @$aref) or return 0 0 0
165  
166 0 $self->delete_idle(@ids);
167 0 $self->delete_front_expiration(@ids);
168 0 $self->delete_nonpersistent_expiration(@ids);
169  
170 0 my $sum = 0;
171 0 foreach my $info ($self->delete_front(@ids))
172 {
173 0 ▶ $sum += $info->{size} if $info;
Branch: 1 branch
BranchTrueFalseTotal
if $info 0 0 0
174 }
175 0 $self->less_front($sum);
176 4 };
177  
178 after empty => sub {
179 0 ▶ my ($self) = @_;
Subroutine __ANON__: not called CC=1 SCAR=6.9
180 0 $self->clear_front();
181 0 $self->clear_idle();
182 0 $self->clear_front_expirations();
183 0 $self->clear_nonpersistent_expirations();
184 0 $self->front_size(0);
185 4 };
186  
187 0 ▶after $_ => sub {$_[0]->_activity($_[1])} foreach qw(claim get);
Subroutine __ANON__: not called CC=1 SCAR=1.2
188  
189 around claim_and_retrieve => sub {
190 0 ▶ my $original = shift;
Subroutine __ANON__: not called CC=1 SCAR=6.9
191 0 my $self = $_[0];
192 0 my $callback = pop;
193 $original->(@_, sub {
194 0 ▶ if (my $msg = $_[0])
Subroutine __ANON__: not called CC=2 SCAR=17.9
Branch: 1 branch
BranchTrueFalseTotal
if (my $msg = $_[0]) 0 0 0
195 {
196 0 $self->_activity($msg->id);
197 }
198 0 goto $callback;
199 0 });
200 4 };
201  
202 sub _activity
203 {
204 0 ▶ my ($self, $arg) = @_;
Subroutine _activity: not called CC=3 SCAR=24.8
205 0 ▶ my $aref = (ref $arg eq 'ARRAY' ? $arg : [$arg]);
Branch: 1 branch
BranchTrueFalseTotal
ref $arg eq 'ARRAY' ? : 0 0 0
206
207 0 my $time = time();
208 0 foreach my $elem (grep {$_} $self->get_idle(@$aref))
209 {
210 # we can't just decrease_key, the values get bigger as we go.
211 0 $self->idle_heap->delete($elem);
212 0 $elem->[2] = $time;
213 0 $self->idle_heap->add($elem);
214 }
215 }
216  
217 sub BUILD
218 {
219 1 ▶ my $self = shift;
Subroutine BUILD: called CC=1 SCAR=0.0
Pod undocumented
220 POE::Session->create(
221 object_states => [ $self => [qw(_expire)] ],
222 inline_states => {
223 _start => sub {
224 1 ▶ $poe_kernel->alias_set($self->alias);
Subroutine __ANON__: called CC=1 SCAR=0.0
225 },
226 _check => sub {
227 5 ▶ $poe_kernel->delay(_expire => $self->granularity);
Subroutine __ANON__: called CC=1 SCAR=0.0
228 },
229 },
230 1 );
231 1 $self->children({FRONT => $self->front, BACK => $self->back});
232 1 $self->add_names('COMPLEX');
233 }
234  
235 sub store
236 {
237 66 ▶ my ($self, $message, $callback) = @_;
Subroutine store: called CC=8 SCAR=20.8
Pod undocumented
238 66 my $id = $message->id;
239  
240 66 $self->more_front($message->size);
241 66 $self->set_front($id => {persisted => 0, size => $message->size});
242 66 $self->set_idle($id);
243  
244 # Move a bunch of messages to the backstore to keep size respectable
245 66 my (@bump, %need_persist);
246 66 ▶ while($self->front_size > $self->front_max)
Branch: 1 branch
BranchTrueFalseTotal
if ($self->front_size > $self->front_max) 58 66 124
247 {
248 58 ▶ my $top = $self->idle_heap->extract_top or last;
Branch: 1 branch
BranchTrueFalseTotal
my $top = $self->idle_heap->extract_top or last 0 58 58
249 58 my $id = $top->val;
250 58 ▶ $need_persist{$id} = 1 unless $self->in_back($id);
Branch: 1 branch
BranchTrueFalseTotal
unless $self->in_back($id) 58 0 58
251 58 $self->less_front($self->delete_front($id)->{size});
252 58 push(@bump, $id);
253 }
254  
255 66 ▶ if(@bump)
Branch: 1 branch
BranchTrueFalseTotal
if (@bump) 58 8 66
256 {
257 58 my $idstr = join(', ', @bump);
258 58 $self->log(info => "Bumping ($idstr) off the frontstore.");
259 58 $self->delete_idle(@bump);
260 58 $self->delete_front_expiration(@bump);
261 $self->front->get(\@bump, sub {
262 58 ▶ my $now = time();
Subroutine __ANON__: called CC=4 SCAR=13.9
263 58 $self->front->remove(\@bump);
264 58 $self->back->store($_) foreach
265 30 grep { $need_persist{$_->id} }
266 30 ▶ grep { !$_->has_expiration or $now < $_->expire_at }
Branch: 1 branch
BranchTrueFalseTotal
not $_->has_expiration or $now < $_->expire_at 2 28 30
267 58 ▶ grep { $_->persistent || $_->has_expiration }
Branch: 1 branch
BranchTrueFalseTotal
$_->persistent or $_->has_expiration 30 28 58
268 58 @{ $_[0] };
269 58 });
270 }
271  
272 66 ▶ if ($message->persistent)
Branch: 2 branches
BranchTrueFalseTotal
if ($message->persistent) { } 32 34 66
elsif ($message->has_expiration) { } 2 32 34
273 {
274 32 $self->expire_from_front($id, time() + $self->timeout);
275 }
276 elsif ($message->has_expiration)
277 {
278 2 $self->expire_nonpersistent($id, $message->expire_at);
279 }
280  
281 66 $self->front->store($message, $callback);
282 66 ▶ $poe_kernel->post($self->alias, '_check') if ($self->count_expirations == 1);
Branch: 1 branch
BranchTrueFalseTotal
if $self->count_expirations == 1 1 65 66
283 }
284  
285 sub _is_expired
286 {
287 10 ▶ my $now = time();
Subroutine _is_expired: called CC=1 SCAR=0.0
288 6 map {$_->[0]}
289 10 grep {$_->[1] <= $now}
290 @_;
291 }
292  
293 sub _expire
294 {
295 5 ▶ my ($self, $kernel) = @_[OBJECT, KERNEL];
Subroutine _expire: called CC=7 SCAR=19.5
296  
297 5 ▶ return if $self->shutting_down;
Branch: 1 branch
BranchTrueFalseTotal
if $self->shutting_down 0 5 5
298  
299 5 ▶ if (my @front_exp = _is_expired($self->front_expiration_pairs))
Branch: 1 branch
BranchTrueFalseTotal
if (my(@front_exp) = _is_expired($self->front_expiration_pairs)) 1 4 5
300 {
301 1 my $idstr = join(', ', @front_exp);
302 1 $self->log(info => "Pushing expired messages ($idstr) to backstore.");
303 1 $_->{persisted} = 1 foreach $self->get_front(@front_exp);
304 1 $self->delete_front_expiration(@front_exp);
305  
306 $self->front->get(\@front_exp, sub {
307 # Messages in two places is dangerous, so we are careful!
308 1 ▶ $self->back->store($_->clone) foreach (@{$_[0]});
Subroutine __ANON__: called CC=2 SCAR=6.9
309 1 });
310 }
311  
312 5 ▶ if (my @np_exp = _is_expired($self->nonpersistent_expiration_pairs))
Branch: 1 branch
BranchTrueFalseTotal
if (my(@np_exp) = _is_expired($self->nonpersistent_expiration_pairs)) 2 3 5
313 {
314 2 my $idstr = join(', ', @np_exp);
315 2 $self->log(info => "Nonpersistent messages ($idstr) have expired.");
316 2 my @remove = grep { $self->in_back($_) } @np_exp;
317 2 ▶ $self->back->remove(\@remove) if (@remove);
Branch: 1 branch
BranchTrueFalseTotal
if @remove 2 0 2
318 2 $self->delete_nonpersistent_expiration(@np_exp);
319 }
320  
321 5 ▶ $kernel->yield('_check') if ($self->count_expirations);
Branch: 1 branch
BranchTrueFalseTotal
if $self->count_expirations 4 1 5
322 }
323  
324 sub storage_shutdown
325 {
326 1 ▶ my ($self, $complete) = @_;
Subroutine storage_shutdown: called CC=1 SCAR=0.0
Pod undocumented
327  
328 1 $self->shutting_down(1);
329  
330 # shutdown our check messages session
331 1 $poe_kernel->alias_remove($self->alias);
332  
333 $self->front->get_all(sub {
334 1 ▶ my $message_aref = $_[0];
Subroutine __ANON__: called CC=3 SCAR=11.0
335  
336 1 ▶ my @messages = grep {$_->persistent && !$self->in_back($_)}
Branch: 1 branch
BranchTrueFalseTotal
$_->persistent and not $self->in_back($_) 4 4 8
337 @$message_aref;
338
339 1 $self->log(info => 'Moving all messages into backstore.');
340 1 $self->back->store($_) foreach @messages;
341 $self->front->empty(sub {
342 $self->front->storage_shutdown(sub {
343 1 ▶ $self->back->storage_shutdown($complete);
Subroutine __ANON__: called CC=1 SCAR=0.0
344 1 ▶ });
Subroutine __ANON__: called CC=1 SCAR=0.0
345 1 });
346 1 });
347 }
348  
349 4 1;
350  
351 __END__
352  
353 =pod
354  
355 =head1 NAME
356  
357 POE::Component::MessageQueue::Storage::Complex -- A configurable storage
358 engine that keeps a front-store (something fast) and a back-store (something
359 persistent), only storing messages in the back-store after a configurable
360 timeout period.
361  
362 =head1 SYNOPSIS
363  
364 use POE;
365 use POE::Component::MessageQueue;
366 use POE::Component::MessageQueue::Storage::Complex;
367 use strict;
368  
369 POE::Component::MessageQueue->new({
370 storage => POE::Component::MessageQueue::Storage::Complex->new({
371 timeout => 4,
372 granularity => 2,
373  
374 # Only allow the front store to grow to 64Mb
375 front_max => 64 * 1024 * 1024,
376  
377 front => POE::Component::MessageQueue::Storage::Memory->new(),
378 # Or, an alternative memory store is available!
379 #front => POE::Component::MessageQueue::Storage::BigMemory->new(),
380  
381 back => POE::Component::MessageQueue::Storage::Throttled->new({
382 storage => My::Persistent::But::Slow::Datastore->new()
383  
384 # Examples include:
385 #storage => POE::Component::MessageQueue::Storage::DBI->new({ ... });
386 #storage => POE::Component::MessageQueue::Storage::FileSystem->new({ ... });
387 })
388 })
389 });
390  
391 POE::Kernel->run();
392 exit;
393  
394 =head1 DESCRIPTION
395  
396 The idea of having a front store (something quick) and a back store (something
397 persistent) is common and recommended, so this class exists as a helper to
398 implementing that pattern.
399  
400 The front store acts as a cache who's max size is specified by front_max.
401 All messages that come in are added to the front store. Messages are only
402 removed after having been successfully delivered or when pushed out of the
403 cache by newer messages.
404  
405 Persistent messages that are not removed after the number of seconds specified
406 by timeout are added to the back store (but not removed from the front store).
407 This optimization allows for the possibility that messages will be handled
408 before having been persisted, reducing the load on the back store.
409  
410 Non-persistent messages will be discarded when eventually pushed off the front
411 store, unless the I<expire-after> header is specified, in which case they may
412 be stored on the back store inorder to keep around them long enough.
413 Non-persistent messages on the back store which are passed their expiration
414 date will be periodically cleaned up.
415  
416 =head1 CONSTRUCTOR PARAMETERS
417  
418 =over 2
419  
420 =item timeout => SCALAR
421  
422 The number of seconds after a message enters the front-store before it
423 expires. After this time, if the message hasn't been removed, it will be
424 moved into the backstore.
425  
426 =item granularity => SCALAR
427  
428 The number of seconds to wait between checks for timeout expiration.
429  
430 =item front_max => SCALAR
431  
432 The maximum number of bytes to allow the front store to grow to. If the front
433 store grows to big, old messages will be "pushed off" to make room for new
434 messages.
435  
436 =item front => SCALAR
437  
438 An optional reference to a storage engine to use as the front store instead of
439 L<POE::Component::MessageQueue::Storage::BigMemory>.
440  
441 =item back => SCALAR
442  
443 Takes a reference to a storage engine to use as the back store.
444  
445 Using L<POE::Component::MessageQueue::Storage::Throttled> to wrap your main
446 storage engine is highly recommended for the reasons explained in its specific
447 documentation.
448  
449 =back
450  
451 =head1 SUPPORTED STOMP HEADERS
452  
453 =over 4
454  
455 =item B<persistent>
456  
457 I<Fully supported>.
458  
459 =item B<expire-after>
460  
461 I<Fully Supported>.
462  
463 =item B<deliver-after>
464  
465 I<Fully Supported>.
466  
467 =back
468  
469 =head1 SEE ALSO
470  
471 L<POE::Component::MessageQueue::Storage::Complex::Default> - The most common case. Based on this storage engine.
472  
473 L<POE::Component::MessageQueue>,
474 L<POE::Component::MessageQueue::Storage>,
475 L<POE::Component::MessageQueue::Storage::Double>
476  
477 I<Other storage engines:>
478  
479 L<POE::Component::MessageQueue::Storage::Default>,
480 L<POE::Component::MessageQueue::Storage::Memory>,
481 L<POE::Component::MessageQueue::Storage::BigMemory>,
482 L<POE::Component::MessageQueue::Storage::FileSystem>,
483 L<POE::Component::MessageQueue::Storage::DBI>,
484 L<POE::Component::MessageQueue::Storage::Generic>,
485 L<POE::Component::MessageQueue::Storage::Generic::DBI>,
486 L<POE::Component::MessageQueue::Storage::Throttled>
487 L<POE::Component::MessageQueue::Storage::Default>
488  
489 =cut
« lib/POE/Component/MessageQueue/Storage/Remote.pm ↑ Summary script/mq.pl »