blib/lib/Future/Selector.pm

filter: Statementstmt 99.0% 109 / 110 Branchbran 92.8% 26 / 28 Conditioncond 72.2% 13 / 18 MC/DCmcdc 27.2% 3 / 11 Subroutinesub 100% 18 / 18 Podpod 100% 4 / 4 totaltotal 91.5% 173 / 189 CC 23 SCAR 18.4
CC
23
Cov
95%
select
13.0
_item_is_ready
7.0
add
4.1
CRAP 6.3
↑ 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, 2023-2025 -- leonerd@leonerd.org.uk
5  
6 6 ▶use v5.26;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 6 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
8  
9 6 ▶use Object::Pad 0.800;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 6 ▶use Future::AsyncAwait 0.44 ':experimental(cancel)';
Subroutine BEGIN: called CC=1 SCAR=0.0
11 6 ▶use Sublike::Extended 0.29 'method';
Subroutine BEGIN: called CC=1 SCAR=0.0
12  
13 class Future::Selector 0.05;
14  
15 6 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
16 6 ▶use Scalar::Util qw( refaddr );
Subroutine BEGIN: called CC=1 SCAR=0.0
17  
18 =head1 NAME
19  
20 C<Future::Selector> - manage a collection of pending futures
21  
22 =head1 SYNOPSIS
23  
24 use Future::AsyncAwait;
25 use Future::IO;
26 use Future::Selector;
27 use IO::Socket::IP;
28  
29 my $selector = Future::Selector->new;
30  
31 my $listensock = IO::Socket::IP->new(
32 LocalHost => "::1",
33 LocalPort => "8191",
34 Listen => 1,
35 );
36  
37 $selector->add(
38 data => "listener",
39 gen => sub { Future::IO->accept( $listensock ) },
40 );
41  
42 while(1) {
43 my @ready = await $selector->select;
44  
45 ...
46 }
47  
48 =head1 DESCRIPTION
49  
50 Objects in this class maintain a collection of pending L<Future> instances,
51 and manage the lifecycle of waiting for their eventual completion. This
52 provides a central structure for writing asynchronous event-driven programs
53 using L<Future> and L<Future::IO>-based logic.
54  
55 When writing an asynchronous C<Future>-based client, often the program can be
56 structured similar to a straight-line synchronous program, where at any point
57 the client is just waiting on sending or receiving one particular message or
58 data-flow. It therefore suffices to use a simple call/response structure,
59 perhaps written using the C<async> and C<await> keywords provided by
60 L<Future::AsyncAwait>.
61  
62 In contrast, a server program often has many things happening at once. It will
63 be handling multiple clients simultaneously, as well as waiting for new client
64 connections and any other internal logic it requires to provide data to those
65 clients. There is not just one obvious pending future at any one time; there
66 could be several that all need to be monitored for success or failure.
67  
68 A C<Future::Selector> instance helps this situation, by storing an entire set
69 of pending futures that represent individual sub-divisions of the work of the
70 program (or a part of it). As each completes, the selector instance informs
71 the containing code so it can continue to perform the work required to handle
72 that part, perhaps resulting in more future instances for the selector to
73 manage.
74  
75 =head2 Program Structure
76  
77 As per the SYNOPSIS example, a typical server-style program would probably be
78 structured around a C<while(1){}> loop that repeatedly C<await>s on the next
79 C<select> future from the selector instance, looking for the next thing to do.
80 The data values stored with each future and returned by the C<select> method
81 can be used to help direct the program into working out what is going on. For
82 example, string names or object instances could help identify different kinds
83 of next step.
84  
85 use v5.36;
86  
87 ...
88  
89 $selector->add(
90 data => "listener",
91 gen => sub { Future::IO->accept( $listensock ) },
92 );
93  
94 while(1) {
95 foreach my ( $data, $f ) ( await $selector->select ) {
96 if( $data eq "listener" ) {
97 # a new client has been accept()ed. should now set up handling
98 # for it in some manner.
99  
100 my $sock = await $f;
101 my $clientconn = ClientConnection->new( fh => $sock );
102  
103 $selector->add( data => $clientconn, f => $clientconn->run );
104 }
105 elsif( $data isa ClientConnection ) {
106 # an existing connection's runloop has terminated. should now
107 # handle that in whatever way is appropriate
108 ...
109 }
110 ...
111 }
112 }
113  
114 Alternatively, if each stored future instance already performed all of the
115 work required to handle it before it yields success, there may be nothing for
116 the toplevel application loop to do other than repeatedly wait for things to
117 happen.
118  
119 $selector->add(
120 data => undef, # ignored
121 gen => async sub {
122 my $sock = await Future::IO->accept( $listensock );
123 my $clientconn = ClientConnection->new( fh => $sock );
124  
125 $selector->add( data => undef, f => $clientconn->run );
126 }
127 );
128  
129 await $selector->select while 1;
130  
131 Failure propagation by the C<select> method here ensures any errors
132 encountered by individual component futures are still passed upwards through
133 the program structure, ultimately ending at the toplevel if nothing else
134 catches it first.
135  
136 =head2 Comparison With C<select(2)>, C<epoll>, etc..
137  
138 In some ways, the operation of this class is similar to system calls like
139 C<select(2)> and C<poll(2)>. However, there are several key differences:
140  
141 =over 4
142  
143 =item *
144  
145 C<Future::Selector> stores high-level futures, rather than operating directly
146 on system-level filehandles. As such, it can wait for application-level
147 events and workflow when those things are represented by futures.
148  
149 =item *
150  
151 The main waiting call, L</select>, is a method that returns a future. This
152 could be returned from some module or component of a program, to be awaited on
153 by another outer C<Future::Selector> instance. The application is not
154 limited to exactly one as would be the case for blocking system calls, but can
155 instead create a hierarchical structure out of as many instances as are
156 required.
157  
158 =item *
159  
160 Once added, a given future remains a member of a C<Future::Selector> instance
161 until it eventually completes; which may require many calls to the C<select>
162 method (or indeed, it may never complete during the lifetime of the program,
163 for tasks that should keep pending throughout). In this way, the object is
164 more comparable to persistent system-level schedulers like Linux's C<epoll> or
165 BSD's C<kqueue> mechanisms, than the one-shot nature of C<select(2)> or
166 C<poll(2)> themselves.
167  
168 =back
169  
170 =cut
171  
172 class Future::Selector::_Item {
173 30 ▶ field $data :param :reader;
Subroutine data: called CC=1 SCAR=0.0
174 135 ▶ field $f :param :mutator;
Subroutine f: called CC=1 SCAR=0.0
175 55 ▶ field $gen :param :reader;
Subroutine gen: called CC=1 SCAR=0.0
176 }
177  
178 6 field %items; # keyed by refaddr
179  
180 =head1 METHODS
181  
182 =cut
183  
184 6 field $next_waitf;
185 6 field @next_ready;
186 6 field $next_failure;
187 6 field @items_needing_regen;
188  
189 37 ▶method _item_is_ready ( $item )
Subroutine _item_is_ready: called CC=7 SCAR=19.5
190 {
191 37 my $f = $item->f;
192  
193 37 delete $items{ refaddr $item };
194  
195 37 ▶ if( $item->gen ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($item->gen) 23 14 37
196 23 push @items_needing_regen, $item;
197 }
198  
199 37 ▶ return if $f->is_cancelled;
Branch: 1 branch
BranchTrueFalseTotal
if $f->is_cancelled 3 34 37
200  
201 34 ▶ if( $next_waitf ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($next_waitf) { } 12 22 34
202 12 ▶ if( $f->is_failed ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($f->is_failed) { } 1 11 12
203 1 $f->on_fail( $next_waitf ); # copy the failure
204 }
205 else {
206 11 $next_waitf->done( $item->data, $item->f );
207 }
208 }
209 else {
210 22 ▶ if( $f->is_failed ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($f->is_failed) { } 3 19 22
211 3 ▶ $next_failure //= $f;
Condition33%1/3
$next_failure //= $f
l!l&&r!l&&!r
030
MC/DC0%0/2
$next_failure //= $f
$next_failure $f
Truth table33%1/3
A //= B
A= $next_failureB= $f
ABresult
1X1
011
000
212 }
213 else {
214 19 push @next_ready, $item->data, $item->f;
215 }
216 }
217 6 }
218  
219 =head2 add
220  
221 $selector->add( data => $data, f => $f );
222  
223 Adds a new future to the collection.
224  
225 After the future becomes ready, the currently-pending C<select> future (or the
226 next one to be created) will complete. It will yield the given data and future
227 instance if this future succeeded, or fail with the same failure if this
228 future failed. At that point it will be removed from the stored collection.
229 If the item future was cancelled, it is removed from the collection but
230 otherwise ignored; the C<select> future will continue waiting for another
231 result.
232  
233 $selector->add( data => $data, gen => $gen );
234  
235 $f = $gen->();
236  
237 Adds a new generator of futures to the collection.
238  
239 The generator is a code reference which is used to generate a future, which is
240 then added to the collection similar to the above case. Each time the future
241 becomes ready, the generator is called again to create another future to
242 continue watching. This continues until the generator returns C<undef>.
243  
244 =cut
245  
246 21 ▶method add ( :$data, :$f = undef, :$gen = undef )
Subroutine add: called CC=4 SCAR=14.0
Pod documented
247 {
248 21 ▶ if( $gen and !$f ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($gen and not $f) { } 5 16 21
elsif (not $f) { } 0 16 16
Condition66%2/3
$gen and not $f
!ll&&!rl&&r
1605
MC/DC50%1/2
$gen and not $f
$gen not $f
Truth table66%2/3
A and not(B)
A= $genB= not $f
ABresult
0X0
100
111
249 # TODO: Consider if we should do this immediately at all?
250 5 $f = $gen->();
251 }
252 elsif( !$f ) {
253 0 croak "Require 'f' or 'gen'";
254 }
255  
256 21 my $item = Future::Selector::_Item->new(
257 data => $data,
258 f => $f,
259 gen => $gen,
260 );
261 21 $items{ refaddr $item } = $item;
262  
263 21 ▶ $f->on_ready( sub { $self->_item_is_ready( $item ) } );
Subroutine __ANON__: called CC=1 SCAR=0.0
264  
265 21 return;
266 6 }
267  
268 =head2 select
269  
270 ( $data1, $f1, $data2, $f2, ... ) = await $selector->select();
271  
272 Returns a future that will become ready when at least one of the stored
273 futures is ready. It will yield an even-sized list of pairs, giving the
274 associated data and original (now-completed) futures that were stored.
275  
276 If you are intending to run the loop indefinitely, be careful not to write
277 code such as
278  
279 1 while await $selector->select;
280  
281 because in scalar context, the C<await>ed future will yield its first value,
282 which will be the data associated with the first completed future. If that
283 data value was false (such as C<undef>) then the loop will stop running at
284 that point. Generally in these sorts of situations you want to use L</run> or
285 L</run_until_ready>.
286  
287 =cut
288  
289 34 ▶method select ()
Subroutine select: called CC=13 SCAR=25.7
Pod documented
290 {
291 34 ▶ my $wait_f = $next_waitf // do {
Condition100%3/3
$next_waitf // do { if (my(@i) = @items_needing_regen) { undef @items_needing_regen; foreach my $item (@i) { my $f = $item->gen->() or next; $f->on_ready(sub { $self->_item_is_ready($item); } ); $item->f = $f; $items{builtin::refaddr($item)} = $item; } ; } ; keys %items or @next_ready or $next_failure or croak("$self cowardly refuses to sit idle and do nothing"); ($_->f->is_ready or $next_waitf = $_->f->new, last) foreach (values %items); $next_waitf //= "Future"->new; $next_waitf->set_label("Future::Selector next_waitf"); if ($next_failure) { $next_failure->on_fail($next_waitf); undef $next_failure; } elsif (@next_ready) { $next_waitf->done(@next_ready); undef @next_ready; } ; $next_waitf->on_ready(sub { undef $next_waitf; } ) }
l!l&&r!l&&!r
1321
MC/DC0%0/2
$next_waitf // do { if (my(@i) = @items_needing_regen) { undef @items_needing_regen; foreach my $item (@i) { my $f = $item->gen->() or next; $f->on_ready(sub { $self->_item_is_ready($item); } ); $item->f = $f; $items{builtin::refaddr($item)} = $item; } ; } ; keys %items or @next_ready or $next_failure or croak("$self cowardly refuses to sit idle and do nothing"); ($_->f->is_ready or $next_waitf = $_->f->new, last) foreach (values %items); $next_waitf //= "Future"->new; $next_waitf->set_label("Future::Selector next_waitf"); if ($next_failure) { $next_failure->on_fail($next_waitf); undef $next_failure; } elsif (@next_ready) { $next_waitf->done(@next_ready); undef @next_ready; } ; $next_waitf->on_ready(sub { undef $next_waitf; } ) }
$next_waitf do { if (my(@i) = @items_needing_regen) { undef @items_needing_regen; foreach my $item (@i) { my $f = $item->gen->() or next; $f->on_ready(sub { $self->_item_is_ready($item); } ); $item->f = $f; $items{builtin::refaddr($item)} = $item; } ; } ; keys %items or @next_ready or $next_failure or croak("$self cowardly refuses to sit idle and do nothing"); ($_->f->is_ready or $next_waitf = $_->f->new, last) foreach (values %items); $next_waitf //= "Future"->new; $next_waitf->set_label("Future::Selector next_waitf"); if ($next_failure) { $next_failure->on_fail($next_waitf); undef $next_failure; } elsif (@next_ready) { $next_waitf->done(@next_ready); undef @next_ready; } ; $next_waitf->on_ready(sub { undef $next_waitf; } ) }
Truth table66%2/3
A // B
A= $next_waitfB= do { if (my(@i) = @items_needing_regen) { undef @items_needing_regen; foreach my $item (@i) { my $f = $item->gen->() or next; $f->on_ready(sub { $self->_item_is_ready($item); } ); $item->f = $f; $items{builtin::refaddr($item)} = $item; } ; } ; keys %items or @next_ready or $next_failure or croak("$self cowardly refuses to sit idle and do nothing"); ($_->f->is_ready or $next_waitf = $_->f->new, last) foreach (values %items); $next_waitf //= "Future"->new; $next_waitf->set_label("Future::Selector next_waitf"); if ($next_failure) { $next_failure->on_fail($next_waitf); undef $next_failure; } elsif (@next_ready) { $next_waitf->done(@next_ready); undef @next_ready; } ; $next_waitf->on_ready(sub { undef $next_waitf; } ) }
ABresult
1X1
011
000
292 33 ▶ if( my @i = @items_needing_regen ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my(@i) = @items_needing_regen) 18 15 33
293 18 undef @items_needing_regen;
294  
295 18 foreach my $item ( @i ) {
296 18 ▶ my $f = $item->gen->() or next;
Branch: 1 branch
BranchTrueFalseTotal
my $f = $item->gen->() or next 18 0 18
297  
298 18 ▶ $f->on_ready( sub { $self->_item_is_ready( $item ) } );
Subroutine __ANON__: called CC=1 SCAR=0.0
299 18 $item->f = $f;
300 18 $items{ refaddr $item } = $item;
301 }
302 }
303  
304 33 ▶ keys %items or @next_ready or $next_failure or
Branch: 1 branch
BranchTrueFalseTotal
keys %items or @next_ready or $next_failure or croak("$self cowardly refuses to sit idle and do nothing") 30 3 33
Condition83%5/6
keys %items or @next_ready or $next_failure
l!l&&r!l&&!r
3003
keys %items or @next_ready
l!l&&r!l&&!r
2913
MC/DC66%2/3
keys %items or @next_ready or $next_failure
keys %items @next_ready $next_failure
Truth table75%3/4
A or B or C
A= keys %itemsB= @next_readyC= $next_failure
ABCresult
1XX1
01X1
0011
0000
305 croak "$self cowardly refuses to sit idle and do nothing";
306  
307 30 ▶ $_->f->is_ready or $next_waitf = $_->f->new, last for values %items;
Branch: 1 branch
BranchTrueFalseTotal
$_->f->is_ready or $next_waitf = $_->f->new, last 12 19 31
308 30 ▶ $next_waitf //= Future->new;
Condition66%2/3
$next_waitf //= "Future"->new
l!l&&r!l&&!r
19110
MC/DC0%0/2
$next_waitf //= "Future"->new
$next_waitf "Future"->new
Truth table66%2/3
A //= B
A= $next_waitfB= "Future"->new
ABresult
1X1
011
000
309  
310 30 $next_waitf->set_label( "Future::Selector next_waitf" );
311  
312 30 ▶ if( $next_failure ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($next_failure) { } 3 27 30
elsif (@next_ready) { } 14 13 27
313 3 $next_failure->on_fail( $next_waitf ); # copy the failure
314 3 undef $next_failure;
315 }
316 elsif( @next_ready ) {
317 14 $next_waitf->done( @next_ready );
318 14 undef @next_ready;
319 }
320  
321 30 ▶ $next_waitf->on_ready( sub { undef $next_waitf } );
Subroutine __ANON__: called CC=1 SCAR=0.0
322 };
323  
324 # We need to ensure that overlapping calls to ->select can't accidentally
325 # cancel each other.
326 # A simple call to ->without_cancel doesn't quite work as it causes
327 # sequence futures to be lost.
328  
329 31 my $ret_f = $wait_f->new;
330 31 $wait_f->on_done( $ret_f )
331 ->on_fail( $ret_f );
332 # nothing about cancel of $ret_f here. technically if we don't tidy up the
333 # on_done/on_fail above these will retain $ret_f longer than necessary, but
334 # there's no API to do that currently. Hopefully $wait_f will get cycled
335 # and replaced soon enough anyway and that will all go then.
336 31 return $ret_f;
337 6 }
338  
339 =head2 run
340  
341 await $selector->run();
342  
343 I<Since version 0.02.>
344  
345 Returns a future that represents repeatedly calling the L</select> method
346 indefinitely. This will not return, except that if any of the contained
347 futures fails then this will fail the same way.
348  
349 This is most typically used at the toplevel of a server-type program, one
350 where there is no normal exit condition and the program is expected to remain
351 running unless some fatal error happens.
352  
353 =cut
354  
355 2 ▶async method run ()
Subroutine run: called CC=1 SCAR=0.0
Pod documented
356 2 {
357 2 await $self->select while 1;
358 6 }
359  
360 =head2 run_until_ready
361  
362 @result = await $selector->run_until_ready( $f );
363  
364 I<Since version 0.02.>
365  
366 Returns a future that represents repeatedly calling the L</select> method
367 until the given future instance is ready. When it becomes ready (either by
368 success or failure) the returned future will yield the same result. If the
369 returned future is cancelled, then C<$f> itself will be cancelled too. This
370 will not cancel a concurrently-pending C<select> or C<run> call, however.
371  
372 The given future will be added to the selector by calling this method; you
373 should I<not> call L</add> on it yourself first.
374  
375 This is typically used in client or hybrid code, or as a nested component of
376 a server program, which needs to wait on a result while also performing other
377 background tasks.
378  
379 Remember that since this method itself returns a future, it could easily serve
380 as the input to another outer-level selector instance.
381  
382 =cut
383  
384 3 ▶async method run_until_ready ( $f )
Subroutine run_until_ready: called CC=2 SCAR=6.9
Pod documented
385 3 {
386 3 $self->add( data => undef, f => $f );
387 CANCEL { $f->cancel; }
388 3 ▶ await $self->select until $f->is_ready;
Branch: 1 branch
BranchTrueFalseTotal
$f->is_ready or do { <custom op await> } 1 7 8
389 1 return await $f;
390 6 }
391  
392 =head1 TODO
393  
394 =over 4
395  
396 =item *
397  
398 Convenience ->add_f / ->add_gen
399  
400 =item *
401  
402 Configurable behaviour on component future failure
403  
404 =back
405  
406 =cut
407  
408 =head1 AUTHOR
409  
410 Paul Evans <leonerd@leonerd.org.uk>
411  
412 =cut
413  
414 6 0x55AA;
↑ Summary