AMQP.pm

filter: Statementstmt 21.2% 57 / 268 Branchbran 4.3% 5 / 116 Conditioncond 6.4% 2 / 31 MC/DCmcdc 0.0% 0 / 19 Subroutinesub 29.1% 14 / 48 Podpod 52.6% 10 / 19 totaltotal 17.5% 88 / 501 CC 73 SCAR 52.6
CC
73
Cov
15%
tcp_server_input
650.0
server_send
342.0
create
32.5
CRAP 193.4
« AMQP/Channel.pm ↑ Summary AMQP/Queue.pm »
1 package POE::Component::Client::AMQP;
2  
3 =head1 NAME
4  
5 POE::Component::Client::AMQP - Asynchronous AMQP client implementation in POE
6  
7 =head1 SYNOPSIS
8  
9 use POE::Component::Client::AMQP;
10  
11 Net::AMQP::Protocol->load_xml_spec('amqp0-8.xml');
12  
13 my $amq = POE::Component::Client::AMQP->create(
14 RemoteAddress => 'mq.domain.tld',
15 );
16  
17 $amq->channel(1)->queue('frank')->subscribe(sub {
18 my ($payload, $meta) = @_;
19  
20 my $reply_to = $meta->{header_frame}->reply_to;
21  
22 $amq->channel(1)->queue($reply_to)->publish("Message received");
23 });
24  
25 $amq->run();
26  
27 =head1 DESCRIPTION
28  
29 This module implements the Advanced Message Queue Protocol (AMQP) TCP/IP client. It's goal is to provide users with a quick and easy way of using AMQP while at the same time exposing the advanced functionality of the protocol if needed.
30  
31 The (de)serialization and representation logic is handled by L<Net::AMQP>, which needs to be setup (via load_xml_spec()) prior to this client software running. Please see the docs there for further information on this.
32  
33 =cut
34  
35 1 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
36 1 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
37 1 ▶use Params::Validate qw(validate validate_with);
Subroutine BEGIN: called CC=1 SCAR=0.0
38 1 ▶use Net::AMQP;
Subroutine BEGIN: called CC=1 SCAR=0.0
39 1 ▶use Net::AMQP::Common qw(:all);
Subroutine BEGIN: called CC=1 SCAR=0.0
40 1 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
41 1 ▶use base qw(Exporter Class::Accessor);
Subroutine BEGIN: called CC=1 SCAR=0.0
42 1 __PACKAGE__->mk_accessors(qw(Logger is_stopped is_started is_stopping frame_max));
43  
44 1 our $VERSION = 0.03;
45  
46 1 ▶use constant {
Subroutine BEGIN: called CC=1 SCAR=0.0
47 1 AMQP_ACK => '__amqp_ack__',
48 AMQP_REJECT => '__amqp_reject__',
49 1 };
50  
51 1 my @_constants;
52 1 our (@EXPORT_OK, %EXPORT_TAGS);
53 1 ▶BEGIN {
Subroutine BEGIN: called CC=1 SCAR=0.0
54 1 @_constants = qw(AMQP_ACK AMQP_REJECT);
55 1 @EXPORT_OK = (@_constants);
56 1 %EXPORT_TAGS = ('constants' => [@_constants]);
57 };
58  
59 # Use libraries that require my constants after defining them
60  
61 1 ▶use POE qw(
Subroutine BEGIN: called CC=1 SCAR=0.0
62 Filter::Stream
63 Component::Client::AMQP::TCP
64 Component::Client::AMQP::Channel
65 Component::Client::AMQP::Queue
66 1 );
67  
68 =head1 USAGE
69  
70 =head2 create
71  
72 my $amq = POE::Component::Client::AMQP->create(
73 RemoteAddress => 'mq.domain.tld',
74 );
75  
76 Create a new AMQP client. Arguments to this method:
77  
78 =over 4
79  
80 =item I<RemoteAddress> (default: 127.0.0.1)
81  
82 Connect to this host
83  
84 =item I<RemotePort> (default: 5672)
85  
86 =item I<Username> (default: guest)
87  
88 =item I<Password> (default: guest)
89  
90 =item I<VirtualHost> (default: /)
91  
92 =item I<Logger> (default: simple screen logger)
93  
94 Provide an object which implements 'debug', 'info' and 'error' logging methods (such as L<Log::Log4perl>).
95  
96 =item I<Debug>
97  
98 This module provides extensive debugging options. These are specified as a hash as follows:
99  
100 =over 4
101  
102 =item I<logic> (boolean)
103  
104 Display decisions the code is making
105  
106 =item I<frame_input> (boolean)
107  
108 =item I<frame_output> (boolean)
109  
110 Use the I<frame_dumper> code to display frames that come in from or out to the server.
111  
112 =item I<frame_dumper> (coderef)
113  
114 A coderef which, given a L<Net::AMQP::Frame> object, will return a string representation of it, prefixed with "\n".
115  
116 =item I<raw_input> (boolean)
117  
118 =item I<raw_output> (boolean)
119  
120 Use the I<raw_dumper> code to display raw data that comes in from or out to the server.
121  
122 =item I<raw_dumper> (coderef)
123  
124 A coderef which, given a raw string, will return a byte representation of it, prefixed with "\n".
125  
126 =back
127  
128 =item I<Keepalive> (default: 0)
129  
130 If set, will send a L<Net::AMQP::Frame::Heartbeat> frame every Keepalive seconds after the last activity on the connection. This is a mechanism to keep a long-open TCP session alive.
131  
132 =item I<Alias> (default: amqp_client)
133  
134 The POE session alias of the main client session
135  
136 =item I<AliasTCP> (default: tcp_client)
137  
138 The POE session alias of the TCP client
139  
140 =item I<Callbacks> (default: {})
141  
142 Provide callbacks. At the moment, 'Startup' and 'FrameSent' are the only recognized callback.
143  
144 FrameSent will be called with $self and the Net::AMQP::Frame being sent.
145  
146 =item I<is_testing>
147  
148 Set to '1' to avoid creating POE::Sessions (mainly useful in t/ scripts)
149  
150 =back
151  
152 Returns a class object.
153  
154 =cut
155  
156 1 ▶sub create {
Subroutine create: called CC=10 SCAR=34.8
Pod documented
157 1 my $class = shift;
158  
159 1 my %self = validate_with(
160 params => \@_,
161 spec => {
162 RemoteAddress => { default => '127.0.0.1' },
163 RemotePort => 0,
164 Username => { default => 'guest' },
165 Password => { default => 'guest' },
166 VirtualHost => { default => '/' },
167  
168 Logger => 0,
169 Debug => { default => {} },
170  
171 Alias => { default => 'amqp_client' },
172 AliasTCP => { default => 'tcp_client' },
173 Callbacks => { default => {} },
174 SSL => { default => 0 },
175 Keepalive => { default => 0 },
176 Reconnect => { default => 0 },
177  
178 channels => { default => {} },
179 is_started => { default => 0 },
180 is_testing => { default => 0 },
181 is_stopped => { default => 0 },
182 frame_max => { default => 0 },
183 },
184 allow_extra => 1,
185 );
186  
187 1 ▶ $self{RemotePort} ||= $self{SSL} ? 5671 : 5672;
Branch: 1 branch
BranchTrueFalseTotal
$self{'SSL'} ? : 0 1 1
Condition33%1/3
$self{"RemotePort"} ||= $self{"SSL"} ? 5671 : 5672
l!l&&r!l&&!r
010
MC/DC0%0/2
$self{"RemotePort"} ||= $self{"SSL"} ? 5671 : 5672
$self{"RemotePort"} $self{"SSL"} ? 5671 : 5672
Truth table33%1/3
A ||= B
A= $self{"RemotePort"}B= $self{"SSL"} ? 5671 : 5672
ABresult
1X1
011
000
188  
189 $self{Logger} ||= POE::Component::Client::AMQP::FakeLogger->new(
190 1 ▶ debug => keys(%{ $self{Debug} }) ? 1 : 0,
Branch: 1 branch
BranchTrueFalseTotal
keys %{$self{'Debug'};} ? : 0 1 1
Condition33%1/3
$self{"Logger"} ||= "POE::Component::Client::AMQP::FakeLogger"->new("debug", keys %{$self{"Debug"};} ? 1 : 0)
l!l&&r!l&&!r
010
MC/DC0%0/2
$self{"Logger"} ||= "POE::Component::Client::AMQP::FakeLogger"->new("debug", keys %{$self{"Debug"};} ? 1 : 0)
$self{"Logger"} "POE::Component::Client::AMQP::FakeLogger"->new("debug", keys %{$self{"Debug"};} ? 1 : 0)
Truth table33%1/3
A ||= B
A= $self{"Logger"}B= "POE::Component::Client::AMQP::FakeLogger"->new("debug", keys %{$self{"Debug"};} ? 1 : 0)
ABresult
1X1
011
000
191 );
192  
193 1 my $self = bless \%self, $class;
194  
195 my %Debug = validate_with(
196 params => $self->{Debug},
197 spec => {
198 raw_input => 0,
199 raw_output => 0,
200 0 ▶ raw_dumper => { default => sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
201 0 my $output = shift;
202 0 return "\nraw [".length($output)."]: ".show_ascii($output);
203 } },
204  
205 frame_input => 0,
206 frame_output => 0,
207 0 ▶ frame_dumper => { default => sub {} },
Subroutine __ANON__: not called CC=1 SCAR=0.0
208  
209 1 logic => 0,
210 },
211 );
212 1 $self->{Debug} = \%Debug;
213  
214 POE::Session->create(
215 object_states => [
216 $self => [qw(
217 _start
218 server_send
219 server_connected
220 server_disconnect
221 shutdown
222 keepalive
223 )],
224 ],
225 1 ▶ ) unless $self->{is_testing};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"is_testing"} 0 1 1
226  
227 # If the user passed an arrayref as the RemoteAddress, pick one
228 # at random to connect to.
229 1 ▶ if (ref $self->{RemoteAddress}) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $self->{'RemoteAddress'}) { } 0 1 1
230 # Shuffle the RemoteAddress array (thanks http://community.livejournal.com/perl/101830.html)
231 0 my $array = $self->{RemoteAddress};
232 0 ▶ for (my $i = @$array; --$i; ) {
Branch: 1 branch
BranchTrueFalseTotal
if (--$i) 0 0 0
233 0 my $j = int rand ($i+1);
234 0 ▶ next if $i == $j;
Branch: 1 branch
BranchTrueFalseTotal
if $i == $j 0 0 0
235 0 @$array[$i,$j] = @$array[$j,$i];
236 }
237  
238 # Take the first shuffled address and move it to the back
239 0 $self->{current_RemoteAddress} = shift @{ $self->{RemoteAddress} };
240 0 push @{ $self->{RemoteAddress} }, $self->{current_RemoteAddress};
241 }
242 else {
243 1 $self->{current_RemoteAddress} = $self->{RemoteAddress};
244 }
245  
246 POE::Component::Client::AMQP::TCP->new(
247 Alias => $self->{AliasTCP},
248 RemoteAddress => $self->{current_RemoteAddress},
249 RemotePort => $self->{RemotePort},
250 0 ▶ Connected => sub { $self->tcp_connected(@_) },
Subroutine __ANON__: not called CC=1 SCAR=6.9
251 0 ▶ Disconnected => sub { $self->tcp_disconnected(@_) },
Subroutine __ANON__: not called CC=1 SCAR=6.9
252 0 ▶ ConnectError => sub { $self->tcp_connect_error(@_) },
Subroutine __ANON__: not called CC=1 SCAR=6.9
253 ConnectTimeout => 20,
254 0 ▶ ServerInput => sub { $self->tcp_server_input(@_) },
Subroutine __ANON__: not called CC=1 SCAR=6.9
255 0 ▶ ServerFlushed => sub { $self->tcp_server_flush(@_) },
Subroutine __ANON__: not called CC=1 SCAR=6.9
256 0 ▶ ServerError => sub { $self->tcp_server_error(@_) },
Subroutine __ANON__: not called CC=1 SCAR=6.9
257 Filter => 'POE::Filter::Stream',
258 SSL => $self->{SSL},
259 InlineStates => {
260 0 ▶ reconnect_delayed => sub { $self->tcp_reconnect_delayed(@_) },
Subroutine __ANON__: not called CC=1 SCAR=6.9
261 },
262 1 ▶ ) unless $self->{is_testing};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"is_testing"} 0 1 1
263  
264 1 return $self;
265 }
266  
267 ## Public Class Methods ###
268  
269 =head1 CLASS METHODS
270  
271 =head2 do_when_startup (...)
272  
273 =over 4
274  
275 Pass a subref that should be executed after the client has connected and authenticated with the remote AMQP server. If the client is already connected and authenticated, the subref will be called immediately. Think: deferred.
276  
277 =back
278  
279 =cut
280  
281 0 ▶sub do_when_startup {
Subroutine do_when_startup: not called CC=2 SCAR=17.9
Pod documented
282 0 my ($self, $subref) = @_;
283  
284 0 ▶ if ($self->{is_started}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'is_started'}) { } 0 0 0
285 0 $subref->();
286 }
287 else {
288 0 push @{ $self->{Callbacks}{Startup} }, $subref;
289 }
290 }
291  
292 =head2 channel ($id)
293  
294 =over 4
295  
296 Call with an optional argument $id (1 - 65536). Returns a L<POE::Component::Client::AMQP::Channel> object which can be used immediately.
297  
298 =back
299  
300 =cut
301  
302 0 ▶sub channel {
Subroutine channel: not called CC=4 SCAR=30.0
Pod documented
303 0 my ($self, $id, $opts) = @_;
304 0 ▶ $opts ||= {};
Condition0%0/2
$opts ||= {}
l!l
00
MC/DC0%0/1
$opts ||= {}
$opts
Truth table0%0/2
A
A= $opts
Aresult
11
00
305  
306 0 ▶ if (defined $id && $self->{channels}{$id}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $id and $self->{"channels"}{$id}) 0 0 0
Condition0%0/3
defined $id and $self->{"channels"}{$id}
!ll&&!rl&&r
000
MC/DC0%0/2
defined $id and $self->{"channels"}{$id}
defined $id $self->{"channels"}{$id}
Truth table0%0/3
A and B
A= defined $idB= $self->{"channels"}{$id}
ABresult
0X0
100
111
307 0 return $self->{channels}{$id};
308 }
309  
310 0 my $channel = POE::Component::Client::AMQP::Channel->create(
311 id => $id,
312 server => $self,
313 %$opts,
314 );
315  
316 # We don't need to record the channel, as the Channel->create() did so already in our 'channels' hash
317  
318 0 return $channel;
319 }
320  
321 =head2 run ()
322  
323 =over 4
324  
325 Shortcut to calling $poe_kernel->run
326  
327 =back
328  
329 =cut
330  
331 0 ▶sub run {
Subroutine run: not called CC=1 SCAR=6.9
Pod documented
332 0 $poe_kernel->run();
333 }
334  
335 =head2 stop ()
336  
337 =over 4
338  
339 Shortcut to calling the POE state 'disconnect'
340  
341 =back
342  
343 =cut
344  
345 0 ▶sub stop {
Subroutine stop: not called CC=1 SCAR=6.9
Pod documented
346 0 my $self = shift;
347 0 $poe_kernel->call($self->{Alias}, 'server_disconnect');
348 }
349  
350 =head2 compose_basic_publish ($payload, %options)
351  
352 =over 4
353  
354 A helper method to generate the frames necessary for a basic publish. Returns a L<Net::AMQP::Protocol::Basic::Publish>, L<Net::AMQP::Frame::Header> (wrapping a L<Net::AMQP::Protocol::Basic::ContentHeader> frame) followed by zero or more L<Net::AMQP::Frame::Body> frames. Since the arguments for each one of these frames are unique, the %options hash provides options for all of the frames.
355  
356 The following options are supported, all of which are optional, some having sane defaults:
357  
358 =over 4
359  
360 =item I<Header options>
361  
362 =over 4
363  
364 =item I<weight> (default: 0)
365  
366 =back
367  
368 =item I<Method options>
369  
370 =over 4
371  
372 =item I<ticket> (default: 0)
373  
374 =item I<exchange>
375  
376 =item I<routing_key>
377  
378 =item I<mandatory> (default: 1)
379  
380 =item I<immediate>
381  
382 =back
383  
384 =item I<Content options>
385  
386 =over 4
387  
388 =item I<content_type>
389  
390 =item I<content_encoding>
391  
392 =item I<headers> (default: {})
393  
394 =item I<delivery_mode> (default: 1)
395  
396 =item I<priority> (default: 1)
397  
398 =item I<correlation_id>
399  
400 =item I<reply_to>
401  
402 =item I<expiration>
403  
404 =item I<message_id>
405  
406 =item I<timestamp>
407  
408 =item I<type>
409  
410 =item I<user_id>
411  
412 =item I<app_id>
413  
414 =item I<cluster_id>
415  
416 =back
417  
418 =back
419  
420 =back
421  
422 =cut
423  
424 0 ▶sub compose_basic_publish {
Subroutine compose_basic_publish: not called CC=2 SCAR=17.9
Pod documented
425 0 my ($self, $payload) = (shift, shift);
426  
427 0 my %opts = validate(@_, {
428 # Header options
429 weight => { default => 0 },
430  
431 # Method options
432 ticket => { default => 0 },
433 exchange => 0,
434 routing_key => 0,
435 mandatory => { default => 1 },
436 immediate => 0,
437  
438 # Content options
439 content_type => 0,
440 content_encoding => 0,
441 headers => { default => {} },
442 delivery_mode => { default => 1 }, # non-persistent
443 priority => { default => 1 },
444 correlation_id => 0,
445 reply_to => 0,
446 expiration => 0,
447 message_id => 0,
448 timestamp => 0,
449 type => 0,
450 user_id => 0,
451 app_id => 0,
452 cluster_id => 0,
453 });
454  
455 0 my $payload_size = length $payload;
456 0 my @body_frames;
457 0 ▶ while (length $payload) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $payload) 0 0 0
458 0 my $partial = substr $payload, 0, $self->frame_max - 8, '';
459 0 push @body_frames, Net::AMQP::Frame::Body->new(payload => $partial);
460 }
461  
462 return (
463 Net::AMQP::Protocol::Basic::Publish->new(
464 0 map { $_ => $opts{$_} }
465 0 grep { defined $opts{$_} }
466 qw(ticket exchange routing_key mandatory immediate)
467 ),
468 Net::AMQP::Frame::Header->new(
469 weight => $opts{weight},
470 body_size => $payload_size,
471 header_frame => Net::AMQP::Protocol::Basic::ContentHeader->new(
472 0 map { $_ => $opts{$_} }
473 0 grep { defined $opts{$_} }
474 qw(content_type content_encoding headers delivery_mode priority correlation_id
475 reply_to expiration message_id timestamp type user_id app_id cluster_id)
476 ),
477 ),
478 @body_frames,
479 );
480 }
481  
482 =head1 POE STATES
483  
484 The following are states you can post to to interact with the client. Use the alias defined in the C<create()> call above.
485  
486 =cut
487  
488 0 ▶sub _start {
Subroutine _start: not called CC=1 SCAR=6.9
489 0 my ($self, $kernel) = @_[OBJECT, KERNEL];
490  
491 0 $kernel->alias_set($self->{Alias});
492 }
493  
494 =head2 server_disconnect
495  
496 =over 4
497  
498 Send a Connection.Close request
499  
500 =back
501  
502 =cut
503  
504 0 ▶sub server_disconnect {
Subroutine server_disconnect: not called CC=1 SCAR=6.9
Pod documented
505 0 my ($self, $kernel) = @_[OBJECT, KERNEL];
506  
507 0 $self->{is_stopping} = 1;
508  
509 # Don't defer my disconnect request just because we're waiting for the response to a synchronous method
510 0 $self->{wait_synchronous} = {};
511  
512 $kernel->yield(server_send =>
513 Net::AMQP::Frame::Method->new(
514 0 ▶ synchronous_callback => sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
515 0 $self->{is_stopped} = 1;
516 0 $self->{is_started} = 0;
517 },
518 0 method_frame => Net::AMQP::Protocol::Connection::Close->new(),
519 )
520 );
521 }
522  
523 0 ▶sub server_connected {
Subroutine server_connected: not called CC=3 SCAR=24.8
Pod undocumented
524 0 my ($self, $kernel) = @_[OBJECT, KERNEL];
525  
526 0 ▶ $self->{Logger}->info("Connected to the AMQP server ".($self->{SSL} ? '(over SSL) ' : '')."and ready to act");
Branch: 1 branch
BranchTrueFalseTotal
$self->{'SSL'} ? : 0 0 0
527  
528 0 $self->do_callback('Startup');
529  
530 0 $self->{is_started} = 1;
531  
532 0 ▶ if ($self->{Keepalive}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"Keepalive"}) 0 0 0
533 0 $kernel->delay(keepalive => $self->{Keepalive});
534 }
535 }
536  
537 =head2 server_send (@output)
538  
539 =over 4
540  
541 Pass one or more L<Net::AMQP::Frame> objects. For short hand, you may pass L<Net::AMQP::Protocol::Base> objects, which will be automatically wrapped in the appropriate frame type, with channel 0. These frames will be written to the server. In the case of L<Net::AMQP::Frame::Method> objects which are calling a synchronous method, the client will handle them one at a time, waiting until a synchronous method returns properly before sending further synchronous frames. This happens automatically.
542  
543 =back
544  
545 =cut
546  
547 0 ▶sub server_send {
Subroutine server_send: not called CC=18 SCAR=58.3
Pod documented
548 0 my ($self, $kernel, @output) = @_[OBJECT, KERNEL, ARG0 .. $#_];
549  
550 0 ▶ if ($self->{is_stopped}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"is_stopped"}) 0 0 0
551 0 $self->{Logger}->error("Server send called while stopped with ".int(@output)." messages");
552 0 push @{ $self->{pending_server_send} }, @output;
553 # FIXME: nothing is currently done with this pending server send queue; users can choose
554 # to resend them in their Reconnected callback
555 0 return;
556 }
557  
558 0 ▶ while (my $output = shift @output) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $output = shift @output) 0 0 0
559 0 ▶ if (! defined $output || ! ref $output) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $output and ref $output) 0 0 0
Condition0%0/3
defined $output and ref $output
!ll&&!rl&&r
000
MC/DC0%0/2
defined $output and ref $output
defined $output ref $output
Truth table0%0/3
A and B
A= defined $outputB= ref $output
ABresult
0X0
100
111
560 0 ▶ $self->{Logger}->error("Server send called with invalid output (".(defined $output ? $output : 'undef').")");
Branch: 1 branch
BranchTrueFalseTotal
defined $output ? : 0 0 0
561 0 next;
562 }
563  
564 0 ▶ if ($output->isa("Net::AMQP::Protocol::Base")) {
Branch: 1 branch
BranchTrueFalseTotal
if ($output->isa("Net::AMQP::Protocol::Base")) 0 0 0
565 0 $output = $output->frame_wrap;
566 }
567  
568 0 ▶ if (! $output->isa("Net::AMQP::Frame")) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($output->isa("Net::AMQP::Frame")) 0 0 0
569 0 $self->{Logger}->error("Server send called with invalid output (".ref($output).")");
570 0 next;
571 }
572  
573 # Set default channel
574 0 ▶ $output->channel(0) unless defined $output->channel;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $output->channel 0 0 0
575  
576 0 ▶ if ($output->isa('Net::AMQP::Frame::Method') && $output->method_frame->method_spec->{synchronous}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($output->isa("Net::AMQP::Frame::Method") and $output->method_frame->method_spec->{"synchronous"}) 0 0 0
Condition0%0/3
$output->isa("Net::AMQP::Frame::Method") and $output->method_frame->method_spec->{"synchronous"}
!ll&&!rl&&r
000
MC/DC0%0/2
$output->isa("Net::AMQP::Frame::Method") and $output->method_frame->method_spec->{"synchronous"}
$output->isa("Net::AMQP::Frame::Method") $output->method_frame->method_spec->{"synchronous"}
Truth table0%0/3
A and B
A= $output->isa("Net::AMQP::Frame::Method")B= $output->method_frame->method_spec->{"synchronous"}
ABresult
0X0
100
111
577 # If we're calling a synchronous method, then the server won't send any other
578 # synchronous replies of particular type(s) until this message is replied to.
579 # Wait for replies of these type(s) and don't send other messages until they're
580 # cleared.
581  
582 0 my $output_class = ref($output->method_frame);
583  
584 0 ▶ $self->{wait_synchronous}{ $output->channel } ||= {};
Condition0%0/2
$self->{"wait_synchronous"}{$output->channel} ||= {}
l!l
00
MC/DC0%0/1
$self->{"wait_synchronous"}{$output->channel} ||= {}
$self->{"wait_synchronous"}{$output->channel}
Truth table0%0/2
A
A= $self->{"wait_synchronous"}{$output->channel}
Aresult
11
00
585 0 my $wait_synchronous = $self->{wait_synchronous}{ $output->channel };
586  
587 # FIXME: It appears that RabbitMQ won't let us do two disimilar synchronous requests at once
588 0 ▶ if (my @waiting_classes = keys %$wait_synchronous) {
Branch: 1 branch
BranchTrueFalseTotal
if (my(@waiting_classes) = keys %$wait_synchronous) 0 0 0
589 $self->{Logger}->debug("Class $waiting_classes[0] is already waiting; do nothing else until it's complete; defering")
590 0 ▶ if $self->{Debug}{logic};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"Debug"}{"logic"} 0 0 0
591 0 push @{ $wait_synchronous->{ $waiting_classes[0] }{process_after} }, [ $output, @output ];
592 0 return;
593 }
594  
595 # if ($self->{wait_synchronous}{$output_class}) {
596 # # There are already other things waiting; enqueue this output
597 # $self->{Logger}->debug("Class $output_class is already synchronously waiting; defering this and subsequent output")
598 # if $self->{Debug}{logic};
599 # push @{ $self->{wait_synchronous}{$output_class}{process_after} }, [ $output, @output ];
600 # return;
601 # }
602  
603 0 my $responses = $output_class->method_spec->{responses};
604  
605 0 ▶ if (keys %$responses) {
Branch: 1 branch
BranchTrueFalseTotal
if (keys %$responses) 0 0 0
606 $self->{Logger}->debug("Setting up synchronous callback for $output_class")
607 0 ▶ if $self->{Debug}{logic};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"Debug"}{"logic"} 0 0 0
608 0 $wait_synchronous->{$output_class} = {
609 request => $output,
610 responses => $responses,
611 process_after => [],
612 };
613 }
614 }
615  
616 0 my $raw_output = $output->to_raw_frame();
617 $self->{Logger}->debug(
618 'chan(' . $output->channel . ") >>> ".$output->type_string
619 . ($self->{Debug}{frame_output} ? $self->{Debug}{frame_dumper}($output) : '')
620 0 ▶ . ($self->{Debug}{raw_output} ? $self->{Debug}{raw_dumper}($raw_output) : '')
Branch: 2 branches
BranchTrueFalseTotal
$self->{'Debug'}{'frame_output'} ? : 0 0 0
$self->{'Debug'}{'raw_output'} ? : 0 0 0
621 );
622  
623 0 $self->{HeapTCP}{server}->put($raw_output);
624 0 $self->{last_server_put} = time;
625 0 $self->do_callback('FrameSent', $output);
626 }
627 }
628  
629 =head2 shutdown ()
630  
631 =over 4
632  
633 If you need to stop things immediately, call shutdown(). This is not graceful.
634  
635 =back
636  
637 =cut
638  
639 0 ▶sub shutdown {
Subroutine shutdown: not called CC=1 SCAR=6.9
Pod documented
640 0 my ($self, $kernel) = @_[OBJECT, KERNEL];
641  
642 0 $self->{is_stopped} = 1;
643  
644 # Clear any alarms that may be set ('keepalive', for instance)
645 0 $poe_kernel->alarm_remove_all();
646  
647 0 $kernel->call($self->{AliasTCP}, 'shutdown');
648 }
649  
650 =head2 keepalive
651  
652 Sends a Heartbeat frame at a regular interval to keep the TCP session from timing out.
653  
654 =cut
655  
656 0 ▶sub keepalive {
Subroutine keepalive: not called CC=3 SCAR=24.8
Pod documented
657 0 my ($self, $kernel) = @_[OBJECT, KERNEL];
658  
659 0 ▶ return unless $self->{Keepalive} > 0;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"Keepalive"} > 0 0 0 0
660  
661 0 my $idle_time = time - $self->{last_server_put};
662 0 my $delay = $self->{Keepalive};
663 0 ▶ if ($idle_time >= $self->{Keepalive}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($idle_time >= $self->{'Keepalive'}) { } 0 0 0
664 0 $kernel->yield(server_send =>
665 Net::AMQP::Frame::Heartbeat->new()
666 );
667 }
668 else {
669 0 $delay -= $idle_time;
670 }
671  
672 0 $kernel->delay(keepalive => $delay);
673 }
674  
675 ## Private Class Methods ###
676  
677 0 ▶sub tcp_connected {
Subroutine tcp_connected: not called CC=2 SCAR=17.9
Pod undocumented
678 0 my $self = shift;
679 0 my ($kernel, $heap) = @_[KERNEL, HEAP];
680  
681 0 $self->{Logger}->debug("Connected to remote host");
682  
683 #$self->{Logger}->debug("Sending 4.2.2 Protocol Header");
684 0 $heap->{server}->put( Net::AMQP::Protocol->header );
685  
686 # If 'reconnect_attempt' has a value, we have reconnected
687 0 ▶ if ($self->{reconnect_attempt}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"reconnect_attempt"}) 0 0 0
688 0 $self->{reconnect_attempt} = 0;
689 0 $self->do_callback('Reconnected');
690 }
691  
692 0 $self->{HeapTCP} = $heap;
693 0 $self->{is_stopped} = 0;
694 }
695  
696 0 ▶sub tcp_server_flush {
Subroutine tcp_server_flush: not called CC=1 SCAR=6.9
Pod undocumented
697 0 my $self = shift;
698 0 my ($kernel, $heap) = @_[KERNEL, HEAP];
699  
700 #$self->{Logger}->debug("Server flush");
701 }
702  
703 0 ▶sub tcp_server_input {
Subroutine tcp_server_input: not called CC=25 SCAR=64.8
Pod undocumented
704 0 my $self = shift;
705 0 my ($kernel, $heap, $input) = @_[KERNEL, HEAP, ARG0];
706  
707 # FIXME: Not every record is complete; it may be split at 16384 bytes
708 # FIXME: Checking last octet is not best; find better way!
709 0 my $frame_end_octet = unpack 'C', substr $input, -1, 1;
710 0 ▶ if ($frame_end_octet != 206) {
Branch: 2 branches
BranchTrueFalseTotal
if ($frame_end_octet != 206) { } 0 0 0
elsif (defined $self->{'buffered_input'}) { } 0 0 0
711 0 $self->{Logger}->debug("Server input length ".length($input)." without frame end octet");
712 0 ▶ $self->{buffered_input} = '' unless defined $self->{buffered_input};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $self->{"buffered_input"} 0 0 0
713 0 $self->{buffered_input} .= $input;
714 0 return;
715 }
716 elsif (defined $self->{buffered_input}) {
717 0 $input = delete($self->{buffered_input}) . $input;
718 }
719  
720 $self->{Logger}->debug("Server said: " . $self->{Debug}{raw_dumper}($input))
721 0 ▶ if $self->{Debug}{raw_input};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"Debug"}{"raw_input"} 0 0 0
722  
723 0 my @frames = Net::AMQP->parse_raw_frames(\$input);
724 FRAMES:
725 0 foreach my $frame (@frames) {
726 $self->{Logger}->debug(
727 'chan(' . $frame->channel . ") <<< ".$frame->type_string
728 0 ▶ . ($self->{Debug}{frame_input} ? $self->{Debug}{frame_dumper}($frame) : '')
Branch: 1 branch
BranchTrueFalseTotal
$self->{'Debug'}{'frame_input'} ? : 0 0 0
729 );
730  
731 0 my $handled = 0;
732 0 ▶ if ($frame->channel != 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($frame->channel != 0) 0 0 0
733 0 my $channel = $self->{channels}{ $frame->channel };
734 0 ▶ if (! $channel) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($channel) 0 0 0
735 0 $self->{Logger}->error("Received frame on channel ".$frame->channel." which we didn't request the creation of");
736 0 next FRAMES;
737 }
738 0 $kernel->post($channel->{Alias}, server_input => $frame);
739 0 $handled++;
740 }
741  
742 0 ▶ if ($frame->isa('Net::AMQP::Frame::Method')) {
Branch: 1 branch
BranchTrueFalseTotal
if ($frame->isa("Net::AMQP::Frame::Method")) 0 0 0
743 0 my $method_frame = $frame->method_frame;
744  
745 # Check the 'wait_synchronous' hash to see if this response is a synchronous reply
746 0 my $method_frame_class = ref $method_frame;
747 0 ▶ if ($method_frame_class->method_spec->{synchronous}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($method_frame_class->method_spec->{"synchronous"}) 0 0 0
748 0 ▶ $self->{Logger}->debug("Checking 'wait_synchronous' hash against $method_frame_class") if $self->{Debug}{logic};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"Debug"}{"logic"} 0 0 0
749  
750 0 my $matching_output_class;
751 0 ▶ while (my ($output_class, $details) = each %{ $self->{wait_synchronous}{ $frame->channel } }) {
Branch: 1 branch
BranchTrueFalseTotal
if (() = each %{$self->{"wait_synchronous"}{$frame->channel};}) 0 0 0
752 0 ▶ next unless $details->{responses}{ $method_frame_class };
Branch: 1 branch
BranchTrueFalseTotal
unless $details->{"responses"}{$method_frame_class} 0 0 0
753 0 $matching_output_class = $output_class;
754 0 last;
755 }
756  
757 0 ▶ if ($matching_output_class) {
Branch: 1 branch
BranchTrueFalseTotal
if ($matching_output_class) 0 0 0
758 $self->{Logger}->debug("Response type '$method_frame_class' found from waiting request '$matching_output_class'")
759 0 ▶ if $self->{Debug}{logic};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"Debug"}{"logic"} 0 0 0
760  
761 0 my $details = delete $self->{wait_synchronous}{ $frame->channel }{$matching_output_class};
762  
763 # Call the asynch callback if there is one
764 0 ▶ if (my $callback = delete $details->{request}{synchronous_callback}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $callback = delete $details->{"request"}{"synchronous_callback"}) 0 0 0
765 0 ▶ $self->{Logger}->debug("Calling $matching_output_class callback") if $self->{Debug}{logic};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"Debug"}{"logic"} 0 0 0
766 0 $callback->($frame);
767 }
768  
769 # Dequeue anything that was blocked by this
770 0 foreach my $output (@{ $details->{process_after} }) {
771 0 ▶ $self->{Logger}->debug("Dequeueing items that blocked due to '$method_frame_class'") if $self->{Debug}{logic};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"Debug"}{"logic"} 0 0 0
772 0 $kernel->post($self->{Alias}, server_send => @$output);
773 }
774  
775 # Consider this frame handled
776 0 $handled++;
777 }
778 }
779  
780 # Act upon connection-level methods
781 0 ▶ if (! $handled && $frame->channel == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $handled and $frame->channel == 0) 0 0 0
Condition0%0/3
not $handled and $frame->channel == 0
!ll&&!rl&&r
000
MC/DC0%0/2
not $handled and $frame->channel == 0
not $handled $frame->channel == 0
Truth table0%0/3
not(A) and B
A= not $handledB= $frame->channel == 0
ABresult
0X0
100
111
782 0 ▶ if ($method_frame->isa('Net::AMQP::Protocol::Connection::Start')) {
Branch: 2 branches
BranchTrueFalseTotal
if ($method_frame->isa('Net::AMQP::Protocol::Connection::Start')) { } 0 0 0
elsif ($method_frame->isa('Net::AMQP::Protocol::Connection::Tune')) { } 0 0 0
783 $kernel->post($self->{Alias}, server_send =>
784 Net::AMQP::Protocol::Connection::StartOk->new(
785 client_properties => {
786 platform => 'Perl/POE',
787 product => __PACKAGE__,
788 information => 'http://code.xmission.com/',
789 version => $VERSION,
790 },
791 mechanism => 'AMQPLAIN', # TODO - ensure this is in $method_frame{mechanisms}
792 response => { LOGIN => $self->{Username}, PASSWORD => $self->{Password} },
793 0 locale => 'en_US',
794 ),
795 );
796 0 $handled++;
797 }
798 elsif ($method_frame->isa('Net::AMQP::Protocol::Connection::Tune')) {
799 0 $self->{frame_max} = $method_frame->frame_max;
800 $kernel->post($self->{Alias}, server_send =>
801 Net::AMQP::Protocol::Connection::TuneOk->new(
802 channel_max => 0,
803 frame_max => $method_frame->frame_max,
804 heartbeat => 0,
805 ),
806 Net::AMQP::Frame::Method->new(
807 0 ▶ synchronous_callback => sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
808 0 $kernel->post($self->{Alias}, 'server_connected');
809 },
810 method_frame => Net::AMQP::Protocol::Connection::Open->new(
811 virtual_host => $self->{VirtualHost},
812 0 capabilities => '',
813 insist => 1,
814 ),
815 ),
816 );
817 0 $handled++;
818 }
819 }
820 }
821  
822 0 ▶ if (! $handled) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($handled) 0 0 0
823 0 $self->{Logger}->error("Unhandled input frame ".ref($frame));
824 }
825 }
826 }
827  
828 0 ▶sub tcp_server_error {
Subroutine tcp_server_error: not called CC=4 SCAR=30.0
Pod undocumented
829 0 my $self = shift;
830 0 my ($kernel, $heap, $name, $num, $string) = @_[KERNEL, HEAP, ARG0, ARG1, ARG2];
831  
832 # Normal disconnection
833 0 ▶ if ($name eq 'read' && $num == 0 && $self->{is_stopping}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($name eq "read" and $num == 0 and $self->{"is_stopping"}) 0 0 0
Condition0%0/6
$name eq "read" and $num == 0 and $self->{"is_stopping"}
!ll&&!rl&&r
000
$name eq "read" and $num == 0
!ll&&!rl&&r
000
MC/DC0%0/3
$name eq "read" and $num == 0 and $self->{"is_stopping"}
$name eq "read" $num == 0 $self->{"is_stopping"}
Truth table0%0/4
A and B and C
A= $name eq "read"B= $num == 0C= $self->{"is_stopping"}
ABCresult
0XX0
10X0
1100
1111
834 0 return;
835 }
836  
837 0 $self->{Logger}->error("TCP error: $name (num: $num, string: $string)");
838 }
839  
840 0 ▶sub tcp_connect_error {
Subroutine tcp_connect_error: not called CC=2 SCAR=17.9
Pod undocumented
841 0 my $self = shift;
842 0 my ($kernel, $heap, $name, $num, $string) = @_[KERNEL, HEAP, ARG0, ARG1, ARG2];
843  
844 0 $self->{Logger}->error("TCP connect error: $name (num: $num, string: $string)");
845 0 ▶ $kernel->post($self->{AliasTCP}, 'reconnect_delayed') if $self->{Reconnect};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"Reconnect"} 0 0 0
846 }
847  
848 0 ▶sub tcp_disconnected {
Subroutine tcp_disconnected: not called CC=3 SCAR=24.8
Pod undocumented
849 0 my $self = shift;
850 0 my ($kernel, $heap) = @_[KERNEL, HEAP];
851  
852 0 $self->{Logger}->error("TCP connection is disconnected");
853  
854 # The flag 'is_stopping' will be 1 if server_disconnect was explicitly called
855 0 ▶ return if $self->{is_stopping};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"is_stopping"} 0 0 0
856  
857 # We are here due to an error; we should record that we're stopped, and try and reconnect
858 0 $self->{is_stopped} = 1;
859 0 $self->{is_started} = 0;
860 0 $self->{wait_synchronous} = {};
861  
862 0 ▶ if ($self->{Reconnect}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"Reconnect"}) 0 0 0
863 0 $kernel->post($self->{AliasTCP}, 'reconnect_delayed');
864 }
865  
866 0 $self->do_callback('Disconnected');
867 }
868  
869 0 ▶sub tcp_reconnect_delayed {
Subroutine tcp_reconnect_delayed: not called CC=3 SCAR=24.8
Pod undocumented
870 0 my $self = shift;
871 0 my ($kernel, $heap) = @_[KERNEL, HEAP];
872  
873 0 ▶ return unless $self->{Reconnect};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"Reconnect"} 0 0 0
874  
875 # Pick a new RemoteAddress if there's more than one
876 0 ▶ if (ref $self->{RemoteAddress}) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $self->{"RemoteAddress"}) 0 0 0
877 0 $self->{current_RemoteAddress} = shift @{ $self->{RemoteAddress} };
878 0 push @{ $self->{RemoteAddress} }, $self->{current_RemoteAddress};
879 }
880  
881 0 my $delay = 2 ** ++$self->{reconnect_attempt};
882 0 $self->{Logger}->info("Reconnecting to '$$self{current_RemoteAddress}' in $delay sec");
883  
884 # This state is in the TCP session, so we can call 'reconnect' directly
885 0 $kernel->delay('reconnect', $delay, $self->{current_RemoteAddress}, $self->{RemotePort});
886 }
887  
888 0 ▶sub do_callback {
Subroutine do_callback: not called CC=3 SCAR=24.8
Pod undocumented
889 0 my ($self, $callback, @args) = @_;
890  
891 0 ▶ return unless $self->{Callbacks}{$callback};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"Callbacks"}{$callback} 0 0 0
892 0 foreach my $subref (@{ $self->{Callbacks}{$callback} }) {
893 0 $subref->($self, @args);
894 }
895 0 return;
896 }
897  
898 {
899 package POE::Component::Client::AMQP::FakeLogger;
900  
901 1 ▶ use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
902 1 ▶ use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
903  
904 1 ▶ sub new {
Subroutine new: called CC=1 SCAR=0.0
905 1 my ($class, %self) = @_;
906 1 return bless \%self, $class;
907 }
908  
909 0 ▶ sub info { shift->log_it('INFO', @_) }
Subroutine info: not called CC=1 SCAR=6.9
910 0 ▶ sub error { shift->log_it('ERROR', @_) }
Subroutine error: not called CC=1 SCAR=6.9
911 0 ▶ sub debug { shift->log_it('DEBUG', @_) }
Subroutine debug: not called CC=1 SCAR=6.9
912  
913 0 ▶ sub log_it {
Subroutine log_it: not called CC=3 SCAR=24.8
914 0 my ($self, $method, $message) = @_;
915 0 ▶ return if $method eq 'DEBUG' && ! $self->{debug};
Branch: 1 branch
BranchTrueFalseTotal
if $method eq "DEBUG" and not $self->{"debug"} 0 0 0
Condition0%0/3
$method eq "DEBUG" and not $self->{"debug"}
!ll&&!rl&&r
000
MC/DC0%0/2
$method eq "DEBUG" and not $self->{"debug"}
$method eq "DEBUG" not $self->{"debug"}
Truth table0%0/3
A and not(B)
A= $method eq "DEBUG"B= not $self->{"debug"}
ABresult
0X0
100
111
916 0 chomp $message;
917 0 print '[' . localtime(time) ."] $method: $message\n";
918 }
919 }
920  
921 =head1 SEE ALSO
922  
923 L<POE>, L<Net::AMQP>
924  
925 =head1 DEVELOPMENT
926  
927 This module is being developed via a git repository publicly avaiable at http://github.com/ewaters/poe-component-client-amqp. I encourage anyone who is interested to fork my code and contribute bug fixes or new features, or just have fun and be creative.
928  
929 =head1 COPYRIGHT
930  
931 Copyright (c) 2009 Eric Waters and XMission LLC (http://www.xmission.com/). All rights reserved. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
932  
933 The full text of the license can be found in the LICENSE file included with this module.
934  
935 =head1 AUTHOR
936  
937 Eric Waters <ewaters@gmail.com>
938  
939 =cut
940  
941 1 1;
« AMQP/Channel.pm ↑ Summary AMQP/Queue.pm »