blib/lib/Evented/API/Engine.pm untested

filter: Statementstmt 0.0% 0 / 409 Branchbran 0.0% 0 / 154 Conditioncond 0.0% 0 / 93 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 41 Podpod 0.0% 0 / 28 totaltotal 0.0% 0 / 725 CC 78 SCAR 50.7
CC
78
Cov
0%
_get_module_info
462.0
load_module
342.0
unload_module
110.0
CRAP 158.7
1 # Copyright (c) 2017, Mitchell Cooper
2 #
3 # the Evented API Engine is in charge of loading and unloading modules.
4 # it also handles dependencies and feature availability.
5 #
6 package Evented::API::Engine;
7  
8 use warnings;
9 use strict;
10 use 5.010;
11  
12 use JSON::XS;
13 use Scalar::Util qw(weaken blessed);
14 use Module::Loaded qw(mark_as_loaded mark_as_unloaded is_loaded);
15 use Evented::Object;
16 use parent 'Evented::Object';
17  
18 our $VERSION = '4.07';
19  
20 use Evented::API::Module;
21 use Evented::API::Events;
22 use Evented::Object::Hax qw(set_symbol make_child);
23  
24 =head1 NAME
25  
26 B<Evented::API::Engine> - an Evented API Engine for Perl applications.
27  
28 =head1 SYNOPSIS
29  
30 Main
31  
32 my $api = Evented::API::Engine->new;
33 $api->load_module('My::Module');
34  
35 My::Module
36  
37 # Module metadata
38 #
39 # @name: 'My::Module'
40 # @package: 'M::My::Module'
41 # @description:
42 #
43 # @depends.modules+ 'Some::Other'
44 # @depends.modules+ 'Another::Yet'
45 #
46 # @author.name: 'Mitchell Cooper'
47 # @author.website: 'https://github.com/cooper'
48 #
49 package M::My::Module;
50
51 use warnings;
52 use strict;
53 use 5.010;
54
55 # Auto-exported variables
56 our ($api, $mod);
57
58 # Default initializer
59 sub init {
60 say 'Loading ', $mod->name;
61
62 # indicates load success
63 return 1;
64 }
65
66 # Default deinitializer
67 sub void {
68 say 'Bye!';
69
70 # indicates unload success
71 return 1;
72 }
73
74 # Package must return module object
75 $mod;
76  
77 =head1 DESCRIPTION
78  
79 Perl provides a simple way to load dependencies. But what about upgrading or
80 unloading? API Engine makes it easy to create an excessively versatile Perl
81 application capable of adapting dynamically with the user's ever-changing needs.
82  
83 =head2 Module management
84  
85 Modules are Perl packages which can be easily loaded, unloaded, and reloaded.
86 API Engine automatically tracks the changes made by each module and reverts them
87 upon unload, leaving no trace. With API Engine used properly, it is even
88 possible to reload your entire program without restarting it.
89  
90 Modules themselves can determine the necessity of additional code which may be
91 dynamically added and removed through the use of submodules.
92  
93 =head2 Dependency resolution
94  
95 API Engine automatically resolves dependencies of both modules and normal Perl
96 packages. It loads and unloads dependencies in the proper order. It is also
97 possible to specify that a submodule is automatically loaded and unloaded in
98 conjunction with some top-level module.
99  
100 =head2 Event management
101  
102 API Engine is I<Evented> in that it tracks all
103 L<Evented::Object> callbacks attached
104 from within modules and automatically removes them upon unloading. This allows
105 you to employ events excessively without constantly worrying about their
106 eventual disposal.
107  
108 =head1 METHODS
109  
110 =head2 Evented::API::Engine->new(%opts)
111  
112 Creates a new instance of the Evented API Engine. This single object will be
113 used throughout the life of the application.
114  
115 my $api = Evented::API::Engine->new(
116 mod_inc => [ 'mod', '/usr/share/something/mod' ],
117 features => [ qw(io-async something-else) ],
118 modules => [ $conf->keys_for_block('modules') ]
119 );
120  
121 B<Parameters>
122  
123 =over
124  
125 =item *
126  
127 B<%opts>: a package whose event activity you're monitoring.
128  
129 =back
130  
131 B<%opts> - constructor options
132  
133 =over
134  
135 =item *
136  
137 B<\@mod_inc> - list of module search directories
138  
139 =item *
140  
141 B<\@features> - I<optional>, list of feature names to enable immediately
142  
143 =item *
144  
145 B<\@modules> - I<optional>, list of names of toplevel modules to load immediately
146  
147 =item *
148  
149 B<\&log_sub> - I<optional>, code to be called for API Engine log messages
150  
151 =item *
152  
153 B<$developer> - I<optional>, if true, module info will be written to JSON
154 metadata files. your program should include a developer mode option which in
155 turn enables this.
156  
157 =back
158  
159 =cut
160  
161 sub new {
162 my ($class, %opts) = @_;
163  
164 # determine module search directories.
165 my ($provided, @inc);
166 if ($provided = delete $opts{mod_inc}) {
167 @inc = @$provided if ref $provided eq 'ARRAY'; # dir list
168 @inc = $provided if !@inc; # one dir
169 }
170  
171 # fall back to default directories
172 else {
173 # current directory, mod directory, submodule mod directory
174 @inc = ('.', 'mod', 'lib/evented-api-engine/mod');
175 }
176  
177 # create the API Engine.
178 my $api = bless {
179 %opts,
180 mod_inc => \@inc,
181 features => [],
182 loaded => [],
183 indent => 0
184 }, $class;
185  
186 # log subroutine.
187 $api->on(log => sub {
188 my $api = shift;
189 $api->{log_sub}(@_) if $api->{log_sub};
190 }, 'api.engine.logSub');
191  
192 $api->_configure_api(%opts);
193 return $api;
194 }
195  
196 # handles post-construct constructor arguments.
197 #
198 # features => automatic ->add_feature()s
199 # modules => automatic ->load_module()s
200 #
201 sub _configure_api {
202 my ($api, %opts) = @_;
203  
204 # automatically add features.
205 if (defined $opts{features}) {
206 $api->add_feature($_) foreach @{
207 ref $opts{features} eq 'ARRAY' ?
208 $opts{features} :
209 [ $opts{features} ]
210 };
211 }
212  
213 # automatically load modules.
214 if (defined $opts{modules}) {
215 $api->load_modules_initially(@{
216 ref $opts{modules} eq 'ARRAY' ?
217 $opts{modules} :
218 [ $opts{modules} ]
219 });
220 }
221  
222 return 1;
223 }
224  
225 #######################
226 ### LOADING MODULES ###
227 #######################
228  
229 # (deprecated)
230 # load modules initially, i.e. from a configuration file.
231 # returns the modules that loaded.
232 sub load_modules_initially {
233 my ($api, @mod_names) = @_;
234 return $api->load_modules(@mod_names);
235 }
236  
237 =head2 $api->load_modules(@mod_names)
238  
239 Loads one or more modules at once.
240  
241 This is preferred over calling C<< ->load_module() >> several times in a row
242 because it skips common dependencies which have already been attempted.
243  
244 B<Parameters>
245  
246 =over
247  
248 =item *
249  
250 B<@mod_names> - list of module names to load
251  
252 =back
253  
254 B<Returns>
255  
256 Module objects for those which loaded successfully.
257  
258 =cut
259  
260 sub load_modules {
261 my ($api, @mod_names) = @_;
262 $api->{load_block} = { in_block => 1 };
263  
264 # load each module from within a load block.
265 my @results = grep $_, map $api->load_module($_), @mod_names;
266  
267 delete $api->{load_block};
268 return @results;
269 }
270  
271 # $api->load_module()
272 # loads a module.
273 #
274 # $mod_name the name of the module.
275 #
276 # $dirs search directories. this can be omitted; in such a case the
277 # the directories in $api->{mod_inc} will be searched.
278 #
279 # $is_submodule for internal use. true when the module being loaded is a
280 # submodule. this is used by $mod->load_submodule().
281 #
282 # $reloading for internal use. true when the module will be reloaded.
283 # this is used by $api->reload_module().
284 #
285 =head2 $api->load_module($mod_name, $dirs)
286  
287 Loads a toplevel module.
288  
289 B<Parameters>
290  
291 =over
292  
293 =item *
294  
295 B<$mod_name> - name of the module to load.
296  
297 =item *
298  
299 B<\@dirs> - I<optional>, module search directories. if omitted, the normal search
300 directories specified at API Engine construction time will be used.
301  
302 =back
303  
304 B<Returns>
305  
306 On success, the loaded module object. Otherwise, false.
307  
308 =cut
309  
310 sub load_module {
311 my ($api, $mod_name, $dirs, $is_submodule, $reloading) = @_;
312 return unless $mod_name;
313 $api->Log($mod_name, 'Loading') unless $dirs;
314  
315  
316 # PRE-LOAD CHECKS
317 #------------------------
318  
319 # check that the module load has not been attempted recently.
320 if ($api->{load_block} && !$is_submodule && !$dirs) {
321  
322 # make sure this module has not been attempted during this load block.
323 if ($api->{load_block}{$mod_name}) {
324 $api->Log($mod_name,
325 'Load FAILED: Skipping already attempted module');
326 return;
327 }
328  
329 # add to attempted list.
330 $api->{load_block}{$mod_name}++;
331 }
332  
333 # check that the module is not currently loaded.
334 if (!$is_submodule && $api->module_loaded($mod_name)) {
335 $api->Log($mod_name, 'Load FAILED: Module already loaded');
336 return;
337 }
338  
339 # if there is no list of search directories, use the default inc.
340 if (!$dirs) {
341 my @inc = @{ $api->{mod_inc} }; # explicitly make a copy
342 return $api->load_module($mod_name, \@inc, @_[3..$#_]);
343 }
344  
345 # use the next-available search directory.
346 # if no search directory is available, we have already checked them all.
347 my $search_dir = shift @$dirs;
348 if (!defined $search_dir) {
349 $api->Log($mod_name, 'Load FAILED: Module not found');
350 return;
351 }
352  
353 # LOCATE MODULE
354 #------------------------
355  
356 $api->Log($mod_name, "Searching for module: $search_dir/");
357  
358 # the file name is the module name with :: mapped to /.
359 # the "last name" of the module is the last portion of the filename.
360 my $mod_name_file = $mod_name; $mod_name_file =~ s/::/\//g;
361 my $mod_last_name = pop @{ [ split '/', $mod_name_file ] };
362  
363 # try to locate the module.
364 # given some module AB::CD
365 #
366 # look for $DIR/AB/CD.module
367 # look for $DIR/AB/CD/CD.module
368 #
369 my $mod_dir_1 = "$search_dir/$mod_name_file.module";
370 my $mod_dir_2 = "$search_dir/$mod_name_file/$mod_last_name.module";
371 my $mod_dir;
372  
373 if (-d $mod_dir_1) { $mod_dir = $mod_dir_1 }
374 elsif (-d $mod_dir_2) { $mod_dir = $mod_dir_2 }
375  
376 # we could not find the module in this search directory. try the next one.
377 else {
378 return $api->load_module(@_[1..$#_]);
379 }
380  
381  
382 # RETRIVE METADATA
383 #------------------------
384  
385 # we located the module directory.
386 # now we must ensure all required files are present.
387 $api->Log($mod_name, "Located module: $mod_dir");
388 foreach my $file ("$mod_last_name.pm") {
389 next if -f "$mod_dir/$file";
390 $api->Log($mod_name, "Load FAILED: Required file '$file' missing");
391 return;
392 }
393  
394 # fetch module information. this will be read from a JSON manifest OR
395 # from the comments atop the module code if we're in developer mode.
396 # give up on loading if we can't retrieve it.
397 my $info = $api->_get_module_info($mod_name, $mod_dir, $mod_last_name);
398 if (!$info || ref $info ne 'HASH') {
399 $api->Log($mod_name, "Load FAILED: Malformed manifest");
400 return;
401 }
402  
403 # find packages
404 if (!$info->{package}) {
405 $api->Log($mod_name, "Load FAILED: \@package is required");
406 return;
407 }
408
409 $info->{package} = [ $info->{package} ]
410 if ref $info->{package} ne 'ARRAY';
411 my @pkgs = @{ $info->{package} };
412 my $pkg = $pkgs[0] or return; # main pkg (module constructor)
413  
414  
415 # LOAD DEPENDENCIES
416 #------------------------
417  
418 # load required module dependencies here.
419 # consider: if the module fails to load, the dependencies remain loaded.
420 $api->_load_module_requirements($info) or return;
421  
422  
423 # CREATE MODULE OBJECT
424 #------------------------
425  
426 # make the module package a child of Evented::API::Module
427 # unless 'no_bless' is true.
428 my $constructor = 'Evented::API::Module';
429 unless ($info->{no_bless}) {
430 make_child($pkg, $constructor);
431 $pkg->isa($constructor) or return;
432 $constructor = $pkg;
433 }
434  
435 # create the module object.
436 my $mod = $constructor->new(
437 %$info,
438 dir => $mod_dir,
439 reloading => $reloading
440 );
441  
442 # the constructor returned bogus or nothing.
443 if (!$mod || !$mod->isa('Evented::API::Module')) {
444 $api->Log($mod_name, "Constructor $constructor->new() failed");
445 _package_unload(@pkgs);
446 return;
447 }
448  
449 # Safe point - the module object is available and safe for use.
450 # add it to the list of loaded modules.
451 push @{ $api->{loaded} }, $mod;
452  
453 # store dependecy module objects.
454 $mod->{dependencies} = [
455 map { $api->get_module($_) } # this definitely is an arrayref;
456 @{ $info->{depends}{modules} } # verified @ ->_load_module_requirements
457 ];
458  
459 # make the API Engine listen to the events of the module.
460 # hold a weak reference to the API engine.
461 $mod->add_listener($api, 'module');
462 weaken($mod->{api} = $api);
463  
464 # here we fire an event which will export symbols for convenient use
465 # within the module packages. see Module.pm for defaults.
466 print "PKGS: @pkgs\n";
467 $mod->fire(set_variables => $_) for @pkgs;
468  
469  
470 # EVALUATE
471 #------------------------
472  
473 my $return;
474 $mod->Log("Evaluating $mod_last_name.pm");
475 {
476  
477 # disable warnings on redefinition.
478 no warnings 'redefine';
479  
480 # capture other warnings.
481 local $SIG{__WARN__} = sub {
482 my $warn = shift;
483 chomp $warn;
484 $mod->Log("WARNING: $warn");
485 };
486  
487 # do() the file.
488 $return = do "$mod_dir/$mod_last_name.pm";
489  
490 }
491  
492 # an error occurred in loading.
493 if (!$return || $return != $mod) {
494 my $error = $@ || $! || 'Package did not return module object';
495 $mod->Log('Load FAILED: '.$error);
496 $api->_abort_module_load($mod);
497 return;
498 }
499  
500  
501 # INITIALIZE
502 #------------------------
503  
504 # initialize the module. returns false on fail.
505 $mod->_do_init or return;
506  
507 # Safe point - the module will certainly remain loaded.
508  
509  
510 # POST-LOAD
511 #------------------------
512  
513 # fire the 'load' event to indicate it has finished loading.
514 $mod->fire('load');
515 $mod->Log("Loaded successfully ($$mod{version})");
516  
517 # mark the packages as loaded.
518 for my $package (@pkgs) {
519 mark_as_loaded($package) unless is_loaded($package);
520 }
521  
522 # load postponed companion submodules, if any.
523 $api->_load_companion_submodules($mod);
524  
525 return $mod;
526 }
527  
528 # loads the modules a module depends on.
529 sub _load_module_requirements {
530 my ($api, $info) = @_;
531 my $mod_name = $info->{name}{full};
532  
533 # @depends.modules
534 my @dep_names;
535 my $names = delete $info->{depends}{modules};
536 push @dep_names, @$names
537 if ref $names eq 'ARRAY';
538 push @dep_names, $names
539 if length $names && !ref $names;
540  
541 # @depends.bases
542 $names = delete $info->{depends}{bases};
543 push @dep_names, map "Base::$_", @$names
544 if ref $names eq 'ARRAY';
545 push @dep_names, "Base::$names"
546 if length $names && !ref $names;
547  
548 # store as arrayref.
549 $info->{depends}{modules} = \@dep_names;
550 return 1 if !@dep_names;
551  
552 # check each dependency.
553 foreach my $dep_name (@dep_names) {
554  
555 # dependency already loaded.
556 if ($api->module_loaded($dep_name)) {
557 $api->Log($mod_name,
558 "Requirements: Dependency $dep_name already loaded");
559 next;
560 }
561  
562 # prevent endless loops.
563 if ($info->{name} eq $dep_name) {
564 $api->Log($mod_name, 'Load FAILED: Module depends on itself');
565 return;
566 }
567  
568 # load the dependency.
569 $api->Log($mod_name, "Requirements: Loading dependency $dep_name");
570 $api->{indent}++;
571 my $ok = $api->load_module($dep_name);
572 $api->{indent}--;
573  
574 # something went wrong.
575 next if $ok;
576 $api->Log($mod_name,
577 "Load FAILED: Loading dependency $dep_name failed");
578 return;
579 }
580  
581 return 1;
582 }
583  
584 my $json = JSON::XS->new->canonical->pretty;
585  
586 # fetch module information.
587 sub _get_module_info {
588 my ($api, $mod_name, $mod_dir, $mod_last_name) = @_;
589  
590 # try reading module JSON file.
591 my $path = "$mod_dir/$mod_last_name.json";
592 my $slurp = $api->_slurp($mod_name, $path);
593  
594 # no file - start with an empty hash.
595 my ($info, $use_manifest);
596 if (!length $slurp) {
597 $api->Log($mod_name, "No JSON manifest found at $path");
598 $info = {};
599 }
600  
601 # parse JSON. stop here if an error occurs, or if the manifest yields
602 # something other than a JSON object.
603 elsif (!($info = eval { $json->decode($slurp) }) || ref $info ne 'HASH') {
604 $api->Log($mod_name, "Load FAILED: JSON parsing of $path failed: $@");
605 $api->Log($mod_name, "JSON text: $slurp");
606 return;
607 }
608  
609 # JSON was decoded successfully at this point.
610 # developer mode is disabled, so return the manifest.
611 elsif (!$api->{developer}) {
612 $use_manifest++;
613 }
614  
615 # JSON was decoded successfully, but we're in developer mode.
616 # check the modification times. only use the manifest if the module's
617 # main package has not been modified since the manifest was written.
618 else {
619 my $pkg_modified = (stat "$mod_dir/$mod_last_name.pm" )[9];
620 my $man_modified = (stat "$mod_dir/$mod_last_name.json")[9];
621 $use_manifest++ if $man_modified >= $pkg_modified;
622 }
623  
624 # info was determined by JSON manifest.
625 if ($use_manifest) {
626 $info->{name} = { full => $info->{name} } if !ref $info->{name};
627 return $info;
628 }
629  
630 $api->Log($mod_name, 'Scanning for metadata');
631  
632 # try reading comments.
633 open my $fh, '<', "$mod_dir/$mod_last_name.pm"
634 or $api->Log($mod_name, "Load FAILED: Could not open file: $!")
635 and return;
636  
637 # parse for variables.
638 my $old_version = $info->{version} || 0;
639 my ($new_info, $parsed_lines) = {};
640 LINE: while (my $line = <$fh>) {
641 next unless $line =~ m/^#\s*@([\.\w]+)\s*(?:([:\+]+)(.+))?$/;
642 $parsed_lines++;
643 my ($var_name, $sym, $perl_value) = ($1, $2, $3);
644  
645 # find the correct hash level.
646 my ($i, $current, @s) = (0, $new_info, split /\./, $var_name);
647 LEVEL: foreach my $l (@s) {
648  
649 # last level, should contain the value.
650 if ($i == $#s) {
651 my ($is_add, $is_set, $is_bool) = map $sym eq $_, '+', ':', '';
652  
653 # for ':' or '+', eval the value now.
654 my $eval;
655 if ($is_set || $is_add) {
656 $perl_value = "[ $perl_value ]" if $is_add;
657 $eval = eval $perl_value;
658 if ($@) {
659 $api->Log($mod_name,
660 "Load FAILED: Evaluating '\@$var_name' failed: $@");
661 close $fh;
662 return;
663 }
664 }
665  
666 # for ':', simply set the value.
667 if ($is_set) {
668 $current->{$l} = $eval;
669 }
670  
671 # for '+', add it to a list.
672 elsif ($is_add) {
673 $current->{$l} = []
674 if ref $current->{$l} ne 'ARRAY';
675 push @{ $current->{$l} }, @$eval;
676 }
677  
678 # if there's no sym, this is a boolean.
679 elsif ($is_bool) {
680 $current->{$l} = 1;
681 }
682  
683 last LEVEL;
684 }
685  
686 # set the current level.
687 $current = ( $current->{$l} ||= {} );
688 $i++;
689 }
690 }
691 close $fh;
692  
693 # only accept the new info if there actually were variables in the comments.
694 # some modules might choose to rely solely on the JSON manifest, in which
695 # case we should preserve the old info.
696 $info = $new_info if $parsed_lines;
697  
698 # if in developer mode, write the changes.
699 if ($api->{developer}) {
700  
701 # automatic versioning.
702 if (!defined $info->{version}) {
703 $info->{version} = $old_version + 0.1;
704 $api->Log($mod_name,
705 "Upgrade: $old_version -> $$info{version} (automatic)");
706 }
707 elsif ($info->{version} != $old_version) {
708 $api->Log($mod_name, "Upgrade: $old_version -> $$info{version}");
709 }
710  
711 # open
712 open $fh, '>', "$mod_dir/$mod_last_name.json" or
713 $api->Log($mod_name,
714 "JSON warning: Could not write module JSON information"
715 ) and return;
716  
717 # encode
718 my $info_json = $json->encode($info);
719  
720 # write
721 $fh->write($info_json);
722 close $fh;
723  
724 $api->Log($mod_name, "JSON: Updated module information file");
725 }
726  
727 $info->{version} //= $old_version;
728 $info->{name} = { full => $info->{name} } if !ref $info->{name};
729 return $info;
730 }
731  
732 # remove the module from the 'loaded' list and delete its symbol table.
733 sub _abort_module_load {
734 my ($api, $mod) = @_;
735 @{ $api->{loaded} } = grep { $_ != $mod } @{ $api->{loaded} };
736 _package_unload($mod->{package}) if $mod->{package};
737 %$mod = ();
738 }
739  
740 #########################
741 ### UNLOADING MODULES ###
742 #########################
743  
744 # unload a module.
745 # returns the NAME of the module unloaded.
746 #
747 # $unload_dependents = recursively unload all dependent modules as well
748 # $unload_parent = if the module is a submodule, force it to unload by unloading parent also
749 #
750 # For internal use only:
751 #
752 # $unloading_submodule = means the parent is unloading a submodule
753 # $reloading = means the module is reloading
754 #
755 #
756  
757 =head2 $api->unload_module($mod, $unload_dependents, $unload_parent)
758  
759 Unloads a module.
760  
761 B<Parameters>
762  
763 =over
764  
765 =item *
766  
767 B<$mod> - module object or name to unload.
768  
769 =item *
770  
771 B<$unload_dependents> - I<optional>, if true, modules dependent on the one
772 being unloaded will also be unloaded. the normal behavior is to refuse to unload
773 if dependent modules are loaded.
774  
775 =item *
776  
777 B<$unload_parent> - I<optional>, if true and the module being unloaded is a
778 submodule, its parent will also be unloaded. the normal behavior is to refuse to
779 unload if the requested module is a submodule.
780  
781 =back
782  
783 B<Returns>
784  
785 Name of the unloaded module on success, otherwise false.
786  
787 =cut
788  
789 sub unload_module {
790 my ($api, $mod, $unload_dependents, $unload_parent,
791 $unloading_submodule, $reloading) = @_;
792  
793 # not blessed, find the module.
794 if (!blessed $mod) {
795 $mod = $api->get_module($mod);
796 if (!$mod) {
797 $api->Log($_[1], 'Unload: not loaded');
798 return;
799 }
800 }
801  
802  
803 # PRE-UNLOAD CHECKS
804 #------------------------
805  
806 # if this is a submodule, it cannot be unloaded this way.
807 if ($mod->parent && !$unloading_submodule) {
808  
809 # if we're forcing to unload, we just gotta unload the parent.
810 # this module will be unloaded because of $unload_dependents, so return.
811 if ($unload_parent) {
812 # ($mod, $unload_dependents, $unload_parent, ...)
813 $api->unload_module($mod->parent, 1, 1);
814 }
815  
816 # not forcing unload. give up.
817 else {
818 $mod->Log(
819 'Unload: submodule cannot be unloaded independently '.
820 'of parent'
821 );
822 }
823  
824 return;
825 }
826  
827 my $mod_name = $mod->name;
828 $mod->Log('Unloading');
829  
830 # check if any loaded modules are dependent on this one.
831 # if we're unloading recursively, do so after voiding.
832 my @dependents = $mod->dependents;
833 if (!$unload_dependents && @dependents) {
834 my $dependents = join ', ', map $_->name, @dependents;
835 $mod->Log("Can't unload: Dependent modules: $dependents");
836 return;
837 }
838  
839  
840 # VOID
841 #------------------------
842  
843 # fire module void. if the fire was stopped, give up.
844 $mod->_do_void($unloading_submodule) or return;
845  
846 # Safe point: from here, we can assume it will be unloaded for sure.
847  
848  
849 # UNLOAD DEPENDENCIES
850 #------------------------
851  
852 # if we're unloading recursively, do so now.
853 if ($unload_dependents && @dependents) {
854 $mod->Log("Unloading dependent modules");
855 $api->{indent}++;
856 # ($unload_dependents, $unload_parent, $unloading_submodule, $reloading)
857 $api->unload_module($_, 1, 1, undef, $reloading) for @dependents;
858 $api->{indent}--;
859 }
860  
861 # unload companion submodules that depend on this.
862 if (my @companions = $mod->dependent_companions) {
863 $mod->Log("Unloading dependent companions");
864 $api->{indent}++;
865 $_->parent->unload_submodule($_, $reloading) for @companions;
866 $api->{indent}--;
867 }
868  
869 # unload my own submodules.
870 $mod->unload_submodule($_, $reloading) for $mod->submodules;
871  
872 # if we're reloading, add to unloaded list.
873 push @{ $api->{r_unloaded} }, $mod->name
874 if $reloading && !$mod->parent;
875  
876  
877 # POST-UNLOAD
878 #------------------------
879  
880 # fire event for module unloaded (after void succeded)
881 $mod->fire('unload');
882  
883 # remove from loaded list.
884 @{ $api->{loaded} } = grep { $_ != $mod } @{ $api->{loaded} };
885  
886 # delete all events in case of cyclical references.
887 $mod->delete_all_events();
888  
889 # prepare for destruction.
890 $mod->{UNLOADED} = 1;
891 bless $mod, 'Evented::API::Module';
892  
893 # clear the symbol table of this module.
894 # if preserve_sym is set and this is during reload, don't delete symbols.
895 $mod->Log("Destroying packages @{ $$mod{package} }");
896 _package_unload($mod->{package})
897 unless $mod->{preserve_sym} && $reloading;
898  
899 $api->Log($mod_name, 'Unloaded successfully');
900 return $mod_name;
901 }
902  
903 #########################
904 ### RELOADING MODULES ###
905 #########################
906  
907 =head2 $api->reload_module($mod)
908  
909 Reloads a module.
910  
911 This is preferred over calling C<< ->unload_module() >> and C<< ->load_module >>
912 for a few reasons:
913  
914 =over
915  
916 =item *
917  
918 Some modules that do not allow permanent unloading may allow reloading.
919  
920 =item *
921  
922 Unchanged dependencies are not unloaded when reloading.
923  
924 =item *
925  
926 Some unchanged data can be retained during reload.
927  
928 =back
929  
930 B<Parameters>
931  
932 =over
933  
934 =item *
935  
936 B<$mod> - module object or name to reload.
937  
938 =back
939  
940 B<Returns>
941  
942 True on success.
943  
944 =cut
945  
946 sub reload_module {
947 my ($api, @mods) = @_;
948 my $count = 0;
949  
950 # during the reload, any modules unloaded,
951 # including dependencies but excluding submodules,
952 # will end up in this array.
953 $api->{r_unloaded} = [];
954  
955 # unload each module provided.
956 foreach my $mod (@mods) {
957  
958 # not blessed, search for module.
959 if (!blessed $mod) {
960 $mod = $api->get_module($mod);
961 if (!$mod) {
962 $api->Log($_[1], 'Reload: not loaded');
963 next;
964 }
965 }
966  
967 # unload the module.
968 $mod->{reloading} = 1;
969 # ($mod, $unload_dependents, $unload_parent, $unloading_submodule, $reloading)
970 $api->unload_module($mod, 1, 1, undef, 1) or return;
971 }
972  
973 # load all of the modules that were unloaded again
974 # (if they weren't already loaded, probably as dependencies).
975 my $unloaded = delete $api->{r_unloaded};
976 while (my $mod_name = shift @$unloaded) {
977 next if $api->module_loaded($mod_name);
978 # ($mod_name, $dirs, $is_submodule, $reloading);
979 $count++ if $api->load_module($mod_name, undef, undef, 1);
980 }
981  
982 return $count;
983 }
984  
985 =head2 $api->reload_modules(@mods)
986  
987 Reloads one or more modules at once. See C<< ->reload_module() >>.
988  
989 B<Parameters>
990  
991 =over
992  
993 =item *
994  
995 B<@mods> - module objects or names to reload.
996  
997 =back
998  
999 B<Returns>
1000  
1001 Number of modules reloaded successfully, false if all failed.
1002  
1003 =cut
1004  
1005 sub reload_modules;
1006 *reload_modules = *reload_module;
1007  
1008 ############################
1009 ### COMPANION SUBMODULES ###
1010 ############################
1011  
1012 sub _add_companion_submodule_wait {
1013 my ($api, $mod, $mod_name, $submod_name) = @_;
1014  
1015 # postpone load until the companion is loaded.
1016 # hold a weak reference to the module waiting.
1017 my $waits = $api->{companion_waits}{$mod_name} ||= [];
1018 my $ref = [ $mod, $submod_name ]; weaken($ref->[0]);
1019 push @$waits, $ref;
1020  
1021 # if it is already loaded, go ahead and load the submodule.
1022 if (my $loaded = $api->get_module($mod_name)) {
1023 return $api->_load_companion_submodules($loaded);
1024 }
1025  
1026 # false return indicates not yet loaded.
1027 return;
1028 }
1029  
1030 sub _load_companion_submodules {
1031 my ($api, $mod) = @_;
1032 my $waits = delete $api->{companion_waits}{ $mod->name } or return;
1033 ref $waits eq 'ARRAY' or return;
1034  
1035 my $status;
1036 foreach (@$waits) {
1037 my ($parent_mod, $submod_name) = @$_;
1038  
1039 # load the submodule.
1040 $parent_mod->Log("Loading companion submodule");
1041 my $submod = $parent_mod->load_submodule($submod_name) or next;
1042  
1043 # remember that this submodule depends on $mod.
1044 push @{ $submod->{companions} ||= [] }, $mod;
1045  
1046 }
1047  
1048 return $status;
1049 }
1050  
1051 ########################
1052 ### FETCHING MODULES ###
1053 ########################
1054  
1055 =head2 $api->get_module($mod_name)
1056  
1057 Fetches a loaded module object.
1058  
1059 B<Parameters>
1060  
1061 =over
1062  
1063 =item *
1064  
1065 B<$mod_name> - name of the module to find.
1066  
1067 =back
1068  
1069 B<Returns>
1070  
1071 Module object on success, false otherwise.
1072  
1073 =cut
1074  
1075 # returns the module object of a full module name.
1076 sub get_module {
1077 my ($api, $mod_name) = @_;
1078 foreach (@{ $api->{loaded} }) {
1079 return $_ if $_->name eq $mod_name;
1080 }
1081 return;
1082 }
1083  
1084 =head2 $api->package_to_module($pkg)
1085  
1086 Fetches a loaded module object by the corresponding Perl package name.
1087  
1088 B<Parameters>
1089  
1090 =over
1091  
1092 =item *
1093  
1094 B<$pkg> - Perl package name to find.
1095  
1096 =back
1097  
1098 B<Returns>
1099  
1100 Module object on success, false otherwise.
1101  
1102 =cut
1103  
1104 # returns the module object associated with a package.
1105 sub package_to_module {
1106 my ($api, $package) = @_;
1107 foreach (@{ $api->{loaded} }) {
1108 return $_ if $_->package eq $package;
1109 }
1110 return;
1111 }
1112  
1113 =head2 $api->module_loaded($mod_name)
1114  
1115 Returns true if the specified module is loaded.
1116  
1117 B<Parameters>
1118  
1119 =over
1120  
1121 =item *
1122  
1123 B<$mod_name> - name of the module to find.
1124  
1125 =back
1126  
1127 B<Returns>
1128  
1129 True if the module is loaded.
1130  
1131 =cut
1132  
1133 # returns true if the full module name provided is loaded.
1134 sub module_loaded {
1135 return 1 if shift->get_module(shift);
1136 return;
1137 }
1138  
1139 ####################
1140 ### DATA STORAGE ###
1141 ####################
1142  
1143 =head2 $api->store($key, $value)
1144  
1145 Stores a piece of data associated with the API Engine.
1146  
1147 B<Parameters>
1148  
1149 =over
1150  
1151 =item *
1152  
1153 B<$key> - name for fetching data later.
1154  
1155 =item *
1156  
1157 B<$value> - value to store.
1158  
1159 =back
1160  
1161 =cut
1162  
1163 # store a piece of data specific to this API Engine.
1164 sub store {
1165 my ($api, $key, $value) = @_;
1166 $api->{store}{$key} = $value;
1167 }
1168  
1169 =head2 $api->retrieve($key)
1170  
1171 Retrieves a piece of data associated with the API Engine.
1172  
1173 B<Parameters>
1174  
1175 =over
1176  
1177 =item *
1178  
1179 B<$key> - name associated with data to fetch.
1180  
1181 =back
1182  
1183 B<Returns>
1184  
1185 Fetched data, undef if not found.
1186  
1187 =cut
1188  
1189 # fetch a piece of data specific to this API Engine.
1190 sub retrieve {
1191 my ($api, $key) = @_;
1192 return $api->{store}{$key};
1193 }
1194  
1195 =head2 $api->list_store_add($key, $value)
1196  
1197 Adds an entry to a list of data associated with the API Engine.
1198  
1199 =over
1200  
1201 =item *
1202  
1203 B<$key> - name for fetching data later.
1204  
1205 =item *
1206  
1207 B<$value> - value to add.
1208  
1209 =back
1210  
1211 =cut
1212  
1213 # adds the item to a list store.
1214 # if the store doesn't exist, creates it.
1215 sub list_store_add {
1216 my ($api, $key, $value) = @_;
1217 push @{ $api->{store}{$key} ||= [] }, $value;
1218 }
1219  
1220 =head2 $api->list_store_items($key)
1221  
1222 Fetches all values in a list associated with the API Engine.
1223  
1224 =over
1225  
1226 =item *
1227  
1228 B<$key> - name of the list to retrieve.
1229  
1230 =back
1231  
1232 B<Returns>
1233  
1234 List of fetch values, or empty list if none were found.
1235  
1236 =cut
1237  
1238 # returns all the items in a list store.
1239 # if the store doesn't exist, this is
1240 # still safe and returns an empty list.
1241 sub list_store_items {
1242 my ($api, $key) = @_;
1243 return @{ $api->{store}{$key} || [] };
1244 }
1245  
1246 ################
1247 ### FEATURES ###
1248 ################
1249  
1250 =head2 $api->add_feature($feature)
1251  
1252 Enables a feature.
1253  
1254 Features are just a simple way for modules to determine whether a feature is
1255 provided by another module. For instance, if multiple modules provide different
1256 database backends, each of these could enable the database feature. Modules
1257 requiring a database would check for the feature enabled without having to know
1258 which module provides it.
1259  
1260 B<Parameters>
1261  
1262 =over
1263  
1264 =item *
1265  
1266 B<$feature> - name of the feature to enable.
1267  
1268 =back
1269  
1270 =cut
1271  
1272 # enable a feature.
1273 sub add_feature {
1274 my ($api, $feature) = @_;
1275 push @{ $api->{features} }, lc $feature;
1276 }
1277  
1278 =head2 $api->remove_feature($feature)
1279  
1280 Disables a feature.
1281  
1282 See C<< ->add_feature >> for an explanation of features.
1283  
1284 B<Parameters>
1285  
1286 =over
1287  
1288 =item *
1289  
1290 B<$feature> - name of the feature to disable.
1291  
1292 =back
1293  
1294 =cut
1295  
1296 # disable a feature.
1297 sub remove_feature {
1298 my ($api, $feature) = @_;
1299 @{ $api->{features} } = grep { $_ ne lc $feature } @{ $api->{features} };
1300 }
1301  
1302 =head2 $api->has_feature($feature)
1303  
1304 Returns true if the specified feature is enabled.
1305  
1306 See C<< ->add_feature >> for an explanation of features.
1307  
1308 B<Parameters>
1309  
1310 =over
1311  
1312 =item *
1313  
1314 B<$feature> - name of the feature to find.
1315  
1316 =back
1317  
1318 B<Returns>
1319  
1320 True if the requested feature is enabled.
1321  
1322 =cut
1323  
1324 # true if a feature is present.
1325 sub has_feature {
1326 my ($api, $feature) = @_;
1327 foreach (@{ $api->{features} }) {
1328 return 1 if $_ eq lc $feature;
1329 }
1330 return;
1331 }
1332  
1333 #####################
1334 ### MISCELLANEOUS ###
1335 #####################
1336  
1337 =head2 $api->Log($msg)
1338  
1339 Used for logging associated with the API Engine. Use module C<< ->Log() >> for
1340 messages associated with a specific module.
1341  
1342 B<Parameters>
1343  
1344 =over
1345  
1346 =item *
1347  
1348 B<$msg> - text to log.
1349  
1350 =back
1351  
1352 =cut
1353  
1354 # API log.
1355 sub Log {
1356 my ($api, $pfx, $msg) = @_;
1357  
1358 # add the prefix.
1359 $msg = defined $msg ? "[$pfx] $msg" : $pfx;
1360  
1361 # log the first line.
1362 my @msgs = split $/, $msg;
1363 $api->fire(log => (' ' x $api->{indent}).shift(@msgs));
1364  
1365 # log all other lines like "... text"
1366 my $i = $api->{indent} + 1;
1367 while (my $next = shift @msgs) {
1368 $api->fire(log => (' ' x $i)."... $next");
1369 }
1370  
1371 return 1;
1372 }
1373  
1374 sub _log;
1375 *_log = *Log;
1376  
1377 # unload a package and delete its symbols.
1378 # _package_unload('My::Package')
1379 sub _package_unload {
1380 for (@_) {
1381 if (ref $_ eq 'ARRAY') {
1382 _package_unload(@$_);
1383 next;
1384 }
1385 __package_unload($_);
1386 }
1387 }
1388  
1389 sub __package_unload {
1390 my $class = shift;
1391 no strict 'refs';
1392 @{ $class . '::ISA' } = ();
1393  
1394 my $symtab = $class.'::';
1395 for my $symbol (keys %$symtab) {
1396 next if $symbol =~ /\A[^:]+::\z/;
1397 delete $symtab->{$symbol};
1398 }
1399  
1400 mark_as_unloaded($class) if is_loaded($class);
1401 return 1;
1402 }
1403  
1404 # read contents of file.
1405 sub _slurp {
1406 my ($api, $mod_name, $file_name) = @_;
1407  
1408 # open file.
1409 my $fh;
1410 if (!open $fh, '<', $file_name) {
1411 $api->Log($mod_name, "$file_name: Could not open for reading: $!");
1412 return;
1413 }
1414  
1415 # read and close file.
1416 local $/ = undef;
1417 my $data = <$fh>;
1418 close $fh;
1419  
1420 return $data;
1421 }
1422  
1423 1;
1424  
1425 =head1 AUTHOR
1426  
1427 L<Mitchell Cooper|https://github.com/cooper> <cooper@cpan.org>
1428  
1429 Copyright E<copy> 2017. Released under New BSD license.
1430  
1431 Comments, complaints, and recommendations are accepted. Bugs may be reported on
1432 L<GitHub|https://github.com/cooper/evented-api-engine/issues>.