InternetData.pm

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