]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/SearchIdx.pm
index: cleanup internal variables
[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         } elsif ($version == 2) {
71                 defined $shard or die "shard is required for v2\n";
72                 # shard is a number
73                 $self->{shard} = $shard;
74                 $self->{lock_path} = undef;
75         } else {
76                 die "unsupported inbox version=$version\n";
77         }
78         $self->{creat} = ($creat || 0) == 1;
79         $self;
80 }
81
82 sub need_xapian ($) { $_[0]->{indexlevel} =~ $xapianlevels }
83
84 sub idx_release {
85         my ($self, $wake) = @_;
86         if (need_xapian($self)) {
87                 my $xdb = delete $self->{xdb} or croak 'not acquired';
88                 $xdb->close;
89         }
90         $self->lock_release($wake) if $self->{creat};
91         undef;
92 }
93
94 sub load_xapian_writable () {
95         return 1 if $X->{WritableDatabase};
96         PublicInbox::Search::load_xapian() or return;
97         my $xap = $PublicInbox::Search::Xap;
98         for (qw(Document TermGenerator WritableDatabase)) {
99                 $X->{$_} = $xap.'::'.$_;
100         }
101         eval 'require '.$X->{WritableDatabase} or die;
102         *sortable_serialise = $xap.'::sortable_serialise';
103         $DB_CREATE_OR_OPEN = eval($xap.'::DB_CREATE_OR_OPEN()');
104         $DB_OPEN = eval($xap.'::DB_OPEN()');
105         my $ver = (eval($xap.'::major_version()') << 16) |
106                 (eval($xap.'::minor_version()') << 8);
107         $DB_NO_SYNC = 0x4 if $ver >= 0x10400;
108         1;
109 }
110
111 sub idx_acquire {
112         my ($self) = @_;
113         my $flag;
114         my $dir = $self->xdir;
115         if (need_xapian($self)) {
116                 croak 'already acquired' if $self->{xdb};
117                 load_xapian_writable();
118                 $flag = $self->{creat} ? $DB_CREATE_OR_OPEN : $DB_OPEN;
119         }
120         if ($self->{creat}) {
121                 require File::Path;
122                 $self->lock_acquire;
123
124                 # don't create empty Xapian directories if we don't need Xapian
125                 my $is_shard = defined($self->{shard});
126                 if (!-d $dir && (!$is_shard ||
127                                 ($is_shard && need_xapian($self)))) {
128                         File::Path::mkpath($dir);
129                         nodatacow_dir($dir);
130                 }
131         }
132         return unless defined $flag;
133         $flag |= $DB_NO_SYNC if $self->{ibx}->{-no_fsync};
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, $eml, $smsg, $mids) = @_;
346         my $doc = $X->{Document}->new;
347         add_val($doc, PublicInbox::Search::TS(), $smsg->{ts});
348         my @ds = gmtime($smsg->{ds});
349         my $yyyymmdd = strftime('%Y%m%d', @ds);
350         add_val($doc, PublicInbox::Search::YYYYMMDD(), $yyyymmdd);
351         my $dt = strftime('%Y%m%d%H%M%S', @ds);
352         add_val($doc, PublicInbox::Search::DT(), $dt);
353         add_val($doc, PublicInbox::Search::BYTES(), $smsg->{bytes});
354         add_val($doc, PublicInbox::Search::UID(), $smsg->{num});
355
356         my $tg = term_generator($self);
357         $tg->set_document($doc);
358         index_headers($self, $smsg);
359
360         msg_iter($eml, \&index_xapian, [ $self, $doc ]);
361         index_ids($self, $doc, $eml, $mids);
362         $smsg->{to} = $smsg->{cc} = ''; # WWW doesn't need these, only NNTP
363         PublicInbox::OverIdx::parse_references($smsg, $eml, $mids);
364         my $data = $smsg->to_doc_data;
365         $doc->set_data($data);
366         if (my $altid = $self->{-altid}) {
367                 foreach my $alt (@$altid) {
368                         my $pfx = $alt->{xprefix};
369                         foreach my $mid (@$mids) {
370                                 my $id = $alt->mid2alt($mid);
371                                 next unless defined $id;
372                                 $doc->add_boolean_term($pfx . $id);
373                         }
374                 }
375         }
376         $self->{xdb}->replace_document($smsg->{num}, $doc);
377 }
378
379 sub _msgmap_init ($) {
380         my ($self) = @_;
381         die "BUG: _msgmap_init is only for v1\n" if $self->{ibx_ver} != 1;
382         $self->{mm} //= eval {
383                 require PublicInbox::Msgmap;
384                 my $rw = $self->{ibx}->{-no_fsync} ? 2 : 1;
385                 PublicInbox::Msgmap->new($self->{ibx}->{inboxdir}, $rw);
386         };
387 }
388
389 sub add_message {
390         # mime = PublicInbox::Eml or Email::MIME object
391         my ($self, $mime, $smsg, $sync) = @_;
392         my $mids = mids_for_index($mime);
393         $smsg //= bless { blob => '' }, 'PublicInbox::Smsg'; # test-only compat
394         $smsg->{mid} //= $mids->[0]; # v1 compatibility
395         $smsg->{num} //= do { # v1
396                 _msgmap_init($self);
397                 index_mm($self, $mime, $smsg->{blob}, $sync);
398         };
399
400         # v1 and tests only:
401         $smsg->populate($mime, $sync);
402         $smsg->{bytes} //= length($mime->as_string);
403
404         eval {
405                 # order matters, overview stores every possible piece of
406                 # data in doc_data (deflated).  Xapian only stores a subset
407                 # of the fields which exist in over.sqlite3.  We may stop
408                 # storing doc_data in Xapian sometime after we get multi-inbox
409                 # search working.
410                 if (my $over = $self->{over}) { # v1 only
411                         $over->add_overview($mime, $smsg);
412                 }
413                 if (need_xapian($self)) {
414                         add_xapian($self, $mime, $smsg, $mids);
415                 }
416         };
417
418         if ($@) {
419                 warn "failed to index message <".join('> <',@$mids).">: $@\n";
420                 return undef;
421         }
422         $smsg->{num};
423 }
424
425 sub xdb_remove {
426         my ($self, $oid, @removed) = @_;
427         my $xdb = $self->{xdb} or return;
428         for my $num (@removed) {
429                 my $doc = eval { $xdb->get_document($num) };
430                 unless ($doc) {
431                         warn "E: $@\n" if $@;
432                         warn "E: #$num $oid missing in Xapian\n";
433                         next;
434                 }
435                 my $smsg = bless {}, 'PublicInbox::Smsg';
436                 $smsg->load_expand($doc);
437                 my $blob = $smsg->{blob} // '(unset)';
438                 if ($blob eq $oid) {
439                         $xdb->delete_document($num);
440                 } else {
441                         warn "E: #$num $oid != $blob in Xapian\n";
442                 }
443         }
444 }
445
446 sub remove_by_oid {
447         my ($self, $oid, $num) = @_;
448         die "BUG: remove_by_oid is v2-only\n" if $self->{over};
449         $self->begin_txn_lazy;
450         xdb_remove($self, $oid, $num) if need_xapian($self);
451 }
452
453 sub index_git_blob_id {
454         my ($doc, $pfx, $objid) = @_;
455
456         my $len = length($objid);
457         for (my $len = length($objid); $len >= 7; ) {
458                 $doc->add_term($pfx.$objid);
459                 $objid = substr($objid, 0, --$len);
460         }
461 }
462
463 # v1 only
464 sub unindex_eml {
465         my ($self, $oid, $eml) = @_;
466         my $mids = mids($eml);
467         my $nr = 0;
468         my %tmp;
469         for my $mid (@$mids) {
470                 my @removed = eval { $self->{over}->remove_oid($oid, $mid) };
471                 if ($@) {
472                         warn "E: failed to remove <$mid> from overview: $@\n";
473                 } else {
474                         $nr += scalar @removed;
475                         $tmp{$_}++ for @removed;
476                 }
477         }
478         if (!$nr) {
479                 $mids = join('> <', @$mids);
480                 warn "W: <$mids> missing for removal from overview\n";
481         }
482         while (my ($num, $nr) = each %tmp) {
483                 warn "BUG: $num appears >1 times ($nr) for $oid\n" if $nr != 1;
484         }
485         if ($nr) {
486                 $self->{mm}->num_delete($_) for (keys %tmp);
487         } else { # just in case msgmap and over.sqlite3 become desynched:
488                 $self->{mm}->mid_delete($mids->[0]);
489         }
490         xdb_remove($self, $oid, keys %tmp) if need_xapian($self);
491 }
492
493 sub index_mm {
494         my ($self, $mime, $oid, $sync) = @_;
495         my $mids = mids($mime);
496         my $mm = $self->{mm};
497         if ($sync->{reindex}) {
498                 my $over = $self->{over};
499                 for my $mid (@$mids) {
500                         my ($num, undef) = $over->num_mid0_for_oid($oid, $mid);
501                         return $num if defined $num;
502                 }
503                 $mm->num_for($mids->[0]) // $mm->mid_insert($mids->[0]);
504         } else {
505                 # fallback to num_for since filters like RubyLang set the number
506                 $mm->mid_insert($mids->[0]) // $mm->num_for($mids->[0]);
507         }
508 }
509
510 # returns the number of bytes to add if given a non-CRLF arg
511 sub crlf_adjust ($) {
512         if (index($_[0], "\r\n") < 0) {
513                 # common case is LF-only, every \n needs an \r;
514                 # so favor a cheap tr// over an expensive m//g
515                 $_[0] =~ tr/\n/\n/;
516         } else { # count number of '\n' w/o '\r', expensive:
517                 scalar(my @n = ($_[0] =~ m/(?<!\r)\n/g));
518         }
519 }
520
521 sub index_both { # git->cat_async callback
522         my ($bref, $oid, $type, $size, $sync) = @_;
523         my ($nr, $max) = @$sync{qw(nr max)};
524         ++$$nr;
525         $$max -= $size;
526         $size += crlf_adjust($$bref);
527         my $smsg = bless { bytes => $size, blob => $oid }, 'PublicInbox::Smsg';
528         my $self = $sync->{sidx};
529         my $eml = PublicInbox::Eml->new($bref);
530         $smsg->{num} = index_mm($self, $eml, $oid, $sync) or
531                 die "E: could not generate NNTP article number for $oid";
532         add_message($self, $eml, $smsg, $sync);
533 }
534
535 sub unindex_both { # git->cat_async callback
536         my ($bref, $oid, $type, $size, $self) = @_;
537         unindex_eml($self, $oid, PublicInbox::Eml->new($bref));
538 }
539
540 # called by public-inbox-index
541 sub index_sync {
542         my ($self, $opts) = @_;
543         delete $self->{lock_path} if $opts->{-skip_lock};
544         $self->{ibx}->with_umask(\&_index_sync, $self, $opts);
545         if ($opts->{reindex}) {
546                 my %again = %$opts;
547                 delete @again{qw(rethread reindex)};
548                 index_sync($self, \%again);
549         }
550 }
551
552 sub check_size { # check_async cb for -index --max-size=...
553         my ($oid, $type, $size, $arg, $git) = @_;
554         (($type // '') eq 'blob') or die "E: bad $oid in $git->{git_dir}";
555         if ($size <= $arg->{max_size}) {
556                 $git->cat_async($oid, $arg->{index_oid}, $arg);
557         } else {
558                 warn "W: skipping $oid ($size > $arg->{max_size})\n";
559         }
560 }
561
562 sub v1_checkpoint ($$;$) {
563         my ($self, $sync, $stk) = @_;
564         $self->{ibx}->git->check_async_wait;
565         $self->{ibx}->git->cat_async_wait;
566
567         # latest_cmt may be undef
568         my $newest = $stk ? $stk->{latest_cmt} : undef;
569         if ($newest) {
570                 my $cur = $self->{mm}->last_commit || '';
571                 if (need_update($self, $cur, $newest)) {
572                         $self->{mm}->last_commit($newest);
573                 }
574         } else {
575                 ${$sync->{max}} = $self->{batch_bytes};
576         }
577
578         $self->{mm}->{dbh}->commit;
579         if ($newest && need_xapian($self)) {
580                 my $cur = $self->{xdb}->get_metadata('last_commit');
581                 if (need_update($self, $cur, $newest)) {
582                         $self->{xdb}->set_metadata('last_commit', $newest);
583                 }
584         }
585
586         $self->{over}->rethread_done($sync->{-opt}) if $newest; # all done
587         commit_txn_lazy($self);
588         $self->{ibx}->git->cleanup;
589         my $nr = ${$sync->{nr}};
590         idx_release($self, $nr);
591         # let another process do some work...
592         if (my $pr = $sync->{-opt}->{-progress}) {
593                 $pr->("indexed $nr/$sync->{ntodo}\n") if $nr;
594         }
595         if (!$stk) { # more to come
596                 begin_txn_lazy($self);
597                 $self->{mm}->{dbh}->begin_work;
598         }
599 }
600
601 # only for v1
602 sub process_stack {
603         my ($self, $sync, $stk) = @_;
604         my $git = $self->{ibx}->git;
605         my $max = $self->{batch_bytes};
606         my $nr = 0;
607         $sync->{nr} = \$nr;
608         $sync->{max} = \$max;
609         $sync->{sidx} = $self;
610
611         $self->{mm}->{dbh}->begin_work;
612         if (my @leftovers = keys %{delete($sync->{D}) // {}}) {
613                 warn('W: unindexing '.scalar(@leftovers)." leftovers\n");
614                 for my $oid (@leftovers) {
615                         $oid = unpack('H*', $oid);
616                         $git->cat_async($oid, \&unindex_both, $self);
617                 }
618         }
619         if ($sync->{max_size} = $sync->{-opt}->{max_size}) {
620                 $sync->{index_oid} = \&index_both;
621         }
622         while (my ($f, $at, $ct, $oid) = $stk->pop_rec) {
623                 if ($f eq 'm') {
624                         my $arg = { %$sync, autime => $at, cotime => $ct };
625                         if ($sync->{max_size}) {
626                                 $git->check_async($oid, \&check_size, $arg);
627                         } else {
628                                 $git->cat_async($oid, \&index_both, $arg);
629                         }
630                         v1_checkpoint($self, $sync) if $max <= 0;
631                 } elsif ($f eq 'd') {
632                         $git->cat_async($oid, \&unindex_both, $self);
633                 }
634         }
635         v1_checkpoint($self, $sync, $stk);
636 }
637
638 sub log2stack ($$$$) {
639         my ($sync, $git, $range, $ibx) = @_;
640         my $D = $sync->{D}; # OID_BIN => NR (if reindexing, undef otherwise)
641         my ($add, $del);
642         if ($ibx->version == 1) {
643                 my $path = $hex.'{2}/'.$hex.'{38}';
644                 $add = qr!\A:000000 100644 \S+ ($OID) A\t$path$!;
645                 $del = qr!\A:100644 000000 ($OID) \S+ D\t$path$!;
646         } else {
647                 $del = qr!\A:\d{6} 100644 $OID ($OID) [AM]\td$!;
648                 $add = qr!\A:\d{6} 100644 $OID ($OID) [AM]\tm$!;
649         }
650
651         # Count the new files so they can be added newest to oldest
652         # and still have numbers increasing from oldest to newest
653         my $fh = $git->popen(qw(log --raw -r --pretty=tformat:%at-%ct-%H
654                                 --no-notes --no-color --no-renames --no-abbrev),
655                                 $range);
656         my ($at, $ct, $stk);
657         while (<$fh>) {
658                 if (/\A([0-9]+)-([0-9]+)-($OID)$/o) {
659                         ($at, $ct) = ($1 + 0, $2 + 0);
660                         $stk //= PublicInbox::IdxStack->new($3);
661                 } elsif (/$del/) {
662                         my $oid = $1;
663                         if ($D) { # reindex case
664                                 $D->{pack('H*', $oid)}++;
665                         } else { # non-reindex case:
666                                 $stk->push_rec('d', $at, $ct, $oid);
667                         }
668                 } elsif (/$add/) {
669                         my $oid = $1;
670                         if ($D) {
671                                 my $oid_bin = pack('H*', $oid);
672                                 my $nr = --$D->{$oid_bin};
673                                 delete($D->{$oid_bin}) if $nr <= 0;
674
675                                 # nr < 0 (-1) means it never existed
676                                 $stk->push_rec('m', $at, $ct, $oid) if $nr < 0;
677                         } else {
678                                 $stk->push_rec('m', $at, $ct, $oid);
679                         }
680                 }
681         }
682         close $fh or die "git log failed: \$?=$?";
683         $stk //= PublicInbox::IdxStack->new;
684         $stk->read_prepare;
685 }
686
687 sub prepare_stack ($$$) {
688         my ($self, $sync, $range) = @_;
689         my $git = $self->{ibx}->git;
690
691         if (index($range, '..') < 0) {
692                 # don't show annoying git errors to users who run -index
693                 # on empty inboxes
694                 $git->qx(qw(rev-parse -q --verify), "$range^0");
695                 return PublicInbox::IdxStack->new->read_prepare if $?;
696         }
697         $sync->{D} = $sync->{reindex} ? {} : undef; # OID_BIN => NR
698         log2stack($sync, $git, $range, $self->{ibx});
699 }
700
701 # --is-ancestor requires git 1.8.0+
702 sub is_ancestor ($$$) {
703         my ($git, $cur, $tip) = @_;
704         return 0 unless $git->check($cur);
705         my $cmd = [ 'git', "--git-dir=$git->{git_dir}",
706                 qw(merge-base --is-ancestor), $cur, $tip ];
707         my $pid = spawn($cmd);
708         waitpid($pid, 0) == $pid or die join(' ', @$cmd) .' did not finish';
709         $? == 0;
710 }
711
712 sub need_update ($$$) {
713         my ($self, $cur, $new) = @_;
714         my $git = $self->{ibx}->git;
715         return 1 if $cur && !is_ancestor($git, $cur, $new);
716         my $range = $cur eq '' ? $new : "$cur..$new";
717         chomp(my $n = $git->qx(qw(rev-list --count), $range));
718         ($n eq '' || $n > 0);
719 }
720
721 # The last git commit we indexed with Xapian or SQLite (msgmap)
722 # This needs to account for cases where Xapian or SQLite is
723 # out-of-date with respect to the other.
724 sub _last_x_commit {
725         my ($self, $mm) = @_;
726         my $lm = $mm->last_commit || '';
727         my $lx = '';
728         if (need_xapian($self)) {
729                 $lx = $self->{xdb}->get_metadata('last_commit') || '';
730         } else {
731                 $lx = $lm;
732         }
733         # Use last_commit from msgmap if it is older or unset
734         if (!$lm || ($lx && $lm && is_ancestor($self->{ibx}->git, $lm, $lx))) {
735                 $lx = $lm;
736         }
737         $lx;
738 }
739
740 sub reindex_from ($$) {
741         my ($reindex, $last_commit) = @_;
742         return $last_commit unless $reindex;
743         ref($reindex) eq 'HASH' ? $reindex->{from} : '';
744 }
745
746 # indexes all unindexed messages (v1 only)
747 sub _index_sync {
748         my ($self, $opts) = @_;
749         my $tip = $opts->{ref} || 'HEAD';
750         my $git = $self->{ibx}->git;
751         $self->{batch_bytes} = $opts->{batch_size} // $BATCH_BYTES;
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;