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