Skip to content

Instantly share code, notes, and snippets.

@beppu
Created March 16, 2011 20:34
Show Gist options
  • Save beppu/873249 to your computer and use it in GitHub Desktop.
Save beppu/873249 to your computer and use it in GitHub Desktop.
Can SOAP::Lite be tricked into being AnyEvent+Coro-friendly?
#!/usr/bin/env perl
use common::sense;
use AnyEvent;
use Coro;
use AnyEvent::HTTP::LWP::UserAgent;
use SOAP::Lite; # +trace => 'all';
use SOAP::Transport::HTTP; # preload it so that we can set USERAGENT_CLASS reliably;
my @results;
warn "1 ".$SOAP::Transport::HTTP::Client::USERAGENT_CLASS;
$SOAP::Transport::HTTP::Client::USERAGENT_CLASS = "AnyEvent::HTTP::LWP::UserAgent";
warn "2 ".$SOAP::Transport::HTTP::Client::USERAGENT_CLASS;
my $proxy = SOAP::Lite->proxy('http://www.mobilefish.com/services/web_service/countries.php');
sub soap {
my $n = shift;
my $response = $proxy->countryInfoByIana('jp');
my $result = $response->result;
push @results, "$n $result->{countryname}";
}
my $ua = AnyEvent::HTTP::LWP::UserAgent->new;
sub http {
my $n = shift;
push @results, "$n " . $ua->get('http://justice.is-found.org/')->content;
}
# added a timeout;
# $timeout has been set to a low value so that you can see that some requests
# get ignored if they take too long.
my @c;
my $timeout = 1.0;
my $cv = AE::cv;
my $w = AE::timer $timeout, 0, sub { warn "timeout"; $_->cancel for (@c); $cv->send; };
for my $i (1 .. 8) {
# A:H:LWP:UA works asynchronously as expected
$cv->begin;
push @c, async {
warn "http $i"; http($i);
$cv->end;
};
# SOAP::Lite can also work asynchronously by using A:H:LWP:UA
$cv->begin;
push @c, async {
warn "soap $i"; soap($i);
$cv->end;
};
}
# $cv->recv will return when either:
# A. all the async blocks have finished running, or
# B. time has run out.
$cv->recv;
# notice that the results are out-of-order
print map { "$_\n" } @results;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment