AnyEvent

 view release on metacpan or  search on metacpan

Changes  view on Meta::CPAN

          5.8.8, and older versions of perl make our live very difficult,
          so write constants.pl during Makefile.PL time.

5.25  Sat Mar 13 00:23:14 CET 2010
	- fix a race condition in AnyEvent::Handle that would cause
          a "bio_read: unsupported method" error (in _another_
          ssl connection) after user code threw an exception.
        - added AnyEvent::Handle->destroyed method.
	- speed up AnyEvent::Socket::format_address and ::format_ipv6.
        - the AnyEvent::Util::fh_nonblocking function worked only
          by lucky accident on win32.
        - smaller and faster AnyEvent::Util::fh_nonblocking.
        - when the (required!) Time::HiRes module is missing, AnyEvent
          did not fall back to built-in time properly.
        - do not load Fcntl at runtime, saving memory and loading time.
        - precompile a number of constants and use them instead of runtime
          detection and eval.
        - free detection code after detection and similar memory optimisations.
        - Perl backend timer interval best effort drift has been improved
          (same algorithm as EV).
        - update unicode idna mapping table.

Changes  view on Meta::CPAN

        - explain why recursion into the event loop is not supported
          unless the backend supports it (only Coro::EV does without
          any restrictions...).
        - add simple manpages for all backend modules.

3.0  Mon Apr  7 21:30:23 CEST 2008
	- Coro::Signal changed semantics, roll our own, also cleaning
          up the Coro implementation in general.
        - rename Coro backend to CoroEvent.
        - add some decision helping paragraph to the manpage that should
          help people to decide whether AnyEvent is the right thing for them.

2.9  Mon Jan 28 13:31:54 CET 2008
	- update for EV 3.0 API changes.

2.8  Sun Nov 25 15:06:03 CET 2007
	- waitpid can validly return 0. accept this fact of life
          instead of reporting it to any watchers.

2.7  Fri Nov 23 11:41:14 CET 2007
	- force use of AnyEvent::Impl::Perl in testsuite, there is

README  view on Meta::CPAN

          warn "timeout\n";
       });

   TIMING ISSUES
    There are two ways to handle timers: based on real time (relative, "fire
    in 10 seconds") and based on wallclock time (absolute, "fire at 12
    o'clock").

    While most event loops expect timers to specified in a relative way,
    they use absolute time internally. This makes a difference when your
    clock "jumps", for example, when ntp decides to set your clock backwards
    from the wrong date of 2014-01-01 to 2008-01-01, a watcher that is
    supposed to fire "after a second" might actually take six years to
    finally fire.

    AnyEvent cannot compensate for this. The only event loop that is
    conscious of these issues is EV, which offers both relative (ev_timer,
    based on true relative time) and absolute (ev_periodic, based on
    wallclock time) timers.

    AnyEvent always prefers relative timers, if available, matching the

README  view on Meta::CPAN

        thread that doesn't run the event loop itself. Coro::AnyEvent is
        loaded automatically when Coro is used with AnyEvent, so code does
        not need to do anything special to take advantage of that: any code
        that would normally block your program because it calls "recv", be
        executed in an "async" thread instead without blocking other
        threads.

        Not all event models support a blocking wait - some die in that case
        (programs might want to do that to stay interactive), so *if you are
        using this from a module, never require a blocking wait*. Instead,
        let the caller decide whether the call will block or not (for
        example, by coupling condition variables with some kind of request
        results and supporting callbacks so the caller knows that getting
        the result will not block, while still supporting blocking waits if
        the caller so desires).

        You can ensure that "->recv" never blocks by setting a callback and
        only calling "->recv" from within that callback (or at a later
        time). This will work even when the event loop does not support
        blocking waits otherwise.

README  view on Meta::CPAN


    AnyEvent::fh_block $filehandle
    AnyEvent::fh_unblock $filehandle
        Sets blocking or non-blocking behaviour for the given filehandle.

WHAT TO DO IN A MODULE
    As a module author, you should "use AnyEvent" and call AnyEvent methods
    freely, but you should not load a specific event module or rely on it.

    Be careful when you create watchers in the module body - AnyEvent will
    decide which event module to use as soon as the first method is called,
    so by calling AnyEvent in your module body you force the user of your
    module to load the event module first.

    Never call "->recv" on a condition variable unless you *know* that the
    "->send" method has been called on it already. This is because it will
    stall the whole program, and the whole point of using events is to stay
    interactive.

    It is fine, however, to call "->recv" when the user of your module
    requests it (i.e. if you create a http request object ad have a method

README  view on Meta::CPAN

    when it depends on a module that uses an AnyEvent. If the program itself
    uses AnyEvent, but does not care which event loop is used, all it needs
    to do is "use AnyEvent". In either case, AnyEvent will choose the best
    available loop implementation.

    If the main program relies on a specific event model - for example, in
    Gtk2 programs you have to rely on the Glib module - you should load the
    event module before loading AnyEvent or any module that uses it:
    generally speaking, you should load it as early as possible. The reason
    is that modules might create watchers when they are loaded, and AnyEvent
    will decide on the event model to use as soon as it creates watchers,
    and it might choose the wrong one unless you load the correct one
    yourself.

    You can chose to use a pure-perl implementation by loading the
    "AnyEvent::Loop" module, which gives you similar behaviour everywhere,
    but letting AnyEvent chose the model is generally better.

  MAINLOOP EMULATION
    Sometimes (often for short test scripts, or even standalone programs who
    only want to use AnyEvent), you do not want to run a specific event

README  view on Meta::CPAN

        resolve or contact IPv6 addresses.
        "PERL_ANYEVENT_PROTOCOLS=ipv6,ipv4" support either IPv4 or IPv6, but
        prefer IPv6 over IPv4.

    "PERL_ANYEVENT_HOSTS"
        This variable, if specified, overrides the /etc/hosts file used by
        AnyEvent::Socket"::resolve_sockaddr", i.e. hosts aliases will be
        read from that file instead.

    "PERL_ANYEVENT_EDNS0"
        Used by AnyEvent::DNS to decide whether to use the EDNS0 extension
        for DNS. This extension is generally useful to reduce DNS traffic,
        especially when DNSSEC is involved, but some (broken) firewalls drop
        such DNS packets, which is why it is off by default.

        Setting this variable to 1 will cause AnyEvent::DNS to announce
        EDNS0 in its DNS requests.

    "PERL_ANYEVENT_MAX_FORKS"
        The maximum number of child processes that
        "AnyEvent::Util::fork_call" will create in parallel.

lib/AnyEvent.pm  view on Meta::CPAN

   });

=head3 TIMING ISSUES

There are two ways to handle timers: based on real time (relative, "fire
in 10 seconds") and based on wallclock time (absolute, "fire at 12
o'clock").

While most event loops expect timers to specified in a relative way, they
use absolute time internally. This makes a difference when your clock
"jumps", for example, when ntp decides to set your clock backwards from
the wrong date of 2014-01-01 to 2008-01-01, a watcher that is supposed to
fire "after a second" might actually take six years to finally fire.

AnyEvent cannot compensate for this. The only event loop that is conscious
of these issues is L<EV>, which offers both relative (ev_timer, based
on true relative time) and absolute (ev_periodic, based on wallclock time)
timers.

AnyEvent always prefers relative timers, if available, matching the
AnyEvent API.

lib/AnyEvent.pm  view on Meta::CPAN

, which allows you to do a blocking C<< ->recv >> from any thread
that doesn't run the event loop itself. L<Coro::AnyEvent> is loaded
automatically when L<Coro> is used with L<AnyEvent>, so code does not need
to do anything special to take advantage of that: any code that would
normally block your program because it calls C<recv>, be executed in an
C<async> thread instead without blocking other threads.

Not all event models support a blocking wait - some die in that case
(programs might want to do that to stay interactive), so I<if you are
using this from a module, never require a blocking wait>. Instead, let the
caller decide whether the call will block or not (for example, by coupling
condition variables with some kind of request results and supporting
callbacks so the caller knows that getting the result will not block,
while still supporting blocking waits if the caller so desires).

You can ensure that C<< ->recv >> never blocks by setting a callback and
only calling C<< ->recv >> from within that callback (or at a later
time). This will work even when the event loop does not support blocking
waits otherwise.

=item $bool = $cv->ready

lib/AnyEvent.pm  view on Meta::CPAN

Sets blocking or non-blocking behaviour for the given filehandle.

=back

=head1 WHAT TO DO IN A MODULE

As a module author, you should C<use AnyEvent> and call AnyEvent methods
freely, but you should not load a specific event module or rely on it.

Be careful when you create watchers in the module body - AnyEvent will
decide which event module to use as soon as the first method is called, so
by calling AnyEvent in your module body you force the user of your module
to load the event module first.

Never call C<< ->recv >> on a condition variable unless you I<know> that
the C<< ->send >> method has been called on it already. This is
because it will stall the whole program, and the whole point of using
events is to stay interactive.

It is fine, however, to call C<< ->recv >> when the user of your module
requests it (i.e. if you create a http request object ad have a method

lib/AnyEvent.pm  view on Meta::CPAN

when it depends on a module that uses an AnyEvent. If the program itself
uses AnyEvent, but does not care which event loop is used, all it needs
to do is C<use AnyEvent>. In either case, AnyEvent will choose the best
available loop implementation.

If the main program relies on a specific event model - for example, in
Gtk2 programs you have to rely on the Glib module - you should load the
event module before loading AnyEvent or any module that uses it: generally
speaking, you should load it as early as possible. The reason is that
modules might create watchers when they are loaded, and AnyEvent will
decide on the event model to use as soon as it creates watchers, and it
might choose the wrong one unless you load the correct one yourself.

You can chose to use a pure-perl implementation by loading the
C<AnyEvent::Loop> module, which gives you similar behaviour
everywhere, but letting AnyEvent chose the model is generally better.

=head2 MAINLOOP EMULATION

Sometimes (often for short test scripts, or even standalone programs who
only want to use AnyEvent), you do not want to run a specific event loop.

lib/AnyEvent.pm  view on Meta::CPAN

IPv6, but prefer IPv6 over IPv4.

=item C<PERL_ANYEVENT_HOSTS>

This variable, if specified, overrides the F</etc/hosts> file used by
L<AnyEvent::Socket>C<::resolve_sockaddr>, i.e. hosts aliases will be read
from that file instead.

=item C<PERL_ANYEVENT_EDNS0>

Used by L<AnyEvent::DNS> to decide whether to use the EDNS0 extension for
DNS. This extension is generally useful to reduce DNS traffic, especially
when DNSSEC is involved, but some (broken) firewalls drop such DNS
packets, which is why it is off by default.

Setting this variable to C<1> will cause L<AnyEvent::DNS> to announce
EDNS0 in its DNS requests.

=item C<PERL_ANYEVENT_MAX_FORKS>

The maximum number of child processes that C<AnyEvent::Util::fork_call>

lib/AnyEvent/DNS.pm  view on Meta::CPAN

#################################################################################

=back

=head2 LOW-LEVEL DNS EN-/DECODING FUNCTIONS

=over 4

=item $AnyEvent::DNS::EDNS0

This variable decides whether dns_pack automatically enables EDNS0
support. By default, this is disabled (C<0>), unless overridden by
C<$ENV{PERL_ANYEVENT_EDNS0}>, but when set to C<1>, AnyEvent::DNS will use
EDNS0 in all requests.

=cut

our $EDNS0 = $ENV{PERL_ANYEVENT_EDNS0}*1; # set to 1 to enable (partial) edns0

our %opcode_id = (
   query  => 0,

lib/AnyEvent/Debug.pm  view on Meta::CPAN

which currently has "help" and a few other commands, and can be freely
modified by all shells. Code is evaluated under C<use strict 'subs'>.

Every shell has a logging context (C<$LOGGER>) that is attached to
C<$AnyEvent::Log::COLLECT>), which is especially useful to gether debug
and trace messages.

As a general programming guide, consider the beneficial aspects of
using more global (C<our>) variables than local ones (C<my>) in package
scope: Earlier all my modules tended to hide internal variables inside
C<my> variables, so users couldn't accidentally access them. Having
interactive access to your programs changed that: having internal
variables still in the global scope means you can debug them easier.

As no authentication is done, in most cases it is best not to use a TCP
port, but a unix domain socket, whcih can be put wherever you can access
it, but not others:

   our $SHELL = AnyEvent::Debug::shell "unix/", "/home/schmorp/shell";

Then you can use a tool to connect to the shell, such as the ever

lib/AnyEvent/FAQ.pod  view on Meta::CPAN

away), tcp_connect will no longer try to connect or call any callbacks.

Often this happens when the C<tcp_connect> call is at the end of a function:

   sub do_connect {
      tcp_connect "www.example.com", 80, sub {
         ... lengthy code
      };
   }

Then the caller decides whether there is a void context or not. One can
avoid these cases by explicitly returning nothing:

   sub do_connect {
      tcp_connect "www.example.com", 80, sub {
         ... lengthy code
      };

      () # return nothing
   }

lib/AnyEvent/Handle.pm  view on Meta::CPAN


The peer's numeric host and port (the socket peername) are passed as
parameters, together with a retry callback. At the time it is called the
read and write queues, EOF status, TLS status and similar properties of
the handle will have been reset.

If, for some reason, the handle is not acceptable, calling C<$retry> will
continue with the next connection target (in case of multi-homed hosts or
SRV records there can be multiple connection endpoints). The C<$retry>
callback can be invoked after the connect callback returns, i.e. one can
start a handshake and then decide to retry with the next host if the
handshake fails.

In most cases, you should ignore the C<$retry> parameter.

=item on_connect_error => $cb->($handle, $message)

This callback is called when the connection could not be
established. C<$!> will contain the relevant error code, and C<$message> a
message describing it (usually the same as C<"$!">).

lib/AnyEvent/Handle.pm  view on Meta::CPAN

is handled, up to the fictituous protocol 4.x (but both SSL3+ and
SSL2-compatible framing is supported).

If it detects that the input data is likely TLS, it calls the callback
with a true value for C<$detect> and the (on-wire) TLS version as second
and third argument (C<$major> is C<3>, and C<$minor> is 0..4 for SSL
3.0, TLS 1.0, 1.1, 1.2 and 1.3, respectively).  If it detects the input
to be definitely not TLS, it calls the callback with a false value for
C<$detect>.

The callback could use this information to decide whether or not to start
TLS negotiation.

In all cases the data read so far is passed to the following read
handlers.

Usually you want to use the C<tls_autostart> read type instead.

If you want to design a protocol that works in the presence of TLS
dtection, make sure that any non-TLS data doesn't start with the octet 22
(ASCII SYN, 16 hex) or 128-255 (i.e. highest bit set). The checks this

lib/AnyEvent/Handle.pm  view on Meta::CPAN

   my ($self, $cb) = @_;

   sub {
      # this regex matches a full or partial tls record
      if (
         # ssl3+: type(22=handshake) major(=3) minor(any) length_hi
         $self->{rbuf} =~ /^(?:\z| \x16 (\z| [\x03\x04] (?:\z| . (?:\z| [\x00-\x40] ))))/xs
         # ssl2 comapatible: len_hi len_lo type(1) major minor dummy(forlength)
         or $self->{rbuf} =~ /^(?:\z| [\x80-\xff] (?:\z| . (?:\z| \x01 (\z| [\x03\x04] (?:\z| . (?:\z| . ))))))/xs
      ) {
         return if 3 != length $1; # partial match, can't decide yet

         # full match, valid TLS record
         my ($major, $minor) = unpack "CC", $1;
         $cb->($self, "accept", $major, $minor);
      } else {
         # mismatch == guaranteed not TLS
         $cb->($self, undef);
      }

      1

lib/AnyEvent/Handle.pm  view on Meta::CPAN


sub AnyEvent::Handle::destroyed::AUTOLOAD {
   #nop
}

=item $handle->destroyed

Returns false as long as the handle hasn't been destroyed by a call to C<<
->destroy >>, true otherwise.

Can be useful to decide whether the handle is still valid after some
callback possibly destroyed the handle. For example, C<< ->push_write >>,
C<< ->starttls >> and other methods can call user callbacks, which in turn
can destroy the handle, so work can be avoided by checking sometimes:

   $hdl->starttls ("accept");
   return if $hdl->destroyed;
   $hdl->push_write (...

Note that the call to C<push_write> will silently be ignored if the handle
has been destroyed, so often you can just ignore the possibility of the

lib/AnyEvent/IO.pm  view on Meta::CPAN

is to I/O the same as L<AnyEvent> is to event libraries - it only
I<interfaces> to other implementations or to a portable pure-perl
implementation (which does not, however, do asynchronous I/O).

The only other implementation that is supported (or even known to the
author) is L<IO::AIO>, which is used automatically when it can be loaded
(via L<AnyEvent::AIO>, which also needs to be installed). If it is not
available, then L<AnyEvent::IO> falls back to its synchronous pure-perl
implementation.

Unlike L<AnyEvent>, which model to use is currently decided at module load
time, not at first use. Future releases might change this.

=head2 RATIONALE

While disk I/O often seems "instant" compared to, say, socket I/O, there
are many situations where your program can block for extended time periods
when doing disk I/O. For example, you access a disk on an NFS server and
it is gone - can take ages to respond again, if ever. Or your system is
extremely busy because it creates or restores a backup - reading data from
disk can then take seconds. Or you use Linux, which for so many years has

lib/AnyEvent/Impl/Tk.pm  view on Meta::CPAN


   bless \\$id, "AnyEvent::Impl::Tk::after"
}

sub idle {
   my (undef, %arg) = @_;

   my $cb = $arg{cb};
   my $id;
   my $rcb = sub {
      # in their endless stupidity, they decided to give repeating idle watchers
      # strictly higher priority than timers :/
      $id = Tk::after $mw, 0 => [sub {
         $id = Tk::after $mw, idle => [$_[0], $_[0]];
      }, $_[0]];
      &$cb;
   };

   $id = Tk::after $mw, idle => [$rcb, $rcb];
   bless \\$id, "AnyEvent::Impl::Tk::after"
}

lib/AnyEvent/Intro.pod  view on Meta::CPAN


In the example using condition variables, we used those to start waiting
for events, and in fact, condition variables are the solution:

   my $quit_program = AnyEvent->condvar;

   # create AnyEvent watchers (or not) here

   $quit_program->recv;

If any of your watcher callbacks decide to quit (this is often
called an "unloop" in other frameworks), they can just call C<<
$quit_program->send >>. Of course, they could also decide not to and
call C<exit> instead, or they could decide never to quit (e.g. in a
long-running daemon program).

If you don't need some clean quit functionality and just want to run the
event loop, you can do this:

   AnyEvent->condvar->recv;

And this is, in fact, the closest to the idea of a main loop run
function that AnyEvent offers.

lib/AnyEvent/Log.pm  view on Meta::CPAN

C<AnyEvent::Log::log> function was called at this point with the given
level. C<$logger> is passed a C<$msg> and optional C<@args>, just as with
the C<AnyEvent::Log::log> function:

   my $debug_log = AnyEvent::Log::logger "debug";

   $debug_log->("debug here");
   $debug_log->("%06d emails processed", 12345);
   $debug_log->(sub { $obj->as_string });

The idea behind this function is to decide whether to log before actually
logging - when the C<logger> function is called once, but the returned
logger callback often, then this can be a tremendous speed win.

Despite this speed advantage, changes in logging configuration will
still be reflected by the logger callback, even if configuration changes
I<after> it was created.

To further speed up logging, you can bind a scalar variable to the logger,
which contains true if the logger should be called or not - if it is
false, calling the logger can be safely skipped. This variable will be

lib/AnyEvent/Log.pm  view on Meta::CPAN


By default, C<AnyEvent::Log> will use C<AE::now>, i.e. the cached
eventloop time, for the log timestamps. After calling this function with a
true value it will instead resort to C<AE::time>, i.e. fetch the current
time on each log message. This only makes a difference for event loops
that actually cache the time (such as L<EV> or L<AnyEvent::Loop>).

This setting can be changed at any time by calling this function.

Since C<AnyEvent::Log> has to work even before the L<AnyEvent> has been
initialised, this switch will also decide whether to use C<CORE::time> or
C<Time::HiRes::time> when logging a message before L<AnyEvent> becomes
available.

=item AnyEvent::Log::format_time $timestamp

Formats a timestamp as returned by C<< AnyEvent->now >> or C<<
AnyEvent->time >> or many other functions in the same way as
C<AnyEvent::Log> does.

In your main program (as opposed to in your module) you can override



( run in 1.724 second using v1.01-cache-2.11-cpan-de7293f3b23 )