1 # Copyright (C) 2018-2020 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
4 # used to interface with a single Xapian shard in V2 repos.
5 # See L<public-inbox-v2-format(5)> for more info on how we shard Xapian
6 package PublicInbox::SearchIdxShard;
9 use base qw(PublicInbox::SearchIdx);
10 use IO::Handle (); # autoflush
14 my ($class, $v2writable, $shard) = @_;
15 my $ibx = $v2writable->{-inbox};
16 my $self = $class->SUPER::new($ibx, 1, $shard);
17 # create the DB before forking:
19 $self->set_indexlevel;
21 $self->spawn_worker($v2writable, $shard) if $v2writable->{parallel};
26 my ($self, $v2w, $shard) = @_;
28 pipe($r, $w) or die "pipe failed: $!\n";
33 defined $pid or die "fork failed: $!\n";
35 my $bnote = $v2w->atfork_child;
36 close $w or die "failed to close: $!";
38 # F_SETPIPE_SZ = 1031 on Linux; increasing the pipe size here
39 # speeds V2Writable batch imports across 8 cores by nearly 20%
40 fcntl($r, 1031, 1048576) if $^O eq 'linux';
42 eval { shard_worker_loop($self, $v2w, $r, $shard, $bnote) };
43 die "worker $shard died: $@\n" if $@;
44 die "unexpected MM $self->{mm}" if $self->{mm};
49 close $r or die "failed to close: $!";
52 sub shard_worker_loop ($$$$$) {
53 my ($self, $v2w, $r, $shard, $bnote) = @_;
54 $0 = "pi-v2-shard[$shard]";
55 $self->begin_txn_lazy;
56 while (my $line = readline($r)) {
57 $v2w->{current_info} = "[$shard] $line";
58 if ($line eq "commit\n") {
59 $self->commit_txn_lazy;
60 } elsif ($line eq "close\n") {
62 } elsif ($line eq "barrier\n") {
63 $self->commit_txn_lazy;
64 # no need to lock < 512 bytes is atomic under POSIX
65 print $bnote "barrier $shard\n" or
66 die "write failed for barrier $!\n";
67 } elsif ($line =~ /\AD ([a-f0-9]{40,}) (.+)\n\z/s) {
68 my ($oid, $mid) = ($1, $2);
69 $self->begin_txn_lazy;
70 $self->remove_by_oid($oid, $mid);
73 # n.b. $mid may contain spaces(!)
74 my ($to_read, $bytes, $num, $blob, $ds, $ts, $mid) =
76 $self->begin_txn_lazy;
77 my $n = read($r, my $msg, $to_read) or die "read: $!\n";
78 $n == $to_read or die "short read: $n != $to_read\n";
79 my $mime = PublicInbox::Eml->new(\$msg);
87 }, 'PublicInbox::Smsg';
88 $self->add_message($mime, $smsg);
94 # called by V2Writable
96 my ($self, $msgref, $mime, $smsg) = @_;
97 if (my $w = $self->{w}) {
98 # mid must be last, it can contain spaces (but not LF)
99 print $w join(' ', @$smsg{qw(raw_bytes bytes
100 num blob ds ts mid)}),
101 "\n", $$msgref or die "failed to write shard $!\n";
104 $self->begin_txn_lazy;
105 $self->add_message($mime, $smsg);
110 close $_[0]->{w} or die "failed to close write pipe: $!\n";
113 # called by V2Writable:
116 if (my $w = $self->{w}) {
117 print $w "barrier\n" or die "failed to print: $!";
119 $self->commit_txn_lazy;