]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/HTTPD/Async.pm
68514f5a5a2123b377da389a527280fa19706c25
[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 restart_read_cb ($) {
28         my ($self) = @_;
29         sub { $self->watch_read(1) }
30 }
31
32 sub async_pass {
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;
37         $fh->write($$bref);
38         my $restart_read = restart_read_cb($self);
39         weaken($self);
40         $self->{cb} = sub {
41                 my $r = sysread($self->{sock}, $$bref, 8192);
42                 if ($r) {
43                         $fh->write($$bref);
44                         return if $io->{closed};
45                         if ($io->{write_buf_size}) {
46                                 $self->watch_read(0);
47                                 $io->write($restart_read); # D::S::write
48                         }
49                         # stay in watch_read, but let other clients
50                         # get some work done, too.
51                         return;
52                 } elsif (!defined $r) {
53                         return if $!{EAGAIN} || $!{EINTR};
54                 }
55
56                 # Done! Error handling will happen in $fh->close
57                 # called by the {cleanup} handler
58                 $io->{forward} = undef;
59                 $self->close;
60         }
61 }
62
63 sub event_read { $_[0]->{cb}->() }
64 sub event_hup { $_[0]->{cb}->() }
65 sub event_err { $_[0]->{cb}->() }
66 sub sysread { shift->{sock}->sysread(@_) }
67
68 sub close {
69         my $self = shift;
70         my $cleanup = $self->{cleanup};
71         $self->{cleanup} = $self->{cb} = undef;
72         $self->SUPER::close(@_);
73
74         # we defer this to the next timer loop since close is deferred
75         PublicInbox::EvCleanup::next_tick($cleanup) if $cleanup;
76 }
77
78 1;