]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/GetlineBody.pm
qspawn: reinstate filter support, add gzip filter
[public-inbox.git] / lib / PublicInbox / GetlineBody.pm
1 # Copyright (C) 2016-2020 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, $end_arg, $buf, $filter) = @_;
17         bless {
18                 rpipe => $rpipe,
19                 end => $end,
20                 end_arg => $end_arg,
21                 initial_buf => $buf,
22                 filter => $filter,
23         }, $class;
24 }
25
26 # close should always be called after getline returns undef,
27 # but a client aborting a connection can ruin our day; so lets
28 # hope our underlying PSGI server does not leak references, here.
29 sub DESTROY { $_[0]->close }
30
31 sub getline {
32         my ($self) = @_;
33         my $rpipe = $self->{rpipe} or return; # EOF was set on previous call
34         my $buf = delete($self->{initial_buf}) // $rpipe->getline;
35         delete($self->{rpipe}) unless defined $buf; # set EOF for next call
36         if (my $filter = $self->{filter}) {
37                 $buf = $filter->translate($buf);
38         }
39         $buf;
40 }
41
42 sub close {
43         my ($self) = @_;
44         my ($end, $end_arg) = delete @$self{qw(end end_arg)};
45         $end->($end_arg) if $end;
46 }
47
48 1;