]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/SearchIdx.pm
support setting No_COW on Perl <5.22
[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 nodatacow_dir);
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);
25 my $X = \%PublicInbox::Search::X;
26 my ($DB_CREATE_OR_OPEN, $DB_OPEN);
27 our $DB_NO_SYNC = 0;
28 our $BATCH_BYTES = $ENV{XAPIAN_FLUSH_THRESHOLD} ? 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
35 sub new {
36         my ($class, $ibx, $creat, $shard) = @_;
37         ref $ibx or die "BUG: expected PublicInbox::Inbox object: $ibx";
38         my $levels = qr/\A(?:full|medium|basic)\z/;
39         my $inboxdir = $ibx->{inboxdir};
40         my $version = $ibx->version;
41         my $indexlevel = 'full';
42         my $altid = $ibx->{altid};
43         if ($altid) {
44                 require PublicInbox::AltId;
45                 $altid = [ map { PublicInbox::AltId->new($ibx, $_); } @$altid ];
46         }
47         if ($ibx->{indexlevel}) {
48                 if ($ibx->{indexlevel} =~ $levels) {
49                         $indexlevel = $ibx->{indexlevel};
50                 } else {
51                         die("Invalid indexlevel $ibx->{indexlevel}\n");
52                 }
53         }
54         $ibx = PublicInbox::InboxWritable->new($ibx);
55         my $self = bless {
56                 ibx => $ibx,
57                 xpfx => $inboxdir, # for xpfx_init
58                 -altid => $altid,
59                 ibx_ver => $version,
60                 indexlevel => $indexlevel,
61         }, $class;
62         $self->xpfx_init;
63         $self->{-set_indexlevel_once} = 1 if $indexlevel eq 'medium';
64         $ibx->umask_prepare;
65         if ($version == 1) {
66                 $self->{lock_path} = "$inboxdir/ssoma.lock";
67                 my $dir = $self->xdir;
68                 $self->{over} = PublicInbox::OverIdx->new("$dir/over.sqlite3");
69                 $self->{over}->{-no_fsync} = 1 if $ibx->{-no_fsync};
70                 $self->{index_max_size} = $ibx->{index_max_size};
71         } elsif ($version == 2) {
72                 defined $shard or die "shard is required for v2\n";
73                 # shard is a number
74                 $self->{shard} = $shard;
75                 $self->{lock_path} = undef;
76         } else {
77                 die "unsupported inbox version=$version\n";
78         }
79         $self->{creat} = ($creat || 0) == 1;
80         $self;
81 }
82
83 sub need_xapian ($) { $_[0]->{indexlevel} =~ $xapianlevels }
84
85 sub idx_release {
86         my ($self, $wake) = @_;
87         if (need_xapian($self)) {
88                 my $xdb = delete $self->{xdb} or croak 'not acquired';
89                 $xdb->close;
90         }
91         $self->lock_release($wake) if $self->{creat};
92         undef;
93 }
94
95 sub load_xapian_writable () {
96         return 1 if $X->{WritableDatabase};
97         PublicInbox::Search::load_xapian() or return;
98         my $xap = $PublicInbox::Search::Xap;
99         for (qw(Document TermGenerator WritableDatabase)) {
100                 $X->{$_} = $xap.'::'.$_;
101         }
102         eval 'require '.$X->{WritableDatabase} or die;
103         *sortable_serialise = $xap.'::sortable_serialise';
104         $DB_CREATE_OR_OPEN = eval($xap.'::DB_CREATE_OR_OPEN()');
105         $DB_OPEN = eval($xap.'::DB_OPEN()');
106         my $ver = (eval($xap.'::major_version()') << 16) |
107                 (eval($xap.'::minor_version()') << 8);
108         $DB_NO_SYNC = 0x4 if $ver >= 0x10400;
109         1;
110 }
111
112 sub idx_acquire {
113         my ($self) = @_;
114         my $flag;
115         my $dir = $self->xdir;
116         if (need_xapian($self)) {
117                 croak 'already acquired' if $self->{xdb};
118                 load_xapian_writable();
119                 $flag = $self->{creat} ? $DB_CREATE_OR_OPEN : $DB_OPEN;
120         }
121         if ($self->{creat}) {
122                 require File::Path;
123                 $self->lock_acquire;
124
125                 # don't create empty Xapian directories if we don't need Xapian
126                 my $is_shard = defined($self->{shard});
127                 if (!-d $dir && (!$is_shard ||
128                                 ($is_shard && need_xapian($self)))) {
129                         File::Path::mkpath($dir);
130                         nodatacow_dir($dir);
131                 }
132         }
133         return unless defined $flag;
134         $flag |= $DB_NO_SYNC if $self->{ibx}->{-no_fsync};
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, $eml, $smsg, $mids) = @_;
347         my $doc = $X->{Document}->new;
348         add_val($doc, PublicInbox::Search::TS(), $smsg->{ts});
349         my @ds = gmtime($smsg->{ds});
350         my $yyyymmdd = strftime('%Y%m%d', @ds);
351         add_val($doc, PublicInbox::Search::YYYYMMDD(), $yyyymmdd);
352         my $dt = strftime('%Y%m%d%H%M%S', @ds);
353         add_val($doc, PublicInbox::Search::DT(), $dt);
354         add_val($doc, PublicInbox::Search::BYTES(), $smsg->{bytes});
355         add_val($doc, PublicInbox::Search::UID(), $smsg->{num});
356
357         my $tg = term_generator($self);
358         $tg->set_document($doc);
359         index_headers($self, $smsg);
360
361         msg_iter($eml, \&index_xapian, [ $self, $doc ]);
362         index_ids($self, $doc, $eml, $mids);
363         $smsg->{to} = $smsg->{cc} = ''; # WWW doesn't need these, only NNTP
364         PublicInbox::OverIdx::parse_references($smsg, $eml, $mids);
365         my $data = $smsg->to_doc_data;
366         $doc->set_data($data);
367         if (my $altid = $self->{-altid}) {
368                 foreach my $alt (@$altid) {
369                         my $pfx = $alt->{xprefix};
370                         foreach my $mid (@$mids) {
371                                 my $id = $alt->mid2alt($mid);
372                                 next unless defined $id;
373                                 $doc->add_boolean_term($pfx . $id);
374                         }
375                 }
376         }
377         $self->{xdb}->replace_document($smsg->{num}, $doc);
378 }
379
380 sub _msgmap_init ($) {
381         my ($self) = @_;
382         die "BUG: _msgmap_init is only for v1\n" if $self->{ibx_ver} != 1;
383         $self->{mm} //= eval {
384                 require PublicInbox::Msgmap;
385                 my $rw = $self->{ibx}->{-no_fsync} ? 2 : 1;
386                 PublicInbox::Msgmap->new($self->{ibx}->{inboxdir}, $rw);
387         };
388 }
389
390 sub add_message {
391         # mime = PublicInbox::Eml or Email::MIME object
392         my ($self, $mime, $smsg, $sync) = @_;
393         my $mids = mids_for_index($mime);
394         $smsg //= bless { blob => '' }, 'PublicInbox::Smsg'; # test-only compat
395         $smsg->{mid} //= $mids->[0]; # v1 compatibility
396         $smsg->{num} //= do { # v1
397                 _msgmap_init($self);
398                 index_mm($self, $mime, $smsg->{blob}, $sync);
399         };
400
401         # v1 and tests only:
402         $smsg->populate($mime, $sync);
403         $smsg->{bytes} //= length($mime->as_string);
404
405         eval {
406                 # order matters, overview stores every possible piece of
407                 # data in doc_data (deflated).  Xapian only stores a subset
408                 # of the fields which exist in over.sqlite3.  We may stop
409                 # storing doc_data in Xapian sometime after we get multi-inbox
410                 # search working.
411                 if (my $over = $self->{over}) { # v1 only
412                         $over->add_overview($mime, $smsg);
413                 }
414                 if (need_xapian($self)) {
415                         add_xapian($self, $mime, $smsg, $mids);
416                 }
417         };
418
419         if ($@) {
420                 warn "failed to index message <".join('> <',@$mids).">: $@\n";
421                 return undef;
422         }
423         $smsg->{num};
424 }
425
426 sub xdb_remove {
427         my ($self, $oid, @removed) = @_;
428         my $xdb = $self->{xdb} or return;
429         for my $num (@removed) {
430                 my $doc = eval { $xdb->get_document($num) };
431                 unless ($doc) {
432                         warn "E: $@\n" if $@;
433                         warn "E: #$num $oid missing in Xapian\n";
434                         next;
435                 }
436                 my $smsg = bless {}, 'PublicInbox::Smsg';
437                 $smsg->load_expand($doc);
438                 my $blob = $smsg->{blob} // '(unset)';
439                 if ($blob eq $oid) {
440                         $xdb->delete_document($num);
441                 } else {
442                         warn "E: #$num $oid != $blob in Xapian\n";
443                 }
444         }
445 }
446
447 sub remove_by_oid {
448         my ($self, $oid, $num) = @_;
449         die "BUG: remove_by_oid is v2-only\n" if $self->{over};
450         $self->begin_txn_lazy;
451         xdb_remove($self, $oid, $num) if need_xapian($self);
452 }
453
454 sub index_git_blob_id {
455         my ($doc, $pfx, $objid) = @_;
456
457         my $len = length($objid);
458         for (my $len = length($objid); $len >= 7; ) {
459                 $doc->add_term($pfx.$objid);
460                 $objid = substr($objid, 0, --$len);
461         }
462 }
463
464 # v1 only
465 sub unindex_eml {
466         my ($self, $oid, $eml) = @_;
467         my $mids = mids($eml);
468         my $nr = 0;
469         my %tmp;
470         for my $mid (@$mids) {
471                 my @removed = eval { $self->{over}->remove_oid($oid, $mid) };
472                 if ($@) {
473                         warn "E: failed to remove <$mid> from overview: $@\n";
474                 } else {
475                         $nr += scalar @removed;
476                         $tmp{$_}++ for @removed;
477                 }
478         }
479         if (!$nr) {
480                 $mids = join('> <', @$mids);
481                 warn "W: <$mids> missing for removal from overview\n";
482         }
483         while (my ($num, $nr) = each %tmp) {
484                 warn "BUG: $num appears >1 times ($nr) for $oid\n" if $nr != 1;
485         }
486         if ($nr) {
487                 $self->{mm}->num_delete($_) for (keys %tmp);
488         } else { # just in case msgmap and over.sqlite3 become desynched:
489                 $self->{mm}->mid_delete($mids->[0]);
490         }
491         xdb_remove($self, $oid, keys %tmp) if need_xapian($self);
492 }
493
494 sub index_mm {
495         my ($self, $mime, $oid, $sync) = @_;
496         my $mids = mids($mime);
497         my $mm = $self->{mm};
498         if ($sync->{reindex}) {
499                 my $over = $self->{over};
500                 for my $mid (@$mids) {
501                         my ($num, undef) = $over->num_mid0_for_oid($oid, $mid);
502                         return $num if defined $num;
503                 }
504                 $mm->num_for($mids->[0]) // $mm->mid_insert($mids->[0]);
505         } else {
506                 # fallback to num_for since filters like RubyLang set the number
507                 $mm->mid_insert($mids->[0]) // $mm->num_for($mids->[0]);
508         }
509 }
510
511 # returns the number of bytes to add if given a non-CRLF arg
512 sub crlf_adjust ($) {
513         if (index($_[0], "\r\n") < 0) {
514                 # common case is LF-only, every \n needs an \r;
515                 # so favor a cheap tr// over an expensive m//g
516                 $_[0] =~ tr/\n/\n/;
517         } else { # count number of '\n' w/o '\r', expensive:
518                 scalar(my @n = ($_[0] =~ m/(?<!\r)\n/g));
519         }
520 }
521
522 sub index_both { # git->cat_async callback
523         my ($bref, $oid, $type, $size, $sync) = @_;
524         my ($nr, $max) = @$sync{qw(nr max)};
525         ++$$nr;
526         $$max -= $size;
527         $size += crlf_adjust($$bref);
528         my $smsg = bless { bytes => $size, blob => $oid }, 'PublicInbox::Smsg';
529         my $self = $sync->{sidx};
530         my $eml = PublicInbox::Eml->new($bref);
531         $smsg->{num} = index_mm($self, $eml, $oid, $sync) or
532                 die "E: could not generate NNTP article number for $oid";
533         add_message($self, $eml, $smsg, $sync);
534 }
535
536 sub unindex_both { # git->cat_async callback
537         my ($bref, $oid, $type, $size, $self) = @_;
538         unindex_eml($self, $oid, PublicInbox::Eml->new($bref));
539 }
540
541 # called by public-inbox-index
542 sub index_sync {
543         my ($self, $opts) = @_;
544         delete $self->{lock_path} if $opts->{-skip_lock};
545         $self->{ibx}->with_umask(\&_index_sync, $self, $opts);
546         if ($opts->{reindex}) {
547                 my %again = %$opts;
548                 delete @again{qw(rethread reindex)};
549                 index_sync($self, \%again);
550         }
551 }
552
553 sub check_size { # check_async cb for -index --max-size=...
554         my ($oid, $type, $size, $arg, $git) = @_;
555         (($type // '') eq 'blob') or die "E: bad $oid in $git->{git_dir}";
556         if ($size <= $arg->{index_max_size}) {
557                 $git->cat_async($oid, $arg->{index_oid}, $arg);
558         } else {
559                 warn "W: skipping $oid ($size > $arg->{index_max_size})\n";
560         }
561 }
562
563 sub v1_checkpoint ($$;$) {
564         my ($self, $sync, $stk) = @_;
565         $self->{ibx}->git->check_async_wait;
566         $self->{ibx}->git->cat_async_wait;
567
568         # latest_cmt may be undef
569         my $newest = $stk ? $stk->{latest_cmt} : undef;
570         if ($newest) {
571                 my $cur = $self->{mm}->last_commit || '';
572                 if (need_update($self, $cur, $newest)) {
573                         $self->{mm}->last_commit($newest);
574                 }
575         } else {
576                 ${$sync->{max}} = $BATCH_BYTES;
577         }
578
579         $self->{mm}->{dbh}->commit;
580         if ($newest && need_xapian($self)) {
581                 my $cur = $self->{xdb}->get_metadata('last_commit');
582                 if (need_update($self, $cur, $newest)) {
583                         $self->{xdb}->set_metadata('last_commit', $newest);
584                 }
585         }
586
587         $self->{over}->rethread_done($sync->{-opt}) if $newest; # all done
588         commit_txn_lazy($self);
589         $self->{ibx}->git->cleanup;
590         my $nr = ${$sync->{nr}};
591         idx_release($self, $nr);
592         # let another process do some work...
593         if (my $pr = $sync->{-opt}->{-progress}) {
594                 $pr->("indexed $nr/$sync->{ntodo}\n") if $nr;
595         }
596         if (!$stk) { # more to come
597                 begin_txn_lazy($self);
598                 $self->{mm}->{dbh}->begin_work;
599         }
600 }
601
602 # only for v1
603 sub process_stack {
604         my ($self, $sync, $stk) = @_;
605         my $git = $self->{ibx}->git;
606         my $max = $BATCH_BYTES;
607         my $nr = 0;
608         $sync->{nr} = \$nr;
609         $sync->{max} = \$max;
610         $sync->{sidx} = $self;
611
612         $self->{mm}->{dbh}->begin_work;
613         if (my @leftovers = keys %{delete($sync->{D}) // {}}) {
614                 warn('W: unindexing '.scalar(@leftovers)." leftovers\n");
615                 for my $oid (@leftovers) {
616                         $oid = unpack('H*', $oid);
617                         $git->cat_async($oid, \&unindex_both, $self);
618                 }
619         }
620         if ($sync->{index_max_size} = $self->{ibx}->{index_max_size}) {
621                 $sync->{index_oid} = \&index_both;
622         }
623         while (my ($f, $at, $ct, $oid) = $stk->pop_rec) {
624                 if ($f eq 'm') {
625                         my $arg = { %$sync, autime => $at, cotime => $ct };
626                         if ($sync->{index_max_size}) {
627                                 $git->check_async($oid, \&check_size, $arg);
628                         } else {
629                                 $git->cat_async($oid, \&index_both, $arg);
630                         }
631                         v1_checkpoint($self, $sync) if $max <= 0;
632                 } elsif ($f eq 'd') {
633                         $git->cat_async($oid, \&unindex_both, $self);
634                 }
635         }
636         v1_checkpoint($self, $sync, $stk);
637 }
638
639 sub log2stack ($$$$) {
640         my ($sync, $git, $range, $ibx) = @_;
641         my $D = $sync->{D}; # OID_BIN => NR (if reindexing, undef otherwise)
642         my ($add, $del);
643         if ($ibx->version == 1) {
644                 my $path = $hex.'{2}/'.$hex.'{38}';
645                 $add = qr!\A:000000 100644 \S+ ($OID) A\t$path$!;
646                 $del = qr!\A:100644 000000 ($OID) \S+ D\t$path$!;
647         } else {
648                 $del = qr!\A:\d{6} 100644 $OID ($OID) [AM]\td$!;
649                 $add = qr!\A:\d{6} 100644 $OID ($OID) [AM]\tm$!;
650         }
651
652         # Count the new files so they can be added newest to oldest
653         # and still have numbers increasing from oldest to newest
654         my $fh = $git->popen(qw(log --raw -r --pretty=tformat:%at-%ct-%H
655                                 --no-notes --no-color --no-renames --no-abbrev),
656                                 $range);
657         my ($at, $ct, $stk);
658         while (<$fh>) {
659                 if (/\A([0-9]+)-([0-9]+)-($OID)$/o) {
660                         ($at, $ct) = ($1 + 0, $2 + 0);
661                         $stk //= PublicInbox::IdxStack->new($3);
662                 } elsif (/$del/) {
663                         my $oid = $1;
664                         if ($D) { # reindex case
665                                 $D->{pack('H*', $oid)}++;
666                         } else { # non-reindex case:
667                                 $stk->push_rec('d', $at, $ct, $oid);
668                         }
669                 } elsif (/$add/) {
670                         my $oid = $1;
671                         if ($D) {
672                                 my $oid_bin = pack('H*', $oid);
673                                 my $nr = --$D->{$oid_bin};
674                                 delete($D->{$oid_bin}) if $nr <= 0;
675
676                                 # nr < 0 (-1) means it never existed
677                                 $stk->push_rec('m', $at, $ct, $oid) if $nr < 0;
678                         } else {
679                                 $stk->push_rec('m', $at, $ct, $oid);
680                         }
681                 }
682         }
683         close $fh or die "git log failed: \$?=$?";
684         $stk //= PublicInbox::IdxStack->new;
685         $stk->read_prepare;
686 }
687
688 sub prepare_stack ($$$) {
689         my ($self, $sync, $range) = @_;
690         my $git = $self->{ibx}->git;
691
692         if (index($range, '..') < 0) {
693                 # don't show annoying git errors to users who run -index
694                 # on empty inboxes
695                 $git->qx(qw(rev-parse -q --verify), "$range^0");
696                 return PublicInbox::IdxStack->new->read_prepare if $?;
697         }
698         $sync->{D} = $sync->{reindex} ? {} : undef; # OID_BIN => NR
699         log2stack($sync, $git, $range, $self->{ibx});
700 }
701
702 # --is-ancestor requires git 1.8.0+
703 sub is_ancestor ($$$) {
704         my ($git, $cur, $tip) = @_;
705         return 0 unless $git->check($cur);
706         my $cmd = [ 'git', "--git-dir=$git->{git_dir}",
707                 qw(merge-base --is-ancestor), $cur, $tip ];
708         my $pid = spawn($cmd);
709         waitpid($pid, 0) == $pid or die join(' ', @$cmd) .' did not finish';
710         $? == 0;
711 }
712
713 sub need_update ($$$) {
714         my ($self, $cur, $new) = @_;
715         my $git = $self->{ibx}->git;
716         return 1 if $cur && !is_ancestor($git, $cur, $new);
717         my $range = $cur eq '' ? $new : "$cur..$new";
718         chomp(my $n = $git->qx(qw(rev-list --count), $range));
719         ($n eq '' || $n > 0);
720 }
721
722 # The last git commit we indexed with Xapian or SQLite (msgmap)
723 # This needs to account for cases where Xapian or SQLite is
724 # out-of-date with respect to the other.
725 sub _last_x_commit {
726         my ($self, $mm) = @_;
727         my $lm = $mm->last_commit || '';
728         my $lx = '';
729         if (need_xapian($self)) {
730                 $lx = $self->{xdb}->get_metadata('last_commit') || '';
731         } else {
732                 $lx = $lm;
733         }
734         # Use last_commit from msgmap if it is older or unset
735         if (!$lm || ($lx && $lm && is_ancestor($self->{ibx}->git, $lm, $lx))) {
736                 $lx = $lm;
737         }
738         $lx;
739 }
740
741 sub reindex_from ($$) {
742         my ($reindex, $last_commit) = @_;
743         return $last_commit unless $reindex;
744         ref($reindex) eq 'HASH' ? $reindex->{from} : '';
745 }
746
747 # indexes all unindexed messages (v1 only)
748 sub _index_sync {
749         my ($self, $opts) = @_;
750         my $tip = $opts->{ref} || 'HEAD';
751         my $git = $self->{ibx}->git;
752         $git->batch_prepare;
753         my $pr = $opts->{-progress};
754         my $sync = { reindex => $opts->{reindex}, -opt => $opts };
755         my $xdb = $self->begin_txn_lazy;
756         $self->{over}->rethread_prepare($opts);
757         my $mm = _msgmap_init($self);
758         if ($sync->{reindex}) {
759                 my $last = $mm->last_commit;
760                 if ($last) {
761                         $tip = $last;
762                 } else {
763                         # somebody just blindly added --reindex when indexing
764                         # for the first time, allow it:
765                         undef $sync->{reindex};
766                 }
767         }
768         my $last_commit = _last_x_commit($self, $mm);
769         my $lx = reindex_from($sync->{reindex}, $last_commit);
770         my $range = $lx eq '' ? $tip : "$lx..$tip";
771         $pr->("counting changes\n\t$range ... ") if $pr;
772         my $stk = prepare_stack($self, $sync, $range);
773         $sync->{ntodo} = $stk ? $stk->num_records : 0;
774         $pr->("$sync->{ntodo}\n") if $pr; # continue previous line
775         process_stack($self, $sync, $stk);
776 }
777
778 sub DESTROY {
779         # order matters for unlocking
780         $_[0]->{xdb} = undef;
781         $_[0]->{lockfh} = undef;
782 }
783
784 # remote_* subs are only used by SearchIdxPart
785 sub remote_commit {
786         my ($self) = @_;
787         if (my $w = $self->{w}) {
788                 print $w "commit\n" or die "failed to write commit: $!";
789         } else {
790                 $self->commit_txn_lazy;
791         }
792 }
793
794 sub remote_close {
795         my ($self) = @_;
796         if (my $w = delete $self->{w}) {
797                 my $pid = delete $self->{pid} or die "no process to wait on\n";
798                 print $w "close\n" or die "failed to write to pid:$pid: $!\n";
799                 close $w or die "failed to close pipe for pid:$pid: $!\n";
800                 waitpid($pid, 0) == $pid or die "remote process did not finish";
801                 $? == 0 or die ref($self)." pid:$pid exited with: $?";
802         } else {
803                 die "transaction in progress $self\n" if $self->{txn};
804                 idx_release($self) if $self->{xdb};
805         }
806 }
807
808 sub remote_remove {
809         my ($self, $oid, $num) = @_;
810         if (my $w = $self->{w}) {
811                 # triggers remove_by_oid in a shard
812                 print $w "D $oid $num\n" or die "failed to write remove $!";
813         } else {
814                 $self->remove_by_oid($oid, $num);
815         }
816 }
817
818 sub _begin_txn {
819         my ($self) = @_;
820         my $xdb = $self->{xdb} || idx_acquire($self);
821         $self->{over}->begin_lazy if $self->{over};
822         $xdb->begin_transaction if $xdb;
823         $self->{txn} = 1;
824         $xdb;
825 }
826
827 sub begin_txn_lazy {
828         my ($self) = @_;
829         $self->{ibx}->with_umask(\&_begin_txn, $self) if !$self->{txn};
830 }
831
832 # store 'indexlevel=medium' in v2 shard=0 and v1 (only one shard)
833 # This metadata is read by Admin::detect_indexlevel:
834 sub set_indexlevel {
835         my ($self) = @_;
836
837         if (!$self->{shard} && # undef or 0, not >0
838                         delete($self->{-set_indexlevel_once})) {
839                 my $xdb = $self->{xdb};
840                 my $level = $xdb->get_metadata('indexlevel');
841                 if (!$level || $level ne 'medium') {
842                         $xdb->set_metadata('indexlevel', 'medium');
843                 }
844         }
845 }
846
847 sub _commit_txn {
848         my ($self) = @_;
849         if (my $xdb = $self->{xdb}) {
850                 set_indexlevel($self);
851                 $xdb->commit_transaction;
852         }
853         $self->{over}->commit_lazy if $self->{over};
854 }
855
856 sub commit_txn_lazy {
857         my ($self) = @_;
858         delete($self->{txn}) and
859                 $self->{ibx}->with_umask(\&_commit_txn, $self);
860 }
861
862 sub worker_done {
863         my ($self) = @_;
864         if (need_xapian($self)) {
865                 die "$$ $0 xdb not released\n" if $self->{xdb};
866         }
867         die "$$ $0 still in transaction\n" if $self->{txn};
868 }
869
870 1;