blib/lib/AnyEvent/HTTPD/ExtDirect.pm

filter: Statementstmt 91.3% 179 / 196 Branchbran 70.8% 34 / 48 Conditioncond 42.8% 12 / 28 MC/DCmcdc 11.1% 2 / 18 Subroutinesub 93.5% 29 / 31 Podpod 50.0% 3 / 6 totaltotal 79.2% 259 / 327 CC 40 SCAR 17.6
CC
40
Cov
83%
_extract_post_data
14.2
new
10.6
set_callbacks
5.0
CRAP 5.8
↑ Summary
1 package AnyEvent::HTTPD::ExtDirect;
2  
3 4 ▶use parent 'AnyEvent::HTTPD';
Subroutine BEGIN: called CC=1 SCAR=0.0
4  
5 4 ▶use common::sense;
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7 4 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 4 ▶use IO::File;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 4 ▶use File::Temp;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 4 ▶use File::Basename;
Subroutine BEGIN: called CC=1 SCAR=0.0
11  
12 4 ▶use AnyEvent::HTTPD::Request;
Subroutine BEGIN: called CC=1 SCAR=0.0
13  
14 4 ▶use RPC::ExtDirect::Util;
Subroutine BEGIN: called CC=1 SCAR=0.0
15 4 ▶use RPC::ExtDirect::Util::Accessor;
Subroutine BEGIN: called CC=1 SCAR=0.0
16 4 ▶use RPC::ExtDirect::Config;
Subroutine BEGIN: called CC=1 SCAR=0.0
17 4 ▶use RPC::ExtDirect::API;
Subroutine BEGIN: called CC=1 SCAR=0.0
18 4 ▶use RPC::ExtDirect;
Subroutine BEGIN: called CC=1 SCAR=0.0
19  
20 #
21 # This module is not compatible with RPC::ExtDirect < 3.0
22 #
23  
24 4 ▶croak __PACKAGE__." requires RPC::ExtDirect 3.0+"
Branch: 1 branch
BranchTrueFalseTotal
if $RPC::ExtDirect::VERSION lt "3.0" 0 4 4
25 if $RPC::ExtDirect::VERSION lt '3.0';
26  
27 ### PACKAGE GLOBAL VARIABLE ###
28 #
29 # Version of the module
30 #
31  
32 4 our $VERSION = '3.20';
33  
34 ### PUBLIC CLASS METHOD (CONSTRUCTOR) ###
35 #
36 # Instantiate a new AnyEvent::HTTPD::ExtDirect object
37 #
38  
39 35 ▶sub new {
Subroutine new: called CC=8 SCAR=23.6
Pod documented
40 35 my $class = shift;
41
42 0 ▶ my %arg = @_ == 1 && 'HASH' eq ref $_[0] ? %{ $_[0] }
Branch: 1 branch
BranchTrueFalseTotal
@_ == 1 && 'HASH' eq ref $_[0] ? : 0 35 35
Condition33%1/3
@_ == 1 and "HASH" eq ref $_[0]
!ll&&!rl&&r
3500
MC/DC0%0/2
@_ == 1 and "HASH" eq ref $_[0]
@_ == 1 "HASH" eq ref $_[0]
Truth table33%1/3
A and B
A= @_ == 1B= "HASH" eq ref $_[0]
ABresult
0X0
100
111
43 : @_
44 ;
45
46 35 ▶ my $api = delete $arg{api} || RPC::ExtDirect->get_api();
Condition33%1/3
delete $arg{'api'} || 'RPC::ExtDirect'->get_api
l!l&&r!l&&!r
0350
MC/DC0%0/2
delete $arg{'api'} || 'RPC::ExtDirect'->get_api
delete $arg{'api'} 'RPC::ExtDirect'->get_api
Truth table33%1/3
A || B
A= delete $arg{'api'}B= 'RPC::ExtDirect'->get_api
ABresult
1X1
011
000
47 35 ▶ my $config = delete $arg{config} || $api->config;
Condition33%1/3
delete $arg{'config'} || $api->config
l!l&&r!l&&!r
3500
MC/DC0%0/2
delete $arg{'config'} || $api->config
delete $arg{'config'} $api->config
Truth table33%1/3
A || B
A= delete $arg{'config'}B= $api->config
ABresult
1X1
011
000
48
49 35 $config->add_accessors(
50 overwrite => 1,
51 complex => [{
52 accessor => 'router_class_anyevent',
53 fallback => 'router_class',
54 }, {
55 accessor => 'eventprovider_class_anyevent',
56 fallback => 'eventprovider_class',
57 }],
58 );
59
60 35 for my $var ( qw/ router_class eventprovider_class / ) {
61 70 my $method = "${var}_anyevent";
62
63 70 ▶ $config->$method( delete $arg{$var} ) if exists $arg{$var};
Branch: 1 branch
BranchTrueFalseTotal
if exists $arg{$var} 0 70 70
64 }
65
66 # AnyEvent::HTTPD wants only IP addresses
67 35 ▶ $arg{host} = '127.0.0.1' if $arg{host} =~ /localhost/io;
Branch: 1 branch
BranchTrueFalseTotal
if $arg{"host"} =~ /localhost/iou 0 35 35
68  
69 35 my $self = $class->SUPER::new(%arg);
70
71 35 $self->config($config);
72 35 $self->api($api);
73  
74 35 return $self;
75 }
76  
77 ### PUBLIC INSTANCE METHOD ###
78 #
79 # Run the server
80 #
81  
82 0 ▶sub run {
Subroutine run: not called CC=1 SCAR=6.9
Pod documented
83 0 my ($self) = @_;
84
85 0 my $config = $self->config;
86  
87 0 $self->set_callbacks(
88 api_path => $config->api_path,
89 router_path => $config->router_path,
90 poll_path => $config->poll_path,
91 );
92  
93 0 $self->SUPER::run();
94 }
95  
96 ### PUBLIC INSTANCE METHOD ###
97 #
98 # Handle Ext.Direct API calls
99 #
100  
101 3 ▶sub handle_api {
Subroutine handle_api: called CC=2 SCAR=6.9
Pod undocumented
102 3 my ($self, $req) = @_;
103  
104 # Get the API JavaScript chunk
105 3 my $js = eval {
106 3 $self->api->get_remoting_api( config => $self->config )
107 };
108  
109 # If JS API call failed, return error
110 3 ▶ return $self->_error_response if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 0 3 3
111  
112 # Content length should be in octets
113 4 ▶ my $content_length = do { use bytes; my $len = length $js };
Subroutine BEGIN: called CC=1 SCAR=0.0
114  
115 3 $req->respond([
116 200,
117 'OK',
118 {
119 'Content-Type' => 'application/javascript',
120 'Content-Length' => $content_length,
121 },
122 $js
123 ]);
124  
125 3 $self->stop_request;
126 }
127  
128 ### PUBLIC INSTANCE METHOD ###
129 #
130 # Handle Ext.Direct method requests
131 #
132  
133 27 ▶sub handle_router {
Subroutine handle_router: called CC=3 SCAR=12.0
Pod undocumented
134 27 my ($self, $req) = @_;
135
136 27 ▶ if ( $req->method ne 'POST' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($req->method ne "POST") 0 27 27
137 0 $req->respond( $self->_error_response );
138 0 $self->stop_request;
139
140 0 return;
141 }
142
143 27 my $config = $self->config;
144 27 my $api = $self->api;
145  
146 # Naked AnyEvent::HTTPD::Request object doesn't provide several
147 # utility methods we'll need down below, and we will need it as
148 # an environment object, too
149 27 my $env = bless $req, __PACKAGE__.'::Env';
150  
151 # We're trying to distinguish between a raw POST and a form call
152 27 my $router_input = $self->_extract_post_data($env);
153  
154 # If the extraction fails, undef is returned by the method above
155 27 ▶ if ( !defined $router_input ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $router_input) 0 27 27
156 0 $req->respond( $self->_error_response );
157 0 $self->stop_request;
158  
159 0 return;
160 }
161
162 27 my $router_class = $config->router_class_anyevent;
163
164 27 eval "require $router_class";
165
166 27 my $router = $router_class->new(
167 config => $config,
168 api => $api,
169 );
170  
171 # No need for eval here, Router won't throw exceptions
172 27 my $result = $router->route($router_input, $env);
173  
174 # Router result is Plack-compatible arrayref; there's not much
175 # difference in what AnyEvent::HTTPD expects so we just convert it
176 # in place
177 $req->respond([
178 200,
179 'OK',
180 27 +{ @{ $result->[1] } },
181 $result->[2]->[0],
182 ]);
183
184 27 $self->stop_request;
185 }
186  
187 ### PUBLIC INSTANCE METHOD ###
188 #
189 # Polls Event handlers for events, returning serialized stream
190 #
191  
192 5 ▶sub handle_events {
Subroutine handle_events: called CC=3 SCAR=11.3
Pod undocumented
193 5 my ($self, $req) = @_;
194
195 # Only GET and POST methods are supported for polling
196 5 my $method = $req->method;
197
198 5 ▶ if ( $method ne 'GET' && $method ne 'POST' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($method ne "GET" and $method ne "POST") 0 5 5
Condition33%1/3
$method ne "GET" and $method ne "POST"
!ll&&!rl&&r
500
MC/DC0%0/2
$method ne "GET" and $method ne "POST"
$method ne "GET" $method ne "POST"
Truth table33%1/3
A and B
A= $method ne "GET"B= $method ne "POST"
ABresult
0X0
100
111
199 0 $req->respond( $self->_error_response );
200 0 $self->stop_request;
201
202 0 return;
203 }
204
205 5 my $config = $self->config;
206 5 my $api = $self->api;
207
208 5 my $env = bless $req, __PACKAGE__.'::Env';
209
210 5 my $provider_class = $config->eventprovider_class_anyevent;
211
212 5 eval "require $provider_class";
213
214 5 my $provider = $provider_class->new(
215 config => $config,
216 api => $api,
217 );
218
219 # Polling for Events is safe from exceptions
220 5 my $http_body = $provider->poll($env);
221
222 my $content_length
223 4 ▶ = do { no warnings 'void'; use bytes; length $http_body };
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
224
225 5 $req->respond([
226 200,
227 'OK',
228 {
229 'Content-Type' => 'application/json; charset=utf-8',
230 'Content-Length' => $content_length,
231 },
232 $http_body,
233 ]);
234
235 5 $self->stop_request;
236 }
237  
238 ### PUBLIC INSTANCE METHOD ###
239 #
240 # Register the callbacks for Ext.Direct handlers.
241 # This effectively "primes" the server but does not make it
242 # enter a blocking wait.
243 #
244  
245 35 ▶sub set_callbacks {
Subroutine set_callbacks: called CC=4 SCAR=16.1
Pod documented
246 35 my ($self, %arg) = @_;
247  
248 35 my $config = $self->config;
249
250 35 ▶ my $api_path = $arg{api_path} || $config->api_path;
Condition33%1/3
$arg{'api_path'} || $config->api_path
l!l&&r!l&&!r
3500
MC/DC0%0/2
$arg{'api_path'} || $config->api_path
$arg{'api_path'} $config->api_path
Truth table33%1/3
A || B
A= $arg{'api_path'}B= $config->api_path
ABresult
1X1
011
000
251 35 ▶ my $router_path = $arg{router_path} || $config->router_path;
Condition33%1/3
$arg{'router_path'} || $config->router_path
l!l&&r!l&&!r
3500
MC/DC0%0/2
$arg{'router_path'} || $config->router_path
$arg{'router_path'} $config->router_path
Truth table33%1/3
A || B
A= $arg{'router_path'}B= $config->router_path
ABresult
1X1
011
000
252 35 ▶ my $poll_path = $arg{poll_path} || $config->poll_path;
Condition33%1/3
$arg{'poll_path'} || $config->poll_path
l!l&&r!l&&!r
3500
MC/DC0%0/2
$arg{'poll_path'} || $config->poll_path
$arg{'poll_path'} $config->poll_path
Truth table33%1/3
A || B
A= $arg{'poll_path'}B= $config->poll_path
ABresult
1X1
011
000
253
254 35 $self->reg_cb(
255 $api_path => $self->can('handle_api'),
256 $router_path => $self->can('handle_router'),
257 $poll_path => $self->can('handle_events'),
258 );
259 }
260  
261 ### PUBLIC INSTANCE METHODS ###
262 #
263 # Read-write accessors.
264 #
265  
266 4 RPC::ExtDirect::Util::Accessor::mk_accessors(
267 simple => [qw/ api config /],
268 );
269  
270 ############## PRIVATE METHODS BELOW ##############
271  
272 ### PRIVATE INSTANCE METHOD ###
273 #
274 # Deals with intricacies of POST-fu and returns something suitable to
275 # feed to Router (string or hashref, really). Or undef if something
276 # goes too wrong to recover.
277 #
278 # This code was mostly copied from the Plack gateway and adapted
279 # for AnyEvent::HTTPD.
280 #
281  
282 27 ▶sub _extract_post_data {
Subroutine _extract_post_data: called CC=14 SCAR=26.6
283 27 my ($self, $req) = @_;
284  
285 # The smartest way to tell if a form was submitted that *I* know of
286 # is to look for 'extAction' and 'extMethod' keywords in form params.
287 27 ▶ my $is_form = $req->param('extAction') && $req->param('extMethod');
Condition66%2/3
$req->param('extAction') && $req->param('extMethod')
!ll&&!rl&&r
2106
MC/DC50%1/2
$req->param('extAction') && $req->param('extMethod')
$req->param('extAction') $req->param('extMethod')
Truth table66%2/3
A && B
A= $req->param('extAction')B= $req->param('extMethod')
ABresult
0X0
100
111
288  
289 # If form is not involved, it's easy: just return raw POST (or undef)
290 27 ▶ if ( !$is_form ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($is_form) 21 6 27
291 21 my $postdata = $req->content;
292 21 ▶ return $postdata ne '' ? $postdata
Branch: 1 branch
BranchTrueFalseTotal
$postdata ne '' ? : 21 0 21
293 : undef
294 ;
295 };
296  
297 # If any files are attached, extUpload field will be set to 'true'
298 6 my $has_uploads = $req->param('extUpload') eq 'true';
299  
300 # Outgoing hash
301 6 my %keyword;
302  
303 # Pluck all parameters from the Request object
304 6 for my $param ( $req->params ) {
305 54 my @values = $req->param($param);
306 54 ▶ $keyword{ $param } = @values == 0 ? undef
Branch: 2 branches
BranchTrueFalseTotal
@values == 0 ? : 0 54 54
@values == 1 ? : 53 1 54
307 : @values == 1 ? $values[0]
308 : [ @values ]
309 ;
310 };
311  
312 # Find all file uploads
313 6 ▶ for ( $has_uploads ? ($has_uploads) : () ) {
Branch: 1 branch
BranchTrueFalseTotal
$has_uploads ? : 3 3 6
314 # The list of fields that contain file uploads
315 3 my @upload_fields = $req->upload_fields;
316
317 3 ▶ last unless @upload_fields;
Branch: 1 branch
BranchTrueFalseTotal
unless @upload_fields 1 2 3
318
319 2 my @uploaded_files;
320
321 2 for my $field_name ( @upload_fields ) {
322 2 my $uploads = $req->raw_param($field_name);
323  
324 # We need files as a formatted list
325 2 my @field_uploads = map { $self->_format_upload($_) } @$uploads;
326 2 push @uploaded_files, @field_uploads;
327  
328 # Now remove the field that contained files
329 2 delete @keyword{ $field_name };
330 }
331  
332 2 ▶ $keyword{ '_uploads' } = \@uploaded_files if @uploaded_files;
Branch: 1 branch
BranchTrueFalseTotal
if @uploaded_files 2 0 2
333 };
334  
335 # Metadata is JSON encoded; decode_metadata lives by side effects!
336 6 ▶ if ( exists $keyword{metadata} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $keyword{"metadata"}) 3 3 6
337 3 RPC::ExtDirect::Util::decode_metadata($self, \%keyword);
338 }
339  
340 # Remove extType because it's meaningless later on
341 6 delete $keyword{ extType };
342  
343 # Fix TID so that it comes as number (JavaScript is picky)
344 6 ▶ $keyword{ extTID } += 0 if exists $keyword{ extTID };
Branch: 1 branch
BranchTrueFalseTotal
if exists $keyword{"extTID"} 6 0 6
345  
346 6 return \%keyword;
347 }
348  
349 ### PRIVATE INSTANCE METHOD ###
350 #
351 # Take the file content and metadata and format it in a way
352 # that RPC::ExtDirect handlers expect
353 #
354  
355 4 ▶sub _format_upload {
Subroutine _format_upload: called CC=1 SCAR=0.0
356 4 my ($self, $upload) = @_;
357
358 4 ▶ my $content_length = do { use bytes; length $upload->[0] };
Subroutine BEGIN: called CC=1 SCAR=0.0
359
360 4 my ($fh, $fname) = File::Temp::tempfile;
361
362 4 binmode $fh;
363 4 syswrite $fh, $upload->[0], $content_length;
364
365 4 sysseek $fh, 0, 0;
366
367 # We don't need the file content anymore, so try to release
368 # the memory it takes
369 4 $upload->[0] = undef;
370
371 4 my $filename = $upload->[2];
372 4 my $basename = File::Basename::basename($filename);
373 4 my $type = $upload->[1];
374 4 my $handle = IO::File->new_from_fd($fh->fileno, '<');
375  
376 return {
377 4 filename => $filename,
378 basename => $basename,
379 type => $type,
380 size => $content_length,
381 path => $fname,
382 handle => $handle,
383 };
384 }
385  
386 ### PRIVATE INSTANCE METHOD ###
387 #
388 # Return an error response formatted to AnyEvent::HTTPD likes
389 #
390  
391 0 ▶sub _error_response {
Subroutine _error_response: not called CC=1 SCAR=6.9
392 0 [ 500, 'Internal Server Error', { 'Content-Type' => 'text/html' }, '' ]
393 }
394  
395 package
396 AnyEvent::HTTPD::ExtDirect::Env;
397  
398 4 ▶use parent 'AnyEvent::HTTPD::Request';
Subroutine BEGIN: called CC=1 SCAR=0.0
399  
400 #
401 # AnyEvent::HTTPD::Request stores the form parameters in a peculiar format:
402 # $self->{parm} is a hashref of arrayrefs; each arrayref contain one
403 # or more values, again in arrayrefs with fixed number of items:
404 # [ content, content-type, file-name ]
405 #
406 # For anything but file uploads, the last 2 elements are undef; for the
407 # file uploads they're the file MIME type and name, respectively.
408 #
409 # A dump might look like this:
410 #
411 # $self->{parm}:
412 # 0 HASH
413 # 'formFieldName' => ARRAY
414 # 0 ARRAY =>
415 # 0 'form field value'
416 # 1 undef
417 # 2 undef
418 # 'fieldWithMultipleValues' => ARRAY # SURMISED!
419 # 0 ARRAY =>
420 # 0 'form field value 0'
421 # 1 undef
422 # 2 undef
423 # 1 ARRAY =>
424 # 0 'form field value 1'
425 # 1 undef
426 # 2 undef
427 # 'fileUploads' => ARRAY
428 # 0 ARRAY =>
429 # 0 'first file content (all of it!)'
430 # 1 'first file MIME type'
431 # 2 'first file name'
432 # 1 ARRAY =>
433 # 0 'second file content'
434 # 1 'second file MIME type'
435 # 2 'second file name'
436 #
437 # There is no method that returns multiple values for a non-file field,
438 # and no method that returns file upload parameters, so we have to
439 # roll our own
440 #
441  
442 95 ▶sub param {
Subroutine param: called CC=4 SCAR=13.9
443 95 my ($self, $key) = @_;
444
445 95 ▶ return $self->params unless defined $key;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $key 1 94 95
446
447 # [] is to avoid autovivification biting my ass ;)
448 94 ▶ my @values = map { $_->[0] } @{ $self->{parm}->{$key} || [] };
Condition100%2/2
$self->{'parm'}{$key} || []
l!l
6925
MC/DC100%1/1
$self->{'parm'}{$key} || []
$self->{'parm'}{$key}
Truth table100%2/2
A
A= $self->{'parm'}{$key}
Aresult
11
00
449
450 94 ▶ return wantarray ? @values : shift @values;
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 54 40 94
451 }
452  
453 # Go over the fields and return the list of names for the fields
454 # that contain file uploads
455 3 ▶sub upload_fields {
Subroutine upload_fields: called CC=4 SCAR=13.9
456 3 my ($self) = @_;
457
458 3 my @upload_fields;
459
460 3 my $params = $self->{parm};
461
462 FIELD:
463 3 for my $field_name ( keys %$params ) {
464 29 my $values = $params->{ $field_name };
465
466 29 for my $value ( @$values ) {
467
468 # We surmise that for a file upload, at least MIME type
469 # should be defined (name is optional)
470 29 ▶ if ( defined $value->[1] ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $value->[1]) 2 27 29
471 2 push @upload_fields, $field_name;
472 2 next FIELD;
473 }
474 }
475 }
476
477 3 return @upload_fields;
478 }
479  
480 2 ▶sub raw_param {
Subroutine raw_param: called CC=1 SCAR=0.0
481 2 my ($self, $key) = @_;
482
483 2 return $self->{parm}->{$key};
484 }
485  
486 2 ▶sub cookie {
Subroutine cookie: called CC=4 SCAR=14.4
487 2 my ($self, $key) = @_;
488  
489 2 my %cookies;
490  
491 2 ▶ if ( $self->{_cookies} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'_cookies'}) { } 0 2 2
492 0 %cookies = %{ $self->{_cookies} };
493 }
494 else {
495 2 my $headers = $self->headers;
496 2 ▶ my $cookie_hdr = $headers ? $headers->{cookie} : '';
Branch: 1 branch
BranchTrueFalseTotal
$headers ? : 2 0 2
497 2 %cookies = map { split /=/, $_ } split /;\s+/, $cookie_hdr;
498 2 $self->{_cookies} = \%cookies;
499 }
500  
501 2 ▶ return $key ? $cookies{ $key } : keys %cookies;
Branch: 1 branch
BranchTrueFalseTotal
$key ? : 1 1 2
502 }
503  
504 2 ▶sub http {
Subroutine http: called CC=3 SCAR=11.1
505 2 my ($self, $key) = @_;
506  
507 2 ▶ my $headers = $self->headers || {};
Condition50%1/2
$self->headers || {}
l!l
20
MC/DC0%0/1
$self->headers || {}
$self->headers
Truth table50%1/2
A
A= $self->headers
Aresult
11
00
508  
509 2 ▶ return $key ? $headers->{ lc $key } : keys %$headers;
Branch: 1 branch
BranchTrueFalseTotal
$key ? : 1 1 2
510 }
511  
512 4 1;
513  
↑ Summary