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