VPNDetection.pm

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