AnyEvent
view release on metacpan or search on metacpan
lib/AnyEvent.pm view on Meta::CPAN
technically possible.
Of course, AnyEvent comes with a big (and fully optional!) toolbox
of useful functionality, such as an asynchronous DNS resolver, 100%
non-blocking connects (even with TLS/SSL, IPv6 and on broken platforms
such as Windows) and lots of real-world knowledge and workarounds for
platform bugs and differences.
Now, if you I<do want> lots of policy (this can arguably be somewhat
useful) and you want to force your users to use the one and only event
model, you should I<not> use this module.
=head1 DESCRIPTION
L<AnyEvent> provides a uniform interface to various event loops. This
allows module authors to use event loop functionality without forcing
module users to use a specific event loop implementation (since more
than one event loop cannot coexist peacefully).
The interface itself is vaguely similar, but not identical to the L<Event>
module.
During the first call of any watcher-creation method, the module tries
to detect the currently loaded event loop by probing whether one of the
following modules is already loaded: L<EV>, L<AnyEvent::Loop>,
L<Event>, L<Glib>, L<Tk>, L<Event::Lib>, L<Qt>, L<POE>. The first one
found is used. If none are detected, the module tries to load the first
four modules in the order given; but note that if L<EV> is not
available, the pure-perl L<AnyEvent::Loop> should always work, so
the other two are not normally tried.
Because AnyEvent first checks for modules that are already loaded, loading
an event model explicitly before first using AnyEvent will likely make
that model the default. For example:
use Tk;
use AnyEvent;
# .. AnyEvent will likely default to Tk
The I<likely> means that, if any module loads another event model and
starts using it, all bets are off - this case should be very rare though,
as very few modules hardcode event loops without announcing this very
loudly.
The pure-perl implementation of AnyEvent is called C<AnyEvent::Loop>. Like
other event modules you can load it explicitly and enjoy the high
availability of that event loop :)
=head1 WATCHERS
AnyEvent has the central concept of a I<watcher>, which is an object that
stores relevant data for each kind of event you are waiting for, such as
the callback to call, the file handle to watch, etc.
These watchers are normal Perl objects with normal Perl lifetime. After
creating a watcher it will immediately "watch" for events and invoke the
callback when the event occurs (of course, only when the event model
is in control).
Note that B<callbacks must not permanently change global variables>
potentially in use by the event loop (such as C<$_> or C<$[>) and that B<<
callbacks must not C<die> >>. The former is good programming practice in
Perl and the latter stems from the fact that exception handling differs
widely between event loops.
To disable a watcher you have to destroy it (e.g. by setting the
variable you store it in to C<undef> or otherwise deleting all references
to it).
All watchers are created by calling a method on the C<AnyEvent> class.
Many watchers either are used with "recursion" (repeating timers for
example), or need to refer to their watcher object in other ways.
One way to achieve that is this pattern:
my $w; $w = AnyEvent->type (arg => value ..., cb => sub {
# you can use $w here, for example to undef it
undef $w;
});
Note that C<my $w; $w => combination. This is necessary because in Perl,
my variables are only visible after the statement in which they are
declared.
=head2 I/O WATCHERS
$w = AnyEvent->io (
fh => <filehandle_or_fileno>,
poll => <"r" or "w">,
cb => <callback>,
);
You can create an I/O watcher by calling the C<< AnyEvent->io >> method
with the following mandatory key-value pairs as arguments:
C<fh> is the Perl I<file handle> (or a naked file descriptor) to watch
for events (AnyEvent might or might not keep a reference to this file
handle). Note that only file handles pointing to things for which
non-blocking operation makes sense are allowed. This includes sockets,
most character devices, pipes, fifos and so on, but not for example files
or block devices.
C<poll> must be a string that is either C<r> or C<w>, which creates a
watcher waiting for "r"eadable or "w"ritable events, respectively.
C<cb> is the callback to invoke each time the file handle becomes ready.
Although the callback might get passed parameters, their value and
presence is undefined and you cannot rely on them. Portable AnyEvent
callbacks cannot use arguments passed to I/O watcher callbacks.
The I/O watcher might use the underlying file descriptor or a copy of it.
You must not close a file handle as long as any watcher is active on the
underlying file descriptor.
Some event loops issue spurious readiness notifications, so you should
always use non-blocking calls when reading/writing from/to your file
handles.
lib/AnyEvent.pm view on Meta::CPAN
consider for AnyEvent.
B<Prima> is not supported as nobody seems to be using it, but it has a POE
backend, so it can be supported through POE.
AnyEvent knows about both L<Prima> and L<Wx>, however, and will try to
load L<POE> when detecting them, in the hope that POE will pick them up,
in which case everything will be automatic.
=item Known event loops outside the AnyEvent distribution
The following event loops or programs support AnyEvent by providing their
own AnyEvent backend. They will be picked up automatically.
urxvt::anyevent available to rxvt-unicode extensions
=back
=head1 GLOBAL VARIABLES AND FUNCTIONS
These are not normally required to use AnyEvent, but can be useful to
write AnyEvent extension modules.
=over 4
=item $AnyEvent::MODEL
Contains C<undef> until the first watcher is being created, before the
backend has been autodetected.
Afterwards it contains the event model that is being used, which is the
name of the Perl class implementing the model. This class is usually one
of the C<AnyEvent::Impl::xxx> modules, but can be any other class in the
case AnyEvent has been extended at runtime (e.g. in I<rxvt-unicode> it
will be C<urxvt::anyevent>).
=item AnyEvent::detect
Returns C<$AnyEvent::MODEL>, forcing autodetection of the event model
if necessary. You should only call this function right before you would
have created an AnyEvent watcher anyway, that is, as late as possible at
runtime, and not e.g. during initialisation of your module.
The effect of calling this function is as if a watcher had been created
(specifically, actions that happen "when the first watcher is created"
happen when calling detetc as well).
If you need to do some initialisation before AnyEvent watchers are
created, use C<post_detect>.
=item $guard = AnyEvent::post_detect { BLOCK }
Arranges for the code block to be executed as soon as the event model is
autodetected (or immediately if that has already happened).
The block will be executed I<after> the actual backend has been detected
(C<$AnyEvent::MODEL> is set), so it is possible to do some initialisation
only when AnyEvent is actually initialised - see the sources of
L<AnyEvent::AIO> to see how this is used.
The most common usage is to create some global watchers, without forcing
event module detection too early. For example, L<AnyEvent::AIO> creates
and installs the global L<IO::AIO> watcher in a C<post_detect> block to
avoid autodetecting the event module at load time.
If called in scalar or list context, then it creates and returns an object
that automatically removes the callback again when it is destroyed (or
C<undef> when the hook was immediately executed). See L<AnyEvent::AIO> for
a case where this is useful.
Example: Create a watcher for the IO::AIO module and store it in
C<$WATCHER>, but do so only do so after the event loop is initialised.
our WATCHER;
my $guard = AnyEvent::post_detect {
$WATCHER = AnyEvent->io (fh => IO::AIO::poll_fileno, poll => 'r', cb => \&IO::AIO::poll_cb);
};
# the ||= is important in case post_detect immediately runs the block,
# as to not clobber the newly-created watcher. assigning both watcher and
# post_detect guard to the same variable has the advantage of users being
# able to just C<undef $WATCHER> if the watcher causes them grief.
$WATCHER ||= $guard;
=item @AnyEvent::post_detect
This is a lower level interface then C<AnyEvent::post_detect> (the
function). This variable is mainly useful for modules that can do
something useful when AnyEvent is used and thus want to know when it
is initialised, but do not need to even load it by default. This array
provides the means to hook into AnyEvent passively, without loading it.
Here is how it works: If there are any code references in this array (you
can C<push> to it before or after loading AnyEvent), then they will be
called directly after the event loop has been chosen.
You should check C<$AnyEvent::MODEL> before adding to this array, though:
if it is defined then the event loop has already been detected, and the
array will be ignored.
Best use C<AnyEvent::post_detect { BLOCK }> when your application allows
it, as it takes care of these details.
Example: To load Coro::AnyEvent whenever Coro and AnyEvent are used
together, you could put this into Coro (this is the actual code used by
Coro to accomplish this):
if (defined $AnyEvent::MODEL) {
# AnyEvent already initialised, so load Coro::AnyEvent
require Coro::AnyEvent;
} else {
# AnyEvent not yet initialised, so make sure to load Coro::AnyEvent
# as soon as it is
push @AnyEvent::post_detect, sub { require Coro::AnyEvent };
}
=item AnyEvent::postpone { BLOCK }
Arranges for the block to be executed as soon as possible, but not before
the call itself returns. In practise, the block will be executed just
before the event loop polls for new events, or shortly afterwards.
lib/AnyEvent.pm view on Meta::CPAN
? sub($$) {
ioctl $_[0], 0x8004667e, pack "L", $_[1]; # FIONBIO
}
: sub($$) {
fcntl $_[0], AnyEvent::F_SETFL, $_[1] ? AnyEvent::O_NONBLOCK : 0;
}
;
}
sub fh_block($) {
_fh_nonblocking shift, 0
}
sub fh_unblock($) {
_fh_nonblocking shift, 1
}
our @models = (
[EV:: => AnyEvent::Impl::EV::],
[AnyEvent::Loop:: => AnyEvent::Impl::Perl::],
# everything below here will not (normally) be autoprobed
# as the pure perl backend should work everywhere
# and is usually faster
[Irssi:: => AnyEvent::Impl::Irssi::], # Irssi has a bogus "Event" package, so msut be near the top
[Event:: => AnyEvent::Impl::Event::], # slow, stable
[Glib:: => AnyEvent::Impl::Glib::], # becomes extremely slow with many watchers
# everything below here should not be autoloaded
[Event::Lib:: => AnyEvent::Impl::EventLib::], # too buggy
[Tk:: => AnyEvent::Impl::Tk::], # crashes with many handles
[UV:: => AnyEvent::Impl::UV::], # switched from libev, added back all bugs imaginable
[Qt:: => AnyEvent::Impl::Qt::], # requires special main program
[POE::Kernel:: => AnyEvent::Impl::POE::], # lasciate ogni speranza
[Wx:: => AnyEvent::Impl::POE::],
[Prima:: => AnyEvent::Impl::POE::],
[IO::Async::Loop:: => AnyEvent::Impl::IOAsync::], # a bitch to autodetect
[Cocoa::EventLoop:: => AnyEvent::Impl::Cocoa::],
[FLTK:: => AnyEvent::Impl::FLTK::],
);
our @isa_hook;
sub _isa_set {
my @pkg = ("AnyEvent", (map $_->[0], grep defined, @isa_hook), $MODEL);
@{"$pkg[$_-1]::ISA"} = $pkg[$_]
for 1 .. $#pkg;
grep $_ && $_->[1], @isa_hook
and AE::_reset ();
}
# used for hooking AnyEvent::Strict and AnyEvent::Debug::Wrap into the class hierarchy
sub _isa_hook($$;$) {
my ($i, $pkg, $reset_ae) = @_;
$isa_hook[$i] = $pkg ? [$pkg, $reset_ae] : undef;
_isa_set;
}
# all autoloaded methods reserve the complete glob, not just the method slot.
# due to bugs in perls method cache implementation.
our @methods = qw(io timer time now now_update signal child idle condvar);
sub detect() {
return $MODEL if $MODEL; # some programs keep references to detect
# IO::Async::Loop::AnyEvent is extremely evil, refuse to work with it
# the author knows about the problems and what it does to AnyEvent as a whole
# (and the ability of others to use AnyEvent), but simply wants to abuse AnyEvent
# anyway.
AnyEvent::log fatal => "IO::Async::Loop::AnyEvent detected - that module is broken by\n"
. "design, abuses internals and breaks AnyEvent - will not continue."
if exists $INC{"IO/Async/Loop/AnyEvent.pm"};
local $!; # for good measure
local $SIG{__DIE__}; # we use eval
# free some memory
*detect = sub () { $MODEL };
# undef &func doesn't correctly update the method cache. grmbl.
# so we delete the whole glob. grmbl.
# otoh, perl doesn't let me undef an active usb, but it lets me free
# a glob with an active sub. hrm. i hope it works, but perl is
# usually buggy in this department. sigh.
delete @{"AnyEvent::"}{@methods};
undef @methods;
if ($ENV{PERL_ANYEVENT_MODEL} =~ /^([a-zA-Z0-9:]+)$/) {
my $model = $1;
$model = "AnyEvent::Impl::$model" unless $model =~ s/::$//;
if (eval "require $model") {
AnyEvent::log 7 => "Loaded model '$model' (forced by \$ENV{PERL_ANYEVENT_MODEL}), using it.";
$MODEL = $model;
} else {
AnyEvent::log 4 => "Unable to load model '$model' (from \$ENV{PERL_ANYEVENT_MODEL}):\n$@";
}
}
# check for already loaded models
unless ($MODEL) {
for (@REGISTRY, @models) {
my ($package, $model) = @$_;
if (${"$package\::VERSION"} > 0) {
if (eval "require $model") {
AnyEvent::log 7 => "Autodetected model '$model', using it.";
$MODEL = $model;
last;
} else {
AnyEvent::log 8 => "Detected event loop $package, but cannot load '$model', skipping: $@";
}
}
}
unless ($MODEL) {
# try to autoload a model
for (@REGISTRY, @models) {
my ($package, $model) = @$_;
if (
eval "require $package"
and ${"$package\::VERSION"} > 0
and eval "require $model"
) {
AnyEvent::log 7 => "Autoloaded model '$model', using it.";
$MODEL = $model;
last;
}
}
$MODEL
or AnyEvent::log fatal => "Backend autodetection failed - did you properly install AnyEvent?";
}
}
# free memory only needed for probing
undef @models;
undef @REGISTRY;
push @{"$MODEL\::ISA"}, "AnyEvent::Base";
# now nuke some methods that are overridden by the backend.
# SUPER usage is not allowed in these.
for (qw(time signal child idle)) {
undef &{"AnyEvent::Base::$_"}
lib/AnyEvent.pm view on Meta::CPAN
development.
As for exception handling (i.e. runtime errors and exceptions thrown while
executing a callback), this is not only highly event-loop specific, but
also not in any way wrapped by this module, as this is the job of the main
program.
The pure perl event loop simply re-throws the exception (usually
within C<< condvar->recv >>), the L<Event> and L<EV> modules call C<<
$Event/EV::DIED->() >>, L<Glib> uses C<< install_exception_handler >> and
so on.
=head1 ENVIRONMENT VARIABLES
AnyEvent supports a number of environment variables that tune the
runtime behaviour. They are usually evaluated when AnyEvent is
loaded, initialised, or a submodule that uses them is loaded. Many of
them also cause AnyEvent to load additional modules - for example,
C<PERL_ANYEVENT_DEBUG_WRAP> causes the L<AnyEvent::Debug> module to be
loaded.
All the environment variables documented here start with
C<PERL_ANYEVENT_>, which is what AnyEvent considers its own
namespace. Other modules are encouraged (but by no means required) to use
C<PERL_ANYEVENT_SUBMODULE> if they have registered the AnyEvent::Submodule
namespace on CPAN, for any submodule. For example, L<AnyEvent::HTTP> could
be expected to use C<PERL_ANYEVENT_HTTP_PROXY> (it should not access env
variables starting with C<AE_>, see below).
All variables can also be set via the C<AE_> prefix, that is, instead
of setting C<PERL_ANYEVENT_VERBOSE> you can also set C<AE_VERBOSE>. In
case there is a clash btween anyevent and another program that uses
C<AE_something> you can set the corresponding C<PERL_ANYEVENT_something>
variable to the empty string, as those variables take precedence.
When AnyEvent is first loaded, it copies all C<AE_xxx> env variables
to their C<PERL_ANYEVENT_xxx> counterpart unless that variable already
exists. If taint mode is on, then AnyEvent will remove I<all> environment
variables starting with C<PERL_ANYEVENT_> from C<%ENV> (or replace them
with C<undef> or the empty string, if the corresaponding C<AE_> variable
is set).
The exact algorithm is currently:
1. if taint mode enabled, delete all PERL_ANYEVENT_xyz variables from %ENV
2. copy over AE_xyz to PERL_ANYEVENT_xyz unless the latter alraedy exists
3. if taint mode enabled, set all PERL_ANYEVENT_xyz variables to undef.
This ensures that child processes will not see the C<AE_> variables.
The following environment variables are currently known to AnyEvent:
=over 4
=item C<PERL_ANYEVENT_VERBOSE>
By default, AnyEvent will log messages with loglevel C<4> (C<error>) or
higher (see L<AnyEvent::Log>). You can set this environment variable to a
numerical loglevel to make AnyEvent more (or less) talkative.
If you want to do more than just set the global logging level
you should have a look at C<PERL_ANYEVENT_LOG>, which allows much more
complex specifications.
When set to C<0> (C<off>), then no messages whatsoever will be logged with
everything else at defaults.
When set to C<5> or higher (C<warn>), AnyEvent warns about unexpected
conditions, such as not being able to load the event model specified by
C<PERL_ANYEVENT_MODEL>, or a guard callback throwing an exception - this
is the minimum recommended level for use during development.
When set to C<7> or higher (info), AnyEvent reports which event model it
chooses.
When set to C<8> or higher (debug), then AnyEvent will report extra
information on which optional modules it loads and how it implements
certain features.
=item C<PERL_ANYEVENT_LOG>
Accepts rather complex logging specifications. For example, you could log
all C<debug> messages of some module to stderr, warnings and above to
stderr, and errors and above to syslog, with:
PERL_ANYEVENT_LOG=Some::Module=debug,+log:filter=warn,+%syslog:%syslog=error,syslog
For the rather extensive details, see L<AnyEvent::Log>.
This variable is evaluated when AnyEvent (or L<AnyEvent::Log>) is loaded,
so will take effect even before AnyEvent has initialised itself.
Note that specifying this environment variable causes the L<AnyEvent::Log>
module to be loaded, while C<PERL_ANYEVENT_VERBOSE> does not, so only
using the latter saves a few hundred kB of memory unless a module
explicitly needs the extra features of AnyEvent::Log.
=item C<PERL_ANYEVENT_STRICT>
AnyEvent does not do much argument checking by default, as thorough
argument checking is very costly. Setting this variable to a true value
will cause AnyEvent to load C<AnyEvent::Strict> and then to thoroughly
check the arguments passed to most method calls. If it finds any problems,
it will croak.
In other words, enables "strict" mode.
Unlike C<use strict> (or its modern cousin, C<< use L<common::sense>
>>, it is definitely recommended to keep it off in production. Keeping
C<PERL_ANYEVENT_STRICT=1> in your environment while developing programs
can be very useful, however.
=item C<PERL_ANYEVENT_DEBUG_SHELL>
If this env variable is nonempty, then its contents will be interpreted by
C<AnyEvent::Socket::parse_hostport> and C<AnyEvent::Debug::shell> (after
replacing every occurance of C<$$> by the process pid). The shell object
is saved in C<$AnyEvent::Debug::SHELL>.
This happens when the first watcher is created.
( run in 1.146 second using v1.01-cache-2.11-cpan-df04353d9ac )