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

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