1 # Copyright (C) 2016-2018 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
4 # XXX This is a totally unstable API for public-inbox internal use only
5 # This is exposed via the 'pi-httpd.async' key in the PSGI env hash.
6 # The name of this key is not even stable!
7 # Currently intended for use with read-only pipes with expensive
8 # processes such as git-http-backend(1), cgit(1)
9 package PublicInbox::HTTPD::Async;
12 use base qw(PublicInbox::DS);
13 use fields qw(cb cleanup);
15 use PublicInbox::Syscall qw(EPOLLIN EPOLLET);
18 my ($class, $io, $cb, $cleanup) = @_;
20 # no $io? call $cb at the top of the next event loop to
22 unless (defined($io)) {
23 PublicInbox::DS::requeue($cb);
24 die 'cleanup unsupported w/o $io' if $cleanup;
28 my $self = fields::new($class);
29 IO::Handle::blocking($io, 0);
30 $self->SUPER::new($io, EPOLLIN | EPOLLET);
32 $self->{cleanup} = $cleanup;
40 my $r = sysread($self->{sock}, my $buf, 65536);
42 $fh->write($buf); # may call $http->close
43 if ($http->{sock}) { # !closed
45 # let other clients get some work done, too
49 # else: fall through to close below...
50 } elsif (!defined $r && $! == EAGAIN) {
51 return; # EPOLLET means we'll be notified
54 # Done! Error handling will happen in $fh->close
55 # called by the {cleanup} handler
56 delete $http->{forward};
62 my ($self, $http, $fh, $bref) = @_;
63 # In case the client HTTP connection ($http) dies, it
64 # will automatically close this ($self) object.
65 $http->{forward} = $self;
66 $fh->write($$bref); # PublicInbox:HTTP::{chunked,identity}_wcb
67 $$bref = undef; # we're done with this
68 my $cb = $self->{cb} = main_cb($http, $fh);
69 $cb->($self); # either hit EAGAIN or ->requeue to keep EPOLLET happy
73 # {cb} may be undef after ->requeue due to $http->close happening
74 my $cb = $_[0]->{cb} or return;
83 # we defer this to the next timer loop since close is deferred
84 if (my $cleanup = delete $self->{cleanup}) {
85 PublicInbox::DS::requeue($cleanup);