1#  You may distribute under the terms of either the GNU General Public License
2#  or the Artistic License (the same terms as Perl itself)
3#
4#  (C) Paul Evans, 2008-2013 -- leonerd@leonerd.org.uk
5
6package IO::Async;
7
8use strict;
9use warnings;
10
11# This package contains no code other than a declaration of the version.
12# It is provided simply to keep CPAN happy:
13#   cpan -i IO::Async
14
15our $VERSION = '0.800';
16
17=head1 NAME
18
19C<IO::Async> - Asynchronous event-driven programming
20
21=head1 SYNOPSIS
22
23   use IO::Async::Stream;
24   use IO::Async::Loop;
25
26   my $loop = IO::Async::Loop->new;
27
28   $loop->connect(
29      host     => "some.other.host",
30      service  => 12345,
31      socktype => 'stream',
32
33      on_stream => sub {
34         my ( $stream ) = @_;
35
36         $stream->configure(
37            on_read => sub {
38               my ( $self, $buffref, $eof ) = @_;
39
40               while( $$buffref =~ s/^(.*\n)// ) {
41                  print "Received a line $1";
42               }
43
44               return 0;
45            }
46         );
47
48         $stream->write( "An initial line here\n" );
49
50         $loop->add( $stream );
51      },
52
53      on_resolve_error => sub { die "Cannot resolve - $_[-1]\n"; },
54      on_connect_error => sub { die "Cannot connect - $_[0] failed $_[-1]\n"; },
55   );
56
57   $loop->run;
58
59=head1 DESCRIPTION
60
61This collection of modules allows programs to be written that perform
62asynchronous filehandle IO operations. A typical program using them would
63consist of a single subclass of L<IO::Async::Loop> to act as a container of
64other objects, which perform the actual IO work required by the program. As
65well as IO handles, the loop also supports timers and signal handlers, and
66includes more higher-level functionality built on top of these basic parts.
67
68Because there are a lot of classes in this collection, the following overview
69gives a brief description of each.
70
71=head2 Notifiers
72
73The base class of all the event handling subclasses is L<IO::Async::Notifier>.
74It does not perform any IO operations itself, but instead acts as a base class
75to build the specific IO functionality upon. It can also coordinate a
76collection of other Notifiers contained within it, forming a tree structure.
77
78The following sections describe particular types of Notifier.
79
80=head2 File Handle IO
81
82An L<IO::Async::Handle> object is a Notifier that represents a single IO handle
83being managed. While in most cases it will represent a single filehandle, such
84as a socket (for example, an L<IO::Socket::INET> connection), it is possible
85to have separate reading and writing handles (most likely for a program's
86C<STDIN> and C<STDOUT> streams, or a pair of pipes connected to a child
87process).
88
89The L<IO::Async::Stream> class is a subclass of L<IO::Async::Handle> which
90maintains internal incoming and outgoing data buffers. In this way, it
91implements bidirectional buffering of a byte stream, such as a TCP socket. The
92class automatically handles reading of incoming data into the incoming buffer,
93and writing of the outgoing buffer. Methods or callbacks are used to inform
94when new incoming data is available, or when the outgoing buffer is empty.
95
96While stream-based sockets can be handled using using L<IO::Async::Stream>,
97datagram or raw sockets do not provide a bytestream. For these, the
98L<IO::Async::Socket> class is another subclass of L<IO::Async::Handle> which
99maintains an outgoing packet queue, and informs of packet receipt using a
100callback or method.
101
102The L<IO::Async::Listener> class is another subclass of L<IO::Async::Handle>
103which facilitates the use of C<listen(2)>-mode sockets. When a new connection
104is available on the socket it will C<accept(2)> it and pass the new client
105socket to its callback function.
106
107=head2 Timers
108
109An L<IO::Async::Timer::Absolute> object represents a timer that expires at a
110given absolute time in the future.
111
112An L<IO::Async::Timer::Countdown> object represents a count time timer, which
113will invoke a callback after a given delay. It can be stopped and restarted.
114
115An L<IO::Async::Timer::Periodic> object invokes a callback at regular intervals
116from its initial start time. It is reliable and will not drift due to the time
117taken to run the callback.
118
119The L<IO::Async::Loop> also supports methods for managing timed events on a
120lower level. Events may be absolute, or relative in time to the time they are
121installed.
122
123=head2 Signals
124
125An L<IO::Async::Signal> object represents a POSIX signal, which will invoke a
126callback when the given signal is received by the process. Multiple objects
127watching the same signal can be used; they will all invoke in no particular
128order.
129
130=head2 Processes Management
131
132An L<IO::Async::PID> object invokes its event when a given child process
133exits. An L<IO::Async::Process> object can start a new child process running
134either a given block of code, or executing a given command, set up pipes on
135its filehandles, write to or read from these pipes, and invoke its event when
136the child process exits.
137
138=head2 Loops
139
140The L<IO::Async::Loop> object class represents an abstract collection of
141L<IO::Async::Notifier> objects, and manages the actual filehandle IO
142watchers, timers, signal handlers, and other functionality. It performs all
143of the abstract collection management tasks, and leaves the actual OS
144interactions to a particular subclass for the purpose.
145
146L<IO::Async::Loop::Poll> uses an L<IO::Poll> object for this test.
147
148L<IO::Async::Loop::Select> uses the C<select(2)> syscall.
149
150Other subclasses of loop may appear on CPAN under their own dists; see the
151L</SEE ALSO> section below for more detail.
152
153As well as these general-purpose classes, the L<IO::Async::Loop> constructor
154also supports looking for OS-specific subclasses, in case a more efficient
155implementation exists for the specific OS it runs on.
156
157=head2 Child Processes
158
159The L<IO::Async::Loop> object provides a number of methods to facilitate the
160running of child processes. C<spawn_child> is primarily a wrapper around the
161typical C<fork(2)>/C<exec(2)> style of starting child processes, and
162C<run_child> provide a method similar to perl's C<readpipe> (which is used
163to implement backticks C<``>).
164
165=head2 File Change Watches
166
167The L<IO::Async::File> object observes changes to C<stat(2)> properties of a
168file, directory, or other filesystem object. It invokes callbacks when
169properties change. This is used by L<IO::Async::FileStream> which presents
170the same events as a L<IO::Async::Stream> but operates on a regular file on
171the filesystem, observing it for updates.
172
173=head2 Asynchronous Co-routines and Functions
174
175The C<IO::Async> framework generally provides mechanisms for multiplexing IO
176tasks between different handles, so there aren't many occasions when it is
177necessary to run code in another thread or process. Two cases where this does
178become useful are when:
179
180=over 4
181
182=item *
183
184A large amount of computationally-intensive work needs to be performed.
185
186=item *
187
188An OS or library-level function needs to be called, that will block, and
189no asynchronous version is supplied.
190
191=back
192
193For these cases, an instance of L<IO::Async::Function> can be used around
194a code block, to execute it in a worker child process or set of processes.
195The code in the sub-process runs isolated from the main program, communicating
196only by function call arguments and return values. This can be used to solve
197problems involving state-less library functions.
198
199An L<IO::Async::Routine> object wraps a code block running in a separate
200process to form a kind of co-routine. Communication with it happens via
201L<IO::Async::Channel> objects. It can be used to solve any sort of problem
202involving keeping a possibly-stateful co-routine running alongside the rest of
203an asynchronous program.
204
205=head2 Futures
206
207An L<IO::Async::Future> object represents a single outstanding action that is
208yet to complete, such as a name resolution operation or a socket connection.
209It stands in contrast to a L<IO::Async::Notifier>, which is an object that
210represents an ongoing source of activity, such as a readable filehandle of
211bytes or a POSIX signal.
212
213Futures are a recent addition to the C<IO::Async> API and details are still
214subject to change and experimentation.
215
216In general, methods that support Futures return a new Future object to
217represent the outstanding operation. If callback functions are supplied as
218well, these will be fired in addition to the Future object becoming ready. Any
219failures that are reported will, in general, use the same conventions for the
220Future's C<fail> arguments to relate it to the legacy C<on_error>-style
221callbacks.
222
223   $on_NAME_error->( $message, @argmuents )
224
225   $f->fail( $message, NAME, @arguments )
226
227where C<$message> is a message intended for humans to read (so that this is
228the message displayed by C<< $f->get >> if the failure is not otherwise
229caught), C<NAME> is the name of the failing operation. If the failure is due
230to a failed system call, the value of C<$!> will be the final argument. The
231message should not end with a linefeed.
232
233=head2 Networking
234
235The L<IO::Async::Loop> provides several methods for performing network-based
236tasks. Primarily, the C<connect> and C<listen> methods allow the creation of
237client or server network sockets. Additionally, the C<resolve> method allows
238the use of the system's name resolvers in an asynchronous way, to resolve
239names into addresses, or vice versa. These methods are fully IPv6-capable if
240the underlying operating system is.
241
242=head2 Protocols
243
244The L<IO::Async::Protocol> class provides storage for a L<IO::Async::Handle>
245object, to act as a transport for some protocol. It allows a level of
246independence from the actual transport being for that protocol, allowing it to
247be easily reused. The L<IO::Async::Protocol::Stream> subclass provides further
248support for protocols based on stream connections, such as TCP sockets.
249
250=head1 TODO
251
252This collection of modules is still very much in development. As a result,
253some of the potentially-useful parts or features currently missing are:
254
255=over 4
256
257=item *
258
259Consider further ideas on Solaris' I<ports>, BSD's I<Kevents> and anything that
260might be useful on Win32.
261
262=item *
263
264Consider some form of persistent object wrapper in the form of an
265C<IO::Async::Object>, based on L<IO::Async::Routine>.
266
267=item *
268
269C<IO::Async::Protocol::Datagram>
270
271=item *
272
273Support for watching filesystem entries for change. Extract logic from
274L<IO::Async::File> and define a Loop watch/unwatch method pair.
275
276=item *
277
278Define more L<Future>-returning methods. Consider also one-shot Futures on
279things like L<IO::Async::Process> exits, or L<IO::Async::Handle> close.
280
281=back
282
283=head1 SUPPORT
284
285Bugs may be reported via RT at
286
287   https://rt.cpan.org/Public/Dist/Display.html?Name=IO-Async
288
289Support by IRC may also be found on F<irc.perl.org> in the F<#io-async>
290channel.
291
292=cut
293
294=head1 SEE ALSO
295
296As well as the two loops supplied in this distribution, many more exist on
297CPAN. At the time of writing this includes:
298
299=over 4
300
301=item *
302
303L<IO::Async::Loop::AnyEvent> - use IO::Async with AnyEvent
304
305=item *
306
307L<IO::Async::Loop::Epoll> - use IO::Async with epoll on Linux
308
309=item *
310
311L<IO::Async::Loop::Event> - use IO::Async with Event
312
313=item *
314
315L<IO::Async::Loop::EV> - use IO::Async with EV
316
317=item *
318
319L<IO::Async::Loop::Glib> - use IO::Async with Glib or GTK
320
321=item *
322
323L<IO::Async::Loop::KQueue> - use IO::Async with kqueue
324
325=item *
326
327L<IO::Async::Loop::Mojo> - use IO::Async with Mojolicious
328
329=item *
330
331L<IO::Async::Loop::POE> - use IO::Async with POE
332
333=item *
334
335L<IO::Async::Loop::Ppoll> - use IO::Async with ppoll(2)
336
337=back
338
339Additionally, some other event loops or modules also support being run on top
340of C<IO::Async>:
341
342=over 4
343
344=item *
345
346L<AnyEvent::Impl::IOAsync> - AnyEvent adapter for IO::Async
347
348=item *
349
350L<Gungho::Engine::IO::Async> - IO::Async Engine
351
352=item *
353
354L<POE::Loop::IO_Async> - IO::Async event loop support for POE
355
356=back
357
358=cut
359
360=head1 AUTHOR
361
362Paul Evans <leonerd@leonerd.org.uk>
363
364=cut
365
3660x55AA;
367