1 # Copyright (C) 2015-2021 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 use PublicInbox::Address;
26 our @EXPORT_OK = qw(log2stack is_ancestor check_size prepare_stack
27 index_text term_generator add_val is_bad_blob);
28 my $X = \%PublicInbox::Search::X;
29 our ($DB_CREATE_OR_OPEN, $DB_OPEN);
31 our $BATCH_BYTES = $ENV{XAPIAN_FLUSH_THRESHOLD} ? 0x7fffffff : 1_000_000;
32 use constant DEBUG => !!$ENV{DEBUG};
34 my $xapianlevels = qr/\A(?:full|medium)\z/;
36 my $OID = $hex .'{40,}';
37 our $INDEXLEVELS = qr/\A(?:full|medium|basic)\z/;
40 my ($class, $ibx, $creat, $shard) = @_;
41 ref $ibx or die "BUG: expected PublicInbox::Inbox object: $ibx";
42 my $inboxdir = $ibx->{inboxdir};
43 my $version = $ibx->version;
44 my $indexlevel = 'full';
45 my $altid = $ibx->{altid};
47 require PublicInbox::AltId;
48 $altid = [ map { PublicInbox::AltId->new($ibx, $_); } @$altid ];
50 if ($ibx->{indexlevel}) {
51 if ($ibx->{indexlevel} =~ $INDEXLEVELS) {
52 $indexlevel = $ibx->{indexlevel};
54 die("Invalid indexlevel $ibx->{indexlevel}\n");
57 $ibx = PublicInbox::InboxWritable->new($ibx);
58 my $self = PublicInbox::Search->new($ibx);
61 $self->{-altid} = $altid;
62 $self->{indexlevel} = $indexlevel;
63 $self->{-set_indexlevel_once} = 1 if $indexlevel eq 'medium';
64 if ($ibx->{-skip_docdata}) {
65 $self->{-set_skip_docdata_once} = 1;
66 $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 $DB_CREATE_OR_OPEN = eval($xap.'::DB_CREATE_OR_OPEN()');
107 $DB_OPEN = eval($xap.'::DB_OPEN()');
108 my $ver = (eval($xap.'::major_version()') << 16) |
109 (eval($xap.'::minor_version()') << 8) |
110 eval($xap.'::revision()');
111 $DB_NO_SYNC = 0x4 if $ver >= 0x10400;
112 # Xapian v1.2.21..v1.2.24 were missing close-on-exec on OFD locks
113 $X->{CLOEXEC_UNSET} = 1 if $ver >= 0x010215 && $ver <= 0x010218;
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(PublicInbox::Search::stemmer($self));
162 sub index_phrase ($$$$) {
163 my ($self, $text, $wdf_inc, $prefix) = @_;
165 my $tg = term_generator($self);
166 $tg->index_text($text, $wdf_inc, $prefix);
167 $tg->increase_termpos;
170 sub index_text ($$$$) {
171 my ($self, $text, $wdf_inc, $prefix) = @_;
173 if ($self->{indexlevel} eq 'full') {
174 index_phrase($self, $text, $wdf_inc, $prefix);
176 my $tg = term_generator($self);
177 $tg->index_text_without_positions($text, $wdf_inc, $prefix);
181 sub index_headers ($$) {
182 my ($self, $smsg) = @_;
183 my @x = (from => 'A', to => 'XTO', cc => 'XCC'); # A: Author
184 while (my ($field, $pfx) = splice(@x, 0, 2)) {
185 my $val = $smsg->{$field};
187 # include "(comments)" after the address, too, so not using
188 # PublicInbox::Address::names or pairs
189 index_text($self, $val, 1, $pfx);
191 # we need positional info for email addresses since they
192 # can be considered phrases
193 if ($self->{indexlevel} eq 'medium') {
194 for my $addr (PublicInbox::Address::emails($val)) {
195 index_phrase($self, $addr, 1, $pfx);
199 @x = (subject => 'S');
200 while (my ($field, $pfx) = splice(@x, 0, 2)) {
201 my $val = $smsg->{$field};
202 index_text($self, $val, 1, $pfx) if $val ne '';
206 sub index_diff_inc ($$$$) {
207 my ($self, $text, $pfx, $xnq) = @_;
209 index_text($self, join("\n", @$xnq), 1, 'XNQ');
212 if ($pfx eq 'XDFN') {
213 index_phrase($self, $text, 1, $pfx);
215 index_text($self, $text, 1, $pfx);
219 sub index_old_diff_fn {
220 my ($self, $seen, $fa, $fb, $xnq) = @_;
222 # no renames or space support for traditional diffs,
223 # find the number of leading common paths to strip:
224 my @fa = split('/', $fa);
225 my @fb = split('/', $fb);
226 while (scalar(@fa) && scalar(@fb)) {
227 $fa = join('/', @fa);
228 $fb = join('/', @fb);
230 unless ($seen->{$fa}++) {
231 index_diff_inc($self, $fa, 'XDFN', $xnq);
241 sub index_diff ($$$) {
242 my ($self, $txt, $doc) = @_;
247 foreach (split(/\n/, $txt)) {
248 if ($in_diff && s/^ //) { # diff context
249 index_diff_inc($self, $_, 'XDFCTX', $xnq);
250 } elsif (/^-- $/) { # email signature begins
252 } elsif (m!^diff --git "?[^/]+/.+ "?[^/]+/.+\z!) {
253 # wait until "---" and "+++" to capture filenames
256 } elsif (m/^diff -(.+) (\S+) (\S+)$/) {
257 my ($opt, $fa, $fb) = ($1, $2, $3);
259 # only support unified:
260 next unless $opt =~ /[uU]/;
261 $in_diff = index_old_diff_fn($self, \%seen, $fa, $fb,
263 } elsif (m!^--- ("?[^/]+/.+)!) {
265 $fn = (split('/', git_unquote($fn), 2))[1];
266 $seen{$fn}++ or index_diff_inc($self, $fn, 'XDFN', $xnq);
268 } elsif (m!^\+\+\+ ("?[^/]+/.+)!) {
270 $fn = (split('/', git_unquote($fn), 2))[1];
271 $seen{$fn}++ or index_diff_inc($self, $fn, 'XDFN', $xnq);
273 } elsif (/^--- (\S+)/) {
276 } elsif (defined $in_diff && /^\+\+\+ (\S+)/) {
277 $in_diff = index_old_diff_fn($self, \%seen, $in_diff,
279 } elsif ($in_diff && s/^\+//) { # diff added
280 index_diff_inc($self, $_, 'XDFB', $xnq);
281 } elsif ($in_diff && s/^-//) { # diff removed
282 index_diff_inc($self, $_, 'XDFA', $xnq);
283 } elsif (m!^index ([a-f0-9]+)\.\.([a-f0-9]+)!) {
284 my ($ba, $bb) = ($1, $2);
285 index_git_blob_id($doc, 'XDFPRE', $ba);
286 index_git_blob_id($doc, 'XDFPOST', $bb);
288 } elsif (/^@@ (?:\S+) (?:\S+) @@\s*$/) {
289 # traditional diff w/o -p
290 } elsif (/^@@ (?:\S+) (?:\S+) @@\s*(\S+.*)$/) {
291 # hunk header context
292 index_diff_inc($self, $1, 'XDFHH', $xnq);
293 # ignore the following lines:
294 } elsif (/^(?:dis)similarity index/ ||
295 /^(?:old|new) mode/ ||
296 /^(?:deleted|new) file mode/ ||
297 /^(?:copy|rename) (?:from|to) / ||
298 /^(?:dis)?similarity index / ||
299 /^\\ No newline at end of file/ ||
300 /^Binary files .* differ/) {
303 # possible to be in diff context, some mail may be
304 # stripped by MUA or even GNU diff(1). "git apply"
305 # treats a bare "\n" as diff context, too
308 warn "non-diff line: $_\n" if DEBUG && $_ ne '';
313 index_text($self, join("\n", @xnq), 1, 'XNQ');
316 sub index_xapian { # msg_iter callback
317 my $part = $_[0]->[0]; # ignore $depth and $idx
318 my ($self, $doc) = @{$_[1]};
319 my $ct = $part->content_type || 'text/plain';
320 my $fn = $part->filename;
321 if (defined $fn && $fn ne '') {
322 index_phrase($self, $fn, 1, 'XFN');
324 if ($part->{is_submsg}) {
325 my $mids = mids_for_index($part);
326 index_ids($self, $doc, $part, $mids);
327 my $smsg = bless {}, 'PublicInbox::Smsg';
328 $smsg->populate($part);
329 index_headers($self, $smsg);
332 my ($s, undef) = msg_part_text($part, $ct);
333 defined $s or return;
334 $_[0]->[0] = $part = undef; # free memory
336 # split off quoted and unquoted blocks:
337 my @sections = PublicInbox::MsgIter::split_quotes($s);
338 undef $s; # free memory
339 for my $txt (@sections) {
341 index_text($self, $txt, 0, 'XQUOT');
343 # does it look like a diff?
344 if ($txt =~ /^(?:diff|---|\+\+\+) /ms) {
345 index_diff($self, $txt, $doc);
347 index_text($self, $txt, 1, 'XNQ');
350 undef $txt; # free memory
354 sub index_list_id ($$$) {
355 my ($self, $doc, $hdr) = @_;
356 for my $l ($hdr->header_raw('List-Id')) {
357 $l =~ /<([^>]+)>/ or next;
359 $doc->add_boolean_term('G' . $lid);
360 index_phrase($self, $lid, 1, 'XL'); # probabilistic
364 sub index_ids ($$$$) {
365 my ($self, $doc, $hdr, $mids) = @_;
366 for my $mid (@$mids) {
367 index_phrase($self, $mid, 1, 'XM');
369 # because too many Message-IDs are prefixed with
371 if ($mid =~ /\w{12,}/) {
372 my @long = ($mid =~ /(\w{3,}+)/g);
373 index_phrase($self, join(' ', @long), 1, 'XM');
376 $doc->add_boolean_term('Q' . $_) for @$mids;
377 index_list_id($self, $doc, $hdr);
380 sub eml2doc ($$$;$) {
381 my ($self, $eml, $smsg, $mids) = @_;
382 $mids //= mids_for_index($eml);
383 my $doc = $X->{Document}->new;
384 add_val($doc, PublicInbox::Search::TS(), $smsg->{ts});
385 my @ds = gmtime($smsg->{ds});
386 my $yyyymmdd = strftime('%Y%m%d', @ds);
387 add_val($doc, PublicInbox::Search::YYYYMMDD(), $yyyymmdd);
388 my $dt = strftime('%Y%m%d%H%M%S', @ds);
389 add_val($doc, PublicInbox::Search::DT(), $dt);
390 add_val($doc, PublicInbox::Search::BYTES(), $smsg->{bytes});
391 add_val($doc, PublicInbox::Search::UID(), $smsg->{num});
392 add_val($doc, PublicInbox::Search::THREADID, $smsg->{tid});
394 my $tg = term_generator($self);
395 $tg->set_document($doc);
396 index_headers($self, $smsg);
398 if (defined(my $eidx_key = $smsg->{eidx_key})) {
399 $doc->add_boolean_term('O'.$eidx_key) if $eidx_key ne '.';
401 msg_iter($eml, \&index_xapian, [ $self, $doc ]);
402 index_ids($self, $doc, $eml, $mids);
404 # by default, we maintain compatibility with v1.5.0 and earlier
405 # by writing to docdata.glass, users who never exect to downgrade can
407 if (!$self->{-skip_docdata}) {
408 # WWW doesn't need {to} or {cc}, only NNTP
409 $smsg->{to} = $smsg->{cc} = '';
410 $smsg->parse_references($eml, $mids);
411 my $data = $smsg->to_doc_data;
412 $doc->set_data($data);
415 if (my $altid = $self->{-altid}) {
416 foreach my $alt (@$altid) {
417 my $pfx = $alt->{xprefix};
418 foreach my $mid (@$mids) {
419 my $id = $alt->mid2alt($mid);
420 next unless defined $id;
421 $doc->add_boolean_term($pfx . $id);
428 sub add_xapian ($$$$) {
429 my ($self, $eml, $smsg, $mids) = @_;
430 begin_txn_lazy($self);
431 my $doc = eml2doc($self, $eml, $smsg, $mids);
432 $self->{xdb}->replace_document($smsg->{num}, $doc);
435 sub _msgmap_init ($) {
437 die "BUG: _msgmap_init is only for v1\n" if $self->{ibx}->version != 1;
438 $self->{mm} //= eval {
439 require PublicInbox::Msgmap;
440 my $rw = $self->{ibx}->{-no_fsync} ? 2 : 1;
441 PublicInbox::Msgmap->new($self->{ibx}->{inboxdir}, $rw);
446 # mime = PublicInbox::Eml or Email::MIME object
447 my ($self, $mime, $smsg, $sync) = @_;
448 begin_txn_lazy($self);
449 my $mids = mids_for_index($mime);
450 $smsg //= bless { blob => '' }, 'PublicInbox::Smsg'; # test-only compat
451 $smsg->{mid} //= $mids->[0]; # v1 compatibility
452 $smsg->{num} //= do { # v1
454 index_mm($self, $mime, $smsg->{blob}, $sync);
458 $smsg->populate($mime, $sync);
459 $smsg->{bytes} //= length($mime->as_string);
462 # order matters, overview stores every possible piece of
463 # data in doc_data (deflated). Xapian only stores a subset
464 # of the fields which exist in over.sqlite3. We may stop
465 # storing doc_data in Xapian sometime after we get multi-inbox
467 if (my $oidx = $self->{oidx}) { # v1 only
468 $oidx->add_overview($mime, $smsg);
470 if (need_xapian($self)) {
471 add_xapian($self, $mime, $smsg, $mids);
476 warn "failed to index message <".join('> <',@$mids).">: $@\n";
483 my ($self, $docid) = @_;
484 my $doc = eval { $self->{xdb}->get_document($docid) };
486 warn "E: $@\n" if $@;
487 warn "E: #$docid missing in Xapian\n";
493 my ($self, $docid, $eidx_key, $eml) = @_;
494 begin_txn_lazy($self);
495 my $doc = _get_doc($self, $docid) or return;
496 term_generator($self)->set_document($doc);
498 # '.' is special for lei_store
499 $doc->add_boolean_term('O'.$eidx_key) if $eidx_key ne '.';
501 index_list_id($self, $doc, $eml);
502 $self->{xdb}->replace_document($docid, $doc);
505 sub remove_eidx_info {
506 my ($self, $docid, $eidx_key, $eml) = @_;
507 begin_txn_lazy($self);
508 my $doc = _get_doc($self, $docid) or return;
509 eval { $doc->remove_term('O'.$eidx_key) };
510 warn "W: ->remove_term O$eidx_key: $@\n" if $@;
511 for my $l ($eml ? $eml->header_raw('List-Id') : ()) {
512 $l =~ /<([^>]+)>/ or next;
514 eval { $doc->remove_term('G' . $lid) };
515 warn "W: ->remove_term G$lid: $@\n" if $@;
517 # nb: we don't remove the XL probabilistic terms
518 # since terms may overlap if cross-posted.
520 # IOW, a message which has both <foo.example.com>
521 # and <bar.example.com> would have overlapping
522 # "XLexample" and "XLcom" as terms and which we
523 # wouldn't know if they're safe to remove if we just
524 # unindex <foo.example.com> while preserving
527 # In any case, this entire sub is will likely never
528 # be needed and users using the "l:" prefix are probably
531 $self->{xdb}->replace_document($docid, $doc);
534 my @VMD_MAP = (kw => 'K', label => 'L');
537 my ($self, $docid, $vmd) = @_;
538 begin_txn_lazy($self);
539 my $doc = _get_doc($self, $docid) or return;
540 my ($end, @rm, @add);
542 while (my ($field, $pfx) = splice(@x, 0, 2)) {
543 my $set = $vmd->{$field} // next;
544 my %keep = map { $_ => 1 } @$set;
546 $end //= $doc->termlist_end;
547 for (my $cur = $doc->termlist_begin; $cur != $end; $cur++) {
549 last if $cur == $end;
550 my $v = $cur->get_termname;
551 $v =~ s/\A$pfx//s or next;
552 $keep{$v} ? delete($add{$v}) : push(@rm, $pfx.$v);
554 push(@add, map { $pfx.$_ } keys %add);
556 return unless scalar(@rm) || scalar(@add);
557 $doc->remove_term($_) for @rm;
558 $doc->add_boolean_term($_) for @add;
559 $self->{xdb}->replace_document($docid, $doc);
563 my ($self, $docid, $vmd) = @_;
564 begin_txn_lazy($self);
565 my $doc = _get_doc($self, $docid) or return;
567 while (my ($field, $pfx) = splice(@x, 0, 2)) {
568 my $add = $vmd->{$field} // next;
569 $doc->add_boolean_term($pfx . $_) for @$add;
571 $self->{xdb}->replace_document($docid, $doc);
575 my ($self, $docid, $vmd) = @_;
576 begin_txn_lazy($self);
577 my $doc = _get_doc($self, $docid) or return;
580 while (my ($field, $pfx) = splice(@x, 0, 2)) {
581 my $rm = $vmd->{$field} // next;
584 $doc->remove_term($pfx . $_);
589 $self->{xdb}->replace_document($docid, $doc) if $replace;
593 my ($self, @docids) = @_;
594 $self->begin_txn_lazy;
595 my $xdb = $self->{xdb} or return;
596 for my $docid (@docids) {
597 eval { $xdb->delete_document($docid) };
598 warn "E: #$docid not in in Xapian? $@\n" if $@;
602 sub index_git_blob_id {
603 my ($doc, $pfx, $objid) = @_;
605 my $len = length($objid);
606 for (my $len = length($objid); $len >= 7; ) {
607 $doc->add_term($pfx.$objid);
608 $objid = substr($objid, 0, --$len);
614 my ($self, $oid, $eml) = @_;
615 my $mids = mids($eml);
618 for my $mid (@$mids) {
619 my @removed = $self->{oidx}->remove_oid($oid, $mid);
620 $nr += scalar @removed;
621 $tmp{$_}++ for @removed;
624 my $m = join('> <', @$mids);
625 warn "W: <$m> missing for removal from overview\n";
627 while (my ($num, $nr) = each %tmp) {
628 warn "BUG: $num appears >1 times ($nr) for $oid\n" if $nr != 1;
631 $self->{mm}->num_delete($_) for (keys %tmp);
632 } else { # just in case msgmap and over.sqlite3 become desynched:
633 $self->{mm}->mid_delete($mids->[0]);
635 xdb_remove($self, keys %tmp) if need_xapian($self);
639 my ($self, $mime, $oid, $sync) = @_;
640 my $mids = mids($mime);
641 my $mm = $self->{mm};
642 if ($sync->{reindex}) {
643 my $oidx = $self->{oidx};
644 for my $mid (@$mids) {
645 my ($num, undef) = $oidx->num_mid0_for_oid($oid, $mid);
646 return $num if defined $num;
648 $mm->num_for($mids->[0]) // $mm->mid_insert($mids->[0]);
650 # fallback to num_for since filters like RubyLang set the number
651 $mm->mid_insert($mids->[0]) // $mm->num_for($mids->[0]);
655 sub is_bad_blob ($$$$) {
656 my ($oid, $type, $size, $expect_oid) = @_;
657 if ($type ne 'blob') {
658 carp "W: $expect_oid is not a blob (type=$type)";
661 croak "BUG: $oid != $expect_oid" if $oid ne $expect_oid;
662 $size == 0 ? 1 : 0; # size == 0 means purged
665 sub index_both { # git->cat_async callback
666 my ($bref, $oid, $type, $size, $sync) = @_;
667 return if is_bad_blob($oid, $type, $size, $sync->{oid});
668 my ($nr, $max) = @$sync{qw(nr max)};
671 my $smsg = bless { blob => $oid }, 'PublicInbox::Smsg';
672 $smsg->set_bytes($$bref, $size);
673 my $self = $sync->{sidx};
674 local $self->{current_info} = "$self->{current_info}: $oid";
675 my $eml = PublicInbox::Eml->new($bref);
676 $smsg->{num} = index_mm($self, $eml, $oid, $sync) or
677 die "E: could not generate NNTP article number for $oid";
678 add_message($self, $eml, $smsg, $sync);
680 my $cur_cmt = $sync->{cur_cmt} // die 'BUG: {cur_cmt} missing';
681 ${$sync->{latest_cmt}} = $cur_cmt;
684 sub unindex_both { # git->cat_async callback
685 my ($bref, $oid, $type, $size, $sync) = @_;
686 return if is_bad_blob($oid, $type, $size, $sync->{oid});
687 my $self = $sync->{sidx};
688 local $self->{current_info} = "$self->{current_info}: $oid";
689 unindex_eml($self, $oid, PublicInbox::Eml->new($bref));
690 # may be undef if leftover
691 if (defined(my $cur_cmt = $sync->{cur_cmt})) {
692 ${$sync->{latest_cmt}} = $cur_cmt;
699 ($self->{ibx} // $self->{eidx})->with_umask(@_);
702 # called by public-inbox-index
704 my ($self, $opt) = @_;
705 delete $self->{lock_path} if $opt->{-skip_lock};
706 $self->with_umask(\&_index_sync, $self, $opt);
707 if ($opt->{reindex} && !$opt->{quit}) {
709 delete @again{qw(rethread reindex)};
710 index_sync($self, \%again);
711 $opt->{quit} = $again{quit}; # propagate to caller
715 sub check_size { # check_async cb for -index --max-size=...
716 my ($oid, $type, $size, $arg, $git) = @_;
717 (($type // '') eq 'blob') or die "E: bad $oid in $git->{git_dir}";
718 if ($size <= $arg->{max_size}) {
719 $git->cat_async($oid, $arg->{index_oid}, $arg);
721 warn "W: skipping $oid ($size > $arg->{max_size})\n";
725 sub v1_checkpoint ($$;$) {
726 my ($self, $sync, $stk) = @_;
727 $self->{ibx}->git->async_wait_all;
729 # $newest may be undef
730 my $newest = $stk ? $stk->{latest_cmt} : ${$sync->{latest_cmt}};
731 if (defined($newest)) {
732 my $cur = $self->{mm}->last_commit || '';
733 if (need_update($self, $cur, $newest)) {
734 $self->{mm}->last_commit($newest);
737 ${$sync->{max}} = $self->{batch_bytes};
739 $self->{mm}->{dbh}->commit;
740 my $xdb = need_xapian($self) ? $self->{xdb} : undef;
741 if ($newest && $xdb) {
742 my $cur = $xdb->get_metadata('last_commit');
743 if (need_update($self, $cur, $newest)) {
744 $xdb->set_metadata('last_commit', $newest);
747 if ($stk) { # all done if $stk is passed
748 # let SearchView know a full --reindex was done so it can
749 # generate ->has_threadid-dependent links
750 if ($xdb && $sync->{reindex} && !ref($sync->{reindex})) {
751 my $n = $xdb->get_metadata('has_threadid');
752 $xdb->set_metadata('has_threadid', '1') if $n ne '1';
754 $self->{oidx}->rethread_done($sync->{-opt}); # all done
756 commit_txn_lazy($self);
757 $sync->{ibx}->git->cleanup;
758 my $nr = ${$sync->{nr}};
759 idx_release($self, $nr);
760 # let another process do some work...
761 if (my $pr = $sync->{-opt}->{-progress}) {
762 $pr->("indexed $nr/$sync->{ntodo}\n") if $nr;
764 if (!$stk && !$sync->{quit}) { # more to come
765 begin_txn_lazy($self);
766 $self->{mm}->{dbh}->begin_work;
772 my ($self, $sync, $stk) = @_;
773 my $git = $sync->{ibx}->git;
774 my $max = $self->{batch_bytes};
777 $sync->{max} = \$max;
778 $sync->{sidx} = $self;
779 $sync->{latest_cmt} = \(my $latest_cmt);
781 $self->{mm}->{dbh}->begin_work;
782 if (my @leftovers = keys %{delete($sync->{D}) // {}}) {
783 warn('W: unindexing '.scalar(@leftovers)." leftovers\n");
784 for my $oid (@leftovers) {
785 last if $sync->{quit};
786 $oid = unpack('H*', $oid);
787 $git->cat_async($oid, \&unindex_both, $sync);
790 if ($sync->{max_size} = $sync->{-opt}->{max_size}) {
791 $sync->{index_oid} = \&index_both;
793 while (my ($f, $at, $ct, $oid, $cur_cmt) = $stk->pop_rec) {
794 my $arg = { %$sync, cur_cmt => $cur_cmt, oid => $oid };
795 last if $sync->{quit};
797 $arg->{autime} = $at;
798 $arg->{cotime} = $ct;
799 if ($sync->{max_size}) {
800 $git->check_async($oid, \&check_size, $arg);
802 $git->cat_async($oid, \&index_both, $arg);
804 v1_checkpoint($self, $sync) if $max <= 0;
805 } elsif ($f eq 'd') {
806 $git->cat_async($oid, \&unindex_both, $arg);
809 v1_checkpoint($self, $sync, $sync->{quit} ? undef : $stk);
812 sub log2stack ($$$) {
813 my ($sync, $git, $range) = @_;
814 my $D = $sync->{D}; # OID_BIN => NR (if reindexing, undef otherwise)
816 if ($sync->{ibx}->version == 1) {
817 my $path = $hex.'{2}/'.$hex.'{38}';
818 $add = qr!\A:000000 100644 \S+ ($OID) A\t$path$!;
819 $del = qr!\A:100644 000000 ($OID) \S+ D\t$path$!;
821 $del = qr!\A:\d{6} 100644 $OID ($OID) [AM]\td$!;
822 $add = qr!\A:\d{6} 100644 $OID ($OID) [AM]\tm$!;
825 # Count the new files so they can be added newest to oldest
826 # and still have numbers increasing from oldest to newest
827 my $fh = $git->popen(qw(log --raw -r --pretty=tformat:%at-%ct-%H
828 --no-notes --no-color --no-renames --no-abbrev),
830 my ($at, $ct, $stk, $cmt);
832 return if $sync->{quit};
833 if (/\A([0-9]+)-([0-9]+)-($OID)$/o) {
834 ($at, $ct, $cmt) = ($1 + 0, $2 + 0, $3);
835 $stk //= PublicInbox::IdxStack->new($cmt);
838 if ($D) { # reindex case
839 $D->{pack('H*', $oid)}++;
840 } else { # non-reindex case:
841 $stk->push_rec('d', $at, $ct, $oid, $cmt);
846 my $oid_bin = pack('H*', $oid);
847 my $nr = --$D->{$oid_bin};
848 delete($D->{$oid_bin}) if $nr <= 0;
849 # nr < 0 (-1) means it never existed
852 $stk->push_rec('m', $at, $ct, $oid, $cmt);
855 close $fh or die "git log failed: \$?=$?";
856 $stk //= PublicInbox::IdxStack->new;
860 sub prepare_stack ($$) {
861 my ($sync, $range) = @_;
862 my $git = $sync->{ibx}->git;
864 if (index($range, '..') < 0) {
865 # don't show annoying git errors to users who run -index
867 $git->qx(qw(rev-parse -q --verify), "$range^0");
868 return PublicInbox::IdxStack->new->read_prepare if $?;
870 $sync->{D} = $sync->{reindex} ? {} : undef; # OID_BIN => NR
871 log2stack($sync, $git, $range);
874 # --is-ancestor requires git 1.8.0+
875 sub is_ancestor ($$$) {
876 my ($git, $cur, $tip) = @_;
877 return 0 unless $git->check($cur);
878 my $cmd = [ 'git', "--git-dir=$git->{git_dir}",
879 qw(merge-base --is-ancestor), $cur, $tip ];
880 my $pid = spawn($cmd);
881 waitpid($pid, 0) == $pid or die join(' ', @$cmd) .' did not finish';
885 sub need_update ($$$) {
886 my ($self, $cur, $new) = @_;
887 my $git = $self->{ibx}->git;
888 return 1 if $cur && !is_ancestor($git, $cur, $new);
889 my $range = $cur eq '' ? $new : "$cur..$new";
890 chomp(my $n = $git->qx(qw(rev-list --count), $range));
891 ($n eq '' || $n > 0);
894 # The last git commit we indexed with Xapian or SQLite (msgmap)
895 # This needs to account for cases where Xapian or SQLite is
896 # out-of-date with respect to the other.
898 my ($self, $mm) = @_;
899 my $lm = $mm->last_commit || '';
901 if (need_xapian($self)) {
902 $lx = $self->{xdb}->get_metadata('last_commit') || '';
906 # Use last_commit from msgmap if it is older or unset
907 if (!$lm || ($lx && $lm && is_ancestor($self->{ibx}->git, $lm, $lx))) {
913 sub reindex_from ($$) {
914 my ($reindex, $last_commit) = @_;
915 return $last_commit unless $reindex;
916 ref($reindex) eq 'HASH' ? $reindex->{from} : '';
922 # we set {-opt}->{quit} too, so ->index_sync callers
923 # can abort multi-inbox loops this way
924 $sync->{quit} = $sync->{-opt}->{quit} = 1;
925 warn "gracefully quitting\n";
929 # indexes all unindexed messages (v1 only)
931 my ($self, $opt) = @_;
932 my $tip = $opt->{ref} || 'HEAD';
933 my $ibx = $self->{ibx};
934 local $self->{current_info} = "$ibx->{inboxdir}";
935 $self->{batch_bytes} = $opt->{batch_size} // $BATCH_BYTES;
936 $ibx->git->batch_prepare;
937 my $pr = $opt->{-progress};
938 my $sync = { reindex => $opt->{reindex}, -opt => $opt, ibx => $ibx };
939 my $quit = quit_cb($sync);
940 local $SIG{QUIT} = $quit;
941 local $SIG{INT} = $quit;
942 local $SIG{TERM} = $quit;
943 my $xdb = $self->begin_txn_lazy;
944 $self->{oidx}->rethread_prepare($opt);
945 my $mm = _msgmap_init($self);
946 if ($sync->{reindex}) {
947 my $last = $mm->last_commit;
951 # somebody just blindly added --reindex when indexing
952 # for the first time, allow it:
953 undef $sync->{reindex};
956 my $last_commit = _last_x_commit($self, $mm);
957 my $lx = reindex_from($sync->{reindex}, $last_commit);
958 my $range = $lx eq '' ? $tip : "$lx..$tip";
959 $pr->("counting changes\n\t$range ... ") if $pr;
960 my $stk = prepare_stack($sync, $range);
961 $sync->{ntodo} = $stk ? $stk->num_records : 0;
962 $pr->("$sync->{ntodo}\n") if $pr; # continue previous line
963 process_stack($self, $sync, $stk) if !$sync->{quit};
967 # order matters for unlocking
968 $_[0]->{xdb} = undef;
969 $_[0]->{lockfh} = undef;
974 my $xdb = $self->{xdb} || idx_acquire($self);
975 $self->{oidx}->begin_lazy if $self->{oidx};
976 $xdb->begin_transaction if $xdb;
983 $self->with_umask(\&_begin_txn, $self) if !$self->{txn};
986 # store 'indexlevel=medium' in v2 shard=0 and v1 (only one shard)
987 # This metadata is read by Admin::detect_indexlevel:
988 sub set_metadata_once {
991 return if $self->{shard}; # only continue if undef or 0, not >0
992 my $xdb = $self->{xdb};
994 if (delete($self->{-set_has_threadid_once})) {
995 $xdb->set_metadata('has_threadid', '1');
997 if (delete($self->{-set_indexlevel_once})) {
998 my $level = $xdb->get_metadata('indexlevel');
999 if (!$level || $level ne 'medium') {
1000 $xdb->set_metadata('indexlevel', 'medium');
1003 if (delete($self->{-set_skip_docdata_once})) {
1004 $xdb->get_metadata('skip_docdata') or
1005 $xdb->set_metadata('skip_docdata', '1');
1011 if (my $eidx = $self->{eidx}) {
1012 $eidx->git->async_wait_all;
1013 $eidx->{transact_bytes} = 0;
1015 if (my $xdb = $self->{xdb}) {
1016 set_metadata_once($self);
1017 $xdb->commit_transaction;
1019 $self->{oidx}->commit_lazy if $self->{oidx};
1022 sub commit_txn_lazy {
1024 delete($self->{txn}) and
1025 $self->with_umask(\&_commit_txn, $self);
1028 sub eidx_shard_new {
1029 my ($class, $eidx, $shard) = @_;
1032 xpfx => $eidx->{xpfx},
1033 indexlevel => $eidx->{indexlevel},
1038 $self->{-set_indexlevel_once} = 1 if $self->{indexlevel} eq 'medium';
1042 # ensure there's no stale Xapian docs by treating $over as canonical
1044 my ($self, $over) = @_;
1045 begin_txn_lazy($self);
1046 my $sth = $over->dbh->prepare(<<'');
1047 SELECT COUNT(*) FROM over WHERE num = ?
1049 my $xdb = $self->{xdb};
1050 my $cur = $xdb->postlist_begin('');
1051 my $end = $xdb->postlist_end('');
1052 my $xdir = $self->xdir;
1053 for (; $cur != $end; $cur++) {
1054 my $docid = $cur->get_docid;
1055 $sth->execute($docid);
1056 my $x = $sth->fetchrow_array;
1058 warn "I: removing $xdir #$docid, not in `over'\n";
1059 $xdb->delete_document($docid);