InternetData.pm

filter: Statementstmt 99.8% 499 / 500 Branchbran 95.6% 199 / 208 Conditioncond 84.2% 134 / 159 MC/DCmcdc 73.2% 63 / 86 Subroutinesub 98.9% 91 / 92 Podpod 62.5% 10 / 16 totaltotal 93.8% 996 / 1061 CC 165 SCAR 23.1
CC
165
Cov
96%
_nonconforming
35.2
new
19.0
lookup_batch_p
13.0
CRAP 10.1
↑ Summary InternetData/Oauth.pm »
1 package InternetData;
2  
3 9 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 9 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5  
6 9 ▶use Carp ();
Subroutine BEGIN: called CC=1 SCAR=0.0
7 9 ▶use Exporter 'import';
Subroutine BEGIN: called CC=1 SCAR=0.0
8 9 ▶use Mojo::IOLoop;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 9 ▶use Mojo::Promise;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 9 ▶use Mojo::URL;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 9 ▶use Mojo::UserAgent;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 9 ▶use Mojo::Util ();
Subroutine BEGIN: called CC=1 SCAR=0.0
13 9 ▶use Scalar::Util ();
Subroutine BEGIN: called CC=1 SCAR=0.0
14  
15 9 ▶use InternetData::AsnResult;
Subroutine BEGIN: called CC=1 SCAR=0.0
16 9 ▶use InternetData::Bogon ();
Subroutine BEGIN: called CC=1 SCAR=0.0
17 9 ▶use InternetData::Cache;
Subroutine BEGIN: called CC=1 SCAR=0.0
18 9 ▶use InternetData::Database;
Subroutine BEGIN: called CC=1 SCAR=0.0
19 9 ▶use InternetData::DomainResult;
Subroutine BEGIN: called CC=1 SCAR=0.0
20 9 ▶use InternetData::Error;
Subroutine BEGIN: called CC=1 SCAR=0.0
21 9 ▶use InternetData::Oauth;
Subroutine BEGIN: called CC=1 SCAR=0.0
22 9 ▶use InternetData::Result;
Subroutine BEGIN: called CC=1 SCAR=0.0
23  
24 9 our $VERSION = '1.18.2';
25 9 our @EXPORT_OK = ('is_bogon');
26  
27 9 ▶use constant DEFAULT_BASE_URL => 'https://api.internetdata.io';
Subroutine BEGIN: called CC=1 SCAR=0.0
28  
29 # The most addresses POST /batch takes in one call; a larger batch is sent in
30 # chunks of this size.
31 9 ▶use constant BATCH_MAX => 1000;
Subroutine BEGIN: called CC=1 SCAR=0.0
32  
33 # Seconds before the first retry; each later one waits twice the one before.
34 9 ▶use constant BACKOFF_BASE => 0.25;
Subroutine BEGIN: called CC=1 SCAR=0.0
35  
36 # The longest Retry-After honored, in seconds: 2**31 - 1 ms, about 24.8 days,
37 # the same bound as the .NET SDK's.
38 9 ▶use constant LONGEST_WAIT => 2_147_483.647;
Subroutine BEGIN: called CC=1 SCAR=0.0
39  
40 9 my %OPTIONS = map { $_ => 1 } qw(
41 api_key base_url cache_size cache_ttl concurrency retries timeout ua
42 );
43  
44 # The shapes of the answers, from the pinned spec's schemas: a member it requires
45 # and never sends as null is required, a nullable or optional one may be absent
46 # or null, and every one present has the spec's type at every depth. A detail
47 # requires no member, so `{}`, its answer under a false flag, is one.
48 9 my $CLASS_DETAIL = [fields => [map { [$_ => ['string']] } qw(provider provider_name confidence last_seen)]];
49 my $PROXY_DETAIL = [fields => [
50 36 (map { [$_ => ['string']] } qw(provider provider_name first_seen last_seen)),
51 9 (map { [$_ => ['integer']] } qw(hits hits_days_pct providers_num)),
52 ]];
53 my $PUBPROXY_DETAIL = [fields => [
54 [entry => ['boolean']], [exit => ['boolean']], [protocols => [list => ['string']]],
55 [num_ports => ['integer']], [num_proxies => ['integer']],
56 9 (map { [$_ => ['string']] } qw(last_seen last_usable)),
57 ]];
58 9 my $CARRIER_DETAIL = [fields => [map { [$_ => ['string']] } qw(name mcc mnc country confidence)]];
59 my $SATELLITE_DETAIL = [fields => [
60 9 (map { [$_ => ['string']] } qw(provider provider_name orbit segment country)),
61 [asn => ['integer']], [confidence => ['string']],
62 ]];
63 # Whose bot uses the address, what its bots do and whether the operator vouches for it.
64 my $BOT_DETAIL = [fields => [
65 18 (map { [$_ => ['string']] } qw(provider provider_name)),
66 18 (map { [$_ => [list => ['string']]] } qw(agents categories)), [verified => ['boolean']],
67 9 (map { [$_ => ['string']] } qw(identity verified_by confidence first_seen last_seen)),
68 ]];
69 my $SSH_DETAIL = [fields => [
70 18 [port => ['integer']], (map { [$_ => ['string']] } qw(banner host_key_fp)),
71 9 [session_ok => ['boolean']], (map { [$_ => ['string']] } qw(first_seen last_seen)),
72 ]];
73 my $SMTP_DETAIL = [fields => [
74 [port => ['integer']], [banner => ['string']], [session_ok => ['boolean']],
75 9 (map { [$_ => ['string']] } qw(first_seen last_seen)),
76 ]];
77 # Web IP's detail is a list of the web servers found, each one whole.
78 my $WEB_SERVER = [fields => [
79 18 [port => ['integer'], 1], (map { [$_ => ['boolean'], 1] } qw(tls_ok session_ok)),
80 [status_code => ['integer'], 1],
81 54 (map { [$_ => ['string'], 1] } qw(server location title cert_subject_cn cert_subject_o cert_issuer_dn)),
82 [cert_browser_trusted => ['boolean'], 1],
83 9 (map { [$_ => ['string'], 1] } qw(tls_version first_seen last_seen)),
84 ]];
85 my $DNS_RESOLVER_DETAIL = [fields => [
86 [port => ['integer']], [recursion_available => ['boolean']], [rcode => ['integer']],
87 9 [answer_correct => ['boolean']], (map { [$_ => ['string']] } qw(first_seen last_seen)),
88 ]];
89 my $BITTORRENT_DETAIL = [fields => [
90 18 (map { [$_ => ['boolean']] } qw(verified id_matches_ip)),
91 27 (map { [$_ => ['string']] } qw(first_seen last_seen last_reachable)),
92 9 (map { [$_ => ['integer']] } qw(days_seen num_ports peak_num_ports)),
93 [indexer => ['boolean']], [clients => [list => ['string']]],
94 ]];
95 # The shared objects, whose members past the required ones are paid.
96 my $LOCATION = [fields => [
97 90 (map { [$_ => ['string'], 1] } qw(
98 continent continent_name country country_name timezone currency_code currency_name
99 currency_symbol flag_emoji flag_unicode
100 )),
101 36 (map { [$_ => ['string']] } qw(region region_code city postal_code)),
102 18 (map { [$_ => ['number']] } qw(latitude longitude)), [accuracy_radius => ['integer']],
103 9 (map { [$_ => ['string']] } qw(geoname_id dma_code last_changed)),
104 ]];
105 my $ASN = [fields => [
106 36 [asn => ['integer'], 1], (map { [$_ => ['string'], 1] } qw(name domain type prefix)),
107 9 (map { [$_ => ['string']] } qw(country rpki_status)),
108 ]];
109 my $COMPANY = [fields => [
110 9 (map { [$_ => ['string'], 1] } qw(name domain)), (map { [$_ => ['string']] } qw(type country)),
111 ]];
112 my $ABUSE = [fields => [
113 9 [email => ['string'], 1], (map { [$_ => ['string']] } qw(name phone address country network)),
114 [validated => ['boolean']], [unvalidated_since => ['string']],
115 ]];
116 my $WHOIS = [fields => [
117 9 (map { [$_ => ['string'], 1] } qw(id name org country status source domain abuse_email)),
118 [asn => ['integer'], 1],
119 ]];
120 9 my $RWHOIS = [fields => [map { [$_ => ['string'], 1] } qw(id name country source domain abuse_email)]];
121 our $LOOKUP = [fields => [
122 [ip => ['string'], 1], [is_bogon => ['boolean'], 1], [is_vpn => ['boolean']],
123 18 (map { [$_ => ['boolean'], 1] } qw(is_tor is_relay)),
124 54 (map { [$_ => ['boolean']] } qw(is_resproxy is_dcproxy is_mobproxy is_pubproxy is_hosting is_cdn)),
125 81 (map { [$_ => ['boolean'], 1] } qw(
126 is_bot is_anycast is_carrier is_satellite is_ssh is_smtp is_web is_dns_resolver is_bittorrent
127 )),
128 18 [vpn => $CLASS_DETAIL], (map { [$_ => $CLASS_DETAIL, 1] } qw(tor relay)),
129 27 (map { [$_ => $PROXY_DETAIL] } qw(resproxy dcproxy mobproxy)), [pubproxy => $PUBPROXY_DETAIL],
130 9 (map { [$_ => $CLASS_DETAIL] } qw(hosting cdn)), [bot => $BOT_DETAIL], [carrier => $CARRIER_DETAIL],
131 [satellite => $SATELLITE_DETAIL], [ssh => $SSH_DETAIL], [smtp => $SMTP_DETAIL],
132 [web => [list => $WEB_SERVER]], [dns_resolver => $DNS_RESOLVER_DETAIL], [bittorrent => $BITTORRENT_DETAIL],
133 [location => $LOCATION, 1], [asn => $ASN, 1], [company => $COMPANY, 1], [hostname => ['string'], 1],
134 [abuse => $ABUSE, 1], [whois => $WHOIS], [rwhois => $RWHOIS],
135 [hosted_domains => [fields => [[total => ['integer'], 1], [domains => [list => ['string']]]]]],
136 [trial_expired => ['boolean']],
137 [cap_reached => ['boolean']],
138 ]];
139 my $AS_PREFIX = [fields => [
140 [prefix => ['string'], 1], [peer_count => ['integer'], 1],
141 9 (map { [$_ => ['string'], 1] } qw(rpki_status first_seen country)),
142 [size => ['integer'], 1], [other_origins => [list => ['integer']], 1],
143 ]];
144 our $ASN_LOOKUP = [fields => [
145 45 [asn => ['integer'], 1], (map { [$_ => ['string'], 1] } qw(name country registry allocated domain)),
146 [type => ['string']],
147 54 (map { [$_ => ['integer']] } qw(num_ips num_prefixes4 num_prefixes6 rpki_valid rpki_invalid rpki_not_found)),
148 [whois => [map_of => ['string']]], [prefixes => [list => $AS_PREFIX]],
149 [rank => ['integer']], [tier1 => ['boolean']],
150 9 (map { (["num_$_" => ['integer']], [$_ => [list => ['integer']]]) } qw(upstreams peers downstreams)),
151 [hosted_domains => [fields => [[total => ['integer'], 1], [domains => [list => ['string']]]]]],
152 [trial_expired => ['boolean']],
153 [cap_reached => ['boolean']],
154 ]];
155 9 my $DNS_ADDRESS = [fields => [map { [$_ => ['string'], 1] } qw(ip last_seen)]];
156 my $DOMAIN_DNS = [fields => [
157 18 (map { [$_ => [list => $DNS_ADDRESS], 1] } qw(a aaaa)),
158 18 [mx => [list => [fields => [[priority => ['integer'], 1], map { [$_ => ['string'], 1] } qw(host last_seen)]]], 1],
159 18 [ns => [list => [fields => [map { [$_ => ['string'], 1] } qw(host last_seen)]]], 1],
160 9 [cname => [list => [fields => [map { [$_ => ['string'], 1] } qw(target last_seen)]]], 1],
161 ]];
162 my $DOMAIN_IP_RANGES = [fields => [
163 18 (map { [$_ => ['string'], 1] } qw(domain redirects_to)), (map { [$_ => ['integer'], 1] } qw(total ipv4)),
164 9 [ranges => [list => [fields => [map { [$_ => ['string'], 1] } qw(range name country)]]], 1],
165 ]];
166 # Each address the domain resolves to, with the address answer's asn.
167 9 my $DOMAIN_HOST = [fields => [[ip => ['string'], 1], [asn => $ASN, 1]]];
168 9 my $COHOSTED_DOMAINS = [fields => [
169 [ip => ['string'], 1], [total => ['integer'], 1], [domains => [list => ['string']], 1],
170 ]];
171 my $DOMAIN_WEB = [fields => [
172 9 (map { [$_ => ['string'], 1] } qw(url title description last_seen)),
173 [links => [fields => [[total => ['integer'], 1], [hosts => [list => ['string']], 1]]], 1],
174 ]];
175 # Redirects and backlinks share it.
176 9 my $DOMAIN_REFERRERS = [fields => [[total => ['integer'], 1], [domains => [list => ['string']], 1]]];
177 our $DOMAIN_LOOKUP = [fields => [
178 [domain => ['string'], 1], [is_registered => ['boolean'], 1], [is_disposable => ['boolean']],
179 45 (map { [$_ => ['boolean'], 1] } qw(has_a has_aaaa has_mx has_ns has_cname)),
180 [dns => $DOMAIN_DNS], [hosting => [list => $DOMAIN_HOST]], [cohosted_domains => $COHOSTED_DOMAINS],
181 [ip_ranges => $DOMAIN_IP_RANGES],
182 [disposable => [fields => [
183 [confidence => ['string']], [providers => [list => ['string']]],
184 18 (map { [$_ => ['string']] } qw(first_seen last_seen)),
185 ]]],
186 9 [web => $DOMAIN_WEB], (map { [$_ => $DOMAIN_REFERRERS] } qw(redirects backlinks)),
187 [trial_expired => ['boolean']],
188 [cap_reached => ['boolean']],
189 ]];
190 9 our $BATCH_ERROR = [fields => [[status => ['integer'], 1], [error => ['string'], 1]]];
191 # Each entry is judged alone, by _lookup_chunk_p.
192 9 our $BATCH = [fields => [[results => [map_of => ['any']], 1], [errors => [map_of => ['any']], 1]]];
193 9 our $ENTITLEMENT = [fields => [
194 [org_id => ['string'], 1],
195 [apikey => [fields => [
196 [id => ['string'], 1], [expires => ['date-time']], [allowed_cidrs => [list => ['string']], 1],
197 ]], 1],
198 [plan => [fields => [[key => ['string'], 1], [name => ['string'], 1], [tier => ['string'], 1]]], 1],
199 [usage => [fields => [
200 [requests => ['integer'], 1], [quota => ['integer'], 1], [hard_limit => ['integer']],
201 [window_start => ['date-time'], 1], [window_end => ['date-time'], 1],
202 ]], 1],
203 ]];
204  
205 503 ▶sub new {
Subroutine new: called CC=19 SCAR=29.4
Pod documented
206 503 my ($class, %args) = @_;
207 503 my @unknown = sort grep { !$OPTIONS{$_} } keys %args;
208 503 ▶ Carp::croak("InternetData->new: unknown option(s): @unknown") if @unknown;
Branch: 1 branch
BranchTrueFalseTotal
if @unknown 1 502 503
209  
210 502 ▶ my $concurrency = defined $args{concurrency} ? $args{concurrency} : 8;
Branch: 1 branch
BranchTrueFalseTotal
defined $args{'concurrency'} ? : 11 491 502
211 502 ▶ my $retries = defined $args{retries} ? $args{retries} : 2;
Branch: 1 branch
BranchTrueFalseTotal
defined $args{'retries'} ? : 236 266 502
212 502 ▶ my $cache_size = defined $args{cache_size} ? $args{cache_size} : 10_000;
Branch: 1 branch
BranchTrueFalseTotal
defined $args{'cache_size'} ? : 32 470 502
213 502 ▶ Carp::croak('InternetData->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 493 502
214 493 ▶ Carp::croak('InternetData->new: retries must be a whole number, 0 or more') unless _is_count($retries, 0);
Branch: 1 branch
BranchTrueFalseTotal
unless _is_count($retries, 0) 8 485 493
215 # Mojo arms a negative or non-numeric bound as a timer that fires at once, so
216 # every call would fail as a network error after reaching the server.
217 485 ▶ my $timeout = defined $args{timeout} ? $args{timeout} : 30;
Branch: 1 branch
BranchTrueFalseTotal
defined $args{'timeout'} ? : 46 439 485
218 485 ▶ Carp::croak('InternetData->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 483 485
Condition100%3/3
&Scalar::Util::looks_like_number($timeout) and $timeout >= 0
!ll&&!rl&&r
11483
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
219 unless Scalar::Util::looks_like_number($timeout) && $timeout >= 0;
220  
221 # Trimmed, so a key read from a file loses its newline, and blanks alone are
222 # no key. Mojo refuses a CR or LF in a header with a raw string from every
223 # call and sends any other control character, so one left inside is refused
224 # here, naming the cause and not the key.
225 483 my $api_key = $args{api_key};
226 483 ▶ if (defined $api_key) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $api_key) 223 260 483
227 223 $api_key =~ s/\A\s+|\s+\z//g;
228 223 ▶ $api_key = undef unless length $api_key;
Branch: 1 branch
BranchTrueFalseTotal
unless length $api_key 4 219 223
229 }
230 483 ▶ Carp::croak('InternetData->new: api_key holds a control character')
Branch: 1 branch
BranchTrueFalseTotal
if defined $api_key and $api_key =~ /[\x00-\x1f\x7f]/ 5 478 483
Condition100%3/3
defined $api_key and $api_key =~ /[\x00-\x1f\x7f]/
!ll&&!rl&&r
2642145
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
231 if defined $api_key && $api_key =~ /[\x00-\x1f\x7f]/;
232 # Mojo writes a header as bytes, so a character past U+00FF dies in the
233 # reactor and every call fails after its whole timeout with nothing sent.
234 478 ▶ Carp::croak('InternetData->new: api_key holds a character past U+00FF')
Branch: 1 branch
BranchTrueFalseTotal
if defined $api_key and $api_key =~ /[^\x00-\xff]/ 2 476 478
Condition100%3/3
defined $api_key and $api_key =~ /[^\x00-\xff]/
!ll&&!rl&&r
2642122
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
235 if defined $api_key && $api_key =~ /[^\x00-\xff]/;
236  
237 my $self = bless {
238 api_key => $api_key,
239 base_url => _base_url($args{base_url}),
240 concurrency => 0 + $concurrency,
241 retries => 0 + $retries,
242 # Held as a number: Mojo tests the bound for truth before arming it, and a
243 # string such as '0.0' is true, so it would be a timer that fires at once
244 # rather than no bound.
245 timeout => 0 + $timeout,
246 cache => $cache_size > 0 ? InternetData::Cache->new(
247 max => $cache_size,
248 ttl => defined $args{cache_ttl} ? $args{cache_ttl} : 3600,
249 ) : undef,
250 # The addresses with a request in flight, each a promise its waiters
251 # take the answer from (see _board).
252 flights => {},
253 476 ▶ ua => $args{ua} || Mojo::UserAgent->new,
Branch: 2 branches
BranchTrueFalseTotal
$cache_size > 0 ? : 445 31 476
defined $args{'cache_ttl'} ? : 15 430 445
Condition66%2/3
$args{'ua'} || 'Mojo::UserAgent'->new
l!l&&r!l&&!r
84680
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
254 }, $class;
255  
256 # Mojo::UserAgent does not follow redirects by default, but MOJO_MAX_REDIRECTS
257 # in the environment turns that on for every agent in the process. Setting it
258 # here is what stops a download's 302 being chased into a multi-gigabyte
259 # transfer, on a machine whose environment we do not own.
260 476 $self->{ua}->max_redirects(0);
261 476 $self->{ua}->request_timeout($self->{timeout});
262 476 $self->{ua}->transactor->name("internetdata-perl/$VERSION");
263 476 return $self;
264 }
265  
266 # Both a method and an exportable function, so the address is the LAST argument
267 # either way: is_bogon($ip) and $client->is_bogon($ip) reach the same code.
268 565 ▶sub is_bogon {
Subroutine is_bogon: called CC=3 SCAR=12.5
Pod documented
269 565 my $ip = pop;
270 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
271 565 return InternetData::Bogon::is_bogon($ip);
272 }
273  
274 # What every database says about one address. A bogon is answered locally and
275 # never reaches the network; everything else is served, then cached for this
276 # client.
277 175 ▶sub lookup {
Subroutine lookup: called CC=1 SCAR=0.0
Pod documented
278 175 my $self = shift;
279 175 $self->_assert_blocking_ok('lookup');
280 174 return $self->_wait($self->lookup_p(@_));
281 }
282  
283 217 ▶sub lookup_p {
Subroutine lookup_p: called CC=10 SCAR=23.0
Pod undocumented
284 217 my ($self, $ip, %options) = @_;
285 217 ▶ Carp::croak('lookup: expected an IP address') if !defined $ip || !length $ip;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $ip and length $ip 2 215 217
Condition100%3/3
defined $ip and length $ip
!ll&&!rl&&r
11215
MC/DC100%2/2
defined $ip and length $ip
defined $ip length $ip
Truth table100%3/3
A and B
A= defined $ipB= length $ip
ABresult
0X0
100
111
286 215 $self->_check_options('lookup', \%options, 'retries', 'timeout');
287 # Judged, cached and sent as the IPv4 address it carries, if it is mapped.
288 189 $ip = InternetData::Bogon::unmapped($ip);
289 # This API answers an AS or a domain at the same path, as an answer this call
290 # cannot read, so one sent here would come back as three retried server_errors.
291 189 ▶ return Mojo::Promise->reject(InternetData::Error->new(
Branch: 1 branch
BranchTrueFalseTotal
unless InternetData::Bogon::is_ip($ip) 16 173 189
292 kind => 'bad_request',
293 message => "'$ip' is not an IP address: look up an AS with lookup_asn, and a domain with lookup_domain",
294 )) unless InternetData::Bogon::is_ip($ip);
295  
296 173 ▶ return Mojo::Promise->resolve(InternetData::Bogon::bogon_result($ip))
Branch: 1 branch
BranchTrueFalseTotal
if InternetData::Bogon::is_bogon($ip) 4 169 173
297 if InternetData::Bogon::is_bogon($ip);
298  
299 169 ▶ if ($self->{cache}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"cache"}) 107 62 169
300 107 my $hit = $self->{cache}->get($ip);
301 107 ▶ return Mojo::Promise->resolve($hit) if $hit;
Branch: 1 branch
BranchTrueFalseTotal
if $hit 5 102 107
302 # A miss for an address already in flight, for a lookup or a batch,
303 # takes that request's answer rather than sending its own.
304 102 ▶ return $self->{flights}{$ip}->then(sub { shift }) if $self->{flights}{$ip};
Subroutine __ANON__: called CC=1 SCAR=0.0
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"flights"}{$ip} 24 78 102
305 }
306  
307 140 my $flight = $self->_board($ip);
308 140 my $url = $self->_url('/' . Mojo::Util::url_escape($ip, '^A-Za-z0-9\-._~:'));
309 140 ▶ my $retries = defined $options{retries} ? $options{retries} : $self->{retries};
Branch: 1 branch
BranchTrueFalseTotal
defined $options{'retries'} ? : 2 138 140
310 # Anything that dies before a request is under way lands the flight too, or
311 # every later lookup of the address would wait on it forever.
312 140 ▶ 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
313 140 ▶ if (!$sent) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($sent) 3 137 140
314 3 my $error = $@;
315 3 $self->_land($ip, $flight, 0, $error);
316 3 die $error;
317 }
318 return $sent->then(
319 54 ▶ sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
320 54 my $result = InternetData::Result->from_wire(shift);
321 # Only a served answer is cached, and before it lands, so a miss
322 # after the flight is gone finds it. Errors never are, and bogons
323 # never reach this far.
324 54 ▶ $self->{cache}->set($ip, $result) if $self->{cache};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"cache"} 36 18 54
325 54 $self->_land($ip, $flight, 1, $result);
326 54 return $result;
327 },
328 83 ▶ sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
329 83 my $error = shift;
330 83 $self->_land($ip, $flight, 0, $error);
331 83 return Mojo::Promise->reject($error);
332 },
333 137 );
334 }
335  
336 # Concurrent misses for one address share ONE request. The first miss boards the
337 # address, and every miss after it, a batch's included, waits for that request
338 # instead. The request runs under the options of the call that led it; a failure
339 # reaches every waiter and is cached for none. Nothing is shared without a cache,
340 # since every lookup is then served. A Mojo::Promise cannot be canceled, so no
341 # waiter is ever left behind by a leader that gave up.
342 27695 ▶sub _board {
Subroutine _board: called CC=2 SCAR=6.9
343 27695 my ($self, $ip) = @_;
344 27695 ▶ return undef unless $self->{cache};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"cache"} 27583 112 27695
345 112 my $flight = Mojo::Promise->new;
346 # Handled even when no waiter joined, so a failure is not warned about.
347 112 ▶ $flight->catch(sub { });
Subroutine __ANON__: called CC=1 SCAR=0.0
348 112 return $self->{flights}{$ip} = $flight;
349 }
350  
351 # Takes an address off the board and settles its flight for every waiter.
352 27695 ▶sub _land {
Subroutine _land: called CC=5 SCAR=16.7
353 27695 my ($self, $ip, $flight, $ok, $value) = @_;
354 27695 ▶ return unless $flight;
Branch: 1 branch
BranchTrueFalseTotal
unless $flight 27583 112 27695
355 delete $self->{flights}{$ip}
356 112 ▶ if $self->{flights}{$ip} && $self->{flights}{$ip} == $flight;
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"flights"}{$ip} and $self->{"flights"}{$ip} == $flight 112 0 112
Condition33%1/3
$self->{"flights"}{$ip} and $self->{"flights"}{$ip} == $flight
!ll&&!rl&&r
00112
MC/DC0%0/2
$self->{"flights"}{$ip} and $self->{"flights"}{$ip} == $flight
$self->{"flights"}{$ip} $self->{"flights"}{$ip} == $flight
Truth table33%1/3
A and B
A= $self->{"flights"}{$ip}B= $self->{"flights"}{$ip} == $flight
ABresult
0X0
100
111
357 112 ▶ return $ok ? $flight->resolve($value) : $flight->reject($value);
Branch: 1 branch
BranchTrueFalseTotal
$ok ? : 64 48 112
358 }
359  
360 # What every database says about one AS. Not cached and not batched: only an
361 # address is.
362 45 ▶sub lookup_asn {
Subroutine lookup_asn: called CC=1 SCAR=0.0
Pod documented
363 45 my $self = shift;
364 45 $self->_assert_blocking_ok('lookup_asn');
365 44 return $self->_wait($self->lookup_asn_p(@_));
366 }
367  
368 45 ▶sub lookup_asn_p {
Subroutine lookup_asn_p: called CC=4 SCAR=13.9
Pod undocumented
369 45 my ($self, $asn, %options) = @_;
370 45 ▶ Carp::croak('lookup_asn: expected an AS number') if !defined $asn || !length $asn;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $asn and length $asn 2 43 45
Condition100%3/3
defined $asn and length $asn
!ll&&!rl&&r
1143
MC/DC100%2/2
defined $asn and length $asn
defined $asn length $asn
Truth table100%3/3
A and B
A= defined $asnB= length $asn
ABresult
0X0
100
111
371 43 $self->_check_options('lookup_asn', \%options, 'retries', 'timeout');
372  
373 33 my $url = $self->_url('/asn/' . _path_segment($asn));
374 33 ▶ my $retries = defined $options{retries} ? $options{retries} : $self->{retries};
Branch: 1 branch
BranchTrueFalseTotal
defined $options{'retries'} ? : 1 32 33
375 47 ▶ return $self->_retry_p($retries, sub { $self->_json_p($url, undef, $options{timeout}, undef, $ASN_LOOKUP) })
Subroutine __ANON__: called CC=1 SCAR=0.0
376 33 ▶ ->then(sub { InternetData::AsnResult->from_wire(shift) });
Subroutine __ANON__: called CC=1 SCAR=0.0
377 }
378  
379 # What every database says about one domain, neither cached nor batched.
380 52 ▶sub lookup_domain {
Subroutine lookup_domain: called CC=1 SCAR=0.0
Pod documented
381 52 my $self = shift;
382 52 $self->_assert_blocking_ok('lookup_domain');
383 51 return $self->_wait($self->lookup_domain_p(@_));
384 }
385  
386 52 ▶sub lookup_domain_p {
Subroutine lookup_domain_p: called CC=4 SCAR=13.9
Pod undocumented
387 52 my ($self, $domain, %options) = @_;
388 52 ▶ Carp::croak('lookup_domain: expected a domain') if !defined $domain || !length $domain;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $domain and length $domain 2 50 52
Condition100%3/3
defined $domain and length $domain
!ll&&!rl&&r
1150
MC/DC100%2/2
defined $domain and length $domain
defined $domain length $domain
Truth table100%3/3
A and B
A= defined $domainB= length $domain
ABresult
0X0
100
111
389 50 $self->_check_options('lookup_domain', \%options, 'retries', 'timeout');
390  
391 40 my $url = $self->_url('/domain/' . _path_segment($domain));
392 40 ▶ my $retries = defined $options{retries} ? $options{retries} : $self->{retries};
Branch: 1 branch
BranchTrueFalseTotal
defined $options{'retries'} ? : 1 39 40
393 56 ▶ return $self->_retry_p($retries, sub { $self->_json_p($url, undef, $options{timeout}, undef, $DOMAIN_LOOKUP) })
Subroutine __ANON__: called CC=1 SCAR=0.0
394 40 ▶ ->then(sub { InternetData::DomainResult->from_wire(shift) });
Subroutine __ANON__: called CC=1 SCAR=0.0
395 }
396  
397 # The address our edge observed this client calling from. Deliberately not
398 # cached: the cache is keyed by address, and which address this is IS the
399 # question.
400 26 ▶sub my_ip {
Subroutine my_ip: called CC=1 SCAR=0.0
Pod documented
401 26 my $self = shift;
402 26 $self->_assert_blocking_ok('my_ip');
403 25 return $self->_wait($self->my_ip_p(@_));
404 }
405  
406 25 ▶sub my_ip_p {
Subroutine my_ip_p: called CC=2 SCAR=6.9
Pod undocumented
407 25 my ($self, %options) = @_;
408 25 $self->_check_options('my_ip', \%options, 'retries', 'timeout');
409  
410 15 my $url = $self->_url('/myip');
411 15 ▶ my $retries = defined $options{retries} ? $options{retries} : $self->{retries};
Branch: 1 branch
BranchTrueFalseTotal
defined $options{'retries'} ? : 1 14 15
412 18 ▶ return $self->_retry_p($retries, sub { $self->_json_p($url, undef, $options{timeout}, undef, $LOOKUP) })
Subroutine __ANON__: called CC=1 SCAR=0.0
413 15 ▶ ->then(sub { InternetData::Result->from_wire(shift) });
Subroutine __ANON__: called CC=1 SCAR=0.0
414 }
415  
416 # What this key is entitled to and what it has spent. Deliberately not cached:
417 # the whole point is the number, and a cached one is wrong within seconds.
418 54 ▶sub my_entitlement {
Subroutine my_entitlement: called CC=1 SCAR=0.0
Pod documented
419 54 my $self = shift;
420 54 $self->_assert_blocking_ok('my_entitlement');
421 53 return $self->_wait($self->my_entitlement_p(@_));
422 }
423  
424 53 ▶sub my_entitlement_p {
Subroutine my_entitlement_p: called CC=2 SCAR=6.9
Pod undocumented
425 53 my ($self, %options) = @_;
426 53 $self->_check_options('my_entitlement', \%options, 'retries', 'timeout');
427  
428 43 my $url = $self->_url('/api/v1/entitlement');
429 43 ▶ my $retries = defined $options{retries} ? $options{retries} : $self->{retries};
Branch: 1 branch
BranchTrueFalseTotal
defined $options{'retries'} ? : 1 42 43
430 43 ▶ return $self->_retry_p($retries, sub { $self->_json_p($url, undef, $options{timeout}, undef, $ENTITLEMENT) });
Subroutine __ANON__: called CC=1 SCAR=0.0
431 }
432  
433 # Look up many addresses concurrently, keyed by address rather than positional,
434 # so duplicates collapse to one request and the caller never lines two lists up.
435 55 ▶sub lookup_batch {
Subroutine lookup_batch: called CC=1 SCAR=0.0
Pod documented
436 55 my $self = shift;
437 55 $self->_assert_blocking_ok('lookup_batch');
438 54 return $self->_wait($self->lookup_batch_p(@_));
439 }
440  
441 72 ▶sub lookup_batch_p {
Subroutine lookup_batch_p: called CC=13 SCAR=25.7
Pod undocumented
442 72 my ($self, $ips, %options) = @_;
443 72 ▶ Carp::croak('lookup_batch: expected an array reference of addresses')
Branch: 1 branch
BranchTrueFalseTotal
if ref $ips ne "ARRAY" 1 71 72
444 if ref $ips ne 'ARRAY';
445 71 $self->_check_options('lookup_batch', \%options, 'retries', 'concurrency', 'timeout');
446  
447 38 ▶ my $limit = defined $options{concurrency} ? $options{concurrency} : $self->{concurrency};
Branch: 1 branch
BranchTrueFalseTotal
defined $options{'concurrency'} ? : 3 35 38
448 38 ▶ my $retries = defined $options{retries} ? $options{retries} : $self->{retries};
Branch: 1 branch
BranchTrueFalseTotal
defined $options{'retries'} ? : 0 38 38
449  
450 # Bogons are answered locally and cached answers are reused; everything else
451 # goes to the batch endpoint in chunks of up to 1000 addresses, with at most
452 # `limit` chunks in flight. An IPv4-mapped address is sent as the address it
453 # carries, once however many of its spellings were asked, and answered under
454 # each one asked.
455 38 ▶ my @asked = grep { defined && length } @$ips;
Condition33%1/3
defined $_ && length $_
!ll&&!rl&&r
0027562
MC/DC0%0/2
defined $_ && length $_
defined $_ length $_
Truth table33%1/3
A && B
A= defined $_B= length $_
ABresult
0X0
100
111
456 38 my %seen;
457 38 my @unique = grep { !$seen{$_}++ } map { InternetData::Bogon::unmapped($_) } @asked;
458 38 my %answers;
459 my @pending;
460 38 my %joined;
461 38 for my $ip (@unique) {
462 27559 ▶ if (InternetData::Bogon::is_bogon($ip)) {
Branch: 1 branch
BranchTrueFalseTotal
if (InternetData::Bogon::is_bogon($ip)) 2 27557 27559
463 2 $answers{$ip} = InternetData::Bogon::bogon_result($ip);
464 2 next;
465 }
466 27557 ▶ my $hit = $self->{cache} ? $self->{cache}->get($ip) : undef;
Branch: 1 branch
BranchTrueFalseTotal
$self->{'cache'} ? : 36 27521 27557
467 27557 ▶ if ($hit) {
Branch: 1 branch
BranchTrueFalseTotal
if ($hit) 1 27556 27557
468 1 $answers{$ip} = $hit;
469 1 next;
470 }
471 # Already in flight, for a lookup or another batch: this batch takes
472 # that request's answer rather than sending the address again.
473 27556 ▶ if ($self->{cache} && $self->{flights}{$ip}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"cache"} and $self->{"flights"}{$ip}) 1 27555 27556
Condition100%3/3
$self->{"cache"} and $self->{"flights"}{$ip}
!ll&&!rl&&r
27521341
MC/DC100%2/2
$self->{"cache"} and $self->{"flights"}{$ip}
$self->{"cache"} $self->{"flights"}{$ip}
Truth table100%3/3
A and B
A= $self->{"cache"}B= $self->{"flights"}{$ip}
ABresult
0X0
100
111
474 1 $joined{$ip} = $self->{flights}{$ip};
475 1 next;
476 }
477 27555 push @pending, $ip;
478 }
479 # Boarded before any chunk is built, so a lookup of one of these arriving
480 # meanwhile waits for this batch's answer.
481 38 my %boarded = map { ($_ => $self->_board($_)) } @pending;
482 38 my @queue;
483 38 ▶ push @queue, [splice @pending, 0, BATCH_MAX] while @pending;
Branch: 1 branch
BranchTrueFalseTotal
@pending and do { push @queue, [splice(@pending, 0, 1000)] } 64 38 102
484  
485 my $batch = {
486 queue => \@queue, answers => \%answers, active => 0, limit => $limit,
487 38 retries => $retries, timeout => $options{timeout}, promise => Mojo::Promise->new,
488 boarded => \%boarded,
489 };
490 38 $self->_dispatch($batch);
491 my $done = %joined ? Mojo::Promise->all(
492 $batch->{promise},
493 map {
494 1 my $ip = $_;
495 $joined{$ip}->then(
496 1 ▶ sub { $answers{$ip} = shift },
Subroutine __ANON__: called CC=1 SCAR=0.0
497 0 ▶ sub { $answers{$ip} = InternetData::Error->wrap(shift) },
Subroutine __ANON__: not called CC=1 SCAR=6.9
498 1 );
499 } sort keys %joined,
500 38 ▶ ) : $batch->{promise};
Branch: 1 branch
BranchTrueFalseTotal
%joined ? : 1 37 38
501 38 ▶ return $done->then(sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
502 38 return { map { ($_ => $answers{ InternetData::Bogon::unmapped($_) }) } @asked };
503 38 });
504 }
505  
506 # The licensed database downloads. Built per call rather than held, so the
507 # client and its sub-API never form a reference cycle.
508 167 ▶sub database {
Subroutine database: called CC=1 SCAR=0.0
Pod documented
509 167 my ($self) = @_;
510 167 return InternetData::Database->_new($self);
511 }
512  
513 # The OAuth device-flow sign-in, built per call for the same reason.
514 167 ▶sub oauth {
Subroutine oauth: called CC=1 SCAR=0.0
Pod documented
515 167 my ($self) = @_;
516 167 return InternetData::Oauth->_new($self);
517 }
518  
519 # Keeps exactly `limit` chunks in flight: every answer starts the next one, so a
520 # per-call concurrency is a real ceiling rather than an option that was accepted
521 # and ignored. A failing address carries its error as its value, so one bad
522 # entry cannot lose the rest of the answers: the API reports a per-entry failure
523 # with the status the single lookup would have answered, and a chunk that fails
524 # as a whole marks every address in it.
525 102 ▶sub _dispatch {
Subroutine _dispatch: called CC=5 SCAR=16.1
526 102 my ($self, $batch) = @_;
527 102 ▶ if (!@{$batch->{queue}} && !$batch->{active}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (@{$batch->{"queue"};} or $batch->{"active"}) 38 64 102
Condition100%3/3
@{$batch->{"queue"};} or $batch->{"active"}
l!l&&r!l&&!r
55938
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
528 38 $batch->{promise}->resolve($batch->{answers});
529 38 return;
530 }
531 64 ▶ while ($batch->{active} < $batch->{limit} && @{$batch->{queue}}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($batch->{"active"} < $batch->{"limit"} and @{$batch->{"queue"};}) 64 64 128
Condition100%3/3
$batch->{"active"} < $batch->{"limit"} and @{$batch->{"queue"};}
!ll&&!rl&&r
224264
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
532 64 my $chunk = shift @{$batch->{queue}};
533 64 $batch->{active}++;
534 64 ▶ $self->_lookup_chunk_p($chunk, $batch->{retries}, $batch->{timeout})->then(sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
535 64 my $answers = shift;
536 64 for my $ip (keys %$answers) {
537 27555 my $answer = $answers->{$ip};
538 27555 $batch->{answers}{$ip} = $answer;
539 27555 ▶ my $failed = Scalar::Util::blessed($answer) && $answer->isa('InternetData::Error');
Condition66%2/3
builtin::blessed($answer) && $answer->isa('InternetData::Error')
!ll&&!rl&&r
02753520
MC/DC50%1/2
builtin::blessed($answer) && $answer->isa('InternetData::Error')
builtin::blessed($answer) $answer->isa('InternetData::Error')
Truth table66%2/3
A && B
A= builtin::blessed($answer)B= $answer->isa('InternetData::Error')
ABresult
0X0
100
111
540 27555 $self->_land($ip, $batch->{boarded}{$ip}, !$failed, $answer);
541 }
542 64 $self->_settled($batch);
543 64 });
544 }
545 }
546  
547 # One POST /batch, mapped back onto the addresses it was asked about. A
548 # chunk-level failure - the call refused, the transport failing, the retries
549 # exhausted - becomes every address's error, exactly as it would have been had
550 # each been looked up alone. Never rejects: the failure is the value.
551 64 ▶sub _lookup_chunk_p {
Subroutine _lookup_chunk_p: called CC=1 SCAR=0.0
552 64 my ($self, $chunk, $retries, $timeout) = @_;
553 64 my $url = $self->_url('/batch');
554 65 ▶ return $self->_retry_p($retries, sub { $self->_json_p($url, { ips => $chunk }, $timeout, undef, $BATCH) })->then(
Subroutine __ANON__: called CC=1 SCAR=0.0
555 54 ▶ sub {
Subroutine __ANON__: called CC=7 SCAR=19.5
556 54 my $body = shift;
557 54 my $results = $body->{results};
558 54 my $errors = $body->{errors};
559 54 my %answers;
560 # An entry is judged alone: one that is not an answer is that
561 # address's error, and the rest of the chunk keeps its answers.
562 54 for my $ip (@$chunk) {
563 27544 ▶ if (defined $results->{$ip} && !defined _nonconforming($LOOKUP, $results->{$ip}, [])) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $results->{$ip} and not defined _nonconforming($InternetData::LOOKUP, $results->{$ip}, scalar [])) { } 27535 9 27544
elsif (defined $errors->{$ip} and not defined _nonconforming($InternetData::BATCH_ERROR, $errors->{$ip}, scalar [])) { } 4 5 9
Condition100%3/3
defined $results->{$ip} and not defined _nonconforming($InternetData::LOOKUP, $results->{$ip}, scalar [])
!ll&&!rl&&r
6327535
MC/DC100%2/2
defined $results->{$ip} and not defined _nonconforming($InternetData::LOOKUP, $results->{$ip}, scalar [])
defined $results->{$ip} not defined _nonconforming($InternetData::LOOKUP, $results->{$ip}, scalar [])
Truth table100%3/3
A and not(B)
A= defined $results->{$ip}B= not defined _nonconforming($InternetData::LOOKUP, $results->{$ip}, scalar [])
ABresult
0X0
100
111
564 27535 my $result = InternetData::Result->from_wire($results->{$ip});
565 27535 ▶ $self->{cache}->set($ip, $result) if $self->{cache};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"cache"} 28 27507 27535
566 27535 $answers{$ip} = $result;
567 }
568 ▶ elsif (defined $errors->{$ip} && !defined _nonconforming($BATCH_ERROR, $errors->{$ip}, [])) {
Condition100%3/3
defined $errors->{$ip} and not defined _nonconforming($InternetData::BATCH_ERROR, $errors->{$ip}, scalar [])
!ll&&!rl&&r
324
MC/DC100%2/2
defined $errors->{$ip} and not defined _nonconforming($InternetData::BATCH_ERROR, $errors->{$ip}, scalar [])
defined $errors->{$ip} not defined _nonconforming($InternetData::BATCH_ERROR, $errors->{$ip}, scalar [])
Truth table100%3/3
A and not(B)
A= defined $errors->{$ip}B= not defined _nonconforming($InternetData::BATCH_ERROR, $errors->{$ip}, scalar [])
ABresult
0X0
100
111
569 $answers{$ip} = InternetData::Error->from_entry(
570 $errors->{$ip}{status}, $errors->{$ip}{error},
571 4 );
572 }
573 else {
574 5 $answers{$ip} = InternetData::Error->new(
575 kind => 'server_error', status => 200,
576 message => "the batch answer did not include $ip",
577 );
578 }
579 }
580 54 return \%answers;
581 },
582 10 ▶ sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
583 10 my $error = InternetData::Error->wrap(shift);
584 10 return { map { $_ => $error } @$chunk };
585 },
586 64 );
587 }
588  
589 # Releasing the slot happens in the SAME handler that records the answer. A
590 # second `then` would leave a gap in which a dying handler strands the slot, and
591 # a batch that never releases one never finishes.
592 64 ▶sub _settled {
Subroutine _settled: called CC=1 SCAR=0.0
593 64 my ($self, $batch) = @_;
594 64 $batch->{active}--;
595 64 $self->_dispatch($batch);
596 }
597  
598 # One file transfer. Every chunk is handed to $on_chunk and none is kept, so a
599 # body costs the same in memory whether it is 264 bytes or 5.34 GiB. Resolves
600 # with the number of bytes handed over.
601 17 ▶sub _stream_p {
Subroutine _stream_p: called CC=1 SCAR=0.0
602 17 my ($self, $url, $on_chunk) = @_;
603 # Built here rather than through _get_p, which is the only place the API key
604 # is ever attached: the presigned link authorizes itself, so carrying the key
605 # would hand it to a host with no business holding it. Object storage answers
606 # 400 to a presigned GET that also carries an Authorization header, so this
607 # is not merely a leak - it breaks the download too.
608 17 my $tx = $self->{ua}->build_tx(GET => $url);
609  
610 # Mojo asks for gzip on every request it builds. A published file is already
611 # compressed, so the only thing that would buy is a Content-Length counting
612 # bytes that never reach the sink, and that length is the only evidence the
613 # transfer arrived whole.
614 17 $tx->req->headers->remove('Accept-Encoding');
615 # Mojo aborts a response past max_message_size, counting every byte it parses
616 # whether or not it keeps any of them. Mojo::Message::Response defaults to
617 # 2 GiB, which the catalog is already past, and MOJO_MAX_MESSAGE_SIZE lowers
618 # it for every response in the process, on a machine whose environment we do
619 # not own.
620 17 $tx->res->max_message_size(0);
621  
622 17 my $received = 0;
623 # Unsubscribing Mojo's own reader is what stops the body being collected into
624 # the message. The subscriber hangs off the transaction, so holding the
625 # transaction strongly inside it would be a cycle the interpreter never
626 # collects; the user agent keeps it alive for as long as bytes are arriving.
627 17 my $weak = $tx;
628 17 Scalar::Util::weaken($weak);
629 211 ▶ $tx->res->content->unsubscribe('read')->on(read => sub {
Subroutine __ANON__: called CC=4 SCAR=14.1
630 211 my (undef, $bytes) = @_;
631 # An error body is neither written out nor held: the status is what
632 # separates a lapsed link from a refused one, and nothing bounds the size
633 # of what a storage host puts in the body of a refusal.
634 211 ▶ return unless $weak && ($weak->res->code || 0) == 200;
Branch: 1 branch
BranchTrueFalseTotal
unless $weak and ($weak->res->code || 0) == 200 2 209 211
Condition60%3/5
$weak and ($weak->res->code || 0) == 200
!ll&&!rl&&r
02209
$weak->res->code || 0
l!l
2110
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
635 209 $received += length $bytes;
636 209 $on_chunk->($bytes);
637 17 });
638  
639 16 ▶ return $self->_start_p($tx, 0)->then(sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
640 16 my $res = shift->res;
641 # No body to read: the handler above kept nothing that was not a 200,
642 # because nothing bounds the size of what a storage host puts in a
643 # refusal. So the message names where the refusal came from, and the
644 # status still decides the kind - which is what says whether the link
645 # lapsed or was never good.
646 16 ▶ die InternetData::Error->from_response(
Branch: 1 branch
BranchTrueFalseTotal
unless $res->code == 200 2 14 16
647 $res->code, $res->headers, undef,
648 'object storage refused the download link with status ' . $res->code,
649 ) unless $res->code == 200;
650  
651 # Before Mojolicious 9.54 a body that stops early reaches Perl as an
652 # ordinary end of stream: the status was 200 and Mojo reports no error,
653 # so without this a half transfer is a short file nobody notices.
654 14 my $short = _short_transfer($res, $received);
655 14 ▶ die $short if $short;
Branch: 1 branch
BranchTrueFalseTotal
if $short 0 14 14
656 14 return $received;
657 1 ▶ }, sub {
Subroutine __ANON__: called CC=2 SCAR=7.6
658 1 my $error = shift;
659 # From 9.54 the same body rejects as `Premature connection close`, which
660 # says nothing of how far it got, so the lengths are added to it.
661 1 my $short = _short_transfer($tx->res, $received, $error);
662 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
663 17 });
664 }
665  
666 # The error for a 200 whose body stopped short of the length it declared, or
667 # undef when it did not. $cause is what Mojo rejected it with, when it did.
668 15 ▶sub _short_transfer {
Subroutine _short_transfer: called CC=8 SCAR=23.7
669 15 my ($res, $received, $cause) = @_;
670 15 my $declared = $res->headers->content_length;
671 return undef
672 15 ▶ 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 14 1 15
Condition45%5/11
($res->code || 0) == 200 and defined $declared and length $declared and $declared != $received
!ll&&!rl&&r
0141
($res->code || 0) == 200 and defined $declared and length $declared
!ll&&!rl&&r
0015
($res->code || 0) == 200 and defined $declared
!ll&&!rl&&r
0015
$res->code || 0
l!l
150
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
673 1 my $message = "the transfer ended after $received of $declared bytes";
674 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
675 1 return InternetData::Error->new(kind => 'network', message => $message);
676 }
677  
678 # request_timeout bounds the WHOLE response and Mojo::UserAgent has no
679 # per-transaction form of it, yet a call may bring its own bound and a transfer
680 # must have none (0): 30 seconds is right for a metadata call and wrong for a
681 # gigabyte. So it is set only across the hand-over, where start_p arms the timer
682 # synchronously - and set EXPLICITLY each time, because Mojo runs a loop tick
683 # inside start_p when the loop is idle, and a retry started in that tick would
684 # otherwise inherit this call's bound.
685 #
686 # A rejection is a plain string when the request never got far enough to have a
687 # status, which is exactly the transport failure the retry rule treats as worth
688 # another attempt.
689 1231 ▶sub _start_p {
Subroutine _start_p: called CC=3 SCAR=11.0
690 1231 my ($self, $tx, $timeout) = @_;
691 1231 my $ua = $self->{ua};
692 1231 my $bound = $ua->request_timeout;
693 # A number, for the reason new gives: a per-call '0.0' is otherwise a timer
694 # that fires at once.
695 1231 ▶ $ua->request_timeout(defined $timeout ? 0 + $timeout : $self->{timeout});
Branch: 1 branch
BranchTrueFalseTotal
defined $timeout ? : 76 1155 1231
696 1231 my $promise = eval { $ua->start_p($tx) };
697 1231 my $failed = $@;
698 1231 $ua->request_timeout($bound);
699 1231 ▶ die InternetData::Error->wrap($failed) unless $promise;
Branch: 1 branch
BranchTrueFalseTotal
unless $promise 6 1225 1231
700 52 ▶ return $promise->catch(sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
701 52 die InternetData::Error->new(kind => 'network', message => "$_[0]");
702 1225 });
703 }
704  
705 # Recurses through $self rather than through a self-referential closure, which
706 # in Perl would be a reference cycle the interpreter never collects. $tries
707 # counts the retries already made.
708 1233 ▶sub _retry_p {
Subroutine _retry_p: called CC=2 SCAR=6.9
709 1233 my ($self, $left, $attempt, $may_retry, $tries) = @_;
710 1233 ▶ $tries //= 0;
Condition100%2/2
$tries //= 0
l!l
340893
MC/DC100%1/1
$tries //= 0
$tries
Truth table100%2/2
A
A= $tries
Aresult
11
00
711 911 ▶ return $attempt->()->catch(sub {
Subroutine __ANON__: called CC=5 SCAR=16.1
712 911 my $error = InternetData::Error->wrap(shift);
713 # $may_retry, when given, can veto a retry the error alone would allow.
714 911 ▶ 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() 571 340 911
Condition100%9/9
$left <= 0 or not $error->retryable or $may_retry and not &$may_retry()
l!l&&r!l&&!r
5701340
$left <= 0 or not $error->retryable
l!l&&r!l&&!r
51456341
$may_retry and not &$may_retry()
!ll&&!rl&&r
33911
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
715 # The wait is a TIMER, never a sleep: this promise may share an event
716 # loop with a Mojolicious application, and sleeping here would stall
717 # every other thing on it.
718 return Mojo::Promise->timer(_retry_delay($error->retry_after, $tries))
719 340 ▶ ->then(sub { $self->_retry_p($left - 1, $attempt, $may_retry, $tries + 1) });
Subroutine __ANON__: called CC=1 SCAR=0.0
720 1233 });
721 }
722  
723 # The server's Retry-After when it gave a usable one, otherwise the backoff:
724 # 250 ms, doubling per retry, capped from the seventh. A Retry-After past
725 # LONGEST_WAIT is waited out on the backoff too, still rate_limited, rather than
726 # holding the call for as long as any server asks.
727 353 ▶sub _retry_delay {
Subroutine _retry_delay: called CC=5 SCAR=16.1
728 353 my ($retry_after, $tries) = @_;
729 353 ▶ return $retry_after
Branch: 1 branch
BranchTrueFalseTotal
if defined $retry_after and $retry_after > 0 and $retry_after <= "2147483.647" 3 350 353
Condition100%6/6
defined $retry_after and $retry_after > 0 and $retry_after <= "2147483.647"
!ll&&!rl&&r
34733
defined $retry_after and $retry_after > 0
!ll&&!rl&&r
337106
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
730 if defined $retry_after && $retry_after > 0 && $retry_after <= LONGEST_WAIT;
731 350 ▶ return BACKOFF_BASE * 2**($tries < 6 ? $tries : 6);
Branch: 1 branch
BranchTrueFalseTotal
$tries < 6 ? : 348 2 350
732 }
733  
734 # $body, when given, is POSTed as JSON, and $timeout is the call's own bound, or
735 # undef for the client's. $shape is the whole answer's, and $member, when given,
736 # the one member of it the call returns. An answer without the shape is no answer
737 # at all, so it fails inside the attempt as a retried server_error, like any
738 # other 2xx that cannot be read, rather than reaching the caller as undef.
739 966 ▶sub _json_p {
Subroutine _json_p: called CC=2 SCAR=6.9
740 966 my ($self, $url, $body, $timeout, $member, $shape) = @_;
741 966 ▶ my $sent = defined $body ? $self->_post_p($url, $body, $timeout) : $self->_get_p($url, $timeout);
Branch: 1 branch
BranchTrueFalseTotal
defined $body ? : 65 901 966
742 937 ▶ return $sent->then(sub {
Subroutine __ANON__: called CC=6 SCAR=17.9
743 937 my $res = shift->res;
744 937 ▶ die InternetData::Error->from_response($res->code, $res->headers, $res->json)
Branch: 1 branch
BranchTrueFalseTotal
unless $res->is_success 143 794 937
745 unless $res->is_success;
746 794 my $decoded = $res->json;
747 578 ▶ my $unreadable = sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
748 578 die InternetData::Error->new(kind => 'server_error', status => $res->code, message => shift);
749 794 };
750 794 ▶ $unreadable->('the API did not answer with a JSON object') unless ref $decoded eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $decoded eq "HASH" 46 748 794
751 748 ▶ return $decoded unless $shape;
Branch: 1 branch
BranchTrueFalseTotal
unless $shape 0 748 748
752 748 my $wrong = _nonconforming($shape, $decoded, []);
753 748 ▶ $unreadable->($wrong) if defined $wrong;
Branch: 1 branch
BranchTrueFalseTotal
if defined $wrong 532 216 748
754 216 ▶ return defined $member ? $decoded->{$member} : $decoded;
Branch: 1 branch
BranchTrueFalseTotal
defined $member ? : 64 152 216
755 962 });
756 }
757  
758 # undef when the value has the shape, else what the API answered wrong, naming
759 # the member by its path. A string is told from a number by the scalar Mojo::JSON
760 # decoded it into, as InternetData::Oauth does, since nothing else in Perl tells
761 # `"7"` from `7`. No list entry or map value may be null.
762 1111392 ▶sub _nonconforming {
Subroutine _nonconforming: called CC=35 SCAR=35.6
763 1111392 my ($shape, $value, $at) = @_;
764 1111392 my ($kind, $inner) = @$shape;
765 1111392 ▶ 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 ? : 115 0 115
766 1111392 ▶ return $wrong->() unless defined $value;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $value 12 1111380 1111392
767 1111380 ▶ return undef if $kind eq 'any';
Branch: 1 branch
BranchTrueFalseTotal
if $kind eq "any" 27544 1083836 1111380
768 1083836 ▶ if ($kind eq 'string') {
Branch: 1 branch
BranchTrueFalseTotal
if ($kind eq "string") 527428 556408 1083836
769 527428 ▶ return InternetData::Oauth::_is_string($value) ? undef : $wrong->();
Branch: 1 branch
BranchTrueFalseTotal
InternetData::Oauth::_is_string($value) ? : 527410 18 527428
770 }
771 556408 ▶ if ($kind eq 'date' || $kind eq 'date-time') {
Branch: 1 branch
BranchTrueFalseTotal
if ($kind eq "date" or $kind eq "date-time") 633 555775 556408
Condition100%3/3
$kind eq "date" or $kind eq "date-time"
l!l&&r!l&&!r
61572555775
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
772 633 ▶ return InternetData::Oauth::_is_string($value) && _is_rfc3339($kind, $value) ? undef
Branch: 1 branch
BranchTrueFalseTotal
InternetData::Oauth::_is_string($value) && _is_rfc3339($kind, $value) ? : 291 342 633
Condition100%3/3
InternetData::Oauth::_is_string($value) and _is_rfc3339($kind, $value)
!ll&&!rl&&r
2340291
MC/DC100%2/2
InternetData::Oauth::_is_string($value) and _is_rfc3339($kind, $value)
InternetData::Oauth::_is_string($value) _is_rfc3339($kind, $value)
Truth table100%3/3
A and B
A= InternetData::Oauth::_is_string($value)B= _is_rfc3339($kind, $value)
ABresult
0X0
100
111
773 : 'the API answered ' . join('.', @$at) . ' that is no RFC 3339 ' . $kind;
774 }
775 555775 ▶ if ($kind eq 'integer') {
Branch: 1 branch
BranchTrueFalseTotal
if ($kind eq "integer") 28009 527766 555775
776 28009 ▶ return !ref $value && !InternetData::Oauth::_is_string($value) && $value =~ /\A-?[0-9]+\z/
Branch: 1 branch
BranchTrueFalseTotal
!(ref $value || InternetData::Oauth::_is_string($value)) && $value =~ /\A-?[0-9]+\z/ ? : 27973 36 28009
Condition83%5/6
not ref $value || InternetData::Oauth::_is_string($value) and $value =~ /\A-?[0-9]+\z/
!ll&&!rl&&r
32427973
ref $value || InternetData::Oauth::_is_string($value)
l!l&&r!l&&!r
03227977
MC/DC66%2/3
not ref $value || InternetData::Oauth::_is_string($value) and $value =~ /\A-?[0-9]+\z/
ref $value InternetData::Oauth::_is_string($value) $value =~ /\A-?[0-9]+\z/
Truth table75%3/4
not(A || B) and C
A= ref $valueB= InternetData::Oauth::_is_string($value)C= $value =~ /\A-?[0-9]+\z/
ABCresult
1XX0
01X0
0000
0011
777 ? undef : $wrong->();
778 }
779 527766 ▶ if ($kind eq 'number') {
Branch: 1 branch
BranchTrueFalseTotal
if ($kind eq "number") 12 527754 527766
780 12 ▶ return !ref $value && !InternetData::Oauth::_is_string($value) && Scalar::Util::looks_like_number($value)
Branch: 1 branch
BranchTrueFalseTotal
!(ref $value || InternetData::Oauth::_is_string($value)) && &Scalar::Util::looks_like_number($value) ? : 10 2 12
Condition66%4/6
not ref $value || InternetData::Oauth::_is_string($value) and &Scalar::Util::looks_like_number($value)
!ll&&!rl&&r
2010
ref $value || InternetData::Oauth::_is_string($value)
l!l&&r!l&&!r
0210
MC/DC33%1/3
not ref $value || InternetData::Oauth::_is_string($value) and &Scalar::Util::looks_like_number($value)
ref $value InternetData::Oauth::_is_string($value) &Scalar::Util::looks_like_number($value)
Truth table50%2/4
not(A || B) and C
A= ref $valueB= InternetData::Oauth::_is_string($value)C= &Scalar::Util::looks_like_number($value)
ABCresult
1XX0
01X0
0000
0011
781 ? undef : $wrong->();
782 }
783 527754 ▶ if ($kind eq 'boolean') {
Branch: 1 branch
BranchTrueFalseTotal
if ($kind eq "boolean") 332368 195386 527754
784 332368 ▶ return Scalar::Util::blessed($value) && $value->isa('JSON::PP::Boolean') ? undef : $wrong->();
Branch: 1 branch
BranchTrueFalseTotal
builtin::blessed($value) && $value->isa('JSON::PP::Boolean') ? : 332339 29 332368
Condition66%2/3
builtin::blessed($value) and $value->isa("JSON::PP::Boolean")
!ll&&!rl&&r
290332339
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
785 }
786 195386 ▶ if ($kind eq 'object') {
Branch: 1 branch
BranchTrueFalseTotal
if ($kind eq "object") 2 195384 195386
787 2 ▶ return ref $value eq 'HASH' ? undef : $wrong->();
Branch: 1 branch
BranchTrueFalseTotal
ref $value eq 'HASH' ? : 0 2 2
788 }
789 195384 ▶ if ($kind eq 'list') {
Branch: 1 branch
BranchTrueFalseTotal
if ($kind eq "list") 559 194825 195384
790 559 ▶ return $wrong->() unless ref $value eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $value eq "ARRAY" 6 553 559
791 553 for my $i (0 .. $#$value) {
792 530 my $w = _nonconforming($inner, $value->[$i], [@$at, $i]);
793 530 ▶ return $w if defined $w;
Branch: 1 branch
BranchTrueFalseTotal
if defined $w 334 196 530
794 }
795 219 return undef;
796 }
797 194825 ▶ if ($kind eq 'map_of') {
Branch: 1 branch
BranchTrueFalseTotal
if ($kind eq "map_of") 151 194674 194825
798 151 ▶ return $wrong->() unless ref $value eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $value eq "HASH" 2 149 151
799 149 for my $key (sort keys %$value) {
800 27623 my $w = _nonconforming($inner, $value->{$key}, [@$at, $key]);
801 27623 ▶ return $w if defined $w;
Branch: 1 branch
BranchTrueFalseTotal
if defined $w 12 27611 27623
802 }
803 137 return undef;
804 }
805 194674 ▶ return $wrong->() unless ref $value eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $value eq "HASH" 8 194666 194674
806 194666 for my $field (@$inner) {
807 2602930 my ($name, $member_shape, $required) = @$field;
808 2602930 ▶ if (!defined $value->{$name}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $value->{$name}) 1547983 1054947 2602930
809 1547983 ▶ return 'the API answered with no ' . join('.', @$at, $name) if $required;
Branch: 1 branch
BranchTrueFalseTotal
if $required 80 1547903 1547983
810 1547903 next;
811 }
812 1054947 my $w = _nonconforming($member_shape, $value->{$name}, [@$at, $name]);
813 1054947 ▶ return $w if defined $w;
Branch: 1 branch
BranchTrueFalseTotal
if defined $w 866 1054081 1054947
814 }
815 193720 return undef;
816 }
817  
818 # RFC 3339's `full-date`, or its `date-time` with the `T` and `Z` in either case,
819 # an hour below 24, a minute and second below 60 and an offset of at most 23:59,
820 # on a day its month has. ASCII digits and `\z`, since Perl's `\d` takes any
821 # script's digits and `$` a trailing newline.
822 9 my $FULL_DATE = qr/\A([0-9]{4})-([0-9]{2})-([0-9]{2})\z/;
823 9 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]+)?
824 (?:[Zz]|[+-]([0-9]{2}):([0-9]{2}))\z/x;
825  
826 631 ▶sub _is_rfc3339 {
Subroutine _is_rfc3339: called CC=10 SCAR=23.0
827 631 my ($kind, $value) = @_;
828 631 ▶ if ($kind eq 'date') {
Branch: 1 branch
BranchTrueFalseTotal
if ($kind eq "date") 61 570 631
829 61 ▶ my @date = $value =~ $FULL_DATE or return 0;
Branch: 1 branch
BranchTrueFalseTotal
my(@date) = $value =~ /$FULL_DATE/ or return 0 33 28 61
830 33 return _is_day(@date);
831 }
832 570 ▶ my ($year, $month, $day, $hour, $minute, $second, $off_hour, $off_minute) = $value =~ $DATE_TIME
Branch: 1 branch
BranchTrueFalseTotal
() = $value =~ /$DATE_TIME/ or return 0 340 230 570
833 or return 0;
834 340 ▶ 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
5220268
_is_day($year, $month, $day) and $hour < 24 and $minute < 60 and $second < 60
!ll&&!rl&&r
4210288
_is_day($year, $month, $day) and $hour < 24 and $minute < 60
!ll&&!rl&&r
3210298
_is_day($year, $month, $day) and $hour < 24
!ll&&!rl&&r
1616308
not defined $off_hour or $off_hour < 24 and $off_minute < 60
l!l&&r!l&&!r
262620
$off_hour < 24 and $off_minute < 60
!ll&&!rl&&r
10106
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
835 && (!defined $off_hour || ($off_hour < 24 && $off_minute < 60));
836 }
837  
838 373 ▶sub _is_day {
Subroutine _is_day: called CC=7 SCAR=19.5
839 373 my ($year, $month, $day) = @_;
840 373 ▶ return 0 if $month < 1 || $month > 12 || $day < 1;
Branch: 1 branch
BranchTrueFalseTotal
if $month < 1 or $month > 12 or $day < 1 2 371 373
Condition66%4/6
$month < 1 or $month > 12 or $day < 1
l!l&&r!l&&!r
20371
$month < 1 or $month > 12
l!l&&r!l&&!r
02371
MC/DC33%1/3
$month < 1 or $month > 12 or $day < 1
$month < 1 $month > 12 $day < 1
Truth table50%2/4
A or B or C
A= $month < 1B= $month > 12C= $day < 1
ABCresult
1XX1
01X1
0011
0000
841 371 ▶ 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
33365
$year % 4 == 0 and $year % 100 != 0
!ll&&!rl&&r
36353
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
842 371 ▶ return $day <= (31, $leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)[$month - 1];
Branch: 1 branch
BranchTrueFalseTotal
$leap ? : 6 365 371
843 }
844  
845 953 ▶sub _get_p {
Subroutine _get_p: called CC=1 SCAR=0.0
846 953 my ($self, $url, $timeout) = @_;
847 953 return $self->_start_p($self->{ua}->build_tx(GET => $url => $self->_headers), $timeout);
848 }
849  
850 # The one request with a body: the batch. Mojo encodes the JSON and sets the
851 # content type.
852 65 ▶sub _post_p {
Subroutine _post_p: called CC=1 SCAR=0.0
853 65 my ($self, $url, $body, $timeout) = @_;
854 65 my $tx = $self->{ua}->build_tx(POST => $url => $self->_headers => json => $body);
855 65 return $self->_start_p($tx, $timeout);
856 }
857  
858 1018 ▶sub _headers {
Subroutine _headers: called CC=2 SCAR=6.9
859 1018 my ($self) = @_;
860 1018 my %headers = (Accept => 'application/json');
861 # One scheme. The v1 endpoints on this same host take `?apikey=` with a
862 # different key vocabulary, so sending a v2 key that way would make it look
863 # plausible on the version it does not belong to, and query strings end up in
864 # logs. A blank key is none at all (see new): that is what an unset
865 # `${{ secrets.X }}` interpolates to, and `Bearer ` is a worse answer than no
866 # header.
867 1018 ▶ $headers{Authorization} = "Bearer $self->{api_key}" if defined $self->{api_key};
Branch: 1 branch
BranchTrueFalseTotal
if defined $self->{"api_key"} 824 194 1018
868 1018 return \%headers;
869 }
870  
871 720 ▶sub _url {
Subroutine _url: called CC=2 SCAR=6.9
872 720 my ($self, $path, %query) = @_;
873 720 my $url = Mojo::URL->new($self->{base_url} . $path);
874 720 ▶ $url->query(%query) if %query;
Branch: 1 branch
BranchTrueFalseTotal
if %query 113 607 720
875 720 return $url;
876 }
877  
878 # One path segment as given: its UTF-8 bytes, everything but the unreserved
879 # characters escaped, so a `/`, `?` or `#` in it cannot reach another route.
880 73 ▶sub _path_segment {
Subroutine _path_segment: called CC=1 SCAR=0.0
881 73 my ($value) = @_;
882 73 return Mojo::Util::url_escape(Mojo::Util::encode('UTF-8', $value), '^A-Za-z0-9\-._~');
883 }
884  
885 837 ▶sub _wait {
Subroutine _wait: called CC=2 SCAR=6.9
886 837 my ($self, $promise) = @_;
887 837 my ($value, $error, $failed);
888 837 ▶ $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
889 837 ▶ die $error if $failed;
Branch: 1 branch
BranchTrueFalseTotal
if $failed 577 260 837
890 260 return $value;
891 }
892  
893 # Checked BEFORE the promise is built, not after: Mojo::UserAgent starts a
894 # transaction as soon as one is created, so croaking later would still have spent
895 # a request from the caller's allowance.
896 1016 ▶sub _assert_blocking_ok {
Subroutine _assert_blocking_ok: called CC=2 SCAR=6.9
897 1016 my ($self, $method) = @_;
898 1016 ▶ return unless Mojo::IOLoop->is_running;
Branch: 1 branch
BranchTrueFalseTotal
unless "Mojo::IOLoop"->is_running 1009 7 1016
899 7 Carp::croak(
900 "InternetData::$method cannot block inside a running Mojo::IOLoop; "
901 . "call ${method}_p instead, which returns a Mojo::Promise"
902 );
903 }
904  
905 1102 ▶sub _check_options {
Subroutine _check_options: called CC=9 SCAR=22.0
906 1102 my ($self, $method, $options, @allowed) = @_;
907 1102 my %allowed = map { $_ => 1 } @allowed;
908 1102 my @unknown = sort grep { !$allowed{$_} } keys %$options;
909 1102 ▶ Carp::croak("InternetData::$method: unknown option(s): @unknown") if @unknown;
Branch: 1 branch
BranchTrueFalseTotal
if @unknown 13 1089 1102
910 # A negative or non-numeric bound would fire at once and fail the very call
911 # it was meant to protect.
912 1089 my $timeout = $options->{timeout};
913 1089 ▶ Carp::croak("InternetData::$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 19 1070 1089
Condition100%6/6
defined $timeout and not &Scalar::Util::looks_like_number($timeout) && $timeout >= 0
!ll&&!rl&&r
10125819
&Scalar::Util::looks_like_number($timeout) && $timeout >= 0
!ll&&!rl&&r
91058
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
914 if defined $timeout && !(Scalar::Util::looks_like_number($timeout) && $timeout >= 0);
915 Carp::croak("InternetData::$method: retries must be a whole number, 0 or more")
916 1070 ▶ 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 972 1070
Condition100%3/3
defined $options->{"retries"} and not _is_count($options->{"retries"}, 0)
!ll&&!rl&&r
964898
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
917 Carp::croak("InternetData::$method: concurrency must be a whole number, 1 or more")
918 972 ▶ 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 956 972
Condition100%3/3
defined $options->{"concurrency"} and not _is_count($options->{"concurrency"}, 1)
!ll&&!rl&&r
953316
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
919 }
920  
921 # A whole number from $least, or Inf for no limit. NaN compares false with
922 # anything, so a NaN count retried a failing call for good and a NaN concurrency
923 # put no chunk in flight, spinning the loop forever; a word reads as 0, and 1.5
924 # as two retries.
925 1120 ▶sub _is_count {
Subroutine _is_count: called CC=4 SCAR=13.9
926 1120 my ($n, $least) = @_;
927 1120 ▶ 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
11318989
not ref $n and &Scalar::Util::looks_like_number($n) and $n >= $least
!ll&&!rl&&r
54591007
not ref $n and &Scalar::Util::looks_like_number($n)
!ll&&!rl&&r
18361066
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
928 }
929  
930 476 ▶sub _base_url {
Subroutine _base_url: called CC=3 SCAR=11.0
931 476 my ($url) = @_;
932 476 ▶ $url = DEFAULT_BASE_URL unless defined $url && length $url;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $url and length $url 10 466 476
Condition66%2/3
defined $url and length $url
!ll&&!rl&&r
100466
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
933 476 $url =~ s{/+\z}{};
934 476 return $url;
935 }
936  
937 9 1;
938  
939 __END__
↑ Summary InternetData/Oauth.pm »