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
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;
12 use parent qw(PublicInbox::Search PublicInbox::Lock Exporter);
14 use PublicInbox::InboxWritable;
15 use PublicInbox::MID qw(mids_for_index mids);
16 use PublicInbox::MsgIter;
17 use PublicInbox::IdxStack;
19 use POSIX qw(strftime);
20 use Time::Local qw(timegm);
21 use PublicInbox::OverIdx;
22 use PublicInbox::Spawn qw(spawn nodatacow_dir);
23 use PublicInbox::Git qw(git_unquote);
24 use PublicInbox::MsgTime qw(msg_timestamp msg_datestamp);
25 our @EXPORT_OK = qw(crlf_adjust log2stack is_ancestor check_size prepare_stack);
26 my $X = \%PublicInbox::Search::X;
27 my ($DB_CREATE_OR_OPEN, $DB_OPEN);
29 our $BATCH_BYTES = $ENV{XAPIAN_FLUSH_THRESHOLD} ? 0x7fffffff : 1_000_000;
30 use constant DEBUG => !!$ENV{DEBUG};
32 my $xapianlevels = qr/\A(?:full|medium)\z/;
34 my $OID = $hex .'{40,}';
35 our $INDEXLEVELS = qr/\A(?:full|medium|basic)\z/;
38 my ($class, $ibx, $creat, $shard) = @_;
39 ref $ibx or die "BUG: expected PublicInbox::Inbox object: $ibx";
40 my $inboxdir = $ibx->{inboxdir};
41 my $version = $ibx->version;
42 my $indexlevel = 'full';
43 my $altid = $ibx->{altid};
45 require PublicInbox::AltId;
46 $altid = [ map { PublicInbox::AltId->new($ibx, $_); } @$altid ];
48 if ($ibx->{indexlevel}) {
49 if ($ibx->{indexlevel} =~ $INDEXLEVELS) {
50 $indexlevel = $ibx->{indexlevel};
52 die("Invalid indexlevel $ibx->{indexlevel}\n");
55 $ibx = PublicInbox::InboxWritable->new($ibx);
58 xpfx => $inboxdir, # for xpfx_init
61 indexlevel => $indexlevel,
64 $self->{-set_indexlevel_once} = 1 if $indexlevel eq 'medium';
65 if ($ibx->{-skip_docdata}) {
66 $self->{-set_skip_docdata_once} = 1;
67 $self->{-skip_docdata} = 1;
71 $self->{lock_path} = "$inboxdir/ssoma.lock";
72 my $dir = $self->xdir;
73 $self->{oidx} = PublicInbox::OverIdx->new("$dir/over.sqlite3");
74 $self->{oidx}->{-no_fsync} = 1 if $ibx->{-no_fsync};
75 } elsif ($version == 2) {
76 defined $shard or die "shard is required for v2\n";
78 $self->{shard} = $shard;
79 $self->{lock_path} = undef;
81 die "unsupported inbox version=$version\n";
83 $self->{creat} = ($creat || 0) == 1;
87 sub need_xapian ($) { $_[0]->{indexlevel} =~ $xapianlevels }
90 my ($self, $wake) = @_;
91 if (need_xapian($self)) {
92 my $xdb = delete $self->{xdb} or croak 'not acquired';
95 $self->lock_release($wake) if $self->{creat};
99 sub load_xapian_writable () {
100 return 1 if $X->{WritableDatabase};
101 PublicInbox::Search::load_xapian() or return;
102 my $xap = $PublicInbox::Search::Xap;
103 for (qw(Document TermGenerator WritableDatabase)) {
104 $X->{$_} = $xap.'::'.$_;
106 eval 'require '.$X->{WritableDatabase} or die;
107 *sortable_serialise = $xap.'::sortable_serialise';
108 *sortable_unserialise = $xap.'::sortable_unserialise';
109 $DB_CREATE_OR_OPEN = eval($xap.'::DB_CREATE_OR_OPEN()');
110 $DB_OPEN = eval($xap.'::DB_OPEN()');
111 my $ver = (eval($xap.'::major_version()') << 16) |
112 (eval($xap.'::minor_version()') << 8);
113 $DB_NO_SYNC = 0x4 if $ver >= 0x10400;
120 my $dir = $self->xdir;
121 if (need_xapian($self)) {
122 croak 'already acquired' if $self->{xdb};
123 load_xapian_writable();
124 $flag = $self->{creat} ? $DB_CREATE_OR_OPEN : $DB_OPEN;
126 if ($self->{creat}) {
130 # don't create empty Xapian directories if we don't need Xapian
131 my $is_shard = defined($self->{shard});
132 if (!-d $dir && (!$is_shard ||
133 ($is_shard && need_xapian($self)))) {
134 File::Path::mkpath($dir);
136 $self->{-set_has_threadid_once} = 1;
139 return unless defined $flag;
140 $flag |= $DB_NO_SYNC if ($self->{ibx} // $self->{eidx})->{-no_fsync};
141 my $xdb = eval { ($X->{WritableDatabase})->new($dir, $flag) };
142 croak "Failed opening $dir: $@" if $@;
147 my ($doc, $col, $num) = @_;
148 $num = sortable_serialise($num);
149 $doc->add_value($col, $num);
152 sub term_generator ($) { # write-only
155 $self->{term_generator} //= do {
156 my $tg = $X->{TermGenerator}->new;
157 $tg->set_stemmer($self->stemmer);
162 sub index_text ($$$$) {
163 my ($self, $text, $wdf_inc, $prefix) = @_;
164 my $tg = term_generator($self); # man Search::Xapian::TermGenerator
166 if ($self->{indexlevel} eq 'full') {
167 $tg->index_text($text, $wdf_inc, $prefix);
168 $tg->increase_termpos;
170 $tg->index_text_without_positions($text, $wdf_inc, $prefix);
174 sub index_headers ($$) {
175 my ($self, $smsg) = @_;
176 my @x = (from => 'A', # Author
177 subject => 'S', to => 'XTO', cc => 'XCC');
178 while (my ($field, $pfx) = splice(@x, 0, 2)) {
179 my $val = $smsg->{$field};
180 index_text($self, $val, 1, $pfx) if $val ne '';
184 sub index_diff_inc ($$$$) {
185 my ($self, $text, $pfx, $xnq) = @_;
187 index_text($self, join("\n", @$xnq), 1, 'XNQ');
190 index_text($self, $text, 1, $pfx);
193 sub index_old_diff_fn {
194 my ($self, $seen, $fa, $fb, $xnq) = @_;
196 # no renames or space support for traditional diffs,
197 # find the number of leading common paths to strip:
198 my @fa = split('/', $fa);
199 my @fb = split('/', $fb);
200 while (scalar(@fa) && scalar(@fb)) {
201 $fa = join('/', @fa);
202 $fb = join('/', @fb);
204 unless ($seen->{$fa}++) {
205 index_diff_inc($self, $fa, 'XDFN', $xnq);
215 sub index_diff ($$$) {
216 my ($self, $txt, $doc) = @_;
221 foreach (split(/\n/, $txt)) {
222 if ($in_diff && s/^ //) { # diff context
223 index_diff_inc($self, $_, 'XDFCTX', $xnq);
224 } elsif (/^-- $/) { # email signature begins
226 } elsif (m!^diff --git "?[^/]+/.+ "?[^/]+/.+\z!) {
227 # wait until "---" and "+++" to capture filenames
230 } elsif (m/^diff -(.+) (\S+) (\S+)$/) {
231 my ($opt, $fa, $fb) = ($1, $2, $3);
233 # only support unified:
234 next unless $opt =~ /[uU]/;
235 $in_diff = index_old_diff_fn($self, \%seen, $fa, $fb,
237 } elsif (m!^--- ("?[^/]+/.+)!) {
239 $fn = (split('/', git_unquote($fn), 2))[1];
240 $seen{$fn}++ or index_diff_inc($self, $fn, 'XDFN', $xnq);
242 } elsif (m!^\+\+\+ ("?[^/]+/.+)!) {
244 $fn = (split('/', git_unquote($fn), 2))[1];
245 $seen{$fn}++ or index_diff_inc($self, $fn, 'XDFN', $xnq);
247 } elsif (/^--- (\S+)/) {
250 } elsif (defined $in_diff && /^\+\+\+ (\S+)/) {
251 $in_diff = index_old_diff_fn($self, \%seen, $in_diff,
253 } elsif ($in_diff && s/^\+//) { # diff added
254 index_diff_inc($self, $_, 'XDFB', $xnq);
255 } elsif ($in_diff && s/^-//) { # diff removed
256 index_diff_inc($self, $_, 'XDFA', $xnq);
257 } elsif (m!^index ([a-f0-9]+)\.\.([a-f0-9]+)!) {
258 my ($ba, $bb) = ($1, $2);
259 index_git_blob_id($doc, 'XDFPRE', $ba);
260 index_git_blob_id($doc, 'XDFPOST', $bb);
262 } elsif (/^@@ (?:\S+) (?:\S+) @@\s*$/) {
263 # traditional diff w/o -p
264 } elsif (/^@@ (?:\S+) (?:\S+) @@\s*(\S+.*)$/) {
265 # hunk header context
266 index_diff_inc($self, $1, 'XDFHH', $xnq);
267 # ignore the following lines:
268 } elsif (/^(?:dis)similarity index/ ||
269 /^(?:old|new) mode/ ||
270 /^(?:deleted|new) file mode/ ||
271 /^(?:copy|rename) (?:from|to) / ||
272 /^(?:dis)?similarity index / ||
273 /^\\ No newline at end of file/ ||
274 /^Binary files .* differ/) {
277 # possible to be in diff context, some mail may be
278 # stripped by MUA or even GNU diff(1). "git apply"
279 # treats a bare "\n" as diff context, too
282 warn "non-diff line: $_\n" if DEBUG && $_ ne '';
287 index_text($self, join("\n", @xnq), 1, 'XNQ');
290 sub index_xapian { # msg_iter callback
291 my $part = $_[0]->[0]; # ignore $depth and $idx
292 my ($self, $doc) = @{$_[1]};
293 my $ct = $part->content_type || 'text/plain';
294 my $fn = $part->filename;
295 if (defined $fn && $fn ne '') {
296 index_text($self, $fn, 1, 'XFN');
298 if ($part->{is_submsg}) {
299 my $mids = mids_for_index($part);
300 index_ids($self, $doc, $part, $mids);
301 my $smsg = bless {}, 'PublicInbox::Smsg';
302 $smsg->populate($part);
303 index_headers($self, $smsg);
306 my ($s, undef) = msg_part_text($part, $ct);
307 defined $s or return;
308 $_[0]->[0] = $part = undef; # free memory
310 # split off quoted and unquoted blocks:
311 my @sections = PublicInbox::MsgIter::split_quotes($s);
312 undef $s; # free memory
313 for my $txt (@sections) {
315 index_text($self, $txt, 0, 'XQUOT');
317 # does it look like a diff?
318 if ($txt =~ /^(?:diff|---|\+\+\+) /ms) {
319 index_diff($self, $txt, $doc);
321 index_text($self, $txt, 1, 'XNQ');
324 undef $txt; # free memory
328 sub index_list_id ($$$) {
329 my ($self, $doc, $hdr) = @_;
330 for my $l ($hdr->header_raw('List-Id')) {
331 $l =~ /<([^>]+)>/ or next;
333 $doc->add_boolean_term('G' . $lid);
334 index_text($self, $lid, 1, 'XL'); # probabilistic
338 sub index_ids ($$$$) {
339 my ($self, $doc, $hdr, $mids) = @_;
340 for my $mid (@$mids) {
341 index_text($self, $mid, 1, 'XM');
343 # because too many Message-IDs are prefixed with
345 if ($mid =~ /\w{12,}/) {
346 my @long = ($mid =~ /(\w{3,}+)/g);
347 index_text($self, join(' ', @long), 1, 'XM');
350 $doc->add_boolean_term('Q' . $_) for @$mids;
351 index_list_id($self, $doc, $hdr);
354 sub add_xapian ($$$$) {
355 my ($self, $eml, $smsg, $mids) = @_;
356 my $doc = $X->{Document}->new;
357 add_val($doc, PublicInbox::Search::TS(), $smsg->{ts});
358 my @ds = gmtime($smsg->{ds});
359 my $yyyymmdd = strftime('%Y%m%d', @ds);
360 add_val($doc, PublicInbox::Search::YYYYMMDD(), $yyyymmdd);
361 my $dt = strftime('%Y%m%d%H%M%S', @ds);
362 add_val($doc, PublicInbox::Search::DT(), $dt);
363 add_val($doc, PublicInbox::Search::BYTES(), $smsg->{bytes});
364 add_val($doc, PublicInbox::Search::UID(), $smsg->{num});
365 add_val($doc, PublicInbox::Search::THREADID, $smsg->{tid});
367 my $tg = term_generator($self);
368 $tg->set_document($doc);
369 index_headers($self, $smsg);
371 if (defined(my $eidx_key = $smsg->{eidx_key})) {
372 $doc->add_boolean_term('O'.$eidx_key);
374 msg_iter($eml, \&index_xapian, [ $self, $doc ]);
375 index_ids($self, $doc, $eml, $mids);
377 # by default, we maintain compatibility with v1.5.0 and earlier
378 # by writing to docdata.glass, users who never exect to downgrade can
380 if (!$self->{-skip_docdata}) {
381 # WWW doesn't need {to} or {cc}, only NNTP
382 $smsg->{to} = $smsg->{cc} = '';
383 PublicInbox::OverIdx::parse_references($smsg, $eml, $mids);
384 my $data = $smsg->to_doc_data;
385 $doc->set_data($data);
388 if (my $altid = $self->{-altid}) {
389 foreach my $alt (@$altid) {
390 my $pfx = $alt->{xprefix};
391 foreach my $mid (@$mids) {
392 my $id = $alt->mid2alt($mid);
393 next unless defined $id;
394 $doc->add_boolean_term($pfx . $id);
398 $self->{xdb}->replace_document($smsg->{num}, $doc);
401 sub _msgmap_init ($) {
403 die "BUG: _msgmap_init is only for v1\n" if $self->{ibx_ver} != 1;
404 $self->{mm} //= eval {
405 require PublicInbox::Msgmap;
406 my $rw = $self->{ibx}->{-no_fsync} ? 2 : 1;
407 PublicInbox::Msgmap->new($self->{ibx}->{inboxdir}, $rw);
412 # mime = PublicInbox::Eml or Email::MIME object
413 my ($self, $mime, $smsg, $sync) = @_;
414 my $mids = mids_for_index($mime);
415 $smsg //= bless { blob => '' }, 'PublicInbox::Smsg'; # test-only compat
416 $smsg->{mid} //= $mids->[0]; # v1 compatibility
417 $smsg->{num} //= do { # v1
419 index_mm($self, $mime, $smsg->{blob}, $sync);
423 $smsg->populate($mime, $sync);
424 $smsg->{bytes} //= length($mime->as_string);
427 # order matters, overview stores every possible piece of
428 # data in doc_data (deflated). Xapian only stores a subset
429 # of the fields which exist in over.sqlite3. We may stop
430 # storing doc_data in Xapian sometime after we get multi-inbox
432 if (my $oidx = $self->{oidx}) { # v1 only
433 $oidx->add_overview($mime, $smsg);
435 if (need_xapian($self)) {
436 add_xapian($self, $mime, $smsg, $mids);
441 warn "failed to index message <".join('> <',@$mids).">: $@\n";
448 my ($self, $docid, $oid) = @_;
449 my $doc = eval { $self->{xdb}->get_document($docid) };
451 warn "E: $@\n" if $@;
452 warn "E: #$docid $oid missing in Xapian\n";
458 my ($self, $docid, $oid, $eidx_key, $eml) = @_;
459 begin_txn_lazy($self);
460 my $doc = _get_doc($self, $docid, $oid) or return;
461 term_generator($self)->set_document($doc);
462 $doc->add_boolean_term('O'.$eidx_key);
463 index_list_id($self, $doc, $eml);
464 $self->{xdb}->replace_document($docid, $doc);
467 sub remove_eidx_info {
468 my ($self, $docid, $oid, $eidx_key, $eml) = @_;
469 begin_txn_lazy($self);
470 my $doc = _get_doc($self, $docid, $oid) or return;
471 eval { $doc->remove_term('O'.$eidx_key) };
472 warn "W: ->remove_term O$eidx_key: $@\n" if $@;
473 for my $l ($eml->header_raw('List-Id')) {
474 $l =~ /<([^>]+)>/ or next;
476 eval { $doc->remove_term('G' . $lid) };
477 warn "W: ->remove_term G$lid: $@\n" if $@;
479 # nb: we don't remove the XL probabilistic terms
480 # since terms may overlap if cross-posted.
482 # IOW, a message which has both <foo.example.com>
483 # and <bar.example.com> would have overlapping
484 # "XLexample" and "XLcom" as terms and which we
485 # wouldn't know if they're safe to remove if we just
486 # unindex <foo.example.com> while preserving
489 # In any case, this entire sub is will likely never
490 # be needed and users using the "l:" prefix are probably
493 $self->{xdb}->replace_document($docid, $doc);
497 my ($doc, $col) = @_;
498 sortable_unserialise($doc->get_value($col));
501 sub smsg_from_doc ($) {
503 my $data = $doc->get_data or return;
504 my $smsg = bless {}, 'PublicInbox::Smsg';
505 $smsg->{ts} = get_val($doc, PublicInbox::Search::TS());
506 my $dt = get_val($doc, PublicInbox::Search::DT());
507 my ($yyyy, $mon, $dd, $hh, $mm, $ss) = unpack('A4A2A2A2A2A2', $dt);
508 $smsg->{ds} = timegm($ss, $mm, $hh, $dd, $mon - 1, $yyyy);
509 $smsg->load_from_data($data);
514 my ($self, $oid, @removed) = @_;
515 my $xdb = $self->{xdb} or return;
516 for my $num (@removed) {
517 my $doc = _get_doc($self, $num, $oid) or next;
518 my $smsg = smsg_from_doc($doc);
519 my $blob = $smsg->{blob}; # may be undef if --skip-docdata
520 if (!defined($blob) || $blob eq $oid) {
521 $xdb->delete_document($num);
523 warn "E: #$num $oid != $blob in Xapian\n";
529 my ($self, $oid, $num) = @_;
530 die "BUG: remove_by_oid is v2-only\n" if $self->{oidx};
531 $self->begin_txn_lazy;
532 xdb_remove($self, $oid, $num) if need_xapian($self);
535 sub index_git_blob_id {
536 my ($doc, $pfx, $objid) = @_;
538 my $len = length($objid);
539 for (my $len = length($objid); $len >= 7; ) {
540 $doc->add_term($pfx.$objid);
541 $objid = substr($objid, 0, --$len);
547 my ($self, $oid, $eml) = @_;
548 my $mids = mids($eml);
551 for my $mid (@$mids) {
552 my @removed = $self->{oidx}->remove_oid($oid, $mid);
553 $nr += scalar @removed;
554 $tmp{$_}++ for @removed;
557 my $m = join('> <', @$mids);
558 warn "W: <$m> missing for removal from overview\n";
560 while (my ($num, $nr) = each %tmp) {
561 warn "BUG: $num appears >1 times ($nr) for $oid\n" if $nr != 1;
564 $self->{mm}->num_delete($_) for (keys %tmp);
565 } else { # just in case msgmap and over.sqlite3 become desynched:
566 $self->{mm}->mid_delete($mids->[0]);
568 xdb_remove($self, $oid, keys %tmp) if need_xapian($self);
572 my ($self, $mime, $oid, $sync) = @_;
573 my $mids = mids($mime);
574 my $mm = $self->{mm};
575 if ($sync->{reindex}) {
576 my $oidx = $self->{oidx};
577 for my $mid (@$mids) {
578 my ($num, undef) = $oidx->num_mid0_for_oid($oid, $mid);
579 return $num if defined $num;
581 $mm->num_for($mids->[0]) // $mm->mid_insert($mids->[0]);
583 # fallback to num_for since filters like RubyLang set the number
584 $mm->mid_insert($mids->[0]) // $mm->num_for($mids->[0]);
588 # returns the number of bytes to add if given a non-CRLF arg
589 sub crlf_adjust ($) {
590 if (index($_[0], "\r\n") < 0) {
591 # common case is LF-only, every \n needs an \r;
592 # so favor a cheap tr// over an expensive m//g
594 } else { # count number of '\n' w/o '\r', expensive:
595 scalar(my @n = ($_[0] =~ m/(?<!\r)\n/g));
599 sub index_both { # git->cat_async callback
600 my ($bref, $oid, $type, $size, $sync) = @_;
601 my ($nr, $max) = @$sync{qw(nr max)};
604 $size += crlf_adjust($$bref);
605 my $smsg = bless { bytes => $size, blob => $oid }, 'PublicInbox::Smsg';
606 my $self = $sync->{sidx};
607 my $eml = PublicInbox::Eml->new($bref);
608 $smsg->{num} = index_mm($self, $eml, $oid, $sync) or
609 die "E: could not generate NNTP article number for $oid";
610 add_message($self, $eml, $smsg, $sync);
611 my $cur_cmt = $sync->{cur_cmt} // die 'BUG: {cur_cmt} missing';
612 ${$sync->{latest_cmt}} = $cur_cmt;
615 sub unindex_both { # git->cat_async callback
616 my ($bref, $oid, $type, $size, $sync) = @_;
617 unindex_eml($sync->{sidx}, $oid, PublicInbox::Eml->new($bref));
618 # may be undef if leftover
619 if (defined(my $cur_cmt = $sync->{cur_cmt})) {
620 ${$sync->{latest_cmt}} = $cur_cmt;
626 ($self->{ibx} // $self->{eidx})->with_umask(@_);
629 # called by public-inbox-index
631 my ($self, $opt) = @_;
632 delete $self->{lock_path} if $opt->{-skip_lock};
633 $self->with_umask(\&_index_sync, $self, $opt);
634 if ($opt->{reindex}) {
636 delete @again{qw(rethread reindex)};
637 index_sync($self, \%again);
641 sub check_size { # check_async cb for -index --max-size=...
642 my ($oid, $type, $size, $arg, $git) = @_;
643 (($type // '') eq 'blob') or die "E: bad $oid in $git->{git_dir}";
644 if ($size <= $arg->{max_size}) {
645 $git->cat_async($oid, $arg->{index_oid}, $arg);
647 warn "W: skipping $oid ($size > $arg->{max_size})\n";
651 sub v1_checkpoint ($$;$) {
652 my ($self, $sync, $stk) = @_;
653 $self->{ibx}->git->async_wait_all;
655 # $newest may be undef
656 my $newest = $stk ? $stk->{latest_cmt} : ${$sync->{latest_cmt}};
657 if (defined($newest)) {
658 my $cur = $self->{mm}->last_commit || '';
659 if (need_update($self, $cur, $newest)) {
660 $self->{mm}->last_commit($newest);
663 ${$sync->{max}} = $self->{batch_bytes};
665 $self->{mm}->{dbh}->commit;
666 my $xdb = need_xapian($self) ? $self->{xdb} : undef;
667 if ($newest && $xdb) {
668 my $cur = $xdb->get_metadata('last_commit');
669 if (need_update($self, $cur, $newest)) {
670 $xdb->set_metadata('last_commit', $newest);
673 if ($stk) { # all done if $stk is passed
674 # let SearchView know a full --reindex was done so it can
675 # generate ->has_threadid-dependent links
676 if ($xdb && $sync->{reindex} && !ref($sync->{reindex})) {
677 my $n = $xdb->get_metadata('has_threadid');
678 $xdb->set_metadata('has_threadid', '1') if $n ne '1';
680 $self->{oidx}->rethread_done($sync->{-opt}); # all done
682 commit_txn_lazy($self);
683 $sync->{ibx}->git->cleanup;
684 my $nr = ${$sync->{nr}};
685 idx_release($self, $nr);
686 # let another process do some work...
687 if (my $pr = $sync->{-opt}->{-progress}) {
688 $pr->("indexed $nr/$sync->{ntodo}\n") if $nr;
690 if (!$stk) { # more to come
691 begin_txn_lazy($self);
692 $self->{mm}->{dbh}->begin_work;
698 my ($self, $sync, $stk) = @_;
699 my $git = $sync->{ibx}->git;
700 my $max = $self->{batch_bytes};
703 $sync->{max} = \$max;
704 $sync->{sidx} = $self;
705 $sync->{latest_cmt} = \(my $latest_cmt);
707 $self->{mm}->{dbh}->begin_work;
708 if (my @leftovers = keys %{delete($sync->{D}) // {}}) {
709 warn('W: unindexing '.scalar(@leftovers)." leftovers\n");
710 for my $oid (@leftovers) {
711 $oid = unpack('H*', $oid);
712 $git->cat_async($oid, \&unindex_both, $sync);
715 if ($sync->{max_size} = $sync->{-opt}->{max_size}) {
716 $sync->{index_oid} = \&index_both;
718 while (my ($f, $at, $ct, $oid, $cur_cmt) = $stk->pop_rec) {
719 my $arg = { %$sync, cur_cmt => $cur_cmt };
721 $arg->{autime} = $at;
722 $arg->{cotime} = $ct;
723 if ($sync->{max_size}) {
724 $git->check_async($oid, \&check_size, $arg);
726 $git->cat_async($oid, \&index_both, $arg);
728 v1_checkpoint($self, $sync) if $max <= 0;
729 } elsif ($f eq 'd') {
730 $git->cat_async($oid, \&unindex_both, $arg);
733 v1_checkpoint($self, $sync, $stk);
736 sub log2stack ($$$) {
737 my ($sync, $git, $range) = @_;
738 my $D = $sync->{D}; # OID_BIN => NR (if reindexing, undef otherwise)
740 if ($sync->{ibx}->version == 1) {
741 my $path = $hex.'{2}/'.$hex.'{38}';
742 $add = qr!\A:000000 100644 \S+ ($OID) A\t$path$!;
743 $del = qr!\A:100644 000000 ($OID) \S+ D\t$path$!;
745 $del = qr!\A:\d{6} 100644 $OID ($OID) [AM]\td$!;
746 $add = qr!\A:\d{6} 100644 $OID ($OID) [AM]\tm$!;
749 # Count the new files so they can be added newest to oldest
750 # and still have numbers increasing from oldest to newest
751 my $fh = $git->popen(qw(log --raw -r --pretty=tformat:%at-%ct-%H
752 --no-notes --no-color --no-renames --no-abbrev),
754 my ($at, $ct, $stk, $cmt);
756 return if $sync->{quit};
757 if (/\A([0-9]+)-([0-9]+)-($OID)$/o) {
758 ($at, $ct, $cmt) = ($1 + 0, $2 + 0, $3);
759 $stk //= PublicInbox::IdxStack->new($cmt);
762 if ($D) { # reindex case
763 $D->{pack('H*', $oid)}++;
764 } else { # non-reindex case:
765 $stk->push_rec('d', $at, $ct, $oid, $cmt);
770 my $oid_bin = pack('H*', $oid);
771 my $nr = --$D->{$oid_bin};
772 delete($D->{$oid_bin}) if $nr <= 0;
773 # nr < 0 (-1) means it never existed
776 $stk->push_rec('m', $at, $ct, $oid, $cmt);
779 close $fh or die "git log failed: \$?=$?";
780 $stk //= PublicInbox::IdxStack->new;
784 sub prepare_stack ($$) {
785 my ($sync, $range) = @_;
786 my $git = $sync->{ibx}->git;
788 if (index($range, '..') < 0) {
789 # don't show annoying git errors to users who run -index
791 $git->qx(qw(rev-parse -q --verify), "$range^0");
792 return PublicInbox::IdxStack->new->read_prepare if $?;
794 $sync->{D} = $sync->{reindex} ? {} : undef; # OID_BIN => NR
795 log2stack($sync, $git, $range);
798 # --is-ancestor requires git 1.8.0+
799 sub is_ancestor ($$$) {
800 my ($git, $cur, $tip) = @_;
801 return 0 unless $git->check($cur);
802 my $cmd = [ 'git', "--git-dir=$git->{git_dir}",
803 qw(merge-base --is-ancestor), $cur, $tip ];
804 my $pid = spawn($cmd);
805 waitpid($pid, 0) == $pid or die join(' ', @$cmd) .' did not finish';
809 sub need_update ($$$) {
810 my ($self, $cur, $new) = @_;
811 my $git = $self->{ibx}->git;
812 return 1 if $cur && !is_ancestor($git, $cur, $new);
813 my $range = $cur eq '' ? $new : "$cur..$new";
814 chomp(my $n = $git->qx(qw(rev-list --count), $range));
815 ($n eq '' || $n > 0);
818 # The last git commit we indexed with Xapian or SQLite (msgmap)
819 # This needs to account for cases where Xapian or SQLite is
820 # out-of-date with respect to the other.
822 my ($self, $mm) = @_;
823 my $lm = $mm->last_commit || '';
825 if (need_xapian($self)) {
826 $lx = $self->{xdb}->get_metadata('last_commit') || '';
830 # Use last_commit from msgmap if it is older or unset
831 if (!$lm || ($lx && $lm && is_ancestor($self->{ibx}->git, $lm, $lx))) {
837 sub reindex_from ($$) {
838 my ($reindex, $last_commit) = @_;
839 return $last_commit unless $reindex;
840 ref($reindex) eq 'HASH' ? $reindex->{from} : '';
843 # indexes all unindexed messages (v1 only)
845 my ($self, $opt) = @_;
846 my $tip = $opt->{ref} || 'HEAD';
847 my $ibx = $self->{ibx};
848 $self->{batch_bytes} = $opt->{batch_size} // $BATCH_BYTES;
849 $ibx->git->batch_prepare;
850 my $pr = $opt->{-progress};
851 my $sync = { reindex => $opt->{reindex}, -opt => $opt, ibx => $ibx };
852 my $xdb = $self->begin_txn_lazy;
853 $self->{oidx}->rethread_prepare($opt);
854 my $mm = _msgmap_init($self);
855 if ($sync->{reindex}) {
856 my $last = $mm->last_commit;
860 # somebody just blindly added --reindex when indexing
861 # for the first time, allow it:
862 undef $sync->{reindex};
865 my $last_commit = _last_x_commit($self, $mm);
866 my $lx = reindex_from($sync->{reindex}, $last_commit);
867 my $range = $lx eq '' ? $tip : "$lx..$tip";
868 $pr->("counting changes\n\t$range ... ") if $pr;
869 my $stk = prepare_stack($sync, $range);
870 $sync->{ntodo} = $stk ? $stk->num_records : 0;
871 $pr->("$sync->{ntodo}\n") if $pr; # continue previous line
872 process_stack($self, $sync, $stk);
876 # order matters for unlocking
877 $_[0]->{xdb} = undef;
878 $_[0]->{lockfh} = undef;
883 my $xdb = $self->{xdb} || idx_acquire($self);
884 $self->{oidx}->begin_lazy if $self->{oidx};
885 $xdb->begin_transaction if $xdb;
892 $self->with_umask(\&_begin_txn, $self) if !$self->{txn};
895 # store 'indexlevel=medium' in v2 shard=0 and v1 (only one shard)
896 # This metadata is read by Admin::detect_indexlevel:
897 sub set_metadata_once {
900 return if $self->{shard}; # only continue if undef or 0, not >0
901 my $xdb = $self->{xdb};
903 if (delete($self->{-set_has_threadid_once})) {
904 $xdb->set_metadata('has_threadid', '1');
906 if (delete($self->{-set_indexlevel_once})) {
907 my $level = $xdb->get_metadata('indexlevel');
908 if (!$level || $level ne 'medium') {
909 $xdb->set_metadata('indexlevel', 'medium');
912 if (delete($self->{-set_skip_docdata_once})) {
913 $xdb->get_metadata('skip_docdata') or
914 $xdb->set_metadata('skip_docdata', '1');
920 if (my $xdb = $self->{xdb}) {
921 set_metadata_once($self);
922 $xdb->commit_transaction;
924 $self->{oidx}->commit_lazy if $self->{oidx};
927 sub commit_txn_lazy {
929 delete($self->{txn}) and
930 $self->with_umask(\&_commit_txn, $self);
935 if (need_xapian($self)) {
936 die "$$ $0 xdb not released\n" if $self->{xdb};
938 die "$$ $0 still in transaction\n" if $self->{txn};
942 my ($class, $eidx, $shard) = @_;
945 xpfx => $eidx->{xpfx},
946 indexlevel => $eidx->{indexlevel},
951 $self->{-set_indexlevel_once} = 1 if $self->{indexlevel} eq 'medium';