]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/SearchIdx.pm
remove unnecessary ->header_obj calls
[public-inbox.git] / lib / PublicInbox / SearchIdx.pm
1 # Copyright (C) 2015-2020 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
3 # based on notmuch, but with no concept of folders, files or flags
4 #
5 # Indexes mail with Xapian and our (SQLite-based) ::Msgmap for use
6 # with the web and NNTP interfaces.  This index maintains thread
7 # relationships for use by PublicInbox::SearchThread.
8 # This writes to the search index.
9 package PublicInbox::SearchIdx;
10 use strict;
11 use v5.10.1;
12 use parent qw(PublicInbox::Search PublicInbox::Lock Exporter);
13 use PublicInbox::Eml;
14 use PublicInbox::InboxWritable;
15 use PublicInbox::MID qw(mids_for_index mids);
16 use PublicInbox::MsgIter;
17 use PublicInbox::IdxStack;
18 use Carp qw(croak);
19 use POSIX qw(strftime);
20 use PublicInbox::OverIdx;
21 use PublicInbox::Spawn qw(spawn);
22 use PublicInbox::Git qw(git_unquote);
23 use PublicInbox::MsgTime qw(msg_timestamp msg_datestamp);
24 our @EXPORT_OK = qw(crlf_adjust log2stack is_ancestor check_size nodatacow_dir);
25 my $X = \%PublicInbox::Search::X;
26 my ($DB_CREATE_OR_OPEN, $DB_OPEN);
27 our $DB_NO_SYNC = 0;
28 our $BATCH_BYTES = defined($ENV{XAPIAN_FLUSH_THRESHOLD}) ?
29                         0x7fffffff : 1_000_000;
30 use constant DEBUG => !!$ENV{DEBUG};
31
32 my $xapianlevels = qr/\A(?:full|medium)\z/;
33 my $hex = '[a-f0-9]';
34 my $OID = $hex .'{40,}';
35
36 sub new {
37         my ($class, $ibx, $creat, $shard) = @_;
38         ref $ibx or die "BUG: expected PublicInbox::Inbox object: $ibx";
39         my $levels = qr/\A(?:full|medium|basic)\z/;
40         my $inboxdir = $ibx->{inboxdir};
41         my $version = $ibx->version;
42         my $indexlevel = 'full';
43         my $altid = $ibx->{altid};
44         if ($altid) {
45                 require PublicInbox::AltId;
46                 $altid = [ map { PublicInbox::AltId->new($ibx, $_); } @$altid ];
47         }
48         if ($ibx->{indexlevel}) {
49                 if ($ibx->{indexlevel} =~ $levels) {
50                         $indexlevel = $ibx->{indexlevel};
51                 } else {
52                         die("Invalid indexlevel $ibx->{indexlevel}\n");
53                 }
54         }
55         $ibx = PublicInbox::InboxWritable->new($ibx);
56         my $self = bless {
57                 ibx => $ibx,
58                 xpfx => $inboxdir, # for xpfx_init
59                 -altid => $altid,
60                 ibx_ver => $version,
61                 indexlevel => $indexlevel,
62         }, $class;
63         $self->xpfx_init;
64         $self->{-set_indexlevel_once} = 1 if $indexlevel eq 'medium';
65         $ibx->umask_prepare;
66         if ($version == 1) {
67                 $self->{lock_path} = "$inboxdir/ssoma.lock";
68                 my $dir = $self->xdir;
69                 $self->{over} = PublicInbox::OverIdx->new("$dir/over.sqlite3");
70                 $self->{over}->{-no_sync} = 1 if $ibx->{-no_sync};
71                 $self->{index_max_size} = $ibx->{index_max_size};
72         } elsif ($version == 2) {
73                 defined $shard or die "shard is required for v2\n";
74                 # shard is a number
75                 $self->{shard} = $shard;
76                 $self->{lock_path} = undef;
77         } else {
78                 die "unsupported inbox version=$version\n";
79         }
80         $self->{creat} = ($creat || 0) == 1;
81         $self;
82 }
83
84 sub need_xapian ($) { $_[0]->{indexlevel} =~ $xapianlevels }
85
86 sub idx_release {
87         my ($self, $wake) = @_;
88         if (need_xapian($self)) {
89                 my $xdb = delete $self->{xdb} or croak 'not acquired';
90                 $xdb->close;
91         }
92         $self->lock_release($wake) if $self->{creat};
93         undef;
94 }
95
96 sub load_xapian_writable () {
97         return 1 if $X->{WritableDatabase};
98         PublicInbox::Search::load_xapian() or return;
99         my $xap = $PublicInbox::Search::Xap;
100         for (qw(Document TermGenerator WritableDatabase)) {
101                 $X->{$_} = $xap.'::'.$_;
102         }
103         eval 'require '.$X->{WritableDatabase} or die;
104         *sortable_serialise = $xap.'::sortable_serialise';
105         $DB_CREATE_OR_OPEN = eval($xap.'::DB_CREATE_OR_OPEN()');
106         $DB_OPEN = eval($xap.'::DB_OPEN()');
107         my $ver = (eval($xap.'::major_version()') << 16) |
108                 (eval($xap.'::minor_version()') << 8);
109         $DB_NO_SYNC = 0x4 if $ver >= 0x10400;
110         1;
111 }
112
113 sub nodatacow_dir ($) {
114         my ($dir) = @_;
115         opendir my $dh, $dir or die "opendir($dir): $!\n";
116         PublicInbox::Spawn::set_nodatacow(fileno($dh));
117 }
118
119 sub idx_acquire {
120         my ($self) = @_;
121         my $flag;
122         my $dir = $self->xdir;
123         if (need_xapian($self)) {
124                 croak 'already acquired' if $self->{xdb};
125                 load_xapian_writable();
126                 $flag = $self->{creat} ? $DB_CREATE_OR_OPEN : $DB_OPEN;
127         }
128         if ($self->{creat}) {
129                 require File::Path;
130                 $self->lock_acquire;
131
132                 # don't create empty Xapian directories if we don't need Xapian
133                 my $is_shard = defined($self->{shard});
134                 if (!-d $dir && (!$is_shard ||
135                                 ($is_shard && need_xapian($self)))) {
136                         File::Path::mkpath($dir);
137                         nodatacow_dir($dir);
138                 }
139         }
140         return unless defined $flag;
141         $flag |= $DB_NO_SYNC if $self->{ibx}->{-no_sync};
142         my $xdb = eval { ($X->{WritableDatabase})->new($dir, $flag) };
143         if ($@) {
144                 die "Failed opening $dir: ", $@;
145         }
146         $self->{xdb} = $xdb;
147 }
148
149 sub add_val ($$$) {
150         my ($doc, $col, $num) = @_;
151         $num = sortable_serialise($num);
152         $doc->add_value($col, $num);
153 }
154
155 sub term_generator ($) { # write-only
156         my ($self) = @_;
157
158         $self->{term_generator} //= do {
159                 my $tg = $X->{TermGenerator}->new;
160                 $tg->set_stemmer($self->stemmer);
161                 $tg;
162         }
163 }
164
165 sub index_text ($$$$) {
166         my ($self, $text, $wdf_inc, $prefix) = @_;
167         my $tg = term_generator($self); # man Search::Xapian::TermGenerator
168
169         if ($self->{indexlevel} eq 'full') {
170                 $tg->index_text($text, $wdf_inc, $prefix);
171                 $tg->increase_termpos;
172         } else {
173                 $tg->index_text_without_positions($text, $wdf_inc, $prefix);
174         }
175 }
176
177 sub index_headers ($$) {
178         my ($self, $smsg) = @_;
179         my @x = (from => 'A', # Author
180                 subject => 'S', to => 'XTO', cc => 'XCC');
181         while (my ($field, $pfx) = splice(@x, 0, 2)) {
182                 my $val = $smsg->{$field};
183                 index_text($self, $val, 1, $pfx) if $val ne '';
184         }
185 }
186
187 sub index_diff_inc ($$$$) {
188         my ($self, $text, $pfx, $xnq) = @_;
189         if (@$xnq) {
190                 index_text($self, join("\n", @$xnq), 1, 'XNQ');
191                 @$xnq = ();
192         }
193         index_text($self, $text, 1, $pfx);
194 }
195
196 sub index_old_diff_fn {
197         my ($self, $seen, $fa, $fb, $xnq) = @_;
198
199         # no renames or space support for traditional diffs,
200         # find the number of leading common paths to strip:
201         my @fa = split('/', $fa);
202         my @fb = split('/', $fb);
203         while (scalar(@fa) && scalar(@fb)) {
204                 $fa = join('/', @fa);
205                 $fb = join('/', @fb);
206                 if ($fa eq $fb) {
207                         unless ($seen->{$fa}++) {
208                                 index_diff_inc($self, $fa, 'XDFN', $xnq);
209                         }
210                         return 1;
211                 }
212                 shift @fa;
213                 shift @fb;
214         }
215         0;
216 }
217
218 sub index_diff ($$$) {
219         my ($self, $txt, $doc) = @_;
220         my %seen;
221         my $in_diff;
222         my @xnq;
223         my $xnq = \@xnq;
224         foreach (split(/\n/, $txt)) {
225                 if ($in_diff && s/^ //) { # diff context
226                         index_diff_inc($self, $_, 'XDFCTX', $xnq);
227                 } elsif (/^-- $/) { # email signature begins
228                         $in_diff = undef;
229                 } elsif (m!^diff --git "?[^/]+/.+ "?[^/]+/.+\z!) {
230                         # wait until "---" and "+++" to capture filenames
231                         $in_diff = 1;
232                 # traditional diff:
233                 } elsif (m/^diff -(.+) (\S+) (\S+)$/) {
234                         my ($opt, $fa, $fb) = ($1, $2, $3);
235                         push @xnq, $_;
236                         # only support unified:
237                         next unless $opt =~ /[uU]/;
238                         $in_diff = index_old_diff_fn($self, \%seen, $fa, $fb,
239                                                         $xnq);
240                 } elsif (m!^--- ("?[^/]+/.+)!) {
241                         my $fn = $1;
242                         $fn = (split('/', git_unquote($fn), 2))[1];
243                         $seen{$fn}++ or index_diff_inc($self, $fn, 'XDFN', $xnq);
244                         $in_diff = 1;
245                 } elsif (m!^\+\+\+ ("?[^/]+/.+)!)  {
246                         my $fn = $1;
247                         $fn = (split('/', git_unquote($fn), 2))[1];
248                         $seen{$fn}++ or index_diff_inc($self, $fn, 'XDFN', $xnq);
249                         $in_diff = 1;
250                 } elsif (/^--- (\S+)/) {
251                         $in_diff = $1;
252                         push @xnq, $_;
253                 } elsif (defined $in_diff && /^\+\+\+ (\S+)/) {
254                         $in_diff = index_old_diff_fn($self, \%seen, $in_diff,
255                                                         $1, $xnq);
256                 } elsif ($in_diff && s/^\+//) { # diff added
257                         index_diff_inc($self, $_, 'XDFB', $xnq);
258                 } elsif ($in_diff && s/^-//) { # diff removed
259                         index_diff_inc($self, $_, 'XDFA', $xnq);
260                 } elsif (m!^index ([a-f0-9]+)\.\.([a-f0-9]+)!) {
261                         my ($ba, $bb) = ($1, $2);
262                         index_git_blob_id($doc, 'XDFPRE', $ba);
263                         index_git_blob_id($doc, 'XDFPOST', $bb);
264                         $in_diff = 1;
265                 } elsif (/^@@ (?:\S+) (?:\S+) @@\s*$/) {
266                         # traditional diff w/o -p
267                 } elsif (/^@@ (?:\S+) (?:\S+) @@\s*(\S+.*)$/) {
268                         # hunk header context
269                         index_diff_inc($self, $1, 'XDFHH', $xnq);
270                 # ignore the following lines:
271                 } elsif (/^(?:dis)similarity index/ ||
272                                 /^(?:old|new) mode/ ||
273                                 /^(?:deleted|new) file mode/ ||
274                                 /^(?:copy|rename) (?:from|to) / ||
275                                 /^(?:dis)?similarity index / ||
276                                 /^\\ No newline at end of file/ ||
277                                 /^Binary files .* differ/) {
278                         push @xnq, $_;
279                 } elsif ($_ eq '') {
280                         # possible to be in diff context, some mail may be
281                         # stripped by MUA or even GNU diff(1).  "git apply"
282                         # treats a bare "\n" as diff context, too
283                 } else {
284                         push @xnq, $_;
285                         warn "non-diff line: $_\n" if DEBUG && $_ ne '';
286                         $in_diff = undef;
287                 }
288         }
289
290         index_text($self, join("\n", @xnq), 1, 'XNQ');
291 }
292
293 sub index_xapian { # msg_iter callback
294         my $part = $_[0]->[0]; # ignore $depth and $idx
295         my ($self, $doc) = @{$_[1]};
296         my $ct = $part->content_type || 'text/plain';
297         my $fn = $part->filename;
298         if (defined $fn && $fn ne '') {
299                 index_text($self, $fn, 1, 'XFN');
300         }
301         if ($part->{is_submsg}) {
302                 my $mids = mids_for_index($part);
303                 index_ids($self, $doc, $part, $mids);
304                 my $smsg = bless {}, 'PublicInbox::Smsg';
305                 $smsg->populate($part);
306                 index_headers($self, $smsg);
307         }
308
309         my ($s, undef) = msg_part_text($part, $ct);
310         defined $s or return;
311         $_[0]->[0] = $part = undef; # free memory
312
313         # split off quoted and unquoted blocks:
314         my @sections = PublicInbox::MsgIter::split_quotes($s);
315         undef $s; # free memory
316         for my $txt (@sections) {
317                 if ($txt =~ /\A>/) {
318                         index_text($self, $txt, 0, 'XQUOT');
319                 } else {
320                         # does it look like a diff?
321                         if ($txt =~ /^(?:diff|---|\+\+\+) /ms) {
322                                 index_diff($self, $txt, $doc);
323                         } else {
324                                 index_text($self, $txt, 1, 'XNQ');
325                         }
326                 }
327                 undef $txt; # free memory
328         }
329 }
330
331 sub index_ids ($$$$) {
332         my ($self, $doc, $hdr, $mids) = @_;
333         for my $mid (@$mids) {
334                 index_text($self, $mid, 1, 'XM');
335
336                 # because too many Message-IDs are prefixed with
337                 # "Pine.LNX."...
338                 if ($mid =~ /\w{12,}/) {
339                         my @long = ($mid =~ /(\w{3,}+)/g);
340                         index_text($self, join(' ', @long), 1, 'XM');
341                 }
342         }
343         $doc->add_boolean_term('Q' . $_) for @$mids;
344         for my $l ($hdr->header_raw('List-Id')) {
345                 $l =~ /<([^>]+)>/ or next;
346                 my $lid = $1;
347                 $doc->add_boolean_term('G' . $lid);
348                 index_text($self, $lid, 1, 'XL'); # probabilistic
349         }
350 }
351
352 sub add_xapian ($$$$) {
353         my ($self, $eml, $smsg, $mids) = @_;
354         my $doc = $X->{Document}->new;
355         add_val($doc, PublicInbox::Search::TS(), $smsg->{ts});
356         my @ds = gmtime($smsg->{ds});
357         my $yyyymmdd = strftime('%Y%m%d', @ds);
358         add_val($doc, PublicInbox::Search::YYYYMMDD(), $yyyymmdd);
359         my $dt = strftime('%Y%m%d%H%M%S', @ds);
360         add_val($doc, PublicInbox::Search::DT(), $dt);
361         add_val($doc, PublicInbox::Search::BYTES(), $smsg->{bytes});
362         add_val($doc, PublicInbox::Search::UID(), $smsg->{num});
363
364         my $tg = term_generator($self);
365         $tg->set_document($doc);
366         index_headers($self, $smsg);
367
368         msg_iter($eml, \&index_xapian, [ $self, $doc ]);
369         index_ids($self, $doc, $eml, $mids);
370         $smsg->{to} = $smsg->{cc} = ''; # WWW doesn't need these, only NNTP
371         PublicInbox::OverIdx::parse_references($smsg, $eml, $mids);
372         my $data = $smsg->to_doc_data;
373         $doc->set_data($data);
374         if (my $altid = $self->{-altid}) {
375                 foreach my $alt (@$altid) {
376                         my $pfx = $alt->{xprefix};
377                         foreach my $mid (@$mids) {
378                                 my $id = $alt->mid2alt($mid);
379                                 next unless defined $id;
380                                 $doc->add_boolean_term($pfx . $id);
381                         }
382                 }
383         }
384         $self->{xdb}->replace_document($smsg->{num}, $doc);
385 }
386
387 sub _msgmap_init ($) {
388         my ($self) = @_;
389         die "BUG: _msgmap_init is only for v1\n" if $self->{ibx_ver} != 1;
390         $self->{mm} //= eval {
391                 require PublicInbox::Msgmap;
392                 my $rw = $self->{ibx}->{-no_sync} ? 2 : 1;
393                 PublicInbox::Msgmap->new($self->{ibx}->{inboxdir}, $rw);
394         };
395 }
396
397 sub add_message {
398         # mime = PublicInbox::Eml or Email::MIME object
399         my ($self, $mime, $smsg, $sync) = @_;
400         my $mids = mids_for_index($mime);
401         $smsg //= bless { blob => '' }, 'PublicInbox::Smsg'; # test-only compat
402         $smsg->{mid} //= $mids->[0]; # v1 compatibility
403         $smsg->{num} //= do { # v1
404                 _msgmap_init($self);
405                 index_mm($self, $mime, $smsg->{blob}, $sync);
406         };
407
408         # v1 and tests only:
409         $smsg->populate($mime, $sync);
410         $smsg->{bytes} //= length($mime->as_string);
411
412         eval {
413                 # order matters, overview stores every possible piece of
414                 # data in doc_data (deflated).  Xapian only stores a subset
415                 # of the fields which exist in over.sqlite3.  We may stop
416                 # storing doc_data in Xapian sometime after we get multi-inbox
417                 # search working.
418                 if (my $over = $self->{over}) { # v1 only
419                         $over->add_overview($mime, $smsg);
420                 }
421                 if (need_xapian($self)) {
422                         add_xapian($self, $mime, $smsg, $mids);
423                 }
424         };
425
426         if ($@) {
427                 warn "failed to index message <".join('> <',@$mids).">: $@\n";
428                 return undef;
429         }
430         $smsg->{num};
431 }
432
433 sub xdb_remove {
434         my ($self, $oid, @removed) = @_;
435         my $xdb = $self->{xdb} or return;
436         for my $num (@removed) {
437                 my $doc = eval { $xdb->get_document($num) };
438                 unless ($doc) {
439                         warn "E: $@\n" if $@;
440                         warn "E: #$num $oid missing in Xapian\n";
441                         next;
442                 }
443                 my $smsg = bless {}, 'PublicInbox::Smsg';
444                 $smsg->load_expand($doc);
445                 my $blob = $smsg->{blob} // '(unset)';
446                 if ($blob eq $oid) {
447                         $xdb->delete_document($num);
448                 } else {
449                         warn "E: #$num $oid != $blob in Xapian\n";
450                 }
451         }
452 }
453
454 sub remove_by_oid {
455         my ($self, $oid, $num) = @_;
456         die "BUG: remove_by_oid is v2-only\n" if $self->{over};
457         $self->begin_txn_lazy;
458         xdb_remove($self, $oid, $num) if need_xapian($self);
459 }
460
461 sub index_git_blob_id {
462         my ($doc, $pfx, $objid) = @_;
463
464         my $len = length($objid);
465         for (my $len = length($objid); $len >= 7; ) {
466                 $doc->add_term($pfx.$objid);
467                 $objid = substr($objid, 0, --$len);
468         }
469 }
470
471 # v1 only
472 sub unindex_eml {
473         my ($self, $oid, $eml) = @_;
474         my $mids = mids($eml);
475         my $nr = 0;
476         my %tmp;
477         for my $mid (@$mids) {
478                 my @removed = eval { $self->{over}->remove_oid($oid, $mid) };
479                 if ($@) {
480                         warn "E: failed to remove <$mid> from overview: $@\n";
481                 } else {
482                         $nr += scalar @removed;
483                         $tmp{$_}++ for @removed;
484                 }
485         }
486         if (!$nr) {
487                 $mids = join('> <', @$mids);
488                 warn "W: <$mids> missing for removal from overview\n";
489         }
490         while (my ($num, $nr) = each %tmp) {
491                 warn "BUG: $num appears >1 times ($nr) for $oid\n" if $nr != 1;
492         }
493         if ($nr) {
494                 $self->{mm}->num_delete($_) for (keys %tmp);
495         } else { # just in case msgmap and over.sqlite3 become desynched:
496                 $self->{mm}->mid_delete($mids->[0]);
497         }
498         xdb_remove($self, $oid, keys %tmp) if need_xapian($self);
499 }
500
501 sub index_mm {
502         my ($self, $mime, $oid, $sync) = @_;
503         my $mids = mids($mime);
504         my $mm = $self->{mm};
505         if ($sync->{reindex}) {
506                 my $over = $self->{over};
507                 for my $mid (@$mids) {
508                         my ($num, undef) = $over->num_mid0_for_oid($oid, $mid);
509                         return $num if defined $num;
510                 }
511                 $mm->num_for($mids->[0]) // $mm->mid_insert($mids->[0]);
512         } else {
513                 # fallback to num_for since filters like RubyLang set the number
514                 $mm->mid_insert($mids->[0]) // $mm->num_for($mids->[0]);
515         }
516 }
517
518 # returns the number of bytes to add if given a non-CRLF arg
519 sub crlf_adjust ($) {
520         if (index($_[0], "\r\n") < 0) {
521                 # common case is LF-only, every \n needs an \r;
522                 # so favor a cheap tr// over an expensive m//g
523                 $_[0] =~ tr/\n/\n/;
524         } else { # count number of '\n' w/o '\r', expensive:
525                 scalar(my @n = ($_[0] =~ m/(?<!\r)\n/g));
526         }
527 }
528
529 sub index_both { # git->cat_async callback
530         my ($bref, $oid, $type, $size, $sync) = @_;
531         my ($nr, $max) = @$sync{qw(nr max)};
532         ++$$nr;
533         $$max -= $size;
534         $size += crlf_adjust($$bref);
535         my $smsg = bless { bytes => $size, blob => $oid }, 'PublicInbox::Smsg';
536         my $self = $sync->{sidx};
537         my $eml = PublicInbox::Eml->new($bref);
538         $smsg->{num} = index_mm($self, $eml, $oid, $sync) or
539                 die "E: could not generate NNTP article number for $oid";
540         add_message($self, $eml, $smsg, $sync);
541 }
542
543 sub unindex_both { # git->cat_async callback
544         my ($bref, $oid, $type, $size, $self) = @_;
545         unindex_eml($self, $oid, PublicInbox::Eml->new($bref));
546 }
547
548 # called by public-inbox-index
549 sub index_sync {
550         my ($self, $opts) = @_;
551         delete $self->{lock_path} if $opts->{-skip_lock};
552         $self->{ibx}->with_umask(\&_index_sync, $self, $opts);
553         if ($opts->{reindex}) {
554                 my %again = %$opts;
555                 delete @again{qw(rethread reindex)};
556                 index_sync($self, \%again);
557         }
558 }
559
560 sub check_size { # check_async cb for -index --max-size=...
561         my ($oid, $type, $size, $arg, $git) = @_;
562         (($type // '') eq 'blob') or die "E: bad $oid in $git->{git_dir}";
563         if ($size <= $arg->{index_max_size}) {
564                 $git->cat_async($oid, $arg->{index_oid}, $arg);
565         } else {
566                 warn "W: skipping $oid ($size > $arg->{index_max_size})\n";
567         }
568 }
569
570 sub v1_checkpoint ($$;$) {
571         my ($self, $sync, $stk) = @_;
572         $self->{ibx}->git->check_async_wait;
573         $self->{ibx}->git->cat_async_wait;
574
575         # latest_cmt may be undef
576         my $newest = $stk ? $stk->{latest_cmt} : undef;
577         if ($newest) {
578                 my $cur = $self->{mm}->last_commit || '';
579                 if (need_update($self, $cur, $newest)) {
580                         $self->{mm}->last_commit($newest);
581                 }
582         } else {
583                 ${$sync->{max}} = $BATCH_BYTES;
584         }
585
586         $self->{mm}->{dbh}->commit;
587         if ($newest && need_xapian($self)) {
588                 my $cur = $self->{xdb}->get_metadata('last_commit');
589                 if (need_update($self, $cur, $newest)) {
590                         $self->{xdb}->set_metadata('last_commit', $newest);
591                 }
592         }
593
594         $self->{over}->rethread_done($sync->{-opt}) if $newest; # all done
595         commit_txn_lazy($self);
596         $self->{ibx}->git->cleanup;
597         my $nr = ${$sync->{nr}};
598         idx_release($self, $nr);
599         # let another process do some work...
600         if (my $pr = $sync->{-opt}->{-progress}) {
601                 $pr->("indexed $nr/$sync->{ntodo}\n") if $nr;
602         }
603         if (!$stk) { # more to come
604                 begin_txn_lazy($self);
605                 $self->{mm}->{dbh}->begin_work;
606         }
607 }
608
609 # only for v1
610 sub process_stack {
611         my ($self, $sync, $stk) = @_;
612         my $git = $self->{ibx}->git;
613         my $max = $BATCH_BYTES;
614         my $nr = 0;
615         $sync->{nr} = \$nr;
616         $sync->{max} = \$max;
617         $sync->{sidx} = $self;
618
619         $self->{mm}->{dbh}->begin_work;
620         if (my @leftovers = keys %{delete($sync->{D}) // {}}) {
621                 warn('W: unindexing '.scalar(@leftovers)." leftovers\n");
622                 for my $oid (@leftovers) {
623                         $oid = unpack('H*', $oid);
624                         $git->cat_async($oid, \&unindex_both, $self);
625                 }
626         }
627         if ($sync->{index_max_size} = $self->{ibx}->{index_max_size}) {
628                 $sync->{index_oid} = \&index_both;
629         }
630         while (my ($f, $at, $ct, $oid) = $stk->pop_rec) {
631                 if ($f eq 'm') {
632                         my $arg = { %$sync, autime => $at, cotime => $ct };
633                         if ($sync->{index_max_size}) {
634                                 $git->check_async($oid, \&check_size, $arg);
635                         } else {
636                                 $git->cat_async($oid, \&index_both, $arg);
637                         }
638                         v1_checkpoint($self, $sync) if $max <= 0;
639                 } elsif ($f eq 'd') {
640                         $git->cat_async($oid, \&unindex_both, $self);
641                 }
642         }
643         v1_checkpoint($self, $sync, $stk);
644 }
645
646 sub log2stack ($$$$) {
647         my ($sync, $git, $range, $ibx) = @_;
648         my $D = $sync->{D}; # OID_BIN => NR (if reindexing, undef otherwise)
649         my ($add, $del);
650         if ($ibx->version == 1) {
651                 my $path = $hex.'{2}/'.$hex.'{38}';
652                 $add = qr!\A:000000 100644 \S+ ($OID) A\t$path$!;
653                 $del = qr!\A:100644 000000 ($OID) \S+ D\t$path$!;
654         } else {
655                 $del = qr!\A:\d{6} 100644 $OID ($OID) [AM]\td$!;
656                 $add = qr!\A:\d{6} 100644 $OID ($OID) [AM]\tm$!;
657         }
658
659         # Count the new files so they can be added newest to oldest
660         # and still have numbers increasing from oldest to newest
661         my $fh = $git->popen(qw(log --raw -r --pretty=tformat:%at-%ct-%H
662                                 --no-notes --no-color --no-renames --no-abbrev),
663                                 $range);
664         my ($at, $ct, $stk);
665         while (<$fh>) {
666                 if (/\A([0-9]+)-([0-9]+)-($OID)$/o) {
667                         ($at, $ct) = ($1 + 0, $2 + 0);
668                         $stk //= PublicInbox::IdxStack->new($3);
669                 } elsif (/$del/) {
670                         my $oid = $1;
671                         if ($D) { # reindex case
672                                 $D->{pack('H*', $oid)}++;
673                         } else { # non-reindex case:
674                                 $stk->push_rec('d', $at, $ct, $oid);
675                         }
676                 } elsif (/$add/) {
677                         my $oid = $1;
678                         if ($D) {
679                                 my $oid_bin = pack('H*', $oid);
680                                 my $nr = --$D->{$oid_bin};
681                                 delete($D->{$oid_bin}) if $nr <= 0;
682
683                                 # nr < 0 (-1) means it never existed
684                                 $stk->push_rec('m', $at, $ct, $oid) if $nr < 0;
685                         } else {
686                                 $stk->push_rec('m', $at, $ct, $oid);
687                         }
688                 }
689         }
690         close $fh or die "git log failed: \$?=$?";
691         $stk //= PublicInbox::IdxStack->new;
692         $stk->read_prepare;
693 }
694
695 sub prepare_stack ($$$) {
696         my ($self, $sync, $range) = @_;
697         my $git = $self->{ibx}->git;
698
699         if (index($range, '..') < 0) {
700                 # don't show annoying git errors to users who run -index
701                 # on empty inboxes
702                 $git->qx(qw(rev-parse -q --verify), "$range^0");
703                 return PublicInbox::IdxStack->new->read_prepare if $?;
704         }
705         $sync->{D} = $sync->{reindex} ? {} : undef; # OID_BIN => NR
706         log2stack($sync, $git, $range, $self->{ibx});
707 }
708
709 # --is-ancestor requires git 1.8.0+
710 sub is_ancestor ($$$) {
711         my ($git, $cur, $tip) = @_;
712         return 0 unless $git->check($cur);
713         my $cmd = [ 'git', "--git-dir=$git->{git_dir}",
714                 qw(merge-base --is-ancestor), $cur, $tip ];
715         my $pid = spawn($cmd);
716         waitpid($pid, 0) == $pid or die join(' ', @$cmd) .' did not finish';
717         $? == 0;
718 }
719
720 sub need_update ($$$) {
721         my ($self, $cur, $new) = @_;
722         my $git = $self->{ibx}->git;
723         return 1 if $cur && !is_ancestor($git, $cur, $new);
724         my $range = $cur eq '' ? $new : "$cur..$new";
725         chomp(my $n = $git->qx(qw(rev-list --count), $range));
726         ($n eq '' || $n > 0);
727 }
728
729 # The last git commit we indexed with Xapian or SQLite (msgmap)
730 # This needs to account for cases where Xapian or SQLite is
731 # out-of-date with respect to the other.
732 sub _last_x_commit {
733         my ($self, $mm) = @_;
734         my $lm = $mm->last_commit || '';
735         my $lx = '';
736         if (need_xapian($self)) {
737                 $lx = $self->{xdb}->get_metadata('last_commit') || '';
738         } else {
739                 $lx = $lm;
740         }
741         # Use last_commit from msgmap if it is older or unset
742         if (!$lm || ($lx && $lm && is_ancestor($self->{ibx}->git, $lm, $lx))) {
743                 $lx = $lm;
744         }
745         $lx;
746 }
747
748 sub reindex_from ($$) {
749         my ($reindex, $last_commit) = @_;
750         return $last_commit unless $reindex;
751         ref($reindex) eq 'HASH' ? $reindex->{from} : '';
752 }
753
754 # indexes all unindexed messages (v1 only)
755 sub _index_sync {
756         my ($self, $opts) = @_;
757         my $tip = $opts->{ref} || 'HEAD';
758         my $git = $self->{ibx}->git;
759         $git->batch_prepare;
760         my $pr = $opts->{-progress};
761         my $sync = { reindex => $opts->{reindex}, -opt => $opts };
762         my $xdb = $self->begin_txn_lazy;
763         $self->{over}->rethread_prepare($opts);
764         my $mm = _msgmap_init($self);
765         if ($sync->{reindex}) {
766                 my $last = $mm->last_commit;
767                 if ($last) {
768                         $tip = $last;
769                 } else {
770                         # somebody just blindly added --reindex when indexing
771                         # for the first time, allow it:
772                         undef $sync->{reindex};
773                 }
774         }
775         my $last_commit = _last_x_commit($self, $mm);
776         my $lx = reindex_from($sync->{reindex}, $last_commit);
777         my $range = $lx eq '' ? $tip : "$lx..$tip";
778         $pr->("counting changes\n\t$range ... ") if $pr;
779         my $stk = prepare_stack($self, $sync, $range);
780         $sync->{ntodo} = $stk ? $stk->num_records : 0;
781         $pr->("$sync->{ntodo}\n") if $pr; # continue previous line
782         process_stack($self, $sync, $stk);
783 }
784
785 sub DESTROY {
786         # order matters for unlocking
787         $_[0]->{xdb} = undef;
788         $_[0]->{lockfh} = undef;
789 }
790
791 # remote_* subs are only used by SearchIdxPart
792 sub remote_commit {
793         my ($self) = @_;
794         if (my $w = $self->{w}) {
795                 print $w "commit\n" or die "failed to write commit: $!";
796         } else {
797                 $self->commit_txn_lazy;
798         }
799 }
800
801 sub remote_close {
802         my ($self) = @_;
803         if (my $w = delete $self->{w}) {
804                 my $pid = delete $self->{pid} or die "no process to wait on\n";
805                 print $w "close\n" or die "failed to write to pid:$pid: $!\n";
806                 close $w or die "failed to close pipe for pid:$pid: $!\n";
807                 waitpid($pid, 0) == $pid or die "remote process did not finish";
808                 $? == 0 or die ref($self)." pid:$pid exited with: $?";
809         } else {
810                 die "transaction in progress $self\n" if $self->{txn};
811                 idx_release($self) if $self->{xdb};
812         }
813 }
814
815 sub remote_remove {
816         my ($self, $oid, $num) = @_;
817         if (my $w = $self->{w}) {
818                 # triggers remove_by_oid in a shard
819                 print $w "D $oid $num\n" or die "failed to write remove $!";
820         } else {
821                 $self->remove_by_oid($oid, $num);
822         }
823 }
824
825 sub _begin_txn {
826         my ($self) = @_;
827         my $xdb = $self->{xdb} || idx_acquire($self);
828         $self->{over}->begin_lazy if $self->{over};
829         $xdb->begin_transaction if $xdb;
830         $self->{txn} = 1;
831         $xdb;
832 }
833
834 sub begin_txn_lazy {
835         my ($self) = @_;
836         $self->{ibx}->with_umask(\&_begin_txn, $self) if !$self->{txn};
837 }
838
839 # store 'indexlevel=medium' in v2 shard=0 and v1 (only one shard)
840 # This metadata is read by Admin::detect_indexlevel:
841 sub set_indexlevel {
842         my ($self) = @_;
843
844         if (!$self->{shard} && # undef or 0, not >0
845                         delete($self->{-set_indexlevel_once})) {
846                 my $xdb = $self->{xdb};
847                 my $level = $xdb->get_metadata('indexlevel');
848                 if (!$level || $level ne 'medium') {
849                         $xdb->set_metadata('indexlevel', 'medium');
850                 }
851         }
852 }
853
854 sub _commit_txn {
855         my ($self) = @_;
856         if (my $xdb = $self->{xdb}) {
857                 set_indexlevel($self);
858                 $xdb->commit_transaction;
859         }
860         $self->{over}->commit_lazy if $self->{over};
861 }
862
863 sub commit_txn_lazy {
864         my ($self) = @_;
865         delete($self->{txn}) and
866                 $self->{ibx}->with_umask(\&_commit_txn, $self);
867 }
868
869 sub worker_done {
870         my ($self) = @_;
871         if (need_xapian($self)) {
872                 die "$$ $0 xdb not released\n" if $self->{xdb};
873         }
874         die "$$ $0 still in transaction\n" if $self->{txn};
875 }
876
877 1;