VPNDetection.pm

filter: Statementstmt 100% 475 / 475 Branchbran 93.3% 211 / 226 Conditioncond 81.9% 145 / 177 MC/DCmcdc 66.6% 64 / 96 Subroutinesub 100% 87 / 87 Podpod 66.6% 8 / 12 totaltotal 92.2% 990 / 1073 CC 181 SCAR 24.6
CC
181
Cov
95%
_nonconforming
37.6
new
23.0
lookup_batch_p
20.2
CRAP 11.8
↑ Summary VPNDetection/Oauth.pm »
1 package VPNDetection;
2  
3 15 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 15 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5  
6 15 ▶use Carp ();
Subroutine BEGIN: called CC=1 SCAR=0.0
7 15 ▶use Exporter 'import';
Subroutine BEGIN: called CC=1 SCAR=0.0
8 15 ▶use Mojo::IOLoop;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 15 ▶use Mojo::Promise;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 15 ▶use Mojo::URL;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 15 ▶use Mojo::UserAgent;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 15 ▶use Mojo::Util ();
Subroutine BEGIN: called CC=1 SCAR=0.0
13 15 ▶use Scalar::Util ();
Subroutine BEGIN: called CC=1 SCAR=0.0
14  
15 15 ▶use VPNDetection::Bogon ();
Subroutine BEGIN: called CC=1 SCAR=0.0
16 15 ▶use VPNDetection::Cache;
Subroutine BEGIN: called CC=1 SCAR=0.0
17 15 ▶use VPNDetection::Database;
Subroutine BEGIN: called CC=1 SCAR=0.0
18 15 ▶use VPNDetection::Error;
Subroutine BEGIN: called CC=1 SCAR=0.0
19 15 ▶use VPNDetection::Oauth;
Subroutine BEGIN: called CC=1 SCAR=0.0
20 15 ▶use VPNDetection::Result;
Subroutine BEGIN: called CC=1 SCAR=0.0
21  
22 15 our $VERSION = '4.0.0';
23 15 our @EXPORT_OK = ('is_bogon');
24  
25 15 ▶use constant DEFAULT_BASE_URL => 'https://api.vpndetection.io';
Subroutine BEGIN: called CC=1 SCAR=0.0
26  
27 # The most addresses POST /batch takes in one call; a larger batch is sent in
28 # chunks of this size.
29 15 ▶use constant BATCH_MAX => 1000;
Subroutine BEGIN: called CC=1 SCAR=0.0
30  
31 # Seconds before the first retry; each later one waits twice the one before.
32 15 ▶use constant BACKOFF_BASE => 0.25;
Subroutine BEGIN: called CC=1 SCAR=0.0
33  
34 # The longest Retry-After honored, in seconds: 2**31 - 1 ms, about 24.8 days,
35 # the same bound as the .NET SDK's.
36 15 ▶use constant LONGEST_WAIT => 2_147_483.647;
Subroutine BEGIN: called CC=1 SCAR=0.0
37  
38 15 my %OPTIONS = map { $_ => 1 } qw(
39 api_key base_url cache_size cache_ttl concurrency retries timeout ua
40 );
41  
42 # The shapes of the answers, from the pinned spec's schemas: a member it requires
43 # and never sends as null is required, a nullable or optional one may be absent
44 # or null, and every one present has the spec's type at every depth, a `date` or
45 # `date-time` RFC 3339's on a day that exists. A detail is as optional as the plan
46 # makes it, so `{}` is one. A field's third element is 1 for a member that is
47 # required, and NOT_NULL for one an answer may lack (a plan without it) but never
48 # serves as null.
49 15 ▶use constant NOT_NULL => 2;
Subroutine BEGIN: called CC=1 SCAR=0.0
50  
51 my $VPN_DETAIL = [fields => [
52 15 (map { [$_ => ['string']] } qw(provider provider_name confidence)), [last_seen => ['date']],
53 ]];
54 15 my $CLASS_DETAIL = [fields => [(map { [$_ => ['string']] } qw(provider provider_name confidence)), [last_seen => ['date']]]];
55 my $PROXY_DETAIL = [fields => [
56 30 [provider => ['string']], [provider_name => ['string']], (map { [$_ => ['date']] } qw(first_seen last_seen)),
57 15 (map { [$_ => ['integer']] } qw(hits hits_days_pct providers_num)),
58 ]];
59 my $BOT_DETAIL = [fields => [
60 30 (map { [$_ => ['string']] } qw(provider provider_name)), (map { [$_ => [list => ['string']]] } qw(agents categories)),
61 45 [verified => ['boolean']], (map { [$_ => ['string']] } qw(identity verified_by confidence)),
62 15 (map { [$_ => ['date']] } qw(first_seen last_seen)),
63 ]];
64 15 my $PUBPROXY_DETAIL = [fields => [
65 [entry => ['boolean']], [exit => ['boolean']], [protocols => [list => ['string']]],
66 [num_ports => ['integer']], [num_proxies => ['integer']], [last_seen => ['date']],
67 [last_usable => ['string']],
68 ]];
69 15 my $CARRIER_DETAIL = [fields => [map { [$_ => ['string']] } qw(name mcc mnc country confidence)]];
70 my $SATELLITE_DETAIL = [fields => [
71 15 (map { [$_ => ['string']] } qw(provider provider_name orbit segment country confidence)),
72 [asn => ['integer']],
73 ]];
74 my $SSH_DETAIL = [fields => [
75 15 [port => ['integer']], (map { [$_ => ['string']] } qw(banner host_key_fp)), (map { [$_ => ['date']] } qw(first_seen last_seen)),
76 [session_ok => ['boolean']],
77 ]];
78 my $SMTP_DETAIL = [fields => [
79 15 [port => ['integer']], [banner => ['string']], (map { [$_ => ['date']] } qw(first_seen last_seen)),
80 [session_ok => ['boolean']],
81 ]];
82 my $WEB_ROW = [fields => [
83 30 (map { [$_ => ['integer'], 1] } qw(port status_code)),
84 45 (map { [$_ => ['boolean'], 1] } qw(tls_ok session_ok cert_browser_trusted)),
85 105 (map { [$_ => ['string'], 1] } qw(
86 server location title cert_subject_cn cert_subject_o cert_issuer_dn tls_version
87 )),
88 15 (map { [$_ => ['date'], 1] } qw(first_seen last_seen)),
89 ]];
90 my $DNS_RESOLVER_DETAIL = [fields => [
91 30 (map { [$_ => ['integer']] } qw(port rcode)), (map { [$_ => ['boolean']] } qw(recursion_available answer_correct)),
92 15 (map { [$_ => ['date']] } qw(first_seen last_seen)),
93 ]];
94 my $BITTORRENT_DETAIL = [fields => [
95 45 (map { [$_ => ['boolean']] } qw(verified id_matches_ip indexer)),
96 30 (map { [$_ => ['date']] } qw(first_seen last_seen)), [last_reachable => ['string']],
97 15 (map { [$_ => ['integer']] } qw(days_seen num_ports peak_num_ports)),
98 [clients => [list => ['string']]],
99 ]];
100 # Where the address is and the AS announcing it carry every member whenever they
101 # are present, bar the ones a plan may leave out.
102 my $LOCATION = [fields => [
103 150 (map { [$_ => ['string'], 1] } qw(
104 continent continent_name country country_name timezone currency_code currency_name
105 currency_symbol flag_emoji flag_unicode
106 )),
107 105 (map { [$_ => ['string']] } qw(region region_code city postal_code geoname_id dma_code last_changed)),
108 15 (map { [$_ => ['number']] } qw(latitude longitude)), [accuracy_radius => ['integer']],
109 ]];
110 my $ASN = [fields => [
111 15 [asn => ['integer'], 1], (map { [$_ => ['string'], 1] } qw(name domain prefix country rpki_status)),
112 [type => ['string'], NOT_NULL],
113 ]];
114 15 my $COMPANY = [fields => [(map { [$_ => ['string'], 1] } qw(name domain)), (map { [$_ => ['string']] } qw(type country))]];
115 my $ABUSE = [fields => [
116 15 [email => ['string'], 1], (map { [$_ => ['string']] } qw(name phone address country network unvalidated_since)),
117 [validated => ['boolean']],
118 ]];
119 our $LOOKUP = [fields => [
120 [ip => ['string'], 1], [is_vpn => ['boolean'], NOT_NULL], [is_bogon => ['boolean']],
121 270 (map { [$_ => ['boolean']] } qw(
122 is_hosting is_relay is_tor is_cdn is_bot is_resproxy is_dcproxy is_mobproxy is_pubproxy
123 is_anycast is_carrier is_satellite is_ssh is_smtp is_web is_dns_resolver is_bittorrent
124 cap_reached
125 )),
126 [vpn => $VPN_DETAIL],
127 60 (map { [$_ => $CLASS_DETAIL] } qw(hosting relay tor cdn)), [bot => $BOT_DETAIL],
128 45 (map { [$_ => $PROXY_DETAIL] } qw(resproxy dcproxy mobproxy)),
129 [pubproxy => $PUBPROXY_DETAIL],
130 [carrier => $CARRIER_DETAIL], [satellite => $SATELLITE_DETAIL], [ssh => $SSH_DETAIL],
131 [smtp => $SMTP_DETAIL], [web => [list => $WEB_ROW]], [dns_resolver => $DNS_RESOLVER_DETAIL],
132 [bittorrent => $BITTORRENT_DETAIL],
133 [location => $LOCATION], [asn => $ASN], [company => $COMPANY], [hostname => ['string']],
134 [abuse => $ABUSE],
135 15 [user_agent => [fields => [map { [$_ => ['string'], 1] } qw(agent kind verdict)]]],
136 ]];
137 15 our $BATCH_ERROR = [fields => [[status => ['integer'], 1], [error => ['string'], 1]]];
138 # Each entry is judged alone, by _lookup_chunk_p.
139 15 our $BATCH = [fields => [[results => [map_of => ['any']], 1], [errors => [map_of => ['any']], 1]]];
140 15 our $ENTITLEMENT = [fields => [
141 [org_id => ['string'], 1],
142 [apikey => [fields => [[id => ['string'], 1], [expires => ['date-time']], [allowed_cidrs => [list => ['string']], 1]]], 1],
143 [plan => [fields => [[key => ['string'], 1], [name => ['string'], 1], [tier => ['string'], 1]]], 1],
144 [usage => [fields => [
145 [requests => ['integer'], 1], [quota => ['integer'], 1], [hard_limit => ['integer']],
146 [window_start => ['date-time'], 1], [window_end => ['date-time'], 1],
147 ]], 1],
148 ]];
149  
150 952 ▶sub new {
Subroutine new: called CC=23 SCAR=31.4
Pod documented
151 952 my ($class, %args) = @_;
152 952 my @unknown = sort grep { !$OPTIONS{$_} } keys %args;
153 952 ▶ Carp::croak("VPNDetection->new: unknown option(s): @unknown") if @unknown;
Branch: 1 branch
BranchTrueFalseTotal
if @unknown 5 947 952
154  
155 947 ▶ my $concurrency = defined $args{concurrency} ? $args{concurrency} : 8;
Branch: 1 branch
BranchTrueFalseTotal
defined $args{'concurrency'} ? : 11 936 947
156 947 ▶ my $retries = defined $args{retries} ? $args{retries} : 2;
Branch: 1 branch
BranchTrueFalseTotal
defined $args{'retries'} ? : 693 254 947
157 947 ▶ my $cache_size = defined $args{cache_size} ? $args{cache_size} : 10_000;
Branch: 1 branch
BranchTrueFalseTotal
defined $args{'cache_size'} ? : 598 349 947
158 947 ▶ Carp::croak('VPNDetection->new: concurrency must be a whole number, 1 or more') unless _is_count($concurrency, 1);
Branch: 1 branch
BranchTrueFalseTotal
unless _is_count($concurrency, 1) 9 938 947
159 938 ▶ Carp::croak('VPNDetection->new: retries must be a whole number, 0 or more') unless _is_count($retries, 0);
Branch: 1 branch
BranchTrueFalseTotal
unless _is_count($retries, 0) 7 931 938
160 931 ▶ Carp::croak('VPNDetection->new: cache_size must be a whole number, 0 or more') unless _is_count($cache_size, 0);
Branch: 1 branch
BranchTrueFalseTotal
unless _is_count($cache_size, 0) 8 923 931
161 # NaN compares false with any time, so a NaN lifetime never went stale and
162 # held every answer for good; a negative or non-numeric one cached nothing.
163 923 ▶ my $cache_ttl = defined $args{cache_ttl} ? $args{cache_ttl} : 3600;
Branch: 1 branch
BranchTrueFalseTotal
defined $args{'cache_ttl'} ? : 28 895 923
164 923 ▶ Carp::croak('VPNDetection->new: cache_ttl must be a number of seconds, 0 or more')
Branch: 1 branch
BranchTrueFalseTotal
unless not ref $cache_ttl and &Scalar::Util::looks_like_number($cache_ttl) and $cache_ttl >= 0 10 913 923
Condition100%6/6
not ref $cache_ttl and &Scalar::Util::looks_like_number($cache_ttl) and $cache_ttl >= 0
!ll&&!rl&&r
55913
not ref $cache_ttl and &Scalar::Util::looks_like_number($cache_ttl)
!ll&&!rl&&r
23918
MC/DC100%3/3
not ref $cache_ttl and &Scalar::Util::looks_like_number($cache_ttl) and $cache_ttl >= 0
not ref $cache_ttl &Scalar::Util::looks_like_number($cache_ttl) $cache_ttl >= 0
Truth table100%4/4
not(A) and B and C
A= not ref $cache_ttlB= &Scalar::Util::looks_like_number($cache_ttl)C= $cache_ttl >= 0
ABCresult
0XX0
10X0
1100
1111
165 unless !ref $cache_ttl && Scalar::Util::looks_like_number($cache_ttl) && $cache_ttl >= 0;
166 # Mojo arms a negative or non-numeric bound as a timer that fires at once, so
167 # every call would fail as a network error.
168 913 ▶ my $timeout = defined $args{timeout} ? $args{timeout} : 30;
Branch: 1 branch
BranchTrueFalseTotal
defined $args{'timeout'} ? : 41 872 913
169 913 ▶ Carp::croak('VPNDetection->new: timeout must be a number of seconds, 0 or more')
Branch: 1 branch
BranchTrueFalseTotal
unless &Scalar::Util::looks_like_number($timeout) and $timeout >= 0 2 911 913
Condition100%3/3
&Scalar::Util::looks_like_number($timeout) and $timeout >= 0
!ll&&!rl&&r
11911
MC/DC100%2/2
&Scalar::Util::looks_like_number($timeout) and $timeout >= 0
&Scalar::Util::looks_like_number($timeout) $timeout >= 0
Truth table100%3/3
A and B
A= &Scalar::Util::looks_like_number($timeout)B= $timeout >= 0
ABresult
0X0
100
111
170 unless Scalar::Util::looks_like_number($timeout) && $timeout >= 0;
171  
172 # Trimmed, so a key read from a file loses its newline, and blanks alone are
173 # no key. Mojo refuses a CR or LF in a header with a raw string from every
174 # call and sends any other control character, so one left inside is refused
175 # here, naming the cause and not the key.
176 911 my $api_key = $args{api_key};
177 911 ▶ if (defined $api_key) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $api_key) 539 372 911
178 539 $api_key =~ s/\A\s+|\s+\z//g;
179 539 ▶ $api_key = undef unless length $api_key;
Branch: 1 branch
BranchTrueFalseTotal
unless length $api_key 3 536 539
180 }
181 911 ▶ Carp::croak('VPNDetection->new: api_key holds a control character')
Branch: 1 branch
BranchTrueFalseTotal
if defined $api_key and $api_key =~ /[\x00-\x1f\x7f]/ 3 908 911
Condition100%3/3
defined $api_key and $api_key =~ /[\x00-\x1f\x7f]/
!ll&&!rl&&r
3755333
MC/DC100%2/2
defined $api_key and $api_key =~ /[\x00-\x1f\x7f]/
defined $api_key $api_key =~ /[\x00-\x1f\x7f]/
Truth table100%3/3
A and B
A= defined $api_keyB= $api_key =~ /[\x00-\x1f\x7f]/
ABresult
0X0
100
111
182 if defined $api_key && $api_key =~ /[\x00-\x1f\x7f]/;
183 # Mojo writes a header as bytes, so a character past U+00FF dies in the
184 # reactor and every call fails after its whole timeout with nothing sent.
185 908 ▶ Carp::croak('VPNDetection->new: api_key holds a character past U+00FF')
Branch: 1 branch
BranchTrueFalseTotal
if defined $api_key and $api_key =~ /[^\x00-\xff]/ 2 906 908
Condition100%3/3
defined $api_key and $api_key =~ /[^\x00-\xff]/
!ll&&!rl&&r
3755312
MC/DC100%2/2
defined $api_key and $api_key =~ /[^\x00-\xff]/
defined $api_key $api_key =~ /[^\x00-\xff]/
Truth table100%3/3
A and B
A= defined $api_keyB= $api_key =~ /[^\x00-\xff]/
ABresult
0X0
100
111
186 if defined $api_key && $api_key =~ /[^\x00-\xff]/;
187  
188 my $self = bless {
189 api_key => $api_key,
190 base_url => _base_url($args{base_url}),
191 concurrency => 0 + $concurrency,
192 retries => 0 + $retries,
193 # Numified: Mojo arms a bound only when it is true, and '0.0', '00', '0e0'
194 # and '0 but true' are true strings, each a timer that fires at once.
195 timeout => 0 + $timeout,
196 cache => $cache_size > 0 ? VPNDetection::Cache->new(max => 0 + $cache_size, ttl => 0 + $cache_ttl) : undef,
197 # The addresses with a request in flight, each a promise its waiters
198 # take the answer from (see _board).
199 flights => {},
200 906 ▶ ua => $args{ua} || Mojo::UserAgent->new,
Branch: 1 branch
BranchTrueFalseTotal
$cache_size > 0 ? : 320 586 906
Condition66%2/3
$args{'ua'} || 'Mojo::UserAgent'->new
l!l&&r!l&&!r
49020
MC/DC0%0/2
$args{'ua'} || 'Mojo::UserAgent'->new
$args{'ua'} 'Mojo::UserAgent'->new
Truth table66%2/3
A || B
A= $args{'ua'}B= 'Mojo::UserAgent'->new
ABresult
1X1
011
000
201 }, $class;
202  
203 # Mojo::UserAgent does not follow redirects by default, but MOJO_MAX_REDIRECTS
204 # in the environment turns that on for every agent in the process. Setting it
205 # here is what stops the database download's 302 being chased into a
206 # multi-gigabyte transfer, on a machine whose environment we do not own.
207 906 $self->{ua}->max_redirects(0);
208 906 $self->{ua}->request_timeout($self->{timeout});
209 906 $self->{ua}->transactor->name("vpndetection-perl/$VERSION");
210 906 return $self;
211 }
212  
213 # Both a method and an exportable function, so the address is the LAST argument
214 # either way: is_bogon($ip) and $client->is_bogon($ip) reach the same code.
215 565 ▶sub is_bogon {
Subroutine is_bogon: called CC=3 SCAR=12.5
Pod documented
216 565 my $ip = pop;
217 565 ▶ Carp::croak('is_bogon: expected an IP address') if !defined $ip || ref $ip;
Branch: 1 branch
BranchTrueFalseTotal
if not defined $ip or ref $ip 0 565 565
Condition33%1/3
not defined $ip or ref $ip
l!l&&r!l&&!r
00565
MC/DC0%0/2
not defined $ip or ref $ip
not defined $ip ref $ip
Truth table33%1/3
not(A) or B
A= not defined $ipB= ref $ip
ABresult
1X1
011
000
218 565 return VPNDetection::Bogon::is_bogon($ip);
219 }
220  
221 # Classify one address. A bogon is answered locally and never reaches the
222 # network; everything else is served, then cached for this client. An answer past
223 # the organization's allowance, carrying cap_reached true, raises quota_exceeded
224 # with that answer as its result, fresh or from the cache.
225 539 ▶sub lookup {
Subroutine lookup: called CC=1 SCAR=0.0
Pod documented
226 539 my $self = shift;
227 539 $self->_assert_blocking_ok('lookup');
228 538 return $self->_wait($self->lookup_p(@_));
229 }
230  
231 592 ▶sub lookup_p {
Subroutine lookup_p: called CC=9 SCAR=22.0
Pod undocumented
232 592 my ($self, $ip, %options) = @_;
233 592 ▶ Carp::croak('lookup: expected an IP address') if !defined $ip || !length $ip;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $ip and length $ip 0 592 592
Condition33%1/3
defined $ip and length $ip
!ll&&!rl&&r
00592
MC/DC0%0/2
defined $ip and length $ip
defined $ip length $ip
Truth table33%1/3
A and B
A= defined $ipB= length $ip
ABresult
0X0
100
111
234 592 $self->_check_options('lookup', \%options, 'retries', 'timeout', 'user_agent');
235 569 my $agent = _agent('lookup', $options{user_agent});
236 # Judged, cached and sent as the IPv4 address it carries, if it is mapped.
237 568 $ip = VPNDetection::Bogon::unmapped($ip);
238  
239 # A bogon is never sent, so it carries no user_agent.
240 568 ▶ return Mojo::Promise->resolve(VPNDetection::Bogon::bogon_result($ip))
Branch: 1 branch
BranchTrueFalseTotal
if VPNDetection::Bogon::is_bogon($ip) 6 562 568
241 if VPNDetection::Bogon::is_bogon($ip);
242  
243 # An answer to an agent is cached and shared on the address and that agent,
244 # apart from the address's plain answer and from another agent's.
245 562 my $key = _key($ip, $agent);
246 562 ▶ if ($self->{cache}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"cache"}) 171 391 562
247 171 my $hit = $self->{cache}->get($key);
248 171 ▶ return _answer_p($hit) if $hit;
Branch: 1 branch
BranchTrueFalseTotal
if $hit 25 146 171
249 # A miss for an address already in flight, for a lookup or a batch,
250 # takes that request's answer rather than sending its own.
251 146 ▶ return $self->{flights}{$key}->then(sub { shift }) if $self->{flights}{$key};
Subroutine __ANON__: called CC=1 SCAR=0.0
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"flights"}{$key} 37 109 146
252 }
253  
254 500 my $flight = $self->_board($key);
255 500 my $url = $self->_url('/' . Mojo::Util::url_escape($ip, '^A-Za-z0-9\-._~:'), _agent_query($agent));
256 500 ▶ my $retries = defined $options{retries} ? $options{retries} : $self->{retries};
Branch: 1 branch
BranchTrueFalseTotal
defined $options{'retries'} ? : 2 498 500
257 # Anything that dies before a request is under way lands the flight too, or
258 # every later lookup of the address would wait on it forever (3.8.0).
259 500 ▶ my $sent = eval { $self->_retry_p($retries, sub { $self->_json_p($url, undef, $options{timeout}, undef, $LOOKUP) }) };
Subroutine __ANON__: called CC=1 SCAR=0.0
260 500 ▶ if (!$sent) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($sent) 2 498 500
261 2 my $error = $@;
262 2 $self->_land($key, $flight, 0, $error);
263 2 die $error;
264 }
265 return $sent->then(
266 191 ▶ sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
267 191 my $result = VPNDetection::Result->from_wire(shift);
268 # Only a served answer is cached, and before it lands, so a miss
269 # after the flight is gone finds it. Errors never are, and bogons
270 # never reach this far. A capped answer is one: the cache holds the
271 # answer, so a hit raises again, and the raise happens here, after
272 # the retries, which a capped answer never gets.
273 191 ▶ $self->{cache}->set($key, $result) if $self->{cache};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"cache"} 90 101 191
274 191 ▶ if (my $capped = _capped($result)) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $capped = _capped($result)) 13 178 191
275 13 $self->_land($key, $flight, 0, $capped);
276 13 die $capped;
277 }
278 178 $self->_land($key, $flight, 1, $result);
279 178 return $result;
280 },
281 307 ▶ sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
282 307 my $error = shift;
283 307 $self->_land($key, $flight, 0, $error);
284 307 return Mojo::Promise->reject($error);
285 },
286 498 );
287 }
288  
289 # The error a capped answer raises, or undef for one within the allowance: only
290 # cap_reached true is capped, so false, null, absent and a bogon's answer are not.
291 28777 ▶sub _capped {
Subroutine _capped: called CC=2 SCAR=6.9
292 28777 my ($result) = @_;
293 28777 ▶ return $result->cap_reached ? VPNDetection::Error->capped($result) : undef;
Branch: 1 branch
BranchTrueFalseTotal
$result->cap_reached ? : 30 28747 28777
294 }
295  
296 # An answer already in hand, as the promise of it: resolved, or rejected with the
297 # error a capped one raises.
298 36 ▶sub _answer_p {
Subroutine _answer_p: called CC=2 SCAR=6.9
299 36 my ($result) = @_;
300 36 my $capped = _capped($result);
301 36 ▶ return $capped ? Mojo::Promise->reject($capped) : Mojo::Promise->resolve($result);
Branch: 1 branch
BranchTrueFalseTotal
$capped ? : 7 29 36
302 }
303  
304 # Concurrent misses for one address share ONE request: 3.3.2 sent one per
305 # caller. The first miss boards the address, and
306 # every miss after it, a batch's included, waits for that request instead. The
307 # request runs under the options of the call that led it; a failure reaches
308 # every waiter and is cached for none. Nothing is shared without a cache, since
309 # every lookup is then served. A Mojo::Promise cannot be canceled, so no waiter
310 # is ever left behind by a leader that gave up.
311 29077 ▶sub _board {
Subroutine _board: called CC=2 SCAR=6.9
312 29077 my ($self, $key) = @_;
313 29077 ▶ return undef unless $self->{cache};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"cache"} 27928 1149 29077
314 1149 my $flight = Mojo::Promise->new;
315 # Handled even when no waiter joined, so a failure is not warned about.
316 1149 ▶ $flight->catch(sub { });
Subroutine __ANON__: called CC=1 SCAR=0.0
317 1149 return $self->{flights}{$key} = $flight;
318 }
319  
320 # Takes an address off the board and settles its flight for every waiter.
321 29077 ▶sub _land {
Subroutine _land: called CC=5 SCAR=16.7
322 29077 my ($self, $key, $flight, $ok, $value) = @_;
323 29077 ▶ return unless $flight;
Branch: 1 branch
BranchTrueFalseTotal
unless $flight 27928 1149 29077
324 delete $self->{flights}{$key}
325 1149 ▶ if $self->{flights}{$key} && $self->{flights}{$key} == $flight;
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"flights"}{$key} and $self->{"flights"}{$key} == $flight 1149 0 1149
Condition33%1/3
$self->{"flights"}{$key} and $self->{"flights"}{$key} == $flight
!ll&&!rl&&r
001149
MC/DC0%0/2
$self->{"flights"}{$key} and $self->{"flights"}{$key} == $flight
$self->{"flights"}{$key} $self->{"flights"}{$key} == $flight
Truth table33%1/3
A and B
A= $self->{"flights"}{$key}B= $self->{"flights"}{$key} == $flight
ABresult
0X0
100
111
326 1149 ▶ return $ok ? $flight->resolve($value) : $flight->reject($value);
Branch: 1 branch
BranchTrueFalseTotal
$ok ? : 1105 44 1149
327 }
328  
329 # The cache and flight key of an address and the agent sent with it. A NUL can
330 # be in neither an address the API answers nor a header, so no pair reads as
331 # another.
332 87334 ▶sub _key {
Subroutine _key: called CC=2 SCAR=6.9
333 87334 my ($ip, $agent) = @_;
334 87334 ▶ return defined $agent ? "$ip\0$agent" : $ip;
Branch: 1 branch
BranchTrueFalseTotal
defined $agent ? : 30 87304 87334
335 }
336  
337 # The user agent a call sends: undef for none, an empty one included, as the API
338 # reads `user_agent=`. One longer than the spec's 1024 characters is sent whole,
339 # since the API cuts it there and answers.
340 29192 ▶sub _agent {
Subroutine _agent: called CC=4 SCAR=13.9
341 29192 my ($method, $agent) = @_;
342 29192 ▶ return undef unless defined $agent;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $agent 29158 34 29192
343 34 ▶ Carp::croak("VPNDetection::$method: user_agent must be a string") if ref $agent;
Branch: 1 branch
BranchTrueFalseTotal
if ref $agent 3 31 34
344 31 ▶ return length $agent ? "$agent" : undef;
Branch: 1 branch
BranchTrueFalseTotal
length $agent ? : 28 3 31
345 }
346  
347 # The query a lookup sends its agent in. Mojo percent-encodes every byte but
348 # letters, digits and `*-._`, a `+` included, and writes a space as `+`.
349 530 ▶sub _agent_query {
Subroutine _agent_query: called CC=2 SCAR=6.9
350 530 my ($agent) = @_;
351 530 ▶ return defined $agent ? (user_agent => $agent) : ();
Branch: 1 branch
BranchTrueFalseTotal
defined $agent ? : 12 518 530
352 }
353  
354 # The address our edge observed this client calling from. Deliberately not
355 # cached: the cache is keyed by address, and which address this is IS the
356 # question.
357 38 ▶sub my_ip {
Subroutine my_ip: called CC=1 SCAR=0.0
Pod documented
358 38 my $self = shift;
359 38 $self->_assert_blocking_ok('my_ip');
360 38 return $self->_wait($self->my_ip_p(@_));
361 }
362  
363 38 ▶sub my_ip_p {
Subroutine my_ip_p: called CC=2 SCAR=7.0
Pod undocumented
364 38 my ($self, %options) = @_;
365 38 $self->_check_options('my_ip', \%options, 'retries', 'timeout', 'user_agent');
366  
367 31 my $url = $self->_url('/myip', _agent_query(_agent('my_ip', $options{user_agent})));
368 30 ▶ my $retries = defined $options{retries} ? $options{retries} : $self->{retries};
Branch: 1 branch
BranchTrueFalseTotal
defined $options{'retries'} ? : 0 30 30
369 32 ▶ return $self->_retry_p($retries, sub { $self->_json_p($url, undef, $options{timeout}, undef, $LOOKUP) })
Subroutine __ANON__: called CC=1 SCAR=0.0
370 30 ▶ ->then(sub { _answer_p(VPNDetection::Result->from_wire(shift)) });
Subroutine __ANON__: called CC=1 SCAR=0.0
371 }
372  
373 # What this key is entitled to and what it has spent. Deliberately not cached:
374 # the whole point is the number, and a cached one is wrong within seconds.
375 89 ▶sub my_entitlement {
Subroutine my_entitlement: called CC=1 SCAR=0.0
Pod documented
376 89 my $self = shift;
377 89 $self->_assert_blocking_ok('my_entitlement');
378 89 return $self->_wait($self->my_entitlement_p(@_));
379 }
380  
381 89 ▶sub my_entitlement_p {
Subroutine my_entitlement_p: called CC=2 SCAR=7.0
Pod undocumented
382 89 my ($self, %options) = @_;
383 89 $self->_check_options('my_entitlement', \%options, 'retries', 'timeout');
384  
385 82 my $url = $self->_url('/api/v1/entitlement');
386 82 ▶ my $retries = defined $options{retries} ? $options{retries} : $self->{retries};
Branch: 1 branch
BranchTrueFalseTotal
defined $options{'retries'} ? : 0 82 82
387 82 ▶ return $self->_retry_p($retries, sub { $self->_json_p($url, undef, $options{timeout}, undef, $ENTITLEMENT) });
Subroutine __ANON__: called CC=1 SCAR=0.0
388 }
389  
390 # Classify many addresses concurrently, keyed by address rather than positional,
391 # so duplicates collapse to one request and the caller never lines two lists up.
392 73 ▶sub lookup_batch {
Subroutine lookup_batch: called CC=1 SCAR=0.0
Pod documented
393 73 my $self = shift;
394 73 $self->_assert_blocking_ok('lookup_batch');
395 73 return $self->_wait($self->lookup_batch_p(@_));
396 }
397  
398 94 ▶sub lookup_batch_p {
Subroutine lookup_batch_p: called CC=20 SCAR=30.1
Pod undocumented
399 94 my ($self, $ips, %options) = @_;
400 94 ▶ Carp::croak('lookup_batch: expected an array reference of addresses')
Branch: 1 branch
BranchTrueFalseTotal
if ref $ips ne "ARRAY" 0 94 94
401 if ref $ips ne 'ARRAY';
402 94 $self->_check_options('lookup_batch', \%options, 'retries', 'concurrency', 'timeout', 'user_agents');
403 63 my $wanted = $options{user_agents};
404 63 ▶ Carp::croak('VPNDetection::lookup_batch: user_agents must be a hash reference of address to agent')
Branch: 1 branch
BranchTrueFalseTotal
if defined $wanted and ref $wanted ne "HASH" 1 62 63
Condition100%3/3
defined $wanted and ref $wanted ne "HASH"
!ll&&!rl&&r
5751
MC/DC100%2/2
defined $wanted and ref $wanted ne "HASH"
defined $wanted ref $wanted ne "HASH"
Truth table100%3/3
A and B
A= defined $wantedB= ref $wanted ne "HASH"
ABresult
0X0
100
111
405 if defined $wanted && ref $wanted ne 'HASH';
406  
407 62 ▶ my $limit = defined $options{concurrency} ? $options{concurrency} : $self->{concurrency};
Branch: 1 branch
BranchTrueFalseTotal
defined $options{'concurrency'} ? : 4 58 62
408 62 ▶ my $retries = defined $options{retries} ? $options{retries} : $self->{retries};
Branch: 1 branch
BranchTrueFalseTotal
defined $options{'retries'} ? : 0 62 62
409  
410 # Bogons are answered locally and cached answers are reused; everything else
411 # goes to the batch endpoint in chunks of up to 1000 addresses, with at most
412 # `limit` chunks in flight. Keyed by address rather than positional, so
413 # duplicates in the input collapse to a single entry and the caller never has
414 # to line two lists up.
415 # An IPv4-mapped address is sent as the address it carries, once however
416 # many of its spellings were asked, and answered under each one asked.
417 62 ▶ my @asked = grep { defined && length } @$ips;
Condition33%1/3
defined $_ && length $_
!ll&&!rl&&r
0028592
MC/DC0%0/2
defined $_ && length $_
defined $_ length $_
Truth table33%1/3
A && B
A= defined $_B= length $_
ABresult
0X0
100
111
418 # Each address's agent, keyed by the address as sent: where two spellings of
419 # one IPv4-mapped address carry different agents, the first listed is sent.
420 62 my %agents;
421 62 for my $ip (@asked) {
422 28592 ▶ my $agent = _agent('lookup_batch', $wanted ? $wanted->{$ip} : undef);
Branch: 1 branch
BranchTrueFalseTotal
$wanted ? : 1009 27583 28592
423 28591 ▶ $agents{ VPNDetection::Bogon::unmapped($ip) } //= $agent if defined $agent;
Branch: 1 branch
BranchTrueFalseTotal
if defined $agent 4 28587 28591
Condition33%1/3
$agents{VPNDetection::Bogon::unmapped($ip)} //= $agent
l!l&&r!l&&!r
040
MC/DC0%0/2
$agents{VPNDetection::Bogon::unmapped($ip)} //= $agent
$agents{VPNDetection::Bogon::unmapped($ip)} $agent
Truth table33%1/3
A //= B
A= $agents{VPNDetection::Bogon::unmapped($ip)}B= $agent
ABresult
1X1
011
000
424 }
425 61 my %seen;
426 61 my @unique = grep { !$seen{$_}++ } map { VPNDetection::Bogon::unmapped($_) } @asked;
427 61 my %answers;
428 my @pending;
429 61 my %joined;
430 61 for my $ip (@unique) {
431 28588 ▶ if (VPNDetection::Bogon::is_bogon($ip)) {
Branch: 1 branch
BranchTrueFalseTotal
if (VPNDetection::Bogon::is_bogon($ip)) 5 28583 28588
432 5 $answers{$ip} = VPNDetection::Bogon::bogon_result($ip);
433 5 next;
434 }
435 28583 my $key = _key($ip, $agents{$ip});
436 28583 ▶ my $hit = $self->{cache} ? $self->{cache}->get($key) : undef;
Branch: 1 branch
BranchTrueFalseTotal
$self->{'cache'} ? : 1046 27537 28583
437 28583 ▶ if ($hit) {
Branch: 1 branch
BranchTrueFalseTotal
if ($hit) 3 28580 28583
438 3 ▶ $answers{$ip} = _capped($hit) || $hit;
Condition66%2/3
_capped($hit) || $hit
l!l&&r!l&&!r
210
MC/DC0%0/2
_capped($hit) || $hit
_capped($hit) $hit
Truth table66%2/3
A || B
A= _capped($hit)B= $hit
ABresult
1X1
011
000
439 3 next;
440 }
441 # Already in flight with the same agent, for a lookup or another batch:
442 # this batch takes that request's answer rather than sending it again.
443 28580 ▶ if ($self->{cache} && $self->{flights}{$key}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"cache"} and $self->{"flights"}{$key}) 3 28577 28580
Condition100%3/3
$self->{"cache"} and $self->{"flights"}{$key}
!ll&&!rl&&r
2753710403
MC/DC100%2/2
$self->{"cache"} and $self->{"flights"}{$key}
$self->{"cache"} $self->{"flights"}{$key}
Truth table100%3/3
A and B
A= $self->{"cache"}B= $self->{"flights"}{$key}
ABresult
0X0
100
111
444 3 $joined{$ip} = $self->{flights}{$key};
445 3 next;
446 }
447 28577 push @pending, $ip;
448 }
449 # Boarded before any chunk is built, so a lookup of one of these arriving
450 # meanwhile waits for this batch's answer.
451 61 my %boarded = map { ($_ => $self->_board(_key($_, $agents{$_}))) } @pending;
452 61 my @queue;
453 61 ▶ push @queue, [splice @pending, 0, BATCH_MAX] while @pending;
Branch: 1 branch
BranchTrueFalseTotal
@pending and do { push @queue, [splice(@pending, 0, 1000)] } 83 61 144
454  
455 my $batch = {
456 queue => \@queue, answers => \%answers, active => 0, limit => $limit,
457 61 retries => $retries, timeout => $options{timeout}, promise => Mojo::Promise->new,
458 boarded => \%boarded, agents => \%agents,
459 };
460 61 $self->_dispatch($batch);
461 my $done = %joined ? Mojo::Promise->all(
462 $batch->{promise},
463 map {
464 3 my $ip = $_;
465 $joined{$ip}->then(
466 2 ▶ sub { $answers{$ip} = shift },
Subroutine __ANON__: called CC=1 SCAR=0.0
467 1 ▶ sub { $answers{$ip} = VPNDetection::Error->wrap(shift) },
Subroutine __ANON__: called CC=1 SCAR=0.0
468 3 );
469 } sort keys %joined,
470 61 ▶ ) : $batch->{promise};
Branch: 1 branch
BranchTrueFalseTotal
%joined ? : 3 58 61
471 61 ▶ return $done->then(sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
472 61 return { map { ($_ => $answers{ VPNDetection::Bogon::unmapped($_) }) } @asked };
473 61 });
474 }
475  
476 # The licensed dataset downloads. Built per call rather than held, so the client
477 # and its sub-API never form a reference cycle.
478 195 ▶sub database {
Subroutine database: called CC=1 SCAR=0.0
Pod documented
479 195 my ($self) = @_;
480 195 return VPNDetection::Database->_new($self);
481 }
482  
483 # The OAuth device-flow sign-in, built per call for the same reason.
484 164 ▶sub oauth {
Subroutine oauth: called CC=1 SCAR=0.0
Pod documented
485 164 my ($self) = @_;
486 164 return VPNDetection::Oauth->_new($self);
487 }
488  
489 # Keeps exactly `limit` chunks in flight: every answer starts the next one, so a
490 # per-call concurrency is a real ceiling rather than an option that was accepted
491 # and ignored. A failing address carries its error as its value, so one bad
492 # entry cannot lose the rest of the answers: the API reports a per-entry failure
493 # with the status the single lookup would have answered, and a chunk that fails
494 # as a whole marks every address in it.
495 144 ▶sub _dispatch {
Subroutine _dispatch: called CC=5 SCAR=16.1
496 144 my ($self, $batch) = @_;
497 144 ▶ if (!@{$batch->{queue}} && !$batch->{active}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (@{$batch->{"queue"};} or $batch->{"active"}) 61 83 144
Condition100%3/3
@{$batch->{"queue"};} or $batch->{"active"}
l!l&&r!l&&!r
74961
MC/DC100%2/2
@{$batch->{"queue"};} or $batch->{"active"}
@{$batch->{"queue"};} $batch->{"active"}
Truth table100%3/3
A or B
A= @{$batch->{"queue"};}B= $batch->{"active"}
ABresult
1X1
011
000
498 61 $batch->{promise}->resolve($batch->{answers});
499 61 return;
500 }
501 83 ▶ while ($batch->{active} < $batch->{limit} && @{$batch->{queue}}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($batch->{"active"} < $batch->{"limit"} and @{$batch->{"queue"};}) 83 83 166
Condition100%3/3
$batch->{"active"} < $batch->{"limit"} and @{$batch->{"queue"};}
!ll&&!rl&&r
245983
MC/DC100%2/2
$batch->{"active"} < $batch->{"limit"} and @{$batch->{"queue"};}
$batch->{"active"} < $batch->{"limit"} @{$batch->{"queue"};}
Truth table100%3/3
A and B
A= $batch->{"active"} < $batch->{"limit"}B= @{$batch->{"queue"};}
ABresult
0X0
100
111
502 83 my $chunk = shift @{$batch->{queue}};
503 83 $batch->{active}++;
504 83 ▶ $self->_lookup_chunk_p($chunk, $batch->{agents}, $batch->{retries}, $batch->{timeout})->then(sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
505 83 my $answers = shift;
506 83 for my $ip (keys %$answers) {
507 28577 my $answer = $answers->{$ip};
508 28577 $batch->{answers}{$ip} = $answer;
509 28577 ▶ my $failed = Scalar::Util::blessed($answer) && $answer->isa('VPNDetection::Error');
Condition66%2/3
builtin::blessed($answer) && $answer->isa('VPNDetection::Error')
!ll&&!rl&&r
02853938
MC/DC50%1/2
builtin::blessed($answer) && $answer->isa('VPNDetection::Error')
builtin::blessed($answer) $answer->isa('VPNDetection::Error')
Truth table66%2/3
A && B
A= builtin::blessed($answer)B= $answer->isa('VPNDetection::Error')
ABresult
0X0
100
111
510 28577 $self->_land(_key($ip, $batch->{agents}{$ip}), $batch->{boarded}{$ip}, !$failed, $answer);
511 }
512 83 $self->_settled($batch);
513 83 });
514 }
515 }
516  
517 # One POST /batch, mapped back onto the addresses it was asked about. A
518 # chunk-level failure - the call refused, the transport failing, the retries
519 # exhausted - becomes every address's error, exactly as it would have been had
520 # each been looked up alone. Never rejects: the failure is the value.
521 83 ▶sub _lookup_chunk_p {
Subroutine _lookup_chunk_p: called CC=2 SCAR=6.9
522 83 my ($self, $chunk, $agents, $retries, $timeout) = @_;
523 83 my $url = $self->_url('/batch');
524 # Sent only when an address of this chunk carries an agent, never as {}.
525 83 my %sent = map { ($_ => $agents->{$_}) } grep { defined $agents->{$_} } @$chunk;
526 83 ▶ my $body = { ips => $chunk, %sent ? (user_agents => \%sent) : () };
Branch: 1 branch
BranchTrueFalseTotal
%sent ? : 2 81 83
527 84 ▶ return $self->_retry_p($retries, sub { $self->_json_p($url, $body, $timeout, undef, $BATCH) })->then(
Subroutine __ANON__: called CC=1 SCAR=0.0
528 78 ▶ sub {
Subroutine __ANON__: called CC=8 SCAR=20.8
529 78 my $body = shift;
530 78 my $results = $body->{results};
531 78 my $errors = $body->{errors};
532 78 my %answers;
533 # An entry is judged alone: one that is not an answer is that
534 # address's error, and the rest of the chunk keeps its answers.
535 78 for my $ip (@$chunk) {
536 28571 ▶ if (defined $results->{$ip} && !defined _nonconforming($LOOKUP, $results->{$ip}, [])) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $results->{$ip} and not defined _nonconforming($VPNDetection::LOOKUP, $results->{$ip}, scalar [])) { } 28547 24 28571
elsif (defined $errors->{$ip} and not defined _nonconforming($VPNDetection::BATCH_ERROR, $errors->{$ip}, scalar [])) { } 3 21 24
Condition100%3/3
defined $results->{$ip} and not defined _nonconforming($VPNDetection::LOOKUP, $results->{$ip}, scalar [])
!ll&&!rl&&r
51928547
MC/DC100%2/2
defined $results->{$ip} and not defined _nonconforming($VPNDetection::LOOKUP, $results->{$ip}, scalar [])
defined $results->{$ip} not defined _nonconforming($VPNDetection::LOOKUP, $results->{$ip}, scalar [])
Truth table100%3/3
A and not(B)
A= defined $results->{$ip}B= not defined _nonconforming($VPNDetection::LOOKUP, $results->{$ip}, scalar [])
ABresult
0X0
100
111
537 28547 my $result = VPNDetection::Result->from_wire($results->{$ip});
538 28547 ▶ $self->{cache}->set(_key($ip, $agents->{$ip}), $result) if $self->{cache};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"cache"} 1035 27512 28547
539 # A capped entry is its error, as a failing address's is, and
540 # the batch returns with the others answered.
541 28547 ▶ $answers{$ip} = _capped($result) || $result;
Condition66%2/3
_capped($result) || $result
l!l&&r!l&&!r
8285390
MC/DC0%0/2
_capped($result) || $result
_capped($result) $result
Truth table66%2/3
A || B
A= _capped($result)B= $result
ABresult
1X1
011
000
542 }
543 ▶ elsif (defined $errors->{$ip} && !defined _nonconforming($BATCH_ERROR, $errors->{$ip}, [])) {
Condition100%3/3
defined $errors->{$ip} and not defined _nonconforming($VPNDetection::BATCH_ERROR, $errors->{$ip}, scalar [])
!ll&&!rl&&r
1923
MC/DC100%2/2
defined $errors->{$ip} and not defined _nonconforming($VPNDetection::BATCH_ERROR, $errors->{$ip}, scalar [])
defined $errors->{$ip} not defined _nonconforming($VPNDetection::BATCH_ERROR, $errors->{$ip}, scalar [])
Truth table100%3/3
A and not(B)
A= defined $errors->{$ip}B= not defined _nonconforming($VPNDetection::BATCH_ERROR, $errors->{$ip}, scalar [])
ABresult
0X0
100
111
544 $answers{$ip} = VPNDetection::Error->from_entry(
545 $errors->{$ip}{status}, $errors->{$ip}{error},
546 3 );
547 }
548 else {
549 21 $answers{$ip} = VPNDetection::Error->new(
550 kind => 'server_error', status => 200,
551 message => "the batch answer did not include $ip",
552 );
553 }
554 }
555 78 return \%answers;
556 },
557 5 ▶ sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
558 5 my $error = VPNDetection::Error->wrap(shift);
559 5 return { map { $_ => $error } @$chunk };
560 },
561 83 );
562 }
563  
564 # Releasing the slot happens in the SAME handler that records the answer. A
565 # second `then` would leave a gap in which a dying handler strands the slot, and
566 # a batch that never releases one never finishes.
567 83 ▶sub _settled {
Subroutine _settled: called CC=1 SCAR=0.0
568 83 my ($self, $batch) = @_;
569 83 $batch->{active}--;
570 83 $self->_dispatch($batch);
571 }
572  
573 # Recurses through $self rather than through a self-referential closure, which
574 # in Perl would be a reference cycle the interpreter never collects. $may_retry,
575 # when given, can veto a retry the error alone would allow; $tries counts the
576 # retries already made.
577 1253 ▶sub _retry_p {
Subroutine _retry_p: called CC=2 SCAR=6.9
578 1253 my ($self, $left, $attempt, $may_retry, $tries) = @_;
579 1253 ▶ $tries //= 0;
Condition100%2/2
$tries //= 0
l!l
1551098
MC/DC100%1/1
$tries //= 0
$tries
Truth table100%2/2
A
A= $tries
Aresult
11
00
580 808 ▶ return $attempt->()->catch(sub {
Subroutine __ANON__: called CC=5 SCAR=16.1
581 808 my $error = VPNDetection::Error->wrap(shift);
582 808 ▶ die $error if $left <= 0 || !$error->retryable || ($may_retry && !$may_retry->());
Branch: 1 branch
BranchTrueFalseTotal
if $left <= 0 or not $error->retryable or $may_retry and not &$may_retry() 653 155 808
Condition100%9/9
$left <= 0 or not $error->retryable or $may_retry and not &$may_retry()
l!l&&r!l&&!r
6521155
$left <= 0 or not $error->retryable
l!l&&r!l&&!r
63418156
$may_retry and not &$may_retry()
!ll&&!rl&&r
15411
MC/DC100%4/4
$left <= 0 or not $error->retryable or $may_retry and not &$may_retry()
$left <= 0 not $error->retryable $may_retry not &$may_retry()
Truth table100%5/5
A or not(B) or C and not(D)
A= $left <= 0B= not $error->retryableC= $may_retryD= not &$may_retry()
ABCDresult
1XXX1
01XX1
00111
000X0
00100
583 # The wait is a TIMER, never a sleep: this promise shares an event loop
584 # with every other request in the batch, and sleeping here would stall
585 # all of them.
586 return Mojo::Promise->timer(_retry_delay($error->retry_after, $tries))
587 155 ▶ ->then(sub { $self->_retry_p($left - 1, $attempt, $may_retry, $tries + 1) });
Subroutine __ANON__: called CC=1 SCAR=0.0
588 1253 });
589 }
590  
591 # The server's Retry-After when it gave a usable one, otherwise the backoff:
592 # 250 ms, doubling per retry, capped from the seventh. A Retry-After past
593 # LONGEST_WAIT is waited out on the backoff too, still rate_limited, rather than
594 # holding the call for as long as any server asks.
595 168 ▶sub _retry_delay {
Subroutine _retry_delay: called CC=5 SCAR=16.1
596 168 my ($retry_after, $tries) = @_;
597 168 ▶ return $retry_after
Branch: 1 branch
BranchTrueFalseTotal
if defined $retry_after and $retry_after > 0 and $retry_after <= "2147483.647" 3 165 168
Condition100%6/6
defined $retry_after and $retry_after > 0 and $retry_after <= "2147483.647"
!ll&&!rl&&r
16233
defined $retry_after and $retry_after > 0
!ll&&!rl&&r
16026
MC/DC100%3/3
defined $retry_after and $retry_after > 0 and $retry_after <= "2147483.647"
defined $retry_after $retry_after > 0 $retry_after <= "2147483.647"
Truth table100%4/4
A and B and C
A= defined $retry_afterB= $retry_after > 0C= $retry_after <= "2147483.647"
ABCresult
0XX0
10X0
1100
1111
598 if defined $retry_after && $retry_after > 0 && $retry_after <= LONGEST_WAIT;
599 165 ▶ return BACKOFF_BASE * 2**($tries < 6 ? $tries : 6);
Branch: 1 branch
BranchTrueFalseTotal
$tries < 6 ? : 163 2 165
600 }
601  
602 # $timeout is the call's own bound, or undef for the client's. $member, when
603 # given, is the one member of the answer the call returns; $shape is what the
604 # whole answer must be (see _nonconforming), members the call never reads
605 # included. An answer that is
606 # not fails inside the attempt as a retried server_error, like any other 2xx that
607 # cannot be read, rather than reaching the caller: through 3.8.0 a lookup's
608 # `"is_hosting": "yes"`, a version of "3" and a list entry of null came back as
609 # served, and `{}` as a lookup's answer.
610 1007 ▶sub _json_p {
Subroutine _json_p: called CC=2 SCAR=6.9
611 1007 my ($self, $url, $body, $timeout, $member, $shape) = @_;
612 1007 ▶ my $sent = defined $body ? $self->_post_p($url, $body, $timeout) : $self->_get_p($url, $timeout);
Branch: 1 branch
BranchTrueFalseTotal
defined $body ? : 84 923 1007
613 985 ▶ return $sent->then(sub {
Subroutine __ANON__: called CC=6 SCAR=17.9
614 985 my $res = shift->res;
615 985 ▶ die VPNDetection::Error->from_response($res->code, $res->headers, $res->json)
Branch: 1 branch
BranchTrueFalseTotal
unless $res->is_success 47 938 985
616 unless $res->is_success;
617 938 my $decoded = $res->json;
618 594 ▶ my $unreadable = sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
619 594 die VPNDetection::Error->new(kind => 'server_error', status => $res->code, message => shift);
620 938 };
621 938 ▶ $unreadable->('the API did not answer with a JSON object') unless ref $decoded eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $decoded eq "HASH" 16 922 938
622 922 ▶ return $decoded unless $shape;
Branch: 1 branch
BranchTrueFalseTotal
unless $shape 0 922 922
623 922 my $wrong = _nonconforming($shape, $decoded, []);
624 922 ▶ $unreadable->($wrong) if defined $wrong;
Branch: 1 branch
BranchTrueFalseTotal
if defined $wrong 578 344 922
625 344 ▶ return defined $member ? $decoded->{$member} : $decoded;
Branch: 1 branch
BranchTrueFalseTotal
defined $member ? : 41 303 344
626 1005 });
627 }
628  
629 # undef when the value has the shape, else what the API answered wrong, naming
630 # the member by its path. A string is told from a number by the scalar Mojo::JSON
631 # decoded it into, as VPNDetection::Oauth does, since nothing else in Perl tells
632 # `"7"` from `7`. No list entry or map value may be null.
633 129148 ▶sub _nonconforming {
Subroutine _nonconforming: called CC=37 SCAR=36.3
634 129148 my ($shape, $value, $at) = @_;
635 129148 my ($kind, $inner) = @$shape;
636 129148 ▶ my $wrong = sub { 'the API answered ' . (@$at ? join('.', @$at) : 'the answer') . ' of the wrong type' };
Subroutine __ANON__: called CC=2 SCAR=7.2
Branch: 1 branch
BranchTrueFalseTotal
@$at ? : 89 0 89
637 129148 ▶ return $wrong->() unless defined $value;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $value 16 129132 129148
638 129132 ▶ return undef if $kind eq 'any';
Branch: 1 branch
BranchTrueFalseTotal
if $kind eq "any" 28571 100561 129132
639 100561 ▶ if ($kind eq 'string') {
Branch: 1 branch
BranchTrueFalseTotal
if ($kind eq "string") 34088 66473 100561
640 34088 ▶ return VPNDetection::Oauth::_is_string($value) ? undef : $wrong->();
Branch: 1 branch
BranchTrueFalseTotal
VPNDetection::Oauth::_is_string($value) ? : 34076 12 34088
641 }
642 66473 ▶ if ($kind eq 'date' || $kind eq 'date-time') {
Branch: 1 branch
BranchTrueFalseTotal
if ($kind eq "date" or $kind eq "date-time") 2856 63617 66473
Condition100%3/3
$kind eq "date" or $kind eq "date-time"
l!l&&r!l&&!r
238647063617
MC/DC100%2/2
$kind eq "date" or $kind eq "date-time"
$kind eq "date" $kind eq "date-time"
Truth table100%3/3
A or B
A= $kind eq "date"B= $kind eq "date-time"
ABresult
1X1
011
000
643 2856 ▶ return VPNDetection::Oauth::_is_string($value) && _is_rfc3339($kind, $value) ? undef
Branch: 1 branch
BranchTrueFalseTotal
VPNDetection::Oauth::_is_string($value) && _is_rfc3339($kind, $value) ? : 2394 462 2856
Condition66%2/3
VPNDetection::Oauth::_is_string($value) and _is_rfc3339($kind, $value)
!ll&&!rl&&r
04622394
MC/DC50%1/2
VPNDetection::Oauth::_is_string($value) and _is_rfc3339($kind, $value)
VPNDetection::Oauth::_is_string($value) _is_rfc3339($kind, $value)
Truth table66%2/3
A and B
A= VPNDetection::Oauth::_is_string($value)B= _is_rfc3339($kind, $value)
ABresult
0X0
100
111
644 : 'the API answered ' . join('.', @$at) . ' that is no RFC 3339 ' . $kind;
645 }
646 63617 ▶ if ($kind eq 'integer') {
Branch: 1 branch
BranchTrueFalseTotal
if ($kind eq "integer") 491 63126 63617
647 491 ▶ return !ref $value && !VPNDetection::Oauth::_is_string($value) && $value =~ /\A-?[0-9]+\z/
Branch: 1 branch
BranchTrueFalseTotal
!(ref $value || VPNDetection::Oauth::_is_string($value)) && $value =~ /\A-?[0-9]+\z/ ? : 471 20 491
Condition66%4/6
not ref $value || VPNDetection::Oauth::_is_string($value) and $value =~ /\A-?[0-9]+\z/
!ll&&!rl&&r
200471
ref $value || VPNDetection::Oauth::_is_string($value)
l!l&&r!l&&!r
020471
MC/DC33%1/3
not ref $value || VPNDetection::Oauth::_is_string($value) and $value =~ /\A-?[0-9]+\z/
ref $value VPNDetection::Oauth::_is_string($value) $value =~ /\A-?[0-9]+\z/
Truth table50%2/4
not(A || B) and C
A= ref $valueB= VPNDetection::Oauth::_is_string($value)C= $value =~ /\A-?[0-9]+\z/
ABCresult
1XX0
01X0
0000
0011
648 ? undef : $wrong->();
649 }
650 63126 ▶ if ($kind eq 'number') {
Branch: 1 branch
BranchTrueFalseTotal
if ($kind eq "number") 10 63116 63126
651 10 ▶ return !ref $value && !VPNDetection::Oauth::_is_string($value)
Branch: 1 branch
BranchTrueFalseTotal
!(ref $value || VPNDetection::Oauth::_is_string($value)) && &Scalar::Util::looks_like_number($value) ? : 8 2 10
Condition66%4/6
not ref $value || VPNDetection::Oauth::_is_string($value) and &Scalar::Util::looks_like_number($value)
!ll&&!rl&&r
208
ref $value || VPNDetection::Oauth::_is_string($value)
l!l&&r!l&&!r
028
MC/DC33%1/3
not ref $value || VPNDetection::Oauth::_is_string($value) and &Scalar::Util::looks_like_number($value)
ref $value VPNDetection::Oauth::_is_string($value) &Scalar::Util::looks_like_number($value)
Truth table50%2/4
not(A || B) and C
A= ref $valueB= VPNDetection::Oauth::_is_string($value)C= &Scalar::Util::looks_like_number($value)
ABCresult
1XX0
01X0
0000
0011
652 && Scalar::Util::looks_like_number($value) ? undef : $wrong->();
653 }
654 63116 ▶ if ($kind eq 'boolean') {
Branch: 1 branch
BranchTrueFalseTotal
if ($kind eq "boolean") 30455 32661 63116
655 30455 ▶ return Scalar::Util::blessed($value) && $value->isa('JSON::PP::Boolean') ? undef : $wrong->();
Branch: 1 branch
BranchTrueFalseTotal
builtin::blessed($value) && $value->isa('JSON::PP::Boolean') ? : 30422 33 30455
Condition66%2/3
builtin::blessed($value) and $value->isa("JSON::PP::Boolean")
!ll&&!rl&&r
33030422
MC/DC50%1/2
builtin::blessed($value) and $value->isa("JSON::PP::Boolean")
builtin::blessed($value) $value->isa("JSON::PP::Boolean")
Truth table66%2/3
A and B
A= builtin::blessed($value)B= $value->isa("JSON::PP::Boolean")
ABresult
0X0
100
111
656 }
657 32661 ▶ if ($kind eq 'object') {
Branch: 1 branch
BranchTrueFalseTotal
if ($kind eq "object") 4 32657 32661
658 4 ▶ return ref $value eq 'HASH' ? undef : $wrong->();
Branch: 1 branch
BranchTrueFalseTotal
ref $value eq 'HASH' ? : 4 0 4
659 }
660 32657 ▶ if ($kind eq 'list') {
Branch: 1 branch
BranchTrueFalseTotal
if ($kind eq "list") 509 32148 32657
661 509 ▶ return $wrong->() unless ref $value eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $value eq "ARRAY" 4 505 509
662 505 for my $i (0 .. $#$value) {
663 446 my $w = _nonconforming($inner, $value->[$i], [@$at, $i]);
664 446 ▶ return $w if defined $w;
Branch: 1 branch
BranchTrueFalseTotal
if defined $w 137 309 446
665 }
666 368 return undef;
667 }
668 32148 ▶ if ($kind eq 'map_of') {
Branch: 1 branch
BranchTrueFalseTotal
if ($kind eq "map_of") 176 31972 32148
669 176 ▶ return $wrong->() unless ref $value eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $value eq "HASH" 0 176 176
670 176 for my $key (sort keys %$value) {
671 28588 my $w = _nonconforming($inner, $value->{$key}, [@$at, $key]);
672 28588 ▶ return $w if defined $w;
Branch: 1 branch
BranchTrueFalseTotal
if defined $w 6 28582 28588
673 }
674 170 return undef;
675 }
676 31972 ▶ return $wrong->() unless ref $value eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $value eq "HASH" 2 31970 31972
677 31970 for my $field (@$inner) {
678 1289031 my ($name, $member_shape, $required) = @$field;
679 1289031 ▶ if (!defined $value->{$name}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $value->{$name}) 1218410 70621 1289031
680 return 'the API answered with no ' . join('.', @$at, $name)
681 1218410 ▶ if $required && ($required != NOT_NULL || exists $value->{$name});
Branch: 1 branch
BranchTrueFalseTotal
if $required and $required != 2 || exists $value->{$name} 48 1218362 1218410
Condition100%6/6
$required and $required != 2 || exists $value->{$name}
!ll&&!rl&&r
12183085448
$required != 2 or exists $value->{$name}
l!l&&r!l&&!r
41754
MC/DC100%3/3
$required and $required != 2 || exists $value->{$name}
$required $required != 2 exists $value->{$name}
Truth table100%4/4
A and B or C
A= $requiredB= $required != 2C= exists $value->{$name}
ABCresult
0XX0
1000
11X1
1011
682 1218362 next;
683 }
684 70621 my $w = _nonconforming($member_shape, $value->{$name}, [@$at, $name]);
685 70621 ▶ return $w if defined $w;
Branch: 1 branch
BranchTrueFalseTotal
if defined $w 1069 69552 70621
686 }
687 30853 return undef;
688 }
689  
690 # RFC 3339's `full-date`, or its `date-time` with the `T` and `Z` in either case,
691 # an hour below 24, a minute and second below 60 and an offset of at most 23:59,
692 # on a day its month has. ASCII digits and `\z`, since Perl's `\d` takes any
693 # script's digits and `$` a trailing newline.
694 15 my $FULL_DATE = qr/\A([0-9]{4})-([0-9]{2})-([0-9]{2})\z/;
695 15 my $DATE_TIME = qr/\A([0-9]{4})-([0-9]{2})-([0-9]{2})[Tt]([0-9]{2}):([0-9]{2}):([0-9]{2})(?:\.[0-9]+)?
696 (?:[Zz]|[+-]([0-9]{2}):([0-9]{2}))\z/x;
697  
698 2856 ▶sub _is_rfc3339 {
Subroutine _is_rfc3339: called CC=10 SCAR=23.0
699 2856 my ($kind, $value) = @_;
700 2856 ▶ if ($kind eq 'date') {
Branch: 1 branch
BranchTrueFalseTotal
if ($kind eq "date") 2386 470 2856
701 2386 ▶ my @date = $value =~ $FULL_DATE or return 0;
Branch: 1 branch
BranchTrueFalseTotal
my(@date) = $value =~ /$FULL_DATE/ or return 0 2162 224 2386
702 2162 return _is_day(@date);
703 }
704 470 ▶ my ($year, $month, $day, $hour, $minute, $second, $off_hour, $off_minute) = $value =~ $DATE_TIME
Branch: 1 branch
BranchTrueFalseTotal
() = $value =~ /$DATE_TIME/ or return 0 363 107 470
705 or return 0;
706 363 ▶ return _is_day($year, $month, $day) && $hour < 24 && $minute < 60 && $second < 60
Condition100%18/18
_is_day($year, $month, $day) && $hour < 24 && $minute < 60 && $second < 60 && (!defined($off_hour) || $off_hour < 24 && $off_minute < 60)
!ll&&!rl&&r
3216315
_is_day($year, $month, $day) and $hour < 24 and $minute < 60 and $second < 60
!ll&&!rl&&r
248331
_is_day($year, $month, $day) and $hour < 24 and $minute < 60
!ll&&!rl&&r
168339
_is_day($year, $month, $day) and $hour < 24
!ll&&!rl&&r
88347
not defined $off_hour or $off_hour < 24 and $off_minute < 60
l!l&&r!l&&!r
2991616
$off_hour < 24 and $off_minute < 60
!ll&&!rl&&r
8816
MC/DC100%7/7
_is_day($year, $month, $day) && $hour < 24 && $minute < 60 && $second < 60 && (!defined($off_hour) || $off_hour < 24 && $off_minute < 60)
_is_day($year, $month, $day) $hour < 24 $minute < 60 $second < 60 not defined $off_hour $off_hour < 24 $off_minute < 60
Truth table100%8/8
A and B and C and D && not(E) or F and G
A= _is_day($year, $month, $day)B= $hour < 24C= $minute < 60D= $second < 60E= not defined $off_hourF= $off_hour < 24G= $off_minute < 60
ABCDEFGresult
0XXXXXX0
10XXXXX0
110XXXX0
1110XXX0
111100X0
11110100
11111XX1
11110111
707 && (!defined $off_hour || ($off_hour < 24 && $off_minute < 60));
708 }
709  
710 2525 ▶sub _is_day {
Subroutine _is_day: called CC=7 SCAR=19.5
711 2525 my ($year, $month, $day) = @_;
712 2525 ▶ return 0 if $month < 1 || $month > 12 || $day < 1;
Branch: 1 branch
BranchTrueFalseTotal
if $month < 1 or $month > 12 or $day < 1 34 2491 2525
Condition83%5/6
$month < 1 or $month > 12 or $day < 1
l!l&&r!l&&!r
17172491
$month < 1 or $month > 12
l!l&&r!l&&!r
0172508
MC/DC66%2/3
$month < 1 or $month > 12 or $day < 1
$month < 1 $month > 12 $day < 1
Truth table75%3/4
A or B or C
A= $month < 1B= $month > 12C= $day < 1
ABCresult
1XX1
01X1
0011
0000
713 2491 ▶ my $leap = ($year % 4 == 0 && $year % 100 != 0) || $year % 400 == 0;
Condition100%6/6
$year % 4 == 0 && $year % 100 != 0 || $year % 400 == 0
l!l&&r!l&&!r
15152461
$year % 4 == 0 and $year % 100 != 0
!ll&&!rl&&r
24463015
MC/DC100%3/3
$year % 4 == 0 && $year % 100 != 0 || $year % 400 == 0
$year % 4 == 0 $year % 100 != 0 $year % 400 == 0
Truth table80%4/5
A and B || C
A= $year % 4 == 0B= $year % 100 != 0C= $year % 400 == 0
ABCresult
11X1
0X11
1011
0X00
1000
714 2491 ▶ return $day <= (31, $leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)[$month - 1];
Branch: 1 branch
BranchTrueFalseTotal
$leap ? : 30 2461 2491
715 }
716  
717 947 ▶sub _get_p {
Subroutine _get_p: called CC=1 SCAR=0.0
718 947 my ($self, $url, $timeout) = @_;
719 947 return $self->_start_p($self->{ua}->build_tx(GET => $url => $self->_headers), $timeout);
720 }
721  
722 # The one request with a body: the batch. Mojo encodes the JSON and sets the
723 # content type.
724 84 ▶sub _post_p {
Subroutine _post_p: called CC=1 SCAR=0.0
725 84 my ($self, $url, $body, $timeout) = @_;
726 84 my $tx = $self->{ua}->build_tx(POST => $url => $self->_headers => json => $body);
727 84 return $self->_start_p($tx, $timeout);
728 }
729  
730 # One dataset transfer. Every chunk is handed to $on_chunk and none is kept, so a
731 # body costs the same in memory whether it is 10 KB or 1.79 GB. Resolves with the
732 # number of bytes handed over.
733 15 ▶sub _stream_p {
Subroutine _stream_p: called CC=1 SCAR=0.0
734 15 my ($self, $url, $on_chunk) = @_;
735 # Built here rather than through _get_p, which is the only place the API key
736 # is ever attached: the presigned link authorizes itself, so carrying the key
737 # would hand it to a host with no business holding it.
738 15 my $tx = $self->{ua}->build_tx(GET => $url);
739  
740 # Mojo asks for gzip on every request it builds. A dataset file is already
741 # compressed, so the only thing that would buy is a Content-Length counting
742 # bytes that never reach the sink, and that length is the only evidence the
743 # transfer arrived whole.
744 15 $tx->req->headers->remove('Accept-Encoding');
745 # Mojo aborts a response past max_message_size, counting every byte it parses
746 # whether or not it keeps any of them. The default is 2 GiB, which the
747 # catalog is already within an order of magnitude of, and
748 # MOJO_MAX_MESSAGE_SIZE lowers it for every response in the process, on a
749 # machine whose environment we do not own.
750 15 $tx->res->max_message_size(0);
751  
752 15 my $received = 0;
753 # Unsubscribing Mojo's own reader is what stops the body being collected into
754 # the message. The subscriber hangs off the transaction, so holding the
755 # transaction strongly inside it would be a cycle the interpreter never
756 # collects; the user agent keeps it alive for as long as bytes are arriving.
757 15 my $weak = $tx;
758 15 Scalar::Util::weaken($weak);
759 209 ▶ $tx->res->content->unsubscribe('read')->on(read => sub {
Subroutine __ANON__: called CC=4 SCAR=14.1
760 209 my (undef, $bytes) = @_;
761 # An error body is neither written out nor held: the status is what
762 # separates a lapsed link from a refused one, and nothing bounds the size
763 # of what a storage host puts in the body of a refusal.
764 209 ▶ return unless $weak && ($weak->res->code || 0) == 200;
Branch: 1 branch
BranchTrueFalseTotal
unless $weak and ($weak->res->code || 0) == 200 2 207 209
Condition60%3/5
$weak and ($weak->res->code || 0) == 200
!ll&&!rl&&r
02207
$weak->res->code || 0
l!l
2090
MC/DC0%0/2
$weak and ($weak->res->code || 0) == 200
$weak $weak->res->code
Truth table33%1/3
A and B
A= $weakB= $weak->res->code
ABresult
0X0
100
111
765 207 $received += length $bytes;
766 207 $on_chunk->($bytes);
767 15 });
768  
769 14 ▶ return $self->_start_p($tx, 0)->then(sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
770 14 my $res = shift->res;
771 14 ▶ die VPNDetection::Error->from_response($res->code, $res->headers, {
Branch: 1 branch
BranchTrueFalseTotal
unless $res->code == 200 2 12 14
772 error => 'object storage refused the download link with status ' . $res->code,
773 }) unless $res->code == 200;
774  
775 # Before Mojolicious 9.54 a body that stops early reaches Perl as an
776 # ordinary end of stream: the status was 200 and Mojo reports no error,
777 # so without this a half transfer is a short file nobody notices.
778 12 my $short = _short_transfer($res, $received);
779 12 ▶ die $short if $short;
Branch: 1 branch
BranchTrueFalseTotal
if $short 0 12 12
780 12 return $received;
781 1 ▶ }, sub {
Subroutine __ANON__: called CC=2 SCAR=7.6
782 1 my $error = shift;
783 # From 9.54 the same body rejects as `Premature connection close`, which
784 # says nothing of how far it got, so the lengths are added to it.
785 1 my $short = _short_transfer($tx->res, $received, $error);
786 1 ▶ die $short // $error;
Condition33%1/3
$short // $error
l!l&&r!l&&!r
100
MC/DC0%0/2
$short // $error
$short $error
Truth table33%1/3
A // B
A= $shortB= $error
ABresult
1X1
011
000
787 15 });
788 }
789  
790 # The error for a 200 whose body stopped short of the length it declared, or
791 # undef when it did not. $cause is what Mojo rejected it with, when it did.
792 13 ▶sub _short_transfer {
Subroutine _short_transfer: called CC=8 SCAR=23.7
793 13 my ($res, $received, $cause) = @_;
794 13 my $declared = $res->headers->content_length;
795 return undef
796 13 ▶ unless ($res->code || 0) == 200 && defined $declared && length $declared && $declared != $received;
Branch: 1 branch
BranchTrueFalseTotal
unless ($res->code || 0) == 200 and defined $declared and length $declared and $declared != $received 12 1 13
Condition45%5/11
($res->code || 0) == 200 and defined $declared and length $declared and $declared != $received
!ll&&!rl&&r
0121
($res->code || 0) == 200 and defined $declared and length $declared
!ll&&!rl&&r
0013
($res->code || 0) == 200 and defined $declared
!ll&&!rl&&r
0013
$res->code || 0
l!l
130
MC/DC25%1/4
($res->code || 0) == 200 and defined $declared and length $declared and $declared != $received
$res->code defined $declared length $declared $declared != $received
Truth table40%2/5
A and B and C and D
A= $res->codeB= defined $declaredC= length $declaredD= $declared != $received
ABCDresult
0XXX0
10XX0
110X0
11100
11111
797 1 my $message = "the transfer ended after $received of $declared bytes";
798 1 ▶ $message .= ': ' . (ref $cause ? $cause->message : $cause) if defined $cause;
Branch: 2 branches
BranchTrueFalseTotal
if defined $cause 1 0 1
ref $cause ? : 1 0 1
799 1 return VPNDetection::Error->new(kind => 'network', message => $message);
800 }
801  
802 # request_timeout bounds the WHOLE response and Mojo::UserAgent has no
803 # per-transaction form of it, yet a call may bring its own bound and a transfer
804 # must have none (0): 30 seconds is right for a lookup and wrong for a gigabyte.
805 # So it is set only across the hand-over, where start_p arms the timer
806 # synchronously - and set EXPLICITLY each time, because Mojo runs a loop tick
807 # inside start_p when the loop is idle, and a retry started in that tick would
808 # otherwise inherit this call's bound.
809 #
810 # A rejection is a plain string when the request never got far enough to have a
811 # status, which is exactly the transport failure the retry rule treats as worth
812 # another attempt.
813 1251 ▶sub _start_p {
Subroutine _start_p: called CC=3 SCAR=11.0
814 1251 my ($self, $tx, $timeout) = @_;
815 1251 my $ua = $self->{ua};
816 1251 my $bound = $ua->request_timeout;
817 1251 ▶ $ua->request_timeout(defined $timeout ? 0 + $timeout : $self->{timeout});
Branch: 1 branch
BranchTrueFalseTotal
defined $timeout ? : 70 1181 1251
818 1251 my $promise = eval { $ua->start_p($tx) };
819 1251 my $failed = $@;
820 1251 $ua->request_timeout($bound);
821 1251 ▶ die VPNDetection::Error->wrap($failed) unless $promise;
Branch: 1 branch
BranchTrueFalseTotal
unless $promise 0 1251 1251
822 47 ▶ return $promise->catch(sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
823 47 die VPNDetection::Error->new(kind => 'network', message => "$_[0]");
824 1251 });
825 }
826  
827 1031 ▶sub _headers {
Subroutine _headers: called CC=2 SCAR=6.9
828 1031 my ($self) = @_;
829 1031 my %headers = (Accept => 'application/json');
830 # One scheme, though the API offers three. Sending the same key as a bearer
831 # token, a header and a query parameter at once is three times the exposure
832 # for one credential, and query strings end up in logs. A blank key is none
833 # at all (see new).
834 1031 ▶ $headers{Authorization} = "Bearer $self->{api_key}" if defined $self->{api_key};
Branch: 1 branch
BranchTrueFalseTotal
if defined $self->{"api_key"} 668 363 1031
835 1031 return \%headers;
836 }
837  
838 1090 ▶sub _url {
Subroutine _url: called CC=2 SCAR=6.9
839 1090 my ($self, $path, %query) = @_;
840 1090 my $url = Mojo::URL->new($self->{base_url} . $path);
841 1090 ▶ $url->query(%query) if %query;
Branch: 1 branch
BranchTrueFalseTotal
if %query 78 1012 1090
842 1090 return $url;
843 }
844  
845 1065 ▶sub _wait {
Subroutine _wait: called CC=2 SCAR=6.9
846 1065 my ($self, $promise) = @_;
847 1065 my ($value, $error, $failed);
848 1065 ▶ $promise->then(sub { $value = shift }, sub { ($error, $failed) = (shift, 1) })->wait;
Subroutine __ANON__: called CC=1 SCAR=0.0
Subroutine __ANON__: called CC=1 SCAR=0.0
849 1065 ▶ die $error if $failed;
Branch: 1 branch
BranchTrueFalseTotal
if $failed 681 384 1065
850 384 return $value;
851 }
852  
853 # Checked BEFORE the promise is built, not after: Mojo::UserAgent starts a
854 # transaction as soon as it is created, so croaking later would still have spent
855 # a request from the caller's allowance.
856 1203 ▶sub _assert_blocking_ok {
Subroutine _assert_blocking_ok: called CC=2 SCAR=6.9
857 1203 my ($self, $method) = @_;
858 1203 ▶ return unless Mojo::IOLoop->is_running;
Branch: 1 branch
BranchTrueFalseTotal
unless "Mojo::IOLoop"->is_running 1202 1 1203
859 1 Carp::croak(
860 "VPNDetection::$method cannot block inside a running Mojo::IOLoop; "
861 . "call ${method}_p instead, which returns a Mojo::Promise"
862 );
863 }
864  
865 1299 ▶sub _check_options {
Subroutine _check_options: called CC=9 SCAR=22.0
866 1299 my ($self, $method, $options, @allowed) = @_;
867 1299 my %allowed = map { $_ => 1 } @allowed;
868 1299 my @unknown = sort grep { !$allowed{$_} } keys %$options;
869 1299 ▶ Carp::croak("VPNDetection::$method: unknown option(s): @unknown") if @unknown;
Branch: 1 branch
BranchTrueFalseTotal
if @unknown 6 1293 1299
870 # A negative or non-numeric bound would fire at once and fail the very call
871 # it was meant to protect.
872 1293 my $timeout = $options->{timeout};
873 1293 ▶ Carp::croak("VPNDetection::$method: timeout must be a number of seconds, 0 or more")
Branch: 1 branch
BranchTrueFalseTotal
if defined $timeout and not &Scalar::Util::looks_like_number($timeout) && $timeout >= 0 5 1288 1293
Condition100%6/6
defined $timeout and not &Scalar::Util::looks_like_number($timeout) && $timeout >= 0
!ll&&!rl&&r
1234545
&Scalar::Util::looks_like_number($timeout) && $timeout >= 0
!ll&&!rl&&r
2354
MC/DC100%3/3
defined $timeout and not &Scalar::Util::looks_like_number($timeout) && $timeout >= 0
defined $timeout &Scalar::Util::looks_like_number($timeout) $timeout >= 0
Truth table100%4/4
A and not(B && C)
A= defined $timeoutB= &Scalar::Util::looks_like_number($timeout)C= $timeout >= 0
ABCresult
0XX0
1110
10X1
1101
874 if defined $timeout && !(Scalar::Util::looks_like_number($timeout) && $timeout >= 0);
875 Carp::croak("VPNDetection::$method: retries must be a whole number, 0 or more")
876 1288 ▶ if defined $options->{retries} && !_is_count($options->{retries}, 0);
Branch: 1 branch
BranchTrueFalseTotal
if defined $options->{"retries"} and not _is_count($options->{"retries"}, 0) 98 1190 1288
Condition100%3/3
defined $options->{"retries"} and not _is_count($options->{"retries"}, 0)
!ll&&!rl&&r
1188298
MC/DC100%2/2
defined $options->{"retries"} and not _is_count($options->{"retries"}, 0)
defined $options->{"retries"} not _is_count($options->{"retries"}, 0)
Truth table100%3/3
A and not(B)
A= defined $options->{"retries"}B= not _is_count($options->{"retries"}, 0)
ABresult
0X0
100
111
877 Carp::croak("VPNDetection::$method: concurrency must be a whole number, 1 or more")
878 1190 ▶ if defined $options->{concurrency} && !_is_count($options->{concurrency}, 1);
Branch: 1 branch
BranchTrueFalseTotal
if defined $options->{"concurrency"} and not _is_count($options->{"concurrency"}, 1) 16 1174 1190
Condition100%3/3
defined $options->{"concurrency"} and not _is_count($options->{"concurrency"}, 1)
!ll&&!rl&&r
1170416
MC/DC100%2/2
defined $options->{"concurrency"} and not _is_count($options->{"concurrency"}, 1)
defined $options->{"concurrency"} not _is_count($options->{"concurrency"}, 1)
Truth table100%3/3
A and not(B)
A= defined $options->{"concurrency"}B= not _is_count($options->{"concurrency"}, 1)
ABresult
0X0
100
111
879 }
880  
881 # A whole number from $least, or Inf for no limit. NaN compares false with
882 # anything, so a NaN count retried a failing call for good and a NaN concurrency
883 # put no chunk in flight, spinning the loop forever; a word reads as 0, and 1.5
884 # as two retries.
885 2936 ▶sub _is_count {
Subroutine _is_count: called CC=4 SCAR=13.9
886 2936 my ($n, $least) = @_;
887 2936 ▶ return !ref $n && Scalar::Util::looks_like_number($n) && $n >= $least && $n == int $n;
Condition100%9/9
!ref($n) && &Scalar::Util::looks_like_number($n) && $n >= $least && $n == int $n
!ll&&!rl&&r
118202798
not ref $n and &Scalar::Util::looks_like_number($n) and $n >= $least
!ll&&!rl&&r
57612818
not ref $n and &Scalar::Util::looks_like_number($n)
!ll&&!rl&&r
19382879
MC/DC100%4/4
!ref($n) && &Scalar::Util::looks_like_number($n) && $n >= $least && $n == int $n
not ref $n &Scalar::Util::looks_like_number($n) $n >= $least $n == int $n
Truth table100%5/5
not(A) and B and C && D
A= not ref $nB= &Scalar::Util::looks_like_number($n)C= $n >= $leastD= $n == int $n
ABCDresult
0XXX0
10XX0
110X0
11100
11111
888 }
889  
890 906 ▶sub _base_url {
Subroutine _base_url: called CC=3 SCAR=11.0
891 906 my ($url) = @_;
892 906 ▶ $url = DEFAULT_BASE_URL unless defined $url && length $url;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $url and length $url 4 902 906
Condition66%2/3
defined $url and length $url
!ll&&!rl&&r
40902
MC/DC50%1/2
defined $url and length $url
defined $url length $url
Truth table66%2/3
A and B
A= defined $urlB= length $url
ABresult
0X0
100
111
893 906 $url =~ s{/+\z}{};
894 906 return $url;
895 }
896  
897 15 1;
898  
899 __END__
↑ Summary VPNDetection/Oauth.pm »