]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/ExtSearchIdx.pm
750ced5c0f453bc8e0241a1ea2e6603a64c00104
[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 ($oid) gone or corrupt\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 ($oid) 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         local $self->{current_info} = 'eidxq process';
758         return unless ($self->{cfg} && eidxq_lock_acquire($self));
759         my $dbh = $self->{oidx}->dbh;
760         my $tot = $dbh->selectrow_array('SELECT COUNT(*) FROM eidxq') or return;
761         ${$sync->{nr}} = 0;
762         local $sync->{-regen_fmt} = "%u/$tot\n";
763         my $pr = $sync->{-opt}->{-progress};
764         if ($pr) {
765                 my $min = $dbh->selectrow_array('SELECT MIN(docid) FROM eidxq');
766                 my $max = $dbh->selectrow_array('SELECT MAX(docid) FROM eidxq');
767                 $pr->("Xapian indexing $min..$max (total=$tot)\n");
768         }
769         $sync->{id2pos} //= prep_id2pos($self);
770         my ($del, $iter);
771 restart:
772         $del = $dbh->prepare('DELETE FROM eidxq WHERE docid = ?');
773         $iter = $dbh->prepare('SELECT docid FROM eidxq ORDER BY docid ASC');
774         $iter->execute;
775         while (defined(my $docid = $iter->fetchrow_array)) {
776                 last if $sync->{quit};
777                 if (my $smsg = $self->{oidx}->get_art($docid)) {
778                         _reindex_smsg($self, $sync, $smsg);
779                 } else {
780                         warn "E: #$docid does not exist in over\n";
781                 }
782                 $del->execute($docid);
783                 ++${$sync->{nr}};
784
785                 if (checkpoint_due($sync)) {
786                         $dbh = $del = $iter = undef;
787                         reindex_checkpoint($self, $sync); # release lock
788                         $dbh = $self->{oidx}->dbh;
789                         goto restart;
790                 }
791         }
792         $self->git->async_wait_all;
793         $pr->("reindexed ${$sync->{nr}}/$tot\n") if $pr;
794 }
795
796 sub _reindex_unseen { # git->cat_async callback
797         my ($bref, $oid, $type, $size, $req) = @_;
798         return if is_bad_blob($oid, $type, $size, $req->{oid});
799         my $self = $req->{self} // die 'BUG: {self} unset';
800         local $self->{current_info} = "$self->{current_info} $oid";
801         my $new_smsg = bless { blob => $oid, }, 'PublicInbox::Smsg';
802         $new_smsg->set_bytes($$bref, $size);
803         my $eml = $req->{eml} = PublicInbox::Eml->new($bref);
804         $req->{new_smsg} = $new_smsg;
805         $req->{chash} = content_hash($eml);
806         $req->{mids} = mids($eml); # do_step iterates through this
807         do_step($req); # enter the normal indexing flow
808 }
809
810 # --reindex may catch totally unseen messages, this handles them
811 sub reindex_unseen ($$$$) {
812         my ($self, $sync, $ibx, $xsmsg) = @_;
813         my $req = {
814                 %$sync, # has {self}
815                 autime => $xsmsg->{ds},
816                 cotime => $xsmsg->{ts},
817                 oid => $xsmsg->{blob},
818                 ibx => $ibx,
819                 xnum => $xsmsg->{num},
820                 # {mids} and {chash} will be filled in at _reindex_unseen
821         };
822         warn "I: reindex_unseen ${\$ibx->eidx_key}:$req->{xnum}:$req->{oid}\n";
823         $self->git->cat_async($xsmsg->{blob}, \&_reindex_unseen, $req);
824 }
825
826 sub _unref_stale_range ($$$) {
827         my ($sync, $ibx, $lt_or_gt) = @_;
828         my $r;
829         my $lim = 10000;
830         do {
831                 $r = $sync->{self}->{oidx}->dbh->selectall_arrayref(
832                         <<EOS, undef, $ibx->{-ibx_id});
833 SELECT docid,xnum,oidbin FROM xref3
834 WHERE ibx_id = ? AND xnum $lt_or_gt LIMIT $lim
835 EOS
836                 return if $sync->{quit};
837                 for (@$r) { # hopefully rare, not worth optimizing:
838                         my ($docid, $xnum, $oidbin) = @$_;
839                         my $hex = unpack('H*', $oidbin);
840                         warn("# $xnum:$hex (#$docid): stale\n");
841                         _unref_doc($sync, $docid, $ibx, $xnum, $oidbin);
842                 }
843         } while (scalar(@$r) == $lim);
844         1;
845 }
846
847 sub _reindex_check_ibx ($$$) {
848         my ($self, $sync, $ibx) = @_;
849         my $ibx_id = $ibx->{-ibx_id};
850         my $slice = 10000;
851         my $opt = { limit => $slice };
852         my ($beg, $end) = (1, $slice);
853         my $err = sync_inbox($self, $sync, $ibx) and return;
854         my $max = $ibx->over->max;
855         $end = $max if $end > $max;
856
857         # first, check if we missed any messages in target $ibx
858         my $msgs;
859         my $pr = $sync->{-opt}->{-progress};
860         my $ekey = $ibx->eidx_key;
861         local $sync->{-regen_fmt} = "$ekey checking %u/$max\n";
862         ${$sync->{nr}} = 0;
863         my $fast = $sync->{-opt}->{fast};
864         my $dsu; # _unref_stale_range (< $lo) called
865         my ($lo, $hi);
866         while (scalar(@{$msgs = $ibx->over->query_xover($beg, $end, $opt)})) {
867                 ${$sync->{nr}} = $beg;
868                 $beg = $msgs->[-1]->{num} + 1;
869                 $end = $beg + $slice;
870                 $end = $max if $end > $max;
871                 if (checkpoint_due($sync)) {
872                         reindex_checkpoint($self, $sync); # release lock
873                 }
874                 ($lo, $hi) = ($msgs->[0]->{num}, $msgs->[-1]->{num});
875                 $dsu //= _unref_stale_range($sync, $ibx, "< $lo");
876                 my $x3a = $self->{oidx}->dbh->selectall_arrayref(
877                         <<"", undef, $ibx_id, $lo, $hi);
878 SELECT xnum,oidbin,docid FROM xref3 WHERE
879 ibx_id = ? AND xnum >= ? AND xnum <= ?
880
881                 my %x3m;
882                 for (@$x3a) {
883                         my $k = pack('J', $_->[0]) . $_->[1];
884                         push @{$x3m{$k}}, $_->[2];
885                 }
886                 undef $x3a;
887                 for my $xsmsg (@$msgs) {
888                         my $k = pack('JH*', $xsmsg->{num}, $xsmsg->{blob});
889                         my $docids = delete($x3m{$k});
890                         if (!defined($docids)) {
891                                 reindex_unseen($self, $sync, $ibx, $xsmsg);
892                         } elsif (!$fast) {
893                                 for my $num (@$docids) {
894                                         $self->{oidx}->eidxq_add($num);
895                                 }
896                                 return if $sync->{quit};
897                         }
898                 }
899                 return if $sync->{quit};
900                 next unless scalar keys %x3m;
901                 $self->git->async_wait_all; # wait for reindex_unseen
902
903                 # eliminate stale/mismatched entries
904                 my %mismatch = map { $_->{num} => $_->{blob} } @$msgs;
905                 while (my ($k, $docids) = each %x3m) {
906                         my ($xnum, $hex) = unpack('JH*', $k);
907                         my $bin = pack('H*', $hex);
908                         my $exp = $mismatch{$xnum};
909                         my $m = defined($exp) ? "mismatch (!= $exp)" : 'stale';
910                         warn("# $xnum:$hex (#@$docids): $m\n");
911                         for my $i (@$docids) {
912                                 _unref_doc($sync, $i, $ibx, $xnum, $bin);
913                         }
914                 }
915         }
916         _unref_stale_range($sync, $ibx, "> $hi") if defined($hi);
917 }
918
919 sub _reindex_inbox ($$$) {
920         my ($self, $sync, $ibx) = @_;
921         my $ekey = $ibx->eidx_key;
922         local $self->{current_info} = $ekey;
923         if (defined(my $err = _ibx_index_reject($ibx))) {
924                 warn "W: cannot reindex $ekey ($err)\n";
925         } else {
926                 _reindex_check_ibx($self, $sync, $ibx);
927         }
928         delete @$ibx{qw(over mm search git)}; # won't need these for a bit
929 }
930
931 sub eidx_reindex {
932         my ($self, $sync) = @_;
933         return unless $self->{cfg};
934
935         # acquire eidxq_lock early because full reindex takes forever
936         # and incremental -extindex processes can run during our checkpoints
937         if (!eidxq_lock_acquire($self)) {
938                 warn "E: aborting --reindex\n";
939                 return;
940         }
941         for my $ibx (@{ibx_sorted($self, 'active')}) {
942                 _reindex_inbox($self, $sync, $ibx);
943                 last if $sync->{quit};
944         }
945         $self->git->async_wait_all; # ensure eidxq gets filled completely
946         eidxq_process($self, $sync) unless $sync->{quit};
947 }
948
949 sub sync_inbox {
950         my ($self, $sync, $ibx) = @_;
951         my $err = _sync_inbox($self, $sync, $ibx);
952         delete @$ibx{qw(mm over)};
953         warn $err, "\n" if defined($err);
954         $err;
955 }
956
957 sub dd_smsg { # git->cat_async callback
958         my ($bref, $oid, $type, $size, $dd) = @_;
959         my $smsg = $dd->{smsg} // die 'BUG: dd->{smsg} missing';
960         my $self = $dd->{self} // die 'BUG: {self} missing';
961         my $per_mid = $dd->{per_mid} // die 'BUG: {per_mid} missing';
962         if ($type eq 'missing') {
963                 _blob_missing($dd, $smsg);
964         } elsif (!is_bad_blob($oid, $type, $size, $smsg->{blob})) {
965                 local $self->{current_info} = "$self->{current_info} $oid";
966                 my $chash = content_hash(PublicInbox::Eml->new($bref));
967                 push(@{$per_mid->{dd_chash}->{$chash}}, $smsg);
968         }
969         return if $per_mid->{last_smsg} != $smsg;
970         while (my ($chash, $ary) = each %{$per_mid->{dd_chash}}) {
971                 my $keep = shift @$ary;
972                 next if !scalar(@$ary);
973                 $per_mid->{sync}->{dedupe_cull} += scalar(@$ary);
974                 print STDERR
975                         "# <$keep->{mid}> keeping #$keep->{num}, dropping ",
976                         join(', ', map { "#$_->{num}" } @$ary),"\n";
977                 next if $per_mid->{sync}->{-opt}->{'dry-run'};
978                 my $oidx = $self->{oidx};
979                 for my $smsg (@$ary) {
980                         my $gone = $smsg->{num};
981                         $oidx->merge_xref3($keep->{num}, $gone, $smsg->{blob});
982                         remove_doc($self, $gone);
983                 }
984         }
985 }
986
987 sub eidx_dedupe ($$$) {
988         my ($self, $sync, $msgids) = @_;
989         $sync->{dedupe_cull} = 0;
990         my $candidates = 0;
991         my $nr_mid = 0;
992         return unless eidxq_lock_acquire($self);
993         my ($iter, $cur_mid);
994         my $min_id = 0;
995         my $idx = 0;
996         my ($max_id) = $self->{oidx}->dbh->selectrow_array(<<EOS);
997 SELECT MAX(id) FROM msgid
998 EOS
999         local $sync->{-regen_fmt} = "dedupe %u/$max_id\n";
1000
1001         # note: we could write this query more intelligently,
1002         # but that causes lock contention with read-only processes
1003 dedupe_restart:
1004         $cur_mid = $msgids->[$idx];
1005         if ($cur_mid eq '') { # all Message-IDs
1006                 $iter = $self->{oidx}->dbh->prepare(<<EOS);
1007 SELECT mid,id FROM msgid WHERE id > ? ORDER BY id ASC
1008 EOS
1009                 $iter->execute($min_id);
1010         } else {
1011                 $iter = $self->{oidx}->dbh->prepare(<<EOS);
1012 SELECT mid,id FROM msgid WHERE mid = ? AND id > ? ORDER BY id ASC
1013 EOS
1014                 $iter->execute($cur_mid, $min_id);
1015         }
1016         while (my ($mid, $id) = $iter->fetchrow_array) {
1017                 last if $sync->{quit};
1018                 $self->{current_info} = "dedupe $mid";
1019                 ${$sync->{nr}} = $min_id = $id;
1020                 my ($prv, @smsg);
1021                 while (my $x = $self->{oidx}->next_by_mid($mid, \$id, \$prv)) {
1022                         push @smsg, $x;
1023                 }
1024                 next if scalar(@smsg) < 2;
1025                 my $per_mid = {
1026                         dd_chash => {}, # chash => [ary of smsgs]
1027                         last_smsg => $smsg[-1],
1028                         sync => $sync
1029                 };
1030                 $nr_mid++;
1031                 $candidates += scalar(@smsg) - 1;
1032                 for my $smsg (@smsg) {
1033                         my $dd = {
1034                                 per_mid => $per_mid,
1035                                 smsg => $smsg,
1036                                 self => $self,
1037                         };
1038                         $self->git->cat_async($smsg->{blob}, \&dd_smsg, $dd);
1039                 }
1040                 # need to wait on every single one @smsg contents can get
1041                 # invalidated inside dd_smsg for messages with multiple
1042                 # Message-IDs.
1043                 $self->git->async_wait_all;
1044
1045                 if (checkpoint_due($sync)) {
1046                         undef $iter;
1047                         reindex_checkpoint($self, $sync);
1048                         goto dedupe_restart;
1049                 }
1050         }
1051         goto dedupe_restart if defined($msgids->[++$idx]);
1052
1053         my $n = delete $sync->{dedupe_cull};
1054         if (my $pr = $sync->{-opt}->{-progress}) {
1055                 $pr->("culled $n/$candidates candidates ($nr_mid msgids)\n");
1056         }
1057         ${$sync->{nr}} = 0;
1058 }
1059
1060 sub eidx_sync { # main entry point
1061         my ($self, $opt) = @_;
1062
1063         my $warn_cb = $SIG{__WARN__} || \&CORE::warn;
1064         local $self->{current_info} = '';
1065         local $SIG{__WARN__} = sub {
1066                 return if PublicInbox::Eml::warn_ignore(@_);
1067                 $warn_cb->($self->{current_info}, ': ', @_);
1068         };
1069         $self->idx_init($opt); # acquire lock via V2Writable::_idx_init
1070         $self->{oidx}->rethread_prepare($opt);
1071         my $sync = {
1072                 need_checkpoint => \(my $need_checkpoint = 0),
1073                 check_intvl => 10,
1074                 next_check => now() + 10,
1075                 -opt => $opt,
1076                 # DO NOT SET {reindex} here, it's incompatible with reused
1077                 # V2Writable code, reindex is totally different here
1078                 # compared to v1/v2 inboxes because we have multiple histories
1079                 self => $self,
1080                 -regen_fmt => "%u/?\n",
1081         };
1082         local $SIG{USR1} = sub { $need_checkpoint = 1 };
1083         my $quit = PublicInbox::SearchIdx::quit_cb($sync);
1084         local $SIG{QUIT} = $quit;
1085         local $SIG{INT} = $quit;
1086         local $SIG{TERM} = $quit;
1087         for my $ibx (@{ibx_sorted($self, 'known')}) {
1088                 $ibx->{-ibx_id} //= $self->{oidx}->ibx_id($ibx->eidx_key);
1089         }
1090
1091         if (scalar(grep { defined($_->{boost}) } @{$self->{ibx_known}})) {
1092                 $sync->{id2pos} //= prep_id2pos($self);
1093                 $sync->{boost_in_use} = 1;
1094         }
1095
1096         if (my $msgids = delete($opt->{dedupe})) {
1097                 local $sync->{checkpoint_unlocks} = 1;
1098                 eidx_dedupe($self, $sync, $msgids);
1099         }
1100         if (delete($opt->{reindex})) {
1101                 local $sync->{checkpoint_unlocks} = 1;
1102                 eidx_reindex($self, $sync);
1103         }
1104
1105         # don't use $_ here, it'll get clobbered by reindex_checkpoint
1106         if ($opt->{scan} // 1) {
1107                 for my $ibx (@{ibx_sorted($self, 'active')}) {
1108                         last if $sync->{quit};
1109                         sync_inbox($self, $sync, $ibx);
1110                 }
1111         }
1112         $self->{oidx}->rethread_done($opt) unless $sync->{quit};
1113         eidxq_process($self, $sync) unless $sync->{quit};
1114
1115         eidxq_release($self);
1116         done($self);
1117         $sync; # for eidx_watch
1118 }
1119
1120 sub update_last_commit { # overrides V2Writable
1121         my ($self, $sync, $stk) = @_;
1122         my $unit = $sync->{unit} // return;
1123         my $latest_cmt = $stk ? $stk->{latest_cmt} : ${$sync->{latest_cmt}};
1124         defined($latest_cmt) or return;
1125         my $ibx = $sync->{ibx} or die 'BUG: {ibx} missing';
1126         my $ekey = $ibx->eidx_key;
1127         my $uv = $ibx->uidvalidity;
1128         my $epoch = $unit->{epoch};
1129         my $meta_key;
1130         my $v = $ibx->version;
1131         if ($v == 2) {
1132                 die 'No {epoch} for v2 unit' unless defined $epoch;
1133                 $meta_key = "lc-v2:$ekey//$uv;$epoch";
1134         } elsif ($v == 1) {
1135                 die 'Unexpected {epoch} for v1 unit' if defined $epoch;
1136                 $meta_key = "lc-v1:$ekey//$uv";
1137         } else {
1138                 die "Unsupported inbox version: $v";
1139         }
1140         my $last = $self->{oidx}->eidx_meta($meta_key);
1141         if (defined $last && is_ancestor($self->git, $last, $latest_cmt)) {
1142                 my @cmd = (qw(rev-list --count), "$last..$latest_cmt");
1143                 chomp(my $n = $unit->{git}->qx(@cmd));
1144                 return if $n ne '' && $n == 0;
1145         }
1146         $self->{oidx}->eidx_meta($meta_key, $latest_cmt);
1147 }
1148
1149 sub _idx_init { # with_umask callback
1150         my ($self, $opt) = @_;
1151         PublicInbox::V2Writable::_idx_init($self, $opt); # acquires ei.lock
1152         $self->{midx} = PublicInbox::MiscIdx->new($self);
1153 }
1154
1155 sub symlink_packs ($$) {
1156         my ($ibx, $pd) = @_;
1157         my $ret = 0;
1158         my $glob = "$ibx->{inboxdir}/git/*.git/objects/pack/*.idx";
1159         for my $idx (bsd_glob($glob, GLOB_NOSORT)) {
1160                 my $src = substr($idx, 0, -length('.idx'));
1161                 my $dst = $pd . substr($src, rindex($src, '/'));
1162                 if (-f "$src.pack" and
1163                                 symlink("$src.pack", "$dst.pack") and
1164                                 symlink($idx, "$dst.idx") and
1165                                 -f $idx) {
1166                         ++$ret;
1167                         # .promisor, .bitmap, .rev and .keep are optional
1168                         # XXX should we symlink .keep here?
1169                         for my $s (qw(promisor bitmap rev)) {
1170                                 symlink("$src.$s", "$dst.$s") if -f "$src.$s";
1171                         }
1172                 } elsif (!$!{EEXIST}) {
1173                         warn "W: ln -s $src.{pack,idx} => $dst.*: $!\n";
1174                         unlink "$dst.pack", "$dst.idx";
1175                 }
1176         }
1177         $ret;
1178 }
1179
1180 sub idx_init { # similar to V2Writable
1181         my ($self, $opt) = @_;
1182         return if $self->{idx_shards};
1183
1184         $self->git->cleanup;
1185         my $mode = 0644;
1186         my $ALL = $self->git->{git_dir}; # topdir/ALL.git
1187         my ($has_new, $alt, $seen);
1188         if ($opt->{-private}) { # LeiStore
1189                 my $local = "$self->{topdir}/local"; # lei/store
1190                 $self->{mg} //= PublicInbox::MultiGit->new($self->{topdir},
1191                                                         'ALL.git', 'local');
1192                 $mode = 0600;
1193                 unless (-d $ALL) {
1194                         umask 077; # don't bother restoring for lei
1195                         PublicInbox::Import::init_bare($ALL);
1196                         $self->git->qx(qw(config core.sharedRepository 0600));
1197                 }
1198                 ($alt, $seen) = $self->{mg}->read_alternates(\$mode);
1199                 $has_new = $self->{mg}->merge_epochs($alt, $seen);
1200         } else { # extindex has no epochs
1201                 $self->{mg} //= PublicInbox::MultiGit->new($self->{topdir},
1202                                                         'ALL.git');
1203                 ($alt, $seen) = $self->{mg}->read_alternates(\$mode,
1204                                                         $opt->{-idx_gc});
1205                 PublicInbox::Import::init_bare($ALL);
1206         }
1207
1208         # git-multi-pack-index(1) can speed up "git cat-file" startup slightly
1209         my $git_midx = 0;
1210         my $pd = "$ALL/objects/pack";
1211         if (opendir(my $dh, $pd)) { # drop stale symlinks
1212                 while (defined(my $dn = readdir($dh))) {
1213                         if ($dn =~ /\.(?:idx|pack|promisor|bitmap|rev)\z/) {
1214                                 my $f = "$pd/$dn";
1215                                 unlink($f) if -l $f && !-e $f;
1216                         }
1217                 }
1218         } elsif ($!{ENOENT}) {
1219                 mkdir($pd) or die "mkdir($pd): $!";
1220         } else {
1221                 die "opendir($pd): $!";
1222         }
1223         my $new = '';
1224         for my $ibx (@{ibx_sorted($self, 'active')}) {
1225                 # create symlinks for multi-pack-index
1226                 $git_midx += symlink_packs($ibx, $pd);
1227                 # add new lines to our alternates file
1228                 my $d = $ibx->git->{git_dir} . '/objects';
1229                 next if exists $alt->{$d};
1230                 if (my @st = stat($d)) {
1231                         next if $seen->{"$st[0]\0$st[1]"}++;
1232                 } else {
1233                         warn "W: stat($d) failed (from $ibx->{inboxdir}): $!\n";
1234                         next if $opt->{-idx_gc};
1235                 }
1236                 $new .= "$d\n";
1237         }
1238         ($has_new || $new ne '') and
1239                 $self->{mg}->write_alternates($mode, $alt, $new);
1240         $git_midx and $self->with_umask(sub {
1241                 my @cmd = ('multi-pack-index');
1242                 push @cmd, '--no-progress' if ($opt->{quiet}//0) > 1;
1243                 my $lk = $self->lock_for_scope;
1244                 system('git', "--git-dir=$ALL", @cmd, 'write');
1245                 # ignore errors, fairly new command, may not exist
1246         });
1247         $self->parallel_init($self->{indexlevel});
1248         $self->with_umask(\&_idx_init, $self, $opt);
1249         $self->{oidx}->begin_lazy;
1250         $self->{oidx}->eidx_prep;
1251         $self->{midx}->create_xdb if $new ne '';
1252 }
1253
1254 sub _watch_commit { # PublicInbox::DS::add_timer callback
1255         my ($self) = @_;
1256         delete $self->{-commit_timer};
1257         eidxq_process($self, $self->{-watch_sync});
1258         eidxq_release($self);
1259         my $fmt = delete $self->{-watch_sync}->{-regen_fmt};
1260         reindex_checkpoint($self, $self->{-watch_sync});
1261         $self->{-watch_sync}->{-regen_fmt} = $fmt;
1262
1263         # call event_step => done unless commit_timer is armed
1264         PublicInbox::DS::requeue($self);
1265 }
1266
1267 sub on_inbox_unlock { # called by PublicInbox::InboxIdle
1268         my ($self, $ibx) = @_;
1269         my $opt = $self->{-watch_sync}->{-opt};
1270         my $pr = $opt->{-progress};
1271         my $ekey = $ibx->eidx_key;
1272         local $0 = "sync $ekey";
1273         $pr->("indexing $ekey\n") if $pr;
1274         $self->idx_init($opt);
1275         sync_inbox($self, $self->{-watch_sync}, $ibx);
1276         $self->{-commit_timer} //= add_timer($opt->{'commit-interval'} // 10,
1277                                         \&_watch_commit, $self);
1278 }
1279
1280 sub eidx_reload { # -extindex --watch SIGHUP handler
1281         my ($self, $idler) = @_;
1282         if ($self->{cfg}) {
1283                 my $pr = $self->{-watch_sync}->{-opt}->{-progress};
1284                 $pr->('reloading ...') if $pr;
1285                 delete $self->{-resync_queue};
1286                 delete $self->{-ibx_ary_known};
1287                 delete $self->{-ibx_ary_active};
1288                 $self->{ibx_known} = [];
1289                 $self->{ibx_active} = [];
1290                 %{$self->{ibx_map}} = ();
1291                 delete $self->{-watch_sync}->{id2pos};
1292                 my $cfg = PublicInbox::Config->new;
1293                 attach_config($self, $cfg);
1294                 $idler->refresh($cfg);
1295                 $pr->(" done\n") if $pr;
1296         } else {
1297                 warn "reload not supported without --all\n";
1298         }
1299 }
1300
1301 sub eidx_resync_start ($) { # -extindex --watch SIGUSR1 handler
1302         my ($self) = @_;
1303         $self->{-resync_queue} //= [ @{ibx_sorted($self, 'active')} ];
1304         PublicInbox::DS::requeue($self); # trigger our ->event_step
1305 }
1306
1307 sub event_step { # PublicInbox::DS::requeue callback
1308         my ($self) = @_;
1309         if (my $resync_queue = $self->{-resync_queue}) {
1310                 if (my $ibx = shift(@$resync_queue)) {
1311                         on_inbox_unlock($self, $ibx);
1312                         PublicInbox::DS::requeue($self);
1313                 } else {
1314                         delete $self->{-resync_queue};
1315                         _watch_commit($self);
1316                 }
1317         } else {
1318                 done($self) unless $self->{-commit_timer};
1319         }
1320 }
1321
1322 sub eidx_watch { # public-inbox-extindex --watch main loop
1323         my ($self, $opt) = @_;
1324         local @SIG{keys %SIG} = values %SIG;
1325         for my $sig (qw(HUP USR1 TSTP QUIT INT TERM)) {
1326                 $SIG{$sig} = sub { warn "SIG$sig ignored while scanning\n" };
1327         }
1328         require PublicInbox::InboxIdle;
1329         require PublicInbox::DS;
1330         require PublicInbox::Syscall;
1331         require PublicInbox::Sigfd;
1332         my $idler = PublicInbox::InboxIdle->new($self->{cfg});
1333         if (!$self->{cfg}) {
1334                 $idler->watch_inbox($_) for (@{ibx_sorted($self, 'active')});
1335         }
1336         for my $ibx (@{ibx_sorted($self, 'active')}) {
1337                 $ibx->subscribe_unlock(__PACKAGE__, $self)
1338         }
1339         my $pr = $opt->{-progress};
1340         $pr->("performing initial scan ...\n") if $pr;
1341         my $sync = eidx_sync($self, $opt); # initial sync
1342         return if $sync->{quit};
1343         my $oldset = PublicInbox::DS::block_signals();
1344         local $self->{current_info} = '';
1345         my $cb = $SIG{__WARN__} || \&CORE::warn;
1346         local $SIG{__WARN__} = sub {
1347                 return if PublicInbox::Eml::warn_ignore(@_);
1348                 $cb->($self->{current_info}, ': ', @_);
1349         };
1350         my $sig = {
1351                 HUP => sub { eidx_reload($self, $idler) },
1352                 USR1 => sub { eidx_resync_start($self) },
1353                 TSTP => sub { kill('STOP', $$) },
1354         };
1355         my $quit = PublicInbox::SearchIdx::quit_cb($sync);
1356         $sig->{QUIT} = $sig->{INT} = $sig->{TERM} = $quit;
1357         local $self->{-watch_sync} = $sync; # for ->on_inbox_unlock
1358         PublicInbox::DS->SetPostLoopCallback(sub { !$sync->{quit} });
1359         $pr->("initial scan complete, entering event loop\n") if $pr;
1360         # calls InboxIdle->event_step:
1361         PublicInbox::DS::event_loop($sig, $oldset);
1362         done($self);
1363 }
1364
1365 no warnings 'once';
1366 *done = \&PublicInbox::V2Writable::done;
1367 *with_umask = \&PublicInbox::InboxWritable::with_umask;
1368 *parallel_init = \&PublicInbox::V2Writable::parallel_init;
1369 *nproc_shards = \&PublicInbox::V2Writable::nproc_shards;
1370 *sync_prepare = \&PublicInbox::V2Writable::sync_prepare;
1371 *index_todo = \&PublicInbox::V2Writable::index_todo;
1372 *count_shards = \&PublicInbox::V2Writable::count_shards;
1373 *atfork_child = \&PublicInbox::V2Writable::atfork_child;
1374 *idx_shard = \&PublicInbox::V2Writable::idx_shard;
1375 *reindex_checkpoint = \&PublicInbox::V2Writable::reindex_checkpoint;
1376 *checkpoint = \&PublicInbox::V2Writable::checkpoint;
1377
1378 1;