Consumer.pm

filter: Statementstmt 76.6% 216 / 282 Branchbran 61.7% 79 / 128 Conditioncond 53.7% 29 / 54 MC/DCmcdc 36.6% 11 / 30 Subroutinesub 82.3% 42 / 51 Podpod 17.6% 6 / 34 totaltotal 66.1% 383 / 579 CC 85 SCAR 21.9
CC
85
Cov
70%
configure
35.8
load_config_from_file
30.0
get_response
13.1
CRAP 9.0
↑ Summary Consumer/Dispatch.pm »
1 package REST::Consumer;
2 # a generic client for talking to restful web services
3  
4 9 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 9 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7 9 ▶use Carp qw(cluck);
Subroutine BEGIN: called CC=1 SCAR=0.0
8 9 ▶use LWP::UserAgent::Paranoid;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 9 ▶use URI;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 9 ▶use JSON::XS;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 9 ▶use HTTP::Request;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 9 ▶use HTTP::Headers;
Subroutine BEGIN: called CC=1 SCAR=0.0
13 9 ▶use File::Path qw( mkpath );
Subroutine BEGIN: called CC=1 SCAR=0.0
14 9 ▶use REST::Consumer::Dispatch;
Subroutine BEGIN: called CC=1 SCAR=0.0
15 9 ▶use REST::Consumer::RequestException;
Subroutine BEGIN: called CC=1 SCAR=0.0
16 9 ▶use REST::Consumer::PermissiveResolver;
Subroutine BEGIN: called CC=1 SCAR=0.0
17 9 ▶use Time::HiRes qw(usleep);
Subroutine BEGIN: called CC=1 SCAR=0.0
18  
19 9 our $VERSION = '1.02';
20  
21 9 my $global_configuration = {};
22 9 my %service_clients;
23 9 ▶my $data_path = $ENV{DATA_PATH} || $ENV{TMPDIR} || '/tmp';
Condition40%2/5
$ENV{'DATA_PATH'} || $ENV{'TMPDIR'} || '/tmp'
l!l
09
$ENV{"DATA_PATH"} or $ENV{"TMPDIR"}
l!l&&r!l&&!r
009
MC/DC0%0/2
$ENV{'DATA_PATH'} || $ENV{'TMPDIR'} || '/tmp'
$ENV{"DATA_PATH"} $ENV{"TMPDIR"}
Truth table33%1/3
A or B
A= $ENV{"DATA_PATH"}B= $ENV{"TMPDIR"}
ABresult
1X1
011
000
24 9 my $throw_exceptions = 1;
25  
26 # make sure config gets loaded from url every 5 minutes
27 9 my $config_reload_interval = 60 * 5;
28  
29 14 ▶sub throw_exceptions {
Subroutine throw_exceptions: called CC=2 SCAR=6.9
Pod undocumented
30 14 my ($class, $value) = @_;
31 14 ▶ $throw_exceptions = $value if defined $value;
Branch: 1 branch
BranchTrueFalseTotal
if defined $value 1 13 14
32 14 return $throw_exceptions;
33 }
34  
35 3 ▶sub configure {
Subroutine configure: called CC=8 SCAR=35.8
Pod undocumented
36 3 my ($class, $config, @args) = @_;
37 3 ▶ if (!ref $config) {
Branch: 1 branch
BranchTrueFalseTotal
unless (ref $config) 0 3 3
38 0 ▶ if ($config =~ /^https?:/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($config =~ /^https?:/) { } 0 0 0
39 # if the config is a scalar that starts with http:, assume it's a url to fetch configuration from
40 0 my $uri = URI->new($config);
41 0 my ($dir, $filename) = _config_file_path($uri);
42  
43 0 my @stat = stat("$dir/$filename");
44 0 my $age_in_seconds = time - $stat[9];
45  
46 0 $config = load_config_from_file("$dir/$filename", \@stat);
47  
48 # reload config from url if it's older than 10 minutes
49 0 ▶ if (!$config || ($age_in_seconds && $age_in_seconds > $config_reload_interval)) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $config or $age_in_seconds and $age_in_seconds > $config_reload_interval) 0 0 0
Condition0%0/6
not $config or $age_in_seconds and $age_in_seconds > $config_reload_interval
l!l&&r!l&&!r
000
$age_in_seconds and $age_in_seconds > $config_reload_interval
!ll&&!rl&&r
000
MC/DC0%0/3
not $config or $age_in_seconds and $age_in_seconds > $config_reload_interval
not $config $age_in_seconds $age_in_seconds > $config_reload_interval
Truth table0%0/4
not(A) or B and C
A= not $configB= $age_in_secondsC= $age_in_seconds > $config_reload_interval
ABCresult
1XX1
0111
00X0
0100
50 0 my $client = $class->new( host => $uri->host, port => $uri->port );
51 0 $config = $client->get( path => $uri->path );
52  
53 # try to cache config loaded from a url to a file for fault tolerance
54 0 write_config_to_file($uri, $config);
55 }
56 } else {
57 # otherwise it's a filename
58 0 my $path = $config;
59 0 $config = load_config_from_file($path);
60 }
61 }
62  
63 3 ▶ if (ref $config ne 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $config ne "HASH") 0 3 3
64 0 die "Invalid configuration. It should either be a hashref or a url or filename to get config data from";
65 }
66  
67 3 for my $key (keys %$config) {
68 4 $global_configuration->{$key} = _validate_client_config($config->{$key});
69 }
70  
71 3 return 1;
72 }
73  
74 0 ▶sub _config_file_path {
Subroutine _config_file_path: not called CC=1 SCAR=6.9
75 0 my ($uri) = @_;
76 0 my $cache_filename = $uri->host . '-' . $uri->port . $uri->path . '.json';
77 # $cache_filename =~ s/\//-/g;
78 0 my ($dir, $filename) = $cache_filename =~ /(.*)\/([^\/]*)/i;
79 0 return ("$data_path/rest-consumer/config/$dir", $filename);
80 }
81  
82 0 ▶sub load_config_from_file {
Subroutine load_config_from_file: not called CC=5 SCAR=34.0
Pod undocumented
83 0 my ($path, $stat) = @_;
84 0 ▶ my @stat = $stat || stat($path);
Condition0%0/3
$stat || stat $path
l!l&&r!l&&!r
000
MC/DC0%0/2
$stat || stat $path
$stat stat $path
Truth table0%0/3
A || B
A= $statB= stat $path
ABresult
1X1
011
000
85 0 ▶ return if !-e _ || !-r _;
Branch: 1 branch
BranchTrueFalseTotal
unless -e _ and -r _ 0 0 0
Condition0%0/3
-e _ and -r _
!ll&&!rl&&r
000
MC/DC0%0/2
-e _ and -r _
-e _ -r _
Truth table0%0/3
A and B
A= -e _B= -r _
ABresult
0X0
100
111
86  
87 0 undef $/;
88 0 ▶ open my $config_fh, $path or die "Couldn't open config file '$path': $!";
Branch: 1 branch
BranchTrueFalseTotal
open my $config_fh, $path or die "Couldn't open config file '${path}': $!" 0 0 0
89  
90 0 my $data = <$config_fh>;
91 0 my $decoded_data = JSON::XS::decode_json($data);
92 0 close $config_fh;
93 0 return $decoded_data;
94 }
95  
96 0 ▶sub write_config_to_file {
Subroutine write_config_to_file: not called CC=3 SCAR=24.8
Pod undocumented
97 0 my ($url, $config) = @_;
98 0 my ($dir, $filename) = _config_file_path($url);
99  
100 0 eval { mkpath($dir) };
101 0 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 0 0
102 0 warn "Couldn’t create make directory for rest consumer config $dir: $@";
103 0 return;
104 }
105  
106 # if (!-w "$dir/$filename") {
107 # warn "Can't write config data to: $dir/$filename - not caching rest consumer config data";
108 # return;
109 # }
110  
111 0 ▶ open my $cache_file, '>', "$dir/$filename"
Branch: 1 branch
BranchTrueFalseTotal
open my $cache_file, ">", "$dir/$filename" or die "Couldn't open config file for write '$dir/${filename}': $!" 0 0 0
112 or die "Couldn't open config file for write '$dir/$filename': $!";
113  
114 0 print $cache_file JSON::XS::encode_json($config);
115 0 close $cache_file;
116 }
117  
118 24 ▶sub service {
Subroutine service: called CC=3 SCAR=11.0
Pod undocumented
119 24 my ($class, $name) = @_;
120 24 ▶ return $service_clients{$name} if defined $service_clients{$name};
Branch: 1 branch
BranchTrueFalseTotal
if defined $service_clients{$name} 21 3 24
121  
122 die "No service configured with name: $name"
123 3 ▶ if !exists $global_configuration->{$name};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $global_configuration->{$name} 0 3 3
124  
125 3 $service_clients{$name} = $class->new(%{$global_configuration->{$name}});
126 3 return $service_clients{$name};
127 }
128  
129 24 ▶sub _validate_client_config {
Subroutine _validate_client_config: called CC=12 SCAR=25.5
130 24 my ($config) = @_;
131 my $valid = {
132 host => $config->{host},
133 url => $config->{url},
134 port => $config->{port},
135 (defined $config->{ua} ? (ua => $config->{ua}) : ()),
136  
137 # timeout on requests to the service
138 timeout => $config->{timeout} || 10,
139  
140 # retry this many times if we don't get a 200 response from the service
141 retry => exists $config->{retry} ? $config->{retry} : exists $config->{retries} ? $config->{retries} : 0,
142  
143 # delay by this many ms before every retry
144 retry_delay => $config->{retry_delay} || 0,
145  
146 # print some extra debugging messages
147 verbose => $config->{verbose} || 0,
148  
149 # enable persistent connection
150 keep_alive => $config->{keep_alive} || 1,
151  
152 agent => $config->{user_agent} || "REST-Consumer/$VERSION",
153  
154 auth => $config->{auth} || {},
155 24 ▶ };
Branch: 3 branches
BranchTrueFalseTotal
defined $config->{'ua'} ? : 1 23 24
exists $config->{'retry'} ? : 4 20 24
exists $config->{'retries'} ? : 4 16 20
Condition91%11/12
$config->{'timeout'} || 10
l!l
618
$config->{'retry_delay'} || 0
l!l
123
$config->{'verbose'} || 0
l!l
024
$config->{'keep_alive'} || 1
l!l
519
$config->{'user_agent'} || "REST-Consumer/$REST::Consumer::VERSION"
l!l
123
$config->{'auth'} || {}
l!l
420
MC/DC100%1/1
$config->{'timeout'} || 10
$config->{'timeout'}
MC/DC100%1/1
$config->{'retry_delay'} || 0
$config->{'retry_delay'}
MC/DC0%0/1
$config->{'verbose'} || 0
$config->{'verbose'}
MC/DC100%1/1
$config->{'keep_alive'} || 1
$config->{'keep_alive'}
MC/DC100%1/1
$config->{'user_agent'} || "REST-Consumer/$REST::Consumer::VERSION"
$config->{'user_agent'}
MC/DC100%1/1
$config->{'auth'} || {}
$config->{'auth'}
Truth table100%2/2
A
A= $config->{'timeout'}
Aresult
11
00
Truth table100%2/2
A
A= $config->{'retry_delay'}
Aresult
11
00
Truth table50%1/2
A
A= $config->{'verbose'}
Aresult
11
00
Truth table100%2/2
A
A= $config->{'keep_alive'}
Aresult
11
00
Truth table100%2/2
A
A= $config->{'user_agent'}
Aresult
11
00
Truth table100%2/2
A
A= $config->{'auth'}
Aresult
11
00
156  
157 24 ▶ if (!$valid->{host} and !$valid->{url}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($valid->{"host"} or $valid->{"url"}) 0 24 24
Condition33%1/3
$valid->{"host"} or $valid->{"url"}
l!l&&r!l&&!r
2400
MC/DC0%0/2
$valid->{"host"} or $valid->{"url"}
$valid->{"host"} $valid->{"url"}
Truth table33%1/3
A or B
A= $valid->{"host"}B= $valid->{"url"}
ABresult
1X1
011
000
158 0 die "Either host or url is required";
159 }
160  
161 24 return $valid;
162 }
163  
164 20 ▶sub new {
Subroutine new: called CC=3 SCAR=11.8
Pod undocumented
165 20 my ($class, @args) = @_;
166 20 my $args = {};
167 20 ▶ if (scalar @args == 1 && !ref $args[0]) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @args == 1 and not ref $args[0]) { } 0 20 20
Condition33%1/3
scalar @args == 1 and not ref $args[0]
!ll&&!rl&&r
2000
MC/DC0%0/2
scalar @args == 1 and not ref $args[0]
scalar @args == 1 not ref $args[0]
Truth table33%1/3
A and not(B)
A= scalar @args == 1B= not ref $args[0]
ABresult
0X0
100
111
168 0 $args->{url} = $args[0];
169 } else {
170 20 $args = { @args };
171 }
172 20 my $self = _validate_client_config($args);
173 20 bless $self, $class;
174 20 return $self;
175 }
176  
177 1 ▶sub host {
Subroutine host: called CC=2 SCAR=7.1
Pod undocumented
178 1 my ($self, $host) = @_;
179 1 ▶ $self->{host} = $host if defined $host;
Branch: 1 branch
BranchTrueFalseTotal
if defined $host 0 1 1
180 1 return $self->{host};
181 }
182  
183 0 ▶sub port {
Subroutine port: not called CC=2 SCAR=17.9
Pod undocumented
184 0 my ($self, $port) = @_;
185 0 ▶ $self->{port} = $port if defined $port;
Branch: 1 branch
BranchTrueFalseTotal
if defined $port 0 0 0
186 0 return $self->{port};
187 }
188  
189 16 ▶sub timeout {
Subroutine timeout: called CC=3 SCAR=15.1
Pod undocumented
190 16 my ($self, $timeout) = @_;
191 16 ▶ if (defined $timeout) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $timeout) 0 16 16
192 0 $self->{timeout} = $timeout;
193 0 ▶ $self->apply_timeout($self->{_user_agent}) if $self->{_user_agent};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_user_agent"} 0 0 0
194 }
195 16 return $self->{timeout};
196 }
197  
198 0 ▶sub retry {
Subroutine retry: not called CC=2 SCAR=17.9
Pod undocumented
199 0 my ($self, $retry) = @_;
200 0 ▶ $self->{retry} = $retry if defined $retry;
Branch: 1 branch
BranchTrueFalseTotal
if defined $retry 0 0 0
201 0 return $self->{retry};
202 }
203  
204 52 ▶sub retry_delay {
Subroutine retry_delay: called CC=2 SCAR=7.1
Pod undocumented
205 52 my ($self, $retry_delay) = @_;
206 52 ▶ $self->{retry_delay} = $retry_delay if defined $retry_delay;
Branch: 1 branch
BranchTrueFalseTotal
if defined $retry_delay 0 52 52
207 52 return $self->{retry_delay};
208 }
209  
210 31 ▶sub keep_alive {
Subroutine keep_alive: called CC=3 SCAR=15.1
Pod undocumented
211 31 my ($self, $keep_alive) = @_;
212 31 ▶ if (defined $keep_alive) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $keep_alive) 0 31 31
213 0 $self->{keep_alive} = $keep_alive;
214 0 ▶ $self->apply_keep_alive($self->{_user_agent}) if $self->{_user_agent};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_user_agent"} 0 0 0
215 }
216 31 return $self->{keep_alive};
217 }
218  
219 16 ▶sub agent {
Subroutine agent: called CC=3 SCAR=15.1
Pod undocumented
220 16 my ($self, $agent) = @_;
221 16 ▶ if (defined $agent) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $agent) 0 16 16
222 0 $self->{agent} = $agent;
223 0 ▶ $self->apply_agent($self->{_user_agent}) if $self->{_user_agent};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_user_agent"} 0 0 0
224 }
225 16 return $self->{agent};
226 }
227  
228 4 ▶sub last_request {
Subroutine last_request: called CC=1 SCAR=0.0
Pod undocumented
229 4 my ($self) = @_;
230 4 return $self->{_last_request};
231 }
232  
233 7 ▶sub last_response {
Subroutine last_response: called CC=1 SCAR=0.0
Pod undocumented
234 7 my ($self) = @_;
235 7 return $self->{_last_response};
236 }
237  
238 3 ▶sub get_user_agent { user_agent(@_) }
Subroutine get_user_agent: called CC=1 SCAR=0.0
Pod undocumented
239  
240 16 ▶sub apply_timeout {
Subroutine apply_timeout: called CC=2 SCAR=7.6
Pod undocumented
241 16 my ($self, $ua) = @_;
242 16 ▶ if ($ua->can('request_timeout')) {
Branch: 1 branch
BranchTrueFalseTotal
if ($ua->can('request_timeout')) { } 16 0 16
243 # $ua is a LWP::UserAgent::Paranoid or some other thing that honors request_timeout
244 16 $ua->request_timeout($self->timeout);
245 } else {
246 # $ua is vanilla LWP or a subclass, use the inferior timeout method
247 0 $ua->timeout($self->timeout);
248 }
249 }
250  
251 16 ▶sub apply_agent {
Subroutine apply_agent: called CC=1 SCAR=0.0
Pod undocumented
252 16 my ($self, $ua) = @_;
253 16 $ua->agent($self->agent);
254 }
255  
256 16 ▶sub apply_keep_alive {
Subroutine apply_keep_alive: called CC=4 SCAR=15.5
Pod undocumented
257 16 my ($self, $ua) = @_;
258 16 ▶ if ($ua->can('keep_alive')) {
Branch: 2 branches
BranchTrueFalseTotal
if ($ua->can('keep_alive')) { } 1 15 16
elsif ($ua->can('conn_cache')) { } 15 0 15
259 # $ua is some well-behaved user-provided object
260 1 $ua->keep_alive($self->keep_alive);
261 } elsif ($ua->can('conn_cache')) {
262 # $ua is an LWP::UserAgent - unfortunately there's no ->keep_alive method exposed by LWP::UserAgent,
263 # so we just do what its constructor does to set up keep-alive.
264 15 ▶ if ($self->keep_alive) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->keep_alive) { } 15 0 15
265 15 $ua->conn_cache({total_capacity => $self->keep_alive});
266 } else {
267 0 $ua->conn_cache(undef);
268 }
269 } else {
270 # no clue how to handle things; sorry charlie.
271 0 cluck "Don't know how to make a user-specified user agent object of type ${\ref($ua)} honor your keep_alive request.\n";
272 }
273 }
274  
275  
276 84 ▶sub user_agent {
Subroutine user_agent: called CC=6 SCAR=17.9
Pod undocumented
277 84 my $self = shift;
278 84 ▶ return $self->{_user_agent} if defined $self->{_user_agent};
Branch: 1 branch
BranchTrueFalseTotal
if defined $self->{"_user_agent"} 68 16 84
279  
280 16 my $user_agent = delete $self->{ua};
281 16 ▶ unless ($user_agent) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($user_agent) 15 1 16
282 # Paranoid's default resolver blocks access to private IP addresses.
283 # We don't want to do any such thing by default, so provide a more permissive one.
284 15 $user_agent = LWP::UserAgent::Paranoid->new(
285 resolver => REST::Consumer::PermissiveResolver->new
286 );
287 }
288  
289 # bubble our ->timeout, ->agent, and ->keep_alive args into this $user_agent object.
290 # if keep alive is enabled, we create a connection that persists globally
291 16 $self->apply_timeout($user_agent);
292 16 $self->apply_agent($user_agent);
293 16 $self->apply_keep_alive($user_agent);
294  
295 # handle auth headers
296 16 my $default_headers = $user_agent->default_headers;
297 16 $default_headers->header( 'accept' => 'application/json' );
298  
299 16 ▶ if (exists $self->{auth} && $self->{auth}{type} && $self->{auth}{type} eq 'basic') {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $self->{"auth"} and $self->{"auth"}{"type"} and $self->{"auth"}{"type"} eq "basic") 1 15 16
Condition66%4/6
exists $self->{"auth"} and $self->{"auth"}{"type"} and $self->{"auth"}{"type"} eq "basic"
!ll&&!rl&&r
1501
exists $self->{"auth"} and $self->{"auth"}{"type"}
!ll&&!rl&&r
0151
MC/DC33%1/3
exists $self->{"auth"} and $self->{"auth"}{"type"} and $self->{"auth"}{"type"} eq "basic"
exists $self->{"auth"} $self->{"auth"}{"type"} $self->{"auth"}{"type"} eq "basic"
Truth table50%2/4
A and B and C
A= exists $self->{"auth"}B= $self->{"auth"}{"type"}C= $self->{"auth"}{"type"} eq "basic"
ABCresult
0XX0
10X0
1100
1111
300 1 $default_headers->authorization_basic($self->{auth}{username}, $self->{auth}{password});
301 }
302  
303 16 $self->{_user_agent} = $user_agent;
304 16 return $user_agent;
305 }
306  
307  
308 # create the base url for the request composed of the host and port
309 # add http if it hasn't already been prepended
310 31 ▶sub get_service_base_url {
Subroutine get_service_base_url: called CC=4 SCAR=13.9
Pod undocumented
311 31 my $self = shift;
312 31 ▶ return $self->{url} if $self->{url};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"url"} 0 31 31
313  
314 31 my $host = $self->{host};
315 31 my $port = $self->{port};
316 31 $host =~ s|/$||;
317  
318 31 ▶ return ( ($host =~ m|^https?://| ? '' : 'http://' ) . $host . ($port ? ":$port" : '') );
Branch: 2 branches
BranchTrueFalseTotal
$host =~ m[^https?://] ? : 2 29 31
$port ? : 12 19 31
319 }
320  
321 # return a URI object containing the url and any query parameters
322 # path: the url
323 # params: an array ref or hash ref containing key/value pairs to add to the URI
324 28 ▶sub get_uri {
Subroutine get_uri: called CC=5 SCAR=16.1
Pod undocumented
325 28 my $self = shift;
326 28 my %args = @_;
327 28 my $path = $args{path};
328 28 my $params = $args{params};
329 28 $path =~ s|^/||;
330  
331 # replace any sinatra-like url tokens with their param value
332 28 ▶ if (ref $params eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $params eq "HASH") 4 24 28
333 4 ▶ $path =~ s/\:(\w+)/exists $params->{$1} ? URI::Escape::uri_escape(delete $params->{$1}) : $1/eg;
Branch: 1 branch
BranchTrueFalseTotal
exists $params->{$1} ? : 4 0 4
334 }
335  
336 28 my $uri = URI->new( $self->get_service_base_url() . "/$path" );
337 # accept key / values in hash or array format
338 28 ▶ my @params = ref($params) eq 'HASH' ? %$params : ref($params) eq 'ARRAY' ? @$params : ();
Branch: 2 branches
BranchTrueFalseTotal
ref $params eq 'HASH' ? : 4 24 28
ref $params eq 'ARRAY' ? : 1 23 24
339 28 $uri->query_form( @params );
340 28 return $uri;
341 }
342  
343 # get an http request object for the given input
344 27 ▶sub get_http_request {
Subroutine get_http_request: called CC=7 SCAR=20.0
Pod documented
345 27 my $self = shift;
346 27 my %args = @_;
347 27 ▶ my $path = $args{path} or die 'path is a required argument. e.g. "/" ';
Branch: 1 branch
BranchTrueFalseTotal
my $path = $args{"path"} or die "path is a required argument. e.g. \"/\" " 27 0 27
348 27 my $content = $args{content};
349 27 my $headers = $args{headers};
350 27 my $params = $args{params};
351 27 ▶ my $method = $args{method} or die 'method is a required argument';
Branch: 1 branch
BranchTrueFalseTotal
my $method = $args{"method"} or die "method is a required argument" 27 0 27
352 27 my $content_type = $args{content_type};
353  
354 # build the uri from path and params
355 27 my $uri = $self->get_uri(path => $path, params => $params);
356  
357 27 $self->debug( sprintf('Creating request: %s %s', $method, $uri->as_string() ));
358  
359 # add headers if present
360 27 ▶ my $full_headers = $self->user_agent->default_headers || HTTP::Headers->new;
Condition33%1/3
$self->user_agent->default_headers || 'HTTP::Headers'->new
l!l&&r!l&&!r
2700
MC/DC0%0/2
$self->user_agent->default_headers || 'HTTP::Headers'->new
$self->user_agent->default_headers 'HTTP::Headers'->new
Truth table33%1/3
A || B
A= $self->user_agent->default_headersB= 'HTTP::Headers'->new
ABresult
1X1
011
000
361 27 ▶ if ($headers) {
Branch: 1 branch
BranchTrueFalseTotal
if ($headers) 1 26 27
362 1 ▶ my @header_params = ref($headers) eq 'HASH' ? %$headers : ref($headers) eq 'ARRAY' ? @$headers : ();
Branch: 2 branches
BranchTrueFalseTotal
ref $headers eq 'HASH' ? : 0 1 1
ref $headers eq 'ARRAY' ? : 1 0 1
363 1 $full_headers->header(@header_params);
364 }
365  
366 # assemble request
367 27 my $req = HTTP::Request->new($method => $uri, $full_headers);
368  
369 27 $self->add_content_to_request(
370 request => $req,
371 content_type => $content_type,
372 content => $content,
373 );
374  
375  
376 27 return $req;
377 }
378  
379  
380 # add content to the request
381 # by default, serialize to json
382 # otherwise use content type to determine any action if needed
383 # content type defaults to application/json
384 27 ▶sub add_content_to_request {
Subroutine add_content_to_request: called CC=11 SCAR=24.5
Pod undocumented
385 27 my $self = shift;
386 27 my %args = @_;
387 27 ▶ my $request = $args{request} or die 'request is required';
Branch: 1 branch
BranchTrueFalseTotal
my $request = $args{"request"} or die "request is required" 27 0 27
388 27 ▶ my $content_type = $args{content_type} || 'application/x-www-form-urlencoded';
Condition100%2/2
$args{'content_type'} || 'application/x-www-form-urlencoded'
l!l
324
MC/DC100%1/1
$args{'content_type'} || 'application/x-www-form-urlencoded'
$args{'content_type'}
Truth table100%2/2
A
A= $args{'content_type'}
Aresult
11
00
389 27 my $content = $args{content};
390  
391 27 ▶ return unless defined($content) && length($content);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $content and length $content 12 15 27
Condition66%2/3
defined $content and length $content
!ll&&!rl&&r
12015
MC/DC50%1/2
defined $content and length $content
defined $content length $content
Truth table66%2/3
A and B
A= defined $contentB= length $content
ABresult
0X0
100
111
392  
393 15 $request->content_type($content_type);
394 15 ▶ if ($content_type eq 'application/x-www-form-urlencoded') {
Branch: 3 branches
BranchTrueFalseTotal
if ($content_type eq 'application/x-www-form-urlencoded') { } 12 3 15
elsif ($content_type eq 'application/json') { } 1 2 3
elsif ($content_type eq 'multipart/form-data') { } 2 0 2
395 # We use a temporary URI object to format
396 # the application/x-www-form-urlencoded content.
397 12 my $url = URI->new('http:');
398 12 ▶ if (ref $content eq 'HASH') {
Branch: 2 branches
BranchTrueFalseTotal
if (ref $content eq 'HASH') { } 6 6 12
elsif (ref $content eq 'ARRAY') { } 0 6 6
399 6 $url->query_form(%$content);
400 } elsif (ref $content eq 'ARRAY') {
401 0 $url->query_form(@$content);
402 } else {
403 6 $url->query($content);
404 }
405 12 $content = $url->query;
406  
407 # HTML/4.01 says that line breaks are represented as "CR LF" pairs (i.e., `%0D%0A')
408 12 $content =~ s/(?<!%0D)%0A/%0D%0A/g;
409 12 $request->content($content);
410 } elsif ($content_type eq 'application/json') {
411 1 ▶ my $json = ref($content) ? JSON::XS::encode_json($content) : $content;
Branch: 1 branch
BranchTrueFalseTotal
ref $content ? : 1 0 1
412 1 $request->content($json);
413 } elsif ($content_type eq 'multipart/form-data') {
414 2 $request->content($content);
415 } else {
416 # if content type is something else, just include the raw data here
417 # modify this code if we need to process other content types differently
418 0 $request->content($content);
419 }
420 }
421  
422 # send a request to the given path with the given method, params, and content body
423 # and get back a response object
424 #
425 # path: the location of the resource on the given hostname. e.g. '/path/to/resource'
426 # content: optional content body to send in a post. e.g. a json document
427 # params: an arrayref or hashref of key/value pairs to include in the request
428 # headers: a list of key value pairs to add to the header
429 # method: get,post,delete,put,head
430 #
431 # depending on the value of $self->retry this function will retry a request if it receives an error.
432 # In the future we may want to consider managing this based on the specific error code received.
433 26 ▶sub get_response {
Subroutine get_response: called CC=13 SCAR=25.7
Pod documented
434 26 my $self = shift;
435 26 my %args = @_;
436 26 ▶ my $path = $args{path} or die 'path is a required argument. e.g. "/" ';
Branch: 1 branch
BranchTrueFalseTotal
my $path = $args{"path"} or die "path is a required argument. e.g. \"/\" " 26 0 26
437 26 ▶ my $content = $args{content} || $args{body};
Condition100%3/3
$args{'content'} || $args{'body'}
l!l&&r!l&&!r
31112
MC/DC100%2/2
$args{'content'} || $args{'body'}
$args{'content'} $args{'body'}
Truth table100%3/3
A || B
A= $args{'content'}B= $args{'body'}
ABresult
1X1
011
000
438 26 my $headers = $args{headers};
439 26 my $params = $args{params};
440 26 ▶ my $method = $args{method} or die 'method is a required argument';
Branch: 1 branch
BranchTrueFalseTotal
my $method = $args{"method"} or die "method is a required argument" 26 0 26
441 26 my $content_type = $args{content_type};
442 26 ▶ my $retry_count = defined $args{retry} ? $args{retry} : $self->{retry};
Branch: 1 branch
BranchTrueFalseTotal
defined $args{'retry'} ? : 6 20 26
443 26 ▶ my $process_response = $args{process_response} || 0;
Condition100%2/2
$args{'process_response'} || 0
l!l
251
MC/DC100%1/1
$args{'process_response'} || 0
$args{'process_response'}
Truth table100%2/2
A
A= $args{'process_response'}
Aresult
11
00
444
445 26 my $req = $self->get_http_request(
446 path => $path,
447 content => $content,
448 headers => $headers,
449 params => $params,
450 method => $method,
451 content_type => $content_type,
452 );
453  
454 26 my ($result, $flow_control);
455 # run the request
456 26 my $try = 0;
457 26 ▶ while ($try <= $retry_count) {
Branch: 1 branch
BranchTrueFalseTotal
if ($try <= $retry_count) 53 12 65
458 53 $try++;
459 53 my $response = $self->get_response_for_request(http_request => $req);
460  
461 # Okay, now do processing like retries, handlers, and whatnot.
462 my $dispatch = REST::Consumer::Dispatch->new(
463 handlers => $args{handlers},
464 52 ▶ default_is_raw => ($process_response ? 0 : 1),
Branch: 1 branch
BranchTrueFalseTotal
$process_response ? : 51 1 52
465 debugger => $self->debugger,
466 );
467  
468 52 ($flow_control, $result) = $dispatch->handle_response(
469 request => $req,
470 response => $response,
471 attempt => $try,
472 );
473
474 51 ▶ last unless $flow_control eq 'retry';
Branch: 1 branch
BranchTrueFalseTotal
unless $flow_control eq "retry" 12 39 51
475 39 ▶ if ($self->retry_delay) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->retry_delay) 6 33 39
476 6 $self->debug(sprintf ("Sleeping %d ms before retrying...", $self->retry_delay));
477 6 usleep (1000 * $self->retry_delay);
478 }
479 }
480  
481 24 ▶ if ($flow_control eq 'succeed') {
Branch: 1 branch
BranchTrueFalseTotal
if ($flow_control eq 'succeed') { } 12 12 24
482 # $result is an arrayref of the value(s) returned
483 # by a handler (possibly the default handler).
484 12 ▶ if (scalar @$result == 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @$result == 1) { } 12 0 12
485 12 return $result->[0];
486 } else {
487 0 return @$result;
488 }
489 } else {
490 # $flow_control could be 'succeed' or 'retry'
491 # (but we ran out of retries)
492 # $result = a failure object
493 12 ▶ if ($self->throw_exceptions) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->throw_exceptions) { } 11 1 12
494 11 $result->throw;
495 } else {
496 1 return $result;
497 }
498 }
499 }
500  
501 # do everything that get_response does, but return the deserialized content in the response instead of the response object
502 25 ▶sub get_processed_response {
Subroutine get_processed_response: called CC=1 SCAR=0.0
Pod documented
503 25 my $self = shift;
504 25 my $response = $self->get_response(
505 process_response => 1,
506 @_,
507 );
508 12 return $response;
509 }
510  
511  
512 #
513 # http_request => an HTTP Request object
514 # _retries => how many times we've already tried to get a valid response for this request
515 53 ▶sub get_response_for_request {
Subroutine get_response_for_request: called CC=1 SCAR=0.0
Pod undocumented
516 53 my ($self, %args) = @_;
517 53 my $http_request = $args{http_request};
518 53 $self->{_last_request} = $http_request;
519 53 $self->{_last_response} = undef;
520  
521 53 my $user_agent = $self->user_agent;
522 53 my $response = $user_agent->request($http_request);
523  
524 52 $self->{_last_response} = $response;
525 52 $self->debug( sprintf('Got response: %s', $response->code()));
526  
527 52 return $response;
528 }
529  
530 0 ▶sub head {
Subroutine head: not called CC=1 SCAR=6.9
Pod undocumented
531 0 my $self = shift;
532 0 return $self->get_response(@_, method => 'HEAD');
533 }
534  
535 5 ▶sub get {
Subroutine get: called CC=1 SCAR=0.0
Pod documented
536 5 my $self = shift;
537 5 return $self->get_processed_response(@_, method => 'GET');
538 }
539  
540 20 ▶sub post {
Subroutine post: called CC=1 SCAR=0.0
Pod documented
541 20 my $self = shift;
542 20 return $self->get_processed_response(@_, method => 'POST');
543 }
544  
545 0 ▶sub delete {
Subroutine delete: not called CC=1 SCAR=6.9
Pod documented
546 0 my $self = shift;
547 0 return $self->get_processed_response(@_, method => 'DELETE');
548 }
549  
550 0 ▶sub put {
Subroutine put: not called CC=1 SCAR=6.9
Pod undocumented
551 0 my $self = shift;
552 0 return $self->get_processed_response(@_, method => 'PUT');
553 }
554  
555  
556 137 ▶sub debugger {
Subroutine debugger: called CC=2 SCAR=10.1
Pod undocumented
557 137 my $self = shift;
558 137 ▶ return sub {} unless $self->{verbose};
Subroutine __ANON__: called CC=1 SCAR=0.4
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"verbose"} 137 0 137
559 0 ▶ return sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
560 0 local $\ = "\n";
561 0 print STDERR @_;
562 }
563 0 }
564  
565 # print status messages to stderr if running in verbose mode
566 85 ▶sub debug {
Subroutine debug: called CC=1 SCAR=0.0
Pod undocumented
567 85 shift->debugger->(@_);
568 }
569  
570  
571 9 1;
572 __END__
↑ Summary Consumer/Dispatch.pm »