]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Gcf2Client.pm
use PublicInbox::DS for dwaitpid
[public-inbox.git] / lib / PublicInbox / Gcf2Client.pm
1 # Copyright (C) 2020 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
3
4 # connects public-inbox processes to PublicInbox::Gcf2::loop()
5 package PublicInbox::Gcf2Client;
6 use strict;
7 use parent qw(PublicInbox::DS);
8 use PublicInbox::Git;
9 use PublicInbox::Spawn qw(popen_rd);
10 use IO::Handle ();
11 use PublicInbox::Syscall qw(EPOLLONESHOT);
12 use PublicInbox::DS qw(dwaitpid);
13 # fields:
14 #       async_cat => GitAsyncCat ref (read-only pipe)
15 #       sock => writable pipe to Gcf2::loop
16 #       in => pipe we read from
17 #       pid => PID of Gcf2::loop process
18 sub new  {
19         my ($rdr) = @_;
20         my $self = bless {}, __PACKAGE__;
21         # ensure the child process has the same @INC we do:
22         my $env = { PERL5LIB => join(':', @INC) };
23         my ($out_r, $out_w);
24         pipe($out_r, $out_w) or die "pipe failed: $!";
25         $rdr //= {};
26         $rdr->{0} = $out_r;
27         my $cmd = [$^X, qw[-MPublicInbox::Gcf2 -e PublicInbox::Gcf2::loop()]];
28         @$self{qw(in pid)} = popen_rd($cmd, $env, $rdr);
29         fcntl($out_w, 1031, 4096) if $^O eq 'linux'; # 1031: F_SETPIPE_SZ
30         $out_w->autoflush(1);
31         $out_w->blocking(0);
32         $self->{inflight} = [];
33         $self->SUPER::new($out_w, EPOLLONESHOT); # detect errors once
34 }
35
36 sub fail {
37         my $self = shift;
38         $self->close; # PublicInbox::DS::close
39         PublicInbox::Git::fail($self, @_);
40 }
41
42 sub cat_async ($$$;$) {
43         my ($self, $req, $cb, $arg) = @_;
44         my $inflight = $self->{inflight};
45
46         # {wbuf} is rare, I hope:
47         cat_async_step($self, $inflight) if $self->{wbuf};
48
49         if (!$self->write(\"$req\n")) {
50                 $self->fail("gcf2c write: $!") if !$self->{sock};
51         }
52         push @$inflight, $req, $cb, $arg;
53 }
54
55 # ensure PublicInbox::Git::cat_async_step never calls cat_async_retry
56 sub alternates_changed {}
57
58 # this is the write-only end of a pipe, DS->EventLoop will call this
59 sub event_step {
60         my ($self) = @_;
61         $self->flush_write;
62         $self->close if !$self->{in}; # process died
63 }
64
65 no warnings 'once';
66
67 sub DESTROY {
68         my ($self) = @_;
69         delete $self->{in};
70         # GitAsyncCat::event_step may reap us with WNOHANG, too
71         my $pid = delete $self->{pid} or return;
72         PublicInbox::DS->in_loop ? $self->close : delete($self->{sock});
73         dwaitpid $pid;
74 }
75
76 # used by GitAsyncCat
77 *cat_async_step = \&PublicInbox::Git::cat_async_step;
78
79 1;