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
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;
18 use Carp qw(croak carp);
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 index_text term_generator add_val is_bad_blob);
27 my $X = \%PublicInbox::Search::X;
28 our ($DB_CREATE_OR_OPEN, $DB_OPEN);
30 our $BATCH_BYTES = $ENV{XAPIAN_FLUSH_THRESHOLD} ? 0x7fffffff : 1_000_000;
31 use constant DEBUG => !!$ENV{DEBUG};
33 my $xapianlevels = qr/\A(?:full|medium)\z/;
35 my $OID = $hex .'{40,}';
36 our $INDEXLEVELS = qr/\A(?:full|medium|basic)\z/;
39 my ($class, $ibx, $creat, $shard) = @_;
40 ref $ibx or die "BUG: expected PublicInbox::Inbox object: $ibx";
41 my $inboxdir = $ibx->{inboxdir};
42 my $version = $ibx->version;
43 my $indexlevel = 'full';
44 my $altid = $ibx->{altid};
46 require PublicInbox::AltId;
47 $altid = [ map { PublicInbox::AltId->new($ibx, $_); } @$altid ];
49 if ($ibx->{indexlevel}) {
50 if ($ibx->{indexlevel} =~ $INDEXLEVELS) {
51 $indexlevel = $ibx->{indexlevel};
53 die("Invalid indexlevel $ibx->{indexlevel}\n");
56 $ibx = PublicInbox::InboxWritable->new($ibx);
57 my $self = PublicInbox::Search->new($ibx);
60 $self->{-altid} = $altid;
61 $self->{indexlevel} = $indexlevel;
62 $self->{-set_indexlevel_once} = 1 if $indexlevel eq 'medium';
63 if ($ibx->{-skip_docdata}) {
64 $self->{-set_skip_docdata_once} = 1;
65 $self->{-skip_docdata} = 1;
69 $self->{lock_path} = "$inboxdir/ssoma.lock";
70 my $dir = $self->xdir;
71 $self->{oidx} = PublicInbox::OverIdx->new("$dir/over.sqlite3");
72 $self->{oidx}->{-no_fsync} = 1 if $ibx->{-no_fsync};
73 } elsif ($version == 2) {
74 defined $shard or die "shard is required for v2\n";
76 $self->{shard} = $shard;
77 $self->{lock_path} = undef;
79 die "unsupported inbox version=$version\n";
81 $self->{creat} = ($creat || 0) == 1;
85 sub need_xapian ($) { $_[0]->{indexlevel} =~ $xapianlevels }
88 my ($self, $wake) = @_;
89 if (need_xapian($self)) {
90 my $xdb = delete $self->{xdb} or croak 'not acquired';
93 $self->lock_release($wake) if $self->{creat};
97 sub load_xapian_writable () {
98 return 1 if $X->{WritableDatabase};
99 PublicInbox::Search::load_xapian() or return;
100 my $xap = $PublicInbox::Search::Xap;
101 for (qw(Document TermGenerator WritableDatabase)) {
102 $X->{$_} = $xap.'::'.$_;
104 eval 'require '.$X->{WritableDatabase} or die;
105 *sortable_serialise = $xap.'::sortable_serialise';
106 *sortable_unserialise = $xap.'::sortable_unserialise';
107 $DB_CREATE_OR_OPEN = eval($xap.'::DB_CREATE_OR_OPEN()');
108 $DB_OPEN = eval($xap.'::DB_OPEN()');
109 my $ver = (eval($xap.'::major_version()') << 16) |
110 (eval($xap.'::minor_version()') << 8);
111 $DB_NO_SYNC = 0x4 if $ver >= 0x10400;
118 my $dir = $self->xdir;
119 if (need_xapian($self)) {
120 croak 'already acquired' if $self->{xdb};
121 load_xapian_writable();
122 $flag = $self->{creat} ? $DB_CREATE_OR_OPEN : $DB_OPEN;
124 if ($self->{creat}) {
128 # don't create empty Xapian directories if we don't need Xapian
129 my $is_shard = defined($self->{shard});
130 if (!-d $dir && (!$is_shard ||
131 ($is_shard && need_xapian($self)))) {
132 File::Path::mkpath($dir);
134 $self->{-set_has_threadid_once} = 1;
137 return unless defined $flag;
138 $flag |= $DB_NO_SYNC if ($self->{ibx} // $self->{eidx})->{-no_fsync};
139 my $xdb = eval { ($X->{WritableDatabase})->new($dir, $flag) };
140 croak "Failed opening $dir: $@" if $@;
145 my ($doc, $col, $num) = @_;
146 $num = sortable_serialise($num);
147 $doc->add_value($col, $num);
150 sub term_generator ($) { # write-only
153 $self->{term_generator} //= do {
154 my $tg = $X->{TermGenerator}->new;
155 $tg->set_stemmer(PublicInbox::Search::stemmer($self));
160 sub index_text ($$$$) {
161 my ($self, $text, $wdf_inc, $prefix) = @_;
162 my $tg = term_generator($self); # man Search::Xapian::TermGenerator
164 if ($self->{indexlevel} eq 'full') {
165 $tg->index_text($text, $wdf_inc, $prefix);
166 $tg->increase_termpos;
168 $tg->index_text_without_positions($text, $wdf_inc, $prefix);
172 sub index_headers ($$) {
173 my ($self, $smsg) = @_;
174 my @x = (from => 'A', # Author
175 subject => 'S', to => 'XTO', cc => 'XCC');
176 while (my ($field, $pfx) = splice(@x, 0, 2)) {
177 my $val = $smsg->{$field};
178 index_text($self, $val, 1, $pfx) if $val ne '';
182 sub index_diff_inc ($$$$) {
183 my ($self, $text, $pfx, $xnq) = @_;
185 index_text($self, join("\n", @$xnq), 1, 'XNQ');
188 index_text($self, $text, 1, $pfx);
191 sub index_old_diff_fn {
192 my ($self, $seen, $fa, $fb, $xnq) = @_;
194 # no renames or space support for traditional diffs,
195 # find the number of leading common paths to strip:
196 my @fa = split('/', $fa);
197 my @fb = split('/', $fb);
198 while (scalar(@fa) && scalar(@fb)) {
199 $fa = join('/', @fa);
200 $fb = join('/', @fb);
202 unless ($seen->{$fa}++) {
203 index_diff_inc($self, $fa, 'XDFN', $xnq);
213 sub index_diff ($$$) {
214 my ($self, $txt, $doc) = @_;
219 foreach (split(/\n/, $txt)) {
220 if ($in_diff && s/^ //) { # diff context
221 index_diff_inc($self, $_, 'XDFCTX', $xnq);
222 } elsif (/^-- $/) { # email signature begins
224 } elsif (m!^diff --git "?[^/]+/.+ "?[^/]+/.+\z!) {
225 # wait until "---" and "+++" to capture filenames
228 } elsif (m/^diff -(.+) (\S+) (\S+)$/) {
229 my ($opt, $fa, $fb) = ($1, $2, $3);
231 # only support unified:
232 next unless $opt =~ /[uU]/;
233 $in_diff = index_old_diff_fn($self, \%seen, $fa, $fb,
235 } elsif (m!^--- ("?[^/]+/.+)!) {
237 $fn = (split('/', git_unquote($fn), 2))[1];
238 $seen{$fn}++ or index_diff_inc($self, $fn, 'XDFN', $xnq);
240 } elsif (m!^\+\+\+ ("?[^/]+/.+)!) {
242 $fn = (split('/', git_unquote($fn), 2))[1];
243 $seen{$fn}++ or index_diff_inc($self, $fn, 'XDFN', $xnq);
245 } elsif (/^--- (\S+)/) {
248 } elsif (defined $in_diff && /^\+\+\+ (\S+)/) {
249 $in_diff = index_old_diff_fn($self, \%seen, $in_diff,
251 } elsif ($in_diff && s/^\+//) { # diff added
252 index_diff_inc($self, $_, 'XDFB', $xnq);
253 } elsif ($in_diff && s/^-//) { # diff removed
254 index_diff_inc($self, $_, 'XDFA', $xnq);
255 } elsif (m!^index ([a-f0-9]+)\.\.([a-f0-9]+)!) {
256 my ($ba, $bb) = ($1, $2);
257 index_git_blob_id($doc, 'XDFPRE', $ba);
258 index_git_blob_id($doc, 'XDFPOST', $bb);
260 } elsif (/^@@ (?:\S+) (?:\S+) @@\s*$/) {
261 # traditional diff w/o -p
262 } elsif (/^@@ (?:\S+) (?:\S+) @@\s*(\S+.*)$/) {
263 # hunk header context
264 index_diff_inc($self, $1, 'XDFHH', $xnq);
265 # ignore the following lines:
266 } elsif (/^(?:dis)similarity index/ ||
267 /^(?:old|new) mode/ ||
268 /^(?:deleted|new) file mode/ ||
269 /^(?:copy|rename) (?:from|to) / ||
270 /^(?:dis)?similarity index / ||
271 /^\\ No newline at end of file/ ||
272 /^Binary files .* differ/) {
275 # possible to be in diff context, some mail may be
276 # stripped by MUA or even GNU diff(1). "git apply"
277 # treats a bare "\n" as diff context, too
280 warn "non-diff line: $_\n" if DEBUG && $_ ne '';
285 index_text($self, join("\n", @xnq), 1, 'XNQ');
288 sub index_xapian { # msg_iter callback
289 my $part = $_[0]->[0]; # ignore $depth and $idx
290 my ($self, $doc) = @{$_[1]};
291 my $ct = $part->content_type || 'text/plain';
292 my $fn = $part->filename;
293 if (defined $fn && $fn ne '') {
294 index_text($self, $fn, 1, 'XFN');
296 if ($part->{is_submsg}) {
297 my $mids = mids_for_index($part);
298 index_ids($self, $doc, $part, $mids);
299 my $smsg = bless {}, 'PublicInbox::Smsg';
300 $smsg->populate($part);
301 index_headers($self, $smsg);
304 my ($s, undef) = msg_part_text($part, $ct);
305 defined $s or return;
306 $_[0]->[0] = $part = undef; # free memory
308 # split off quoted and unquoted blocks:
309 my @sections = PublicInbox::MsgIter::split_quotes($s);
310 undef $s; # free memory
311 for my $txt (@sections) {
313 index_text($self, $txt, 0, 'XQUOT');
315 # does it look like a diff?
316 if ($txt =~ /^(?:diff|---|\+\+\+) /ms) {
317 index_diff($self, $txt, $doc);
319 index_text($self, $txt, 1, 'XNQ');
322 undef $txt; # free memory
326 sub index_list_id ($$$) {
327 my ($self, $doc, $hdr) = @_;
328 for my $l ($hdr->header_raw('List-Id')) {
329 $l =~ /<([^>]+)>/ or next;
331 $doc->add_boolean_term('G' . $lid);
332 index_text($self, $lid, 1, 'XL'); # probabilistic
336 sub index_ids ($$$$) {
337 my ($self, $doc, $hdr, $mids) = @_;
338 for my $mid (@$mids) {
339 index_text($self, $mid, 1, 'XM');
341 # because too many Message-IDs are prefixed with
343 if ($mid =~ /\w{12,}/) {
344 my @long = ($mid =~ /(\w{3,}+)/g);
345 index_text($self, join(' ', @long), 1, 'XM');
348 $doc->add_boolean_term('Q' . $_) for @$mids;
349 index_list_id($self, $doc, $hdr);
352 sub eml2doc ($$$;$) {
353 my ($self, $eml, $smsg, $mids) = @_;
354 $mids //= mids_for_index($eml);
355 my $doc = $X->{Document}->new;
356 add_val($doc, PublicInbox::Search::TS(), $smsg->{ts});
357 my @ds = gmtime($smsg->{ds});
358 my $yyyymmdd = strftime('%Y%m%d', @ds);
359 add_val($doc, PublicInbox::Search::YYYYMMDD(), $yyyymmdd);
360 my $dt = strftime('%Y%m%d%H%M%S', @ds);
361 add_val($doc, PublicInbox::Search::DT(), $dt);
362 add_val($doc, PublicInbox::Search::BYTES(), $smsg->{bytes});
363 add_val($doc, PublicInbox::Search::UID(), $smsg->{num});
364 add_val($doc, PublicInbox::Search::THREADID, $smsg->{tid});
366 my $tg = term_generator($self);
367 $tg->set_document($doc);
368 index_headers($self, $smsg);
370 if (defined(my $eidx_key = $smsg->{eidx_key})) {
371 $doc->add_boolean_term('O'.$eidx_key) if $eidx_key ne '.';
373 msg_iter($eml, \&index_xapian, [ $self, $doc ]);
374 index_ids($self, $doc, $eml, $mids);
376 # by default, we maintain compatibility with v1.5.0 and earlier
377 # by writing to docdata.glass, users who never exect to downgrade can
379 if (!$self->{-skip_docdata}) {
380 # WWW doesn't need {to} or {cc}, only NNTP
381 $smsg->{to} = $smsg->{cc} = '';
382 PublicInbox::OverIdx::parse_references($smsg, $eml, $mids);
383 my $data = $smsg->to_doc_data;
384 $doc->set_data($data);
387 if (my $altid = $self->{-altid}) {
388 foreach my $alt (@$altid) {
389 my $pfx = $alt->{xprefix};
390 foreach my $mid (@$mids) {
391 my $id = $alt->mid2alt($mid);
392 next unless defined $id;
393 $doc->add_boolean_term($pfx . $id);
400 sub add_xapian ($$$$) {
401 my ($self, $eml, $smsg, $mids) = @_;
402 my $doc = eml2doc($self, $eml, $smsg, $mids);
403 $self->{xdb}->replace_document($smsg->{num}, $doc);
406 sub _msgmap_init ($) {
408 die "BUG: _msgmap_init is only for v1\n" if $self->{ibx}->version != 1;
409 $self->{mm} //= eval {
410 require PublicInbox::Msgmap;
411 my $rw = $self->{ibx}->{-no_fsync} ? 2 : 1;
412 PublicInbox::Msgmap->new($self->{ibx}->{inboxdir}, $rw);
417 # mime = PublicInbox::Eml or Email::MIME object
418 my ($self, $mime, $smsg, $sync) = @_;
419 my $mids = mids_for_index($mime);
420 $smsg //= bless { blob => '' }, 'PublicInbox::Smsg'; # test-only compat
421 $smsg->{mid} //= $mids->[0]; # v1 compatibility
422 $smsg->{num} //= do { # v1
424 index_mm($self, $mime, $smsg->{blob}, $sync);
428 $smsg->populate($mime, $sync);
429 $smsg->{bytes} //= length($mime->as_string);
432 # order matters, overview stores every possible piece of
433 # data in doc_data (deflated). Xapian only stores a subset
434 # of the fields which exist in over.sqlite3. We may stop
435 # storing doc_data in Xapian sometime after we get multi-inbox
437 if (my $oidx = $self->{oidx}) { # v1 only
438 $oidx->add_overview($mime, $smsg);
440 if (need_xapian($self)) {
441 add_xapian($self, $mime, $smsg, $mids);
446 warn "failed to index message <".join('> <',@$mids).">: $@\n";
453 my ($self, $docid) = @_;
454 my $doc = eval { $self->{xdb}->get_document($docid) };
456 warn "E: $@\n" if $@;
457 warn "E: #$docid missing in Xapian\n";
463 my ($self, $docid, $eidx_key, $eml) = @_;
464 begin_txn_lazy($self);
465 my $doc = _get_doc($self, $docid) or return;
466 term_generator($self)->set_document($doc);
467 $doc->add_boolean_term('O'.$eidx_key) if $eidx_key ne '.';
468 index_list_id($self, $doc, $eml);
469 $self->{xdb}->replace_document($docid, $doc);
472 sub remove_eidx_info {
473 my ($self, $docid, $eidx_key, $eml) = @_;
474 begin_txn_lazy($self);
475 my $doc = _get_doc($self, $docid) or return;
476 eval { $doc->remove_term('O'.$eidx_key) };
477 warn "W: ->remove_term O$eidx_key: $@\n" if $@;
478 for my $l ($eml ? $eml->header_raw('List-Id') : ()) {
479 $l =~ /<([^>]+)>/ or next;
481 eval { $doc->remove_term('G' . $lid) };
482 warn "W: ->remove_term G$lid: $@\n" if $@;
484 # nb: we don't remove the XL probabilistic terms
485 # since terms may overlap if cross-posted.
487 # IOW, a message which has both <foo.example.com>
488 # and <bar.example.com> would have overlapping
489 # "XLexample" and "XLcom" as terms and which we
490 # wouldn't know if they're safe to remove if we just
491 # unindex <foo.example.com> while preserving
494 # In any case, this entire sub is will likely never
495 # be needed and users using the "l:" prefix are probably
498 $self->{xdb}->replace_document($docid, $doc);
502 my ($self, $docid, @kw) = @_;
503 begin_txn_lazy($self);
504 my $doc = _get_doc($self, $docid) or return;
505 my %keep = map { $_ => 1 } @kw;
508 my $end = $doc->termlist_end;
509 for (my $cur = $doc->termlist_begin; $cur != $end; $cur++) {
511 last if $cur == $end;
512 my $kw = $cur->get_termname;
513 $kw =~ s/\AK//s or next;
514 $keep{$kw} ? delete($add{$kw}) : push(@rm, $kw);
516 return unless (scalar(@rm) + scalar(keys %add));
517 $doc->remove_term('K'.$_) for @rm;
518 $doc->add_boolean_term('K'.$_) for (keys %add);
519 $self->{xdb}->replace_document($docid, $doc);
523 my ($self, $docid, @kw) = @_;
524 begin_txn_lazy($self);
525 my $doc = _get_doc($self, $docid) or return;
526 $doc->add_boolean_term('K'.$_) for @kw;
527 $self->{xdb}->replace_document($docid, $doc);
530 sub remove_keywords {
531 my ($self, $docid, @kw) = @_;
532 begin_txn_lazy($self);
533 my $doc = _get_doc($self, $docid) or return;
536 $doc->remove_term('K'.$_);
539 $self->{xdb}->replace_document($docid, $doc) if $replace;
543 my ($doc, $col) = @_;
544 sortable_unserialise($doc->get_value($col));
547 sub smsg_from_doc ($) {
549 my $data = $doc->get_data or return;
550 my $smsg = bless {}, 'PublicInbox::Smsg';
551 $smsg->{ts} = get_val($doc, PublicInbox::Search::TS());
552 my $dt = get_val($doc, PublicInbox::Search::DT());
553 my ($yyyy, $mon, $dd, $hh, $mm, $ss) = unpack('A4A2A2A2A2A2', $dt);
554 $smsg->{ds} = timegm($ss, $mm, $hh, $dd, $mon - 1, $yyyy);
555 $smsg->load_from_data($data);
560 my ($self, @docids) = @_;
561 my $xdb = $self->{xdb} or return;
562 for my $docid (@docids) {
563 eval { $xdb->delete_document($docid) };
564 warn "E: #$docid not in in Xapian? $@\n" if $@;
568 sub remove_by_docid {
569 my ($self, $num) = @_;
570 die "BUG: remove_by_docid is v2-only\n" if $self->{oidx};
571 $self->begin_txn_lazy;
572 xdb_remove($self, $num) if need_xapian($self);
575 sub index_git_blob_id {
576 my ($doc, $pfx, $objid) = @_;
578 my $len = length($objid);
579 for (my $len = length($objid); $len >= 7; ) {
580 $doc->add_term($pfx.$objid);
581 $objid = substr($objid, 0, --$len);
587 my ($self, $oid, $eml) = @_;
588 my $mids = mids($eml);
591 for my $mid (@$mids) {
592 my @removed = $self->{oidx}->remove_oid($oid, $mid);
593 $nr += scalar @removed;
594 $tmp{$_}++ for @removed;
597 my $m = join('> <', @$mids);
598 warn "W: <$m> missing for removal from overview\n";
600 while (my ($num, $nr) = each %tmp) {
601 warn "BUG: $num appears >1 times ($nr) for $oid\n" if $nr != 1;
604 $self->{mm}->num_delete($_) for (keys %tmp);
605 } else { # just in case msgmap and over.sqlite3 become desynched:
606 $self->{mm}->mid_delete($mids->[0]);
608 xdb_remove($self, keys %tmp) if need_xapian($self);
612 my ($self, $mime, $oid, $sync) = @_;
613 my $mids = mids($mime);
614 my $mm = $self->{mm};
615 if ($sync->{reindex}) {
616 my $oidx = $self->{oidx};
617 for my $mid (@$mids) {
618 my ($num, undef) = $oidx->num_mid0_for_oid($oid, $mid);
619 return $num if defined $num;
621 $mm->num_for($mids->[0]) // $mm->mid_insert($mids->[0]);
623 # fallback to num_for since filters like RubyLang set the number
624 $mm->mid_insert($mids->[0]) // $mm->num_for($mids->[0]);
628 # returns the number of bytes to add if given a non-CRLF arg
629 sub crlf_adjust ($) {
630 if (index($_[0], "\r\n") < 0) {
631 # common case is LF-only, every \n needs an \r;
632 # so favor a cheap tr// over an expensive m//g
634 } else { # count number of '\n' w/o '\r', expensive:
635 scalar(my @n = ($_[0] =~ m/(?<!\r)\n/g));
639 sub is_bad_blob ($$$$) {
640 my ($oid, $type, $size, $expect_oid) = @_;
641 if ($type ne 'blob') {
642 carp "W: $expect_oid is not a blob (type=$type)";
645 croak "BUG: $oid != $expect_oid" if $oid ne $expect_oid;
646 $size == 0 ? 1 : 0; # size == 0 means purged
649 sub index_both { # git->cat_async callback
650 my ($bref, $oid, $type, $size, $sync) = @_;
651 return if is_bad_blob($oid, $type, $size, $sync->{oid});
652 my ($nr, $max) = @$sync{qw(nr max)};
655 $size += crlf_adjust($$bref);
656 my $smsg = bless { bytes => $size, blob => $oid }, 'PublicInbox::Smsg';
657 my $self = $sync->{sidx};
658 local $self->{current_info} = "$self->{current_info}: $oid";
659 my $eml = PublicInbox::Eml->new($bref);
660 $smsg->{num} = index_mm($self, $eml, $oid, $sync) or
661 die "E: could not generate NNTP article number for $oid";
662 add_message($self, $eml, $smsg, $sync);
663 my $cur_cmt = $sync->{cur_cmt} // die 'BUG: {cur_cmt} missing';
664 ${$sync->{latest_cmt}} = $cur_cmt;
667 sub unindex_both { # git->cat_async callback
668 my ($bref, $oid, $type, $size, $sync) = @_;
669 return if is_bad_blob($oid, $type, $size, $sync->{oid});
670 my $self = $sync->{sidx};
671 local $self->{current_info} = "$self->{current_info}: $oid";
672 unindex_eml($self, $oid, PublicInbox::Eml->new($bref));
673 # may be undef if leftover
674 if (defined(my $cur_cmt = $sync->{cur_cmt})) {
675 ${$sync->{latest_cmt}} = $cur_cmt;
681 ($self->{ibx} // $self->{eidx})->with_umask(@_);
684 # called by public-inbox-index
686 my ($self, $opt) = @_;
687 delete $self->{lock_path} if $opt->{-skip_lock};
688 $self->with_umask(\&_index_sync, $self, $opt);
689 if ($opt->{reindex} && !$opt->{quit}) {
691 delete @again{qw(rethread reindex)};
692 index_sync($self, \%again);
693 $opt->{quit} = $again{quit}; # propagate to caller
697 sub check_size { # check_async cb for -index --max-size=...
698 my ($oid, $type, $size, $arg, $git) = @_;
699 (($type // '') eq 'blob') or die "E: bad $oid in $git->{git_dir}";
700 if ($size <= $arg->{max_size}) {
701 $git->cat_async($oid, $arg->{index_oid}, $arg);
703 warn "W: skipping $oid ($size > $arg->{max_size})\n";
707 sub v1_checkpoint ($$;$) {
708 my ($self, $sync, $stk) = @_;
709 $self->{ibx}->git->async_wait_all;
711 # $newest may be undef
712 my $newest = $stk ? $stk->{latest_cmt} : ${$sync->{latest_cmt}};
713 if (defined($newest)) {
714 my $cur = $self->{mm}->last_commit || '';
715 if (need_update($self, $cur, $newest)) {
716 $self->{mm}->last_commit($newest);
719 ${$sync->{max}} = $self->{batch_bytes};
721 $self->{mm}->{dbh}->commit;
722 my $xdb = need_xapian($self) ? $self->{xdb} : undef;
723 if ($newest && $xdb) {
724 my $cur = $xdb->get_metadata('last_commit');
725 if (need_update($self, $cur, $newest)) {
726 $xdb->set_metadata('last_commit', $newest);
729 if ($stk) { # all done if $stk is passed
730 # let SearchView know a full --reindex was done so it can
731 # generate ->has_threadid-dependent links
732 if ($xdb && $sync->{reindex} && !ref($sync->{reindex})) {
733 my $n = $xdb->get_metadata('has_threadid');
734 $xdb->set_metadata('has_threadid', '1') if $n ne '1';
736 $self->{oidx}->rethread_done($sync->{-opt}); # all done
738 commit_txn_lazy($self);
739 $sync->{ibx}->git->cleanup;
740 my $nr = ${$sync->{nr}};
741 idx_release($self, $nr);
742 # let another process do some work...
743 if (my $pr = $sync->{-opt}->{-progress}) {
744 $pr->("indexed $nr/$sync->{ntodo}\n") if $nr;
746 if (!$stk && !$sync->{quit}) { # more to come
747 begin_txn_lazy($self);
748 $self->{mm}->{dbh}->begin_work;
754 my ($self, $sync, $stk) = @_;
755 my $git = $sync->{ibx}->git;
756 my $max = $self->{batch_bytes};
759 $sync->{max} = \$max;
760 $sync->{sidx} = $self;
761 $sync->{latest_cmt} = \(my $latest_cmt);
763 $self->{mm}->{dbh}->begin_work;
764 if (my @leftovers = keys %{delete($sync->{D}) // {}}) {
765 warn('W: unindexing '.scalar(@leftovers)." leftovers\n");
766 for my $oid (@leftovers) {
767 last if $sync->{quit};
768 $oid = unpack('H*', $oid);
769 $git->cat_async($oid, \&unindex_both, $sync);
772 if ($sync->{max_size} = $sync->{-opt}->{max_size}) {
773 $sync->{index_oid} = \&index_both;
775 while (my ($f, $at, $ct, $oid, $cur_cmt) = $stk->pop_rec) {
776 my $arg = { %$sync, cur_cmt => $cur_cmt, oid => $oid };
777 last if $sync->{quit};
779 $arg->{autime} = $at;
780 $arg->{cotime} = $ct;
781 if ($sync->{max_size}) {
782 $git->check_async($oid, \&check_size, $arg);
784 $git->cat_async($oid, \&index_both, $arg);
786 v1_checkpoint($self, $sync) if $max <= 0;
787 } elsif ($f eq 'd') {
788 $git->cat_async($oid, \&unindex_both, $arg);
791 v1_checkpoint($self, $sync, $sync->{quit} ? undef : $stk);
794 sub log2stack ($$$) {
795 my ($sync, $git, $range) = @_;
796 my $D = $sync->{D}; # OID_BIN => NR (if reindexing, undef otherwise)
798 if ($sync->{ibx}->version == 1) {
799 my $path = $hex.'{2}/'.$hex.'{38}';
800 $add = qr!\A:000000 100644 \S+ ($OID) A\t$path$!;
801 $del = qr!\A:100644 000000 ($OID) \S+ D\t$path$!;
803 $del = qr!\A:\d{6} 100644 $OID ($OID) [AM]\td$!;
804 $add = qr!\A:\d{6} 100644 $OID ($OID) [AM]\tm$!;
807 # Count the new files so they can be added newest to oldest
808 # and still have numbers increasing from oldest to newest
809 my $fh = $git->popen(qw(log --raw -r --pretty=tformat:%at-%ct-%H
810 --no-notes --no-color --no-renames --no-abbrev),
812 my ($at, $ct, $stk, $cmt);
814 return if $sync->{quit};
815 if (/\A([0-9]+)-([0-9]+)-($OID)$/o) {
816 ($at, $ct, $cmt) = ($1 + 0, $2 + 0, $3);
817 $stk //= PublicInbox::IdxStack->new($cmt);
820 if ($D) { # reindex case
821 $D->{pack('H*', $oid)}++;
822 } else { # non-reindex case:
823 $stk->push_rec('d', $at, $ct, $oid, $cmt);
828 my $oid_bin = pack('H*', $oid);
829 my $nr = --$D->{$oid_bin};
830 delete($D->{$oid_bin}) if $nr <= 0;
831 # nr < 0 (-1) means it never existed
834 $stk->push_rec('m', $at, $ct, $oid, $cmt);
837 close $fh or die "git log failed: \$?=$?";
838 $stk //= PublicInbox::IdxStack->new;
842 sub prepare_stack ($$) {
843 my ($sync, $range) = @_;
844 my $git = $sync->{ibx}->git;
846 if (index($range, '..') < 0) {
847 # don't show annoying git errors to users who run -index
849 $git->qx(qw(rev-parse -q --verify), "$range^0");
850 return PublicInbox::IdxStack->new->read_prepare if $?;
852 $sync->{D} = $sync->{reindex} ? {} : undef; # OID_BIN => NR
853 log2stack($sync, $git, $range);
856 # --is-ancestor requires git 1.8.0+
857 sub is_ancestor ($$$) {
858 my ($git, $cur, $tip) = @_;
859 return 0 unless $git->check($cur);
860 my $cmd = [ 'git', "--git-dir=$git->{git_dir}",
861 qw(merge-base --is-ancestor), $cur, $tip ];
862 my $pid = spawn($cmd);
863 waitpid($pid, 0) == $pid or die join(' ', @$cmd) .' did not finish';
867 sub need_update ($$$) {
868 my ($self, $cur, $new) = @_;
869 my $git = $self->{ibx}->git;
870 return 1 if $cur && !is_ancestor($git, $cur, $new);
871 my $range = $cur eq '' ? $new : "$cur..$new";
872 chomp(my $n = $git->qx(qw(rev-list --count), $range));
873 ($n eq '' || $n > 0);
876 # The last git commit we indexed with Xapian or SQLite (msgmap)
877 # This needs to account for cases where Xapian or SQLite is
878 # out-of-date with respect to the other.
880 my ($self, $mm) = @_;
881 my $lm = $mm->last_commit || '';
883 if (need_xapian($self)) {
884 $lx = $self->{xdb}->get_metadata('last_commit') || '';
888 # Use last_commit from msgmap if it is older or unset
889 if (!$lm || ($lx && $lm && is_ancestor($self->{ibx}->git, $lm, $lx))) {
895 sub reindex_from ($$) {
896 my ($reindex, $last_commit) = @_;
897 return $last_commit unless $reindex;
898 ref($reindex) eq 'HASH' ? $reindex->{from} : '';
904 # we set {-opt}->{quit} too, so ->index_sync callers
905 # can abort multi-inbox loops this way
906 $sync->{quit} = $sync->{-opt}->{quit} = 1;
907 warn "gracefully quitting\n";
911 # indexes all unindexed messages (v1 only)
913 my ($self, $opt) = @_;
914 my $tip = $opt->{ref} || 'HEAD';
915 my $ibx = $self->{ibx};
916 local $self->{current_info} = "$ibx->{inboxdir}";
917 $self->{batch_bytes} = $opt->{batch_size} // $BATCH_BYTES;
918 $ibx->git->batch_prepare;
919 my $pr = $opt->{-progress};
920 my $sync = { reindex => $opt->{reindex}, -opt => $opt, ibx => $ibx };
921 my $quit = quit_cb($sync);
922 local $SIG{QUIT} = $quit;
923 local $SIG{INT} = $quit;
924 local $SIG{TERM} = $quit;
925 my $xdb = $self->begin_txn_lazy;
926 $self->{oidx}->rethread_prepare($opt);
927 my $mm = _msgmap_init($self);
928 if ($sync->{reindex}) {
929 my $last = $mm->last_commit;
933 # somebody just blindly added --reindex when indexing
934 # for the first time, allow it:
935 undef $sync->{reindex};
938 my $last_commit = _last_x_commit($self, $mm);
939 my $lx = reindex_from($sync->{reindex}, $last_commit);
940 my $range = $lx eq '' ? $tip : "$lx..$tip";
941 $pr->("counting changes\n\t$range ... ") if $pr;
942 my $stk = prepare_stack($sync, $range);
943 $sync->{ntodo} = $stk ? $stk->num_records : 0;
944 $pr->("$sync->{ntodo}\n") if $pr; # continue previous line
945 process_stack($self, $sync, $stk) if !$sync->{quit};
949 # order matters for unlocking
950 $_[0]->{xdb} = undef;
951 $_[0]->{lockfh} = undef;
956 my $xdb = $self->{xdb} || idx_acquire($self);
957 $self->{oidx}->begin_lazy if $self->{oidx};
958 $xdb->begin_transaction if $xdb;
965 $self->with_umask(\&_begin_txn, $self) if !$self->{txn};
968 # store 'indexlevel=medium' in v2 shard=0 and v1 (only one shard)
969 # This metadata is read by Admin::detect_indexlevel:
970 sub set_metadata_once {
973 return if $self->{shard}; # only continue if undef or 0, not >0
974 my $xdb = $self->{xdb};
976 if (delete($self->{-set_has_threadid_once})) {
977 $xdb->set_metadata('has_threadid', '1');
979 if (delete($self->{-set_indexlevel_once})) {
980 my $level = $xdb->get_metadata('indexlevel');
981 if (!$level || $level ne 'medium') {
982 $xdb->set_metadata('indexlevel', 'medium');
985 if (delete($self->{-set_skip_docdata_once})) {
986 $xdb->get_metadata('skip_docdata') or
987 $xdb->set_metadata('skip_docdata', '1');
993 if (my $eidx = $self->{eidx}) {
994 $eidx->git->async_wait_all;
995 $eidx->{transact_bytes} = 0;
997 if (my $xdb = $self->{xdb}) {
998 set_metadata_once($self);
999 $xdb->commit_transaction;
1001 $self->{oidx}->commit_lazy if $self->{oidx};
1004 sub commit_txn_lazy {
1006 delete($self->{txn}) and
1007 $self->with_umask(\&_commit_txn, $self);
1012 if (need_xapian($self)) {
1013 die "$$ $0 xdb not released\n" if $self->{xdb};
1015 die "$$ $0 still in transaction\n" if $self->{txn};
1018 sub eidx_shard_new {
1019 my ($class, $eidx, $shard) = @_;
1022 xpfx => $eidx->{xpfx},
1023 indexlevel => $eidx->{indexlevel},
1028 $self->{-set_indexlevel_once} = 1 if $self->{indexlevel} eq 'medium';
1032 # ensure there's no stale Xapian docs by treating $over as canonical
1034 my ($self, $over) = @_;
1035 begin_txn_lazy($self);
1036 my $sth = $over->dbh->prepare(<<'');
1037 SELECT COUNT(*) FROM over WHERE num = ?
1039 my $xdb = $self->{xdb};
1040 my $cur = $xdb->postlist_begin('');
1041 my $end = $xdb->postlist_end('');
1042 my $xdir = $self->xdir;
1043 for (; $cur != $end; $cur++) {
1044 my $docid = $cur->get_docid;
1045 $sth->execute($docid);
1046 my $x = $sth->fetchrow_array;
1048 warn "I: removing $xdir #$docid, not in `over'\n";
1049 $xdb->delete_document($docid);