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