]> Sergey Matveev's repositories - public-inbox.git/blobdiff - lib/PublicInbox/GetlineBody.pm
treewide: run update-copyrights from gnulib for 2019
[public-inbox.git] / lib / PublicInbox / GetlineBody.pm
index 5f32782886205641ac46dcbc7abd28949d0b0c32..92719a8255c56f46fcf9312ac7c669a6f64104da 100644 (file)
@@ -1,16 +1,26 @@
-# Copyright (C) 2016 all contributors <meta@public-inbox.org>
+# Copyright (C) 2016-2020 all contributors <meta@public-inbox.org>
 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
 
 # Wrap a pipe or file for PSGI streaming response bodies and calls the
 # end callback when the object goes out-of-scope.
 # This depends on rpipe being _blocking_ on getline.
+#
+# public-inbox-httpd favors "getline" response bodies to take a
+# "pull"-based approach to feeding slow clients (as opposed to a
+# more common "push" model)
 package PublicInbox::GetlineBody;
 use strict;
 use warnings;
 
 sub new {
-       my ($class, $rpipe, $end, $buf) = @_;
-       bless { rpipe => $rpipe, end => $end, buf => $buf }, $class;
+       my ($class, $rpipe, $end, $end_arg, $buf) = @_;
+       bless {
+               rpipe => $rpipe,
+               end => $end,
+               end_arg => $end_arg,
+               buf => $buf,
+               filter => 0,
+       }, $class;
 }
 
 # close should always be called after getline returns undef,
@@ -20,16 +30,20 @@ sub DESTROY { $_[0]->close }
 
 sub getline {
        my ($self) = @_;
+       my $filter = $self->{filter};
+       return if $filter == -1; # last call was EOF
+
        my $buf = delete $self->{buf}; # initial buffer
-       defined $buf ? $buf : $self->{rpipe}->getline;
+       $buf = $self->{rpipe}->getline unless defined $buf;
+       $self->{filter} = -1 unless defined $buf; # set EOF for next call
+       $buf;
 }
 
 sub close {
        my ($self) = @_;
-       my $rpipe = delete $self->{rpipe};
+       my ($rpipe, $end, $end_arg) = delete @$self{qw(rpipe end end_arg)};
        close $rpipe if $rpipe;
-       my $end = delete $self->{end};
-       $end->() if $end;
+       $end->($end_arg) if $end;
 }
 
 1;