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 use Scalar::Util qw(weaken);
14 require PublicInbox::EvCleanup;
17 my ($class, $io, $cb, $cleanup) = @_;
18 my $self = fields::new($class);
19 IO::Handle::blocking($io, 0);
20 $self->SUPER::new($io);
22 $self->{cleanup} = $cleanup;
27 sub restart_read_cb ($) {
29 sub { $self->watch_read(1) }
33 my ($self, $io, $fh, $bref) = @_;
34 # In case the client HTTP connection ($io) dies, it
35 # will automatically close this ($self) object.
36 $io->{forward} = $self;
38 my $restart_read = restart_read_cb($self);
41 my $r = sysread($self->{sock}, $$bref, 8192);
44 if ($io->{write_buf_size}) {
46 $io->write($restart_read); # D::S::write
48 return; # stay in watch_read
49 } elsif (!defined $r) {
50 return if $!{EAGAIN} || $!{EINTR};
53 # Done! Error handling will happen in $fh->close
54 # called by the {cleanup} handler
55 $io->{forward} = undef;
60 sub event_read { $_[0]->{cb}->() }
61 sub event_hup { $_[0]->{cb}->() }
62 sub event_err { $_[0]->{cb}->() }
63 sub sysread { shift->{sock}->sysread(@_) }
67 my $cleanup = $self->{cleanup};
68 $self->{cleanup} = $self->{cb} = undef;
69 $self->SUPER::close(@_);
71 # we defer this to the next timer loop since close is deferred
72 PublicInbox::EvCleanup::asap($cleanup) if $cleanup;
75 # do not let ourselves be closed during graceful termination
76 sub busy () { $_[0]->{cb} }