blib/lib/IO/Async/Function.pm

filter: Statementstmt 95.6% 241 / 252 Branchbran 74.1% 86 / 116 Conditioncond 65.5% 19 / 29 MC/DCmcdc 22.2% 4 / 18 Subroutinesub 97.9% 47 / 48 Podpod 72.7% 8 / 11 totaltotal 85.4% 405 / 474 CC 78 SCAR 21.8
CC
78
Cov
87%
configure
26.2
call
18.2
_dispatch_pending
7.0
CRAP 8.9
« blib/lib/IO/Async/Handle.pm ↑ Summary blib/lib/IO/Async/Socket.pm »
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, 2011-2024 -- leonerd@leonerd.org.uk
5  
6 package IO::Async::Function 0.805;
7  
8 10 ▶use v5.14;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 10 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
10  
11 10 ▶use base qw( IO::Async::Notifier );
Subroutine BEGIN: called CC=1 SCAR=0.0
12 10 ▶use IO::Async::Timer::Countdown;
Subroutine BEGIN: called CC=1 SCAR=0.0
13  
14 10 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
15  
16 10 ▶use List::Util qw( first );
Subroutine BEGIN: called CC=1 SCAR=0.0
17  
18 10 ▶use Struct::Dumb qw( readonly_struct );
Subroutine BEGIN: called CC=1 SCAR=0.0
19  
20 10 readonly_struct Pending => [qw( priority f )];
21  
22 =head1 NAME
23  
24 C<IO::Async::Function> - call a function asynchronously
25  
26 =head1 SYNOPSIS
27  
28 =for highlighter language=perl
29  
30 use Future::AsyncAwait;
31 use IO::Async::Function;
32  
33 use IO::Async::Loop;
34 my $loop = IO::Async::Loop->new;
35  
36 my $function = IO::Async::Function->new(
37 code => sub {
38 my ( $number ) = @_;
39 return is_prime( $number );
40 },
41 );
42  
43 $loop->add( $function );
44  
45 my $isprime = await $function->call(
46 args => [ 123454321 ],
47 );
48  
49 print "123454321 " . ( $isprime ? "is" : "is not" ) . " a prime number\n";
50  
51 =head1 DESCRIPTION
52  
53 This subclass of L<IO::Async::Notifier> wraps a function body in a collection
54 of worker processes, to allow it to execute independently of the main process.
55 The object acts as a proxy to the function, allowing invocations to be made by
56 passing in arguments, and invoking a continuation in the main process when the
57 function returns.
58  
59 The object represents the function code itself, rather than one specific
60 invocation of it. It can be called multiple times, by the C<call> method.
61 Multiple outstanding invocations can be called; they will be dispatched in
62 the order they were queued. If only one worker process is used then results
63 will be returned in the order they were called. If multiple are used, then
64 each request will be sent in the order called, but timing differences between
65 each worker may mean results are returned in a different order.
66  
67 Since the code block will be called multiple times within the same child
68 process, it must take care not to modify any of its state that might affect
69 subsequent calls. Since it executes in a child process, it cannot make any
70 modifications to the state of the parent program. Therefore, all the data
71 required to perform its task must be represented in the call arguments, and
72 all of the result must be represented in the return values.
73  
74 The Function object is implemented using an L<IO::Async::Routine> with two
75 L<IO::Async::Channel> objects to pass calls into and results out from it.
76  
77 The L<IO::Async> framework generally provides mechanisms for multiplexing IO
78 tasks between different handles, so there aren't many occasions when such an
79 asynchronous function is necessary. Two cases where this does become useful
80 are:
81  
82 =over 4
83  
84 =item 1.
85  
86 When a large amount of computationally-intensive work needs to be performed
87 (for example, the C<is_prime> test in the example in the C<SYNOPSIS>).
88  
89 =item 2.
90  
91 When a blocking OS syscall or library-level function needs to be called, and
92 no nonblocking or asynchronous version is supplied. This is used by
93 L<IO::Async::Resolver>.
94  
95 =back
96  
97 This object is ideal for representing "pure" functions; that is, blocks of
98 code which have no stateful effect on the process, and whose result depends
99 only on the arguments passed in. For a more general co-routine ability, see
100 also L<IO::Async::Routine>.
101  
102 =cut
103  
104 =head1 PARAMETERS
105  
106 The following named parameters may be passed to C<new> or C<configure>:
107  
108 =head2 code => CODE
109  
110 The body of the function to execute.
111  
112 @result = $code->( @args );
113  
114 =head2 init_code => CODE
115  
116 Optional. If defined, this is invoked exactly once in every child process or
117 thread, after it is created, but before the first invocation of the function
118 body itself.
119  
120 $init_code->();
121  
122 =head2 module => STRING
123  
124 =head2 func => STRING
125  
126 I<Since version 0.79.>
127  
128 An alternative to the C<code> argument, which names a module to load and a
129 function to call within it. C<module> should give a perl module name (i.e.
130 C<Some::Name>, not a filename like F<Some/Name.pm>), and C<func> should give
131 the basename of a function within that module (i.e. without the module name
132 prefixed). It will be invoked, without extra arguments, as the main code
133 body of the object.
134  
135 The task of loading this module and resolving the resulting function from it
136 is only performed on the remote worker side, so the controlling process will
137 not need to actually load the module.
138  
139 =head2 init_func => STRING or ARRAY [ STRING, ... ]
140  
141 Optional addition to the C<module> and C<func> alternatives. Names a function
142 within the module to call each time a new worker is created.
143  
144 If this value is an array reference, its first element must be a string giving
145 the name of the function; the remaining values are passed to that function as
146 arguments.
147  
148 =head2 model => "fork" | "thread" | "spawn"
149  
150 Optional. Requests a specific L<IO::Async::Routine> model. If not supplied,
151 leaves the default choice up to Routine.
152  
153 =head2 min_workers => INT
154  
155 =head2 max_workers => INT
156  
157 The lower and upper bounds of worker processes to try to keep running. The
158 actual number running at any time will be kept somewhere between these bounds
159 according to load.
160  
161 =head2 max_worker_calls => INT
162  
163 Optional. If provided, stop a worker process after it has processed this
164 number of calls. (New workers may be started to replace stopped ones, within
165 the bounds given above).
166  
167 =head2 idle_timeout => NUM
168  
169 Optional. If provided, idle worker processes will be shut down after this
170 amount of time, if there are more than C<min_workers> of them.
171  
172 =head2 exit_on_die => BOOL
173  
174 Optional boolean, controls what happens after the C<code> throws an
175 exception. If missing or false, the worker will continue running to process
176 more requests. If true, the worker will be shut down. A new worker might be
177 constructed by the C<call> method to replace it, if necessary.
178  
179 =head2 setup => ARRAY
180  
181 Optional array reference. Specifies the C<setup> key to pass to the underlying
182 L<IO::Async::Process> when setting up new worker processes.
183  
184 =cut
185  
186 sub _init
187 {
188 49 ▶ my $self = shift;
Subroutine _init: called CC=1 SCAR=0.0
189 49 $self->SUPER::_init( @_ );
190  
191 49 $self->{min_workers} = 1;
192 49 $self->{max_workers} = 8;
193  
194 49 $self->{workers} = {}; # {$id} => IaFunction:Worker
195  
196 49 $self->{pending_queue} = [];
197 }
198  
199 sub configure
200 {
201 49 ▶ my $self = shift;
Subroutine configure: called CC=19 SCAR=32.7
Pod documented
202 49 my %params = @_;
203  
204 49 my %worker_params;
205 49 foreach (qw( model exit_on_die max_worker_calls )) {
206 147 ▶ $self->{$_} = $worker_params{$_} = delete $params{$_} if exists $params{$_};
Branch: 1 branch
BranchTrueFalseTotal
if exists $params{$_} 14 133 147
207 }
208  
209 49 ▶ if( keys %worker_params ) {
Branch: 1 branch
BranchTrueFalseTotal
if (keys %worker_params) 14 35 49
210 14 foreach my $worker ( $self->_worker_objects ) {
211 0 $worker->configure( %worker_params );
212 }
213 }
214  
215 49 ▶ if( exists $params{idle_timeout} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $params{"idle_timeout"}) 7 42 49
216 7 my $timeout = delete $params{idle_timeout};
217 7 ▶ if( !$timeout ) {
Branch: 2 branches
BranchTrueFalseTotal
if (not $timeout) { } 0 7 7
elsif (my $idle_timer = $self->{'idle_timer'}) { } 0 7 7
218 0 ▶ $self->remove_child( delete $self->{idle_timer} ) if $self->{idle_timer};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"idle_timer"} 0 0 0
219 }
220 elsif( my $idle_timer = $self->{idle_timer} ) {
221 0 $idle_timer->configure( delay => $timeout );
222 }
223 else {
224 $self->{idle_timer} = IO::Async::Timer::Countdown->new(
225 delay => $timeout,
226 on_expire => $self->_capture_weakself( sub {
227 1 ▶ my $self = shift or return;
Subroutine __ANON__: called CC=5 SCAR=16.7
Branch: 1 branch
BranchTrueFalseTotal
my $self = shift() or return 0 1 1
228 1 my $workers = $self->{workers};
229  
230 # Shut down atmost one idle worker, starting from the highest
231 # ID. Since we search from lowest to assign work, this tries
232 # to ensure we'll shut down the least useful ones first,
233 # keeping more useful ones in memory (page/cache warmth, etc..)
234 1 foreach my $id ( reverse sort keys %$workers ) {
235 1 ▶ next if $workers->{$id}{busy};
Branch: 1 branch
BranchTrueFalseTotal
if $workers->{$id}{"busy"} 0 1 1
236  
237 1 $workers->{$id}->stop;
238 1 last;
239 }
240  
241 # Still more?
242 1 ▶ $self->{idle_timer}->start if $self->workers_idle > $self->{min_workers};
Branch: 1 branch
BranchTrueFalseTotal
if $self->workers_idle > $self->{"min_workers"} 0 1 1
243 7 } ),
244 );
245 7 $self->add_child( $self->{idle_timer} );
246 }
247 }
248  
249 49 foreach (qw( min_workers max_workers )) {
250 98 ▶ $self->{$_} = delete $params{$_} if exists $params{$_};
Branch: 1 branch
BranchTrueFalseTotal
if exists $params{$_} 48 50 98
251 # TODO: something about retuning
252 }
253  
254 49 my $need_restart;
255  
256 49 foreach (qw( init_code code module init_func func setup )) {
257 294 ▶ $need_restart++, $self->{$_} = delete $params{$_} if exists $params{$_};
Branch: 1 branch
BranchTrueFalseTotal
if exists $params{$_} 61 233 294
258 }
259  
260 defined $self->{code} and defined $self->{func} and
261 49 ▶ croak "Cannot ->configure both 'code' and 'func'";
Branch: 1 branch
BranchTrueFalseTotal
defined $self->{"code"} and defined $self->{"func"} and croak("Cannot ->configure both 'code' and 'func'") 0 49 49
Condition66%2/3
defined $self->{"code"} and defined $self->{"func"}
!ll&&!rl&&r
10390
MC/DC0%0/2
defined $self->{"code"} and defined $self->{"func"}
defined $self->{"code"} defined $self->{"func"}
Truth table66%2/3
A and B
A= defined $self->{"code"}B= defined $self->{"func"}
ABresult
0X0
100
111
262 defined $self->{func} and !defined $self->{module} and
263 49 ▶ croak "'func' parameter requires a 'module' as well";
Branch: 1 branch
BranchTrueFalseTotal
defined $self->{"func"} and not defined $self->{"module"} and croak("'func' parameter requires a 'module' as well") 0 49 49
Condition66%2/3
defined $self->{"func"} and not defined $self->{"module"}
!ll&&!rl&&r
39100
MC/DC0%0/2
defined $self->{"func"} and not defined $self->{"module"}
defined $self->{"func"} not defined $self->{"module"}
Truth table66%2/3
A and not(B)
A= defined $self->{"func"}B= not defined $self->{"module"}
ABresult
0X0
100
111
264  
265 49 $self->SUPER::configure( %params );
266  
267 49 ▶ if( $need_restart and $self->loop ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($need_restart and $self->loop) 0 49 49
Condition33%1/3
$need_restart and $self->loop
!ll&&!rl&&r
0490
MC/DC0%0/2
$need_restart and $self->loop
$need_restart $self->loop
Truth table33%1/3
A and B
A= $need_restartB= $self->loop
ABresult
0X0
100
111
268 0 $self->stop;
269 0 $self->start;
270 }
271 }
272  
273 sub _add_to_loop
274 {
275 49 ▶ my $self = shift;
Subroutine _add_to_loop: called CC=1 SCAR=0.0
276 49 $self->SUPER::_add_to_loop( @_ );
277  
278 49 $self->start;
279 }
280  
281 sub _remove_from_loop
282 {
283 37 ▶ my $self = shift;
Subroutine _remove_from_loop: called CC=1 SCAR=0.0
284  
285 37 $self->stop;
286  
287 37 $self->SUPER::_remove_from_loop( @_ );
288 }
289  
290 =head1 METHODS
291  
292 The following methods documented in C<await> expressions return L<Future>
293 instances.
294  
295 =cut
296  
297 =head2 start
298  
299 $function->start;
300  
301 Start the worker processes
302  
303 =cut
304  
305 sub start
306 {
307 51 ▶ my $self = shift;
Subroutine start: called CC=2 SCAR=6.9
Pod documented
308  
309 51 $self->_new_worker for 1 .. $self->{min_workers};
310 }
311  
312 =head2 stop
313  
314 $function->stop;
315  
316 Stop the worker processes
317  
318 $f = $function->stop;
319  
320 I<Since version 0.75.>
321  
322 If called in non-void context, returns a L<IO::Async::Future> instance that
323 will complete once every worker process has stopped and exited. This may be
324 useful for waiting until all of the processes are waited on, or other
325 edge-cases, but is not otherwise particularly useful.
326  
327 =cut
328  
329 sub stop
330 {
331 43 ▶ my $self = shift;
Subroutine stop: called CC=4 SCAR=13.9
Pod documented
332  
333 43 $self->{stopping} = 1;
334  
335 43 my @f;
336  
337 43 foreach my $worker ( $self->_worker_objects ) {
338 38 ▶ defined wantarray ? push @f, $worker->stop : $worker->stop;
Branch: 1 branch
BranchTrueFalseTotal
defined wantarray ? : 3 35 38
339 }
340  
341 43 ▶ return Future->needs_all( @f ) if defined wantarray;
Branch: 1 branch
BranchTrueFalseTotal
if defined wantarray 3 40 43
342 }
343  
344 =head2 restart
345  
346 $function->restart;
347  
348 Gracefully stop and restart all the worker processes.
349  
350 =cut
351  
352 sub restart
353 {
354 2 ▶ my $self = shift;
Subroutine restart: called CC=1 SCAR=0.0
Pod documented
355  
356 2 $self->stop;
357 2 $self->start;
358 }
359  
360 =head2 call
361  
362 @result = await $function->call( %params );
363  
364 Schedules an invocation of the contained function to be executed on one of the
365 worker processes. If a non-busy worker is available now, it will be called
366 immediately. If not, it will be queued and sent to the next free worker that
367 becomes available.
368  
369 The request will already have been serialised by the marshaller, so it will be
370 safe to modify any referenced data structures in the arguments after this call
371 returns.
372  
373 The C<%params> hash takes the following keys:
374  
375 =over 8
376  
377 =item args => ARRAY
378  
379 A reference to the array of arguments to pass to the code.
380  
381 =item priority => NUM
382  
383 Optional. Defines the sorting order when no workers are available and calls
384 must be queued for later. A default of zero will apply if not provided.
385  
386 Higher values cause the call to be considered more important, and will be
387 placed earlier in the queue than calls with a smaller value. Calls of equal
388 priority are still handled in FIFO order.
389  
390 =back
391  
392 If the function body returns normally the list of results are provided as the
393 (successful) result of returned future. If the function throws an exception
394 this results in a failed future. In the special case that the exception is in
395 fact an unblessed C<ARRAY> reference, this array is unpacked and used as-is
396 for the C<fail> result. If the exception is not such a reference, it is used
397 as the first argument to C<fail>, in the category of C<error>.
398  
399 $f->done( @result );
400  
401 $f->fail( @{ $exception } );
402 $f->fail( $exception, error => );
403  
404 =head2 call (void)
405  
406 $function->call( %params );
407  
408 When not returning a future, the C<on_result>, C<on_return> and C<on_error>
409 arguments give continuations to handle successful results or failure.
410  
411 =over 8
412  
413 =item on_result => CODE
414  
415 A continuation that is invoked when the code has been executed. If the code
416 returned normally, it is called as:
417  
418 $on_result->( 'return', @values )
419  
420 If the code threw an exception, or some other error occurred such as a closed
421 connection or the process died, it is called as:
422  
423 $on_result->( 'error', $exception_name )
424  
425 =item on_return => CODE and on_error => CODE
426  
427 An alternative to C<on_result>. Two continuations to use in either of the
428 circumstances given above. They will be called directly, without the leading
429 'return' or 'error' value.
430  
431 =back
432  
433 =cut
434  
435 sub debug_printf_call
436 {
437 75 ▶ my $self = shift;
Subroutine debug_printf_call: called CC=1 SCAR=0.0
Pod undocumented
438 75 $self->debug_printf( "CALL" );
439 }
440  
441 sub debug_printf_result
442 {
443 52 ▶ my $self = shift;
Subroutine debug_printf_result: called CC=1 SCAR=0.0
Pod undocumented
444 52 $self->debug_printf( "RESULT" );
445 }
446  
447 sub debug_printf_failure
448 {
449 21 ▶ my $self = shift;
Subroutine debug_printf_failure: called CC=1 SCAR=0.0
Pod undocumented
450 21 my ( $err ) = @_;
451 21 $self->debug_printf( "FAIL $err" );
452 }
453  
454 sub call
455 {
456 88 ▶ my $self = shift;
Subroutine call: called CC=17 SCAR=29.0
Pod documented
457 88 my %params = @_;
458  
459 # TODO: possibly just queue this?
460 88 ▶ $self->loop or croak "Cannot ->call on a Function not yet in a Loop";
Branch: 1 branch
BranchTrueFalseTotal
$self->loop or croak("Cannot ->call on a Function not yet in a Loop") 0 88 88
461  
462 88 my $args = delete $params{args};
463 88 ▶ ref $args eq "ARRAY" or croak "Expected 'args' to be an array";
Branch: 1 branch
BranchTrueFalseTotal
ref $args eq "ARRAY" or croak("Expected 'args' to be an array") 0 88 88
464  
465 88 my ( $on_done, $on_fail );
466 88 ▶ if( defined $params{on_result} ) {
Branch: 3 branches
BranchTrueFalseTotal
if (defined $params{'on_result'}) { } 2 86 88
elsif (defined $params{'on_return'} and defined $params{'on_error'}) { } 44 42 86
elsif (not defined wantarray) { } 0 42 42
467 2 my $on_result = delete $params{on_result};
468 2 ▶ ref $on_result or croak "Expected 'on_result' to be a reference";
Branch: 1 branch
BranchTrueFalseTotal
ref $on_result or croak("Expected 'on_result' to be a reference") 0 2 2
469  
470 $on_done = sub {
471 2 ▶ $on_result->( return => @_ );
Subroutine __ANON__: called CC=1 SCAR=0.0
472 2 };
473 $on_fail = sub {
474 0 ▶ my ( $err, @values ) = @_;
Subroutine __ANON__: not called CC=1 SCAR=6.9
475 0 $on_result->( error => @values );
476 2 };
477 }
478 ▶ elsif( defined $params{on_return} and defined $params{on_error} ) {
Condition66%2/3
defined $params{"on_return"} and defined $params{"on_error"}
!ll&&!rl&&r
42044
MC/DC50%1/2
defined $params{"on_return"} and defined $params{"on_error"}
defined $params{"on_return"} defined $params{"on_error"}
Truth table66%2/3
A and B
A= defined $params{"on_return"}B= defined $params{"on_error"}
ABresult
0X0
100
111
479 44 my $on_return = delete $params{on_return};
480 44 ▶ ref $on_return or croak "Expected 'on_return' to be a reference";
Branch: 1 branch
BranchTrueFalseTotal
ref $on_return or croak("Expected 'on_return' to be a reference") 0 44 44
481 44 my $on_error = delete $params{on_error};
482 44 ▶ ref $on_error or croak "Expected 'on_error' to be a reference";
Branch: 1 branch
BranchTrueFalseTotal
ref $on_error or croak("Expected 'on_error' to be a reference") 0 44 44
483  
484 44 $on_done = $on_return;
485 44 $on_fail = $on_error;
486 }
487 elsif( !defined wantarray ) {
488 0 croak "Expected either 'on_result' or 'on_return' and 'on_error' keys, or to return a Future";
489 }
490  
491 88 $self->debug_printf_call( @$args );
492  
493 88 my $request = IO::Async::Channel->encode( $args );
494  
495 88 my $future;
496 88 ▶ if( my $worker = $self->_get_worker ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $worker = $self->_get_worker) { } 64 23 87
497 64 $future = $self->_call_worker( $worker, $request );
498 }
499 else {
500 23 $self->debug_printf( "QUEUE" );
501 23 my $queue = $self->{pending_queue};
502  
503 my $next = Pending(
504 23 ▶ my $priority = $params{priority} || 0,
Condition100%2/2
$params{'priority'} || 0
l!l
914
MC/DC100%1/1
$params{'priority'} || 0
$params{'priority'}
Truth table100%2/2
A
A= $params{'priority'}
Aresult
11
00
505 my $wait_f = $self->loop->new_future,
506 );
507  
508 23 ▶ if( $priority ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($priority) { } 9 14 23
509 9 ▶ my $idx = first { $queue->[$_]->priority < $priority } 0 .. $#$queue;
Subroutine __ANON__: called CC=1 SCAR=0.0
510 9 ▶ splice @$queue, $idx // $#$queue+1, 0, ( $next );
Condition33%1/3
$idx // $queue->$#* + 1
l!l&&r!l&&!r
900
MC/DC0%0/2
$idx // $queue->$#* + 1
$idx $queue->$#* + 1
Truth table33%1/3
A // B
A= $idxB= $queue->$#* + 1
ABresult
1X1
011
000
511 }
512 else {
513 14 push @$queue, $next;
514 }
515  
516 $future = $wait_f->then( sub {
517 22 ▶ my ( $self, $worker ) = @_;
Subroutine __ANON__: called CC=1 SCAR=0.0
518 22 $self->_call_worker( $worker, $request );
519 23 });
520 }
521  
522 $future->on_done( $self->_capture_weakself( sub {
523 64 ▶ my $self = shift or return;
Subroutine __ANON__: called CC=2 SCAR=7.2
Branch: 1 branch
BranchTrueFalseTotal
my $self = shift() or return 0 64 64
524 64 $self->debug_printf_result( @_ );
525 87 }));
526 $future->on_fail( $self->_capture_weakself( sub {
527 21 ▶ my $self = shift or return;
Subroutine __ANON__: called CC=2 SCAR=7.2
Branch: 1 branch
BranchTrueFalseTotal
my $self = shift() or return 0 21 21
528 21 $self->debug_printf_failure( @_ );
529 87 }));
530  
531 87 ▶ $future->on_done( $on_done ) if $on_done;
Branch: 1 branch
BranchTrueFalseTotal
if $on_done 45 42 87
532 87 ▶ $future->on_fail( $on_fail ) if $on_fail;
Branch: 1 branch
BranchTrueFalseTotal
if $on_fail 45 42 87
533  
534 87 ▶ return $future if defined wantarray;
Branch: 1 branch
BranchTrueFalseTotal
if defined wantarray 51 36 87
535  
536 # Caller is not going to keep hold of the Future, so we have to ensure it
537 # stays alive somehow
538 36 ▶ $self->adopt_future( $future->else( sub { Future->done } ) );
Subroutine __ANON__: called CC=1 SCAR=0.0
539 }
540  
541 sub _worker_objects
542 {
543 226 ▶ my $self = shift;
Subroutine _worker_objects: called CC=1 SCAR=0.0
544 226 return values %{ $self->{workers} };
545 }
546  
547 =head2 workers
548  
549 $count = $function->workers;
550  
551 Returns the total number of worker processes available
552  
553 =cut
554  
555 sub workers
556 {
557 53 ▶ my $self = shift;
Subroutine workers: called CC=1 SCAR=0.0
Pod documented
558 53 return scalar keys %{ $self->{workers} };
559 }
560  
561 =head2 workers_busy
562  
563 $count = $function->workers_busy;
564  
565 Returns the number of worker processes that are currently busy
566  
567 =cut
568  
569 sub workers_busy
570 {
571 9 ▶ my $self = shift;
Subroutine workers_busy: called CC=1 SCAR=0.0
Pod documented
572 9 return scalar grep { $_->{busy} } $self->_worker_objects;
573 }
574  
575 =head2 workers_idle
576  
577 $count = $function->workers_idle;
578  
579 Returns the number of worker processes that are currently idle
580  
581 =cut
582  
583 sub workers_idle
584 {
585 160 ▶ my $self = shift;
Subroutine workers_idle: called CC=1 SCAR=0.0
Pod documented
586 160 return scalar grep { !$_->{busy} } $self->_worker_objects;
587 }
588  
589 sub _new_worker
590 {
591 55 ▶ my $self = shift;
Subroutine _new_worker: called CC=1 SCAR=0.5
592  
593 my $worker = IO::Async::Function::Worker->new(
594 440 ( map { $_ => $self->{$_} } qw( model init_code code module init_func func setup exit_on_die ) ),
595 max_calls => $self->{max_worker_calls},
596  
597 on_finish => $self->_capture_weakself( sub {
598 3 ▶ my $self = shift or return;
Subroutine __ANON__: called CC=4 SCAR=18.9
Branch: 1 branch
BranchTrueFalseTotal
my $self = shift() or return 0 3 3
599 3 my ( $worker ) = @_;
600  
601 3 ▶ return if $self->{stopping};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"stopping"} 3 0 3
602  
603 0 ▶ $self->_new_worker if $self->workers < $self->{min_workers};
Branch: 1 branch
BranchTrueFalseTotal
if $self->workers < $self->{"min_workers"} 0 0 0
604  
605 0 $self->_dispatch_pending;
606 55 } ),
607 );
608  
609 55 $self->add_child( $worker );
610  
611 53 return $self->{workers}{$worker->id} = $worker;
612 }
613  
614 sub _get_worker
615 {
616 111 ▶ my $self = shift;
Subroutine _get_worker: called CC=4 SCAR=13.9
617  
618 111 foreach ( sort keys %{ $self->{workers} } ) {
619 102 ▶ return $self->{workers}{$_} if !$self->{workers}{$_}{busy};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"workers"}{$_}{"busy"} 76 26 102
620 }
621  
622 35 ▶ if( $self->workers < $self->{max_workers} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->workers < $self->{"max_workers"}) 12 23 35
623 12 return $self->_new_worker;
624 }
625  
626 23 return undef;
627 }
628  
629 sub _call_worker
630 {
631 86 ▶ my $self = shift;
Subroutine _call_worker: called CC=3 SCAR=11.0
632 86 my ( $worker, $type, $args ) = @_;
633  
634 86 my $future = $worker->call( $type, $args );
635  
636 86 ▶ if( $self->workers_idle == 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->workers_idle == 0) 84 2 86
637 84 ▶ $self->{idle_timer}->stop if $self->{idle_timer};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"idle_timer"} 15 69 84
638 }
639  
640 86 return $future;
641 }
642  
643 sub _dispatch_pending
644 {
645 86 ▶ my $self = shift;
Subroutine _dispatch_pending: called CC=7 SCAR=19.5
646  
647 86 ▶ while( my $next = shift @{ $self->{pending_queue} } ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $next = shift @{$$self{"pending_queue"};}) 23 64 87
648 23 ▶ my $worker = $self->_get_worker or return;
Branch: 1 branch
BranchTrueFalseTotal
my $worker = $self->_get_worker or return 0 23 23
649  
650 23 my $f = $next->f;
651  
652 23 ▶ next if $f->is_cancelled;
Branch: 1 branch
BranchTrueFalseTotal
if $f->is_cancelled 1 22 23
653  
654 22 $self->debug_printf( "UNQUEUE" );
655 22 $f->done( $self, $worker );
656 22 return;
657 }
658  
659 64 ▶ if( $self->workers_idle > $self->{min_workers} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->workers_idle > $self->{"min_workers"}) 17 47 64
660 17 ▶ $self->{idle_timer}->start if $self->{idle_timer} and !$self->{idle_timer}->is_running;
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"idle_timer"} and not $self->{"idle_timer"}->is_running 15 2 17
Condition66%2/3
$self->{"idle_timer"} and not $self->{"idle_timer"}->is_running
!ll&&!rl&&r
2015
MC/DC50%1/2
$self->{"idle_timer"} and not $self->{"idle_timer"}->is_running
$self->{"idle_timer"} not $self->{"idle_timer"}->is_running
Truth table66%2/3
A and not(B)
A= $self->{"idle_timer"}B= not $self->{"idle_timer"}->is_running
ABresult
0X0
100
111
661 }
662 }
663  
664 package # hide from indexer
665 IO::Async::Function::Worker;
666  
667 10 ▶use base qw( IO::Async::Routine );
Subroutine BEGIN: called CC=1 SCAR=0.0
668  
669 10 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
670  
671 10 ▶use IO::Async::Channel;
Subroutine BEGIN: called CC=1 SCAR=0.0
672  
673 10 ▶use IO::Async::Internals::FunctionWorker;
Subroutine BEGIN: called CC=1 SCAR=0.0
674  
675 sub new
676 {
677 55 ▶ my $class = shift;
Subroutine new: called CC=5 SCAR=16.1
678 55 my %params = @_;
679  
680 55 my $arg_channel = IO::Async::Channel->new;
681 55 my $ret_channel = IO::Async::Channel->new;
682  
683 55 my $send_initial;
684  
685 55 ▶ if( defined( my $code = $params{code} ) ) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined(my $code = $params{'code'})) { } 49 6 55
elsif (defined(my $func = $params{'func'})) { } 6 0 6
686 49 my $init_code = $params{init_code};
687  
688 $params{code} = sub {
689 1 ▶ $init_code->() if defined $init_code;
Subroutine __ANON__: called CC=2 SCAR=7.2
Branch: 1 branch
BranchTrueFalseTotal
if defined $init_code 0 1 1
690  
691 1 IO::Async::Internals::FunctionWorker::runloop( $code, $arg_channel, $ret_channel );
692 49 };
693 }
694 elsif( defined( my $func = $params{func} ) ) {
695 6 my $module = $params{module};
696 6 my $init_func = $params{init_func};
697 6 my @init_args;
698  
699 6 $params{module} = "IO::Async::Internals::FunctionWorker";
700 6 $params{func} = "run_worker";
701  
702 6 ▶ ( $init_func, @init_args ) = @$init_func if ref( $init_func ) eq "ARRAY";
Branch: 1 branch
BranchTrueFalseTotal
if ref $init_func eq "ARRAY" 0 6 6
703  
704 6 $send_initial = [ $module, $func, $init_func, @init_args ];
705 }
706  
707 55 delete @params{qw( init_code init_func )};
708  
709 55 my $worker = $class->SUPER::new(
710 %params,
711 channels_in => [ $arg_channel ],
712 channels_out => [ $ret_channel ],
713 );
714  
715 55 $worker->{arg_channel} = $arg_channel;
716 55 $worker->{ret_channel} = $ret_channel;
717  
718 55 ▶ $worker->{send_initial} = $send_initial if $send_initial;
Branch: 1 branch
BranchTrueFalseTotal
if $send_initial 6 49 55
719  
720 55 return $worker;
721 }
722  
723 sub _add_to_loop
724 {
725 55 ▶ my $self = shift;
Subroutine _add_to_loop: called CC=2 SCAR=6.9
726 55 $self->SUPER::_add_to_loop( @_ );
727  
728 53 ▶ $self->{arg_channel}->send( delete $self->{send_initial} ) if $self->{send_initial};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"send_initial"} 5 48 53
729 }
730  
731 sub configure
732 {
733 55 ▶ my $self = shift;
Subroutine configure: called CC=3 SCAR=11.1
734 55 my %params = @_;
735  
736 55 ▶ exists $params{$_} and $self->{$_} = delete $params{$_} for qw( exit_on_die max_calls );
Branch: 1 branch
BranchTrueFalseTotal
exists $params{$_} and $self->{$_} = delete $params{$_} 110 0 110
737  
738 55 $self->SUPER::configure( %params );
739 }
740  
741 sub stop
742 {
743 48 ▶ my $worker = shift;
Subroutine stop: called CC=4 SCAR=13.9
744 48 $worker->{arg_channel}->close;
745  
746 48 my $ret;
747 48 ▶ $ret = $worker->result_future if defined wantarray;
Branch: 1 branch
BranchTrueFalseTotal
if defined wantarray 3 45 48
748  
749 48 ▶ if( my $function = $worker->parent ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $function = $worker->parent) 48 0 48
750 48 delete $function->{workers}{$worker->id};
751  
752 48 ▶ if( $worker->{busy} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($worker->{'busy'}) { } 10 38 48
753 10 $worker->{remove_on_idle}++;
754 }
755 else {
756 38 $function->remove_child( $worker );
757 }
758 }
759  
760 48 return $ret;
761 }
762  
763 sub call
764 {
765 86 ▶ my $worker = shift;
Subroutine call: called CC=1 SCAR=0.0
766 86 my ( $args ) = @_;
767  
768 86 $worker->{arg_channel}->send_encoded( $args );
769  
770 86 $worker->{busy} = 1;
771 86 $worker->{max_calls}--;
772  
773 return $worker->{ret_channel}->recv->then(
774 # on recv
775 $worker->_capture_weakself( sub {
776 83 ▶ my ( $worker, $result ) = @_;
Subroutine __ANON__: called CC=6 SCAR=18.2
777 83 my ( $type, @values ) = @$result;
778  
779 $worker->stop if !$worker->{max_calls} or
780 83 ▶ $worker->{exit_on_die} && $type eq "e";
Branch: 1 branch
BranchTrueFalseTotal
if not $worker->{"max_calls"} or $worker->{"exit_on_die"} and $type eq "e" 7 76 83
Condition83%5/6
not $worker->{"max_calls"} or $worker->{"exit_on_die"} and $type eq "e"
l!l&&r!l&&!r
14834
$worker->{"exit_on_die"} and $type eq "e"
!ll&&!rl&&r
7606
MC/DC0%0/3
not $worker->{"max_calls"} or $worker->{"exit_on_die"} and $type eq "e"
not $worker->{"max_calls"} $worker->{"exit_on_die"} $type eq "e"
Truth table50%2/4
not(A) or B and C
A= not $worker->{"max_calls"}B= $worker->{"exit_on_die"}C= $type eq "e"
ABCresult
1XX1
0111
00X0
0100
781  
782 83 ▶ if( $type eq "r" ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($type eq 'r') { } 64 19 83
elsif ($type eq 'e') { } 19 0 19
783 64 return Future->done( @values );
784 }
785 elsif( $type eq "e" ) {
786 19 return Future->fail( @values );
787 }
788 else {
789 0 die "Unrecognised type from worker - $type\n";
790 }
791 } ),
792 # on EOF
793 $worker->_capture_weakself( sub {
794 2 ▶ my ( $worker ) = @_;
Subroutine __ANON__: called CC=1 SCAR=0.0
795  
796 2 $worker->stop;
797  
798 2 return Future->fail( "closed", "closed" );
799 } )
800 )->on_ready( $worker->_capture_weakself( sub {
801 86 ▶ my ( $worker, $f ) = @_;
Subroutine __ANON__: called CC=4 SCAR=14.0
802 86 $worker->{busy} = 0;
803  
804 86 my $function = $worker->parent;
805 86 ▶ $function->_dispatch_pending if $function;
Branch: 1 branch
BranchTrueFalseTotal
if $function 86 0 86
806  
807 86 ▶ $function->remove_child( $worker ) if $function and $worker->{remove_on_idle};
Branch: 1 branch
BranchTrueFalseTotal
if $function and $worker->{"remove_on_idle"} 10 76 86
Condition66%2/3
$function and $worker->{"remove_on_idle"}
!ll&&!rl&&r
07610
MC/DC50%1/2
$function and $worker->{"remove_on_idle"}
$function $worker->{"remove_on_idle"}
Truth table66%2/3
A and B
A= $functionB= $worker->{"remove_on_idle"}
ABresult
0X0
100
111
808 86 }));
809 }
810  
811 =head1 EXAMPLES
812  
813 =head2 Extended Error Information on Failure
814  
815 The array-unpacking form of exception indiciation allows the function body to
816 more precicely control the resulting failure from the C<call> future.
817  
818 my $divider = IO::Async::Function->new(
819 code => sub {
820 my ( $numerator, $divisor ) = @_;
821 $divisor == 0 and
822 die [ "Cannot divide by zero", div_zero => $numerator, $divisor ];
823  
824 return $numerator / $divisor;
825 }
826 );
827  
828 =head1 NOTES
829  
830 For the record, 123454321 is 11111 * 11111, a square number, and therefore not
831 prime.
832  
833 =head1 AUTHOR
834  
835 Paul Evans <leonerd@leonerd.org.uk>
836  
837 =cut
838  
839 10 0x55AA;
« blib/lib/IO/Async/Handle.pm ↑ Summary blib/lib/IO/Async/Socket.pm »