]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/HTTPD/Async.pm
http: async getline supports push_back_read
[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);
13
14 sub new {
15         my ($class, $io, $cb) = @_;
16         my $self = fields::new($class);
17         IO::Handle::blocking($io, 0);
18         $self->SUPER::new($io);
19         $self->{cb} = $cb;
20         $self->watch_read(1);
21         $self;
22 }
23
24 sub async_pass { $_[0]->{cb} = $_[1] }
25 sub event_read { $_[0]->{cb}->() }
26 sub event_hup { $_[0]->{cb}->() }
27 sub event_err { $_[0]->{cb}->() }
28 sub sysread { shift->{sock}->sysread(@_) }
29
30 sub getline {
31         my ($self) = @_;
32         die 'getline called without $/ ref' unless ref $/;
33         while (1) {
34                 my $ret = $self->read(8192); # Danga::Socket::read
35                 return $$ret if defined $ret;
36
37                 return unless $!{EAGAIN} || $!{EINTR};
38
39                 # in case of spurious wakeup, hopefully we never hit this
40                 my $vin = '';
41                 vec($vin, $self->{fd}, 1) = 1;
42                 my $n;
43                 do { $n = select($vin, undef, undef, undef) } until $n;
44         }
45 }
46
47 sub close {
48         my $self = shift;
49         $self->{cb} = undef;
50         $self->SUPER::close(@_);
51 }
52
53 # do not let ourselves be closed during graceful termination
54 sub busy () { $_[0]->{cb} }
55
56 1;