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