Parallel.pm

filter: Statementstmt 90.4% 19 / 21 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 7 / 7 Podpod n/a totaltotal 92.8% 26 / 28 CC 1 SCAR 0.4
CC
1
Cov
90%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.0
« Parallel/Types.pm ↑ Summary
1 package Net::Curl::Parallel;
2  
3 7 ▶use strictures 2;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 7 ▶use Moo;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 7 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 7 ▶use Guard qw(scope_guard);
Subroutine BEGIN: called CC=1 SCAR=0.0
7 7 ▶use HTTP::Response;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 7 ▶use HTTP::Parser::XS qw(parse_http_response HEADERS_AS_ARRAYREF);
Subroutine BEGIN: called CC=1 SCAR=0.0
9 0 ▶use Net::Curl::Easy qw(:constants);
Subroutine BEGIN: called CC=1 SCAR=2.6
10 use Net::Curl::Multi qw(:constants);
11 use Net::Curl::Parallel::Types -types;
12 use Net::Curl::Parallel::Response;
13  
14 my @AVAIL_CURL_POOL;
15 {
16 my $MAX_CURLS_IN_POOL = 50;
17 sub max_curls_in_pool {
18 shift;
19 $MAX_CURLS_IN_POOL = $_[0] if @_;
20 return $MAX_CURLS_IN_POOL;
21 }
22 }
23  
24 has agent => (is => 'ro', default => 'Net::Curl::Parallel/v2.0');
25 has slots => (is => 'ro', default => 10);
26 has connect_timeout => (is => 'ro', default => 50);
27 has request_timeout => (is => 'ro', default => 500);
28 has max_redirects => (is => 'ro', default => 0);
29 has verify_ssl_peer => (is => 'ro', default => 1);
30 has keep_alive => (is => 'ro', default => 1);
31 has verbose => (is => 'rw', default => 0);
32 has requests => (is => 'ro', default => sub{ [] });
33 has responses => (is => 'ro', default => sub{ [] });
34  
35 has curl_multi => (is => 'ro', default => sub{ Net::Curl::Multi->new });
36 has avail_curl_pool => (is => 'ro', default => sub{ \@AVAIL_CURL_POOL });
37  
38 sub add { shift->_queue(1, @_) }
39 sub try { shift->_queue(0, @_) } ## no critic (TryTiny)
40  
41 sub _queue {
42 my $self = shift;
43 my $die = shift;
44 my @args = ref $_[0] ? @_ : [@_];
45 my @rv = map { $self->request($_, $die) } @args;
46  
47 return $rv[0] if @rv == 1;
48 return @rv if wantarray;
49 return [@rv];
50 }
51  
52 sub request {
53 my ($self, $request, $die) = @_;
54 my ($method, $uri, $headers, $content) = @{Request->assert_coerce($request)};
55 my $idx = scalar @{$self->requests};
56  
57 # HTTP Keep-alive
58 push @$headers, "Connection: keep-alive"
59 if $self->keep_alive
60 && !grep{ $_ =~ /^Connection:/i } @$headers;
61  
62 if ($method eq 'POST') {
63 # libcurl adds an 'Expect: 100-continue' header to all POST requests with a
64 # body greater than 1024 bytes. This is not needed for our internal APIs,
65 # so we are turning it off by default. It can be turned back on by
66 # explicitly including the header in the request, and the client code will
67 # need to handle the 100 response
68 push @$headers, "Expect:"
69 unless grep{ $_ =~ /^Expect:/i } @$headers;
70 }
71  
72 push @{$self->requests}, [$method, $uri, $headers, $content, $die];
73 return $idx;
74 }
75  
76 sub setup_curl {
77 my ($self, $idx) = @_;
78 my ($method, $uri, $headers, $content, $die) = @{$self->requests->[$idx]};
79 # Both sides of the // can never be false because Net::Curl::Easy->new
80 # will always return true.
81 # uncoverable condition false
82 my $curl = shift(@{$self->avail_curl_pool}) // Net::Curl::Easy->new({});
83  
84 # This is okay because the first parameter to Net::Curl::Easy->new() is the
85 # base object. We can put whatever we want into here.
86 $curl->{private} = {
87 response => Net::Curl::Parallel::Response->new,
88 idx => $idx,
89 uri => $uri,
90 die => $die,
91 };
92  
93 # Basic config and tcp setup
94 $curl->setopt(CURLOPT_NOPROGRESS, 1);
95 $curl->setopt(CURLOPT_TCP_NODELAY, 1);
96  
97 # Set connection timeout
98 $curl->setopt(CURLOPT_CONNECTTIMEOUT_MS, $self->connect_timeout)
99 if $self->connect_timeout;
100  
101 # Keep idle TCP connections alive longer. Note - this option is available
102 # starting in libcurl 7.25.0
103 # uncoverable branch false
104 $curl->setopt(CURLOPT_TCP_KEEPALIVE, 1)
105 if &CURLOPT_TCP_KEEPALIVE;
106  
107 # Set verbosity
108 $curl->setopt(CURLOPT_VERBOSE, 1)
109 if $self->verbose;
110  
111 # HTTP
112 $curl->setopt(CURLOPT_ACCEPT_ENCODING, '');
113 $curl->setopt(CURLOPT_PROTOCOLS, CURLPROTO_HTTP | CURLPROTO_HTTPS);
114 $curl->setopt(CURLOPT_USERAGENT, $self->agent);
115 $curl->setopt(CURLOPT_URL, $uri);
116  
117 if ($method eq 'POST') {
118 $curl->setopt(CURLOPT_POST, 1);
119 $curl->setopt(CURLOPT_POSTFIELDS, $content);
120 }
121  
122 # Configure headers
123 $curl->setopt(CURLOPT_HTTPHEADER, $headers)
124 if @$headers;
125  
126 $curl->setopt(CURLOPT_WRITEDATA, $curl->{private}{response}->fh_body);
127 $curl->setopt(CURLOPT_WRITEHEADER, $curl->{private}{response}->fh_head);
128  
129 # Configure redirect behavior
130 $curl->setopt(CURLOPT_FOLLOWLOCATION, $self->max_redirects > 0);
131 $curl->setopt(CURLOPT_MAXREDIRS, $self->max_redirects);
132 $curl->setopt(CURLOPT_AUTOREFERER, 1);
133  
134 # Allow user override of ssl certificate verification
135 $curl->setopt(CURLOPT_SSL_VERIFYPEER, $self->verify_ssl_peer);
136  
137 # Set request timeout
138 $curl->setopt(CURLOPT_TIMEOUT_MS, $self->request_timeout)
139 if $self->request_timeout;
140  
141 # Clean up memory a little, but leave an undef at the index in the requests
142 # array since we are using the index as the key.
143 $self->requests->[$idx] = undef;
144  
145 return $curl;
146 }
147  
148 sub perform {
149 my $self = shift;
150 my $total = @{$self->requests};
151 my $pending = 0;
152 my $idx = 0;
153  
154 $self->{responses} = []; # clear responses state from any prior runs
155 scope_guard{ $self->{requests} = [] }; # clear state for next run
156  
157 until ($idx == $total && $pending == 0) {
158 # Fill empty slots
159 while ($idx < $total && $pending < $self->slots) {
160 $self->curl_multi->add_handle($self->setup_curl($idx));
161 ++$pending;
162 ++$idx;
163 }
164  
165 $self->curl_multi->wait(1);
166 my $running = $self->curl_multi->perform;
167  
168 # At least one request is complete
169 if ($running != $pending) {
170 my ($msg, $curl, $result) = $self->curl_multi->info_read;
171  
172 # A request is complete
173 if ($msg) {
174 scope_guard{
175 --$pending;
176  
177 $self->curl_multi->remove_handle($curl);
178  
179 delete $curl->{private};
180 $curl->reset;
181  
182 # Ignore max_curls while perform() is running
183 push @{$self->avail_curl_pool}, $curl;
184 };
185  
186 my $ridx = $curl->{private}{idx};
187  
188 # Successful result
189 if ($result == 0) {
190 $curl->{private}{response}->complete;
191 }
192 # Network error
193 else {
194 my $msg = join ' ', $curl->strerror($result), $curl->{private}{uri};
195 croak $msg if $curl->{private}{die};
196 $curl->{private}{response}->fail($msg);
197 }
198  
199 $self->set_response($ridx, $curl->{private}{response});
200 }
201 }
202 }
203  
204 # Remove extraneous curl instances
205 $#{$self->avail_curl_pool} = $self->max_curls_in_pool;
206  
207 return @{$self->responses};
208 }
209  
210 sub set_response {
211 my ($self, $idx, $response) = @_;
212 $self->responses->[$idx] = $response;
213 }
214  
215 sub collect {
216 my $self = shift;
217 return $self->responses->[shift] if @_ == 1; # single id
218 my @results = @_
219 ? map{ $self->responses->[$_] } @_ # multiple ids
220 : @{$self->responses}; # no ids
221 return @results if wantarray;
222 return [@results];
223 }
224  
225 sub fetch {
226 my $class = shift;
227 my $fetch = ref $class ? $class : $class->new;
228 my ($id) = $fetch->try(@_);
229 $fetch->perform;
230 my ($response) = $fetch->collect($id);
231 return $response;
232 }
233  
234 1;
235  
236 =head1 NAME
237  
238 Net::Curl::Parallel - perform concurrent HTTP requests using libcurl
239  
240 =head1 SYNOPSIS
241  
242 use Net::Curl::Parallel;
243  
244 my $fetch = Net::Curl::Parallel->new(
245 agent => 'Net::Curl::Parallel/v0.1',
246 slots => 10,
247 max_redirects => 3,
248 connect_timeout => 50, # ms
249 request_timeout => 500, # ms
250 );
251  
252 # Add requests to be handled concurrently
253 my ($req1) = $fetch->add(HTTP::Request->new(...)); # pass an HTTP::Request instance
254 my ($req2) = $fetch->add(GET => 'http://www.example.com'); # pass HTTP::Request constructor args
255 my ($req3) = $fetch->try(GET => ...); # like add() but don't croak on failure
256  
257 # Request the... uh, well, requests
258 $fetch->perform;
259  
260 # Collect individually
261 my $res1 = $fetch->collect($req1);
262 my $res2 = $fetch->collect($req2);
263 my $res3 = $fetch->collect($req3);
264  
265 # Collect a few
266 my @responses = $fetch->collect($req1, $req2);
267  
268 # Or get the whole set
269 my @responses = $fetch->collect;
270  
271 # Perform a single request
272 my $response = Net::Curl::Parallel->fetch(...);
273  
274 =head1 DESCRIPTION
275  
276 Stop trying to make fetch happen; it's not going to happen
277 <https://www.youtube.com/watch?v=Pubd-spHN-0>
278 -- author of superior module, L<ZR::Curl>, fREW "mean-girl" Schmidt
279  
280 =head1 CLASS METHODS
281  
282 =head2 fetch
283  
284 Performs a single request and returns the response. Accepts the same parameters
285 as L</add> or L</try> and returns a L<Net::Curl::Parallel::Response>. Internally, this routine
286 uses L</try>, so failed requests do not C<die>. Instead, check the value of
287 L<Net::Curl::Parallel::Response/failed>.
288  
289 my $response = Net::Curl::Parallel->fetch(GET => ...);
290  
291 if ($response->failed) {
292 ...
293 } else {
294 ...
295 }
296  
297 =head2 max_curls_in_pool
298  
299 Please see the NOTES below about this class method.
300  
301 =head1 METHODS
302  
303 =head2 new
304  
305 The default values for constructor arguments have been selected as sensible for
306 an interactive web request. Please exercise care when increasing these numbers
307 to ensure web service worker availability as well as to avoid bandwidth
308 saturation and throttling.
309  
310 =over
311  
312 =item agent
313  
314 User agent string. Defaults to C<'Net::Curl::Parallel/v0.1'>.
315  
316 =item slots
317  
318 Max number of requests to process simultaneously. Defaults to 10.
319  
320 =item max_redirects
321  
322 Max number of times a remote server may redirect any single request. Defaults
323 to C<undef> (no redirects).
324  
325 =item connect_timeout
326  
327 Max initial connection time in milliseconds. Defaults to 50.
328  
329 =item request_timeout
330  
331 Max total request time in milliseconds. Defaults to 500.
332  
333 =item keep_alive
334  
335 Autmatically set C<Connection: keep-alive> on all HTTP requests. Defaults to
336 true.
337  
338 If a request already has a C<Connection:> header, that header will be left alone.
339  
340 =item verbose
341  
342 Turn on verbose logging within curl. Defaults to false.
343  
344 =back
345  
346 =head2 add
347  
348 Adds any number of L<HTTP::Request> objects to the download set. May also be
349 called with arguments to pass unchanged to the L<HTTP::Request> constructor, in
350 which case all arguments are consumed and a single request is added.
351  
352 Any request which fails will croak, preventing the servicing of any further
353 requests. Completed requests result in an L<Net::Curl::Parallel::Response> object.
354  
355 Returns a list of array indexes that identify the location of the responses in
356 the result array returned by L</perform>. The order of the returned indexes
357 corresponds to the order of requests passed to C<add> as parameters.
358  
359 my @ids = $fetch->add($req1, $req2, $req3);
360 my ($id) = $fetch->add(GET => ...);
361  
362 # This also works.
363 my $id = $fetch->add(GET => ...);
364  
365 =head2 try
366  
367 Similar to L</add>, but a failed request will result in a failed
368 L<HTTP::Response> with an error message rather than croaking.
369  
370 $fetch->try(HTTP::Request->new(...));
371  
372 my ($response) = $fetch->perform;
373  
374 if ($response->failed) {
375 handle_errors($response->error);
376 } else {
377 do_stuff($response);
378 }
379  
380 =head2 perform
381  
382 Performs all requests and returns a list of each response in the order it was
383 added. This method will not return until all requests have completed or an
384 unhandled error is encountered. Returns a list of L<Net::Curl::Parallel::Response>
385 objects corresponding to the index values returned by the L</add> and L</try>
386 methods.
387  
388 The behavior of an individual request when an error is encountered (e.g. unable
389 to reach the remote host, timeout, etc.) is determined by whether the request
390 was added by L</add> or L</try>.
391  
392 B<NOTE>: This means perform() could end prematurely if a request added with L</add> throws an exception, even if all the other requests were added with L</try>.
393  
394 =head2 collect
395  
396 When called in list context, returns a list of responses corresponding to the
397 list of request ids passed in. If called without arguments, the defaults to all
398 responses.
399  
400 When called in scalar context, returns a single response corresponding to the
401 request id passed in. If called without arguments, returns an array ref holding
402 all responses.
403  
404 B<NOTE>: This will B<not> block if the request is not completed with L</perform>.
405  
406 =head1 NOTES
407  
408 =head2 POSTs and Expect header
409  
410 If you L</add> a POST request, libcurl normally adds a 'Expect: 100-continue'
411 header depending on the body size. This can often result in undesirable
412 behavior, so Net::Curl::Parallel disables that by adding a blank 'Expect:'
413 header by default.
414  
415 You can set an 'Expect:' header and Net::Curl::Parallel will leave it alone.
416  
417 =head2 Pool of curls
418  
419 In order to conserve memory, there is a process-global pool of Net::Curl::Easy
420 objects. These are the objects that do the actual HTTP requests. You can access
421 them with C<< $self->curls >>.
422  
423 The pool's size defaults to 50. You can set this by calling
424  
425 # Or whatever number
426 Net::Curl::Parallel->max_curls_in_pool(20);
427  
428 The pool will be resized the next time L</perform> completes.
429  
430 Note: The pool's max size is ignored while L</perform> is running; the max is
431 only enforced at the end of L</perform>.
432  
433 =head1 CAVEATS
434  
435 =head2 Remember to call perform
436  
437 jp [4:07 PM] ah, helps if you actually `perform` the requests
438 jober [4:09 PM] Ah, good caveat. I ought to put that in the docs.
439 jp [4:09 PM] it is in there, just a little hidden
440  
441 =head1 MAINTAINER
442  
443 Rob Kinyon <rob.kinyon@gmail.com>
444  
445 =head1 SUPPORT
446  
447 Initial versions written by ZipRecruiter staff (jober and others).
448  
449 Codebase and support generously provided by ZipRecruiter for opensourcing.
450  
451 =head1 COPYRIGHT & LICENSE
452  
453 Copyright (C) 2010-onwards by ZipRecruiter
454  
455 This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
456  
457 =cut
« Parallel/Types.pm ↑ Summary