Event-Distributor-0.05000755001750001750 013325370231 13547 5ustar00leoleo000000000000Event-Distributor-0.05/Build.PL000444001750001750 112213325370231 15174 0ustar00leoleo000000000000use strict; use warnings; use Module::Build; my $build = Module::Build->new( module_name => 'Event::Distributor', requires => { 'Future' => '0.15', 'Syntax::Keyword::Try' => 0, }, test_requires => { 'Test::Fatal' => 0, 'Test::More' => '0.88', # done_testing }, configure_requires => { 'Module::Build' => '0.4004', # test_requires }, license => 'perl', create_license => 1, create_readme => 1, meta_merge => { resources => { x_IRC => "irc://irc.perl.org/#io-async", }, }, ); $build->create_build_script; Event-Distributor-0.05/Changes000444001750001750 210013325370231 15170 0ustar00leoleo000000000000Revision history for Event-Distributor 0.05 2018-07-23 16:11:07 [CHANGES] * Ensure an empty query event doesn't fail * Ensure that a dying subscriber to query doesn't kill the entire distribution * Make empty results count as failures for Query * Make Query return empty result if all its subscribers did * Use Syntax::Keyword::Try instead of plain eval{} block 0.04 2015/11/27 21:53:07 [CHANGES] * Added 'action' events * Update documentation to barename function style 0.03 2015/02/11 20:21:19 [CHANGES] * Expose Ev:Dist::Signal/Query as user-accessible objects [BUGFIXES] * Don't corrupt internal state when subscriber functions trash $_ 0.02 2014/12/10 22:18:13 [CHANGES] * Add query-like events * Ensure Signals raise errors as failures if any of their subscribers do * Add TODO note about anonymous signals 0.01 2014/08/16 19:04:30 First version, released on an unsuspecting world. Event-Distributor-0.05/LICENSE000444001750001750 4376213325370231 14745 0ustar00leoleo000000000000This software is copyright (c) 2018 by Paul Evans . This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. Terms of the Perl programming language system itself a) the GNU General Public License as published by the Free Software Foundation; either version 1, or (at your option) any later version, or b) the "Artistic License" --- The GNU General Public License, Version 1, February 1989 --- This software is Copyright (c) 2018 by Paul Evans . This is free software, licensed under: The GNU General Public License, Version 1, February 1989 GNU GENERAL PUBLIC LICENSE Version 1, February 1989 Copyright (C) 1989 Free Software Foundation, Inc. 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The license agreements of most software companies try to keep users at the mercy of those companies. By contrast, our General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. The General Public License applies to the Free Software Foundation's software and to any other program whose authors commit to using it. You can use it for your programs, too. When we speak of free software, we are referring to freedom, not price. Specifically, the General Public License is designed to make sure that you have the freedom to give away or sell copies of free software, that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of a such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must tell them their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License Agreement applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any work containing the Program or a portion of it, either verbatim or with modifications. Each licensee is addressed as "you". 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this General Public License and to the absence of any warranty; and give any other recipients of the Program a copy of this General Public License along with the Program. You may charge a fee for the physical act of transferring a copy. 2. You may modify your copy or copies of the Program or any portion of it, and copy and distribute such modifications under the terms of Paragraph 1 above, provided that you also do the following: a) cause the modified files to carry prominent notices stating that you changed the files and the date of any change; and b) cause the whole of any work that you distribute or publish, that in whole or in part contains the Program or any part thereof, either with or without modifications, to be licensed at no charge to all third parties under the terms of this General Public License (except that you may choose to grant warranty protection to some or all third parties, at your option). c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the simplest and most usual way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this General Public License. d) You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. Mere aggregation of another independent work with the Program (or its derivative) on a volume of a storage or distribution medium does not bring the other work under the scope of these terms. 3. You may copy and distribute the Program (or a portion or derivative of it, under Paragraph 2) in object code or executable form under the terms of Paragraphs 1 and 2 above provided that you also do one of the following: a) accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Paragraphs 1 and 2 above; or, b) accompany it with a written offer, valid for at least three years, to give any third party free (except for a nominal charge for the cost of distribution) a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Paragraphs 1 and 2 above; or, c) accompany it with the information you received as to where the corresponding source code may be obtained. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form alone.) Source code for a work means the preferred form of the work for making modifications to it. For an executable file, complete source code means all the source code for all modules it contains; but, as a special exception, it need not include source code for modules which are standard libraries that accompany the operating system on which the executable file runs, or for standard header files or definitions files that accompany that operating system. 4. You may not copy, modify, sublicense, distribute or transfer the Program except as expressly provided under this General Public License. Any attempt otherwise to copy, modify, sublicense, distribute or transfer the Program is void, and will automatically terminate your rights to use the Program under this License. However, parties who have received copies, or rights to use copies, from you under this General Public License will not have their licenses terminated so long as such parties remain in full compliance. 5. By copying, distributing or modifying the Program (or any work based on the Program) you indicate your acceptance of this license to do so, and all its terms and conditions. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. 7. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of the license which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the license, you may choose any version ever published by the Free Software Foundation. 8. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 9. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 10. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS Appendix: How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to humanity, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) 19yy This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 1, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301 USA Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) 19xx name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (a program to direct compilers to make passes at assemblers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice That's all there is to it! --- The Artistic License 1.0 --- This software is Copyright (c) 2018 by Paul Evans . This is free software, licensed under: The Artistic License 1.0 The Artistic License Preamble The intent of this document is to state the conditions under which a Package may be copied, such that the Copyright Holder maintains some semblance of artistic control over the development of the package, while giving the users of the package the right to use and distribute the Package in a more-or-less customary fashion, plus the right to make reasonable modifications. Definitions: - "Package" refers to the collection of files distributed by the Copyright Holder, and derivatives of that collection of files created through textual modification. - "Standard Version" refers to such a Package if it has not been modified, or has been modified in accordance with the wishes of the Copyright Holder. - "Copyright Holder" is whoever is named in the copyright or copyrights for the package. - "You" is you, if you're thinking about copying or distributing this Package. - "Reasonable copying fee" is whatever you can justify on the basis of media cost, duplication charges, time of people involved, and so on. (You will not be required to justify it to the Copyright Holder, but only to the computing community at large as a market that must bear the fee.) - "Freely Available" means that no fee is charged for the item itself, though there may be fees involved in handling the item. It also means that recipients of the item may redistribute it under the same conditions they received it. 1. You may make and give away verbatim copies of the source form of the Standard Version of this Package without restriction, provided that you duplicate all of the original copyright notices and associated disclaimers. 2. You may apply bug fixes, portability fixes and other modifications derived from the Public Domain or from the Copyright Holder. A Package modified in such a way shall still be considered the Standard Version. 3. You may otherwise modify your copy of this Package in any way, provided that you insert a prominent notice in each changed file stating how and when you changed that file, and provided that you do at least ONE of the following: a) place your modifications in the Public Domain or otherwise make them Freely Available, such as by posting said modifications to Usenet or an equivalent medium, or placing the modifications on a major archive site such as ftp.uu.net, or by allowing the Copyright Holder to include your modifications in the Standard Version of the Package. b) use the modified Package only within your corporation or organization. c) rename any non-standard executables so the names do not conflict with standard executables, which must also be provided, and provide a separate manual page for each non-standard executable that clearly documents how it differs from the Standard Version. d) make other distribution arrangements with the Copyright Holder. 4. You may distribute the programs of this Package in object code or executable form, provided that you do at least ONE of the following: a) distribute a Standard Version of the executables and library files, together with instructions (in the manual page or equivalent) on where to get the Standard Version. b) accompany the distribution with the machine-readable source of the Package with your modifications. c) accompany any non-standard executables with their corresponding Standard Version executables, giving the non-standard executables non-standard names, and clearly documenting the differences in manual pages (or equivalent), together with instructions on where to get the Standard Version. d) make other distribution arrangements with the Copyright Holder. 5. You may charge a reasonable copying fee for any distribution of this Package. You may charge any fee you choose for support of this Package. You may not charge a fee for this Package itself. However, you may distribute this Package in aggregate with other (possibly commercial) programs as part of a larger (possibly commercial) software distribution provided that you do not advertise this Package as a product of your own. 6. The scripts and library files supplied as input to or produced as output from the programs of this Package do not automatically fall under the copyright of this Package, but belong to whomever generated them, and may be sold commercially, and may be aggregated with this Package. 7. C or perl subroutines supplied by you and linked into this Package shall not be considered part of this Package. 8. The name of the Copyright Holder may not be used to endorse or promote products derived from this software without specific prior written permission. 9. THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. The End Event-Distributor-0.05/MANIFEST000444001750001750 45613325370231 15022 0ustar00leoleo000000000000Build.PL Changes lib/Event/Distributor.pm lib/Event/Distributor/_Event.pm lib/Event/Distributor/Action.pm lib/Event/Distributor/Query.pm lib/Event/Distributor/Signal.pm LICENSE MANIFEST This list of files META.json META.yml README t/00use.t t/01signal.t t/02action.t t/03query.t t/10dist.t t/99pod.t Event-Distributor-0.05/META.json000444001750001750 302113325370231 15321 0ustar00leoleo000000000000{ "abstract" : "a simple in-process pub/sub mechanism", "author" : [ "Paul Evans " ], "dynamic_config" : 1, "generated_by" : "Module::Build version 0.4224", "license" : [ "perl_5" ], "meta-spec" : { "url" : "http://search.cpan.org/perldoc?CPAN::Meta::Spec", "version" : 2 }, "name" : "Event-Distributor", "prereqs" : { "configure" : { "requires" : { "Module::Build" : "0.4004" } }, "runtime" : { "requires" : { "Future" : "0.15", "Syntax::Keyword::Try" : "0" } }, "test" : { "requires" : { "Test::Fatal" : "0", "Test::More" : "0.88" } } }, "provides" : { "Event::Distributor" : { "file" : "lib/Event/Distributor.pm", "version" : "0.05" }, "Event::Distributor::Action" : { "file" : "lib/Event/Distributor/Action.pm", "version" : "0.05" }, "Event::Distributor::Query" : { "file" : "lib/Event/Distributor/Query.pm", "version" : "0.05" }, "Event::Distributor::Signal" : { "file" : "lib/Event/Distributor/Signal.pm", "version" : "0.05" } }, "release_status" : "stable", "resources" : { "license" : [ "http://dev.perl.org/licenses/" ], "x_IRC" : "irc://irc.perl.org/#io-async" }, "version" : "0.05", "x_serialization_backend" : "JSON::PP version 2.97001" } Event-Distributor-0.05/META.yml000444001750001750 177013325370231 15162 0ustar00leoleo000000000000--- abstract: 'a simple in-process pub/sub mechanism' author: - 'Paul Evans ' build_requires: Test::Fatal: '0' Test::More: '0.88' configure_requires: Module::Build: '0.4004' dynamic_config: 1 generated_by: 'Module::Build version 0.4224, CPAN::Meta::Converter version 2.150010' license: perl meta-spec: url: http://module-build.sourceforge.net/META-spec-v1.4.html version: '1.4' name: Event-Distributor provides: Event::Distributor: file: lib/Event/Distributor.pm version: '0.05' Event::Distributor::Action: file: lib/Event/Distributor/Action.pm version: '0.05' Event::Distributor::Query: file: lib/Event/Distributor/Query.pm version: '0.05' Event::Distributor::Signal: file: lib/Event/Distributor/Signal.pm version: '0.05' requires: Future: '0.15' Syntax::Keyword::Try: '0' resources: IRC: irc://irc.perl.org/#io-async license: http://dev.perl.org/licenses/ version: '0.05' x_serialization_backend: 'CPAN::Meta::YAML version 0.018' Event-Distributor-0.05/README000444001750001750 1711113325370231 14605 0ustar00leoleo000000000000NAME Event::Distributor - a simple in-process pub/sub mechanism SYNOPSIS use Event::Distributor; my $dist = Event::Distributor->new; $dist->declare_signal( "announce" ); $dist->subscribe_sync( announce => sub { my ( $message ) = @_; say $message; }); $dist->subscribe_async( announce => sub { my ( $message ) = @_; return $async_http->POST( "http://server/message", $message ); }); $dist->fire_sync( announce => "Hello, world!" ); DESCRIPTION Instances of this class provide a simple publish/subscribe mechanism within a single process, for either synchronous or Future-based asynchronous use. A given instance has a set of named events. Subscribers are CODE references attached to a named event. Publishers can declare the existence of a named event, and then later invoke it by passing in arguments, which are distributed to all of the subscribers of that named event. It is specifically not an error to request to subscribe an event that has not yet been declared, in order to allow multiple modules of code to be loaded and subscribe events the others publish, without introducing loading order dependencies. An event only needs to be declared by the time it is fired. Natively all of the events provided by the distributor are fully-asynchronous in nature. Each subscriber is expected to return a Future instance which will indicate its completion; the results of these are merged into a single future returned by the fire method itself. However, to support synchronous or semi-synchronous programs using it, both the observe and invoke methods also have a synchronous variant. Note however, that this module does not provide any kind of asynchronous detachment of synchronous functions; using the "subscribe_sync" method to subscribe a long-running blocking function will cause the fire_* methods to block until that method returns. To achieve a truely-asynchronous experience the attached code will need to use some kind of asynchronous event system. This module is very-much a work-in-progress, and many ideas may still be added or changed about it. It is the start of a concrete implementaion of some of the ideas in my "Event-Reflexive Programming" series of blog posts. See the "TODO" and "SEE ALSO" sections for more detail. EVENTS Each of the events known by a distributor has a name. Conceptually each also has a type. Currently there are three types of event, a "signal", an "action", and a "query". * A signal event simply informs subscribers that some event or condition has occurred. Additional arguments can be passed from the invoker to the subscribers, but subscriptions are not expected to return a meaningful value, nor does firing this event return a value. All subscriber functions are invoked sequentually and synchronously by a fire_* method (though, of course, asynchronous subscribers synchronously return a future instance, which allows them to continue working asynchronously). * An action event requires a single subscriber, and represents a request from the invoker to the subscriber to perform some activity. This behaves much like a regular (Future-returning) method call, except that the indirection mechanism of the distributor allows a more flexible method of connection between the two sides. * A query event invokes subscriber code expecting a successful return, returning the first result that is successful. If a synchronous subscriber returns a result, or if an asynchronous one returns a successful immediate Future, then no further subscribers are invoked, and that result is taken immediately. Any other pending Futures are then cancelled. METHODS declare_signal $distributor->declare_signal( $name ) Declares a new "signal" event of the given name. declare_action $distributor->declare_action( $name ) Since version 0.04. Declares a new "action" event of the given name. declare_query $distributor->declare_query( $name ) Since version 0.02. Declares a new "query" event of the given name. subscribe_async $distributor->subscribe_async( $name, $code ) Adds a new CODE reference to the list of subscribers for the named event. This subscriber is expected to return a Future that will eventually yield its result. When invoked the code will be passed the distributor object itself and the list of arguments, and is expected to return a Future. $f = $code->( $distributor, @args ) subscribe_sync $distributor->subscribe_sync( $name, $code ) Adds a new CODE reference to the list of subscribers for the named event. This subscriber is expected to perform its work synchronously and return its result immediately. In non-blocking or asynchronous applications, this method should only be used for simple subscribers which can immediately return having completed their work. If the work is likely to take some time by blocking on external factors, consider instead using the "subscribe_async" method. When invoked the code will be passed the distributor object itself and the list of arguments. $code->( $distributor, @args ) fire_async $f = $distributor->fire_async( $name, @args ) Invokes the named event, passing the arguments to the subscriber functions. This function returns as soon as all the subscriber functions have been invoked, returning a Future that will eventually complete when all the futures returned by the subscriber functions have completed. fire_sync $distributor->fire_sync( $name, @args ) Invokes the named event, passing the arguments to the subscriber functions. This function synchronously waits until all the subscriber futures have completed, and will return once they have all done so. Note that since this method calls the get method on the Future instance returned by "fire_async", it is required that this either be an immediate, or be some subclass that can actually perform the await operation. This should be the case if it is provided by an event framework or similar, or custom application logic. TODO Some of these ideas appear in the "Event-Reflexive Progamming" series of blog posts, and may be suitable for implementation here. All of these ideas are simply for consideration; there is no explicit promise that any of these will actually be implemented. * Unsubscription from events. * Define (or document the lack of) ordering between subscriptions of a given event. * Refine the failure-handling semantics of signals. * Ability to invoke signals after the current one is finished, by deferring the fire method. Should this be a new fire_* method, or a property of the signal itself? * More control over the semantics of value-returning events - scatter/map/gather pattern. * Sub-heirarchies of events. * Subclasses for specific event frameworks (IO::Async). * Subclasses (or other behaviours) for out-of-process event serialisation and subscribers. * Event parameter filtering mechanics - allows parametric heirarchies, instrumentation logging, efficient out-of-process subscribers. SEE ALSO Event-Reflexive Programming AUTHOR Paul Evans Event-Distributor-0.05/lib000755001750001750 013325370231 14315 5ustar00leoleo000000000000Event-Distributor-0.05/lib/Event000755001750001750 013325370231 15376 5ustar00leoleo000000000000Event-Distributor-0.05/lib/Event/Distributor.pm000444001750001750 2254413325370231 20432 0ustar00leoleo000000000000# You may distribute under the terms of either the GNU General Public License # or the Artistic License (the same terms as Perl itself) # # (C) Paul Evans, 2014-2018 -- leonerd@leonerd.org.uk package Event::Distributor; use strict; use warnings; our $VERSION = '0.05'; use Carp; use Syntax::Keyword::Try; use Future; use Event::Distributor::Signal; use Event::Distributor::Action; use Event::Distributor::Query; =head1 NAME C - a simple in-process pub/sub mechanism =head1 SYNOPSIS use Event::Distributor; my $dist = Event::Distributor->new; $dist->declare_signal( "announce" ); $dist->subscribe_sync( announce => sub { my ( $message ) = @_; say $message; }); $dist->subscribe_async( announce => sub { my ( $message ) = @_; return $async_http->POST( "http://server/message", $message ); }); $dist->fire_sync( announce => "Hello, world!" ); =head1 DESCRIPTION Instances of this class provide a simple publish/subscribe mechanism within a single process, for either synchronous or L-based asynchronous use. A given instance has a set of named events. Subscribers are C references attached to a named event. Publishers can declare the existence of a named event, and then later invoke it by passing in arguments, which are distributed to all of the subscribers of that named event. It is specifically I an error to request to subscribe an event that has not yet been declared, in order to allow multiple modules of code to be loaded and subscribe events the others publish, without introducing loading order dependencies. An event only needs to be declared by the time it is fired. Natively all of the events provided by the distributor are fully-asynchronous in nature. Each subscriber is expected to return a L instance which will indicate its completion; the results of these are merged into a single future returned by the fire method itself. However, to support synchronous or semi-synchronous programs using it, both the observe and invoke methods also have a synchronous variant. Note however, that this module does not provide any kind of asynchronous detachment of synchronous functions; using the L method to subscribe a long-running blocking function will cause the C methods to block until that method returns. To achieve a truely-asynchronous experience the attached code will need to use some kind of asynchronous event system. This module is very-much a work-in-progress, and many ideas may still be added or changed about it. It is the start of a concrete implementaion of some of the ideas in my "Event-Reflexive Programming" series of blog posts. See the L and L sections for more detail. =head1 EVENTS Each of the events known by a distributor has a name. Conceptually each also has a type. Currently there are three types of event, a "signal", an "action", and a "query". =over 2 =item * A signal event simply informs subscribers that some event or condition has occurred. Additional arguments can be passed from the invoker to the subscribers, but subscriptions are not expected to return a meaningful value, nor does firing this event return a value. All subscriber functions are invoked sequentually and synchronously by a C method (though, of course, asynchronous subscribers synchronously return a future instance, which allows them to continue working asynchronously). =item * An action event requires a single subscriber, and represents a request from the invoker to the subscriber to perform some activity. This behaves much like a regular (L-returning) method call, except that the indirection mechanism of the distributor allows a more flexible method of connection between the two sides. =item * A query event invokes subscriber code expecting a successful return, returning the first result that is successful. If a synchronous subscriber returns a result, or if an asynchronous one returns a successful immediate Future, then no further subscribers are invoked, and that result is taken immediately. Any other pending Futures are then cancelled. =back =cut sub new { my $class = shift; my $self = bless { events => {}, pre_registration => {}, }, $class; return $self; } =head1 METHODS =cut sub _add_event { my $self = shift; my ( $name, $event ) = @_; $self->{events}{$name} and croak "Cannot declare an event '$name' a second time"; $self->{events}{$name} = $event; if( my $subs = delete $self->{pre_registration}{$name} ) { $event->subscribe( $_ ) for @$subs; } } =head2 declare_signal $distributor->declare_signal( $name ) Declares a new "signal" event of the given name. =cut sub declare_signal { my $self = shift; my ( $name ) = @_; $self->_add_event( $name, Event::Distributor::Signal->new ); } =head2 declare_action $distributor->declare_action( $name ) I Declares a new "action" event of the given name. =cut sub declare_action { my $self = shift; my ( $name ) = @_; $self->_add_event( $name, Event::Distributor::Action->new ); } =head2 declare_query $distributor->declare_query( $name ) I Declares a new "query" event of the given name. =cut sub declare_query { my $self = shift; my ( $name ) = @_; $self->_add_event( $name, Event::Distributor::Query->new ); } =head2 subscribe_async $distributor->subscribe_async( $name, $code ) Adds a new C reference to the list of subscribers for the named event. This subscriber is expected to return a L that will eventually yield its result. When invoked the code will be passed the distributor object itself and the list of arguments, and is expected to return a L. $f = $code->( $distributor, @args ) =cut sub subscribe_async { my $self = shift; my ( $name, $code ) = @_; if( my $event = $self->{events}{$name} ) { $event->subscribe( $code ); } else { push @{ $self->{pre_registration}{$name} }, $code; } } =head2 subscribe_sync $distributor->subscribe_sync( $name, $code ) Adds a new C reference to the list of subscribers for the named event. This subscriber is expected to perform its work synchronously and return its result immediately. In non-blocking or asynchronous applications, this method should only be used for simple subscribers which can immediately return having completed their work. If the work is likely to take some time by blocking on external factors, consider instead using the L method. When invoked the code will be passed the distributor object itself and the list of arguments. $code->( $distributor, @args ) =cut sub subscribe_sync { my $self = shift; my ( $name, $code ) = @_; $self->subscribe_async( $name, sub { my @args = @_; try { return Future->done( $code->( @args ) ); } catch { return Future->fail( $@ ); } }); } =head2 fire_async $f = $distributor->fire_async( $name, @args ) Invokes the named event, passing the arguments to the subscriber functions. This function returns as soon as all the subscriber functions have been invoked, returning a L that will eventually complete when all the futures returned by the subscriber functions have completed. =cut sub fire_async { my $self = shift; my ( $name, @args ) = @_; my $event = $self->{events}{$name} or croak "Cannot fire an event '$name' when it doesn't exist"; $event->fire( $self, @args ); } =head2 fire_sync $distributor->fire_sync( $name, @args ) Invokes the named event, passing the arguments to the subscriber functions. This function synchronously waits until all the subscriber futures have completed, and will return once they have all done so. Note that since this method calls the C method on the Future instance returned by L, it is required that this either be an immediate, or be some subclass that can actually perform the await operation. This should be the case if it is provided by an event framework or similar, or custom application logic. =cut sub fire_sync { my $self = shift; $self->fire_async( @_ )->get; } =head1 TODO Some of these ideas appear in the "Event-Reflexive Progamming" series of blog posts, and may be suitable for implementation here. All of these ideas are simply for consideration; there is no explicit promise that any of these will actually be implemented. =over 4 =item * Unsubscription from events. =item * Define (or document the lack of) ordering between subscriptions of a given event. =item * Refine the failure-handling semantics of signals. =item * Ability to invoke signals after the current one is finished, by deferring the C method. Should this be a new C method, or a property of the signal itself? =item * More control over the semantics of value-returning events - scatter/map/gather pattern. =item * Sub-heirarchies of events. =item * Subclasses for specific event frameworks (L). =item * Subclasses (or other behaviours) for out-of-process event serialisation and subscribers. =item * Event parameter filtering mechanics - allows parametric heirarchies, instrumentation logging, efficient out-of-process subscribers. =back =head1 SEE ALSO =over 4 =item L =back =head1 AUTHOR Paul Evans =cut 0x55AA; Event-Distributor-0.05/lib/Event/Distributor000755001750001750 013325370231 17710 5ustar00leoleo000000000000Event-Distributor-0.05/lib/Event/Distributor/Action.pm000444001750001750 205213325370231 21617 0ustar00leoleo000000000000# You may distribute under the terms of either the GNU General Public License # or the Artistic License (the same terms as Perl itself) # # (C) Paul Evans, 2015 -- leonerd@leonerd.org.uk package Event::Distributor::Action; use strict; use warnings; use base qw( Event::Distributor::_Event ); our $VERSION = '0.05'; use Carp; use Future; =head1 NAME C - an event that requires one subscriber =head1 DESCRIPTION This subclass of L requires exactly one subscriber at the time that it is invoked. It passes on the caller's arguments to the subscriber, and the subscriber's return value back to the caller. =cut sub subscribe { my $self = shift; $self->subscribers and croak "Too many subscribers"; $self->SUPER::subscribe( @_ ); } sub fire { my $self = shift; my ( $dist, @args ) = @_; my @subs = $self->subscribers or return Future->fail( "No subscribers" ); Future->call( $subs[0], $dist, @args ); } =head1 AUTHOR Paul Evans =cut 0x55AA; Event-Distributor-0.05/lib/Event/Distributor/Query.pm000444001750001750 271713325370231 21517 0ustar00leoleo000000000000# You may distribute under the terms of either the GNU General Public License # or the Artistic License (the same terms as Perl itself) # # (C) Paul Evans, 2014-2017 -- leonerd@leonerd.org.uk package Event::Distributor::Query; use strict; use warnings; use base qw( Event::Distributor::_Event ); our $VERSION = '0.05'; use Future; =head1 NAME C - an event that collects a result =head1 DESCRIPTION This subclass of L invokes each of its subscribers in turn, yielding either the (first) successful and non-empty result, or a failure if they all fail. Yields a (successful) empty result if there are no subscribers. =cut sub fire { my $self = shift; my ( $dist, @args ) = @_; my $await = $self->{await}; my @f; foreach my $sub ( $self->subscribers ) { my $f = $sub->( $dist, @args )->then_with_f( sub { my $f = shift; return $f if @_; die "No result\n"; }); push @f, $f; last if $f->is_ready and !$f->failure; } return Future->done if !@f; return Future->needs_any( @f )->then( sub { my @results = @_; # TODO: conversions? Future->done( @results ); })->else_with_f( sub { my $f = shift; my @other_fails = grep { $_->failure ne "No result\n" } $f->failed_futures; return $other_fails[0] if @other_fails; Future->done(); }); } =head1 AUTHOR Paul Evans =cut 0x55AA Event-Distributor-0.05/lib/Event/Distributor/Signal.pm000444001750001750 307213325370231 21622 0ustar00leoleo000000000000# You may distribute under the terms of either the GNU General Public License # or the Artistic License (the same terms as Perl itself) # # (C) Paul Evans, 2014-2015 -- leonerd@leonerd.org.uk package Event::Distributor::Signal; use strict; use warnings; use base qw( Event::Distributor::_Event ); our $VERSION = '0.05'; use Future; =head1 NAME C - an event that returns no result =head1 DESCRIPTION This subclass of L invokes each of its subscribers in turn, ensuring each has a chance to be invoked regardless of the result of the others. Its L succeeds (with no value) if no subscriber failed. If one subscriber failed, the C fails in the same way. If two or more subscribers fail, the resulting C fails with a message composed by combining all the individual messages, in the C category, whose failure details are a list of the failed component futures. =cut sub fire { my $self = shift; my ( $dist, @args ) = @_; return Future->wait_all( map { my $sub = $_; local $_; # protect against corruption of $_ Future->call( $sub, $dist, @args ); } $self->subscribers )->then( sub { my @failed = grep { $_->failure } @_; return Future->done() if !@failed; return $failed[0] if @failed == 1; return Future->fail( "Multiple subscribers failed:\n" . join( "", map { " | " . $_->failure } @failed ), distributor => @failed, ); }); } =head1 AUTHOR Paul Evans =cut 0x55AA Event-Distributor-0.05/lib/Event/Distributor/_Event.pm000444001750001750 343113325370231 21624 0ustar00leoleo000000000000# You may distribute under the terms of either the GNU General Public License # or the Artistic License (the same terms as Perl itself) # # (C) Paul Evans, 2015 -- leonerd@leonerd.org.uk package Event::Distributor::_Event; use strict; use warnings; our $VERSION = '0.05'; use Future; =head1 NAME C - base class for L events =head1 DESCRIPTION This class is the base from which the following actual classes are derived: =over 2 =item * L =item * L =back Instances of this class shouldn't be directly created by end-user code, but it is documented here in order to list the shared methods available on all the subclasses. =cut sub new { my $class = shift; return bless { subscribers => [], }, $class; } =head1 METHODS =cut =head2 subscribe $event->subscribe( $code ) Adds a new C reference that subscribes to the event. This code is expected to return a L instance. =cut sub subscribe { my $self = shift; my ( $code ) = @_; push @{ $self->{subscribers} }, $code; } =head2 subscribers @codes = $event->subscribers Returns a list of C references previously subscribed. =cut sub subscribers { my $self = shift; return @{ $self->{subscribers} }; } =head1 EXPECTED METHODS Subclasses are expected to implement the following methods: =cut =head2 fire $f = $event->fire( @args ) Invoked by L to actually run the signal. This is expected to invoke any or all subscribers in whatever manner it implements, passing arguments as required, and collecting results in some way to provide as the eventual answer of the L it returns. =cut =head1 AUTHOR Paul Evans =cut 0x55AA Event-Distributor-0.05/t000755001750001750 013325370231 14012 5ustar00leoleo000000000000Event-Distributor-0.05/t/00use.t000444001750001750 41413325370231 15247 0ustar00leoleo000000000000#!/usr/bin/perl use strict; use warnings; use Test::More; use_ok( 'Event::Distributor' ); use_ok( 'Event::Distributor::_Event' ); use_ok( 'Event::Distributor::Signal' ); use_ok( 'Event::Distributor::Action' ); use_ok( 'Event::Distributor::Query' ); done_testing; Event-Distributor-0.05/t/01signal.t000444001750001750 415313325370231 15755 0ustar00leoleo000000000000#!/usr/bin/perl use strict; use warnings; use Test::More; use Test::Fatal; use Future; use Event::Distributor::Signal; # async->async { my $sig = Event::Distributor::Signal->new; my $called_f; my @called_args; $sig->subscribe( sub { @called_args = @_; return $called_f = Future->new }); my $f = $sig->fire( "args", "here" ); ok( $f, '->fire yields Future' ); ok( !$f->is_ready, '$f not yet ready' ); is_deeply( \@called_args, [ "args", "here" ], 'Args to subscriber' ); $called_f->done(); ok( $f->is_ready, '$f is now ready after $called_f->done' ); is_deeply( [ $f->get ], [], '$f->get yields nothing' ); } # two subscribers { my $sig = Event::Distributor::Signal->new; my $f1; $sig->subscribe( sub { $f1 = Future->new } ); my $f2; $sig->subscribe( sub { $f2 = Future->new } ); my $f = $sig->fire; ok( $f1 && $f2, 'Both subscribers invoked' ); $f1->done; ok( !$f->is_ready, 'Result future still waiting after $f1->done' ); $f2->done; ok( $f->is_ready, 'Result future now done after $f2->done' ); } # failure { my $sig = Event::Distributor::Signal->new; $sig->subscribe( sub { die "Failure" } ); my $called; $sig->subscribe( sub { $called++; Future->done } ); like( exception { $sig->fire->get }, qr/^Failure /, '->fire_sync raises exception' ); ok( $called, 'second subscriber still invoked after first failure' ); } # Multiple failures { my $sig = Event::Distributor::Signal->new; $sig->subscribe( sub { die "One failed\n" } ); $sig->subscribe( sub { die "Two failed\n" } ); is( exception { $sig->fire->get }, "Multiple subscribers failed:\n" . " | One failed\n" . " | Two failed\n", '->fire_sync raises special multiple failure' ); } # subscribers cannot corrupt object by $_ leakage { my $sig = Event::Distributor::Signal->new; my $called; $sig->subscribe( sub { $called++; undef $_; Future->done } ); Future->needs_all( $sig->fire( whail => ), $sig->fire( whail => ), )->get; is( $called, 2, 'Subscriber invoked twice' ); } done_testing; Event-Distributor-0.05/t/02action.t000444001750001750 201513325370231 15751 0ustar00leoleo000000000000#!/usr/bin/perl use strict; use warnings; use Test::More; use Test::Fatal; use Future; use Event::Distributor::Action; { my $act = Event::Distributor::Action->new; my $called_f; my @called_args; $act->subscribe( sub { @called_args = @_; return $called_f = Future->new; }); my $f = $act->fire( "args", "here" ); ok( $f, '->fire yields Future' ); ok( !$f->is_ready, '$f not yet ready' ); is_deeply( \@called_args, [ "args", "here" ], 'Args to subscriber' ); $called_f->done( "result" ); ok( $f->is_ready, '$f is now ready after $called_f->done' ); is_deeply( [ $f->get ], [ "result" ], '$f->get yields subscriber result' ); } # No subscribers { my $act = Event::Distributor::Action->new; my $f = $act->fire(); ok( $f->failure, '->fire with no subscribers fails' ); } # Many subscribers { my $act = Event::Distributor::Action->new; $act->subscribe( sub { } ); ok( exception { $act->subscribe( sub { } ) }, 'Second ->subscribe fails' ); } done_testing; Event-Distributor-0.05/t/03query.t000444001750001750 274113325370231 15650 0ustar00leoleo000000000000#!/usr/bin/perl use strict; use warnings; use Test::More; use Future; use Event::Distributor::Query; { my $query = Event::Distributor::Query->new; $query->subscribe( sub { Future->done( "The result", "here" ); }); my @result = $query->fire->get; is_deeply( \@result, [ "The result", "here" ], 'result of query event' ); } # two sync subscribers { my $query = Event::Distributor::Query->new; my $called; $query->subscribe( sub { $called++; Future->done( 123 ) } ); $query->subscribe( sub { $called++; Future->done( 456 ) } ); my $result = $query->fire->get; is( $result, 123, 'query event takes first result' ); is( $called, 1, 'query event does not invoke later sync subscribers' ); } # no subscribers { my $query = Event::Distributor::Query->new; my $result = $query->fire->get; is( $result, undef, 'query yields undef with no subscribers' ); } # empty result counts as failure { my $query = Event::Distributor::Query->new; $query->subscribe( sub { Future->done() } ); $query->subscribe( sub { Future->done( "second" ) } ); is( scalar $query->fire->get, "second", 'query considers empty results failures' ); } # all empty results yields empty result { my $query = Event::Distributor::Query->new; $query->subscribe( sub { Future->done() } ); my $f = $query->fire; ok( !$f->is_failed, 'query yielding empty result does not fail' ); is_deeply( [ $f->get ], [], 'query yields empty result' ); } done_testing; Event-Distributor-0.05/t/10dist.t000444001750001750 401513325370231 15440 0ustar00leoleo000000000000#!/usr/bin/perl use strict; use warnings; use Test::More; use Future; use Event::Distributor; # async->async { my $dist = Event::Distributor->new; $dist->declare_signal( "alert" ); my $called_f; my $called_dist; my @called_args; $dist->subscribe_async( alert => sub { $called_dist = shift; @called_args = @_; return $called_f = Future->new }); my $f = $dist->fire_async( alert => "args", "here" ); ok( $f, '->fire_async yields signal' ); ok( !$f->is_ready, '$f not yet ready' ); is( $called_dist, $dist, 'First arg to subscriber is $dist' ); is_deeply( \@called_args, [ "args", "here" ], 'Args to subscriber' ); $called_f->done(); ok( $f->is_ready, '$f is now ready after $called_f->done' ); is_deeply( [ $f->get ], [], '$f->get yields nothing' ); } # pre-registration of subscriber { my $dist = Event::Distributor->new; my $called; $dist->subscribe_sync( wibble => sub { $called++ } ); $dist->declare_signal( "wibble" ); $dist->fire_sync( wibble => ); ok( $called, 'Preregistered subscriber is invoked' ); } # subscribe_sync { my $dist = Event::Distributor->new; $dist->declare_signal( "alert" ); my $called; $dist->subscribe_sync( alert => sub { $called++ } ); my $f = $dist->fire_async( alert => ); ok( $f->is_ready, '$f already ready for only sync subscriber' ); ok( $called, 'Synchronous subscriber actually called' ); } # fire_sync { my $dist = Event::Distributor->new; $dist->declare_signal( "alert" ); $dist->subscribe_async( alert => sub { Future->done } ); $dist->fire_sync( alert => ); pass( 'Synchronous fire returns immediately' ); } # subscriber death is not fatal to queries { my $dist = Event::Distributor->new; $dist->declare_query( "question" ); $dist->subscribe_sync( question => sub { die "Oopsie\n" } ); $dist->subscribe_sync( question => sub { return "OK" } ); is( $dist->fire_sync( question => ), "OK", 'Synchronous subscriber death is not fatal to query' ); } done_testing; Event-Distributor-0.05/t/99pod.t000444001750001750 25713325370231 15264 0ustar00leoleo000000000000#!/usr/bin/perl use strict; use warnings; use Test::More; eval "use Test::Pod 1.00"; plan skip_all => "Test::Pod 1.00 required for testing POD" if $@; all_pod_files_ok();