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;
16 my ($class, $io, $cb, $cleanup) = @_;
18 # no $io? call $cb at the top of the next event loop to
20 unless (defined($io)) {
21 PublicInbox::EvCleanup::asap($cb) if $cb;
22 PublicInbox::EvCleanup::next_tick($cleanup) if $cleanup;
26 my $self = fields::new($class);
27 IO::Handle::blocking($io, 0);
28 $self->SUPER::new($io, PublicInbox::DS::EPOLLIN());
30 $self->{cleanup} = $cleanup;
34 # fires after pending writes are complete:
35 sub restart_read_cb ($) {
37 sub { $self->watch_read(1) }
41 my ($http, $fh, $bref) = @_;
44 my $r = sysread($self->{sock}, $$bref, 8192);
47 if ($http->{sock}) { # !closed
50 $http->write(restart_read_cb($self));
52 # stay in watch_read, but let other clients
53 # get some work done, too.
56 # fall through to close below...
57 } elsif (!defined $r) {
58 return if $!{EAGAIN} || $!{EINTR};
61 # Done! Error handling will happen in $fh->close
62 # called by the {cleanup} handler
63 $http->{forward} = undef;
69 my ($self, $http, $fh, $bref) = @_;
70 # In case the client HTTP connection ($http) dies, it
71 # will automatically close this ($self) object.
72 $http->{forward} = $self;
73 $fh->write($$bref); # PublicInbox:HTTP::{chunked,identity}_wcb
74 $self->{cb} = main_cb($http, $fh, $bref);
77 sub event_step { $_[0]->{cb}->(@_) }
81 my $cleanup = $self->{cleanup};
82 $self->{cleanup} = $self->{cb} = undef;
83 $self->SUPER::close(@_);
85 # we defer this to the next timer loop since close is deferred
86 PublicInbox::EvCleanup::next_tick($cleanup) if $cleanup;