Acme-Parataxis

 view release on metacpan or  search on metacpan

t/013_real_http.t  view on Meta::CPAN

        return $res;
    }
}
{

    package Acme::Parataxis::Test::RealHTTP::Handle;
    use parent -norequire, 'HTTP::Tiny::Handle';

    sub _do_timeout {
        my ( $self, $type, $timeout ) = @_;
        $timeout //= $self->{timeout} // 60;
        if ( $self->{fh} ) {
            my $start = time();
            while (1) {
                return 1 if $self->SUPER::_do_timeout( $type, 0 );
                my $elapsed = time() - $start;
                return 0 if $elapsed > $timeout;
                my $wait = ( $timeout - $elapsed ) > 0.5 ? 0.5 : ( $timeout - $elapsed );
                if ( $type eq 'read' ) {
                    Acme::Parataxis->await_read( $self->{fh}, int( $wait * 1000 ) );
                }
                else {
                    Acme::Parataxis->await_write( $self->{fh}, int( $wait * 1000 ) );
                }
            }
        }
        return $self->SUPER::_do_timeout( $type, 0 );
    }
}
Acme::Parataxis::run(
    sub {
        my $http = Acme::Parataxis::Test::RealHTTP->new( timeout => 10, verify_SSL => 0 );
        my @urls = qw[
            http://example.com
            https://www.google.com/
            https://www.perl.org/
            https://metacpan.org/
            https://www.cpan.org/
            https://github.com/
        ];
        my @futures;

        for my $url (@urls) {
            push @futures, Acme::Parataxis->spawn(
                sub {
                    my $fid = Acme::Parataxis->current_fid;
                    diag "Fiber $fid: Fetching $url...";
                    my $res = $http->get($url);
                    diag "Fiber $fid: Done fetching $url.";
                    $res;
                }
            );
        }
        for my $i ( 0 .. $#urls ) {
            my $url = $urls[$i];
            my $res = $futures[$i]->await();
            todo "External network fetch for $url might fail" => sub {
                is( $res->{status}, 200, "Fetched $url successfully" ) or
                    diag "Failed to fetch $url: $res->{status} $res->{reason}\nContent: " . ( $res->{content} // '' );
                if ( $res->{status} == 200 ) {
                    like( $res->{content}, qr/<html/i, "$url content looks like HTML" );
                }
            };
        }
        Acme::Parataxis::stop();
    }
);
done_testing();



( run in 1.545 second using v1.01-cache-2.11-cpan-ad19def0cd9 )