Debian Codegraph @

lib/Test2/Harness/Runner/Preload.pm

raw
1 package Test2::Harness::Runner::Preload;
2 use strict;
3 use warnings;
4
5 our $VERSION = '1.000179';
6
7 use Carp qw/croak/;
8
9 use Test2::Harness::Runner::Preload::Stage();
10
11 sub import {
12 my $class = shift;
13 my $caller = caller;
14
15 my %exports;
16
17 my $instance = $class->new;
18
19 $exports{TEST2_HARNESS_PRELOAD} = sub { $instance };
20
21 $exports{stage} = sub {
22 my ($name, $code) = @_;
23 my @caller = caller();
24 $instance->build_stage(
25 name => $name,
26 code => $code,
27 caller => \@caller,
28 );
29 };
30
31 $exports{eager} = sub {
32 croak "No current stage" unless @{$instance->stack};
33 my $stage = $instance->stack->[-1];
34 $stage->set_eager(1);
35 };
36
37 $exports{default} = sub {
38 croak "No current stage" unless @{$instance->stack};
39 my $stage = $instance->stack->[-1];
40 my $name = $stage->name;
41 $instance->set_default_stage($name);
42 };
43
44 $exports{file_stage} = sub {
45 my ($callback) = @_;
46 my @caller = caller();
47 croak "'file_stage' cannot be used under a stage" if @{$instance->stack};
48 $instance->add_file_stage(\@caller, $callback);
49 };
50
51 for my $name (qw/pre_fork post_fork pre_launch/) {
52 my $meth = "add_${name}_callback";
53 $exports{$name} = sub {
54 croak "No current stage" unless @{$instance->stack};
55 my $stage = $instance->stack->[-1];
56 $stage->$meth(@_);
57 };
58 }
59
60 $exports{watch} = sub {
61 if (@{$instance->stack}) {
62 my $stage = $instance->stack->[-1];
63 return $stage->watch(@_);
64 }
65
66 if ($INC{'Test2/Harness/Runner/DepTracer.pm'}) {
67 if (my $active = Test2::Harness::Runner::DepTracer->ACTIVE) {
68 return $active->add_callback(@_);
69 }
70 }
71
72 croak "No current stage, and no active deptracer";
73 };
74
75 $exports{preload} = sub {
76 croak "No current stage" unless @{$instance->stack};
77 my $stage = $instance->stack->[-1];
78 $stage->add_to_load_sequence(@_);
79 };
80
81 $exports{reload_remove_check} = sub {
82 croak "No current stage" unless @{$instance->stack};
83 my $stage = $instance->stack->[-1];
84 $stage->set_reload_remove_check(@_);
85 };
86
87 $exports{reload_inplace_check} = sub {
88 croak "No current stage" unless @{$instance->stack};
89 my $stage = $instance->stack->[-1];
90 $stage->set_reload_inplace_check(@_);
91 };
92
93 for my $name (keys %exports) {
94 no strict 'refs';
95 *{"$caller\::$name"} = $exports{$name};
96 }
97 }
98
99 use Test2::Harness::Util::HashBase qw{
100 <stage_list
101 <stage_lookup
102 <stack
103 +default_stage
104 +file_stage
105 };
106
107 sub init {
108 my $self = shift;
109
110 $self->{+STAGE_LIST} //= [];
111 $self->{+STAGE_LOOKUP} //= {};
112
113 $self->{+STACK} //= [];
114
115 $self->{+FILE_STAGE} //= [];
116 }
117
118 sub build_stage {
119 my $self = shift;
120 my %params = @_;
121
122 my $caller = $params{caller} //= [caller()];
123
124 die "A coderef is required at $caller->[1] line $caller->[2].\n"
125 unless $params{code};
126
127 my $stage = Test2::Harness::Runner::Preload::Stage->new(
128 stage_lookup => $self->{+STAGE_LOOKUP},
129 %params,
130 );
131
132 my $stack = $self->{+STACK} //= [];
133 push @$stack => $stage;
134
135 my $ok = eval { $params{code}->($stage); 1 };
136 my $err = $@;
137
138 die "Mangled stack" unless @$stack && $stack->[-1] eq $stage;
139
140 pop @$stack;
141
142 die $err unless $ok;
143
144 if (@$stack) {
145 $stack->[-1]->add_child($stage);
146 }
147 else {
148 $self->add_stage($stage, $caller);
149 }
150
151 return $stage;
152 }
153
154 sub add_stage {
155 my $self = shift;
156 my ($stage, $caller) = @_;
157
158 $caller //= [caller()];
159
160 my @all = ($stage, @{$stage->all_children});
161
162 for my $item (@all) {
163 my $name = $item->name;
164
165 if (my $existing = $self->{+STAGE_LOOKUP}->{$name}) {
166 $caller //= [caller()];
167 my $ncaller = $item->frame;
168 my $ecaller = $existing->frame;
169 die <<" EOT"
170 A stage named '$name' was already defined.
171 First at $ecaller->[1] line $ecaller->[2].
172 Second at $ncaller->[1] line $ncaller->[2].
173 Mixed at $caller->[1] line $caller->[2].
174 EOT
175 }
176
177 $self->{+STAGE_LOOKUP}->{$name} = $item;
178 }
179
180 push @{$self->{+STAGE_LIST}} => $stage;
181 }
182
183 sub merge {
184 my $self = shift;
185 my ($merge) = @_;
186
187 my $caller = [caller()];
188
189 for my $stage (@{$merge->{+STAGE_LIST}}) {
190 $self->add_stage($stage, $caller);
191 }
192
193 push @{$self->{+FILE_STAGE}} => @{$merge->{+FILE_STAGE}};
194
195 $self->{+DEFAULT_STAGE} //= $merge->default_stage;
196 }
197
198 sub add_file_stage {
199 my $self = shift;
200 my ($caller, $code) = @_;
201
202 croak "Caller must be defined and an array" unless $caller && ref($caller) eq 'ARRAY';
203 croak "Code must be defined and a coderef" unless $code && ref($code) eq 'CODE';
204
205 push @{$self->{+FILE_STAGE}} => [$caller, $code];
206 }
207
208 sub file_stage {
209 my $self = shift;
210 my ($file) = @_;
211
212 for my $cb (@{$self->{+FILE_STAGE}}) {
213 my ($caller, $code) = @$cb;
214 my $stage = $code->($file) or next;
215
216 die "file_stage callback returned invalid stage: $stage at $caller->[1] line $caller->[2].\n"
217 unless $self->{+STAGE_LOOKUP}->{$stage};
218
219 return $stage;
220 }
221
222 return;
223 }
224
225 sub default_stage {
226 my $self = shift;
227 return $self->{+DEFAULT_STAGE} if $self->{+DEFAULT_STAGE};
228 return $self->{+STAGE_LIST}->[0];
229 }
230
231 sub set_default_stage {
232 my $self = shift;
233 my ($name) = @_;
234
235 croak "Default stage already set to $self->{+DEFAULT_STAGE}" if $self->{+DEFAULT_STAGE};
236 $self->{+DEFAULT_STAGE} = $name;
237 }
238
239 sub eager_stages {
240 my $self = shift;
241
242 my %eager;
243
244 for my $root (@{$self->{+STAGE_LIST}}) {
245 for my $stage ($root, @{$root->all_children}) {
246 next unless $stage->eager;
247 $eager{$stage->name} = [map { $_->name } @{$stage->all_children}];
248 }
249 }
250
251 return \%eager;
252 }
253
254 1;
255
256 __END__
257
258 =pod
259
260 =encoding UTF-8
261
262 =head1 NAME
263
264 Test2::Harness::Runner::Preload - DSL for building complex stage-based preload
265 tools.
266
267 =head1 DESCRIPTION
268
269 L<Test2::Harness> allows you to preload libraries for a performance boost. This
270 module provides tools that let you go beyond that and build a more complex
271 preload. In addition you can build multiple preload I<stages>, each stage will
272 be its own process and tests can run from a specific stage. This allows for
273 multiple different preload states from which to run tests.
274
275 =head1 SYNOPSIS
276
277 =head2 USING YOUR PRELOAD
278
279 The C<-P> or C<--preload> options work for custom preload modules just as they
280 do regular modules. Yath will know the difference and act accordingly.
281
282 yath test -PMy::Preload
283
284 =head2 WRITING YOUR PRELOAD
285
286 package My::Preload;
287 use strict;
288 use warnings;
289
290 # This imports several useful tools, and puts the necessary meta-data in
291 # your package to identify it as a special preload.
292 use Test2::Harness::Runner::Preload;
293
294 # You must specify at least one stage.
295 stage Moose => sub {
296 # Preload can be called multiple times, and can load multiple modules
297 # per call. Order is preserved.
298 preload 'Moose', 'Moose::Role';
299 preload 'Scalar::Util', 'List::Util';
300
301 # preload can also be given a sub if you have some custom code to run
302 # at a specific point in the load order
303 preload sub {
304 # Do something before loading Try::Tiny
305 ...
306 };
307
308 preload 'Try::Tiny';
309
310 # Tell the runner to watch this file for changes, if it does change run
311 # the sub instead of the usual reload process. This lets you reload
312 # configs and other non-perl files, or allows you to use a custom
313 # reload sub for perl files.
314 watch 'path/to/file' => sub { ... };
315
316 # You can also use watch inside preload subs:
317 preload sub {
318 watch 'path/to/file' => sub { ... };
319 };
320
321 # In app code you can add watches dynamically when applicable:
322 preload sub {
323 ... # inside app code
324
325 if ($INC{'Test2/Harness/Runner/DepTracer.pm'}) {
326 if (my $active = Test2::Harness::Runner::DepTracer->ACTIVE) {
327 $active->add_callback('path/to/file' => sub { ... });
328 }
329 }
330
331 ...
332 };
333
334 # Eager means tests from nested stages can be run in this stage as
335 # well, this is useful if the nested stage takes a long time to load as
336 # it allows yath to start running tests sooner instead of waiting for
337 # the stage to finish loading. Once the nested stage is loaded tests
338 # intended for it will start running from it instead.
339 eager();
340
341 # default means this stage is the one to use if the test does not
342 # specify a stage.
343 default();
344
345 # These are hooks that let you run arbitrary code at specific points in
346 # the process. pre_fork happens just before forking to run a test.
347 # post_fork happens just after forking for a test. pre_launch happens
348 # as late as possible before the test starts executing (post fork,
349 # after $0 and other special state are reset).
350 pre_fork sub { ... };
351 post_fork sub { ... };
352 pre_launch sub { ... };
353
354 # Stages can be nested, nested ones build off the previous stage, but
355 # are in a forked process to avoid contaminating the parent.
356 stage Types => sub {
357 preload 'MooseX::Types';
358 };
359 };
360
361 # Alternative stage that loads Moo instead of Moose
362 stage Moo => sub {
363 preload 'Moo';
364
365 ...
366 };
367
368 =head2 HARNESS DIRECTIVES IN PRELOADS
369
370 If you use a staged preload, and the --reload option, you can add 'CHURN'
371 directives to files in order to only reload sections you are working on. This
372 is particularly useful when a file cannot be reloaded in full, or when doing so
373 is expensive. You can wrap subroutines in the churn directives to have yath
374 reload only those subroutines.
375
376 sub do_not_reload_this { ... {
377
378 # HARNESS-CHURN-START
379
380 sub reload_this_one {
381 ...
382 }
383
384 sub reload_this_one_too {
385 ...
386 }
387
388 # HARNESS-CHURN-STOP
389
390 sub this_is_not_reloaded { ... }
391
392 You can put as many churn sections you want in as many preloaded modules as you
393 want. If a change is detected then only the churn sections will be reloaded.
394 The churn sections are reloaded by taking the source between the start and stop
395 markers, and running them in an eval like this:
396
397 eval <<EOT
398 package MODULE_FROM_FILENAME;
399 use strict;
400 use warnings;
401 no warnings 'redefine';
402 #line $line_number $file
403 $YOUR_CODE
404 ;1;
405 EOT
406
407 In most cases this is sufficient to replace the old sub with the new one. If
408 the automatically determined package is not correct you can add a C<package
409 FOO;> statement inside the markers. If the strict/warnings settings are not to
410 your specifications you can add overrides inside the markers. Any valid perl
411 code can go into the markers.
412
413 B<CAVEATS:> Be aware they do not have their original scope, and that can lead
414 to problems if you are not paying attention. Variables outside your markers are
415 not accessible, and lexical variables put inside your markers will be "new" on
416 each reload, this can cause confusion if you have lexicals used by multiple
417 subs where some are inside churn blocks and others are not, so best not to do
418 that. Package variables work a bit better, but any assignment lines are re-run.
419 So C<our $FOO;> is fine (it does not change the value if it is set) but
420 C<our $FOO = ...> will reset the var on each reload.
421
422 =head1 EXPORTS
423
424 =over 4
425
426 =item $meta = TEST2_HARNESS_PRELOAD()
427
428 =item $meta = $class->TEST2_HARNESS_PRELOAD()
429
430 This export provides the meta object, which is an instance of this class. This
431 method being present is how Test2::Harness differentiates between a regular
432 module and a special preload library.
433
434 =item stage NAME => sub { ... }
435
436 This creates a new stage with the given C<NAME>, and then runs the coderef with
437 the new stage set as the I<active> one upon which the other function here will
438 operate. Once the coderef returns the I<active> stage is cleared.
439
440 You may nest stages by calling this function again inside the codeblock.
441
442 B<NOTE:> stage names B<ARE> case sensitive. This can be confusing when you
443 consider that most harness directives are all-caps. In the following case the
444 stage requested by the test and the stage defined in
445 the library are NOT the same.
446
447 In a test file:
448
449 # HARNESS-STAGE-FOO
450
451 In a preload library:
452
453 stage foo { ... }
454
455 Harness directives are all-caps, however the user data portion need not be,
456 this is fine:
457
458 # HARNESS-STAGE-foo
459
460 However it is very easy to make the mistake of thinking it is case insensitive.
461 It is also easy to assume the 'foo' part of the harness directive must be all
462 caps. In many cases it is smart to make your stage names all-caps.
463
464 =item preload $module_name
465
466 =item preload @module_names
467
468 =item preload sub { ... }
469
470 This B<MUST> be called inside a C<stage()> builder coderef.
471
472 This adds modules to the list of libraries to preload. Order is preserved. You
473 can also add coderefs to execute arbitrary code between module loads.
474
475 The coderef is called with no arguments, and its return is ignored.
476
477 =item eager()
478
479 This B<MUST> be called inside a C<stage()> builder coderef.
480
481 This marks the I<active> stage as being I<eager>. An eager stage will start
482 running tests for nested stages if it finds itself with no tests of its own to
483 run before the nested stage can finish loading. The idea here is to avoid
484 unused test slots when possible allowing for tests to complete sooner.
485
486 =item default()
487
488 This B<MUST> be called inside a C<stage()> builder coderef.
489
490 This B<MUST> be called only once across C<ALL> stages in a given library.
491
492 If multiple preload libraries are loaded then the I<first> default set (based
493 on load order) will be the default, others will not be honored.
494
495 =item $stage_name = file_stage($test_file)
496
497 This is optional. If defined this callback will have a chance to look at all
498 files that are going to be run and assign them a stage. This may return undef
499 or an empty list if it does not have a stage to assign.
500
501 If multiple preload libraries define file_stage callbacks they will be called
502 in order, the first one to return a stage name will win.
503
504 If no file_stage callbacks provide a stage for a file then any harness
505 directives declaring a stage will be honored. If no stage is ever assigned then
506 the test will be run int he default stage.
507
508 =item pre_fork sub { ... }
509
510 This B<MUST> be called inside a C<stage()> builder coderef.
511
512 Add a callback to be run just before the preload-stage process forks to run the
513 test. Note that any state changes here can effect future tests to be run.
514
515 =item post_fork sub { ... }
516
517 This B<MUST> be called inside a C<stage()> builder coderef.
518
519 Add a callback to be run just after the preload-stage process forks to run the
520 test. This is run as early as possible, things like C<$0> may not be set
521 properly yet.
522
523 =item pre_launch sub { ... }
524
525 This B<MUST> be called inside a C<stage()> builder coderef.
526
527 Add a callback to be run just before control of the test process is turned over
528 to the test file itself. This is run as late as possible, so things like C<$0>
529 should be set properly.
530
531 =back
532
533 =head1 META-OBJECT
534
535 This class is also the meta-object used to construct a preload library. The
536 methods are left undocumented as this is an implementation detail and you are
537 not intended to directly use this object.
538
539 =head1 SOURCE
540
541 The source code repository for Test2-Harness can be found at
542 F<http://github.com/Test-More/Test2-Harness/>.
543
544 =head1 MAINTAINERS
545
546 =over 4
547
548 =item Chad Granum E<lt>[email protected]<gt>
549
550 =back
551
552 =head1 AUTHORS
553
554 =over 4
555
556 =item Chad Granum E<lt>[email protected]<gt>
557
558 =back
559
560 =head1 COPYRIGHT
561
562 Copyright 2020 Chad Granum E<lt>[email protected]<gt>.
563
564 This program is free software; you can redistribute it and/or
565 modify it under the same terms as Perl itself.
566
567 See F<http://dev.perl.org/licenses/>
568
569 =cut