Promiser.pm

filter: Statementstmt 77.7% 7 / 9 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 3 / 3 Podpod n/a totaltotal 83.3% 10 / 12 CC 1 SCAR 0.9
CC
1
Cov
78%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.1
« Promiser/LoopBase.pm ↑ Summary Promiser/Select.pm »
1 package Net::Curl::Promiser;
2  
3 1 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 1 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5  
6 our $VERSION = '0.07_03';
7  
8 =encoding utf-8
9  
10 =head1 NAME
11  
12 Net::Curl::Promiser - A Promise interface for L<Net::Curl::Multi>
13  
14 =head1 DESCRIPTION
15  
16 This module wraps L<Net::Curl::Multi> to facilitate asynchronous
17 requests with Promise objects. Net::Curl::Promiser interfaces with
18 Net::Curl::Multi’s polling callbacks to simplify your task of coordinating
19 multiple concurrent requests.
20  
21 L<Net::Curl::Promiser> itself is a base class; you’ll need to provide
22 an interface to whatever event loop you use. See L</SUBCLASS INTERFACE>
23 below.
24  
25 This distribution provides the following as both demonstrations and
26 portable implementations:
27  
28 =over
29  
30 =item * L<Net::Curl::Promiser::Mojo> (for L<Mojolicious>)
31  
32 =item * L<Net::Curl::Promiser::AnyEvent> (for L<AnyEvent>)
33  
34 =item * L<Net::Curl::Promiser::IOAsync> (for L<IO::Async>)
35  
36 =item * L<Net::Curl::Promiser::Select> (for manually-written
37 C<select()> loops)
38  
39 =back
40  
41 (See the distribution’s F</examples> directory for one based on Linux’s
42 C<epoll>.)
43  
44 =head1 PROMISE IMPLEMENTATION
45  
46 This class’s default Promise implementation is L<Promise::ES6>.
47 You can use a different one by overriding the L<PROMISE_CLASS()> method in
48 a subclass, as long as the substitute class’s C<new()> method works the
49 same way as Promise::ES6’s (which itself follows the ECMAScript standard).
50  
51 (NB: L<Net::Curl::Promiser::Mojo> uses L<Mojo::Promise> instead of
52 Promise::ES6.)
53  
54 =cut
55  
56 #----------------------------------------------------------------------
57  
58 1 ▶use Net::Curl::Multi ();
Subroutine BEGIN: called CC=1 SCAR=2.6
59  
60 use constant _DEFAULT_TIMEOUT => 1000;
61  
62 use constant PROMISE_CLASS => 'Promise::ES6';
63  
64 #----------------------------------------------------------------------
65  
66 =head1 GENERAL-USE METHODS
67  
68 The following are of interest to any code that uses this module:
69  
70 =head2 I<CLASS>->new(@ARGS)
71  
72 Instantiates this class. This creates an underlying
73 L<Net::Curl::Multi> object and calls the subclass’s C<_INIT()>
74 method at the end, passing a reference to @ARGS.
75  
76 (Most end classes of this module do not require @ARGS.)
77  
78 =cut
79  
80 sub new {
81 my ($class, @args) = @_;
82  
83 my %props = (
84 callbacks => {},
85 to_fail => {},
86 );
87  
88 my $self = bless \%props, $class;
89  
90 my $multi = Net::Curl::Multi->new();
91 $self->{'multi'} = $multi;
92  
93 $multi->setopt(
94 Net::Curl::Multi::CURLMOPT_SOCKETDATA,
95 $self,
96 );
97  
98 $multi->setopt(
99 Net::Curl::Multi::CURLMOPT_SOCKETFUNCTION,
100 \&_socket_fn,
101 );
102  
103 $self->_INIT(\@args);
104  
105 return $self;
106 }
107  
108 #----------------------------------------------------------------------
109  
110 =head2 promise($EASY) = I<OBJ>->add_handle( $EASY )
111  
112 A passthrough to the underlying L<Net::Curl::Multi> object’s
113 method of the same name, but the return is given as a Promise object.
114  
115 That promise resolves with the passed-in $EASY object.
116 It rejects with either the error given to C<fail_handle()> or the
117 error that L<Net::Curl::Multi> object’s C<info_read()> returns.
118  
119 B<IMPORTANT:> As with libcurl itself, HTTP-level failures
120 (e.g., 4xx and 5xx responses) are B<NOT> considered failures at this level.
121  
122 =cut
123  
124 sub add_handle {
125 my ($self, $easy) = @_;
126  
127 $self->{'multi'}->add_handle($easy);
128  
129 my $env_engine = $ENV{'NET_CURL_PROMISER_PROMISE_ENGINE'} || q<>;
130  
131 my $promise;
132  
133 if ($env_engine eq 'Promise::XS') {
134 require Promise::XS;
135  
136 my $deferred = Promise::XS::deferred();
137 $self->{'deferred'}{$easy} = $deferred;
138 $promise = $deferred->promise();
139 }
140 elsif ($env_engine) {
141 die "bad promise engine: [$env_engine]";
142 }
143 else {
144 my $module = $self->PROMISE_CLASS() . '.pm';
145 $module =~ s<::></>g;
146 require $module;
147  
148 $promise = $self->PROMISE_CLASS()->new( sub {
149 $self->{'callbacks'}{$easy} = \@_;
150 } );
151 }
152  
153 return $promise;
154 }
155  
156 =head2 $obj = I<OBJ>->fail_handle( $EASY, $REASON )
157  
158 Prematurely fails $EASY. The given $REASON will be the associated
159 Promise object’s rejection value.
160  
161 =cut
162  
163 sub fail_handle {
164 my ($self, $easy, $reason) = @_;
165  
166 $self->{'to_fail'}{$easy} = [ $easy, $reason ];
167  
168 return $self;
169 }
170  
171 #----------------------------------------------------------------------
172  
173 =head2 $obj = I<OBJ>->setopt( … )
174  
175 A passthrough to the underlying L<Net::Curl::Multi> object’s
176 method of the same name. Returns I<OBJ> to facilitate chaining.
177  
178 C<CURLMOPT_SOCKETFUNCTION> or C<CURLMOPT_SOCKETDATA> are set internally;
179 any attempt to set them via this interface will prompt an error.
180  
181 =cut
182  
183 sub setopt {
184 my $self = shift;
185  
186 for my $opt ( qw( SOCKETFUNCTION SOCKETDATA ) ) {
187 my $fullopt = "CURLMOPT_$opt";
188  
189 if ($_[0] == Net::Curl::Multi->can($fullopt)->()) {
190 my $ref = ref $self;
191 die "Don’t set $fullopt via $ref!";
192 }
193 }
194  
195 $self->{'multi'}->setopt(@_);
196 return $self;
197 }
198  
199 =head2 $obj = I<OBJ>->handles( … )
200  
201 A passthrough to the underlying L<Net::Curl::Multi> object’s
202 method of the same name.
203  
204 =cut
205  
206 sub handles {
207 return shift()->{'multi'}->handles();
208 }
209  
210 #----------------------------------------------------------------------
211  
212 =head1 EVENT LOOP METHODS
213  
214 The following are needed only when you’re managing an event loop directly:
215  
216 =head2 $num = I<OBJ>->get_timeout()
217  
218 Returns the underlying L<Net::Curl::Multi> object’s C<timeout()>
219 value, with a suitable (positive) default substituted if that value is
220 less than 0.
221  
222 (NB: This value is in I<milliseconds>.)
223  
224 This may not suit your needs; if you wish/need, you can handle timeouts
225 via the L<CURLMOPT_TIMERFUNCTION|Net::Curl::Multi/CURLMOPT_TIMERFUNCTION>
226 callback instead.
227  
228 This should only be called (if it’s called at all) from event loop logic.
229  
230 =cut
231  
232 sub get_timeout {
233 my ($self) = @_;
234  
235 my $timeout = $self->{'multi'}->timeout();
236  
237 return( $timeout < 0 ? _DEFAULT_TIMEOUT() : $timeout );
238 }
239  
240 #----------------------------------------------------------------------
241  
242 =head2 $obj = I<OBJ>->process( @ARGS )
243  
244 Tell the underlying L<Net::Curl::Multi> object which socket events have
245 happened.
246  
247 If, in fact, no events have happened, then this calls
248 C<socket_action(CURL_SOCKET_TIMEOUT)> on the
249 L<Net::Curl::Multi> object (similar to C<time_out()>).
250  
251 Finally, this reaps whatever pending HTTP responses may be ready and
252 resolves or rejects the corresponding Promise objects.
253  
254 This should only be called from event loop logic.
255  
256 Returns I<OBJ>.
257  
258 =cut
259  
260 sub process {
261 my ($self, @fd_action_args) = @_;
262  
263 my $fd_action_hr = $self->_GET_FD_ACTION(\@fd_action_args);
264  
265 if (%$fd_action_hr) {
266 for my $fd (keys %$fd_action_hr) {
267 local $self->{'_removed_fd'};
268 $self->{'multi'}->socket_action( $fd, $fd_action_hr->{$fd} );
269 }
270 }
271 else {
272 $self->{'multi'}->socket_action( Net::Curl::Multi::CURL_SOCKET_TIMEOUT() );
273 }
274  
275 $self->_process_pending();
276  
277 return $self;
278 }
279  
280 #----------------------------------------------------------------------
281  
282 =head2 $is_active = I<OBJ>->time_out();
283  
284 Tell the underlying L<Net::Curl::Multi> object that a timeout happened,
285 and reap whatever pending HTTP responses may be ready.
286  
287 Calls C<socket_action(CURL_SOCKET_TIMEOUT)> on the
288 underlying L<Net::Curl::Multi> object. The return is the same as
289 that operation returns.
290  
291 Since C<process()> can also do the work of this function, a call to this
292 function is just an optimization.
293  
294 This should only be called from event loop logic.
295  
296 =cut
297  
298 sub time_out {
299 my ($self) = @_;
300  
301 my $is_active = $self->{'multi'}->socket_action( Net::Curl::Multi::CURL_SOCKET_TIMEOUT() );
302  
303 $self->_process_pending();
304  
305 return $is_active;
306 }
307  
308 #----------------------------------------------------------------------
309  
310 =head1 SUBCLASS INTERFACE
311  
312 B<NOTE:> The distribution provides several ready-built end classes;
313 unless you’re managing your own event loop, you don’t need to concern
314 yourself with this.
315  
316 To use Net::Curl::Promiser, you’ll need a subclass that defines
317 the following methods:
318  
319 =over
320  
321 =item * C<_INIT(\@ARGS)>: Called at the end of C<new()>. Receives a reference
322 to the arguments given to C<new()>.
323  
324 =item * C<_SET_POLL_IN($FD)>: Tells the event loop that the given file
325 descriptor is ready to read.
326  
327 =item * C<_SET_POLL_OUT($FD)>: Like C<_SET_POLL_IN()> but for a write event.
328  
329 =item * C<_SET_POLL_INOUT($FD)>: Like C<_SET_POLL_IN()> but registers
330 a read and write event simultaneously.
331  
332 =item * C<_STOP_POLL($FD)>: Tells the event loop that the given file
333 descriptor is finished.
334  
335 =item * C<_GET_FD_ACTION(\@ARGS)>: Receives a reference to the arguments
336 given to C<process()> and returns a reference to a hash of
337 ( $fd => $event_mask ). $event_mask is the sum of
338 C<Net::Curl::Multi::CURL_CSELECT_IN()> and/or
339 C<Net::Curl::Multi::CURL_CSELECT_OUT()>, depending on which events
340 are available.
341  
342 =back
343  
344 =cut
345  
346 #----------------------------------------------------------------------
347  
348 sub _socket_fn {
349 my ( $fd, $action, $self ) = @_[2, 3, 5];
350  
351 if ($action == Net::Curl::Multi::CURL_POLL_IN) {
352 $self->_SET_POLL_IN($fd);
353 }
354 elsif ($action == Net::Curl::Multi::CURL_POLL_OUT) {
355 $self->_SET_POLL_OUT($fd);
356 }
357 elsif ($action == Net::Curl::Multi::CURL_POLL_INOUT) {
358 $self->_SET_POLL_INOUT($fd);
359 }
360 elsif ($action == Net::Curl::Multi::CURL_POLL_REMOVE) {
361 $self->_STOP_POLL($fd);
362 $self->{'_removed_fd'} = $fd;
363 }
364 else {
365 warn "$self: Unrecognized action $action on FD $fd\n";
366 }
367  
368 return 0;
369 }
370  
371 sub _socket_action {
372 my ($self, $fd, $direction) = @_;
373  
374 my $is_active = $self->{'multi'}->socket_action( $fd, $direction );
375  
376 $self->_process_pending();
377  
378 return $is_active;
379 }
380  
381 sub _finish_handle {
382 my ($self, $easy, $cb_idx, $payload) = @_;
383  
384 delete $self->{'to_fail'}{$easy};
385  
386 $self->{'multi'}->remove_handle( $easy );
387  
388 if ( my $cb_ar = delete $self->{'callbacks'}{$easy} ) {
389 $cb_ar->[$cb_idx]->($payload);
390 }
391 elsif ( my $deferred = delete $self->{'deferred'}{$easy} ) {
392 if ($cb_idx) {
393 $deferred->reject($payload);
394 }
395 else {
396 $deferred->resolve($payload);
397 }
398 }
399  
400 return;
401 }
402  
403 sub _clear_failed {
404 my ($self) = @_;
405  
406 for my $val_ar ( values %{ $self->{'to_fail'} } ) {
407 my ($easy, $reason) = @$val_ar;
408 $self->_finish_handle( $easy, 1, $reason );
409 }
410  
411 %{ $self->{'to_fail'} } = ();
412  
413 return;
414 }
415  
416 sub _process_pending {
417 my ($self) = @_;
418  
419 $self->_clear_failed();
420  
421 while ( my ( $msg, $easy, $result ) = $self->{'multi'}->info_read() ) {
422  
423 if ($msg != Net::Curl::Multi::CURLMSG_DONE()) {
424 die "Unrecognized info_read() message: [$msg]";
425 }
426  
427 $self->_finish_handle(
428 $easy,
429 ($result == 0) ? ( 0 => $easy ) : ( 1 => $result ),
430 );
431 }
432  
433 return;
434 }
435  
436 #----------------------------------------------------------------------
437  
438 =head1 EXAMPLES
439  
440 See the distribution’s F</examples> directory.
441  
442 =head1 SEE ALSO
443  
444 If you use L<AnyEvent>, then L<AnyEvent::XSPromises> with
445 L<AnyEvent::YACurl> may be a nicer fit for you.
446  
447 =head1 REPOSITORY
448  
449 L<https://github.com/FGasper/p5-Net-Curl-Promiser>
450  
451 =head1 LICENSE & COPYRIGHT
452  
453 Copyright 2019-2020 Gasper Software Consulting.
454  
455 This library is licensed under the same terms as Perl itself.
456  
457 =cut
458  
459 1;
« Promiser/LoopBase.pm ↑ Summary Promiser/Select.pm »