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