Workflow/Pipeline.pm

filter: Statementstmt 100% 115 / 115 Branchbran 87.5% 21 / 24 Conditioncond 100% 3 / 3 MC/DCmcdc 100% 2 / 2 Subroutinesub 100% 19 / 19 Podpod 100% 5 / 5 totaltotal 98.2% 165 / 168 CC 15 SCAR 10.4
CC
15
Cov
98%
push_input
6.0
append_stage
4.0
__ANON__
4.0
CRAP 2.8
↑ Summary Workflow.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, 2021-2024 -- 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 6 ▶use Object::Pad 0.800;
Subroutine BEGIN: called CC=1 SCAR=0.0
9  
10 package Future::Workflow::Pipeline 0.02;
11 class Future::Workflow::Pipeline;
12  
13 6 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
14  
15 6 ▶use Future::AsyncAwait;
Subroutine BEGIN: called CC=1 SCAR=0.0
16  
17 =head1 NAME
18  
19 C<Future::Workflow::Pipeline> - a pipeline of processing stages
20  
21 =head1 SYNOPSIS
22  
23 =for highlighter language=perl
24  
25 # 1: Make a pipeline
26 my $pipeline = Future::Workflow::Pipeline->new;
27  
28  
29 # 2: Add some stages to it
30
31 # An async stage; e.g. perform an HTTP fetch
32 my $ua = Net::Future::HTTP->new;
33 $pipeline->append_stage_async( async sub ($url) {
34 return await $ua->GET( $url );
35 });
36  
37 # A synchronous (in-process) stage; e.g. some HTML parsing
38 $pipeline->append_stage_sync( sub ($response) {
39 my $dom = Mojo::DOM->new( $response->decoded_content );
40 return $dom->at('div[id="main"]')->text;
41 });
42  
43 # A detached (out-of-process/thread) stage; e.g. some silly CPU-intensive task
44 $pipeline->append_stage_detached( sub ($text) {
45 my $iter = Algorithm::Permute->new([ split m/\s+/, $text ]);
46  
47 my $best; my $bestscore;
48 while(my @words = $iter->next) {
49 my $str = join "\0", @words;
50 my $score = md5sum( $str );
51 next if defined $bestscore and $score ge $bestscore;
52  
53 $best = $str;
54 $bestscore = $score;
55 }
56  
57 return $best;
58 });
59  
60  
61 # 3: Give it an output
62  
63 # These are alternatives:
64  
65 # An asynchronous output
66 my $dbh = Database::Async->new( ... );
67 $pipeline->set_output_async( async sub ($best) {
68 await $dbh->do('INSERT INTO Results VALUES (?)', $best);
69 });
70  
71 # A synchronous output
72 $pipeline->set_output_sync( sub ($best) {
73 print "MD5 minimized sort order is:\n";
74 print " $_\n" for split m/\0/, $best;
75 });
76  
77  
78 # 4: Now start it running on some input values
79  
80 foreach my $url (slurp_lines("urls.txt")) {
81 await $pipeline->push_input($url);
82 }
83  
84  
85 # 5: Wait for it all to finish
86 await $pipeline->drain;
87  
88 =head1 DESCRIPTION
89  
90 Instances of this class implement a "pipeline", a sequence of data-processing
91 stages. Each stage is represented by a function that is passed a single
92 argument and should return a result. The pipeline itself stores a function
93 that will be passed each eventual result.
94  
95 =head2 Queueing
96  
97 In front of every stage there exists a queue of pending items. If the first
98 stage is currently busy when C</push_input> is called, the item is accepted
99 into its queue instead. Items will be taken from the queue in the order they
100 were pushed when the stage's work function finishes with prior items.
101  
102 If the queue between stages is full, then items will remain pending in prior
103 stages. Ultimately this back-pressure will make its way back to the
104 C</push_input> method at the beginning of the pipeline.
105  
106 =cut
107  
108 =head1 CONSTRUCTOR
109  
110 $pipeline = Future::Workflow::Pipeline->new;
111  
112 The constructor takes no additional parameters.
113  
114 =cut
115  
116 6 field $_output;
117 6 field @_stages;
118  
119 =head1 METHODS
120  
121 =cut
122  
123 =head2 set_output
124  
125 $pipeline->set_output( $code );
126  
127 await $code->( $result );
128  
129 Sets the destination output for the pipeline. Each completed work item will be
130 passed to the invoked function, which is expected to return a C<Future>.
131  
132 =cut
133  
134 12 ▶method set_output ( $code )
Subroutine set_output: called CC=2 SCAR=7.0
Pod documented
135 {
136 12 $_output = $code;
137 12 ▶ $_stages[-1]->set_output( $_output ) if @_stages;
Branch: 1 branch
BranchTrueFalseTotal
if @_stages 0 12 12
138 6 }
139  
140 =head2 set_output_sync
141  
142 $pipeline->set_output_sync( $code );
143  
144 $code->( $result );
145  
146 Similar to L</set_output>, where the output function is called synchronously,
147 returning when it has finished.
148  
149 =cut
150  
151 3 ▶method set_output_sync ( $code )
Subroutine set_output_sync: called CC=1 SCAR=0.0
Pod documented
152 {
153 3 ▶ $self->set_output( async sub ( $result ) { $code->( $result ) } );
Subroutine __ANON__: called CC=1 SCAR=0.0
154 6 }
155  
156 =head2 append_stage
157  
158 $pipeline->append_stage( $code, %args );
159  
160 $result = await $code->( $item );
161  
162 Appends a pipeline stage that is implemented by an asynchronous function. Each
163 work item will be passed in by invoking the function, and it is expected to
164 return a C<Future> which will eventually yield the result of that stage.
165  
166 The following optional named args are recognised:
167  
168 =over 4
169  
170 =item concurrent => NUM
171  
172 Allow this number of outstanding items concurrently.
173  
174 =item max_queue => NUM
175  
176 If defined, no more than this number of items can be enqueued. If undefined,
177 no limit is applied.
178  
179 This value can be zero, which means that any attempts to push more items will
180 remain pending until the work function is free to deal with it; i.e. no
181 queueing will be permitted.
182  
183 =item on_failure => CODE
184  
185 $on_failure->( $f )
186  
187 Provides a callback event function for handling a failure thrown by the stage
188 code. If not provided, the default behaviour is to print the failure message
189 as a warning.
190  
191 Note that this handler cannot turn a failure into a successful result or
192 otherwise resume or change behaviour of the pipeline. For error-correction you
193 will have to handle that inside the stage function code itself. This handler
194 is purely the last stop of error handling, informing the user of an
195 otherwise-unhandled error before ignoring it.
196  
197 =back
198  
199 =cut
200  
201 13 ▶method append_stage ( $code, %args )
Subroutine append_stage: called CC=4 SCAR=13.9
Pod documented
202 {
203 13 ▶ my $old_tail = @_stages ? $_stages[-1] : undef;
Branch: 1 branch
BranchTrueFalseTotal
@_stages ? : 3 10 13
204  
205 13 push @_stages, my $new_tail = Future::Workflow::Pipeline::_Stage->new(
206 code => $code,
207 %args,
208 );
209 13 ▶ $new_tail->set_output( $_output ) if $_output;
Branch: 1 branch
BranchTrueFalseTotal
if $_output 13 0 13
210  
211 4 ▶ $old_tail->set_output( async sub ( $item ) {
Subroutine __ANON__: called CC=1 SCAR=0.0
212 4 await $new_tail->push_input( $item );
213 13 ▶ } ) if $old_tail;
Branch: 1 branch
BranchTrueFalseTotal
if $old_tail 3 10 13
214 6 }
215  
216 =head2 append_stage_sync
217  
218 $pipeline->append_stage_sync( $code, %args );
219  
220 $result = $code->( $item );
221  
222 Similar to L</append_stage>, where the stage function is called synchronously,
223 returning its result immediately.
224  
225 Because of this, the C<concurrent> named parameter is not permitted.
226  
227 =cut
228  
229 2 ▶method append_stage_sync ( $code, %args )
Subroutine append_stage_sync: called CC=2 SCAR=6.9
Pod documented
230 {
231 defined $args{concurrent} and
232 2 ▶ croak "->append_stage_sync does not permit the 'concurrent' parameter";
Branch: 1 branch
BranchTrueFalseTotal
defined $args{"concurrent"} and croak("->append_stage_sync does not permit the 'concurrent' parameter") 0 2 2
233  
234 2 return $self->append_stage(
235 2 ▶ async sub ( $item ) { return $code->( $item ) },
Subroutine __ANON__: called CC=1 SCAR=0.0
236 %args,
237 );
238 6 }
239  
240 =head2 push_input
241  
242 await $pipeline->push_input( $item );
243  
244 Adds a new work item into the pipeline, which will pass through each of the
245 stages and eventually invoke the output function.
246  
247 =cut
248  
249 25 ▶async method push_input ( $item )
Subroutine push_input: called CC=2 SCAR=6.9
Pod documented
250 25 {
251 # TODO: this feels like a weird specialcase for no stages
252 25 ▶ if( @_stages ) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_stages) { } 21 4 25
253 21 await $_stages[0]->push_input( $item );
254 }
255 else {
256 4 await $_output->( $item );
257 }
258 6 }
259  
260 class Future::Workflow::Pipeline::_Stage :strict(params) {
261  
262 6 ▶ use Future;
Subroutine BEGIN: called CC=1 SCAR=0.0
263  
264 6 field $_code :param;
265 16 ▶ field $_output :writer;
Subroutine set_output: called CC=1 SCAR=0.0
266  
267 field $_on_failure :param = sub ( $f ) {
268 warn "Pipeline stage failed: ", scalar $f->failure;
269 };
270  
271 # $_concurrent == maximum size of @_work_f
272 6 field $_concurrent :param = 1;
273 6 field @_work_f;
274  
275 # $_max_queue == maximum size of @_queue, or undef for unbounded
276 field $_max_queue :param = undef;
277 6 field @_queue;
278  
279 6 field @_awaiting_input;
280  
281 23 ▶ async method _do ( $item )
Subroutine _do: called CC=1 SCAR=0.0
282 23 {
283 23 await $_output->( await $_code->( $item ) );
284 6 }
285  
286 23 ▶ method _schedule ( $item, $i )
Subroutine _schedule: called CC=1 SCAR=0.0
287 {
288 23 my $f = $_work_f[$i] = $self->_do( $item );
289 21 ▶ $f->on_ready( sub ( $f ) {
Subroutine __ANON__: called CC=4 SCAR=13.9
290 21 ▶ $_on_failure->( $f ) if $f->is_failed;
Branch: 1 branch
BranchTrueFalseTotal
if $f->is_failed 2 19 21
291  
292 21 ▶ if( @_queue ) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_queue) { } 5 16 21
293 5 $self->_schedule( shift @_queue, $i );
294 5 ▶ ( shift @_awaiting_input )->done if @_awaiting_input;
Branch: 1 branch
BranchTrueFalseTotal
if @_awaiting_input 1 4 5
295 }
296 else {
297 16 undef $_work_f[$i];
298 }
299 23 } );
300 6 }
301  
302 25 ▶ async method push_input ( $item )
Subroutine push_input: called CC=6 SCAR=17.9
303 25 {
304 25 my $i;
305 defined $_work_f[$_] or ( $i = $_ ), last
306 25 ▶ for 0 .. $_concurrent-1;
Branch: 1 branch
BranchTrueFalseTotal
defined $_work_f[$_] or $i = $_, last 10 18 28
307  
308 25 ▶ if( defined $i ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $i) { } 18 7 25
309 18 $self->_schedule( $item, $i );
310 }
311 else {
312 7 ▶ if( defined $_max_queue and @_queue >= $_max_queue ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $_max_queue and @_queue >= $_max_queue) 3 4 7
Condition100%3/3
defined $_max_queue and @_queue >= $_max_queue
!ll&&!rl&&r
223
MC/DC100%2/2
defined $_max_queue and @_queue >= $_max_queue
defined $_max_queue @_queue >= $_max_queue
Truth table100%3/3
A and B
A= defined $_max_queueB= @_queue >= $_max_queue
ABresult
0X0
100
111
313 # TODO: Maybe we should clone one of the work futures?
314 3 push @_awaiting_input, my $enqueue_f = Future->new;
315 3 await $enqueue_f;
316 }
317 5 push @_queue, $item;
318 }
319 6 }
320 }
321  
322 6 =head1 UNSOLVED QUESTIONS
323  
324 =over 4
325  
326 =item *
327  
328 Is each work item represented by some object that gets passed around?
329  
330 Can we store context, maybe in a hash or somesuch, that each stage can inspect
331 and append more things into? It might be useful to remember at least the
332 initial URLs by the time we generate the outputs
333  
334 =item *
335  
336 Tuning parameters. In particular, being able to at least set overall
337 concurrency of C<async> and C<detached> stages, the detachment model of the
338 C<detached> stages (threads vs. forks), inter-stage buffering?
339  
340 =back
341  
342 =cut
343  
344 =head1 AUTHOR
345  
346 Paul Evans <leonerd@leonerd.org.uk>
347  
348 =cut
349  
350 6 0x55AA;
↑ Summary Workflow.pm »