| 1 | package DBIx::Loop::Loop::AnyEvent; | ||
| 2 | |||
| 3 | use 5.008003; | ||
| 4 | use strict; | ||
| 5 | use warnings; | ||
| 6 | use Carp (); | ||
| 7 | |||
| 8 | our $VERSION = '0.09'; | ||
| 9 | |||
| 10 | # The loop adapter for AnyEvent, implementing the DBIx::Loop seam over AE io | ||
| 11 | # and timer watchers. AnyEvent has no native future, so queries stay | ||
| 12 | # DBIx::Loop::Future; to_native() bridges one to an AnyEvent condvar. Through | ||
| 13 | # AnyEvent this also covers EV, Event, etc. via its own backends. | ||
| 14 | |||
| 15 | sub new { | ||
| 16 | my ($class, %opt) = @_; | ||
| 17 | require AnyEvent; | ||
| 18 | return bless { r => {}, w => {}, t => {} }, $class; | ||
| 19 | } | ||
| 20 | |||
| 21 | sub add_reader { | ||
| 22 | my ($self, $fd, $cb) = @_; | ||
| 23 | $self->{r}{$fd} = AnyEvent->io(fh => $fd, poll => 'r', cb => $cb); | ||
| 24 | } | ||
| 25 | |||
| 26 | sub add_writer { | ||
| 27 | my ($self, $fd, $cb) = @_; | ||
| 28 | $self->{w}{$fd} = AnyEvent->io(fh => $fd, poll => 'w', cb => $cb); | ||
| 29 | } | ||
| 30 | |||
| 31 | sub remove { | ||
| 32 | my ($self, $fd) = @_; | ||
| 33 | delete $self->{r}{$fd}; | ||
| 34 | delete $self->{w}{$fd}; | ||
| 35 | return; | ||
| 36 | } | ||
| 37 | |||
| 38 | sub timer { | ||
| 39 | my ($self, $after, $cb) = @_; | ||
| 40 | my $id; | ||
| 41 | $id = "t" . ++$self->{tid}; | ||
| 42 | $self->{t}{$id} = AnyEvent->timer(after => $after, cb => sub { | ||
| 43 | delete $self->{t}{$id}; | ||
| 44 | $cb->(); | ||
| 45 | }); | ||
| 46 | return $id; | ||
| 47 | } | ||
| 48 | |||
| 49 | # AnyEvent has no ecosystem future; the canonical one is ours | ||
| 50 | sub new_future { | ||
| 51 | require DBIx::Loop; | ||
| 52 | return DBIx::Loop::Future->new; | ||
| 53 | } | ||
| 54 | |||
| 55 | # bridge a DBIx::Loop::Future to an AnyEvent condvar | ||
| 56 | sub to_native { | ||
| 57 | my ($self, $future) = @_; | ||
| 58 | require AnyEvent; | ||
| 59 | my $cv = AnyEvent->condvar; | ||
| 60 | $future->on_ready(sub { | ||
| 61 | my ($f) = @_; | ||
| 62 | $f->is_done ? $cv->send($f->get) : $cv->croak($f->failure); | ||
| 63 | }); | ||
| 64 | return $cv; | ||
| 65 | } | ||
| 66 | |||
| 67 | # block (running the AE loop) until $future is ready | ||
| 68 | sub await { | ||
| 69 | my ($self, $future) = @_; | ||
| 70 | return $future if $future->is_ready; | ||
| 71 | require AnyEvent; | ||
| 72 | my $cv = AnyEvent->condvar; | ||
| 73 | $future->on_ready(sub { $cv->send }); | ||
| 74 | $cv->recv; | ||
| 75 | return $future; | ||
| 76 | } | ||
| 77 | |||
| 78 | 1; | ||
| 79 | |||
| 80 | __END__ |