Client/Bayeux.pm

filter: Statementstmt 100% 9 / 9 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 3 / 3 Podpod n/a totaltotal 100% 12 / 12 CC 1 SCAR 0.0
CC
1
Cov
100%
BEGIN
1.0
BEGIN
1.0
BEGIN
1.0
CRAP 1.0
« Server/Bayeux/Message/Invalid.pm ↑ Summary
1 package POE::Component::Client::Bayeux;
2  
3 =head1 NAME
4  
5 POE::Component::Client::Bayeux - Bayeux/cometd client implementation in POE
6  
7 =head1 SYNOPSIS
8  
9 use POE qw(Component::Client::Bayeux);
10  
11 POE::Component::Client::Bayeux->spawn(
12 Host => '127.0.0.1',
13 Alias => 'comet',
14 );
15  
16 POE::Session->create(
17 inline_states => {
18 _start => sub {
19 my ($kernel, $heap) = @_[KERNEL, HEAP];
20 $kernel->alias_set('my_client');
21  
22 $kernel->post('comet', 'init');
23 $kernel->post('comet', 'subscribe', '/chat/demo', 'events');
24 $kernel->post('comet', 'publish', '/chat/demo', {
25 user => "POE",
26 chat => "POE has joined",
27 join => JSON::XS::true,
28 });
29 },
30 events => sub {
31 my ($kernel, $heap, $message) = @_[KERNEL, HEAP, ARG0];
32  
33 print STDERR "Client got subscribed message:\n" . Dumper($message);
34 },
35 },
36 );
37  
38 $poe_kernel->run();
39  
40 =head1 DESCRIPTION
41  
42 This module implements the Bayeux Protocol (1.0draft1) from the Dojo Foundation.
43 Also called cometd, Bayeux is a low-latency routing protocol for JSON encoded
44 events between clients and servers in a publish-subscribe model.
45  
46 This is the client implementation. It is not feature complete, but works at the
47 moment for testing a Bayeux server.
48  
49 =cut
50  
51 3 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
52 3 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
53 3 ▶use POE qw(Component::Client::HTTP Component::Client::Bayeux::Transport);
Subroutine BEGIN: called CC=1 SCAR=0.0
54 use Params::Validate;
55 use Data::Dumper;
56 use JSON::Any;
57 use Data::UUID;
58 use HTTP::Request::Common;
59 use Log::Log4perl qw(get_logger :levels);
60 use Log::Log4perl::Appender;
61 use Log::Log4perl::Layout;
62  
63 use POE::Component::Client::Bayeux::Utilities qw(decode_json_response);
64 use POE::Component::Server::Bayeux::Utilities qw(channel_match);
65  
66 use base qw(Class::Accessor Exporter);
67 __PACKAGE__->mk_accessors(qw(session clientId logger));
68  
69 our @EXPORT_OK = qw(decode_json_response);
70  
71 my $protocol_version = '1.0';
72 our $VERSION = '0.03';
73  
74 =head1 USAGE
75  
76 =head2 spawn (...)
77  
78 =over 4
79  
80 Create a new Bayeux client. Arguments to this method:
81  
82 =over 4
83  
84 =item I<Host> (required)
85  
86 Connect to this host.
87  
88 =item I<Port> (default: 80)
89  
90 Connect to this port.
91  
92 =item I<SSL> (default: 0)
93  
94 Use SSL on connection
95  
96 =item I<Alias> (default: 'bayeux_client')
97  
98 The POE session alias for local sessions to interact with.
99  
100 =item I<Debug> (default: 0)
101  
102 Either 0 or 1, indicates level of logging.
103  
104 =item I<LogFile> (default: undef)
105  
106 Logfile to write output to.
107  
108 =item I<LogStdout> (default: 1)
109  
110 If false, no logger output to STDOUT.
111  
112 =item I<CrossDomain> (not implemented)
113  
114 Enables cross domain protocol of messaging.
115  
116 =item I<ErrorCallback> (default: none)
117  
118 Provide a coderef that will receive a message hashref of any failed messages (erorrs in protocol, or simply unhandled messages).
119  
120 =back
121  
122 Returns a class object with methods of interest:
123  
124 =over 4
125  
126 =item I<session>
127  
128 The L<POE::Session> object returned from an internal create() call.
129  
130 =back
131  
132 =back
133  
134 =cut
135  
136 sub spawn {
137 my $class = shift;
138 my %args = validate(@_, {
139 Host => 1,
140 Port => { default => 80 },
141 Path => { default => '/cometd' },
142 SSL => { default => 0 },
143 Alias => { default => 'bayeux_client' },
144 CrossDomain => { default => 0 },
145 Debug => { default => 0 },
146 ErrorCallback => 0,
147 LogFile => 0,
148 LogStdout => { default => 1 },
149 });
150  
151 if ($args{CrossDomain}) {
152 # TODO
153 die __PACKAGE__ . " doesn't yet support cross domain protocol.\n";
154 }
155  
156 my $ua_alias = $args{Alias} . '_ua';
157 my $cometd_url = sprintf 'http%s://%s:%s%s',
158 ($args{SSL} ? 's' : ''), $args{Host}, $args{Port}, $args{Path};
159  
160 POE::Component::Client::HTTP->spawn(
161 Alias => $ua_alias,
162 );
163  
164 my $self = bless { %args }, $class;
165  
166 my $session = POE::Session->create(
167 inline_states => {
168 _start => \&client_start,
169 _stop => \&client_stop,
170 shutdown => \&client_shutdown,
171  
172 # Public methods
173 init => \&init,
174 publish => \&publish,
175 subscribe => \&subscribe,
176 unsubscribe => \&unsubscribe,
177 disconnect => \&disconnect,
178 reconnect => \&reconnect,
179  
180 # Internal
181 handshake => \&handshake,
182 handshake_response => \&handshake_response,
183 send_message => \&send_message,
184 ua_response => \&ua_response,
185 deliver => \&deliver,
186 flush_queue => \&flush_queue,
187 send_transport => \&send_transport,
188 },
189 heap => {
190 args => \%args,
191 ua => $ua_alias,
192 remote_url => $cometd_url,
193 json => JSON::Any->new(),
194 uuid => Data::UUID->new(),
195 subscriptions => {},
196 client => $self,
197 },
198 ($ENV{POE_DEBUG} ? (
199 options => { trace => 1, debug => 1 },
200 ) : ()),
201 );
202  
203 # Setup logger
204 my $logger = Log::Log4perl->get_logger('bayeux_client');
205 {
206 my $logger_layout = Log::Log4perl::Layout::PatternLayout->new("[\%d] \%p: \%m\%n");
207 $logger->level($args{Debug} ? $DEBUG : $INFO);
208  
209 if ($args{LogFile}) {
210 my $file_appender = Log::Log4perl::Appender->new(
211 'Log::Log4perl::Appender::File',
212 name => 'filelog',
213 filename => $args{LogFile},
214 );
215 $file_appender->layout( $logger_layout );
216 $logger->add_appender($file_appender);
217 }
218 if ($args{LogStdout}) {
219 my $stdout_appender = Log::Log4perl::Appender->new(
220 'Log::Log4perl::Appender::Screen',
221 name => 'screenlog',
222 stderr => 0,
223 );
224 $stdout_appender->layout($logger_layout);
225 $logger->add_appender($stdout_appender);
226 }
227 }
228  
229 $self->{logger} = $logger;
230 $self->{session} = $session->ID;
231 return $self;
232 }
233  
234 sub client_start {
235 my ($kernel, $heap) = @_[KERNEL, HEAP];
236  
237 $kernel->alias_set( $heap->{args}{Alias} );
238  
239 if ($ENV{POE_DEBUG}) {
240 $kernel->alias_resolve($heap->{ua})->option( trace => 1, debug => 1 );
241 }
242 }
243  
244 sub client_stop {
245 my ($kernel, $heap) = @_[KERNEL, HEAP];
246 }
247  
248 sub client_shutdown {
249 my ($kernel, $heap) = @_[KERNEL, HEAP];
250  
251 $heap->{_shutdown} = 1;
252  
253 $kernel->call( $heap->{ua}, 'shutdown' );
254  
255 if ($heap->{transport}) {
256 $kernel->call( $heap->{transport}, 'shutdown' );
257 }
258  
259 $kernel->alias_remove( $heap->{args}{Alias} );
260 }
261  
262 ## Public States ###
263  
264 =head1 POE STATES
265  
266 The following are states you can post to to interact with the client.
267  
268 =head2 init ()
269  
270 =over 4
271  
272 Initializes the client, connecting to the server, and sets up long polling.
273  
274 =back
275  
276 =cut
277  
278 sub init {
279 my ($kernel, $heap) = @_[KERNEL, HEAP];
280  
281 $kernel->yield('handshake');
282 }
283  
284  
285 sub handshake {
286 my ($kernel, $heap, %ext) = @_[KERNEL, HEAP, ARG0 .. $#_];
287  
288 my %handshake = (
289 channel => '/meta/handshake',
290 version => $protocol_version,
291 minimumVersion => $protocol_version,
292 supportedConnectionTypes => [ 'long-polling' ],
293 ext => {
294 'json-comment-filtered' => 1,
295 %ext,
296 }
297 );
298  
299 $kernel->yield('send_message', 'handshake_response', \%handshake);
300  
301 # Unsubscribe from all TODO
302  
303 $heap->{_initialized} = 1;
304 $heap->{_connected} = 0;
305 }
306  
307 =head2 publish ($channel, $message)
308  
309 =over 4
310  
311 Publishes arbitrary message to the channel given. Message will have 'clientId'
312 and 'id' fields auto-populated.
313  
314 =back
315  
316 =cut
317  
318 sub publish {
319 my ($kernel, $heap, $channel, $message) = @_[KERNEL, HEAP, ARG0, ARG1];
320  
321 $kernel->call($_[SESSION], 'send_transport', {
322 channel => $channel,
323 data => $message,
324 });
325 }
326  
327 =head2 subscribe ($channel, $callback)
328  
329 =over 4
330  
331 Subscribes client to the channel given. Callback can either be a coderef or
332 the name of a state in the calling session. Callback will get one arg, the
333 message that was posted to the channel subscribed to.
334  
335 =back
336  
337 =cut
338  
339 sub subscribe {
340 my ($kernel, $heap, $channel, $callback) = @_[KERNEL, HEAP, ARG0, ARG1];
341  
342 return if $heap->{subscriptions}{$channel}
343 && $heap->{subscriptions}{$channel}{callback} eq $callback
344 && $heap->{subscriptions}{$channel}{session} eq $_[SENDER];
345  
346 $heap->{subscriptions}{$channel} = {
347 callback => $callback,
348 session => $_[SENDER],
349 };
350  
351 $kernel->call($_[SESSION], 'send_transport', {
352 channel => '/meta/subscribe',
353 subscription => $channel,
354 });
355 }
356  
357 =head2 unsubscribe ($channel)
358  
359 =over 4
360  
361 Unsubscribes from channel.
362  
363 =back
364  
365 =cut
366  
367 sub unsubscribe {
368 my ($kernel, $heap, $channel) = @_[KERNEL, HEAP, ARG0];
369  
370 delete $heap->{subscriptions}{$channel};
371  
372 $kernel->call($_[SESSION], 'send_transport', {
373 channel => '/meta/unsubscribe',
374 subscription => $channel,
375 });
376 }
377  
378 =head2 disconnect ()
379  
380 =over 4
381  
382 Sends a disconnect request.
383  
384 =back
385  
386 =cut
387  
388 sub disconnect {
389 my ($kernel, $heap) = @_[KERNEL, HEAP];
390  
391 $kernel->call($_[SESSION], 'send_transport', {
392 channel => '/meta/disconnect',
393 });
394 $heap->{_disconnect} = 1;
395 }
396  
397 =head2 reconnect ()
398  
399 =over 4
400  
401 Disconnect and reconnect
402  
403 =back
404  
405 =cut
406  
407 sub reconnect {
408 my ($kernel, $heap) = @_[KERNEL, HEAP];
409  
410 $kernel->call($_[SESSION], 'send_transport', {
411 channel => '/meta/disconnect',
412 });
413 $heap->{_reconnect} = 1;
414 }
415  
416 ## Internal Main States ###
417  
418 sub handshake_response {
419 my ($kernel, $heap, $session, $response) = @_[KERNEL, HEAP, SESSION, ARG0];
420  
421 if (! $response || ! ref $response || ! ref $response eq 'HASH') {
422 die "Invalid response from handshake\n";
423 }
424  
425 if ($response->{version} && $protocol_version < $response->{version}) {
426 die "Can't connect to server: version $$response{version} is > my supported version $protocol_version\n";
427 }
428  
429 if (! $response->{successful}) {
430 die "Unsuccessful handshake.\n" . Dumper($response);
431 }
432  
433 # Store client id for all future requests
434 $heap->{clientId} = $response->{clientId};
435 $heap->{client}->clientId( $heap->{clientId} );
436  
437 # Store advice
438 $heap->{advice} = $response->{advice} || {};
439  
440 # Choose a transport, build it, and ask it to connect
441 # TODO: make sure it's one of the returned supportedConnectionTypes
442  
443 $heap->{transport} = POE::Component::Client::Bayeux::Transport->spawn(
444 type => 'long-polling',
445 parent => $session,
446 parent_heap => $heap,
447 );
448  
449 $kernel->post($heap->{transport}, 'tunnelInit');
450 }
451  
452 sub deliver {
453 my ($kernel, $heap, $message) = @_[KERNEL, HEAP, ARG0];
454  
455 if (! $message || ! ref $message || ! ref $message eq 'HASH' || ! $message->{channel}) {
456 die "deliver(): Invalid message\n";
457 }
458  
459 # If the message has an id, see if I have a record of the instigating request
460 my $request;
461 if ($message->{id}) {
462 $request = delete $heap->{messages}{ $message->{id} };
463 }
464  
465 # Handle /meta/ channel responses
466 if (my ($meta_channel) = $message->{channel} =~ m{^/meta/(.+)$}) {
467 if ($meta_channel eq 'connect') {
468 if ($message->{successful} && ! $heap->{_connected}) {
469 $heap->{_connected} = 1;
470 }
471 elsif (! $heap->{_initialized}) {
472 $heap->{_connected} = 0;
473 }
474 $kernel->yield('flush_queue');
475 return;
476 }
477 }
478  
479 # Publishes to a non-private channel MAY yield a simple successful message. Ignore those.
480 if ($request && $request->{caller_state} eq 'publish'
481 && $message->{successful} && $message->{channel} !~ m{^/service/}) {
482 return;
483 }
484  
485 # Check if I have a subscription for the channel
486 my $matching_subscription;
487 foreach my $subscription (keys %{ $heap->{subscriptions} }) {
488 next unless channel_match($message->{channel}, $subscription);
489 $matching_subscription = $subscription;
490 last;
491 }
492  
493 # Call the callback if so for each subscription
494 if ($matching_subscription) {
495 my $sub_details = $heap->{subscriptions}{$matching_subscription};
496 if ($sub_details->{callback}) {
497 if (ref $sub_details->{callback}) {
498 $sub_details->{callback}($message, $heap);
499 return;
500 }
501 elsif ($_[SESSION] ne $sub_details->{session}) {
502 $kernel->post( $sub_details->{session}, $sub_details->{callback}, $message, $heap );
503 return;
504 }
505 }
506 }
507  
508 # Call generic callback for all non-successful messages
509 if (defined $message->{successful} && ! $message->{successful} && $heap->{args}{ErrorCallback}) {
510 $heap->{args}{ErrorCallback}($message);
511 }
512  
513 $heap->{client}->logger->debug("deliver() couldn't handle message:\n" . Dumper($message));
514 }
515  
516 ## Utilities ###
517  
518 sub send_message {
519 my ($kernel, $heap, $callback_state, @args) = @_[KERNEL, HEAP, ARG0 .. $#_];
520  
521 $heap->{client}->logger->debug(" >>> Pre-transport >>>\n" . Dumper(\@args));
522  
523 # Create an HTTP POST request, encoding the args into JSON
524 my $request = POST $heap->{remote_url}, [ message => $heap->{json}->encode(\@args) ];
525  
526 # Create a UUID so I can collect meta info about this request
527 my $uuid = $heap->{uuid}->create_str();
528 $heap->{_ua_requests}{$uuid} = { json_callback => $callback_state };
529  
530 # Send the request to the user agent
531 $kernel->post( $heap->{ua}, 'request', 'ua_response', $request, $uuid );
532 }
533  
534 sub ua_response {
535 my ($kernel, $heap, $request_packet, $response_packet) = @_[KERNEL, HEAP, ARG0, ARG1];
536  
537 my $request_object = $request_packet->[0];
538 my $request_tag = $request_packet->[1]; # from the 'request' post
539 my $response_object = $response_packet->[0];
540  
541 my $meta = delete $heap->{_ua_requests}{$request_tag};
542 if ($meta && $meta->{json_callback}) {
543 my $json;
544 eval {
545 $json = decode_json_response($response_object);
546 };
547 if ($@) {
548 # Ignore errors if shutting down
549 return if $heap->{_shutdown};
550 die $@;
551 }
552 $heap->{client}->logger->debug("<<< Pre-transport <<<\n" . Dumper($json));
553 $kernel->yield( $meta->{json_callback}, @$json );
554 }
555 }
556  
557 sub send_transport {
558 my ($kernel, $heap, $message) = @_[KERNEL, HEAP, ARG0];
559  
560 # Add unique ID to each message
561 my $msg_id = ++$heap->{message_id};
562 $message->{id} = $msg_id;
563  
564 # Store a copy of this message
565 $heap->{messages}{$msg_id} = {
566 %$message,
567 caller_session => $_[SENDER],
568 caller_state => $_[CALLER_STATE],
569 };
570  
571 if ($heap->{transport}) {
572 $kernel->post( $heap->{transport}, 'sendMessages', [ $message ]);
573 }
574 else {
575 $heap->{client}->logger->debug("Queueing message ".Dumper($message)." as no active transport");
576 push @{ $heap->{message_queue} }, $message;
577 }
578  
579 return $msg_id;
580 }
581  
582 sub flush_queue {
583 my ($kernel, $heap) = @_[KERNEL, HEAP];
584  
585 return unless $heap->{message_queue} && ref $heap->{message_queue} && int @{ $heap->{message_queue} };
586 return unless $heap->{transport};
587  
588 $heap->{client}->logger->debug("Flushing queue to transport");
589  
590 $kernel->post($heap->{transport}, 'sendMessages', [ @{ $heap->{message_queue} } ]);
591  
592 $heap->{message_queue} = [];
593 }
594  
595 =head1 TODO
596  
597 Lots of stuff.
598  
599 The code currently implements only the long-polling transport and doesn't yet
600 strictly follow all the directives in the protocol document http://svn.xantus.org/shortbus/trunk/bayeux/bayeux.html
601  
602 =head1 KNOWN BUGS
603  
604 No known bugs, but I'm sure you can find some.
605  
606 =head1 SEE ALSO
607  
608 L<POE>, L<POE::Component::Server::Bayeux>, L<POE::Component::Client::HTTP>
609  
610 =head1 COPYRIGHT
611  
612 Copyright (c) 2008 Eric Waters and XMission LLC (http://www.xmission.com/).
613 All rights reserved. This program is free software; you can redistribute it
614 and/or modify it under the same terms as Perl itself.
615  
616 The full text of the license can be found in the LICENSE file included with
617 this module.
618  
619 =head1 AUTHOR
620  
621 Eric Waters <ewaters@uarc.com>
622  
623 =cut
624  
625 1;
« Server/Bayeux/Message/Invalid.pm ↑ Summary