1 # Copyright (C) 2016 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(Danga::Socket);
12 use fields qw(cb cleanup);
13 require PublicInbox::EvCleanup;
16 my ($class, $io, $cb, $cleanup) = @_;
17 my $self = fields::new($class);
18 IO::Handle::blocking($io, 0);
19 $self->SUPER::new($io);
21 $self->{cleanup} = $cleanup;
27 my ($self, $io, $fh, $bref) = @_;
28 my $restart_read = sub { $self->watch_read(1) };
29 # In case the client HTTP connection ($io) dies, it
30 # will automatically close this ($self) object.
31 $io->{forward} = $self;
34 my $r = sysread($self->{sock}, $$bref, 8192);
37 if ($io->{write_buf_size}) {
39 $io->write($restart_read); # D::S::write
41 return; # stay in watch_read
42 } elsif (!defined $r) {
43 return if $!{EAGAIN} || $!{EINTR};
46 # Done! Error handling will happen in $fh->close
47 # called by the {cleanup} handler
48 $io->{forward} = undef;
53 sub event_read { $_[0]->{cb}->() }
54 sub event_hup { $_[0]->{cb}->() }
55 sub event_err { $_[0]->{cb}->() }
56 sub sysread { shift->{sock}->sysread(@_) }
60 my $cleanup = $self->{cleanup};
61 $self->{cleanup} = $self->{cb} = undef;
62 $self->SUPER::close(@_);
64 # we defer this to the next timer loop since close is deferred
65 PublicInbox::EvCleanup::asap($cleanup) if $cleanup;
68 # do not let ourselves be closed during graceful termination
69 sub busy () { $_[0]->{cb} }