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 is is intended for use with read-only pipes.
8 package PublicInbox::HTTPD::Async;
11 use base qw(PublicInbox::DS);
12 use fields qw(cb cleanup);
13 require PublicInbox::EvCleanup;
17 my ($class, $io, $cb, $cleanup) = @_;
19 # no $io? call $cb at the top of the next event loop to
21 unless (defined($io)) {
22 PublicInbox::EvCleanup::asap($cb) if $cb;
23 PublicInbox::EvCleanup::next_tick($cleanup) if $cleanup;
27 my $self = fields::new($class);
28 IO::Handle::blocking($io, 0);
29 $self->SUPER::new($io, PublicInbox::DS::EPOLLIN());
31 $self->{cleanup} = $cleanup;
35 sub restart_read ($) { $_[0]->watch(PublicInbox::DS::EPOLLIN()) }
38 my ($http, $fh, $bref) = @_;
41 my $r = sysread($self->{sock}, $$bref, 8192);
43 $fh->write($$bref); # may call $http->close
45 if ($http->{sock}) { # !closed
47 # HTTP client could not keep up, so
48 # stop reading and buffering.
51 # Tell the HTTP socket to restart us
52 # when HTTP client is done draining
54 $http->enqueue_restart_pass;
56 # stay in EPOLLIN, but let other clients
57 # get some work done, too.
60 # fall through to close below...
61 } elsif (!defined $r) {
62 return restart_read($self) if $! == EAGAIN;
65 # Done! Error handling will happen in $fh->close
66 # called by the {cleanup} handler
67 delete $http->{forward};
73 my ($self, $http, $fh, $bref) = @_;
74 # In case the client HTTP connection ($http) dies, it
75 # will automatically close this ($self) object.
76 $http->{forward} = $self;
77 $fh->write($$bref); # PublicInbox:HTTP::{chunked,identity}_wcb
78 $self->{cb} = main_cb($http, $fh, $bref);
81 sub event_step { $_[0]->{cb}->(@_) }
88 # we defer this to the next timer loop since close is deferred
89 if (my $cleanup = delete $self->{cleanup}) {
90 PublicInbox::EvCleanup::next_tick($cleanup);