blib/lib/Amon2/Plugin/Web/WebSocket.pm untested

filter: Statementstmt 0.0% 0 / 72 Branchbran 0.0% 0 / 2 Conditioncond 0.0% 0 / 7 MC/DCmcdc 0.0% 0 / 4 Subroutinesub 0.0% 0 / 12 Podpod 0.0% 0 / 2 totaltotal 0.0% 0 / 99 CC 2 SCAR 9.6
CC
2
Cov
0%
_websocket
6.0
init
2.0
BEGIN
2.0
CRAP 2.6
1 package Amon2::Plugin::Web::WebSocket;
2 use strict;
3 use warnings;
4 use utf8;
5  
6 use Amon2::Util;
7  
8 use AnyEvent::Handle;
9 use Amon2::Web::WebSocket;
10 use Amon2::Web::Response::Callback;
11 use Protocol::WebSocket 0.00906;
12 use Protocol::WebSocket::Frame;
13 use Protocol::WebSocket::Handshake::Server;
14  
15 sub init {
16 my ($class, $c, $conf) = @_;
17  
18 Amon2::Util::add_method(ref $c || $c, 'websocket', \&_websocket);
19 }
20  
21 sub _websocket {
22 my ($c, $code) = @_;
23  
24 my $fh = $c->req->env->{'psgix.io'}
25 or return $c->create_response( 500, [], [] );
26 my $ws = Amon2::Web::WebSocket->new();
27 my $hs = Protocol::WebSocket::Handshake::Server->new_from_psgi(
28 $c->req->env );
29 $hs->parse($fh)
30 or return $c->create_response( 400, [], [ $hs->error ] );
31 my @messages;
32 $ws->{send_message} = sub {
33 my $message = shift;
34 push @messages, $message;
35 };
36 $code->( $ws );
37 my $res = Amon2::Web::Response::Callback->new(
38 code => sub {
39 my $respond = shift;
40 eval {
41 my $h = AnyEvent::Handle->new( fh => $fh );
42 $ws->{send_message} = sub {
43 my $message = shift;
44 $message = Protocol::WebSocket::Frame->new($message)
45 ->to_bytes;
46 $h->push_write($message);
47 };
48 my $frame = Protocol::WebSocket::Frame->new();
49 $h->push_write( $hs->to_string );
50 $ws->send_message($_) for @messages;
51 $h->on_read(
52 sub {
53 $frame->append( $_[0]->rbuf );
54 while ( my $message = $frame->next ) {
55 $ws->call_receive_message( $c, $message );
56 }
57 }
58 );
59 $h->on_error(
60 sub {
61 $ws->call_error($c);
62 }
63 );
64 $h->on_eof(
65 sub {
66 $ws->call_eof($c);
67 close $fh;
68 }
69 );
70 };
71 if ($@) {
72 warn $@;
73 die "Cannot process websocket";
74 }
75 },
76 );
77 return $res;
78 }
79  
80 1;
81 __END__