]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/GetlineBody.pm
update copyrights for 2021
[public-inbox.git] / lib / PublicInbox / GetlineBody.pm
1 # Copyright (C) 2016-2021 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 # This is only used by generic PSGI servers and not public-inbox-httpd
9 package PublicInbox::GetlineBody;
10 use strict;
11 use warnings;
12
13 sub new {
14         my ($class, $rpipe, $end, $end_arg, $buf, $filter) = @_;
15         bless {
16                 rpipe => $rpipe,
17                 end => $end,
18                 end_arg => $end_arg,
19                 initial_buf => $buf,
20                 filter => $filter,
21         }, $class;
22 }
23
24 # close should always be called after getline returns undef,
25 # but a client aborting a connection can ruin our day; so lets
26 # hope our underlying PSGI server does not leak references, here.
27 sub DESTROY { $_[0]->close }
28
29 sub getline {
30         my ($self) = @_;
31         my $rpipe = $self->{rpipe} or return; # EOF was set on previous call
32         my $buf = delete($self->{initial_buf}) // $rpipe->getline;
33         delete($self->{rpipe}) unless defined $buf; # set EOF for next call
34         if (my $filter = $self->{filter}) {
35                 $buf = $filter->translate($buf);
36         }
37         $buf;
38 }
39
40 sub close {
41         my ($self) = @_;
42         my ($end, $end_arg) = delete @$self{qw(end end_arg)};
43         $end->($end_arg) if $end;
44 }
45
46 1;