]> Sergey Matveev's repositories - public-inbox.git/blobdiff - lib/PublicInbox/HTTP.pm
remove hard Devel::Peek dependency and lazy load for daemons
[public-inbox.git] / lib / PublicInbox / HTTP.pm
index 77b178c07e6fea56cfe47c9b95a7358499f91088..10e6d6a43b518115c7eece8a5f11e67ebe613fb2 100644 (file)
@@ -1,22 +1,24 @@
-# Copyright (C) 2016 all contributors <meta@public-inbox.org>
+# Copyright (C) 2016-2018 all contributors <meta@public-inbox.org>
 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
 #
 # Generic PSGI server for convenience.  It aims to provide
 # a consistent experience for public-inbox admins so they don't have
 # to learn different ways to admin both NNTP and HTTP components.
-# There's nothing public-inbox-specific, here.
+# There's nothing which depends on public-inbox, here.
 # Each instance of this class represents a HTTP client socket
 
 package PublicInbox::HTTP;
 use strict;
 use warnings;
-use base qw(Danga::Socket);
-use fields qw(httpd env rbuf input_left remote_addr remote_port forward);
+use base qw(PublicInbox::DS);
+use fields qw(httpd env rbuf input_left remote_addr remote_port forward pull);
+use bytes (); # only for bytes::length
 use Fcntl qw(:seek);
 use Plack::HTTPParser qw(parse_http_request); # XS or pure Perl
 use HTTP::Status qw(status_message);
 use HTTP::Date qw(time2str);
-use IO::File;
+use IO::Handle;
+require PublicInbox::EvCleanup;
 use constant {
        CHUNK_START => -1,   # [a-f0-9]+\r\n
        CHUNK_END => -2,     # \r\n
@@ -24,13 +26,16 @@ use constant {
        CHUNK_MAX_HDR => 256,
 };
 
-# FIXME: duplicated code with NNTP.pm
-my $WEAKEN = {}; # string(inbox) -> inbox
-my $WEAKTIMER;
-sub weaken_task () {
-       $WEAKTIMER = undef;
-       $_->weaken_all for values %$WEAKEN;
-       $WEAKEN = {};
+my $pipelineq = [];
+my $pipet;
+sub process_pipelineq () {
+       my $q = $pipelineq;
+       $pipet = undef;
+       $pipelineq = [];
+       foreach (@$q) {
+               next if $_->{closed};
+               rbuf_process($_);
+       }
 }
 
 # Use the same configuration parameter as git since this is primarily
@@ -39,7 +44,7 @@ sub weaken_task () {
 our $MAX_REQUEST_BUFFER = $ENV{GIT_HTTP_MAX_REQUEST_BUFFER} ||
                        (10 * 1024 * 1024);
 
-my $null_io = IO::File->new('/dev/null', '<');
+open(my $null_io, '<', '/dev/null') or die "failed to open /dev/null: $!";
 my $http_date;
 my $prev = 0;
 sub http_date () {
@@ -59,7 +64,7 @@ sub new ($$$) {
        $self;
 }
 
-sub event_read { # called by Danga::Socket
+sub event_read { # called by PublicInbox::DS
        my ($self) = @_;
 
        return event_read_input($self) if defined $self->{env};
@@ -94,7 +99,7 @@ sub rbuf_process {
        $self->{rbuf} = substr($self->{rbuf}, $r);
 
        my $len = input_prepare($self, \%env);
-       defined $len or return write_err($self); # EMFILE/ENFILE
+       defined $len or return write_err($self, undef); # EMFILE/ENFILE
 
        $len ? event_read_input($self) : app_dispatch($self);
 }
@@ -114,7 +119,7 @@ sub event_read_input ($) {
        while ($len > 0) {
                if ($$rbuf ne '') {
                        my $w = write_in_full($input, $rbuf, $len);
-                       return write_err($self) unless $w;
+                       return write_err($self, $len) unless $w;
                        $len -= $w;
                        die "BUG: $len < 0 (w=$w)" if $len < 0;
                        if ($len == 0) { # next request may be pipelined
@@ -144,7 +149,7 @@ sub app_dispatch {
                sysseek($input, 0, SEEK_SET) or
                        die "BUG: psgi.input seek failed: $!";
        }
-       # note: NOT $self->{sock}, we want our close (+ Danga::Socket::close),
+       # note: NOT $self->{sock}, we want our close (+ PublicInbox::DS::close),
        # to do proper cleanup:
        $env->{'psgix.io'} = $self; # only for ->close
        my $res = Plack::Util::run_app($self->{httpd}->{app}, $env);
@@ -190,6 +195,7 @@ sub response_header_write {
                $alive = 1;
                $h .= "Connection: keep-alive\r\n";
        } else {
+               $alive = 0;
                $h .= "Connection: close\r\n";
        }
        $h .= 'Date: ' . http_date() . "\r\n\r\n";
@@ -209,7 +215,10 @@ sub chunked_wcb ($) {
                return if $_[0] eq '';
                more($self, sprintf("%x\r\n", bytes::length($_[0])));
                more($self, $_[0]);
-               $self->write("\r\n");
+
+               # use $self->write("\n\n") if you care about real-time
+               # streaming responses, public-inbox WWW does not.
+               more($self, "\r\n");
        }
 }
 
@@ -218,46 +227,83 @@ sub identity_wcb ($) {
        sub { $self->write(\($_[0])) if $_[0] ne '' }
 }
 
-sub response_write {
-       my ($self, $env, $res) = @_;
-       my $alive = response_header_write($self, $env, $res);
+sub next_request ($) {
+       my ($self) = @_;
+       $self->watch_write(0);
+       if ($self->{rbuf} eq '') { # wait for next request
+               $self->watch_read(1);
+       } else { # avoid recursion for pipelined requests
+               push @$pipelineq, $self;
+               $pipet ||= PublicInbox::EvCleanup::asap(*process_pipelineq);
+       }
+}
 
-       my $write = $alive == 2 ? chunked_wcb($self) : identity_wcb($self);
-       my $close = sub {
+sub response_done_cb ($$) {
+       my ($self, $alive) = @_;
+       sub {
+               my $env = $self->{env};
+               $self->{env} = undef;
                $self->write("0\r\n\r\n") if $alive == 2;
-               if ($alive) {
-                       $self->event_write; # watch for readability if done
-               } else {
-                       Danga::Socket::write($self, sub { $self->close });
+               $self->write(sub{$alive ? next_request($self) : $self->close});
+       }
+}
+
+sub getline_cb ($$$) {
+       my ($self, $write, $close) = @_;
+       local $/ = \8192;
+       my $forward = $self->{forward};
+       # limit our own running time for fairness with other
+       # clients and to avoid buffering too much:
+       if ($forward) {
+               my $buf = eval { $forward->getline };
+               if (defined $buf) {
+                       $write->($buf); # may close in PublicInbox::DS::write
+                       unless ($self->{closed}) {
+                               my $next = $self->{pull};
+                               if ($self->{write_buf_size}) {
+                                       $self->write($next);
+                               } else {
+                                       PublicInbox::EvCleanup::asap($next);
+                               }
+                               return;
+                       }
+               } elsif ($@) {
+                       err($self, "response ->getline error: $@");
+                       $forward = undef;
+                       $self->close;
                }
-               if (my $obj = $env->{'pi-httpd.inbox'}) {
-                       # grace period for reaping resources
-                       $WEAKEN->{"$obj"} = $obj;
-                       $WEAKTIMER ||= Danga::Socket->AddTimer(60, *weaken_task);
+       }
+
+       $self->{forward} = $self->{pull} = undef;
+       # avoid recursion
+       if ($forward) {
+               eval { $forward->close };
+               if ($@) {
+                       err($self, "response ->close error: $@");
+                       $self->close; # idempotent
                }
-               $self->{env} = undef;
-       };
+       }
+       $close->();
+}
+
+sub getline_response ($$$) {
+       my ($self, $write, $close) = @_;
+       my $pull = $self->{pull} = sub { getline_cb($self, $write, $close) };
+       $pull->();
+}
 
+sub response_write {
+       my ($self, $env, $res) = @_;
+       my $alive = response_header_write($self, $env, $res);
+       my $close = response_done_cb($self, $alive);
+       my $write = $alive == 2 ? chunked_wcb($self) : identity_wcb($self);
        if (defined(my $body = $res->[2])) {
                if (ref $body eq 'ARRAY') {
                        $write->($_) foreach @$body;
                        $close->();
                } else {
-                       my $pull;
-                       $pull = sub {
-                               local $/ = \8192;
-                               while (defined(my $buf = $body->getline)) {
-                                       $write->($buf);
-                                       if ($self->{write_buf_size}) {
-                                               $self->write($pull);
-                                               return;
-                                       }
-                               }
-                               $pull = undef;
-                               $body->close();
-                               $close->();
-                       };
-                       $pull->();
+                       $self->{forward} = $body;
+                       getline_response($self, $write, $close);
                }
        } else {
                # this is returned to the calling application:
@@ -268,54 +314,35 @@ sub response_write {
 use constant MSG_MORE => ($^O eq 'linux') ? 0x8000 : 0;
 sub more ($$) {
        my $self = $_[0];
+       return if $self->{closed};
        if (MSG_MORE && !$self->{write_buf_size}) {
                my $n = send($self->{sock}, $_[1], MSG_MORE);
                if (defined $n) {
-                       my $dlen = length($_[1]);
-                       return 1 if $n == $dlen; # all done!
-                       $_[1] = substr($_[1], $n, $dlen - $n);
-                       # fall through to normal write:
+                       my $nlen = length($_[1]) - $n;
+                       return 1 if $nlen == 0; # all done!
+
+                       # PublicInbox::DS::write queues the unwritten substring:
+                       return $self->write(substr($_[1], $n, $nlen));
                }
        }
        $self->write($_[1]);
 }
 
-my $pipelineq = [];
-my $next_tick;
-sub process_pipelineq () {
-       $next_tick = undef;
-       my $q = $pipelineq;
-       $pipelineq = [];
-       rbuf_process($_) foreach @$q;
-}
-
-# overrides existing Danga::Socket method
-sub event_write {
-       my ($self) = @_;
-       # only continue watching for readability when we are done writing:
-       return if $self->write(undef) != 1;
-
-       if ($self->{rbuf} eq '') { # wait for next request
-               $self->watch_read(1);
-       } else { # avoid recursion for pipelined requests
-               push @$pipelineq, $self;
-               $next_tick ||= Danga::Socket->AddTimer(0, *process_pipelineq);
-       }
-}
-
 sub input_prepare {
        my ($self, $env) = @_;
-       my $input = $null_io;
+       my $input;
        my $len = $env->{CONTENT_LENGTH};
        if ($len) {
                if ($len > $MAX_REQUEST_BUFFER) {
                        quit($self, 413);
                        return;
                }
-               $input = IO::File->new_tmpfile;
+               open($input, '+>', undef);
        } elsif (env_chunked($env)) {
                $len = CHUNK_START;
-               $input = IO::File->new_tmpfile;
+               open($input, '+>', undef);
+       } else {
+               $input = $null_io;
        }
 
        # TODO: expire idle clients on ENFILE / EMFILE
@@ -328,11 +355,15 @@ sub input_prepare {
 
 sub env_chunked { ($_[0]->{HTTP_TRANSFER_ENCODING} || '') =~ /\bchunked\b/i }
 
+sub err ($$) {
+       eval { $_[0]->{httpd}->{env}->{'psgi.errors'}->print($_[1]."\n") };
+}
+
 sub write_err {
-       my ($self) = @_;
-       my $err = $self->{httpd}->{env}->{'psgi.errors'};
+       my ($self, $len) = @_;
        my $msg = $! || '(zero write)';
-       $err->print("error buffering to input: $msg\n");
+       $msg .= " ($len bytes remaining)" if defined $len;
+       err($self, "error buffering to input: $msg");
        quit($self, 500);
 }
 
@@ -343,8 +374,7 @@ sub recv_err {
                $self->{input_left} = $len;
                return;
        }
-       my $err = $self->{httpd}->{env}->{'psgi.errors'};
-       $err->print("error reading for input: $! ($len bytes remaining)\n");
+       err($self, "error reading for input: $! ($len bytes remaining)");
        quit($self, 500);
 }
 
@@ -407,7 +437,7 @@ sub event_read_input_chunked { # unlikely...
                until ($len <= 0) {
                        if ($$rbuf ne '') {
                                my $w = write_in_full($input, $rbuf, $len);
-                               return write_err($self) unless $w;
+                               return write_err($self, "$len chunk") if !$w;
                                $len -= $w;
                                if ($len == 0) {
                                        # we may have leftover data to parse
@@ -436,7 +466,7 @@ sub quit {
        $self->close;
 }
 
-# callbacks for Danga::Socket
+# callbacks for PublicInbox::DS
 
 sub event_hup { $_[0]->close }
 sub event_err { $_[0]->close }
@@ -444,8 +474,13 @@ sub event_err { $_[0]->close }
 sub close {
        my $self = shift;
        my $forward = $self->{forward};
-       $forward->close if $forward;
-       $self->{forward} = $self->{env} = undef;
+       my $env = $self->{env};
+       delete $env->{'psgix.io'} if $env; # prevent circular references
+       $self->{pull} = $self->{forward} = $self->{env} = undef;
+       if ($forward) {
+               eval { $forward->close };
+               err($self, "forward ->close error: $@") if $@;
+       }
        $self->SUPER::close(@_);
 }