plack / Plack

PSGI toolkit and server adapters
http://plackperl.org/
Other
486 stars 214 forks source link

Add --listen-sock option #641

Closed ned closed 4 years ago

ned commented 4 years ago

This allows passing in a socket object, for example

$sock = IO::Socket::INET->new(
    LocalAddr => 'localhost',
    LocalPort => 0,
    Proto     => 'tcp',
);
$runner->parse_options('--listen-sock', $sock);

The option will get passed down to HTTP::Server::PSGI

https://github.com/plack/Plack/blob/master/lib/HTTP/Server/PSGI.pm#L40-L43

I need this because I want to ensure Plack::Runner is running on a free port, but I don't think there's a way to do that currently (that's guaranteed to be free from race conditions). What I'd like to be able to do is

my $server = Test::TCP->new(
    listen => 1,
    code => sub {
        my $socket = shift;
        my $sock_fd = fileno($socket);
        my $app = ...;
        my $runner = Plack::Runner->new;
        $runner->parse_options('--listen-sock', $sock);
        $runner->run($app);
    }
);
my $port = $server->port;
miyagawa commented 4 years ago

Plack::Runner is not the right layer for this since you already have access to $app and the raw socket.

    my $runner = Plack::Runner->new;
    $runner->parse_options('--listen-sock', $sock);
    $runner->run($app);

This can be done easily with Plack::Loader:

Plack::Loader->auto(listen_sock => $sock)->run($app);

Or directly with HTTP::Server::PSGI:

my $server = HTTP::Server::PSGI->new(
   ...
   listen_sock => $sock,
);
$server->run($app);