]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/ExtSearchIdx.pm
extindex: flush pending reindex before unref
[public-inbox.git] / lib / PublicInbox / ExtSearchIdx.pm
1 # Copyright (C) 2020-2021 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
3
4 # Detached/external index cross inbox search indexing support
5 # read-write counterpart to PublicInbox::ExtSearch
6 #
7 # It's based on the same ideas as public-inbox-v2-format(5) using
8 # over.sqlite3 for dedupe and sharded Xapian.  msgmap.sqlite3 is
9 # missing, so there is no Message-ID conflict resolution, meaning
10 # no NNTP support for now.
11 #
12 # v2 has a 1:1 mapping of index:inbox or msgmap for NNTP support.
13 # This is intended to be an M:N index:inbox mapping, but it'll likely
14 # be 1:N in common practice (M==1)
15
16 package PublicInbox::ExtSearchIdx;
17 use strict;
18 use v5.10.1;
19 use parent qw(PublicInbox::ExtSearch PublicInbox::Lock);
20 use Carp qw(croak carp);
21 use Sys::Hostname qw(hostname);
22 use POSIX qw(strftime);
23 use File::Glob qw(bsd_glob GLOB_NOSORT);
24 use PublicInbox::MultiGit;
25 use PublicInbox::Search;
26 use PublicInbox::SearchIdx qw(prepare_stack is_ancestor is_bad_blob);
27 use PublicInbox::OverIdx;
28 use PublicInbox::MiscIdx;
29 use PublicInbox::MID qw(mids);
30 use PublicInbox::V2Writable;
31 use PublicInbox::InboxWritable;
32 use PublicInbox::ContentHash qw(content_hash);
33 use PublicInbox::Eml;
34 use PublicInbox::DS qw(now add_timer);
35 use DBI qw(:sql_types); # SQL_BLOB
36
37 sub new {
38         my (undef, $dir, $opt) = @_;
39         my $l = $opt->{indexlevel} // 'full';
40         $l !~ $PublicInbox::SearchIdx::INDEXLEVELS and
41                 die "invalid indexlevel=$l\n";
42         $l eq 'basic' and die "E: indexlevel=basic not yet supported\n";
43         my $self = bless {
44                 xpfx => "$dir/ei".PublicInbox::Search::SCHEMA_VERSION,
45                 topdir => $dir,
46                 creat => $opt->{creat},
47                 ibx_map => {}, # (newsgroup//inboxdir) => $ibx
48                 ibx_active => [], # by config section order
49                 ibx_known => [], # by config section order
50                 indexlevel => $l,
51                 transact_bytes => 0,
52                 total_bytes => 0,
53                 current_info => '',
54                 parallel => 1,
55                 lock_path => "$dir/ei.lock",
56         }, __PACKAGE__;
57         $self->{shards} = $self->count_shards ||
58                 nproc_shards({ nproc => $opt->{jobs} });
59         my $oidx = PublicInbox::OverIdx->new("$self->{xpfx}/over.sqlite3");
60         $self->{-no_fsync} = $oidx->{-no_fsync} = 1 if !$opt->{fsync};
61         $self->{oidx} = $oidx;
62         $self
63 }
64
65 sub attach_inbox {
66         my ($self, $ibx, $types) = @_;
67         $self->{ibx_map}->{$ibx->eidx_key} //= do {
68                 delete $self->{-ibx_ary_known}; # invalidate cache
69                 delete $self->{-ibx_ary_active}; # invalidate cache
70                 $types //= [ qw(active known) ];
71                 for my $t (@$types) {
72                         push @{$self->{"ibx_$t"}}, $ibx;
73                 }
74                 $ibx;
75         }
76 }
77
78 sub _ibx_attach { # each_inbox callback
79         my ($ibx, $self, $types) = @_;
80         attach_inbox($self, $ibx, $types);
81 }
82
83 sub attach_config {
84         my ($self, $cfg, $ibxs) = @_;
85         $self->{cfg} = $cfg;
86         my $types;
87         if ($ibxs) {
88                 for my $ibx (@$ibxs) {
89                         $self->{ibx_map}->{$ibx->eidx_key} //= do {
90                                 push @{$self->{ibx_active}}, $ibx;
91                                 push @{$self->{ibx_known}}, $ibx;
92                                 $ibx;
93                         }
94                 }
95                 # invalidate cache
96                 delete $self->{-ibx_ary_known};
97                 delete $self->{-ibx_ary_active};
98                 $types = [ 'known' ];
99         }
100         $types //= [ qw(known active) ];
101         $cfg->each_inbox(\&_ibx_attach, $self, $types);
102 }
103
104 sub check_batch_limit ($) {
105         my ($req) = @_;
106         my $self = $req->{self};
107         my $new_smsg = $req->{new_smsg};
108         my $n = $self->{transact_bytes} += $new_smsg->{bytes};
109
110         # set flag for PublicInbox::V2Writable::index_todo:
111         ${$req->{need_checkpoint}} = 1 if $n >= $self->{batch_bytes};
112 }
113
114 sub apply_boost ($$) {
115         my ($req, $smsg) = @_;
116         my $id2pos = $req->{id2pos}; # index in ibx_sorted
117         my $xr3 = $req->{self}->{oidx}->get_xref3($smsg->{num}, 1);
118         @$xr3 = sort {
119                 $id2pos->{$a->[0]} <=> $id2pos->{$b->[0]}
120                                 ||
121                 $a->[1] <=> $b->[1] # break ties with {xnum}
122         } @$xr3;
123         my $new_smsg = $req->{new_smsg};
124         return if $xr3->[0]->[2] ne pack('H*', $new_smsg->{blob}); # loser
125
126         # replace the old smsg with the more boosted one
127         $new_smsg->{num} = $smsg->{num};
128         $new_smsg->populate($req->{eml}, $req);
129         $req->{self}->{oidx}->add_overview($req->{eml}, $new_smsg);
130 }
131
132 sub remove_doc ($$) {
133         my ($self, $docid) = @_;
134         $self->{oidx}->delete_by_num($docid);
135         $self->{oidx}->eidxq_del($docid);
136         $self->idx_shard($docid)->ipc_do('xdb_remove', $docid);
137 }
138
139 sub _unref_doc ($$$$$;$) {
140         my ($sync, $docid, $ibx, $xnum, $oidbin, $eml) = @_;
141         my $smsg;
142         if (ref($docid)) {
143                 $smsg = $docid;
144                 $docid = $smsg->{num};
145         }
146         my $s = 'DELETE FROM xref3 WHERE oidbin = ?';
147         $s .= ' AND ibx_id = ?' if defined($ibx);
148         $s .= ' AND xnum = ?' if defined($xnum);
149         my $del = $sync->{self}->{oidx}->dbh->prepare_cached($s);
150         my $col = 0;
151         $del->bind_param(++$col, $oidbin, SQL_BLOB);
152         $del->bind_param(++$col, $ibx->{-ibx_id}) if $ibx;
153         $del->bind_param(++$col, $xnum) if defined($xnum);
154         $del->execute;
155         my $xr3 = $sync->{self}->{oidx}->get_xref3($docid);
156         if (scalar(@$xr3) == 0) { # all gone
157                 remove_doc($sync->{self}, $docid);
158         } else { # enqueue for reindex of remaining messages
159                 if ($ibx) {
160                         my $ekey = $ibx->{-gc_eidx_key} // $ibx->eidx_key;
161                         my $idx = $sync->{self}->idx_shard($docid);
162                         $idx->ipc_do('remove_eidx_info', $docid, $ekey, $eml);
163                 } # else: we can't remove_eidx_info in reindex-only path
164
165                 # replace invalidated blob ASAP with something which should be
166                 # readable since we may commit the transaction on checkpoint.
167                 # eidxq processing will re-apply boost
168                 $smsg //= $sync->{self}->{oidx}->get_art($docid);
169                 my $hex = unpack('H*', $oidbin);
170                 if ($smsg && $smsg->{blob} eq $hex) {
171                         $xr3->[0] =~ /:([a-f0-9]{40,}+)\z/ or
172                                 die "BUG: xref $xr3->[0] has no OID";
173                         $sync->{self}->{oidx}->update_blob($smsg, $1);
174                 }
175                 # yes, add, we'll need to re-apply boost
176                 $sync->{self}->{oidx}->eidxq_add($docid);
177         }
178         @$xr3
179 }
180
181 sub do_xpost ($$) {
182         my ($req, $smsg) = @_;
183         my $self = $req->{self};
184         my $docid = $smsg->{num};
185         my $oid = $req->{oid};
186         my $xibx = $req->{ibx};
187         my $eml = $req->{eml};
188         if (my $new_smsg = $req->{new_smsg}) { # 'm' on cross-posted message
189                 my $eidx_key = $xibx->eidx_key;
190                 my $xnum = $req->{xnum};
191                 $self->{oidx}->add_xref3($docid, $xnum, $oid, $eidx_key);
192                 my $idx = $self->idx_shard($docid);
193                 $idx->ipc_do('add_eidx_info', $docid, $eidx_key, $eml);
194                 apply_boost($req, $smsg) if $req->{boost_in_use};
195         } else { # 'd' no {xnum}
196                 $self->git->async_wait_all;
197                 $oid = pack('H*', $oid);
198                 _unref_doc($req, $docid, $xibx, undef, $oid, $eml);
199         }
200 }
201
202 # called by V2Writable::sync_prepare
203 sub artnum_max { $_[0]->{oidx}->eidx_max }
204
205 sub index_unseen ($) {
206         my ($req) = @_;
207         my $new_smsg = $req->{new_smsg} or die 'BUG: {new_smsg} unset';
208         my $eml = delete $req->{eml};
209         $new_smsg->populate($eml, $req);
210         my $self = $req->{self};
211         my $docid = $self->{oidx}->adj_counter('eidx_docid', '+');
212         $new_smsg->{num} = $docid;
213         my $idx = $self->idx_shard($docid);
214         $self->{oidx}->add_overview($eml, $new_smsg);
215         my $oid = $new_smsg->{blob};
216         my $ibx = delete $req->{ibx} or die 'BUG: {ibx} unset';
217         $self->{oidx}->add_xref3($docid, $req->{xnum}, $oid, $ibx->eidx_key);
218         $idx->index_eml($eml, $new_smsg, $ibx->eidx_key);
219         check_batch_limit($req);
220 }
221
222 sub do_finalize ($) {
223         my ($req) = @_;
224         if (my $indexed = $req->{indexed}) { # duplicated messages
225                 do_xpost($req, $_) for @$indexed;
226         } elsif (exists $req->{new_smsg}) { # totally unseen messsage
227                 index_unseen($req);
228         } else {
229                 # `d' message was already unindexed in the v1/v2 inboxes,
230                 # so it's too noisy to warn, here.
231         }
232         # cur_cmt may be undef for unindex_oid, set by V2Writable::index_todo
233         if (defined(my $cur_cmt = $req->{cur_cmt})) {
234                 ${$req->{latest_cmt}} = $cur_cmt;
235         }
236 }
237
238 sub do_step ($) { # main iterator for adding messages to the index
239         my ($req) = @_;
240         my $self = $req->{self} // die 'BUG: {self} missing';
241         while (1) {
242                 if (my $next_arg = $req->{next_arg}) {
243                         if (my $smsg = $self->{oidx}->next_by_mid(@$next_arg)) {
244                                 $req->{cur_smsg} = $smsg;
245                                 $self->git->cat_async($smsg->{blob},
246                                                         \&ck_existing, $req);
247                                 return; # ck_existing calls do_step
248                         }
249                         delete $req->{next_arg};
250                 }
251                 die "BUG: {cur_smsg} still set" if $req->{cur_smsg};
252                 my $mid = shift(@{$req->{mids}}) // last;
253                 my ($id, $prev);
254                 $req->{next_arg} = [ $mid, \$id, \$prev ];
255                 # loop again
256         }
257         do_finalize($req);
258 }
259
260 sub _blob_missing ($$) { # called when a known $smsg->{blob} is gone
261         my ($req, $smsg) = @_;
262         # xnum and ibx are unknown, we only call this when an entry from
263         # /ei*/over.sqlite3 is bad, not on entries from xap*/over.sqlite3
264         my $oidbin = pack('H*', $smsg->{blob});
265         $req->{self}->git->async_wait_all;
266         _unref_doc($req, $smsg, undef, undef, $oidbin);
267 }
268
269 sub ck_existing { # git->cat_async callback
270         my ($bref, $oid, $type, $size, $req) = @_;
271         my $smsg = delete $req->{cur_smsg} or die 'BUG: {cur_smsg} missing';
272         if ($type eq 'missing') {
273                 _blob_missing($req, $smsg);
274         } elsif (!is_bad_blob($oid, $type, $size, $smsg->{blob})) {
275                 my $self = $req->{self} // die 'BUG: {self} missing';
276                 local $self->{current_info} = "$self->{current_info} $oid";
277                 my $cur = PublicInbox::Eml->new($bref);
278                 if (content_hash($cur) eq $req->{chash}) {
279                         push @{$req->{indexed}}, $smsg; # for do_xpost
280                 } # else { index_unseen later }
281         }
282         do_step($req);
283 }
284
285 # is the messages visible in the inbox currently being indexed?
286 # return the number if so
287 sub cur_ibx_xnum ($$) {
288         my ($req, $bref) = @_;
289         my $ibx = $req->{ibx} or die 'BUG: current {ibx} missing';
290
291         $req->{eml} = PublicInbox::Eml->new($bref);
292         $req->{chash} = content_hash($req->{eml});
293         $req->{mids} = mids($req->{eml});
294         for my $mid (@{$req->{mids}}) {
295                 my ($id, $prev);
296                 while (my $x = $ibx->over->next_by_mid($mid, \$id, \$prev)) {
297                         return $x->{num} if $x->{blob} eq $req->{oid};
298                 }
299         }
300         undef;
301 }
302
303 sub index_oid { # git->cat_async callback for 'm'
304         my ($bref, $oid, $type, $size, $req) = @_;
305         my $self = $req->{self};
306         local $self->{current_info} = "$self->{current_info} $oid";
307         return if is_bad_blob($oid, $type, $size, $req->{oid});
308         my $new_smsg = $req->{new_smsg} = bless {
309                 blob => $oid,
310         }, 'PublicInbox::Smsg';
311         $new_smsg->set_bytes($$bref, $size);
312         defined($req->{xnum} = cur_ibx_xnum($req, $bref)) or return;
313         ++${$req->{nr}};
314         do_step($req);
315 }
316
317 sub unindex_oid { # git->cat_async callback for 'd'
318         my ($bref, $oid, $type, $size, $req) = @_;
319         my $self = $req->{self};
320         local $self->{current_info} = "$self->{current_info} $oid";
321         return if is_bad_blob($oid, $type, $size, $req->{oid});
322         return if defined(cur_ibx_xnum($req, $bref)); # was re-added
323         do_step($req);
324 }
325
326 # overrides V2Writable::last_commits, called by sync_ranges via sync_prepare
327 sub last_commits {
328         my ($self, $sync) = @_;
329         my $heads = [];
330         my $ekey = $sync->{ibx}->eidx_key;
331         my $uv = $sync->{ibx}->uidvalidity;
332         for my $i (0..$sync->{epoch_max}) {
333                 $heads->[$i] = $self->{oidx}->eidx_meta("lc-v2:$ekey//$uv;$i");
334         }
335         $heads;
336 }
337
338 sub _ibx_index_reject ($) {
339         my ($ibx) = @_;
340         $ibx->mm // return 'unindexed, no msgmap.sqlite3';
341         $ibx->uidvalidity // return 'no UIDVALIDITY';
342         $ibx->over // return 'unindexed, no over.sqlite3';
343         undef;
344 }
345
346 sub _sync_inbox ($$$) {
347         my ($self, $sync, $ibx) = @_;
348         my $ekey = $ibx->eidx_key;
349         if (defined(my $err = _ibx_index_reject($ibx))) {
350                 return "W: skipping $ekey ($err)";
351         }
352         $sync->{ibx} = $ibx;
353         $sync->{nr} = \(my $nr = 0);
354         my $v = $ibx->version;
355         if ($v == 2) {
356                 $sync->{epoch_max} = $ibx->max_git_epoch // return;
357                 sync_prepare($self, $sync); # or return # TODO: once MiscIdx is stable
358         } elsif ($v == 1) {
359                 my $uv = $ibx->uidvalidity;
360                 my $lc = $self->{oidx}->eidx_meta("lc-v1:$ekey//$uv");
361                 my $head = $ibx->mm->last_commit //
362                         return "E: $ibx->{inboxdir} is not indexed";
363                 my $stk = prepare_stack($sync, $lc ? "$lc..$head" : $head);
364                 my $unit = { stack => $stk, git => $ibx->git };
365                 push @{$sync->{todo}}, $unit;
366         } else {
367                 return "E: $ekey unsupported inbox version (v$v)";
368         }
369         for my $unit (@{delete($sync->{todo}) // []}) {
370                 last if $sync->{quit};
371                 index_todo($self, $sync, $unit);
372         }
373         $self->{midx}->index_ibx($ibx) unless $sync->{quit};
374         $ibx->git->cleanup; # done with this inbox, now
375         undef;
376 }
377
378 sub eidx_gc_scan_inboxes ($$) {
379         my ($self, $sync) = @_;
380         my ($x3_doc, $ibx_ck);
381 restart:
382         $x3_doc = $self->{oidx}->dbh->prepare(<<EOM);
383 SELECT docid,xnum,oidbin FROM xref3 WHERE ibx_id = ?
384 EOM
385         $ibx_ck = $self->{oidx}->dbh->prepare(<<EOM);
386 SELECT ibx_id,eidx_key FROM inboxes
387 EOM
388         $ibx_ck->execute;
389         while (my ($ibx_id, $eidx_key) = $ibx_ck->fetchrow_array) {
390                 next if $self->{ibx_map}->{$eidx_key};
391                 $self->{midx}->remove_eidx_key($eidx_key);
392                 warn "I: deleting messages for $eidx_key...\n";
393                 $x3_doc->execute($ibx_id);
394                 my $ibx = { -ibx_id => $ibx_id, -gc_eidx_key => $eidx_key };
395                 while (my ($docid, $xnum, $oid) = $x3_doc->fetchrow_array) {
396                         my $r = _unref_doc($sync, $docid, $ibx, $xnum, $oid);
397                         $oid = unpack('H*', $oid);
398                         $r = $r ? 'unref' : 'remove';
399                         warn "I: $r #$docid $eidx_key $oid\n";
400                         if (checkpoint_due($sync)) {
401                                 $x3_doc = $ibx_ck = undef;
402                                 reindex_checkpoint($self, $sync);
403                                 goto restart;
404                         }
405                 }
406                 $self->{oidx}->dbh->do(<<'', undef, $ibx_id);
407 DELETE FROM inboxes WHERE ibx_id = ?
408
409                 # drop last_commit info
410                 my $pat = $eidx_key;
411                 $pat =~ s/([_%\\])/\\$1/g;
412                 $self->{oidx}->dbh->do('PRAGMA case_sensitive_like = ON');
413                 my $lc_i = $self->{oidx}->dbh->prepare(<<'');
414 SELECT key FROM eidx_meta WHERE key LIKE ? ESCAPE ?
415
416                 $lc_i->execute("lc-%:$pat//%", '\\');
417                 while (my ($key) = $lc_i->fetchrow_array) {
418                         next if $key !~ m!\Alc-v[1-9]+:\Q$eidx_key\E//!;
419                         warn "I: removing $key\n";
420                         $self->{oidx}->dbh->do(<<'', undef, $key);
421 DELETE FROM eidx_meta WHERE key = ?
422
423                 }
424                 warn "I: $eidx_key removed\n";
425         }
426 }
427
428 sub eidx_gc_scan_shards ($$) { # TODO: use for lei/store
429         my ($self, $sync) = @_;
430         my $nr = $self->{oidx}->dbh->do(<<'');
431 DELETE FROM xref3 WHERE docid NOT IN (SELECT num FROM over)
432
433         warn "I: eliminated $nr stale xref3 entries\n" if $nr != 0;
434         reindex_checkpoint($self, $sync) if checkpoint_due($sync);
435
436         # fixup from old bugs:
437         $nr = $self->{oidx}->dbh->do(<<'');
438 DELETE FROM over WHERE num > 0 AND num NOT IN (SELECT docid FROM xref3)
439
440         warn "I: eliminated $nr stale over entries\n" if $nr != 0;
441         reindex_checkpoint($self, $sync) if checkpoint_due($sync);
442
443         $nr = $self->{oidx}->dbh->do(<<'');
444 DELETE FROM eidxq WHERE docid NOT IN (SELECT num FROM over)
445
446         warn "I: eliminated $nr stale reindex queue entries\n" if $nr != 0;
447         reindex_checkpoint($self, $sync) if checkpoint_due($sync);
448
449         my ($cur) = $self->{oidx}->dbh->selectrow_array(<<EOM);
450 SELECT MIN(num) FROM over WHERE num > 0
451 EOM
452         $cur // return; # empty
453         my ($r, $n, %active_shards);
454         $nr = 0;
455         while (1) {
456                 $r = $self->{oidx}->dbh->selectcol_arrayref(<<"", undef, $cur);
457 SELECT num FROM over WHERE num >= ? ORDER BY num ASC LIMIT 10000
458
459                 last unless scalar(@$r);
460                 while (defined($n = shift @$r)) {
461                         for my $i ($cur..($n - 1)) {
462                                 my $idx = idx_shard($self, $i);
463                                 $idx->ipc_do('xdb_remove_quiet', $i);
464                                 $active_shards{$idx} = $idx;
465                         }
466                         $cur = $n + 1;
467                 }
468                 if (checkpoint_due($sync)) {
469                         for my $idx (values %active_shards) {
470                                 $nr += $idx->ipc_do('nr_quiet_rm')
471                         }
472                         %active_shards = ();
473                         reindex_checkpoint($self, $sync);
474                 }
475         }
476         warn "I: eliminated $nr stale Xapian documents\n" if $nr != 0;
477 }
478
479 sub eidx_gc {
480         my ($self, $opt) = @_;
481         $self->{cfg} or die "E: GC requires ->attach_config\n";
482         $opt->{-idx_gc} = 1;
483         my $sync = {
484                 need_checkpoint => \(my $need_checkpoint = 0),
485                 check_intvl => 10,
486                 next_check => now() + 10,
487                 checkpoint_unlocks => 1,
488                 -opt => $opt,
489                 self => $self,
490         };
491         $self->idx_init($opt); # acquire lock via V2Writable::_idx_init
492         eidx_gc_scan_inboxes($self, $sync);
493         eidx_gc_scan_shards($self, $sync);
494         done($self);
495 }
496
497 sub _ibx_for ($$$) {
498         my ($self, $sync, $smsg) = @_;
499         my $ibx_id = delete($smsg->{ibx_id}) // die '{ibx_id} unset';
500         my $pos = $sync->{id2pos}->{$ibx_id} // die "$ibx_id no pos";
501         $self->{-ibx_ary_known}->[$pos] //
502                 die "BUG: ibx for $smsg->{blob} not mapped"
503 }
504
505 sub _fd_constrained ($) {
506         my ($self) = @_;
507         $self->{-fd_constrained} //= do {
508                 my $soft;
509                 if (eval { require BSD::Resource; 1 }) {
510                         my $NOFILE = BSD::Resource::RLIMIT_NOFILE();
511                         ($soft, undef) = BSD::Resource::getrlimit($NOFILE);
512                 } else {
513                         chomp($soft = `sh -c 'ulimit -n'`);
514                 }
515                 if (defined($soft)) {
516                         # $want is an estimate
517                         my $want = scalar(@{$self->{ibx_active}}) + 64;
518                         my $ret = $want > $soft;
519                         if ($ret) {
520                                 warn <<EOF;
521 RLIMIT_NOFILE=$soft insufficient (want: $want), will close DB handles early
522 EOF
523                         }
524                         $ret;
525                 } else {
526                         warn "Unable to determine RLIMIT_NOFILE: $@\n";
527                         1;
528                 }
529         };
530 }
531
532 sub _reindex_finalize ($$$) {
533         my ($req, $smsg, $eml) = @_;
534         my $sync = $req->{sync};
535         my $self = $sync->{self};
536         my $by_chash = delete $req->{by_chash} or die 'BUG: no {by_chash}';
537         my $nr = scalar(keys(%$by_chash)) or die 'BUG: no content hashes';
538         my $orig_smsg = $req->{orig_smsg} // die 'BUG: no {orig_smsg}';
539         my $docid = $smsg->{num} = $orig_smsg->{num};
540         $self->{oidx}->add_overview($eml, $smsg); # may rethread
541         check_batch_limit({ %$sync, new_smsg => $smsg });
542         my $chash0 = $smsg->{chash} // die "BUG: $smsg->{blob} no {chash}";
543         my $stable = delete($by_chash->{$chash0}) //
544                                 die "BUG: $smsg->{blob} chash missing";
545         my $idx = $self->idx_shard($docid);
546         my $top_smsg = pop @$stable;
547         $top_smsg == $smsg or die 'BUG: top_smsg != smsg';
548         my $ibx = _ibx_for($self, $sync, $smsg);
549         $idx->index_eml($eml, $smsg, $ibx->eidx_key);
550         for my $x (reverse @$stable) {
551                 $ibx = _ibx_for($self, $sync, $x);
552                 my $hdr = delete $x->{hdr} // die 'BUG: no {hdr}';
553                 $idx->ipc_do('add_eidx_info', $docid, $ibx->eidx_key, $hdr);
554         }
555         return if $nr == 1; # likely, all good
556
557         $self->git->async_wait_all;
558         warn "W: #$docid split into $nr due to deduplication change\n";
559         my @todo;
560         for my $ary (values %$by_chash) {
561                 for my $x (reverse @$ary) {
562                         warn "removing #$docid xref3 $x->{blob}\n";
563                         my $bin = pack('H*', $x->{blob});
564                         my $n = _unref_doc($sync, $docid, undef, undef, $bin);
565                         die "BUG: $x->{blob} invalidated #$docid" if $n == 0;
566                 }
567                 my $x = pop(@$ary) // die "BUG: #$docid {by_chash} empty";
568                 $x->{num} = delete($x->{xnum}) // die '{xnum} unset';
569                 $ibx = _ibx_for($self, $sync, $x);
570                 if (my $over = $ibx->over) {
571                         my $e = $over->get_art($x->{num});
572                         $e->{blob} eq $x->{blob} or die <<EOF;
573 $x->{blob} != $e->{blob} (${\$ibx->eidx_key}:$e->{num});
574 EOF
575                         push @todo, $ibx, $e;
576                         $over->dbh_close if _fd_constrained($self);
577                 } else {
578                         die "$ibx->{inboxdir}: over.sqlite3 unusable: $!\n";
579                 }
580         }
581         undef $by_chash;
582         while (my ($ibx, $e) = splice(@todo, 0, 2)) {
583                 reindex_unseen($self, $sync, $ibx, $e);
584         }
585 }
586
587 sub _reindex_oid { # git->cat_async callback
588         my ($bref, $oid, $type, $size, $req) = @_;
589         my $sync = $req->{sync};
590         my $self = $sync->{self};
591         my $orig_smsg = $req->{orig_smsg} // die 'BUG: no {orig_smsg}';
592         my $expect_oid = $req->{xr3r}->[$req->{ix}]->[2];
593         my $docid = $orig_smsg->{num};
594         if (is_bad_blob($oid, $type, $size, $expect_oid)) {
595                 my $oidbin = pack('H*', $expect_oid);
596                 my $remain = _unref_doc($sync, $docid, undef, undef, $oidbin);
597                 if ($remain == 0) {
598                         warn "W: #$docid gone or corrupted\n";
599                 } elsif (my $next_oid = $req->{xr3r}->[++$req->{ix}]->[2]) {
600                         $self->git->cat_async($next_oid, \&_reindex_oid, $req);
601                 } else {
602                         warn "BUG: #$docid gone (UNEXPECTED)\n";
603                 }
604                 return;
605         }
606         my $ci = $self->{current_info};
607         local $self->{current_info} = "$ci #$docid $oid";
608         my $re_smsg = bless { blob => $oid }, 'PublicInbox::Smsg';
609         $re_smsg->set_bytes($$bref, $size);
610         my $eml = PublicInbox::Eml->new($bref);
611         $re_smsg->populate($eml, { autime => $orig_smsg->{ds},
612                                 cotime => $orig_smsg->{ts} });
613         my $chash = content_hash($eml);
614         $re_smsg->{chash} = $chash;
615         $re_smsg->{xnum} = $req->{xr3r}->[$req->{ix}]->[1];
616         $re_smsg->{ibx_id} = $req->{xr3r}->[$req->{ix}]->[0];
617         $re_smsg->{hdr} = $eml->header_obj;
618         push @{$req->{by_chash}->{$chash}}, $re_smsg;
619         if (my $next_oid = $req->{xr3r}->[++$req->{ix}]->[2]) {
620                 $self->git->cat_async($next_oid, \&_reindex_oid, $req);
621         } else { # last $re_smsg is the highest priority xref3
622                 local $self->{current_info} = "$ci #$docid";
623                 _reindex_finalize($req, $re_smsg, $eml);
624         }
625 }
626
627 sub _reindex_smsg ($$$) {
628         my ($self, $sync, $smsg) = @_;
629         my $docid = $smsg->{num};
630         my $xr3 = $self->{oidx}->get_xref3($docid, 1);
631         if (scalar(@$xr3) == 0) { # _reindex_check_stale should've covered this
632                 warn <<"";
633 BUG? #$docid $smsg->{blob} is not referenced by inboxes during reindex
634
635                 remove_doc($self, $docid);
636                 return;
637         }
638
639         # we sort {xr3r} in the reverse order of ibx_sorted so we can
640         # hit the common case in _reindex_finalize without rereading
641         # from git (or holding multiple messages in memory).
642         my $id2pos = $sync->{id2pos}; # index in ibx_sorted
643         @$xr3 = sort {
644                 $id2pos->{$b->[0]} <=> $id2pos->{$a->[0]}
645                                 ||
646                 $b->[1] <=> $a->[1] # break ties with {xnum}
647         } @$xr3;
648         @$xr3 = map { [ $_->[0], $_->[1], unpack('H*', $_->[2]) ] } @$xr3;
649         my $req = { orig_smsg => $smsg, sync => $sync, xr3r => $xr3, ix => 0 };
650         $self->git->cat_async($xr3->[$req->{ix}]->[2], \&_reindex_oid, $req);
651 }
652
653 sub checkpoint_due ($) {
654         my ($sync) = @_;
655         ${$sync->{need_checkpoint}} || (now() > $sync->{next_check});
656 }
657
658 sub host_ident () {
659         # I've copied FS images and only changed the hostname before,
660         # so prepend hostname.  Use `state' since these a BOFH can change
661         # these while this process is running and we always want to be
662         # able to release locks taken by this process.
663         state $retval = hostname . '-' . do {
664                 my $m; # machine-id(5) is systemd
665                 if (open(my $fh, '<', '/etc/machine-id')) { $m = <$fh> }
666                 # (g)hostid(1) is in GNU coreutils, kern.hostid is most BSDs
667                 chomp($m ||= `{ sysctl -n kern.hostid ||
668                                 hostid || ghostid; } 2>/dev/null`
669                         || "no-machine-id-or-hostid-on-$^O");
670                 $m;
671         };
672 }
673
674 sub eidxq_release {
675         my ($self) = @_;
676         my $expect = delete($self->{-eidxq_locked}) or return;
677         my ($owner_pid, undef) = split(/-/, $expect);
678         return if $owner_pid != $$; # shards may fork
679         my $oidx = $self->{oidx};
680         $oidx->begin_lazy;
681         my $cur = $oidx->eidx_meta('eidxq_lock') // '';
682         if ($cur eq $expect) {
683                 $oidx->eidx_meta('eidxq_lock', '');
684                 return 1;
685         } elsif ($cur ne '') {
686                 warn "E: eidxq_lock($expect) stolen by $cur\n";
687         } else {
688                 warn "E: eidxq_lock($expect) released by another process\n";
689         }
690         undef;
691 }
692
693 sub DESTROY {
694         my ($self) = @_;
695         eidxq_release($self) and $self->{oidx}->commit_lazy;
696 }
697
698 sub _eidxq_take ($) {
699         my ($self) = @_;
700         my $val = "$$-${\time}-$>-".host_ident;
701         $self->{oidx}->eidx_meta('eidxq_lock', $val);
702         $self->{-eidxq_locked} = $val;
703 }
704
705 sub eidxq_lock_acquire ($) {
706         my ($self) = @_;
707         my $oidx = $self->{oidx};
708         $oidx->begin_lazy;
709         my $cur = $oidx->eidx_meta('eidxq_lock') || return _eidxq_take($self);
710         if (my $locked = $self->{-eidxq_locked}) { # be lazy
711                 return $locked if $locked eq $cur;
712         }
713         my ($pid, $time, $euid, $ident) = split(/-/, $cur, 4);
714         my $t = strftime('%Y-%m-%d %k:%M:%S', gmtime($time));
715         if ($euid == $> && $ident eq host_ident) {
716                 if (kill(0, $pid)) {
717                         warn <<EOM; return;
718 I: PID:$pid (re)indexing Xapian since $t, it will continue our work
719 EOM
720                 }
721                 if ($!{ESRCH}) {
722                         warn "I: eidxq_lock is stale ($cur), clobbering\n";
723                         return _eidxq_take($self);
724                 }
725                 warn "E: kill(0, $pid) failed: $!\n"; # fall-through:
726         }
727         my $fn = $oidx->dbh->sqlite_db_filename;
728         warn <<EOF;
729 W: PID:$pid, UID:$euid on $ident is indexing Xapian since $t
730 W: If this is unexpected, delete `eidxq_lock' from the `eidx_meta' table:
731 W:      sqlite3 $fn 'DELETE FROM eidx_meta WHERE key = "eidxq_lock"'
732 EOF
733         undef;
734 }
735
736 sub ibx_sorted ($$) {
737         my ($self, $type) = @_;
738         $self->{"-ibx_ary_$type"} //= do {
739                 # highest boost first, stable for config-ordering tiebreaker
740                 use sort 'stable';
741                 [ sort {
742                         ($b->{boost} // 0) <=> ($a->{boost} // 0)
743                   } @{$self->{'ibx_'.$type} // die "BUG: $type unknown"} ];
744         }
745 }
746
747 sub prep_id2pos ($) {
748         my ($self) = @_;
749         my %id2pos;
750         my $pos = 0;
751         $id2pos{$_->{-ibx_id}} = $pos++ for (@{ibx_sorted($self, 'known')});
752         \%id2pos;
753 }
754
755 sub eidxq_process ($$) { # for reindexing
756         my ($self, $sync) = @_;
757         return unless $self->{cfg};
758
759         return unless eidxq_lock_acquire($self);
760         my $dbh = $self->{oidx}->dbh;
761         my $tot = $dbh->selectrow_array('SELECT COUNT(*) FROM eidxq') or return;
762         ${$sync->{nr}} = 0;
763         local $sync->{-regen_fmt} = "%u/$tot\n";
764         my $pr = $sync->{-opt}->{-progress};
765         if ($pr) {
766                 my $min = $dbh->selectrow_array('SELECT MIN(docid) FROM eidxq');
767                 my $max = $dbh->selectrow_array('SELECT MAX(docid) FROM eidxq');
768                 $pr->("Xapian indexing $min..$max (total=$tot)\n");
769         }
770         $sync->{id2pos} //= prep_id2pos($self);
771         my ($del, $iter);
772 restart:
773         $del = $dbh->prepare('DELETE FROM eidxq WHERE docid = ?');
774         $iter = $dbh->prepare('SELECT docid FROM eidxq ORDER BY docid ASC');
775         $iter->execute;
776         while (defined(my $docid = $iter->fetchrow_array)) {
777                 last if $sync->{quit};
778                 if (my $smsg = $self->{oidx}->get_art($docid)) {
779                         _reindex_smsg($self, $sync, $smsg);
780                 } else {
781                         warn "E: #$docid does not exist in over\n";
782                 }
783                 $del->execute($docid);
784                 ++${$sync->{nr}};
785
786                 if (checkpoint_due($sync)) {
787                         $dbh = $del = $iter = undef;
788                         reindex_checkpoint($self, $sync); # release lock
789                         $dbh = $self->{oidx}->dbh;
790                         goto restart;
791                 }
792         }
793         $self->git->async_wait_all;
794         $pr->("reindexed ${$sync->{nr}}/$tot\n") if $pr;
795 }
796
797 sub _reindex_unseen { # git->cat_async callback
798         my ($bref, $oid, $type, $size, $req) = @_;
799         return if is_bad_blob($oid, $type, $size, $req->{oid});
800         my $self = $req->{self} // die 'BUG: {self} unset';
801         local $self->{current_info} = "$self->{current_info} $oid";
802         my $new_smsg = bless { blob => $oid, }, 'PublicInbox::Smsg';
803         $new_smsg->set_bytes($$bref, $size);
804         my $eml = $req->{eml} = PublicInbox::Eml->new($bref);
805         $req->{new_smsg} = $new_smsg;
806         $req->{chash} = content_hash($eml);
807         $req->{mids} = mids($eml); # do_step iterates through this
808         do_step($req); # enter the normal indexing flow
809 }
810
811 # --reindex may catch totally unseen messages, this handles them
812 sub reindex_unseen ($$$$) {
813         my ($self, $sync, $ibx, $xsmsg) = @_;
814         my $req = {
815                 %$sync, # has {self}
816                 autime => $xsmsg->{ds},
817                 cotime => $xsmsg->{ts},
818                 oid => $xsmsg->{blob},
819                 ibx => $ibx,
820                 xnum => $xsmsg->{num},
821                 # {mids} and {chash} will be filled in at _reindex_unseen
822         };
823         warn "I: reindex_unseen ${\$ibx->eidx_key}:$req->{xnum}:$req->{oid}\n";
824         $self->git->cat_async($xsmsg->{blob}, \&_reindex_unseen, $req);
825 }
826
827 sub _unref_stale_range ($$$) {
828         my ($sync, $ibx, $lt_or_gt) = @_;
829         my $r;
830         my $lim = 10000;
831         do {
832                 $r = $sync->{self}->{oidx}->dbh->selectall_arrayref(
833                         <<EOS, undef, $ibx->{-ibx_id});
834 SELECT docid,xnum,oidbin FROM xref3
835 WHERE ibx_id = ? AND xnum $lt_or_gt LIMIT $lim
836 EOS
837                 return if $sync->{quit};
838                 for (@$r) { # hopefully rare, not worth optimizing:
839                         my ($docid, $xnum, $oidbin) = @$_;
840                         my $hex = unpack('H*', $oidbin);
841                         warn("# $xnum:$hex (#$docid): stale\n");
842                         _unref_doc($sync, $docid, $ibx, $xnum, $oidbin);
843                 }
844         } while (scalar(@$r) == $lim);
845         1;
846 }
847
848 sub _reindex_check_ibx ($$$) {
849         my ($self, $sync, $ibx) = @_;
850         my $ibx_id = $ibx->{-ibx_id};
851         my $slice = 10000;
852         my $opt = { limit => $slice };
853         my ($beg, $end) = (1, $slice);
854         my $err = sync_inbox($self, $sync, $ibx) and return;
855         my $max = $ibx->over->max;
856         $end = $max if $end > $max;
857
858         # first, check if we missed any messages in target $ibx
859         my $msgs;
860         my $pr = $sync->{-opt}->{-progress};
861         my $ekey = $ibx->eidx_key;
862         local $sync->{-regen_fmt} = "$ekey checking %u/$max\n";
863         ${$sync->{nr}} = 0;
864         my $fast = $sync->{-opt}->{fast};
865         my $dsu; # _unref_stale_range (< $lo) called
866         my ($lo, $hi);
867         while (scalar(@{$msgs = $ibx->over->query_xover($beg, $end, $opt)})) {
868                 ${$sync->{nr}} = $beg;
869                 $beg = $msgs->[-1]->{num} + 1;
870                 $end = $beg + $slice;
871                 $end = $max if $end > $max;
872                 if (checkpoint_due($sync)) {
873                         reindex_checkpoint($self, $sync); # release lock
874                 }
875                 ($lo, $hi) = ($msgs->[0]->{num}, $msgs->[-1]->{num});
876                 $dsu //= _unref_stale_range($sync, $ibx, "< $lo");
877                 my $x3a = $self->{oidx}->dbh->selectall_arrayref(
878                         <<"", undef, $ibx_id, $lo, $hi);
879 SELECT xnum,oidbin,docid FROM xref3 WHERE
880 ibx_id = ? AND xnum >= ? AND xnum <= ?
881
882                 my %x3m;
883                 for (@$x3a) {
884                         my $k = pack('J', $_->[0]) . $_->[1];
885                         push @{$x3m{$k}}, $_->[2];
886                 }
887                 undef $x3a;
888                 for my $xsmsg (@$msgs) {
889                         my $k = pack('JH*', $xsmsg->{num}, $xsmsg->{blob});
890                         my $docids = delete($x3m{$k});
891                         if (!defined($docids)) {
892                                 reindex_unseen($self, $sync, $ibx, $xsmsg);
893                         } elsif (!$fast) {
894                                 for my $num (@$docids) {
895                                         $self->{oidx}->eidxq_add($num);
896                                 }
897                                 return if $sync->{quit};
898                         }
899                 }
900                 return if $sync->{quit};
901                 next unless scalar keys %x3m;
902                 $self->git->async_wait_all; # wait for reindex_unseen
903
904                 # eliminate stale/mismatched entries
905                 my %mismatch = map { $_->{num} => $_->{blob} } @$msgs;
906                 while (my ($k, $docids) = each %x3m) {
907                         my ($xnum, $hex) = unpack('JH*', $k);
908                         my $bin = pack('H*', $hex);
909                         my $exp = $mismatch{$xnum};
910                         my $m = defined($exp) ? "mismatch (!= $exp)" : 'stale';
911                         warn("# $xnum:$hex (#@$docids): $m\n");
912                         for my $i (@$docids) {
913                                 _unref_doc($sync, $i, $ibx, $xnum, $bin);
914                         }
915                 }
916         }
917         _unref_stale_range($sync, $ibx, "> $hi") if defined($hi);
918 }
919
920 sub _reindex_inbox ($$$) {
921         my ($self, $sync, $ibx) = @_;
922         my $ekey = $ibx->eidx_key;
923         local $self->{current_info} = $ekey;
924         if (defined(my $err = _ibx_index_reject($ibx))) {
925                 warn "W: cannot reindex $ekey ($err)\n";
926         } else {
927                 _reindex_check_ibx($self, $sync, $ibx);
928         }
929         delete @$ibx{qw(over mm search git)}; # won't need these for a bit
930 }
931
932 sub eidx_reindex {
933         my ($self, $sync) = @_;
934         return unless $self->{cfg};
935
936         # acquire eidxq_lock early because full reindex takes forever
937         # and incremental -extindex processes can run during our checkpoints
938         if (!eidxq_lock_acquire($self)) {
939                 warn "E: aborting --reindex\n";
940                 return;
941         }
942         for my $ibx (@{ibx_sorted($self, 'active')}) {
943                 _reindex_inbox($self, $sync, $ibx);
944                 last if $sync->{quit};
945         }
946         $self->git->async_wait_all; # ensure eidxq gets filled completely
947         eidxq_process($self, $sync) unless $sync->{quit};
948 }
949
950 sub sync_inbox {
951         my ($self, $sync, $ibx) = @_;
952         my $err = _sync_inbox($self, $sync, $ibx);
953         delete @$ibx{qw(mm over)};
954         warn $err, "\n" if defined($err);
955         $err;
956 }
957
958 sub dd_smsg { # git->cat_async callback
959         my ($bref, $oid, $type, $size, $dd) = @_;
960         my $smsg = $dd->{smsg} // die 'BUG: dd->{smsg} missing';
961         my $self = $dd->{self} // die 'BUG: {self} missing';
962         my $per_mid = $dd->{per_mid} // die 'BUG: {per_mid} missing';
963         if ($type eq 'missing') {
964                 _blob_missing($dd, $smsg);
965         } elsif (!is_bad_blob($oid, $type, $size, $smsg->{blob})) {
966                 local $self->{current_info} = "$self->{current_info} $oid";
967                 my $chash = content_hash(PublicInbox::Eml->new($bref));
968                 push(@{$per_mid->{dd_chash}->{$chash}}, $smsg);
969         }
970         return if $per_mid->{last_smsg} != $smsg;
971         while (my ($chash, $ary) = each %{$per_mid->{dd_chash}}) {
972                 my $keep = shift @$ary;
973                 next if !scalar(@$ary);
974                 $per_mid->{sync}->{dedupe_cull} += scalar(@$ary);
975                 print STDERR
976                         "# <$keep->{mid}> keeping #$keep->{num}, dropping ",
977                         join(', ', map { "#$_->{num}" } @$ary),"\n";
978                 next if $per_mid->{sync}->{-opt}->{'dry-run'};
979                 my $oidx = $self->{oidx};
980                 for my $smsg (@$ary) {
981                         my $gone = $smsg->{num};
982                         $oidx->merge_xref3($keep->{num}, $gone, $smsg->{blob});
983                         remove_doc($self, $gone);
984                 }
985         }
986 }
987
988 sub eidx_dedupe ($$$) {
989         my ($self, $sync, $msgids) = @_;
990         $sync->{dedupe_cull} = 0;
991         my $candidates = 0;
992         my $nr_mid = 0;
993         return unless eidxq_lock_acquire($self);
994         my ($iter, $cur_mid);
995         my $min_id = 0;
996         my $idx = 0;
997         my ($max_id) = $self->{oidx}->dbh->selectrow_array(<<EOS);
998 SELECT MAX(id) FROM msgid
999 EOS
1000         local $sync->{-regen_fmt} = "dedupe %u/$max_id\n";
1001
1002         # note: we could write this query more intelligently,
1003         # but that causes lock contention with read-only processes
1004 dedupe_restart:
1005         $cur_mid = $msgids->[$idx];
1006         if ($cur_mid eq '') { # all Message-IDs
1007                 $iter = $self->{oidx}->dbh->prepare(<<EOS);
1008 SELECT mid,id FROM msgid WHERE id > ? ORDER BY id ASC
1009 EOS
1010                 $iter->execute($min_id);
1011         } else {
1012                 $iter = $self->{oidx}->dbh->prepare(<<EOS);
1013 SELECT mid,id FROM msgid WHERE mid = ? AND id > ? ORDER BY id ASC
1014 EOS
1015                 $iter->execute($cur_mid, $min_id);
1016         }
1017         while (my ($mid, $id) = $iter->fetchrow_array) {
1018                 last if $sync->{quit};
1019                 $self->{current_info} = "dedupe $mid";
1020                 ${$sync->{nr}} = $min_id = $id;
1021                 my ($prv, @smsg);
1022                 while (my $x = $self->{oidx}->next_by_mid($mid, \$id, \$prv)) {
1023                         push @smsg, $x;
1024                 }
1025                 next if scalar(@smsg) < 2;
1026                 my $per_mid = {
1027                         dd_chash => {}, # chash => [ary of smsgs]
1028                         last_smsg => $smsg[-1],
1029                         sync => $sync
1030                 };
1031                 $nr_mid++;
1032                 $candidates += scalar(@smsg) - 1;
1033                 for my $smsg (@smsg) {
1034                         my $dd = {
1035                                 per_mid => $per_mid,
1036                                 smsg => $smsg,
1037                                 self => $self,
1038                         };
1039                         $self->git->cat_async($smsg->{blob}, \&dd_smsg, $dd);
1040                 }
1041                 # need to wait on every single one @smsg contents can get
1042                 # invalidated inside dd_smsg for messages with multiple
1043                 # Message-IDs.
1044                 $self->git->async_wait_all;
1045
1046                 if (checkpoint_due($sync)) {
1047                         undef $iter;
1048                         reindex_checkpoint($self, $sync);
1049                         goto dedupe_restart;
1050                 }
1051         }
1052         goto dedupe_restart if defined($msgids->[++$idx]);
1053
1054         my $n = delete $sync->{dedupe_cull};
1055         if (my $pr = $sync->{-opt}->{-progress}) {
1056                 $pr->("culled $n/$candidates candidates ($nr_mid msgids)\n");
1057         }
1058         ${$sync->{nr}} = 0;
1059 }
1060
1061 sub eidx_sync { # main entry point
1062         my ($self, $opt) = @_;
1063
1064         my $warn_cb = $SIG{__WARN__} || \&CORE::warn;
1065         local $self->{current_info} = '';
1066         local $SIG{__WARN__} = sub {
1067                 return if PublicInbox::Eml::warn_ignore(@_);
1068                 $warn_cb->($self->{current_info}, ': ', @_);
1069         };
1070         $self->idx_init($opt); # acquire lock via V2Writable::_idx_init
1071         $self->{oidx}->rethread_prepare($opt);
1072         my $sync = {
1073                 need_checkpoint => \(my $need_checkpoint = 0),
1074                 check_intvl => 10,
1075                 next_check => now() + 10,
1076                 -opt => $opt,
1077                 # DO NOT SET {reindex} here, it's incompatible with reused
1078                 # V2Writable code, reindex is totally different here
1079                 # compared to v1/v2 inboxes because we have multiple histories
1080                 self => $self,
1081                 -regen_fmt => "%u/?\n",
1082         };
1083         local $SIG{USR1} = sub { $need_checkpoint = 1 };
1084         my $quit = PublicInbox::SearchIdx::quit_cb($sync);
1085         local $SIG{QUIT} = $quit;
1086         local $SIG{INT} = $quit;
1087         local $SIG{TERM} = $quit;
1088         for my $ibx (@{ibx_sorted($self, 'known')}) {
1089                 $ibx->{-ibx_id} //= $self->{oidx}->ibx_id($ibx->eidx_key);
1090         }
1091
1092         if (scalar(grep { defined($_->{boost}) } @{$self->{ibx_known}})) {
1093                 $sync->{id2pos} //= prep_id2pos($self);
1094                 $sync->{boost_in_use} = 1;
1095         }
1096
1097         if (my $msgids = delete($opt->{dedupe})) {
1098                 local $sync->{checkpoint_unlocks} = 1;
1099                 eidx_dedupe($self, $sync, $msgids);
1100         }
1101         if (delete($opt->{reindex})) {
1102                 local $sync->{checkpoint_unlocks} = 1;
1103                 eidx_reindex($self, $sync);
1104         }
1105
1106         # don't use $_ here, it'll get clobbered by reindex_checkpoint
1107         if ($opt->{scan} // 1) {
1108                 for my $ibx (@{ibx_sorted($self, 'active')}) {
1109                         last if $sync->{quit};
1110                         sync_inbox($self, $sync, $ibx);
1111                 }
1112         }
1113         $self->{oidx}->rethread_done($opt) unless $sync->{quit};
1114         eidxq_process($self, $sync) unless $sync->{quit};
1115
1116         eidxq_release($self);
1117         done($self);
1118         $sync; # for eidx_watch
1119 }
1120
1121 sub update_last_commit { # overrides V2Writable
1122         my ($self, $sync, $stk) = @_;
1123         my $unit = $sync->{unit} // return;
1124         my $latest_cmt = $stk ? $stk->{latest_cmt} : ${$sync->{latest_cmt}};
1125         defined($latest_cmt) or return;
1126         my $ibx = $sync->{ibx} or die 'BUG: {ibx} missing';
1127         my $ekey = $ibx->eidx_key;
1128         my $uv = $ibx->uidvalidity;
1129         my $epoch = $unit->{epoch};
1130         my $meta_key;
1131         my $v = $ibx->version;
1132         if ($v == 2) {
1133                 die 'No {epoch} for v2 unit' unless defined $epoch;
1134                 $meta_key = "lc-v2:$ekey//$uv;$epoch";
1135         } elsif ($v == 1) {
1136                 die 'Unexpected {epoch} for v1 unit' if defined $epoch;
1137                 $meta_key = "lc-v1:$ekey//$uv";
1138         } else {
1139                 die "Unsupported inbox version: $v";
1140         }
1141         my $last = $self->{oidx}->eidx_meta($meta_key);
1142         if (defined $last && is_ancestor($self->git, $last, $latest_cmt)) {
1143                 my @cmd = (qw(rev-list --count), "$last..$latest_cmt");
1144                 chomp(my $n = $unit->{git}->qx(@cmd));
1145                 return if $n ne '' && $n == 0;
1146         }
1147         $self->{oidx}->eidx_meta($meta_key, $latest_cmt);
1148 }
1149
1150 sub _idx_init { # with_umask callback
1151         my ($self, $opt) = @_;
1152         PublicInbox::V2Writable::_idx_init($self, $opt); # acquires ei.lock
1153         $self->{midx} = PublicInbox::MiscIdx->new($self);
1154 }
1155
1156 sub symlink_packs ($$) {
1157         my ($ibx, $pd) = @_;
1158         my $ret = 0;
1159         my $glob = "$ibx->{inboxdir}/git/*.git/objects/pack/*.idx";
1160         for my $idx (bsd_glob($glob, GLOB_NOSORT)) {
1161                 my $src = substr($idx, 0, -length('.idx'));
1162                 my $dst = $pd . substr($src, rindex($src, '/'));
1163                 if (-f "$src.pack" and
1164                                 symlink("$src.pack", "$dst.pack") and
1165                                 symlink($idx, "$dst.idx") and
1166                                 -f $idx) {
1167                         ++$ret;
1168                         # .promisor, .bitmap, .rev and .keep are optional
1169                         # XXX should we symlink .keep here?
1170                         for my $s (qw(promisor bitmap rev)) {
1171                                 symlink("$src.$s", "$dst.$s") if -f "$src.$s";
1172                         }
1173                 } elsif (!$!{EEXIST}) {
1174                         warn "W: ln -s $src.{pack,idx} => $dst.*: $!\n";
1175                         unlink "$dst.pack", "$dst.idx";
1176                 }
1177         }
1178         $ret;
1179 }
1180
1181 sub idx_init { # similar to V2Writable
1182         my ($self, $opt) = @_;
1183         return if $self->{idx_shards};
1184
1185         $self->git->cleanup;
1186         my $mode = 0644;
1187         my $ALL = $self->git->{git_dir}; # topdir/ALL.git
1188         my ($has_new, $alt, $seen);
1189         if ($opt->{-private}) { # LeiStore
1190                 my $local = "$self->{topdir}/local"; # lei/store
1191                 $self->{mg} //= PublicInbox::MultiGit->new($self->{topdir},
1192                                                         'ALL.git', 'local');
1193                 $mode = 0600;
1194                 unless (-d $ALL) {
1195                         umask 077; # don't bother restoring for lei
1196                         PublicInbox::Import::init_bare($ALL);
1197                         $self->git->qx(qw(config core.sharedRepository 0600));
1198                 }
1199                 ($alt, $seen) = $self->{mg}->read_alternates(\$mode);
1200                 $has_new = $self->{mg}->merge_epochs($alt, $seen);
1201         } else { # extindex has no epochs
1202                 $self->{mg} //= PublicInbox::MultiGit->new($self->{topdir},
1203                                                         'ALL.git');
1204                 ($alt, $seen) = $self->{mg}->read_alternates(\$mode,
1205                                                         $opt->{-idx_gc});
1206                 PublicInbox::Import::init_bare($ALL);
1207         }
1208
1209         # git-multi-pack-index(1) can speed up "git cat-file" startup slightly
1210         my $git_midx = 0;
1211         my $pd = "$ALL/objects/pack";
1212         if (opendir(my $dh, $pd)) { # drop stale symlinks
1213                 while (defined(my $dn = readdir($dh))) {
1214                         if ($dn =~ /\.(?:idx|pack|promisor|bitmap|rev)\z/) {
1215                                 my $f = "$pd/$dn";
1216                                 unlink($f) if -l $f && !-e $f;
1217                         }
1218                 }
1219         } elsif ($!{ENOENT}) {
1220                 mkdir($pd) or die "mkdir($pd): $!";
1221         } else {
1222                 die "opendir($pd): $!";
1223         }
1224         my $new = '';
1225         for my $ibx (@{ibx_sorted($self, 'active')}) {
1226                 # create symlinks for multi-pack-index
1227                 $git_midx += symlink_packs($ibx, $pd);
1228                 # add new lines to our alternates file
1229                 my $d = $ibx->git->{git_dir} . '/objects';
1230                 next if exists $alt->{$d};
1231                 if (my @st = stat($d)) {
1232                         next if $seen->{"$st[0]\0$st[1]"}++;
1233                 } else {
1234                         warn "W: stat($d) failed (from $ibx->{inboxdir}): $!\n";
1235                         next if $opt->{-idx_gc};
1236                 }
1237                 $new .= "$d\n";
1238         }
1239         ($has_new || $new ne '') and
1240                 $self->{mg}->write_alternates($mode, $alt, $new);
1241         $git_midx and $self->with_umask(sub {
1242                 my @cmd = ('multi-pack-index');
1243                 push @cmd, '--no-progress' if ($opt->{quiet}//0) > 1;
1244                 my $lk = $self->lock_for_scope;
1245                 system('git', "--git-dir=$ALL", @cmd, 'write');
1246                 # ignore errors, fairly new command, may not exist
1247         });
1248         $self->parallel_init($self->{indexlevel});
1249         $self->with_umask(\&_idx_init, $self, $opt);
1250         $self->{oidx}->begin_lazy;
1251         $self->{oidx}->eidx_prep;
1252         $self->{midx}->create_xdb if $new ne '';
1253 }
1254
1255 sub _watch_commit { # PublicInbox::DS::add_timer callback
1256         my ($self) = @_;
1257         delete $self->{-commit_timer};
1258         eidxq_process($self, $self->{-watch_sync});
1259         eidxq_release($self);
1260         my $fmt = delete $self->{-watch_sync}->{-regen_fmt};
1261         reindex_checkpoint($self, $self->{-watch_sync});
1262         $self->{-watch_sync}->{-regen_fmt} = $fmt;
1263
1264         # call event_step => done unless commit_timer is armed
1265         PublicInbox::DS::requeue($self);
1266 }
1267
1268 sub on_inbox_unlock { # called by PublicInbox::InboxIdle
1269         my ($self, $ibx) = @_;
1270         my $opt = $self->{-watch_sync}->{-opt};
1271         my $pr = $opt->{-progress};
1272         my $ekey = $ibx->eidx_key;
1273         local $0 = "sync $ekey";
1274         $pr->("indexing $ekey\n") if $pr;
1275         $self->idx_init($opt);
1276         sync_inbox($self, $self->{-watch_sync}, $ibx);
1277         $self->{-commit_timer} //= add_timer($opt->{'commit-interval'} // 10,
1278                                         \&_watch_commit, $self);
1279 }
1280
1281 sub eidx_reload { # -extindex --watch SIGHUP handler
1282         my ($self, $idler) = @_;
1283         if ($self->{cfg}) {
1284                 my $pr = $self->{-watch_sync}->{-opt}->{-progress};
1285                 $pr->('reloading ...') if $pr;
1286                 delete $self->{-resync_queue};
1287                 delete $self->{-ibx_ary_known};
1288                 delete $self->{-ibx_ary_active};
1289                 $self->{ibx_known} = [];
1290                 $self->{ibx_active} = [];
1291                 %{$self->{ibx_map}} = ();
1292                 delete $self->{-watch_sync}->{id2pos};
1293                 my $cfg = PublicInbox::Config->new;
1294                 attach_config($self, $cfg);
1295                 $idler->refresh($cfg);
1296                 $pr->(" done\n") if $pr;
1297         } else {
1298                 warn "reload not supported without --all\n";
1299         }
1300 }
1301
1302 sub eidx_resync_start ($) { # -extindex --watch SIGUSR1 handler
1303         my ($self) = @_;
1304         $self->{-resync_queue} //= [ @{ibx_sorted($self, 'active')} ];
1305         PublicInbox::DS::requeue($self); # trigger our ->event_step
1306 }
1307
1308 sub event_step { # PublicInbox::DS::requeue callback
1309         my ($self) = @_;
1310         if (my $resync_queue = $self->{-resync_queue}) {
1311                 if (my $ibx = shift(@$resync_queue)) {
1312                         on_inbox_unlock($self, $ibx);
1313                         PublicInbox::DS::requeue($self);
1314                 } else {
1315                         delete $self->{-resync_queue};
1316                         _watch_commit($self);
1317                 }
1318         } else {
1319                 done($self) unless $self->{-commit_timer};
1320         }
1321 }
1322
1323 sub eidx_watch { # public-inbox-extindex --watch main loop
1324         my ($self, $opt) = @_;
1325         local @SIG{keys %SIG} = values %SIG;
1326         for my $sig (qw(HUP USR1 TSTP QUIT INT TERM)) {
1327                 $SIG{$sig} = sub { warn "SIG$sig ignored while scanning\n" };
1328         }
1329         require PublicInbox::InboxIdle;
1330         require PublicInbox::DS;
1331         require PublicInbox::Syscall;
1332         require PublicInbox::Sigfd;
1333         my $idler = PublicInbox::InboxIdle->new($self->{cfg});
1334         if (!$self->{cfg}) {
1335                 $idler->watch_inbox($_) for (@{ibx_sorted($self, 'active')});
1336         }
1337         for my $ibx (@{ibx_sorted($self, 'active')}) {
1338                 $ibx->subscribe_unlock(__PACKAGE__, $self)
1339         }
1340         my $pr = $opt->{-progress};
1341         $pr->("performing initial scan ...\n") if $pr;
1342         my $sync = eidx_sync($self, $opt); # initial sync
1343         return if $sync->{quit};
1344         my $oldset = PublicInbox::DS::block_signals();
1345         local $self->{current_info} = '';
1346         my $cb = $SIG{__WARN__} || \&CORE::warn;
1347         local $SIG{__WARN__} = sub {
1348                 return if PublicInbox::Eml::warn_ignore(@_);
1349                 $cb->($self->{current_info}, ': ', @_);
1350         };
1351         my $sig = {
1352                 HUP => sub { eidx_reload($self, $idler) },
1353                 USR1 => sub { eidx_resync_start($self) },
1354                 TSTP => sub { kill('STOP', $$) },
1355         };
1356         my $quit = PublicInbox::SearchIdx::quit_cb($sync);
1357         $sig->{QUIT} = $sig->{INT} = $sig->{TERM} = $quit;
1358         local $self->{-watch_sync} = $sync; # for ->on_inbox_unlock
1359         PublicInbox::DS->SetPostLoopCallback(sub { !$sync->{quit} });
1360         $pr->("initial scan complete, entering event loop\n") if $pr;
1361         # calls InboxIdle->event_step:
1362         PublicInbox::DS::event_loop($sig, $oldset);
1363         done($self);
1364 }
1365
1366 no warnings 'once';
1367 *done = \&PublicInbox::V2Writable::done;
1368 *with_umask = \&PublicInbox::InboxWritable::with_umask;
1369 *parallel_init = \&PublicInbox::V2Writable::parallel_init;
1370 *nproc_shards = \&PublicInbox::V2Writable::nproc_shards;
1371 *sync_prepare = \&PublicInbox::V2Writable::sync_prepare;
1372 *index_todo = \&PublicInbox::V2Writable::index_todo;
1373 *count_shards = \&PublicInbox::V2Writable::count_shards;
1374 *atfork_child = \&PublicInbox::V2Writable::atfork_child;
1375 *idx_shard = \&PublicInbox::V2Writable::idx_shard;
1376 *reindex_checkpoint = \&PublicInbox::V2Writable::reindex_checkpoint;
1377 *checkpoint = \&PublicInbox::V2Writable::checkpoint;
1378
1379 1;