Mojo/IOLoop/Subprocess.pm

filter: Statementstmt 30.8% 25 / 81 Branchbran 0.0% 0 / 16 Conditioncond 0.0% 0 / 10 MC/DCmcdc 0.0% 0 / 6 Subroutinesub 33.3% 7 / 21 Podpod 100% 5 / 5 totaltotal 26.6% 37 / 139 CC 13 SCAR 28.0
CC
13
Cov
23%
_start
56.0
__ANON__
20.0
__ANON__
12.0
CRAP 16.5
« Mojo/DOM/CSS.pm ↑ Summary Mojo/IOLoop/Server.pm »
1 package Mojo::IOLoop::Subprocess;
2 33 ▶use Mojo::Base 'Mojo::EventEmitter';
Subroutine BEGIN: called CC=1 SCAR=0.0
3  
4 33 ▶use Config;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 33 ▶use Mojo::IOLoop;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 33 ▶use Mojo::IOLoop::Stream;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 33 ▶use Mojo::JSON;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 33 ▶use Mojo::Promise;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 33 ▶use POSIX ();
Subroutine BEGIN: called CC=1 SCAR=0.0
10  
11 0 ▶has deserialize => sub { \&Mojo::JSON::decode_json };
Subroutine __ANON__: not called CC=1 SCAR=1.2
12 0 ▶has ioloop => sub { Mojo::IOLoop->singleton }, weak => 1;
Subroutine __ANON__: not called CC=1 SCAR=1.2
13 0 ▶has serialize => sub { \&Mojo::JSON::encode_json };
Subroutine __ANON__: not called CC=1 SCAR=1.2
14  
15 0 ▶sub exit_code { shift->{exit_code} }
Subroutine exit_code: not called CC=1 SCAR=6.9
Pod documented
16  
17 0 ▶sub pid { shift->{pid} }
Subroutine pid: not called CC=1 SCAR=6.9
Pod documented
18  
19 0 ▶sub run {
Subroutine run: not called CC=1 SCAR=6.9
Pod documented
20 0 my ($self, @args) = @_;
21 0 ▶ $self->ioloop->next_tick(sub { $self->_start(@args) });
Subroutine __ANON__: not called CC=1 SCAR=6.9
22 0 return $self;
23 }
24  
25 0 ▶sub run_p {
Subroutine run_p: not called CC=1 SCAR=6.9
Pod documented
26 0 my ($self, $child) = @_;
27  
28 0 my $p = Mojo::Promise->new;
29 0 ▶ my $parent = sub {
Subroutine __ANON__: not called CC=2 SCAR=17.9
30 0 my ($self, $err) = (shift, shift);
31 0 ▶ $err ? $p->reject($err) : $p->resolve(@_);
Branch: 1 branch
BranchTrueFalseTotal
$err ? : 0 0 0
32 0 };
33 0 ▶ $self->ioloop->next_tick(sub { $self->_start($child, $parent) });
Subroutine __ANON__: not called CC=1 SCAR=6.9
34  
35 0 return $p;
36 }
37  
38 0 ▶sub _start {
Subroutine _start: not called CC=7 SCAR=40.3
39 0 my ($self, $child, $parent) = @_;
40  
41 # No fork emulation support
42 0 ▶ return $self->$parent('Subprocesses do not support fork emulation') if $Config{d_pseudofork};
Branch: 1 branch
BranchTrueFalseTotal
if $Mojo::IOLoop::Subprocess::Config{"d_pseudofork"} 0 0 0
43  
44 # Pipe for subprocess communication
45 0 ▶ return $self->$parent("Can't create pipe: $!") unless pipe(my $reader, $self->{writer});
Branch: 1 branch
BranchTrueFalseTotal
unless pipe my $reader, $self->{"writer"} 0 0 0
46 0 $self->{writer}->autoflush(1);
47  
48 # Child
49 0 ▶ return $self->$parent("Can't fork: $!") unless defined(my $pid = $self->{pid} = fork);
Branch: 1 branch
BranchTrueFalseTotal
unless defined(my $pid = $self->{"pid"} = fork) 0 0 0
50 0 ▶ unless ($pid) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($pid) 0 0 0
51 0 ▶ eval {
Branch: 1 branch
BranchTrueFalseTotal
eval { do { $self->ioloop->reset({"freeze", 1}); my $results = eval { do { [$self->$child] } } // []; print {$self->{"writer"};} "0-", $self->serialize->([$@, @$results]); $self->emit("cleanup") } } or warn $@ 0 0 0
52 0 $self->ioloop->reset({freeze => 1});
53 0 ▶ my $results = eval { [$self->$child] } // [];
Condition0%0/2
eval { do { [$self->$child] } } // []
l!l
00
MC/DC0%0/1
eval { do { [$self->$child] } } // []
eval { do { [$self->$child] } }
Truth table0%0/2
A
A= eval { do { [$self->$child] } }
Aresult
11
00
54 0 print {$self->{writer}} '0-', $self->serialize->([$@, @$results]);
55 0 $self->emit('cleanup');
56 } or warn $@;
57 0 POSIX::_exit(0);
58 }
59  
60 # Parent
61 0 my $me = $$;
62 0 close $self->{writer};
63 0 my $stream = Mojo::IOLoop::Stream->new($reader)->timeout(0);
64 0 $self->emit('spawn')->ioloop->stream($stream);
65 0 my $buffer = '';
66 $stream->on(
67 0 ▶ read => sub {
Subroutine __ANON__: not called CC=3 SCAR=24.8
68 0 $buffer .= pop;
69 0 while (1) {
70 0 my ($len) = $buffer =~ /^([0-9]+)\-/;
71 0 ▶ last unless $len and length $buffer >= $len + $+[0];
Branch: 1 branch
BranchTrueFalseTotal
unless $len and length $buffer >= $len + $+[0] 0 0 0
Condition0%0/3
$len and length $buffer >= $len + $+[0]
!ll&&!rl&&r
000
MC/DC0%0/2
$len and length $buffer >= $len + $+[0]
$len length $buffer >= $len + $+[0]
Truth table0%0/3
A and B
A= $lenB= length $buffer >= $len + $+[0]
ABresult
0X0
100
111
72 0 my $snippet = substr $buffer, 0, $len + $+[0], '';
73 0 my $args = $self->deserialize->(substr $snippet, $+[0]);
74 0 $self->emit(progress => @$args);
75 }
76 }
77 0 );
78 $stream->on(
79 0 ▶ close => sub {
Subroutine __ANON__: not called CC=4 SCAR=30.0
80 0 ▶ return unless $$ == $me;
Branch: 1 branch
BranchTrueFalseTotal
unless $$ == $me 0 0 0
81 0 waitpid $pid, 0;
82 0 $self->{exit_code} = $? >> 8;
83 0 substr $buffer, 0, 2, '';
84 0 ▶ my $results = eval { $self->deserialize->($buffer) } // [];
Condition0%0/2
eval { do { $self->deserialize->($buffer) } } // []
l!l
00
MC/DC0%0/1
eval { do { $self->deserialize->($buffer) } } // []
eval { do { $self->deserialize->($buffer) } }
Truth table0%0/2
A
A= eval { do { $self->deserialize->($buffer) } }
Aresult
11
00
85 0 ▶ $self->$parent(shift(@$results) // $@, @$results);
Condition0%0/3
shift @$results // $@
l!l&&r!l&&!r
000
MC/DC0%0/2
shift @$results // $@
shift @$results $@
Truth table0%0/3
A // B
A= shift @$resultsB= $@
ABresult
1X1
011
000
86 }
87 0 );
88 }
89  
90 0 ▶sub progress {
Subroutine progress: not called CC=1 SCAR=6.9
Pod documented
91 0 my ($self, @args) = @_;
92 0 my $serialized = $self->serialize->(\@args);
93 0 print {$self->{writer}} length($serialized), '-', $serialized;
94 }
95  
96 33 1;
97  
98 =encoding utf8
99  
100 =head1 NAME
101  
102 Mojo::IOLoop::Subprocess - Subprocesses
103  
104 =head1 SYNOPSIS
105  
106 use Mojo::IOLoop::Subprocess;
107  
108 # Operation that would block the event loop for 5 seconds
109 my $subprocess = Mojo::IOLoop::Subprocess->new;
110 $subprocess->run(
111 sub ($subprocess) {
112 sleep 5;
113 return '♥', 'Mojolicious';
114 },
115 sub ($subprocess, $err, @results) {
116 say "Subprocess error: $err" and return if $err;
117 say "I $results[0] $results[1]!";
118 }
119 );
120  
121 # Operation that would block the event loop for 5 seconds (with promise)
122 $subprocess->run_p(sub {
123 sleep 5;
124 return '♥', 'Mojolicious';
125 })->then(sub (@results) {
126 say "I $results[0] $results[1]!";
127 })->catch(sub {
128 my $err = shift;
129 say "Subprocess error: $err";
130 });
131  
132 # Start event loop if necessary
133 $subprocess->ioloop->start unless $subprocess->ioloop->is_running;
134  
135 =head1 DESCRIPTION
136  
137 L<Mojo::IOLoop::Subprocess> allows L<Mojo::IOLoop> to perform computationally expensive operations in subprocesses,
138 without blocking the event loop.
139  
140 =head1 EVENTS
141  
142 L<Mojo::IOLoop::Subprocess> inherits all events from L<Mojo::EventEmitter> and can emit the following new ones.
143  
144 =head2 cleanup
145  
146 $subprocess->on(cleanup => sub ($subprocess) {...});
147  
148 Emitted in the subprocess right before the process will exit.
149  
150 $subprocess->on(cleanup => sub ($subprocess) { say "Process $$ is about to exit" });
151  
152 =head2 progress
153  
154 $subprocess->on(progress => sub ($subprocess, @data) {...});
155  
156 Emitted in the parent process when the subprocess calls the L<progress|/"progress1"> method.
157  
158 =head2 spawn
159  
160 $subprocess->on(spawn => sub ($subprocess) {...});
161  
162 Emitted in the parent process when the subprocess has been spawned.
163  
164 $subprocess->on(spawn => sub ($subprocess) {
165 my $pid = $subprocess->pid;
166 say "Performing work in process $pid";
167 });
168  
169 =head1 ATTRIBUTES
170  
171 L<Mojo::IOLoop::Subprocess> implements the following attributes.
172  
173 =head2 deserialize
174  
175 my $cb = $subprocess->deserialize;
176 $subprocess = $subprocess->deserialize(sub {...});
177  
178 A callback used to deserialize subprocess return values, defaults to using L<Mojo::JSON>.
179  
180 $subprocess->deserialize(sub ($bytes) { return [] });
181  
182 =head2 ioloop
183  
184 my $loop = $subprocess->ioloop;
185 $subprocess = $subprocess->ioloop(Mojo::IOLoop->new);
186  
187 Event loop object to control, defaults to the global L<Mojo::IOLoop> singleton. Note that this attribute is weakened.
188  
189 =head2 serialize
190  
191 my $cb = $subprocess->serialize;
192 $subprocess = $subprocess->serialize(sub {...});
193  
194 A callback used to serialize subprocess return values, defaults to using L<Mojo::JSON>.
195  
196 $subprocess->serialize(sub ($array) { return '' });
197  
198 =head1 METHODS
199  
200 L<Mojo::IOLoop::Subprocess> inherits all methods from L<Mojo::EventEmitter> and implements the following new ones.
201  
202 =head2 exit_code
203  
204 my $code = $subprocess->exit_code;
205  
206 Returns the subprocess exit code, or C<undef> if the subprocess is still running.
207  
208 =head2 pid
209  
210 my $pid = $subprocess->pid;
211  
212 Process id of the spawned subprocess if available.
213  
214 =head2 progress
215  
216 $subprocess->progress(@data);
217  
218 Send data serialized with L<Mojo::JSON> to the parent process at any time during the subprocess's execution. Must be
219 called by the subprocess and emits the L</"progress"> event in the parent process with the data.
220  
221 # Send progress information to the parent process
222 $subprocess->run(
223 sub ($subprocess) {
224 $subprocess->progress('0%');
225 sleep 5;
226 $subprocess->progress('50%');
227 sleep 5;
228 return 'Hello Mojo!';
229 },
230 sub ($subprocess, $err, @results) {
231 say 'Progress is 100%';
232 say $results[0];
233 }
234 );
235 $subprocess->on(progress => sub ($subprocess, @data) { say "Progress is $data[0]" });
236  
237 =head2 run
238  
239 $subprocess = $subprocess->run(sub {...}, sub {...});
240  
241 Execute the first callback in a child process and wait for it to return one or more values, without blocking
242 L</"ioloop"> in the parent process. Then execute the second callback in the parent process with the results. The return
243 values of the first callback and exceptions thrown by it, will be serialized with L<Mojo::JSON>, so they can be shared
244 between processes.
245  
246 =head2 run_p
247  
248 my $promise = $subprocess->run_p(sub {...});
249  
250 Same as L</"run">, but returns a L<Mojo::Promise> object instead of accepting a second callback.
251  
252 $subprocess->run_p(sub {
253 sleep 5;
254 return '♥', 'Mojolicious';
255 })->then(sub (@results) {
256 say "I $results[0] $results[1]!";
257 })->catch(sub ($err) {
258 say "Subprocess error: $err";
259 })->wait;
260  
261 =head1 SEE ALSO
262  
263 L<Mojolicious>, L<Mojolicious::Guides>, L<https://mojolicious.org>.
264  
265 =cut
« Mojo/DOM/CSS.pm ↑ Summary Mojo/IOLoop/Server.pm »