]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/HTTPD/Async.pm
httpd/async: prevent circular reference
[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 use Scalar::Util qw(weaken);
14 require PublicInbox::EvCleanup;
15
16 sub new {
17         my ($class, $io, $cb, $cleanup) = @_;
18         my $self = fields::new($class);
19         IO::Handle::blocking($io, 0);
20         $self->SUPER::new($io);
21         $self->{cb} = $cb;
22         $self->{cleanup} = $cleanup;
23         $self->watch_read(1);
24         $self;
25 }
26
27 sub async_pass {
28         my ($self, $io, $fh, $bref) = @_;
29         # In case the client HTTP connection ($io) dies, it
30         # will automatically close this ($self) object.
31         $io->{forward} = $self;
32         $fh->write($$bref);
33         weaken($self);
34         my $restart_read = sub { $self->watch_read(1) };
35         $self->{cb} = sub {
36                 my $r = sysread($self->{sock}, $$bref, 8192);
37                 if ($r) {
38                         $fh->write($$bref);
39                         if ($io->{write_buf_size}) {
40                                 $self->watch_read(0);
41                                 $io->write($restart_read); # D::S::write
42                         }
43                         return; # stay in watch_read
44                 } elsif (!defined $r) {
45                         return if $!{EAGAIN} || $!{EINTR};
46                 }
47
48                 # Done! Error handling will happen in $fh->close
49                 # called by the {cleanup} handler
50                 $io->{forward} = undef;
51                 $self->close;
52         }
53 }
54
55 sub event_read { $_[0]->{cb}->() }
56 sub event_hup { $_[0]->{cb}->() }
57 sub event_err { $_[0]->{cb}->() }
58 sub sysread { shift->{sock}->sysread(@_) }
59
60 sub close {
61         my $self = shift;
62         my $cleanup = $self->{cleanup};
63         $self->{cleanup} = $self->{cb} = undef;
64         $self->SUPER::close(@_);
65
66         # we defer this to the next timer loop since close is deferred
67         PublicInbox::EvCleanup::asap($cleanup) if $cleanup;
68 }
69
70 # do not let ourselves be closed during graceful termination
71 sub busy () { $_[0]->{cb} }
72
73 1;