HTTP2/Client.pm

filter: Statementstmt 82.3% 93 / 113 Branchbran 77.7% 42 / 54 Conditioncond 50.0% 7 / 14 MC/DCmcdc 33.3% 3 / 9 Subroutinesub 86.3% 19 / 22 Podpod 88.8% 8 / 9 totaltotal 77.8% 172 / 221 CC 33 SCAR 19.3
CC
33
Cov
78%
request
14.4
__ANON__
12.0
new
8.7
CRAP 6.9
« HTTP2/Frame/Headers.pm ↑ Summary HTTP2/Frame/Continuation.pm »
1 package Protocol::HTTP2::Client;
2 9 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
3 9 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 9 ▶use Protocol::HTTP2::Connection;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 9 ▶use Protocol::HTTP2::Constants qw(:frame_types :flags :states :endpoints
Subroutine BEGIN: called CC=1 SCAR=0.0
6 9 :errors);
7 9 ▶use Protocol::HTTP2::Trace qw(tracer);
Subroutine BEGIN: called CC=1 SCAR=0.0
8 9 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 9 ▶use Scalar::Util ();
Subroutine BEGIN: called CC=1 SCAR=0.0
10  
11 =encoding utf-8
12  
13 =head1 NAME
14  
15 Protocol::HTTP2::Client - HTTP/2 client
16  
17 =head1 SYNOPSIS
18  
19 use Protocol::HTTP2::Client;
20  
21 # Create client object
22 my $client = Protocol::HTTP2::Client->new;
23  
24 # Prepare first request
25 $client->request(
26  
27 # HTTP/2 headers
28 ':scheme' => 'http',
29 ':authority' => 'localhost:8000',
30 ':path' => '/',
31 ':method' => 'GET',
32  
33 # HTTP/1.1 headers
34 headers => [
35 'accept' => '*/*',
36 'user-agent' => 'perl-Protocol-HTTP2/0.13',
37 ],
38  
39 # Callback when receive server's response
40 on_done => sub {
41 my ( $headers, $data ) = @_;
42 ...
43 },
44 );
45  
46 # Protocol::HTTP2 is just HTTP/2 protocol decoder/encoder
47 # so you must create connection yourself
48  
49 use AnyEvent;
50 use AnyEvent::Socket;
51 use AnyEvent::Handle;
52 my $w = AnyEvent->condvar;
53  
54 # Plain-text HTTP/2 connection
55 tcp_connect 'localhost', 8000, sub {
56 my ($fh) = @_ or die "connection failed: $!\n";
57
58 my $handle;
59 $handle = AnyEvent::Handle->new(
60 fh => $fh,
61 autocork => 1,
62 on_error => sub {
63 $_[0]->destroy;
64 print "connection error\n";
65 $w->send;
66 },
67 on_eof => sub {
68 $handle->destroy;
69 $w->send;
70 }
71 );
72  
73 # First write preface to peer
74 while ( my $frame = $client->next_frame ) {
75 $handle->push_write($frame);
76 }
77  
78 # Receive servers frames
79 # Reply to server
80 $handle->on_read(
81 sub {
82 my $handle = shift;
83  
84 $client->feed( $handle->{rbuf} );
85  
86 $handle->{rbuf} = undef;
87 while ( my $frame = $client->next_frame ) {
88 $handle->push_write($frame);
89 }
90  
91 # Terminate connection if all done
92 $handle->push_shutdown if $client->shutdown;
93 }
94 );
95 };
96  
97 $w->recv;
98  
99 =head1 DESCRIPTION
100  
101 Protocol::HTTP2::Client is HTTP/2 client library. It's intended to make
102 http2-client implementations on top of your favorite event-loop.
103  
104 =head2 METHODS
105  
106 =head3 new
107  
108 Initialize new client object
109  
110 my $client = Protocol::HTTP2::Client->new( %options );
111  
112 Available options:
113  
114 =over
115  
116 =item on_push => sub {...}
117  
118 If server send push promise this callback will be invoked
119  
120 on_push => sub {
121 # received PUSH PROMISE headers
122 my $pp_header = shift;
123 ...
124
125 # if we want reject this push
126 # return undef
127
128 # if we want to accept pushed resource
129 # return callback to receive data
130 return sub {
131 my ( $headers, $data ) = @_;
132 ...
133 }
134 },
135  
136 =item upgrade => 0|1
137  
138 Use HTTP/1.1 Upgrade to upgrade protocol from HTTP/1.1 to HTTP/2. Upgrade
139 possible only on plain (non-tls) connection. Default value is 0.
140  
141 See
142 L<Starting HTTP/2 for "http" URIs|https://tools.ietf.org/html/rfc7540#section-3.2>
143  
144 =item keepalive => 0|1
145  
146 Keep connection alive after requests. Default value is 0. Don't forget to
147 explicitly call close method if set this to true.
148  
149 =item on_error => sub {...}
150  
151 Callback invoked on protocol errors
152  
153 on_error => sub {
154 my $error = shift;
155 ...
156 },
157  
158 =item on_change_state => sub {...}
159  
160 Callback invoked every time when http/2 streams change their state.
161 See
162 L<Stream States|https://tools.ietf.org/html/rfc7540#section-5.1>
163  
164 on_change_state => sub {
165 my ( $stream_id, $previous_state, $current_state ) = @_;
166 ...
167 },
168  
169 =back
170  
171 =cut
172  
173 21 ▶sub new {
Subroutine new: called CC=4 SCAR=21.7
Pod documented
174 21 my ( $class, %opts ) = @_;
175 my $self = {
176 con => undef,
177 input => '',
178 active_streams => 0,
179 keepalive => exists $opts{keepalive}
180 ? delete $opts{keepalive}
181 : 0,
182 settings => exists $opts{settings} ? $opts{settings} : {},
183 21 ▶ };
Branch: 2 branches
BranchTrueFalseTotal
exists $opts{'keepalive'} ? : 1 20 21
exists $opts{'settings'} ? : 1 20 21
184  
185 21 ▶ if ( exists $opts{on_push} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $opts{"on_push"}) 0 21 21
186 0 Scalar::Util::weaken( my $self = $self );
187  
188 0 my $cb = delete $opts{on_push};
189 0 ▶ $opts{on_new_peer_stream} = sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
190 0 my $stream_id = shift;
191 0 my $pp_headers;
192 0 $self->active_streams(+1);
193  
194 $self->{con}->stream_cb(
195 $stream_id,
196 RESERVED,
197 0 ▶ sub {
Subroutine __ANON__: not called CC=3 SCAR=24.8
198 my $res =
199 0 $cb->( $self->{con}->stream_pp_headers($stream_id) );
200 0 ▶ if ( $res && ref $cb eq 'CODE' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($res and ref $cb eq 'CODE') { } 0 0 0
Condition0%0/3
$res and ref $cb eq "CODE"
!ll&&!rl&&r
000
MC/DC0%0/2
$res and ref $cb eq "CODE"
$res ref $cb eq "CODE"
Truth table0%0/3
A and B
A= $resB= ref $cb eq "CODE"
ABresult
0X0
100
111
201 $self->{con}->stream_cb(
202 $stream_id,
203 CLOSED,
204 0 ▶ sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
205 $res->(
206 $self->{con}->stream_headers($stream_id),
207 0 $self->{con}->stream_data($stream_id),
208 );
209 0 $self->active_streams(-1);
210 }
211 0 );
212 }
213 else {
214 $self->{con}
215 0 ->stream_error( $stream_id, REFUSED_STREAM );
216 0 $self->active_streams(-1);
217 }
218 }
219 0 );
220 0 };
221 }
222  
223 21 $self->{con} = Protocol::HTTP2::Connection->new( CLIENT, %opts );
224 21 bless $self, $class;
225 }
226  
227 74 ▶sub active_streams {
Subroutine active_streams: called CC=4 SCAR=13.9
Pod undocumented
228 74 my $self = shift;
229 74 ▶ my $add = shift || 0;
Condition50%1/2
shift() || 0
l!l
740
MC/DC0%0/1
shift() || 0
shift()
Truth table50%1/2
A
A= shift()
Aresult
11
00
230 74 $self->{active_streams} += $add;
231 $self->{con}->finish
232 unless $self->{active_streams} > 0
233 74 ▶ || $self->{keepalive};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"active_streams"} > 0 or $self->{"keepalive"} 10 64 74
Condition100%3/3
$self->{"active_streams"} > 0 or $self->{"keepalive"}
l!l&&r!l&&!r
541010
MC/DC100%2/2
$self->{"active_streams"} > 0 or $self->{"keepalive"}
$self->{"active_streams"} > 0 $self->{"keepalive"}
Truth table100%3/3
A or B
A= $self->{"active_streams"} > 0B= $self->{"keepalive"}
ABresult
1X1
011
000
234 }
235  
236 =head3 request
237  
238 Prepare HTTP/2 request.
239  
240 $client->request(
241  
242 # HTTP/2 headers
243 ':scheme' => 'http',
244 ':authority' => 'localhost:8000',
245 ':path' => '/items',
246 ':method' => 'POST',
247  
248 # HTTP/1.1 headers
249 headers => [
250 'content-type' => 'application/x-www-form-urlencoded',
251 'user-agent' => 'perl-Protocol-HTTP2/0.06',
252 ],
253  
254 # Callback when receive server's response
255 on_done => sub {
256 my ( $headers, $data ) = @_;
257 ...
258 },
259  
260 # Callback when receive stream reset
261 on_error => sub {
262 my $error_code = shift;
263 },
264  
265 # Body of POST request
266 data => "hello=world&test=done",
267 );
268  
269 You can chaining request one by one:
270  
271 $client->request( 1-st request )->request( 2-nd request );
272  
273 Available callbacks:
274  
275 =over
276  
277 =item on_done => sub {...}
278  
279 Invoked when full servers response is available
280  
281 on_done => sub {
282 my ( $headers, $data ) = @_;
283 ...
284 },
285  
286 =item on_headers => sub {...}
287  
288 Invoked as soon as headers have been successfully received from the server
289  
290 on_headers => sub {
291 my $headers = shift;
292 ...
293  
294 # if we want reject any data
295 # return undef
296  
297 # continue
298 return 1
299 }
300  
301 =item on_data => sub {...}
302  
303 If specified all data will be passed to this callback instead if on_done.
304 on_done will receive empty string.
305  
306 on_data => sub {
307 my ( $partial_data, $headers ) = @_;
308 ...
309  
310 # if we want cancel download
311 # return undef
312  
313 # continue downloading
314 return 1
315 }
316  
317 =item on_error => sub {...}
318  
319 Callback invoked on stream errors
320  
321 on_error => sub {
322 my $error = shift;
323 ...
324 }
325  
326 =back
327  
328 =cut
329  
330 9 my @must = (qw(:authority :method :path :scheme));
331  
332 44 ▶sub request {
Subroutine request: called CC=14 SCAR=26.7
Pod documented
333 44 my ( $self, %h ) = @_;
334 44 my @miss = grep { !exists $h{$_} } @must;
335 44 ▶ croak "Missing fields in request: @miss" if @miss;
Branch: 1 branch
BranchTrueFalseTotal
if @miss 0 44 44
336  
337 44 my $con = $self->{con};
338  
339 44 my $stream_id = $con->new_stream;
340 44 ▶ unless ( defined $stream_id ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $stream_id) 2 42 44
341 2 ▶ if ( exists $con->{on_error} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $con->{'on_error'}) { } 1 1 2
342 1 $con->{on_error}->(PROTOCOL_ERROR);
343 1 return $self;
344 }
345 else {
346 1 croak "Can't create new stream, connection is closed";
347 }
348 }
349  
350 42 $self->active_streams(+1);
351  
352 42 ▶ if ( $con->upgrade && !exists $self->{sent_upgrade} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($con->upgrade and not exists $self->{'sent_upgrade'}) { } 1 41 42
Condition66%2/3
$con->upgrade and not exists $self->{"sent_upgrade"}
!ll&&!rl&&r
4101
MC/DC50%1/2
$con->upgrade and not exists $self->{"sent_upgrade"}
$con->upgrade not exists $self->{"sent_upgrade"}
Truth table66%2/3
A and not(B)
A= $con->upgradeB= not exists $self->{"sent_upgrade"}
ABresult
0X0
100
111
353 $con->enqueue_raw(
354 $con->upgrade_request(
355 4 ▶ ( map { $_ => $h{$_} } @must ),
Branch: 1 branch
BranchTrueFalseTotal
exists $h{'headers'} ? : 1 0 1
356 1 headers => exists $h{headers} ? $h{headers} : []
357 )
358 );
359 1 $self->{sent_upgrade} = 1;
360 1 $con->stream_state( $stream_id, HALF_CLOSED );
361 }
362 else {
363 41 ▶ if ( !$con->preface ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($con->preface) 20 21 41
364 $con->enqueue_raw( $con->preface_encode ),
365 20 $con->enqueue( SETTINGS, 0, 0, $self->{settings} );
366 20 $con->preface(1);
367 }
368  
369 $con->send_headers(
370 $stream_id,
371 [
372 164 ▶ ( map { $_ => $h{$_} } @must ),
Branch: 1 branch
BranchTrueFalseTotal
exists $h{'headers'} ? : 39 2 41
373 39 ▶ exists $h{headers} ? @{ $h{headers} } : ()
Branch: 1 branch
BranchTrueFalseTotal
exists $h{'data'} ? : 2 39 41
374 ],
375 41 exists $h{data} ? 0 : 1
376 );
377 41 ▶ $con->send_data( $stream_id, $h{data}, 1 ) if exists $h{data};
Branch: 1 branch
BranchTrueFalseTotal
if exists $h{"data"} 2 39 41
378 }
379  
380 42 Scalar::Util::weaken $self;
381 42 Scalar::Util::weaken $con;
382  
383 $con->stream_cb(
384 $stream_id,
385 CLOSED,
386 32 ▶ sub {
Subroutine __ANON__: called CC=3 SCAR=13.3
387 32 ▶ if ( exists $h{on_error} && $con->stream_reset($stream_id) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $h{'on_error'} and $con->stream_reset($stream_id)) { } 0 32 32
Condition33%1/3
exists $h{"on_error"} and $con->stream_reset($stream_id)
!ll&&!rl&&r
3200
MC/DC0%0/2
exists $h{"on_error"} and $con->stream_reset($stream_id)
exists $h{"on_error"} $con->stream_reset($stream_id)
Truth table33%1/3
A and B
A= exists $h{"on_error"}B= $con->stream_reset($stream_id)
ABresult
0X0
100
111
388 0 $h{on_error}->( $con->stream_reset($stream_id) );
389 }
390 else {
391 32 $h{on_done}->(
392 $con->stream_headers($stream_id),
393 $con->stream_data($stream_id),
394 );
395 }
396 32 $self->active_streams(-1);
397 }
398 42 ▶ ) if exists $h{on_done};
Branch: 1 branch
BranchTrueFalseTotal
if exists $h{"on_done"} 33 9 42
399  
400 $con->stream_frame_cb(
401 $stream_id,
402 HEADERS,
403 5 ▶ sub {
Subroutine __ANON__: called CC=2 SCAR=8.1
404 5 my $res = $h{on_headers}->( $_[0] );
405 5 ▶ return if $res;
Branch: 1 branch
BranchTrueFalseTotal
if $res 5 0 5
406 0 $con->stream_error( $stream_id, REFUSED_STREAM );
407 }
408 42 ▶ ) if exists $h{on_headers};
Branch: 1 branch
BranchTrueFalseTotal
if exists $h{"on_headers"} 5 37 42
409  
410 $con->stream_frame_cb(
411 $stream_id,
412 DATA,
413 5 ▶ sub {
Subroutine __ANON__: called CC=2 SCAR=7.1
414 5 my $res = $h{on_data}->( $_[0], $con->stream_headers($stream_id), );
415 5 ▶ return if $res;
Branch: 1 branch
BranchTrueFalseTotal
if $res 0 5 5
416 5 $con->stream_error( $stream_id, REFUSED_STREAM );
417 }
418 42 ▶ ) if exists $h{on_data};
Branch: 1 branch
BranchTrueFalseTotal
if exists $h{"on_data"} 5 37 42
419  
420 42 return $self;
421 }
422  
423 =head3 keepalive
424  
425 Keep connection alive after requests
426  
427 my $bool = $client->keepalive;
428 $client = $client->keepalive($bool);
429  
430 =cut
431  
432 1 ▶sub keepalive {
Subroutine keepalive: called CC=2 SCAR=7.2
Pod documented
433 1 my $self = shift;
434 return @_
435 ? scalar( $self->{keepalive} = shift, $self )
436 1 ▶ : $self->{keepalive};
Branch: 1 branch
BranchTrueFalseTotal
@_ ? : 1 0 1
437 }
438  
439 =head3 shutdown
440  
441 Get connection status:
442  
443 =over
444  
445 =item 0 - active
446  
447 =item 1 - closed (you can terminate connection)
448  
449 =back
450  
451 =cut
452  
453 7 ▶sub shutdown {
Subroutine shutdown: called CC=1 SCAR=0.0
Pod documented
454 7 shift->{con}->shutdown;
455 }
456  
457 =head3 close
458  
459 Explicitly close connection (send GOAWAY frame). This is required if client
460 has keepalive option enabled.
461  
462 =cut
463  
464 1 ▶sub close {
Subroutine close: called CC=1 SCAR=0.0
Pod documented
465 1 shift->{con}->finish;
466 }
467  
468 =head3 next_frame
469  
470 get next frame to send over connection to server.
471 Returns:
472  
473 =over
474  
475 =item undef - on error
476  
477 =item 0 - nothing to send
478  
479 =item binary string - encoded frame
480  
481 =back
482  
483 # Example
484 while ( my $frame = $client->next_frame ) {
485 syswrite $fh, $frame;
486 }
487  
488 =cut
489  
490 219 ▶sub next_frame {
Subroutine next_frame: called CC=2 SCAR=6.9
Pod documented
491 219 my $self = shift;
492 219 my $frame = $self->{con}->dequeue;
493 219 ▶ tracer->debug("send one frame to wire\n") if $frame;
Branch: 1 branch
BranchTrueFalseTotal
if $frame 124 95 219
494 219 return $frame;
495 }
496  
497 =head3 feed
498  
499 Feed decoder with chunks of server's response
500  
501 sysread $fh, $binary_data, 4096;
502 $client->feed($binary_data);
503  
504 =cut
505  
506 116 ▶sub feed {
Subroutine feed: called CC=6 SCAR=18.8
Pod documented
507 116 my ( $self, $chunk ) = @_;
508 116 $self->{input} .= $chunk;
509 116 my $offset = 0;
510 116 my $len;
511 116 my $con = $self->{con};
512 116 tracer->debug( "got " . length($chunk) . " bytes on a wire\n" );
513 116 ▶ if ( $con->upgrade ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($con->upgrade) 1 115 116
514 1 $len = $con->decode_upgrade_response( \$self->{input}, $offset );
515 1 ▶ $con->shutdown(1) unless defined $len;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $len 1 0 1
516 1 ▶ return unless $len;
Branch: 1 branch
BranchTrueFalseTotal
unless $len 1 0 1
517 0 $offset += $len;
518 0 $con->upgrade(0);
519 0 $con->enqueue_raw( $con->preface_encode );
520 0 $con->preface(1);
521 }
522 115 ▶ while ( $len = $con->frame_decode( \$self->{input}, $offset ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($len = $con->frame_decode(\$self->{"input"}, $offset)) 121 115 236
523 121 tracer->debug("decoded frame at $offset, length $len\n");
524 121 $offset += $len;
525 }
526 115 ▶ substr( $self->{input}, 0, $offset ) = '' if $offset;
Branch: 1 branch
BranchTrueFalseTotal
if $offset 115 0 115
527 }
528  
529 =head3 ping
530  
531 Send ping frame to server (to keep connection alive)
532  
533 $client->ping
534  
535 or
536  
537 $client->ping($payload);
538  
539 Payload can be arbitrary binary string and must contain 8 octets. If payload argument
540 is omitted client will send random data.
541  
542 =cut
543  
544 1 ▶sub ping {
Subroutine ping: called CC=1 SCAR=0.0
Pod documented
545 1 shift->{con}->send_ping(@_);
546 }
547  
548 9 1;
« HTTP2/Frame/Headers.pm ↑ Summary HTTP2/Frame/Continuation.pm »