1 # Copyright (C) 2016-2018 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
4 # Limits the number of processes spawned
5 # This does not depend on Danga::Socket or any other external
6 # scheduling mechanism, you just need to call start and finish
8 package PublicInbox::Qspawn;
11 use PublicInbox::Spawn qw(popen_rd);
15 my ($class, $cmd, $env, $opt) = @_;
16 bless { args => [ $cmd, $env, $opt ] }, $class;
23 ($self->{rpipe}, $self->{pid}) = popen_rd(@{$self->{args}});
24 if (defined $self->{pid}) {
25 $self->{limiter}->{running}++;
29 $cb->($self->{rpipe});
34 my $limiter = $self->{limiter};
36 if (delete $self->{rpipe}) {
37 my $pid = delete $self->{pid};
38 $self->{err} = $pid == waitpid($pid, 0) ? $? :
39 "PID:$pid still running?";
40 $running = --$limiter->{running};
43 # limiter->{max} may change dynamically
44 if (($running || $limiter->{running}) < $limiter->{max}) {
45 if (my $next = shift @{$limiter->{run_queue}}) {
53 my ($self, $limiter, $cb) = @_;
54 $self->{limiter} = $limiter;
56 if ($limiter->{running} < $limiter->{max}) {
57 _do_spawn($self, $cb);
59 push @{$limiter->{run_queue}}, [ $self, $cb ];
64 my ($self, $env, $limiter, $parse_hdr) = @_;
67 if (my $err = $self->finish) {
68 $err = join(' ', @{$self->{args}->[0]}).": $err\n";
69 $env->{'psgi.errors'}->print($err);
71 $fh->close if $fh; # async-only
74 # Danga::Socket users, we queue up the read_enable callback to
75 # fire after pending writes are complete:
78 my $r = sysread($rpipe, $buf, 1024, length($buf));
79 return if !defined($r) && ($!{EINTR} || $!{EAGAIN});
80 $parse_hdr->($r, \$buf);
83 my $async = $env->{'pi-httpd.async'};
85 my $r = $rd_hdr->() or return;
87 if (scalar(@$r) == 3) { # error
89 $async->close; # calls rpipe->close
96 $fh = $res->($r); # scalar @$r == 2
97 $async->async_pass($env->{'psgix.io'}, $fh, \$buf);
98 } else { # for synchronous PSGI servers
99 require PublicInbox::GetlineBody;
100 $r->[2] = PublicInbox::GetlineBody->new($rpipe, $end,
105 $limiter ||= $def_limiter ||= PublicInbox::Qspawn::Limiter->new(32);
108 $self->start($limiter, sub { # may run later, much later...
111 # PublicInbox::HTTPD::Async->new($rpipe, $cb, $end)
112 $async = $async->($rpipe, $cb, $end);
113 } else { # generic PSGI
114 $cb->() while $rd_hdr;
120 package PublicInbox::Qspawn::Limiter;
125 my ($class, $max) = @_;
127 # 32 is same as the git-daemon connection limit