| 1 | package Mojo::IOLoop::DNSNative; | ||
| 2 | $Mojo::IOLoop::DNSNative::VERSION = '0.001'; | ||
| 3 | # ABSTRACT: Async native DNS lookup | ||
| 4 | use Mojo::Base -base; | ||
| 5 | |||
| 6 | use List::Util qw/ uniq /; | ||
| 7 | use Mojo::IOLoop; | ||
| 8 | use Net::DNS::Native; | ||
| 9 | use Socket qw/ getnameinfo NI_NUMERICHOST NIx_NOSERV /; | ||
| 10 | |||
| 11 | has NDN => | ||
| 12 | sub { state $NDN = Net::DNS::Native->new(pool => 5, extra_thread => 1) }; | ||
| 13 | has reactor => sub { Mojo::IOLoop->singleton->reactor }; | ||
| 14 | has timeout => 10; | ||
| 15 | |||
| 16 | sub lookup { | ||
| 17 | my ($self, $address, $cb) = @_; | ||
| 18 | |||
| 19 | my $reactor = $self->reactor; | ||
| 20 | my $ndn = $self->NDN; | ||
| 21 | |||
| 22 | my $handle = $ndn->getaddrinfo($address, undef); | ||
| 23 | my $tid; | ||
| 24 | if (my $timeout = $self->timeout) { | ||
| 25 | $tid = $reactor->timer( | ||
| 26 | $timeout, | ||
| 27 | sub { | ||
| 28 | $ndn->timedout($handle); | ||
| 29 | $reactor->remove($handle); | ||
| 30 | $cb->('DNS lookup timed out'); | ||
| 31 | } | ||
| 32 | ); | ||
| 33 | } | ||
| 34 | $reactor->io( | ||
| 35 | $handle => sub { | ||
| 36 | my $reactor = shift; | ||
| 37 | $reactor->remove($handle); | ||
| 38 | $reactor->remove($tid) if defined $tid; | ||
| 39 | my ($err, @res) = $ndn->get_result($handle); | ||
| 40 | |||
| 41 | $cb->( | ||
| 42 | $err, | ||
| 43 | uniq map { (getnameinfo($_->{addr}, NI_NUMERICHOST, NIx_NOSERV))[1] } | ||
| 44 | @res | ||
| 45 | ); | ||
| 46 | } | ||
| 47 | )->watch($handle, 1, 0); | ||
| 48 | } | ||
| 49 | |||
| 50 | 1; | ||
| 51 | |||
| 52 | __END__ |