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

filter: Statementstmt 0.0% 0 / 136 Branchbran 0.0% 0 / 18 Conditioncond 0.0% 0 / 23 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 32 Podpod 0.0% 0 / 25 totaltotal 0.0% 0 / 234 CC 10 SCAR 15.0
CC
10
Cov
0%
_do_void
12.0
list_store_remove_matches
12.0
_do_init
6.0
CRAP 4.5
1 # Copyright (c) 2017, Mitchell Cooper
2 # Module represents an API module and provides an interface for managing one.
3 package Evented::API::Module;
4  
5 use warnings;
6 use strict;
7 use 5.010;
8  
9 use Evented::Object;
10 use parent 'Evented::Object';
11  
12 use Scalar::Util qw(blessed weaken);
13 use List::Util qw(first);
14  
15 our $VERSION = '4.11';
16  
17 =head1 NAME
18  
19 B<Evented::API::Module> - represents a module for use with
20 L<Evented::API::Engine>.
21  
22 =head1 SYNOPSIS
23  
24 # Module metadata
25 #
26 # @name: 'My::Module'
27 # @package: 'M::My::Module'
28 # @description:
29 #
30 # @depends.modules+ 'Some::Other'
31 # @depends.modules+ 'Another::Yet'
32 #
33 # @author.name: 'Mitchell Cooper'
34 # @author.website: 'https://github.com/cooper'
35 #
36 package M::My::Module;
37
38 use warnings;
39 use strict;
40 use 5.010;
41
42 # Auto-exported variables
43 our ($api, $mod);
44
45 # Default initializer
46 sub init {
47 say 'Loading ', $mod->name;
48
49 # indicates load success
50 return 1;
51 }
52
53 # Default deinitializer
54 sub void {
55 say 'Bye!';
56
57 # indicates unload success
58 return 1;
59 }
60
61 # Package must return module object
62 $mod;
63  
64 =head1 DESCRIPTION
65  
66 =head2 Module directory structure
67  
68 Modules must be placed within one of the search directories specified in the
69 L<Evented:API::Engine> C<mod_inc> consturctor option or the C<dirs> option
70 of C<< ->load_module >> and similar Engine methods.
71  
72 A module in its simplest form is a directory with the C<.module> extension
73 and a single C<.pm> file of the same name. Double-colon namespace separators
74 are condensed to directories, as with normal Perl packages. For instance, a
75 module called My::Backend's main package file could be located at either of the
76 following:
77  
78 $SEARCH_DIR/My/Backend.module/Backend.pm
79 $SEARCH_DIR/My/Backend/Backend.module/Backend.pm
80  
81 The directory with the C<.module> extension is called the module directory. In
82 addition to the Perl package file, it can house other data associated with the
83 module, such as JSON-encoded metadata, submodules, and documentation.
84  
85 $MODULE_DIR/Backend.pm # package file
86 $MODULE_DIR/Backend.json # metadata file
87 $MODULE_DIR/Backend.md # documentation
88 $MODULE_DIR/More.module/More.pm # submodule package
89 $MODULE_DIR/More.module/More.json # submodule metadata
90
91 =head2 Module metadata
92  
93 Module metadata is extracted from comments in primary package file.
94  
95 Metadata is written to a C<.json> file within the module directory
96 (when developer mode is enabled). These metadata files should be included in
97 distributions, as they contains version and author information.
98  
99 B<Syntax> for metadata comments is as follows:
100  
101 # @normal: "A normal option with a Perl-encoded value"
102 # @boolean # a boolean option!
103 # @list+ 'A value to add to a list'
104 # @list+ 'Another value to add to the list'
105
106 B<Supported options>
107  
108 # @name: 'Some::Module' # module name
109 # @package: 'M::Some::Module' # main package
110 # @package+ 'M::Some::Module::Blah' # additional packages
111 # @version: '1.01' # module version
112 # @depends.modules+ 'Some::Mod::Dependency' # module dependencies
113 # @depends.modules+ 'A::B', 'C::D' # additional dependencies
114 # @depends.bases+ 'Some::Base::Dependency' # base dependencies
115 # @author.name: 'John Doe' # author name
116 # @author.website: 'http://john.example.com' # author URL
117 # @no_bless # don't bless
118 # @preserve_sym # don't erase symbols
119
120 These, I feel, require additional explanation:
121  
122 =over
123  
124 =item *
125  
126 B<@version> - this obviously is a numerical module version. I'm mentioning it
127 here to tell you that you probably shouldn't bother using it, as the API Engine
128 offers automatic versioning (with developer mode enabled) if you simply omit
129 this option.
130  
131 =item *
132  
133 B<@depends.bases> - like C<@depends.modules>, except the C<Base::> prefix is
134 added. bases are modules which don't really offer any functionality on their
135 own but provide APIs for other modules to use.
136  
137 =item *
138  
139 B<@no_bless> - if true, the module object will not be blessed to the module's
140 primary package (which is the default behavior). this might be useful if your
141 module contains names conflicting with API Engine or uses autoloading.
142  
143 =item *
144  
145 B<@preserve_sym> - if true, the packages associated with the module will not be
146 deleted from the symbol table upon unload. this is worse for memory, but it
147 may be necessary for the "guts" of your program, particularly those parts which
148 deal with the loading and unloading of modules themselves.
149  
150 =back
151  
152 =head1 METHODS
153  
154 =cut
155  
156 sub new {
157 my ($class, %opts) = @_;
158 my $mod = bless \%opts, $class;
159 Evented::API::Events::add_events($mod);
160 return $mod;
161 }
162  
163 =head2 $mod->name
164  
165 B<Returns> module full name.
166  
167 =head2 $mod->package
168  
169 B<Returns> module's primary Perl package name.
170  
171 =head2 $mod->packages
172  
173 B<Returns> all packages associate with module.
174  
175 =head2 $mod->api
176  
177 B<Returns> associated L<API Engine | Evented::API::Engine>.
178  
179 =head2 $mod->parent
180  
181 B<Returns> parent module, if this is a submodule.
182  
183 =head2 $mod->submodules
184  
185 B<Returns> list of loaded submodules objects.
186  
187 =cut
188  
189 sub name { shift->{name}{full} } # full name
190 sub package { shift->{package}[0] } # main package
191 sub packages { @{ shift->{package} } } # all packages
192 sub api { shift->{api} }
193 sub parent { shift->{parent} }
194 sub submodules { @{ shift->{submodules} || [] } }
195  
196 =head2 $mod->Log($msg)
197  
198 Used for logging associated with module. Use L<API Engine | Evented:API::Engine>
199 C<< ->Log() >> for messages not associated with a specific module.
200  
201 B<Parameters>
202  
203 =over
204  
205 =item *
206  
207 B<$msg> - text to log.
208  
209 =back
210  
211 =head2 $mod->Debug($msg)
212  
213 Used for debug logging associated with module.
214 Use L<API Engine | Evented:API::Engine> C<< ->Debug() >> for messages not
215 associated with a specific module.
216  
217 B<Parameters>
218  
219 =over
220  
221 =item *
222  
223 B<$msg> - text to log.
224  
225 =back
226  
227 =cut
228  
229 sub Log {
230 my $mod = shift;
231 $mod->api->Log($mod->name, "@_");
232 }
233  
234 sub Debug {
235 my $mod = shift;
236 $mod->api->Debug($mod->name, "@_");
237 }
238  
239 # compat
240 sub _log;
241 *_log = \&Log;
242  
243 =head2 $mod->get_symbol($sym)
244  
245 Fetches the value of a symbol in module's main package.
246  
247 B<Parameters>
248  
249 =over
250  
251 =item *
252  
253 B<$sym> - string symbol; such as C<@list>, C<%hash>, or C<$scalar>.
254  
255 =back
256  
257 B<Returns>
258  
259 The data in its native type (NOT a reference), or the zero value for that type
260 if no symbol table entry exists.
261  
262 =cut
263  
264 sub get_symbol {
265 my ($mod, $symbol) = @_;
266 return Evented::Object::Hax::get_symbol($mod->package, $symbol);
267 }
268  
269 sub _do_init {
270 my $mod = shift;
271 my $api = $mod->api;
272  
273 # fire module initialize.
274 $api->Log($mod->name, 'Initializing');
275 $api->{indent}++;
276 my $init_fire = $mod->prepare('init')->fire('return_check');
277 $api->{indent}--;
278  
279 # init was stopped. cancel the load.
280 if (my $stopper = $init_fire->stopper) {
281 $mod->Log('init stopped: '.$init_fire->stop);
282 $mod->Log("Load FAILED: Initialization canceled by '$stopper'");
283  
284 $api->_abort_module_load($mod);
285  
286 # fire unload so that bases can undo whatever was done up
287 # to the fail point of init.
288 bless $mod, 'Evented::API::Module';
289 $mod->fire('unload');
290  
291 return;
292 }
293  
294 # init was successful
295 return 1;
296 }
297  
298 sub _do_void {
299 my ($mod, $unloading_submodule) = @_;
300 my $api = $mod->api;
301  
302 # fire module void.
303 # consider: should this have return_check like init?
304 $mod->Log('Voiding');
305 my $void_fire = $mod->fire('void');
306  
307 # init was stopped. cancel the unload.
308 my $stopper = $void_fire->stopper;
309 if (!$unloading_submodule && $stopper) {
310 $mod->Log("void stopped: ".$void_fire->stop);
311 $mod->Log("Can't unload: canceled by '$stopper'");
312 return;
313 }
314  
315 # if this is a submodule, it isn't allowed to refuse to unload.
316 elsif ($stopper) {
317 $mod->Log(
318 "Warning! This submodule has requested to remain ".
319 'loaded, but submodules MUST be unloaded with their parent'
320 );
321 }
322  
323 # void was successful
324 return 1;
325  
326 }
327  
328 ##################
329 ### SUBMODULES ###
330 ##################
331  
332 =head2 $mod->load_submodule($submod_name)
333  
334 Loads a submodule.
335  
336 This is generally used within the module initializer.
337  
338 B<Parameters>
339  
340 =over
341  
342 =item *
343  
344 B<$submod_name> - name of the submodule, without the parent module name prefix.
345 for instance if the full submodule name is C<My::Module::Sub>, this is simply
346 C<Sub>.
347  
348 =back
349  
350 B<Returns>
351  
352 Submodule object on success, false otherwise.
353  
354 =cut
355  
356 sub load_submodule {
357 my ($mod, $mod_name) = @_;
358 $mod->Log("Loading submodule $mod_name");
359  
360 # call ->load_module with the search dir set to the
361 # parent module's main directory.
362 $mod->api->{indent}++;
363 my $ret = $mod->api->load_module($mod_name, [ $mod->{dir} ], 1);
364 $mod->api->{indent}--;
365  
366 # add weakly to submodules list. hold weak reference to parent module.
367 if ($ret) {
368 my $a = $mod->{submodules} ||= [];
369 push @$a, $ret;
370 weaken($a->[$#$a]);
371 weaken($ret->{parent} = $mod);
372 }
373  
374 return $ret;
375 }
376  
377 =head2 $mod->unload_submodule($submod)
378  
379 Unloads a submodule.
380  
381 You do not have to call this in the parent module deinitializer. Only use this
382 method if you want to dynamically unload a submodule for some reason without
383 unloading the parent module.
384  
385 B<Parameters>
386  
387 =over
388  
389 =item *
390  
391 B<$submod> - submodule object or name, without the parent module name prefix.
392 for instance if the full submodule name is C<My::Module::Sub>, this is simply
393 C<Sub>.
394  
395 =back
396  
397 =cut
398  
399 sub unload_submodule {
400 my ($mod, $submod, $reloading) = @_;
401 my $submod_name = $submod->name;
402 $mod->Log("Unloading submodule $submod_name");
403  
404 # unload
405 $mod->api->{indent}++;
406  
407 # ($mod, $unload_dependents, $force, $unloading_submodule, $reloading)
408 #
409 # do not force, as that might unload the parent
410 # but do say we are unloading a submodule so it can be unloaded
411 # independently (which usually wouldn't be allowed)
412 #
413 $mod->api->unload_module($submod, undef, undef, 1, $reloading);
414  
415 $mod->api->{indent}--;
416  
417 # remove from submodules
418 if (my $submods = $mod->{submodules}) {
419 @$submods = grep { $_ != $submod } @$submods;
420 }
421 delete $submod->{parent};
422  
423 return 1;
424 }
425  
426 =head2 $mod->add_companion_submodule($mod_name, $submod_name)
427  
428 Registers a submodule (provided by this module) as a companion of another
429 top-level module.
430  
431 Companion submodules are submodules which are automatically loaded and unloaded
432 as needed in conjunction with other top-level modules.
433  
434 This is generally called from within the parent module initializer.
435  
436 B<Parameters>
437  
438 =over
439  
440 =item *
441  
442 B<$mod_name> - name of another top-level module to register the submodule as
443 a companion.
444  
445 =item *
446  
447 B<$submod_name> - name of the submodule to register a companion, without the
448 parent module name prefix. for instance if the full submodule name is
449 C<My::Module::Sub>, this is simply C<Sub>.
450  
451 =back
452  
453 =cut
454  
455 sub add_companion_submodule {
456 my ($mod, $mod_name, $submod_name) = @_;
457 $mod->api->_add_companion_submodule_wait($mod, $mod_name, $submod_name);
458 }
459  
460 ####################
461 ### DATA STORAGE ###
462 ####################
463  
464 =head2 $mod->store($key, $value)
465  
466 Stores a piece of data associated with module.
467  
468 B<Parameters>
469  
470 =over
471  
472 =item *
473  
474 B<$key> - name for fetching data later.
475  
476 =item *
477  
478 B<$value> - value to store.
479  
480 =back
481  
482 =cut
483  
484 # store a piece of data specific to this module.
485 sub store {
486 my ($mod, $key, $value) = @_;
487 $mod->{store}{$key} = $value;
488 }
489  
490 =head2 $mod->retrieve($key, $default_value)
491  
492 Retrieves a piece of data associated with module.
493  
494 B<Parameters>
495  
496 =over
497  
498 =item *
499  
500 B<$key> - name associated with data to fetch.
501  
502 =back
503  
504 B<Returns>
505  
506 Fetched data, undef if not found.
507  
508 =cut
509  
510 # fetch a piece of data specific to this module.
511 sub retrieve {
512 my ($mod, $key, $default_value) = @_;
513 return $mod->{store}{$key} //= $default_value;
514 }
515  
516 =head2 $mod->list_store_add($key, $value)
517  
518 Adds an entry to a list of data associated with module.
519  
520 =over
521  
522 =item *
523  
524 B<$key> - name for fetching data later.
525  
526 =item *
527  
528 B<$value> - value to add.
529  
530 =back
531  
532 =cut
533  
534 # adds the item to a list store.
535 # if the store doesn't exist, creates it.
536 sub list_store_add {
537 my ($mod, $key, $value) = @_;
538 push @{ $mod->{store}{$key} ||= [] }, $value;
539 }
540  
541 =head2 $mod->list_store_remove_matches($key, $code, $max)
542  
543 Removes entries satisfying a code from a list of data associated with module.
544  
545 B<Parameters>
546  
547 =over
548  
549 =item *
550  
551 B<$key> - name of list.
552  
553 =item *
554  
555 B<$code> - code reference passed each entry which should return true for
556 matches.
557  
558 =item *
559  
560 B<$max> - I<optional>, maximum number of entries to remove.
561  
562 =back
563  
564 B<Returns>
565  
566 Number of items removed, false if none matched.
567  
568 =cut
569  
570 # remove a single item matching.
571 # $max = stop searching when removed this many (optional)
572 sub list_store_remove_matches {
573 my ($mod, $key, $sub, $max) = @_;
574 my @before = @{ $mod->{store}{$key} or return };
575 my ($removed, @after) = 0;
576 while (my $item = shift @before) {
577  
578 # it matches. add the remaining.
579 if ($sub->($item)) {
580 last if $max && $removed == $max;
581 next;
582 }
583  
584 # no match. add and continue.
585 push @after, $item;
586  
587 }
588  
589 # add the rest, store.
590 push @after, @before;
591 $mod->{store}{$key} = \@after;
592  
593 return $removed;
594 }
595  
596 =head2 $mod->list_store_items($key)
597  
598 Fetches all values in a list associated with module.
599  
600 =over
601  
602 =item *
603  
604 B<$key> - name of the list to retrieve.
605  
606 =back
607  
608 B<Returns>
609  
610 List of fetch values, or empty list if none were found.
611  
612 =cut
613  
614 # returns all the items in a list store.
615 # if the store doesn't exist, this is
616 # still safe and returns an empty list.
617 sub list_store_items {
618 my ($mod, $key) = @_;
619 return @{ $mod->{store}{$key} || [] };
620 }
621  
622 ####################
623 ### DEPENDENCIES ###
624 ####################
625  
626 =head2 $mod->dependencies
627  
628 B<Returns> top-level module dependencies.
629  
630 =cut
631  
632 # returns the modules that this depends on.
633 sub dependencies {
634 return @{ shift->{dependencies} || [] };
635 }
636  
637 =head2 $mod->companions
638  
639 For companion submodules,
640 B<Returns> modules that this submodule depends on.
641  
642 =cut
643  
644 # returns the modules that this companion submodule depends on.
645 sub companions {
646 return @{ shift->{companions} || [] };
647 }
648  
649 =head2 $mod->dependents
650  
651 B<Returns> top-level modules that depend on this module.
652  
653 =cut
654  
655 # returns the top-level modules that depend on this.
656 sub dependents {
657 my $mod = shift;
658 my @mods;
659 foreach my $m (@{ $mod->api->{loaded} }) {
660 next unless first { $_ == $mod } $m->dependencies;
661 push @mods, $m;
662 }
663 return @mods;
664 }
665  
666 =head2 $mod->dependent_companions
667  
668 B<Returns> companion submodules that depend on this module.
669  
670 =cut
671  
672 # returns the companion submodules that depend on this.
673 sub dependent_companions {
674 my $mod = shift;
675 my @mods;
676 foreach my $m (@{ $mod->api->{loaded} }) {
677 next unless first { $_ == $mod } $m->companions;
678 push @mods, $m;
679 }
680 return @mods;
681 }
682  
683 =head1 AUTHOR
684  
685 L<Mitchell Cooper|https://github.com/cooper> <cooper@cpan.org>
686  
687 Copyright E<copy> 2017. Released under New BSD license.
688  
689 Comments, complaints, and recommendations are accepted. Bugs may be reported on
690 L<GitHub|https://github.com/cooper/evented-api-engine/issues>.
691  
692 =cut
693  
694 1;