VPNDetection.pm

filter: Statementstmt 99.7% 466 / 467 Branchbran 93.1% 205 / 220 Conditioncond 82.4% 141 / 171 MC/DCmcdc 69.5% 64 / 92 Subroutinesub 98.8% 84 / 85 Podpod 66.6% 8 / 12 totaltotal 92.4% 968 / 1047 CC 176 SCAR 24.7
CC
176
Cov
95%
_nonconforming
37.6
new
23.0
lookup_batch_p
19.2
CRAP 11.8
↑ Summary VPNDetection/Oauth.pm »
1 package VPNDetection;
2  
3 12 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 12 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5  
6 12 ▶use Carp ();
Subroutine BEGIN: called CC=1 SCAR=0.0
7 12 ▶use Exporter 'import';
Subroutine BEGIN: called CC=1 SCAR=0.0
8 12 ▶use Mojo::IOLoop;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 12 ▶use Mojo::Promise;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 12 ▶use Mojo::URL;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 12 ▶use Mojo::UserAgent;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 12 ▶use Mojo::Util ();
Subroutine BEGIN: called CC=1 SCAR=0.0
13 12 ▶use Scalar::Util ();
Subroutine BEGIN: called CC=1 SCAR=0.0
14  
15 12 ▶use VPNDetection::Bogon ();
Subroutine BEGIN: called CC=1 SCAR=0.0
16 12 ▶use VPNDetection::Cache;
Subroutine BEGIN: called CC=1 SCAR=0.0
17 12 ▶use VPNDetection::Database;
Subroutine BEGIN: called CC=1 SCAR=0.0
18 12 ▶use VPNDetection::Error;
Subroutine BEGIN: called CC=1 SCAR=0.0
19 12 ▶use VPNDetection::Oauth;
Subroutine BEGIN: called CC=1 SCAR=0.0
20 12 ▶use VPNDetection::Result;
Subroutine BEGIN: called CC=1 SCAR=0.0
21  
22 12 our $VERSION = '3.20.0';
23 12 our @EXPORT_OK = ('is_bogon');
24  
25 12 ▶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 12 ▶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 12 ▶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 12 ▶use constant LONGEST_WAIT => 2_147_483.647;
Subroutine BEGIN: called CC=1 SCAR=0.0
37  
38 12 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 12 ▶use constant NOT_NULL => 2;
Subroutine BEGIN: called CC=1 SCAR=0.0
50  
51 my $VPN_DETAIL = [fields => [
52 12 (map { [$_ => ['string']] } qw(provider provider_name confidence method)), [last_seen => ['date']],
53 ]];
54 12 my $CLASS_DETAIL = [fields => [(map { [$_ => ['string']] } qw(provider provider_name confidence)), [last_seen => ['date']]]];
55 my $PROXY_DETAIL = [fields => [
56 24 [provider => ['string']], [provider_name => ['string']], (map { [$_ => ['date']] } qw(first_seen last_seen)),
57 12 (map { [$_ => ['integer']] } qw(hits hits_days_pct providers_num)),
58 ]];
59 my $BOT_DETAIL = [fields => [
60 24 (map { [$_ => ['string']] } qw(provider provider_name)), (map { [$_ => [list => ['string']]] } qw(agents categories)),
61 36 [verified => ['boolean']], (map { [$_ => ['string']] } qw(identity verified_by confidence)),
62 12 (map { [$_ => ['date']] } qw(first_seen last_seen)),
63 ]];
64 12 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 12 my $CARRIER_DETAIL = [fields => [map { [$_ => ['string']] } qw(name mcc mnc country confidence)]];
70 my $SATELLITE_DETAIL = [fields => [
71 12 (map { [$_ => ['string']] } qw(provider provider_name orbit segment country confidence)),
72 [asn => ['integer']],
73 ]];
74 my $SSH_DETAIL = [fields => [
75 12 [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 12 [port => ['integer']], [banner => ['string']], (map { [$_ => ['date']] } qw(first_seen last_seen)),
80 [session_ok => ['boolean']],
81 ]];
82 my $WEB_ROW = [fields => [
83 24 (map { [$_ => ['integer'], 1] } qw(port status_code)),
84 36 (map { [$_ => ['boolean'], 1] } qw(tls_ok session_ok cert_browser_trusted)),
85 84 (map { [$_ => ['string'], 1] } qw(
86 server location title cert_subject_cn cert_subject_o cert_issuer_dn tls_version
87 )),
88 12 (map { [$_ => ['date'], 1] } qw(first_seen last_seen)),
89 ]];
90 my $DNS_RESOLVER_DETAIL = [fields => [
91 24 (map { [$_ => ['integer']] } qw(port rcode)), (map { [$_ => ['boolean']] } qw(recursion_available answer_correct)),
92 12 (map { [$_ => ['date']] } qw(first_seen last_seen)),
93 ]];
94 my $BITTORRENT_DETAIL = [fields => [
95 36 (map { [$_ => ['boolean']] } qw(verified id_matches_ip indexer)),
96 24 (map { [$_ => ['date']] } qw(first_seen last_seen)), [last_reachable => ['string']],
97 12 (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 120 (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 84 (map { [$_ => ['string']] } qw(region region_code city postal_code geoname_id dma_code last_changed)),
108 12 (map { [$_ => ['number']] } qw(latitude longitude)), [accuracy_radius => ['integer']],
109 ]];
110 my $ASN = [fields => [
111 12 [asn => ['integer'], 1], (map { [$_ => ['string'], 1] } qw(name domain prefix country rpki_status)),
112 [type => ['string'], NOT_NULL],
113 ]];
114 12 my $COMPANY = [fields => [(map { [$_ => ['string'], 1] } qw(name domain)), (map { [$_ => ['string']] } qw(type country))]];
115 my $ABUSE = [fields => [
116 12 [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'], 1], [is_bogon => ['boolean']],
121 228 (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 trial_expired cap_reached
125 )),
126 [vpn => $VPN_DETAIL],
127 48 (map { [$_ => $CLASS_DETAIL] } qw(hosting relay tor cdn)), [bot => $BOT_DETAIL],
128 36 (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 12 [user_agent => [fields => [map { [$_ => ['string'], 1] } qw(agent kind verdict)]]],
136 ]];
137 12 our $BATCH_ERROR = [fields => [[status => ['integer'], 1], [error => ['string'], 1]]];
138 # Each entry is judged alone, by _lookup_chunk_p.
139 12 our $BATCH = [fields => [[results => [map_of => ['any']], 1], [errors => [map_of => ['any']], 1]]];
140 12 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 917 ▶sub new {
Subroutine new: called CC=23 SCAR=31.4
Pod documented
151 917 my ($class, %args) = @_;
152 917 my @unknown = sort grep { !$OPTIONS{$_} } keys %args;
153 917 ▶ Carp::croak("VPNDetection->new: unknown option(s): @unknown") if @unknown;
Branch: 1 branch
BranchTrueFalseTotal
if @unknown 1 916 917
154  
155 916 ▶ my $concurrency = defined $args{concurrency} ? $args{concurrency} : 8;
Branch: 1 branch
BranchTrueFalseTotal
defined $args{'concurrency'} ? : 11 905 916
156 916 ▶ my $retries = defined $args{retries} ? $args{retries} : 2;
Branch: 1 branch
BranchTrueFalseTotal
defined $args{'retries'} ? : 660 256 916
157 916 ▶ my $cache_size = defined $args{cache_size} ? $args{cache_size} : 10_000;
Branch: 1 branch
BranchTrueFalseTotal
defined $args{'cache_size'} ? : 586 330 916
158 916 ▶ 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 907 916
159 907 ▶ 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 900 907
160 900 ▶ 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 892 900
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 892 ▶ my $cache_ttl = defined $args{cache_ttl} ? $args{cache_ttl} : 3600;
Branch: 1 branch
BranchTrueFalseTotal
defined $args{'cache_ttl'} ? : 30 862 892
164 892 ▶ 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 882 892
Condition100%6/6
not ref $cache_ttl and &Scalar::Util::looks_like_number($cache_ttl) and $cache_ttl >= 0
!ll&&!rl&&r
55882
not ref $cache_ttl and &Scalar::Util::looks_like_number($cache_ttl)
!ll&&!rl&&r
23887
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 882 ▶ my $timeout = defined $args{timeout} ? $args{timeout} : 30;
Branch: 1 branch
BranchTrueFalseTotal
defined $args{'timeout'} ? : 41 841 882
169 882 ▶ 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 880 882
Condition100%3/3
&Scalar::Util::looks_like_number($timeout) and $timeout >= 0
!ll&&!rl&&r
11880
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 880 my $api_key = $args{api_key};
177 880 ▶ if (defined $api_key) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $api_key) 537 343 880
178 537 $api_key =~ s/\A\s+|\s+\z//g;
179 537 ▶ $api_key = undef unless length $api_key;
Branch: 1 branch
BranchTrueFalseTotal
unless length $api_key 3 534 537
180 }
181 880 ▶ 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 877 880
Condition100%3/3
defined $api_key and $api_key =~ /[\x00-\x1f\x7f]/
!ll&&!rl&&r
3465313
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 877 ▶ 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 875 877
Condition100%3/3
defined $api_key and $api_key =~ /[^\x00-\xff]/
!ll&&!rl&&r
3465292
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 875 ▶ ua => $args{ua} || Mojo::UserAgent->new,
Branch: 1 branch
BranchTrueFalseTotal
$cache_size > 0 ? : 301 574 875
Condition66%2/3
$args{'ua'} || 'Mojo::UserAgent'->new
l!l&&r!l&&!r
48710
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 875 $self->{ua}->max_redirects(0);
208 875 $self->{ua}->request_timeout($self->{timeout});
209 875 $self->{ua}->transactor->name("vpndetection-perl/$VERSION");
210 875 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.
223 505 ▶sub lookup {
Subroutine lookup: called CC=1 SCAR=0.0
Pod documented
224 505 my $self = shift;
225 505 $self->_assert_blocking_ok('lookup');
226 504 return $self->_wait($self->lookup_p(@_));
227 }
228  
229 551 ▶sub lookup_p {
Subroutine lookup_p: called CC=9 SCAR=22.0
Pod undocumented
230 551 my ($self, $ip, %options) = @_;
231 551 ▶ Carp::croak('lookup: expected an IP address') if !defined $ip || !length $ip;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $ip and length $ip 0 551 551
Condition33%1/3
defined $ip and length $ip
!ll&&!rl&&r
00551
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
232 551 $self->_check_options('lookup', \%options, 'retries', 'timeout', 'user_agent');
233 528 my $agent = _agent('lookup', $options{user_agent});
234 # Judged, cached and sent as the IPv4 address it carries, if it is mapped.
235 527 $ip = VPNDetection::Bogon::unmapped($ip);
236  
237 # A bogon is never sent, so it carries no user_agent.
238 527 ▶ return Mojo::Promise->resolve(VPNDetection::Bogon::bogon_result($ip))
Branch: 1 branch
BranchTrueFalseTotal
if VPNDetection::Bogon::is_bogon($ip) 5 522 527
239 if VPNDetection::Bogon::is_bogon($ip);
240  
241 # An answer to an agent is cached and shared on the address and that agent,
242 # apart from the address's plain answer and from another agent's.
243 522 my $key = _key($ip, $agent);
244 522 ▶ if ($self->{cache}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"cache"}) 148 374 522
245 148 my $hit = $self->{cache}->get($key);
246 148 ▶ return Mojo::Promise->resolve($hit) if $hit;
Branch: 1 branch
BranchTrueFalseTotal
if $hit 21 127 148
247 # A miss for an address already in flight, for a lookup or a batch,
248 # takes that request's answer rather than sending its own.
249 127 ▶ 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} 32 95 127
250 }
251  
252 469 my $flight = $self->_board($key);
253 469 my $url = $self->_url('/' . Mojo::Util::url_escape($ip, '^A-Za-z0-9\-._~:'), _agent_query($agent));
254 469 ▶ my $retries = defined $options{retries} ? $options{retries} : $self->{retries};
Branch: 1 branch
BranchTrueFalseTotal
defined $options{'retries'} ? : 2 467 469
255 # Anything that dies before a request is under way lands the flight too, or
256 # every later lookup of the address would wait on it forever (3.8.0).
257 469 ▶ 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
258 469 ▶ if (!$sent) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($sent) 2 467 469
259 2 my $error = $@;
260 2 $self->_land($key, $flight, 0, $error);
261 2 die $error;
262 }
263 return $sent->then(
264 172 ▶ sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
265 172 my $result = VPNDetection::Result->from_wire(shift);
266 # Only a served answer is cached, and before it lands, so a miss
267 # after the flight is gone finds it. Errors never are, and bogons
268 # never reach this far.
269 172 ▶ $self->{cache}->set($key, $result) if $self->{cache};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"cache"} 78 94 172
270 172 $self->_land($key, $flight, 1, $result);
271 172 return $result;
272 },
273 295 ▶ sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
274 295 my $error = shift;
275 295 $self->_land($key, $flight, 0, $error);
276 295 return Mojo::Promise->reject($error);
277 },
278 467 );
279 }
280  
281 # Concurrent misses for one address share ONE request: 3.3.2 sent one per
282 # caller. The first miss boards the address, and
283 # every miss after it, a batch's included, waits for that request instead. The
284 # request runs under the options of the call that led it; a failure reaches
285 # every waiter and is cached for none. Nothing is shared without a cache, since
286 # every lookup is then served. A Mojo::Promise cannot be canceled, so no waiter
287 # is ever left behind by a leader that gave up.
288 29040 ▶sub _board {
Subroutine _board: called CC=2 SCAR=6.9
289 29040 my ($self, $key) = @_;
290 29040 ▶ return undef unless $self->{cache};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"cache"} 27908 1132 29040
291 1132 my $flight = Mojo::Promise->new;
292 # Handled even when no waiter joined, so a failure is not warned about.
293 1132 ▶ $flight->catch(sub { });
Subroutine __ANON__: called CC=1 SCAR=0.0
294 1132 return $self->{flights}{$key} = $flight;
295 }
296  
297 # Takes an address off the board and settles its flight for every waiter.
298 29040 ▶sub _land {
Subroutine _land: called CC=5 SCAR=16.7
299 29040 my ($self, $key, $flight, $ok, $value) = @_;
300 29040 ▶ return unless $flight;
Branch: 1 branch
BranchTrueFalseTotal
unless $flight 27908 1132 29040
301 delete $self->{flights}{$key}
302 1132 ▶ if $self->{flights}{$key} && $self->{flights}{$key} == $flight;
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"flights"}{$key} and $self->{"flights"}{$key} == $flight 1132 0 1132
Condition33%1/3
$self->{"flights"}{$key} and $self->{"flights"}{$key} == $flight
!ll&&!rl&&r
001132
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
303 1132 ▶ return $ok ? $flight->resolve($value) : $flight->reject($value);
Branch: 1 branch
BranchTrueFalseTotal
$ok ? : 1110 22 1132
304 }
305  
306 # The cache and flight key of an address and the agent sent with it. A NUL can
307 # be in neither an address the API answers nor a header, so no pair reads as
308 # another.
309 87270 ▶sub _key {
Subroutine _key: called CC=2 SCAR=6.9
310 87270 my ($ip, $agent) = @_;
311 87270 ▶ return defined $agent ? "$ip\0$agent" : $ip;
Branch: 1 branch
BranchTrueFalseTotal
defined $agent ? : 30 87240 87270
312 }
313  
314 # The user agent a call sends: undef for none, an empty one included, as the API
315 # reads `user_agent=`. One longer than the spec's 1024 characters is sent whole,
316 # since the API cuts it there and answers.
317 29137 ▶sub _agent {
Subroutine _agent: called CC=4 SCAR=13.9
318 29137 my ($method, $agent) = @_;
319 29137 ▶ return undef unless defined $agent;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $agent 29103 34 29137
320 34 ▶ Carp::croak("VPNDetection::$method: user_agent must be a string") if ref $agent;
Branch: 1 branch
BranchTrueFalseTotal
if ref $agent 3 31 34
321 31 ▶ return length $agent ? "$agent" : undef;
Branch: 1 branch
BranchTrueFalseTotal
length $agent ? : 28 3 31
322 }
323  
324 # The query a lookup sends its agent in. Mojo percent-encodes every byte but
325 # letters, digits and `*-._`, a `+` included, and writes a space as `+`.
326 496 ▶sub _agent_query {
Subroutine _agent_query: called CC=2 SCAR=6.9
327 496 my ($agent) = @_;
328 496 ▶ return defined $agent ? (user_agent => $agent) : ();
Branch: 1 branch
BranchTrueFalseTotal
defined $agent ? : 12 484 496
329 }
330  
331 # The address our edge observed this client calling from. Deliberately not
332 # cached: the cache is keyed by address, and which address this is IS the
333 # question.
334 35 ▶sub my_ip {
Subroutine my_ip: called CC=1 SCAR=0.0
Pod documented
335 35 my $self = shift;
336 35 $self->_assert_blocking_ok('my_ip');
337 35 return $self->_wait($self->my_ip_p(@_));
338 }
339  
340 35 ▶sub my_ip_p {
Subroutine my_ip_p: called CC=2 SCAR=7.0
Pod undocumented
341 35 my ($self, %options) = @_;
342 35 $self->_check_options('my_ip', \%options, 'retries', 'timeout', 'user_agent');
343  
344 28 my $url = $self->_url('/myip', _agent_query(_agent('my_ip', $options{user_agent})));
345 27 ▶ my $retries = defined $options{retries} ? $options{retries} : $self->{retries};
Branch: 1 branch
BranchTrueFalseTotal
defined $options{'retries'} ? : 0 27 27
346 29 ▶ return $self->_retry_p($retries, sub { $self->_json_p($url, undef, $options{timeout}, undef, $LOOKUP) })
Subroutine __ANON__: called CC=1 SCAR=0.0
347 27 ▶ ->then(sub { VPNDetection::Result->from_wire(shift) });
Subroutine __ANON__: called CC=1 SCAR=0.0
348 }
349  
350 # What this key is entitled to and what it has spent. Deliberately not cached:
351 # the whole point is the number, and a cached one is wrong within seconds.
352 89 ▶sub my_entitlement {
Subroutine my_entitlement: called CC=1 SCAR=0.0
Pod documented
353 89 my $self = shift;
354 89 $self->_assert_blocking_ok('my_entitlement');
355 89 return $self->_wait($self->my_entitlement_p(@_));
356 }
357  
358 89 ▶sub my_entitlement_p {
Subroutine my_entitlement_p: called CC=2 SCAR=7.0
Pod undocumented
359 89 my ($self, %options) = @_;
360 89 $self->_check_options('my_entitlement', \%options, 'retries', 'timeout');
361  
362 82 my $url = $self->_url('/api/v1/entitlement');
363 82 ▶ my $retries = defined $options{retries} ? $options{retries} : $self->{retries};
Branch: 1 branch
BranchTrueFalseTotal
defined $options{'retries'} ? : 0 82 82
364 82 ▶ return $self->_retry_p($retries, sub { $self->_json_p($url, undef, $options{timeout}, undef, $ENTITLEMENT) });
Subroutine __ANON__: called CC=1 SCAR=0.0
365 }
366  
367 # Classify many addresses concurrently, keyed by address rather than positional,
368 # so duplicates collapse to one request and the caller never lines two lists up.
369 67 ▶sub lookup_batch {
Subroutine lookup_batch: called CC=1 SCAR=0.0
Pod documented
370 67 my $self = shift;
371 67 $self->_assert_blocking_ok('lookup_batch');
372 67 return $self->_wait($self->lookup_batch_p(@_));
373 }
374  
375 86 ▶sub lookup_batch_p {
Subroutine lookup_batch_p: called CC=19 SCAR=29.6
Pod undocumented
376 86 my ($self, $ips, %options) = @_;
377 86 ▶ Carp::croak('lookup_batch: expected an array reference of addresses')
Branch: 1 branch
BranchTrueFalseTotal
if ref $ips ne "ARRAY" 0 86 86
378 if ref $ips ne 'ARRAY';
379 86 $self->_check_options('lookup_batch', \%options, 'retries', 'concurrency', 'timeout', 'user_agents');
380 55 my $wanted = $options{user_agents};
381 55 ▶ 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 54 55
Condition100%3/3
defined $wanted and ref $wanted ne "HASH"
!ll&&!rl&&r
4951
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
382 if defined $wanted && ref $wanted ne 'HASH';
383  
384 54 ▶ my $limit = defined $options{concurrency} ? $options{concurrency} : $self->{concurrency};
Branch: 1 branch
BranchTrueFalseTotal
defined $options{'concurrency'} ? : 4 50 54
385 54 ▶ my $retries = defined $options{retries} ? $options{retries} : $self->{retries};
Branch: 1 branch
BranchTrueFalseTotal
defined $options{'retries'} ? : 0 54 54
386  
387 # Bogons are answered locally and cached answers are reused; everything else
388 # goes to the batch endpoint in chunks of up to 1000 addresses, with at most
389 # `limit` chunks in flight. Keyed by address rather than positional, so
390 # duplicates in the input collapse to a single entry and the caller never has
391 # to line two lists up.
392 # An IPv4-mapped address is sent as the address it carries, once however
393 # many of its spellings were asked, and answered under each one asked.
394 54 ▶ my @asked = grep { defined && length } @$ips;
Condition33%1/3
defined $_ && length $_
!ll&&!rl&&r
0028581
MC/DC0%0/2
defined $_ && length $_
defined $_ length $_
Truth table33%1/3
A && B
A= defined $_B= length $_
ABresult
0X0
100
111
395 # Each address's agent, keyed by the address as sent: where two spellings of
396 # one IPv4-mapped address carry different agents, the first listed is sent.
397 54 my %agents;
398 54 for my $ip (@asked) {
399 28581 ▶ my $agent = _agent('lookup_batch', $wanted ? $wanted->{$ip} : undef);
Branch: 1 branch
BranchTrueFalseTotal
$wanted ? : 1009 27572 28581
400 28580 ▶ $agents{ VPNDetection::Bogon::unmapped($ip) } //= $agent if defined $agent;
Branch: 1 branch
BranchTrueFalseTotal
if defined $agent 4 28576 28580
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
401 }
402 53 my %seen;
403 53 my @unique = grep { !$seen{$_}++ } map { VPNDetection::Bogon::unmapped($_) } @asked;
404 53 my %answers;
405 my @pending;
406 53 my %joined;
407 53 for my $ip (@unique) {
408 28577 ▶ if (VPNDetection::Bogon::is_bogon($ip)) {
Branch: 1 branch
BranchTrueFalseTotal
if (VPNDetection::Bogon::is_bogon($ip)) 3 28574 28577
409 3 $answers{$ip} = VPNDetection::Bogon::bogon_result($ip);
410 3 next;
411 }
412 28574 my $key = _key($ip, $agents{$ip});
413 28574 ▶ my $hit = $self->{cache} ? $self->{cache}->get($key) : undef;
Branch: 1 branch
BranchTrueFalseTotal
$self->{'cache'} ? : 1040 27534 28574
414 28574 ▶ if ($hit) {
Branch: 1 branch
BranchTrueFalseTotal
if ($hit) 1 28573 28574
415 1 $answers{$ip} = $hit;
416 1 next;
417 }
418 # Already in flight with the same agent, for a lookup or another batch:
419 # this batch takes that request's answer rather than sending it again.
420 28573 ▶ if ($self->{cache} && $self->{flights}{$key}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"cache"} and $self->{"flights"}{$key}) 2 28571 28573
Condition100%3/3
$self->{"cache"} and $self->{"flights"}{$key}
!ll&&!rl&&r
2753410372
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
421 2 $joined{$ip} = $self->{flights}{$key};
422 2 next;
423 }
424 28571 push @pending, $ip;
425 }
426 # Boarded before any chunk is built, so a lookup of one of these arriving
427 # meanwhile waits for this batch's answer.
428 53 my %boarded = map { ($_ => $self->_board(_key($_, $agents{$_}))) } @pending;
429 53 my @queue;
430 53 ▶ push @queue, [splice @pending, 0, BATCH_MAX] while @pending;
Branch: 1 branch
BranchTrueFalseTotal
@pending and do { push @queue, [splice(@pending, 0, 1000)] } 79 53 132
431  
432 my $batch = {
433 queue => \@queue, answers => \%answers, active => 0, limit => $limit,
434 53 retries => $retries, timeout => $options{timeout}, promise => Mojo::Promise->new,
435 boarded => \%boarded, agents => \%agents,
436 };
437 53 $self->_dispatch($batch);
438 my $done = %joined ? Mojo::Promise->all(
439 $batch->{promise},
440 map {
441 2 my $ip = $_;
442 $joined{$ip}->then(
443 2 ▶ sub { $answers{$ip} = shift },
Subroutine __ANON__: called CC=1 SCAR=0.0
444 0 ▶ sub { $answers{$ip} = VPNDetection::Error->wrap(shift) },
Subroutine __ANON__: not called CC=1 SCAR=6.9
445 2 );
446 } sort keys %joined,
447 53 ▶ ) : $batch->{promise};
Branch: 1 branch
BranchTrueFalseTotal
%joined ? : 2 51 53
448 53 ▶ return $done->then(sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
449 53 return { map { ($_ => $answers{ VPNDetection::Bogon::unmapped($_) }) } @asked };
450 53 });
451 }
452  
453 # The licensed dataset downloads. Built per call rather than held, so the client
454 # and its sub-API never form a reference cycle.
455 195 ▶sub database {
Subroutine database: called CC=1 SCAR=0.0
Pod documented
456 195 my ($self) = @_;
457 195 return VPNDetection::Database->_new($self);
458 }
459  
460 # The OAuth device-flow sign-in, built per call for the same reason.
461 164 ▶sub oauth {
Subroutine oauth: called CC=1 SCAR=0.0
Pod documented
462 164 my ($self) = @_;
463 164 return VPNDetection::Oauth->_new($self);
464 }
465  
466 # Keeps exactly `limit` chunks in flight: every answer starts the next one, so a
467 # per-call concurrency is a real ceiling rather than an option that was accepted
468 # and ignored. A failing address carries its error as its value, so one bad
469 # entry cannot lose the rest of the answers: the API reports a per-entry failure
470 # with the status the single lookup would have answered, and a chunk that fails
471 # as a whole marks every address in it.
472 132 ▶sub _dispatch {
Subroutine _dispatch: called CC=5 SCAR=16.1
473 132 my ($self, $batch) = @_;
474 132 ▶ if (!@{$batch->{queue}} && !$batch->{active}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (@{$batch->{"queue"};} or $batch->{"active"}) 53 79 132
Condition100%3/3
@{$batch->{"queue"};} or $batch->{"active"}
l!l&&r!l&&!r
70953
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
475 53 $batch->{promise}->resolve($batch->{answers});
476 53 return;
477 }
478 79 ▶ while ($batch->{active} < $batch->{limit} && @{$batch->{queue}}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($batch->{"active"} < $batch->{"limit"} and @{$batch->{"queue"};}) 79 79 158
Condition100%3/3
$batch->{"active"} < $batch->{"limit"} and @{$batch->{"queue"};}
!ll&&!rl&&r
245579
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
479 79 my $chunk = shift @{$batch->{queue}};
480 79 $batch->{active}++;
481 79 ▶ $self->_lookup_chunk_p($chunk, $batch->{agents}, $batch->{retries}, $batch->{timeout})->then(sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
482 79 my $answers = shift;
483 79 for my $ip (keys %$answers) {
484 28571 my $answer = $answers->{$ip};
485 28571 $batch->{answers}{$ip} = $answer;
486 28571 ▶ my $failed = Scalar::Util::blessed($answer) && $answer->isa('VPNDetection::Error');
Condition66%2/3
builtin::blessed($answer) && $answer->isa('VPNDetection::Error')
!ll&&!rl&&r
02854229
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
487 28571 $self->_land(_key($ip, $batch->{agents}{$ip}), $batch->{boarded}{$ip}, !$failed, $answer);
488 }
489 79 $self->_settled($batch);
490 79 });
491 }
492 }
493  
494 # One POST /batch, mapped back onto the addresses it was asked about. A
495 # chunk-level failure - the call refused, the transport failing, the retries
496 # exhausted - becomes every address's error, exactly as it would have been had
497 # each been looked up alone. Never rejects: the failure is the value.
498 79 ▶sub _lookup_chunk_p {
Subroutine _lookup_chunk_p: called CC=2 SCAR=6.9
499 79 my ($self, $chunk, $agents, $retries, $timeout) = @_;
500 79 my $url = $self->_url('/batch');
501 # Sent only when an address of this chunk carries an agent, never as {}.
502 79 my %sent = map { ($_ => $agents->{$_}) } grep { defined $agents->{$_} } @$chunk;
503 79 ▶ my $body = { ips => $chunk, %sent ? (user_agents => \%sent) : () };
Branch: 1 branch
BranchTrueFalseTotal
%sent ? : 2 77 79
504 80 ▶ return $self->_retry_p($retries, sub { $self->_json_p($url, $body, $timeout, undef, $BATCH) })->then(
Subroutine __ANON__: called CC=1 SCAR=0.0
505 75 ▶ sub {
Subroutine __ANON__: called CC=7 SCAR=19.5
506 75 my $body = shift;
507 75 my $results = $body->{results};
508 75 my $errors = $body->{errors};
509 75 my %answers;
510 # An entry is judged alone: one that is not an answer is that
511 # address's error, and the rest of the chunk keeps its answers.
512 75 for my $ip (@$chunk) {
513 28566 ▶ 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 [])) { } 28542 24 28566
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
51928542
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
514 28542 my $result = VPNDetection::Result->from_wire($results->{$ip});
515 28542 ▶ $self->{cache}->set(_key($ip, $agents->{$ip}), $result) if $self->{cache};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"cache"} 1032 27510 28542
516 28542 $answers{$ip} = $result;
517 }
518 ▶ 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
519 $answers{$ip} = VPNDetection::Error->from_entry(
520 $errors->{$ip}{status}, $errors->{$ip}{error},
521 3 );
522 }
523 else {
524 21 $answers{$ip} = VPNDetection::Error->new(
525 kind => 'server_error', status => 200,
526 message => "the batch answer did not include $ip",
527 );
528 }
529 }
530 75 return \%answers;
531 },
532 4 ▶ sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
533 4 my $error = VPNDetection::Error->wrap(shift);
534 4 return { map { $_ => $error } @$chunk };
535 },
536 79 );
537 }
538  
539 # Releasing the slot happens in the SAME handler that records the answer. A
540 # second `then` would leave a gap in which a dying handler strands the slot, and
541 # a batch that never releases one never finishes.
542 79 ▶sub _settled {
Subroutine _settled: called CC=1 SCAR=0.0
543 79 my ($self, $batch) = @_;
544 79 $batch->{active}--;
545 79 $self->_dispatch($batch);
546 }
547  
548 # Recurses through $self rather than through a self-referential closure, which
549 # in Perl would be a reference cycle the interpreter never collects. $may_retry,
550 # when given, can veto a retry the error alone would allow; $tries counts the
551 # retries already made.
552 1206 ▶sub _retry_p {
Subroutine _retry_p: called CC=2 SCAR=6.9
553 1206 my ($self, $left, $attempt, $may_retry, $tries) = @_;
554 1206 ▶ $tries //= 0;
Condition100%2/2
$tries //= 0
l!l
1461060
MC/DC100%1/1
$tries //= 0
$tries
Truth table100%2/2
A
A= $tries
Aresult
11
00
555 786 ▶ return $attempt->()->catch(sub {
Subroutine __ANON__: called CC=5 SCAR=16.1
556 786 my $error = VPNDetection::Error->wrap(shift);
557 786 ▶ 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() 640 146 786
Condition100%9/9
$left <= 0 or not $error->retryable or $may_retry and not &$may_retry()
l!l&&r!l&&!r
6391146
$left <= 0 or not $error->retryable
l!l&&r!l&&!r
62415147
$may_retry and not &$may_retry()
!ll&&!rl&&r
14511
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
558 # The wait is a TIMER, never a sleep: this promise shares an event loop
559 # with every other request in the batch, and sleeping here would stall
560 # all of them.
561 return Mojo::Promise->timer(_retry_delay($error->retry_after, $tries))
562 146 ▶ ->then(sub { $self->_retry_p($left - 1, $attempt, $may_retry, $tries + 1) });
Subroutine __ANON__: called CC=1 SCAR=0.0
563 1206 });
564 }
565  
566 # The server's Retry-After when it gave a usable one, otherwise the backoff:
567 # 250 ms, doubling per retry, capped from the seventh. A Retry-After past
568 # LONGEST_WAIT is waited out on the backoff too, still rate_limited, rather than
569 # holding the call for as long as any server asks.
570 159 ▶sub _retry_delay {
Subroutine _retry_delay: called CC=5 SCAR=16.1
571 159 my ($retry_after, $tries) = @_;
572 159 ▶ return $retry_after
Branch: 1 branch
BranchTrueFalseTotal
if defined $retry_after and $retry_after > 0 and $retry_after <= "2147483.647" 3 156 159
Condition100%6/6
defined $retry_after and $retry_after > 0 and $retry_after <= "2147483.647"
!ll&&!rl&&r
15333
defined $retry_after and $retry_after > 0
!ll&&!rl&&r
15126
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
573 if defined $retry_after && $retry_after > 0 && $retry_after <= LONGEST_WAIT;
574 156 ▶ return BACKOFF_BASE * 2**($tries < 6 ? $tries : 6);
Branch: 1 branch
BranchTrueFalseTotal
$tries < 6 ? : 154 2 156
575 }
576  
577 # $timeout is the call's own bound, or undef for the client's. $member, when
578 # given, is the one member of the answer the call returns; $shape is what the
579 # whole answer must be (see _nonconforming), members the call never reads
580 # included. An answer that is
581 # not fails inside the attempt as a retried server_error, like any other 2xx that
582 # cannot be read, rather than reaching the caller: through 3.8.0 a lookup's
583 # `"is_hosting": "yes"`, a version of "3" and a list entry of null came back as
584 # served, and `{}` as a lookup's answer.
585 960 ▶sub _json_p {
Subroutine _json_p: called CC=2 SCAR=6.9
586 960 my ($self, $url, $body, $timeout, $member, $shape) = @_;
587 960 ▶ my $sent = defined $body ? $self->_post_p($url, $body, $timeout) : $self->_get_p($url, $timeout);
Branch: 1 branch
BranchTrueFalseTotal
defined $body ? : 80 880 960
588 938 ▶ return $sent->then(sub {
Subroutine __ANON__: called CC=6 SCAR=17.9
589 938 my $res = shift->res;
590 938 ▶ die VPNDetection::Error->from_response($res->code, $res->headers, $res->json)
Branch: 1 branch
BranchTrueFalseTotal
unless $res->is_success 43 895 938
591 unless $res->is_success;
592 895 my $decoded = $res->json;
593 576 ▶ my $unreadable = sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
594 576 die VPNDetection::Error->new(kind => 'server_error', status => $res->code, message => shift);
595 895 };
596 895 ▶ $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 879 895
597 879 ▶ return $decoded unless $shape;
Branch: 1 branch
BranchTrueFalseTotal
unless $shape 0 879 879
598 879 my $wrong = _nonconforming($shape, $decoded, []);
599 879 ▶ $unreadable->($wrong) if defined $wrong;
Branch: 1 branch
BranchTrueFalseTotal
if defined $wrong 560 319 879
600 319 ▶ return defined $member ? $decoded->{$member} : $decoded;
Branch: 1 branch
BranchTrueFalseTotal
defined $member ? : 41 278 319
601 958 });
602 }
603  
604 # undef when the value has the shape, else what the API answered wrong, naming
605 # the member by its path. A string is told from a number by the scalar Mojo::JSON
606 # decoded it into, as VPNDetection::Oauth does, since nothing else in Perl tells
607 # `"7"` from `7`. No list entry or map value may be null.
608 128619 ▶sub _nonconforming {
Subroutine _nonconforming: called CC=37 SCAR=36.3
609 128619 my ($shape, $value, $at) = @_;
610 128619 my ($kind, $inner) = @$shape;
611 128619 ▶ 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 ? : 73 0 73
612 128619 ▶ return $wrong->() unless defined $value;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $value 16 128603 128619
613 128603 ▶ return undef if $kind eq 'any';
Branch: 1 branch
BranchTrueFalseTotal
if $kind eq "any" 28566 100037 128603
614 100037 ▶ if ($kind eq 'string') {
Branch: 1 branch
BranchTrueFalseTotal
if ($kind eq "string") 33848 66189 100037
615 33848 ▶ return VPNDetection::Oauth::_is_string($value) ? undef : $wrong->();
Branch: 1 branch
BranchTrueFalseTotal
VPNDetection::Oauth::_is_string($value) ? : 33836 12 33848
616 }
617 66189 ▶ if ($kind eq 'date' || $kind eq 'date-time') {
Branch: 1 branch
BranchTrueFalseTotal
if ($kind eq "date" or $kind eq "date-time") 2849 63340 66189
Condition100%3/3
$kind eq "date" or $kind eq "date-time"
l!l&&r!l&&!r
237947063340
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
618 2849 ▶ return VPNDetection::Oauth::_is_string($value) && _is_rfc3339($kind, $value) ? undef
Branch: 1 branch
BranchTrueFalseTotal
VPNDetection::Oauth::_is_string($value) && _is_rfc3339($kind, $value) ? : 2387 462 2849
Condition66%2/3
VPNDetection::Oauth::_is_string($value) and _is_rfc3339($kind, $value)
!ll&&!rl&&r
04622387
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
619 : 'the API answered ' . join('.', @$at) . ' that is no RFC 3339 ' . $kind;
620 }
621 63340 ▶ if ($kind eq 'integer') {
Branch: 1 branch
BranchTrueFalseTotal
if ($kind eq "integer") 465 62875 63340
622 465 ▶ 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/ ? : 445 20 465
Condition66%4/6
not ref $value || VPNDetection::Oauth::_is_string($value) and $value =~ /\A-?[0-9]+\z/
!ll&&!rl&&r
200445
ref $value || VPNDetection::Oauth::_is_string($value)
l!l&&r!l&&!r
020445
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
623 ? undef : $wrong->();
624 }
625 62875 ▶ if ($kind eq 'number') {
Branch: 1 branch
BranchTrueFalseTotal
if ($kind eq "number") 10 62865 62875
626 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
627 && Scalar::Util::looks_like_number($value) ? undef : $wrong->();
628 }
629 62865 ▶ if ($kind eq 'boolean') {
Branch: 1 branch
BranchTrueFalseTotal
if ($kind eq "boolean") 30308 32557 62865
630 30308 ▶ return Scalar::Util::blessed($value) && $value->isa('JSON::PP::Boolean') ? undef : $wrong->();
Branch: 1 branch
BranchTrueFalseTotal
builtin::blessed($value) && $value->isa('JSON::PP::Boolean') ? : 30291 17 30308
Condition66%2/3
builtin::blessed($value) and $value->isa("JSON::PP::Boolean")
!ll&&!rl&&r
17030291
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
631 }
632 32557 ▶ if ($kind eq 'object') {
Branch: 1 branch
BranchTrueFalseTotal
if ($kind eq "object") 4 32553 32557
633 4 ▶ return ref $value eq 'HASH' ? undef : $wrong->();
Branch: 1 branch
BranchTrueFalseTotal
ref $value eq 'HASH' ? : 4 0 4
634 }
635 32553 ▶ if ($kind eq 'list') {
Branch: 1 branch
BranchTrueFalseTotal
if ($kind eq "list") 509 32044 32553
636 509 ▶ return $wrong->() unless ref $value eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $value eq "ARRAY" 4 505 509
637 505 for my $i (0 .. $#$value) {
638 446 my $w = _nonconforming($inner, $value->[$i], [@$at, $i]);
639 446 ▶ return $w if defined $w;
Branch: 1 branch
BranchTrueFalseTotal
if defined $w 137 309 446
640 }
641 368 return undef;
642 }
643 32044 ▶ if ($kind eq 'map_of') {
Branch: 1 branch
BranchTrueFalseTotal
if ($kind eq "map_of") 170 31874 32044
644 170 ▶ return $wrong->() unless ref $value eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $value eq "HASH" 0 170 170
645 170 for my $key (sort keys %$value) {
646 28583 my $w = _nonconforming($inner, $value->{$key}, [@$at, $key]);
647 28583 ▶ return $w if defined $w;
Branch: 1 branch
BranchTrueFalseTotal
if defined $w 6 28577 28583
648 }
649 164 return undef;
650 }
651 31874 ▶ return $wrong->() unless ref $value eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $value eq "HASH" 2 31872 31874
652 31872 for my $field (@$inner) {
653 1316638 my ($name, $member_shape, $required) = @$field;
654 1316638 ▶ if (!defined $value->{$name}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $value->{$name}) 1246493 70145 1316638
655 return 'the API answered with no ' . join('.', @$at, $name)
656 1246493 ▶ if $required && ($required != NOT_NULL || exists $value->{$name});
Branch: 1 branch
BranchTrueFalseTotal
if $required and $required != 2 || exists $value->{$name} 46 1246447 1246493
Condition100%6/6
$required and $required != 2 || exists $value->{$name}
!ll&&!rl&&r
1246438946
$required != 2 or exists $value->{$name}
l!l&&r!l&&!r
4429
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
657 1246447 next;
658 }
659 70145 my $w = _nonconforming($member_shape, $value->{$name}, [@$at, $name]);
660 70145 ▶ return $w if defined $w;
Branch: 1 branch
BranchTrueFalseTotal
if defined $w 1053 69092 70145
661 }
662 30773 return undef;
663 }
664  
665 # RFC 3339's `full-date`, or its `date-time` with the `T` and `Z` in either case,
666 # an hour below 24, a minute and second below 60 and an offset of at most 23:59,
667 # on a day its month has. ASCII digits and `\z`, since Perl's `\d` takes any
668 # script's digits and `$` a trailing newline.
669 12 my $FULL_DATE = qr/\A([0-9]{4})-([0-9]{2})-([0-9]{2})\z/;
670 12 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]+)?
671 (?:[Zz]|[+-]([0-9]{2}):([0-9]{2}))\z/x;
672  
673 2849 ▶sub _is_rfc3339 {
Subroutine _is_rfc3339: called CC=10 SCAR=23.0
674 2849 my ($kind, $value) = @_;
675 2849 ▶ if ($kind eq 'date') {
Branch: 1 branch
BranchTrueFalseTotal
if ($kind eq "date") 2379 470 2849
676 2379 ▶ my @date = $value =~ $FULL_DATE or return 0;
Branch: 1 branch
BranchTrueFalseTotal
my(@date) = $value =~ /$FULL_DATE/ or return 0 2155 224 2379
677 2155 return _is_day(@date);
678 }
679 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
680 or return 0;
681 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
682 && (!defined $off_hour || ($off_hour < 24 && $off_minute < 60));
683 }
684  
685 2518 ▶sub _is_day {
Subroutine _is_day: called CC=7 SCAR=19.5
686 2518 my ($year, $month, $day) = @_;
687 2518 ▶ return 0 if $month < 1 || $month > 12 || $day < 1;
Branch: 1 branch
BranchTrueFalseTotal
if $month < 1 or $month > 12 or $day < 1 34 2484 2518
Condition83%5/6
$month < 1 or $month > 12 or $day < 1
l!l&&r!l&&!r
17172484
$month < 1 or $month > 12
l!l&&r!l&&!r
0172501
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
688 2484 ▶ 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
15152454
$year % 4 == 0 and $year % 100 != 0
!ll&&!rl&&r
24393015
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
689 2484 ▶ return $day <= (31, $leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)[$month - 1];
Branch: 1 branch
BranchTrueFalseTotal
$leap ? : 30 2454 2484
690 }
691  
692 904 ▶sub _get_p {
Subroutine _get_p: called CC=1 SCAR=0.0
693 904 my ($self, $url, $timeout) = @_;
694 904 return $self->_start_p($self->{ua}->build_tx(GET => $url => $self->_headers), $timeout);
695 }
696  
697 # The one request with a body: the batch. Mojo encodes the JSON and sets the
698 # content type.
699 80 ▶sub _post_p {
Subroutine _post_p: called CC=1 SCAR=0.0
700 80 my ($self, $url, $body, $timeout) = @_;
701 80 my $tx = $self->{ua}->build_tx(POST => $url => $self->_headers => json => $body);
702 80 return $self->_start_p($tx, $timeout);
703 }
704  
705 # One dataset transfer. Every chunk is handed to $on_chunk and none is kept, so a
706 # body costs the same in memory whether it is 10 KB or 1.79 GB. Resolves with the
707 # number of bytes handed over.
708 15 ▶sub _stream_p {
Subroutine _stream_p: called CC=1 SCAR=0.0
709 15 my ($self, $url, $on_chunk) = @_;
710 # Built here rather than through _get_p, which is the only place the API key
711 # is ever attached: the presigned link authorizes itself, so carrying the key
712 # would hand it to a host with no business holding it.
713 15 my $tx = $self->{ua}->build_tx(GET => $url);
714  
715 # Mojo asks for gzip on every request it builds. A dataset file is already
716 # compressed, so the only thing that would buy is a Content-Length counting
717 # bytes that never reach the sink, and that length is the only evidence the
718 # transfer arrived whole.
719 15 $tx->req->headers->remove('Accept-Encoding');
720 # Mojo aborts a response past max_message_size, counting every byte it parses
721 # whether or not it keeps any of them. The default is 2 GiB, which the
722 # catalog is already within an order of magnitude of, and
723 # MOJO_MAX_MESSAGE_SIZE lowers it for every response in the process, on a
724 # machine whose environment we do not own.
725 15 $tx->res->max_message_size(0);
726  
727 15 my $received = 0;
728 # Unsubscribing Mojo's own reader is what stops the body being collected into
729 # the message. The subscriber hangs off the transaction, so holding the
730 # transaction strongly inside it would be a cycle the interpreter never
731 # collects; the user agent keeps it alive for as long as bytes are arriving.
732 15 my $weak = $tx;
733 15 Scalar::Util::weaken($weak);
734 209 ▶ $tx->res->content->unsubscribe('read')->on(read => sub {
Subroutine __ANON__: called CC=4 SCAR=14.1
735 209 my (undef, $bytes) = @_;
736 # An error body is neither written out nor held: the status is what
737 # separates a lapsed link from a refused one, and nothing bounds the size
738 # of what a storage host puts in the body of a refusal.
739 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
740 207 $received += length $bytes;
741 207 $on_chunk->($bytes);
742 15 });
743  
744 14 ▶ return $self->_start_p($tx, 0)->then(sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
745 14 my $res = shift->res;
746 14 ▶ die VPNDetection::Error->from_response($res->code, $res->headers, {
Branch: 1 branch
BranchTrueFalseTotal
unless $res->code == 200 2 12 14
747 error => 'object storage refused the download link with status ' . $res->code,
748 }) unless $res->code == 200;
749  
750 # Before Mojolicious 9.54 a body that stops early reaches Perl as an
751 # ordinary end of stream: the status was 200 and Mojo reports no error,
752 # so without this a half transfer is a short file nobody notices.
753 12 my $short = _short_transfer($res, $received);
754 12 ▶ die $short if $short;
Branch: 1 branch
BranchTrueFalseTotal
if $short 0 12 12
755 12 return $received;
756 1 ▶ }, sub {
Subroutine __ANON__: called CC=2 SCAR=7.6
757 1 my $error = shift;
758 # From 9.54 the same body rejects as `Premature connection close`, which
759 # says nothing of how far it got, so the lengths are added to it.
760 1 my $short = _short_transfer($tx->res, $received, $error);
761 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
762 15 });
763 }
764  
765 # The error for a 200 whose body stopped short of the length it declared, or
766 # undef when it did not. $cause is what Mojo rejected it with, when it did.
767 13 ▶sub _short_transfer {
Subroutine _short_transfer: called CC=8 SCAR=23.7
768 13 my ($res, $received, $cause) = @_;
769 13 my $declared = $res->headers->content_length;
770 return undef
771 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
772 1 my $message = "the transfer ended after $received of $declared bytes";
773 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
774 1 return VPNDetection::Error->new(kind => 'network', message => $message);
775 }
776  
777 # request_timeout bounds the WHOLE response and Mojo::UserAgent has no
778 # per-transaction form of it, yet a call may bring its own bound and a transfer
779 # must have none (0): 30 seconds is right for a lookup and wrong for a gigabyte.
780 # So it is set only across the hand-over, where start_p arms the timer
781 # synchronously - and set EXPLICITLY each time, because Mojo runs a loop tick
782 # inside start_p when the loop is idle, and a retry started in that tick would
783 # otherwise inherit this call's bound.
784 #
785 # A rejection is a plain string when the request never got far enough to have a
786 # status, which is exactly the transport failure the retry rule treats as worth
787 # another attempt.
788 1204 ▶sub _start_p {
Subroutine _start_p: called CC=3 SCAR=11.0
789 1204 my ($self, $tx, $timeout) = @_;
790 1204 my $ua = $self->{ua};
791 1204 my $bound = $ua->request_timeout;
792 1204 ▶ $ua->request_timeout(defined $timeout ? 0 + $timeout : $self->{timeout});
Branch: 1 branch
BranchTrueFalseTotal
defined $timeout ? : 70 1134 1204
793 1204 my $promise = eval { $ua->start_p($tx) };
794 1204 my $failed = $@;
795 1204 $ua->request_timeout($bound);
796 1204 ▶ die VPNDetection::Error->wrap($failed) unless $promise;
Branch: 1 branch
BranchTrueFalseTotal
unless $promise 0 1204 1204
797 47 ▶ return $promise->catch(sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
798 47 die VPNDetection::Error->new(kind => 'network', message => "$_[0]");
799 1204 });
800 }
801  
802 984 ▶sub _headers {
Subroutine _headers: called CC=2 SCAR=6.9
803 984 my ($self) = @_;
804 984 my %headers = (Accept => 'application/json');
805 # One scheme, though the API offers three. Sending the same key as a bearer
806 # token, a header and a query parameter at once is three times the exposure
807 # for one credential, and query strings end up in logs. A blank key is none
808 # at all (see new).
809 984 ▶ $headers{Authorization} = "Bearer $self->{api_key}" if defined $self->{api_key};
Branch: 1 branch
BranchTrueFalseTotal
if defined $self->{"api_key"} 666 318 984
810 984 return \%headers;
811 }
812  
813 1052 ▶sub _url {
Subroutine _url: called CC=2 SCAR=6.9
814 1052 my ($self, $path, %query) = @_;
815 1052 my $url = Mojo::URL->new($self->{base_url} . $path);
816 1052 ▶ $url->query(%query) if %query;
Branch: 1 branch
BranchTrueFalseTotal
if %query 78 974 1052
817 1052 return $url;
818 }
819  
820 1022 ▶sub _wait {
Subroutine _wait: called CC=2 SCAR=6.9
821 1022 my ($self, $promise) = @_;
822 1022 my ($value, $error, $failed);
823 1022 ▶ $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
824 1022 ▶ die $error if $failed;
Branch: 1 branch
BranchTrueFalseTotal
if $failed 651 371 1022
825 371 return $value;
826 }
827  
828 # Checked BEFORE the promise is built, not after: Mojo::UserAgent starts a
829 # transaction as soon as it is created, so croaking later would still have spent
830 # a request from the caller's allowance.
831 1160 ▶sub _assert_blocking_ok {
Subroutine _assert_blocking_ok: called CC=2 SCAR=6.9
832 1160 my ($self, $method) = @_;
833 1160 ▶ return unless Mojo::IOLoop->is_running;
Branch: 1 branch
BranchTrueFalseTotal
unless "Mojo::IOLoop"->is_running 1159 1 1160
834 1 Carp::croak(
835 "VPNDetection::$method cannot block inside a running Mojo::IOLoop; "
836 . "call ${method}_p instead, which returns a Mojo::Promise"
837 );
838 }
839  
840 1247 ▶sub _check_options {
Subroutine _check_options: called CC=9 SCAR=22.0
841 1247 my ($self, $method, $options, @allowed) = @_;
842 1247 my %allowed = map { $_ => 1 } @allowed;
843 1247 my @unknown = sort grep { !$allowed{$_} } keys %$options;
844 1247 ▶ Carp::croak("VPNDetection::$method: unknown option(s): @unknown") if @unknown;
Branch: 1 branch
BranchTrueFalseTotal
if @unknown 6 1241 1247
845 # A negative or non-numeric bound would fire at once and fail the very call
846 # it was meant to protect.
847 1241 my $timeout = $options->{timeout};
848 1241 ▶ 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 1236 1241
Condition100%6/6
defined $timeout and not &Scalar::Util::looks_like_number($timeout) && $timeout >= 0
!ll&&!rl&&r
1182545
&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
849 if defined $timeout && !(Scalar::Util::looks_like_number($timeout) && $timeout >= 0);
850 Carp::croak("VPNDetection::$method: retries must be a whole number, 0 or more")
851 1236 ▶ 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 1138 1236
Condition100%3/3
defined $options->{"retries"} and not _is_count($options->{"retries"}, 0)
!ll&&!rl&&r
1136298
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
852 Carp::croak("VPNDetection::$method: concurrency must be a whole number, 1 or more")
853 1138 ▶ 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 1122 1138
Condition100%3/3
defined $options->{"concurrency"} and not _is_count($options->{"concurrency"}, 1)
!ll&&!rl&&r
1118416
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
854 }
855  
856 # A whole number from $least, or Inf for no limit. NaN compares false with
857 # anything, so a NaN count retried a failing call for good and a NaN concurrency
858 # put no chunk in flight, spinning the loop forever; a word reads as 0, and 1.5
859 # as two retries.
860 2843 ▶sub _is_count {
Subroutine _is_count: called CC=4 SCAR=13.9
861 2843 my ($n, $least) = @_;
862 2843 ▶ 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
118202705
not ref $n and &Scalar::Util::looks_like_number($n) and $n >= $least
!ll&&!rl&&r
57612725
not ref $n and &Scalar::Util::looks_like_number($n)
!ll&&!rl&&r
19382786
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
863 }
864  
865 875 ▶sub _base_url {
Subroutine _base_url: called CC=3 SCAR=11.0
866 875 my ($url) = @_;
867 875 ▶ $url = DEFAULT_BASE_URL unless defined $url && length $url;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $url and length $url 4 871 875
Condition66%2/3
defined $url and length $url
!ll&&!rl&&r
40871
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
868 875 $url =~ s{/+\z}{};
869 875 return $url;
870 }
871  
872 12 1;
873  
874 __END__
↑ Summary VPNDetection/Oauth.pm »