1 # Copyright (C) 2020 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
4 # internal class used by PublicInbox::Git + PublicInbox::DS
5 # This parses the output pipe of "git cat-file --batch"
7 # Note: this does NOT set the non-blocking flag, we expect `git cat-file'
8 # to be a local process, and git won't start writing a blob until it's
9 # fully read. So minimize context switching and read as much as possible
10 # and avoid holding a buffer in our heap any longer than it has to live.
11 package PublicInbox::GitAsyncCat;
13 use parent qw(PublicInbox::DS Exporter);
14 use POSIX qw(WNOHANG);
15 use PublicInbox::Syscall qw(EPOLLIN EPOLLET);
16 our @EXPORT = qw(git_async_cat git_async_prefetch);
17 use PublicInbox::Git ();
19 our $GCF2C; # singleton PublicInbox::Gcf2Client
24 if (my $gitish = delete $self->{gitish}) {
25 PublicInbox::Git::cat_async_abort($gitish);
27 $self->SUPER::close; # PublicInbox::DS::close
32 my $gitish = $self->{gitish} or return;
33 return $self->close if ($gitish->{in} // 0) != ($self->{sock} // 1);
34 my $inflight = $gitish->{inflight};
35 if ($inflight && @$inflight) {
36 $gitish->cat_async_step($inflight);
39 if (($gitish->{in} // 0) != ($self->{sock} // 1)) {
41 } elsif (@$inflight || exists $gitish->{cat_rbuf}) {
42 # ok, more to do, requeue for fairness
45 } elsif ((my $pid = waitpid($gitish->{pid}, WNOHANG)) > 0) {
46 # May happen if the child process is killed by a BOFH
48 delete $gitish->{pid};
49 warn "E: gitish $pid exited with \$?=$?\n";
54 sub git_async_cat ($$$$) {
55 my ($git, $oid, $cb, $arg) = @_;
58 $oid .= " $git->{git_dir}";
62 $gitish->cat_async($oid, $cb, $arg);
63 $gitish->{async_cat} //= do {
64 my $self = bless { gitish => $gitish }, __PACKAGE__;
65 $self->SUPER::new($gitish->{in}, EPOLLIN|EPOLLET);
66 \undef; # this is a true ref()
70 # this is safe to call inside $cb, but not guaranteed to enqueue
71 # returns true if successful, undef if not.
72 sub git_async_prefetch {
73 my ($git, $oid, $cb, $arg) = @_;
75 if ($GCF2C->{async_cat} && !$GCF2C->{wbuf}) {
76 $oid .= " $git->{git_dir}";
77 return $GCF2C->cat_async($oid, $cb, $arg);
79 } elsif ($git->{async_cat} && (my $inflight = $git->{inflight})) {
80 # we could use MAX_INFLIGHT here w/o the halving,
81 # but lets not allow one client to monopolize a git process
82 if (@$inflight < int(PublicInbox::Git::MAX_INFLIGHT/2)) {
83 print { $git->{out} } $oid, "\n" or
84 $git->fail("write error: $!");
85 return push(@$inflight, $oid, $cb, $arg);