blib/lib/AnyEvent/Future.pm

filter: Statementstmt 100% 65 / 65 Branchbran 100% 4 / 4 Conditioncond 66.6% 2 / 3 MC/DCmcdc 50.0% 1 / 2 Subroutinesub 100% 24 / 24 Podpod 100% 7 / 7 totaltotal 98.1% 103 / 105 CC 4 SCAR 3.7
CC
4
Cov
99%
__ANON__
4.0
from_cv
1.0
BEGIN
1.0
CRAP 1.4
↑ Summary
1 # You may distribute under the terms of either the GNU General Public License
2 # or the Artistic License (the same terms as Perl itself)
3 #
4 # (C) Paul Evans, 2014-2021 -- leonerd@leonerd.org.uk
5  
6 package AnyEvent::Future 0.05;
7  
8 4 ▶use v5.14;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 4 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
10  
11 4 ▶use base qw( Future );
Subroutine BEGIN: called CC=1 SCAR=0.0
12 4 Future->VERSION( '0.49' ); # ->set_udata
13  
14 4 ▶use Exporter 'import';
Subroutine BEGIN: called CC=1 SCAR=0.0
15 4 our @EXPORT_OK = qw(
16 as_future
17 as_future_cb
18 );
19  
20 4 ▶use AnyEvent;
Subroutine BEGIN: called CC=1 SCAR=0.0
21  
22 =head1 NAME
23  
24 C<AnyEvent::Future> - use L<Future> with L<AnyEvent>
25  
26 =head1 SYNOPSIS
27  
28 use AnyEvent;
29 use AnyEvent::Future;
30  
31 my $future = AnyEvent::Future->new;
32  
33 some_async_function( ..., cb => sub { $future->done( @_ ) } );
34  
35 print Future->wait_any(
36 $future,
37 AnyEvent::Future->new_timeout( after => 10 ),
38 )->get;
39  
40 Or
41  
42 use AnyEvent::Future qw( as_future_cb );
43  
44 print Future->wait_any(
45 as_future_cb {
46 some_async_function( ..., cb => shift )
47 },
48 AnyEvent::Future->new_timeout( after => 10 ),
49 )->get;
50  
51 =head1 DESCRIPTION
52  
53 This subclass of L<Future> integrates with L<AnyEvent>, allowing the C<await>
54 method to block until the future is ready. It allows C<AnyEvent>-using code to
55 be written that returns C<Future> instances, so that it can make full use of
56 C<Future>'s abilities, including L<Future::Utils>, and also that modules using
57 it can provide a C<Future>-based asynchronous interface of their own.
58  
59 For a full description on how to use Futures, see the L<Future> documentation.
60  
61 =cut
62  
63 # Forward
64 sub as_future(&);
65  
66 =head1 CONSTRUCTORS
67  
68 =cut
69  
70 =head2 new
71  
72 $f = AnyEvent::Future->new
73  
74 Returns a new leaf future instance, which will allow waiting for its result to
75 be made available, using the C<await> method.
76  
77 =cut
78  
79 =head2 new_delay
80  
81 $f = AnyEvent::Future->new_delay( @args )
82  
83 =head2 new_timeout
84  
85 $f = AnyEvent::Future->new_timeout( @args )
86  
87 Returns a new leaf future instance that will become ready at the time given by
88 the arguments, which will be passed to the C<< AnyEvent->timer >> method.
89  
90 C<new_delay> returns a future that will complete successfully at the alotted
91 time, whereas C<new_timeout> returns a future that will fail with the message
92 C<Timeout>. This is provided as a simple utility for small use-cases; for a
93 more find-grained control over the failure message and additional values you
94 may wish to use C<new_delay> combined with the C<then_fail> method:
95  
96 new_delay( after => 10 )
97 ->then_fail( "The operation timed out after 10 seconds", timeout => );
98  
99 =cut
100  
101 sub new_delay
102 1 ▶{
Subroutine new_delay: called CC=1 SCAR=0.0
Pod documented
103 1 shift;
104 1 my %args = @_;
105  
106 1 ▶ as_future {
Subroutine __ANON__: called CC=1 SCAR=0.0
107 1 my $f = shift;
108 1 ▶ AnyEvent->timer( %args, cb => sub { $f->done } );
Subroutine __ANON__: called CC=1 SCAR=0.0
109 1 };
110 }
111  
112 sub new_timeout
113 1 ▶{
Subroutine new_timeout: called CC=1 SCAR=0.0
Pod documented
114 1 shift;
115 1 my %args = @_;
116  
117 1 ▶ as_future {
Subroutine __ANON__: called CC=1 SCAR=0.0
118 1 my $f = shift;
119 1 ▶ AnyEvent->timer( %args, cb => sub { $f->fail( "Timeout" ) } );
Subroutine __ANON__: called CC=1 SCAR=0.0
120 1 };
121 }
122  
123 =head2 from_cv
124  
125 $f = AnyEvent::Future->from_cv( $cv )
126  
127 Returns a new leaf future instance that will become ready when the given
128 L<AnyEvent::CondVar> instance is ready. The success or failure result of the
129 future will be the result passed to the condvar's C<send> or C<croak> method.
130  
131 =cut
132  
133 sub from_cv
134 3 ▶{
Subroutine from_cv: called CC=1 SCAR=0.0
Pod documented
135 3 my $class = shift;
136 3 my ( $cv ) = @_;
137  
138 3 my $f = $class->new;
139  
140 3 my $was_cb = $cv->cb;
141  
142 3 ▶ $cv->cb( sub {
Subroutine __ANON__: called CC=4 SCAR=13.9
143 3 my ( $cv ) = @_;
144 3 my @result;
145 3 ▶ eval { @result = $cv->recv; 1 } and $f->done( @result ) or
Branch: 1 branch
BranchTrueFalseTotal
eval { do { @result = $cv->recv; 1 } } and $f->done(@result) or $f->fail($@) 2 1 3
Condition66%2/3
eval { do { @result = $cv->recv; 1 } } and $f->done(@result)
!ll&&!rl&&r
102
MC/DC50%1/2
eval { do { @result = $cv->recv; 1 } } and $f->done(@result)
eval { do { @result = $cv->recv; 1 } } $f->done(@result)
Truth table66%2/3
A and B
A= eval { do { @result = $cv->recv; 1 } }B= $f->done(@result)
ABresult
0X0
100
111
146 $f->fail( $@ );
147  
148 3 ▶ $was_cb->( @_ ) if $was_cb;
Branch: 1 branch
BranchTrueFalseTotal
if $was_cb 1 2 3
149 3 });
150  
151 3 return $f;
152 }
153  
154 =head1 METHODS
155  
156 =cut
157  
158 =head2 as_cv
159  
160 $cv = $f->as_cv
161  
162 Returns a new C<AnyEvent::CondVar> instance that wraps the given future; it
163 will complete with success or failure when the future does.
164  
165 Note that because C<< AnyEvent::CondVar->croak >> takes only a single string
166 message for the argument, any subsequent failure detail values from the future
167 are lost by the condvar. To capture these as well, you may wish to use an
168 C<on_fail> callback or the C<failure> method, to obtain them.
169  
170 =cut
171  
172 sub as_cv
173 2 ▶{
Subroutine as_cv: called CC=1 SCAR=0.0
Pod documented
174 2 my $self = shift;
175  
176 2 my $cv = AnyEvent->condvar;
177  
178 2 ▶ $self->on_done( sub { $cv->send( @_ ) } );
Subroutine __ANON__: called CC=1 SCAR=0.0
179 2 ▶ $self->on_fail( sub { $cv->croak( $_[0] ) } );
Subroutine __ANON__: called CC=1 SCAR=0.0
180  
181 2 return $cv;
182 }
183  
184 sub await
185 6 ▶{
Subroutine await: called CC=1 SCAR=0.0
Pod documented
186 6 my $self = shift;
187  
188 6 my $cv = AnyEvent->condvar;
189 6 ▶ $self->on_ready( sub { $cv->send } );
Subroutine __ANON__: called CC=1 SCAR=0.0
190  
191 6 $cv->recv;
192 }
193  
194 =head1 UTILITY FUNCTIONS
195  
196 The following utility functions are exported as a convenience.
197  
198 =cut
199  
200 =head2 as_future
201  
202 $f = as_future { CODE }
203  
204 Returns a new leaf future instance, which is also passed in to the block of
205 code. The code is called in scalar context, and its return value is stored on
206 the future. This will be deleted if the future is cancelled.
207  
208 $w = CODE->( $f )
209  
210 This utility is provided for the common case of wanting to wrap an C<AnyEvent>
211 function which will want to receive a callback function to inform of
212 completion, and which will return a watcher object reference that needs to be
213 stored somewhere.
214  
215 =cut
216  
217 sub as_future(&)
218 6 ▶{
Subroutine as_future: called CC=1 SCAR=0.0
Pod documented
219 6 my ( $code ) = @_;
220  
221 6 my $f = AnyEvent::Future->new;
222  
223 6 $f->set_udata( w => scalar $code->( $f ) );
224 6 ▶ $f->on_cancel( sub { $f->set_udata( w => undef ) } );
Subroutine __ANON__: called CC=1 SCAR=0.0
225  
226 6 return $f;
227 }
228  
229 =head2 as_future_cb
230  
231 $f = as_future_cb { CODE }
232  
233 A futher shortcut to C<as_future>, where the code is passed two callback
234 functions for C<done> and C<fail> directly, avoiding boilerplate in the common
235 case for creating these closures capturing the future variable. In many cases
236 this can reduce the code block to a single line.
237  
238 $w = CODE->( $done_cb, $fail_cb )
239  
240 =cut
241  
242 sub as_future_cb(&)
243 2 ▶{
Subroutine as_future_cb: called CC=1 SCAR=0.0
Pod documented
244 2 my ( $code ) = @_;
245  
246 2 ▶ &as_future( sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
247 2 my $f = shift;
248 2 ▶ $code->( sub { $f->done(@_) }, sub { $f->fail(@_) } );
Subroutine __ANON__: called CC=1 SCAR=0.0
Subroutine __ANON__: called CC=1 SCAR=0.0
249 2 });
250 }
251  
252 =head1 EXAMPLES
253  
254 =head2 Wrapping watcher-style C<AnyEvent> functions
255  
256 The C<as_future_cb> utility provides an excellent wrapper to take the common
257 style of C<AnyEvent> function that returns a watcher object and takes a
258 completion callback, and turn it into a C<Future> that can be used or combined
259 with other C<Future>-based code. For example, the L<AnyEvent::HTTP> function
260 called C<http_get> performs in this style.
261  
262 use AnyEvent::Future qw( as_future_cb );
263 use AnyEvent::HTTP qw( http_get );
264  
265 my $url = ...;
266  
267 my $f = as_future_cb {
268 my ( $done_cb ) = @_;
269  
270 http_get $url, $done_cb;
271 };
272  
273 This could of course be easily wrapped by a convenient function to return
274 futures:
275  
276 sub http_get_future
277 {
278 my ( $url, @args ) = @_;
279  
280 as_future_cb {
281 my ( $done_cb ) = @_;
282  
283 http_get $url, @args, $done_cb;
284 }
285 }
286  
287 =head2 Using C<Future>s as enhanced C<CondVar>s
288  
289 While at first glance it may appear that a C<Future> instance is much like an
290 L<AnyEvent::CondVar>, the greater set of convergence methods (such as
291 C<needs_all> or C<needs_any>), and the various utility functions (in
292 L<Future::Utils>) makes it possible to write the same style of code in a more
293 concise or powerful way.
294  
295 For example, rather than using the C<CondVar> C<begin> and C<end> methods, a
296 set of C<CondVar>-returning functions can be converted into C<Futures>,
297 combined using C<needs_all>, and converted back to a C<CondVar> again:
298  
299 my $cv = Future->needs_all(
300 Future::AnyEvent->from_cv( FUNC1() ),
301 Future::AnyEvent->from_cv( FUNC2() ),
302 ...
303 )->as_cv;
304  
305 my @results = $cv->recv;
306  
307 This would become yet more useful if, instead of functions that return
308 C<CondVars>, we were operating on functions that return C<Future>s directly.
309 Because the C<needs_all> will cancel any still-pending futures the moment one
310 of them failed, we get a nice neat cancellation of outstanding work if one of
311 them fails, in a way that would be much harder without the C<Future>s. For
312 example, using the C<http_get_future> function from above:
313  
314 my $cv = Future->needs_all(
315 http_get_future( "http://url-1" ),
316 http_get_future( "http://url-2" ),
317 http_get_future( "https://url-third/secret" ),
318 )->as_cv;
319  
320 my @results = $cv->recv;
321  
322 In this case, the moment any of the HTTP GET functions fails, the ones that
323 are still pending are all cancelled (by dropping their cancellation watcher
324 object) and the overall C<recv> call throws an exception.
325  
326 Of course, there is no need to convert the outermost C<Future> into a
327 C<CondVar>; the full set of waiting semantics are implemented on these
328 instances, so instead you may simply call C<get> on it to achieve the same
329 effect:
330  
331 my $f = Future->needs_all(
332 http_get_future( "http://url-1" ),
333 ...
334 );
335  
336 my @results = $f->get;
337  
338 This has other side advantages, such as the list-valued semantics of failures
339 that can provide additional information besides just the error message, and
340 propagation of cancellation requests.
341  
342 =cut
343  
344 =head1 TODO
345  
346 =over 4
347  
348 =item *
349  
350 Consider whether or not it would be considered "evil" to inject a new method
351 into L<AnyEvent::CondVar>; namely by doing
352  
353 sub AnyEvent::CondVar::as_future { AnyEvent::Future->from_cv( shift ) }
354  
355 =back
356  
357 =head1 AUTHOR
358  
359 Paul Evans <leonerd@leonerd.org.uk>
360  
361 =cut
362  
363 4 0x55AA;
↑ Summary