Skip to content

Commit

Permalink
Very rough outline of a pluggable resolver api
Browse files Browse the repository at this point in the history
  • Loading branch information
jberger committed Dec 11, 2014
1 parent 9a5c2ce commit 93c380d
Show file tree
Hide file tree
Showing 3 changed files with 59 additions and 17 deletions.
31 changes: 14 additions & 17 deletions lib/Mojo/IOLoop/Client.pm
Expand Up @@ -29,6 +29,9 @@ use constant SOCKS_WRITE => SOCKS ? IO::Socket::Socks::SOCKS_WANT_WRITE() : 0;

has reactor => sub { Mojo::IOLoop->singleton->reactor };

use Mojo::IOLoop::Resolver;
has resolver => sub { Mojo::IOLoop::Resolver->new(reactor => shift->reactor) };

sub DESTROY { shift->_cleanup }

sub connect {
Expand All @@ -45,23 +48,17 @@ sub connect {
$_ && s/[[\]]//g for @$args{qw(address socks_address)};
my $address = $args->{socks_address} || ($args->{address} ||= 'localhost');
return $reactor->next_tick(sub { $self && $self->_connect($args) })
unless NDN && $address ne 'localhost' && !$args->{handle};

# Non-blocking name resolution
my $handle = $self->{dns}
= $NDN->getaddrinfo($address, _port($args), {protocol => IPPROTO_TCP});
$reactor->io(
$handle => sub {
my $reactor = shift;

$reactor->remove($self->{dns});
my ($err, @res) = $NDN->get_result(delete $self->{dns});
return $self->emit(error => "Can't resolve: $err") if $err;

$args->{addr_info} = \@res;
$self->_connect($args);
}
)->watch($handle, 1, 0);
if $address eq 'localhost' || $args->{handle};

# Pluggable name resolution
my $resolver = $self->resolver;
$resolver->getaddrinfo( $address, _port($args), sub {
my ($resolver, $err, $addr_info) = @_;
return unless $self;
return $self->emit(error => "Can't resolve: $err") if $err;
$args->{addr_info} = $addr_info if $addr_info;
$self->_connect($args);
});
}

sub _cleanup {
Expand Down
16 changes: 16 additions & 0 deletions lib/Mojo/IOLoop/Resolver.pm
@@ -0,0 +1,16 @@
package Mojo::IOLoop::Resolver;

use Mojo::Base -base;

has reactor => sub { Mojo::IOLoop->singleton->reactor };

sub getaddrinfo {
my ($self, $address, $port, $cb) = @_;

# $self, $err, $addr_info
$self->reactor->next_tick(sub { $self->cb(undef, undef) });
}


1;

29 changes: 29 additions & 0 deletions lib/Mojo/IOLoop/Resolver/NetDNSNative.pm
@@ -0,0 +1,29 @@
package Mojo::IOLoop::Resolver::NetDNSNative;

use Mojo::Base 'Mojo::IOLoop::Resolver';

use Socket qw(IPPROTO_TCP);
has ndn => sub { Net::DNS::Native->new(pool => 5, extra_thread => 1) };

sub getaddrinfo {
my ($self, $address, $port, $cb) = @_;

my $NDN = $self->ndn;

my $handle = $self->{dns}
= $NDN->getaddrinfo($address, $port, {protocol => IPPROTO_TCP});

$self->reactor->io(
$handle => sub {
my $reactor = shift;

$reactor->remove($self->{dns});
my ($err, @res) = $NDN->get_result(delete $self->{dns});

$self->$cb($err, \@res);
}
)->watch($handle, 1, 0);
}

1;

0 comments on commit 93c380d

Please sign in to comment.