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