HTTP2/Client/Connection.pm

filter: Statementstmt 73.3% 110 / 150 Branchbran 33.3% 12 / 36 Conditioncond 38.4% 5 / 13 MC/DCmcdc 0.0% 0 / 7 Subroutinesub 84.8% 28 / 33 Podpod 100% 2 / 2 totaltotal 65.1% 157 / 241 CC 27 SCAR 17.2
CC
27
Cov
64%
_send_pending_frames
13.8
request
12.1
_on_stream_close
12.0
CRAP 5.6
« HTTP2/Client/Connection/IOAsync.pm ↑ Summary HTTP2/Response.pm »
1 package Net::HTTP2::Client::Connection;
2  
3 1 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 1 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5  
6 =encoding utf-8
7  
8 =head1 NAME
9  
10 Net::HTTP2::Client::Connection - Base class for individual HTTP/2
11 client connection
12  
13 =head1 SYNOPSIS
14  
15 See:
16  
17 =over
18  
19 =item * L<Net::HTTP2::Client::Connection::Mojo>
20  
21 =item * L<Net::HTTP2::Client::Connection::IOAsync>
22  
23 =item * L<Net::HTTP2::Client::Connection::AnyEvent>
24  
25 =back
26  
27 =head1 DESCRIPTION
28  
29 This implements a non-blocking, B<non-redirecting> HTTP/2 client.
30 It’s a base class; the actual class you’ll use will depend on your
31 event loop interface (see L</SYNOPSIS>).
32  
33 If you want a full-featured client (that honors redirections),
34 see L<Net::HTT2::Client>.
35  
36 =head1 CONNECTION LONGEVITY
37  
38 TCP connections are kept open as long as instances of this class live.
39  
40 =head1 HTTP REDIRECTION
41  
42 This class’s design would facilitate HTTP redirects only in the case
43 where the target of the redirect is the same server that answers the
44 initial request. (e.g., we could honor
45 C<Location: https://same.server/some/other/path> or
46 C<Location: /some/other/path>, but not
47 C<Location: https://some.other.server/foo>.)
48  
49 To avoid that inconsistency, this class purposely omits HTTP redirection.
50 See L<Net::HTTP2::UserAgent> for an interface that implements redirection.
51  
52 =cut
53  
54 #----------------------------------------------------------------------
55  
56 1 ▶use Carp ();
Subroutine BEGIN: called CC=1 SCAR=0.0
57 1 ▶use Scalar::Util ();
Subroutine BEGIN: called CC=1 SCAR=0.0
58  
59 1 ▶use Protocol::HTTP2::Client ();
Subroutine BEGIN: called CC=1 SCAR=0.0
60 1 ▶use Protocol::HTTP2::Constants ();
Subroutine BEGIN: called CC=1 SCAR=0.0
61  
62 1 ▶use Net::HTTP2::Constants ();
Subroutine BEGIN: called CC=1 SCAR=0.0
63 1 ▶use Net::HTTP2::X ();
Subroutine BEGIN: called CC=1 SCAR=0.0
64 1 ▶use Net::HTTP2::Response ();
Subroutine BEGIN: called CC=1 SCAR=0.0
65 1 ▶use Net::HTTP2::PartialResponse ();
Subroutine BEGIN: called CC=1 SCAR=0.0
66 1 ▶use Net::HTTP2::RejectorRegistry ();
Subroutine BEGIN: called CC=1 SCAR=0.0
67  
68 # Lazy-load so that Mojo doesn’t load Promise::ES6.
69 1 ▶use constant _PROMISE_CLASS => 'Promise::ES6';
Subroutine BEGIN: called CC=1 SCAR=0.0
70  
71 1 ▶use constant {
Subroutine BEGIN: called CC=1 SCAR=0.0
72 1 _DEBUG => 1,
73  
74 _ALPN_PROTOS => ['h2'],
75 1 };
76  
77 1 ▶use constant _INIT_OPTS => (
Subroutine BEGIN: called CC=1 SCAR=0.0
78 'port',
79 'tls_verify',
80 1 );
81  
82 1 my %TLS_VERIFY = (
83 none => 0,
84 peer => 1,
85 );
86  
87 2 ▶sub _parse_args {
Subroutine _parse_args: called CC=4 SCAR=16.3
88 2 my $class = shift;
89 2 my $peer = shift;
90  
91 2 my %raw_opts = @_;
92  
93 2 my %opts = map { $_ => delete $raw_opts{$_} } $class->_INIT_OPTS();
94  
95 2 ▶ if (my @extra = sort keys %raw_opts) {
Branch: 1 branch
BranchTrueFalseTotal
if (my(@extra) = sort(keys %raw_opts)) 0 2 2
96 0 Carp::croak "Unknown: @extra";
97 }
98  
99 2 my @extra_args;
100  
101 2 my $port = delete $opts{'port'};
102  
103 2 ▶ if (my $tls_verify = delete $opts{'tls_verify'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $tls_verify = delete $opts{"tls_verify"}) 0 2 2
104 0 my $val = $TLS_VERIFY{$tls_verify};
105 0 ▶ if (!defined $val) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $val) 0 0 0
106 0 Carp::croak "Bad `tls_verify`: $tls_verify";
107 }
108  
109 0 push @extra_args, tls_verify_yn => $val;
110 }
111  
112 2 push @extra_args, $class->_parse_event_args(%opts);
113  
114 2 return ( $peer, $port, @extra_args );
115 }
116  
117 1 ▶use constant _parse_event_args => ();
Subroutine BEGIN: called CC=1 SCAR=0.0
118  
119 #----------------------------------------------------------------------
120  
121 =head1 METHODS
122  
123 =head2 $obj = I<CLASS>->new( $HOSTNAME_OR_IP, %OPTS )
124  
125 Instantiates I<CLASS>.
126  
127 %OPTS will depend on the I<CLASS>, but can always include:
128  
129 =over
130  
131 =item * C<port> - The TCP port to connect to. Defaults to 443.
132  
133 =item * C<tls_verify> - Either C<peer> (default) or C<none>.
134  
135 =back
136  
137 =cut
138  
139 2 ▶sub new {
Subroutine new: called CC=2 SCAR=7.1
Pod documented
140 2 my ($class, @args) = @_;
141  
142 # TODO: Allow special options to be passed for TLS,
143 # e.g., verification options.
144  
145 2 my ($host, $port, @extra_args) = $class->_parse_args(@args);
146  
147 2 ▶ $port ||= Net::HTTP2::Constants::HTTPS_PORT;
Condition50%1/2
$port ||= 443
l!l
02
MC/DC0%0/1
$port ||= 443
$port
Truth table50%1/2
A
A= $port
Aresult
11
00
148  
149 2 my $rejectors_obj = Net::HTTP2::RejectorRegistry->new();
150  
151 2 my $self = bless {
152 host => $host,
153 port => $port,
154  
155 pid => $$,
156  
157 rejectors => $rejectors_obj,
158  
159 @extra_args,
160 }, $class;
161  
162 my @client_args = (
163 keepalive => 1,
164  
165 # H2 server push is, as of 2022, rarely used,
166 # so we won’t support it here.
167  
168 0 ▶ on_error => sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
169 0 my $errnum = shift;
170  
171 0 $rejectors_obj->reject_all(
172 Net::HTTP2::X->create('HTTP2', $errnum),
173 );
174 },
175 2 );
176  
177 2 if (_DEBUG) {
178 push @client_args, (
179 4 ▶ on_change_state => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
180 4 my ( $stream_id, $previous_state, $current_state ) = @_;
181 4 _debug( change_State => @_ );
182 },
183 2 );
184 }
185  
186 2 $self->{'h2'} = Protocol::HTTP2::Client->new(@client_args);
187  
188 2 return $self;
189 }
190  
191 =head2 promise($result) = I<OBJ>->request( $METHOD, $PATH_AND_QUERY, %OPTS )
192  
193 Sends an HTTP/2 request.
194  
195 Returns a promise (an instance of <Promise::ES6>, unless
196 otherwise noted in the subclass) that resolves to a L<Net::HTTP2::Response>
197 instance.
198  
199 %OPTS can be:
200  
201 =over
202  
203 =item * C<headers> - Request headers, as in L<HTTP::Tiny>’s C<request()>.
204  
205 =item * C<content> - Request content, as in L<HTTP::Tiny>’s C<request()>.
206  
207 =item * C<on_data> - A code reference that fires as each chunk of the
208 HTTP response arrives. The code reference always receives a
209 L<Net::HTTP2::PartialResponse> instance.
210  
211 =back
212  
213 On failure (I<NOT> including valid HTTP responses!), the promise rejects
214 with an instance of an appropriate L<Net::HTTP2::X::Base> class,
215 e.g., L<Net::HTTP2::X::HTTP2>.
216  
217 =cut
218  
219 2 ▶sub request {
Subroutine request: called CC=7 SCAR=24.9
Pod documented
220 2 my ($self, $method, $path_query, %opts) = @_;
221  
222 2 my @headers;
223  
224 2 ▶ if ($opts{'headers'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($opts{"headers"}) 0 2 2
225 0 for my $name (keys %{$opts{'headers'}}) {
226 0 my $val = $opts{'headers'}{$name};
227  
228 0 ▶ if ('ARRAY' eq ref $val) {
Branch: 1 branch
BranchTrueFalseTotal
if ('ARRAY' eq ref $val) { } 0 0 0
229 0 push @headers, $name => $_ for @$val;
230 }
231 else {
232 0 push @headers, $name => $val;
233 }
234 }
235 }
236  
237 2 my @extra_args;
238  
239 2 ▶ if (defined $opts{'content'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $opts{"content"}) 0 2 2
240 0 push @extra_args, data => $opts{'content'};
241 }
242  
243 2 ▶ if (my $data_cr = $opts{'on_data'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $data_cr = $opts{"on_data"}) 0 2 2
244 push @extra_args, (
245 0 ▶ on_headers => sub {
Subroutine __ANON__: not called CC=2 SCAR=17.9
246 0 my $canceled;
247  
248 0 $data_cr->( Net::HTTP2::PartialResponse->new(\$canceled, $_[0], q<>) );
249  
250 0 ▶ return !$canceled || undef;
Condition0%0/2
!$canceled || undef
l!l
00
MC/DC0%0/1
!$canceled || undef
!$canceled
Truth table0%0/2
not(A)
A= !$canceled
Aresult
11
00
251 },
252 0 ▶ on_data => sub {
Subroutine __ANON__: not called CC=2 SCAR=17.9
253 0 my $canceled;
254  
255 0 $data_cr->( Net::HTTP2::PartialResponse->new(\$canceled, @_[1, 0]) );
256  
257 0 ▶ return !$canceled || undef;
Condition0%0/2
!$canceled || undef
l!l
00
MC/DC0%0/1
!$canceled || undef
!$canceled
Truth table0%0/2
not(A)
A= !$canceled
Aresult
11
00
258 },
259 0 );
260 }
261  
262 2 my $rejectors_obj = $self->{'rejectors'};
263  
264 2 my $rejector_str;
265  
266 2 ▶ return $self->_get_promise_class()->new( sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
267 2 my ($res, $rej) = @_;
268  
269 2 $rejector_str = $rejectors_obj->add($rej);
270  
271 2 $self->_start_io_if_needed(@{$self}{'host', 'port', 'h2'});
272  
273 2 my $weak_h2 = $self->{'h2'};
274 2 Scalar::Util::weaken($weak_h2);
275  
276 2 my $authty = $self->{'host'};
277  
278 # Some services act differently if :443 is postfixed unnecessarily.
279 # For example, as of this writing perl.org will give a 404 rather
280 # than the redirect to www.perl.org that it should give.
281 #
282 2 ▶ $authty .= ":$self->{'port'}" if $self->{'port'} != Net::HTTP2::Constants::HTTPS_PORT;
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"port"} != 443 0 2 2
283  
284 $self->{'h2'}->request(
285 ':scheme' => 'https',
286 ':authority' => $authty,
287 ':path' => $path_query,
288 ':method' => $method,
289  
290 headers => \@headers,
291  
292 1 ▶ on_done => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
293 1 $res->( Net::HTTP2::Response->new(@_) );
294 },
295  
296 1 ▶ on_error => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
297 1 my $errnum = shift;
298 1 $rej->( Net::HTTP2::X->create('HTTP2', $errnum) );
299 },
300  
301 2 @extra_args,
302 );
303  
304 2 $self->_send_pending_frames();
305 2 ▶ } )->finally( sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
306 2 $rejectors_obj->remove($rejector_str);
307 2 } );
308 }
309  
310 # =head2 $obj = I<OBJ>->close()
311 #
312 # Tells the server we are ending the connection. Automatically called
313 # when I<OBJ> is DESTROY()ed, so you usually don’t need to call this.
314 #
315 # Returns a promise that resolves when the HTTP/2 GOAWAY frame is sent.
316 #
317 # =cut
318 #
319 # sub close {
320 # my ($self) = @_;
321 #
322 # if ($self->{'_close_called'}) {
323 # Carp::croak "Duplicate close() call\n";
324 # }
325 #
326 # $self->{'_close_called'} = 1;
327 #
328 # my $close_cr = sub {
329 # my $res = shift;
330 #
331 # $self->{'h2'}->close();
332 #
333 # $self->_send_pending_frames($res || ());
334 # };
335 #
336 # if (defined wantarray) {
337 # my $rejector_str;
338 #
339 # my $rejectors_obj = $self->{'rejectors'};
340 #
341 # return $self->{'_close_p'} ||= $self->_get_promise_class()->new( sub {
342 # my ($res, $rej) = @_;
343 #
344 # $rejector_str = $rejectors_obj->add($rej);
345 #
346 # $close_cr->($res);
347 # } )->finally( sub {
348 # $rejectors_obj->remove($rejector_str);
349 # } );
350 # }
351 # else {
352 # $close_cr->();
353 # }
354 # }
355  
356 #----------------------------------------------------------------------
357  
358 2 ▶sub DESTROY {
Subroutine DESTROY: called CC=4 SCAR=19.7
359 2 my $self = shift;
360  
361 2 $self->_h2_close();
362  
363 2 ▶ if (${^GLOBAL_PHASE} && ${^GLOBAL_PHASE} eq 'DESTRUCT') {
Branch: 1 branch
BranchTrueFalseTotal
if (${^GLOBAL_PHASE} and ${^GLOBAL_PHASE} eq "DESTRUCT") 0 2 2
Condition33%1/3
${^GLOBAL_PHASE} and ${^GLOBAL_PHASE} eq "DESTRUCT"
!ll&&!rl&&r
020
MC/DC0%0/2
${^GLOBAL_PHASE} and ${^GLOBAL_PHASE} eq "DESTRUCT"
${^GLOBAL_PHASE} ${^GLOBAL_PHASE} eq "DESTRUCT"
Truth table33%1/3
A and B
A= ${^GLOBAL_PHASE}B= ${^GLOBAL_PHASE} eq "DESTRUCT"
ABresult
0X0
100
111
364 0 ▶ if ($self->{'pid'} == $$) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"pid"} == $$) 0 0 0
365 0 warn "$self: DESTROY() at global destruction; memory leak likely!\n";
366 }
367 }
368 }
369  
370 2 ▶sub _h2_close {
Subroutine _h2_close: called CC=1 SCAR=0.0
371 2 my $self = shift;
372  
373 2 $self->{'h2'}->close();
374 2 $self->_send_pending_frames();
375 }
376  
377 0 ▶sub _on_stream_error {
Subroutine _on_stream_error: not called CC=2 SCAR=17.9
378 0 my ($self, $err) = @_;
379  
380 0 my $rejectors = $self->{'rejectors'};
381  
382 0 ▶ if ($rejectors->count()) {
Branch: 1 branch
BranchTrueFalseTotal
if ($rejectors->count) { } 0 0 0
383 0 $rejectors->reject_all($err);
384 }
385 else {
386 0 warn $err;
387 }
388 }
389  
390 0 ▶sub _on_stream_close {
Subroutine _on_stream_close: not called CC=3 SCAR=24.8
391 0 my $self = shift;
392  
393 0 my $rejectors = $self->{'rejectors'};
394  
395 0 ▶ if ($rejectors->count()) {
Branch: 2 branches
BranchTrueFalseTotal
if ($rejectors->count) { } 0 0 0
elsif (not $self->{'_close_called'}) { } 0 0 0
396 0 $rejectors->reject_all("Unexpected close of TCP stream!");
397 }
398 elsif (!$self->{'_close_called'}) {
399 0 print "TCP peer closed\n";
400 }
401 }
402  
403 4 ▶sub _send_pending_frames {
Subroutine _send_pending_frames: called CC=6 SCAR=26.2
404 4 my ($self, $cb) = @_;
405  
406 4 ▶ if ($cb) {
Branch: 1 branch
BranchTrueFalseTotal
if ($cb) { } 0 4 4
407 0 my @frames;
408  
409 0 ▶ while (my $frame = $self->{'h2'}->next_frame()) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $frame = $self->{"h2"}->next_frame) 0 0 0
410 0 push @frames, $frame;
411 }
412  
413 0 ▶ if (@frames) {
Branch: 1 branch
BranchTrueFalseTotal
if (@frames) 0 0 0
414 0 my $last_frame = pop @frames;
415  
416 0 $self->_write_frame($_) for @frames;
417 0 $self->_write_frame($last_frame, $cb);
418 }
419 }
420 else {
421 4 ▶ while (my $frame = $self->{'h2'}->next_frame()) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $frame = $self->{"h2"}->next_frame) 14 4 18
422 14 $self->_write_frame($frame);
423 }
424 }
425  
426 4 return;
427 }
428  
429 4 ▶sub _debug {
Subroutine _debug: called CC=1 SCAR=0.0
430 4 print STDERR "DEBUG: @_\n" if _DEBUG;
431 }
432  
433 2 ▶sub _get_promise_class {
Subroutine _get_promise_class: called CC=3 SCAR=11.0
434 2 my ($self) = @_;
435  
436 2 my $promise_class = $self->_PROMISE_CLASS();
437  
438 2 local ($!, $@);
439 2 ▶ eval "require $promise_class; 1" || die if !$promise_class->can('new');
Branch: 1 branch
BranchTrueFalseTotal
unless $promise_class->can("new") 1 1 2
Condition75%3/4
$promise_class->can('new') || (eval "require $promise_class; 1" || die())
l!l
11
eval "require $promise_class; 1" or die
l!l
10
MC/DC0%0/2
$promise_class->can('new') || (eval "require $promise_class; 1" || die())
$promise_class->can('new') eval "require $promise_class; 1"
Truth table66%2/3
A || B
A= $promise_class->can('new')B= eval "require $promise_class; 1"
ABresult
1X1
011
000
440  
441 2 return $promise_class;
442 }
443  
444 1 1;
« HTTP2/Client/Connection/IOAsync.pm ↑ Summary HTTP2/Response.pm »