]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/HTTPD/Async.pm
bd2eacbfdfee8a5be8f3e9b423907a9ac16b5851
[public-inbox.git] / lib / PublicInbox / HTTPD / Async.pm
1 # Copyright (C) 2016 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
3 #
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;
9 use strict;
10 use warnings;
11 use base qw(Danga::Socket);
12 use fields qw(cb cleanup);
13
14 sub new {
15         my ($class, $io, $cb, $cleanup) = @_;
16         my $self = fields::new($class);
17         IO::Handle::blocking($io, 0);
18         $self->SUPER::new($io);
19         $self->{cb} = $cb;
20         $self->{cleanup} = $cleanup;
21         $self->watch_read(1);
22         $self;
23 }
24
25 sub async_pass {
26         my ($self, $io, $fh, $bref) = @_;
27         my $restart_read = sub { $self->watch_read(1) };
28         # In case the client HTTP connection ($io) dies, it
29         # will automatically close this ($self) object.
30         $io->{forward} = $self;
31         $fh->write($$bref);
32         $self->{cb} = sub {
33                 my $r = sysread($self->{sock}, $$bref, 8192);
34                 if ($r) {
35                         $fh->write($$bref);
36                         if ($io->{write_buf_size}) {
37                                 $self->watch_read(0);
38                                 $io->write($restart_read); # D::S::write
39                         }
40                         return; # stay in watch_read
41                 } elsif (!defined $r) {
42                         return if $!{EAGAIN} || $!{EINTR};
43                 }
44
45                 # Done! Error handling will happen in $fh->close
46                 # called by the {cleanup} handler
47                 $io->{forward} = undef;
48                 $self->close;
49         }
50 }
51
52 sub event_read { $_[0]->{cb}->() }
53 sub event_hup { $_[0]->{cb}->() }
54 sub event_err { $_[0]->{cb}->() }
55 sub sysread { shift->{sock}->sysread(@_) }
56
57 sub close {
58         my $self = shift;
59         my $cleanup = $self->{cleanup};
60         $self->{cleanup} = $self->{cb} = undef;
61         $self->SUPER::close(@_);
62
63         # we defer this to the next timer loop since close is deferred
64         Danga::Socket->AddTimer(0, $cleanup) if $cleanup;
65 }
66
67 # do not let ourselves be closed during graceful termination
68 sub busy () { $_[0]->{cb} }
69
70 1;