]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/GetlineBody.pm
run update-copyrights from gnulib for 2019
[public-inbox.git] / lib / PublicInbox / GetlineBody.pm
1 # Copyright (C) 2016-2019 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
3
4 # Wrap a pipe or file for PSGI streaming response bodies and calls the
5 # end callback when the object goes out-of-scope.
6 # This depends on rpipe being _blocking_ on getline.
7 #
8 # public-inbox-httpd favors "getline" response bodies to take a
9 # "pull"-based approach to feeding slow clients (as opposed to a
10 # more common "push" model)
11 package PublicInbox::GetlineBody;
12 use strict;
13 use warnings;
14
15 sub new {
16         my ($class, $rpipe, $end, $buf, $filter) = @_;
17         bless {
18                 rpipe => $rpipe,
19                 end => $end,
20                 buf => $buf,
21                 filter => $filter || 0,
22         }, $class;
23 }
24
25 # close should always be called after getline returns undef,
26 # but a client aborting a connection can ruin our day; so lets
27 # hope our underlying PSGI server does not leak references, here.
28 sub DESTROY { $_[0]->close }
29
30 sub getline {
31         my ($self) = @_;
32         my $filter = $self->{filter};
33         return if $filter == -1; # last call was EOF
34
35         my $buf = delete $self->{buf}; # initial buffer
36         $buf = $self->{rpipe}->getline unless defined $buf;
37         $self->{filter} = -1 unless defined $buf; # set EOF for next call
38         $filter ? $filter->($buf) : $buf;
39 }
40
41 sub close {
42         my ($self) = @_;
43         my $rpipe = delete $self->{rpipe};
44         close $rpipe if $rpipe;
45         my $end = delete $self->{end};
46         $end->() if $end;
47 }
48
49 1;