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 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;
68 $self->{lock_path} = "$inboxdir/ssoma.lock";
69 my $dir = $self->xdir;
70 $self->{oidx} = PublicInbox::OverIdx->new("$dir/over.sqlite3");
71 $self->{oidx}->{-no_fsync} = 1 if $ibx->{-no_fsync};
72 } elsif ($version == 2) {
73 defined $shard or die "shard is required for v2\n";
75 $self->{shard} = $shard;
76 $self->{lock_path} = undef;
78 die "unsupported inbox version=$version\n";
80 $self->{creat} = ($creat || 0) == 1;
84 sub need_xapian ($) { $_[0]->{indexlevel} =~ $xapianlevels }
87 my ($self, $wake) = @_;
88 if (need_xapian($self)) {
89 my $xdb = delete $self->{xdb} or croak 'not acquired';
92 $self->lock_release($wake) if $self->{creat};
96 sub load_xapian_writable () {
97 return 1 if $X->{WritableDatabase};
98 PublicInbox::Search::load_xapian() or return;
99 my $xap = $PublicInbox::Search::Xap;
100 for (qw(Document TermGenerator WritableDatabase)) {
101 $X->{$_} = $xap.'::'.$_;
103 eval 'require '.$X->{WritableDatabase} or die;
104 *sortable_serialise = $xap.'::sortable_serialise';
105 $DB_CREATE_OR_OPEN = eval($xap.'::DB_CREATE_OR_OPEN()');
106 $DB_OPEN = eval($xap.'::DB_OPEN()');
107 my $ver = (eval($xap.'::major_version()') << 16) |
108 (eval($xap.'::minor_version()') << 8);
109 $DB_NO_SYNC = 0x4 if $ver >= 0x10400;
116 my $dir = $self->xdir;
117 if (need_xapian($self)) {
118 croak 'already acquired' if $self->{xdb};
119 load_xapian_writable();
120 $flag = $self->{creat} ? $DB_CREATE_OR_OPEN : $DB_OPEN;
122 if ($self->{creat}) {
126 # don't create empty Xapian directories if we don't need Xapian
127 my $is_shard = defined($self->{shard});
128 if (!-d $dir && (!$is_shard ||
129 ($is_shard && need_xapian($self)))) {
130 File::Path::mkpath($dir);
132 $self->{-set_has_threadid_once} = 1;
135 return unless defined $flag;
136 $flag |= $DB_NO_SYNC if ($self->{ibx} // $self->{eidx})->{-no_fsync};
137 my $xdb = eval { ($X->{WritableDatabase})->new($dir, $flag) };
138 croak "Failed opening $dir: $@" if $@;
143 my ($doc, $col, $num) = @_;
144 $num = sortable_serialise($num);
145 $doc->add_value($col, $num);
148 sub term_generator ($) { # write-only
151 $self->{term_generator} //= do {
152 my $tg = $X->{TermGenerator}->new;
153 $tg->set_stemmer(PublicInbox::Search::stemmer($self));
158 sub index_text ($$$$) {
159 my ($self, $text, $wdf_inc, $prefix) = @_;
160 my $tg = term_generator($self); # man Search::Xapian::TermGenerator
162 if ($self->{indexlevel} eq 'full') {
163 $tg->index_text($text, $wdf_inc, $prefix);
164 $tg->increase_termpos;
166 $tg->index_text_without_positions($text, $wdf_inc, $prefix);
170 sub index_headers ($$) {
171 my ($self, $smsg) = @_;
172 my @x = (from => 'A', # Author
173 subject => 'S', to => 'XTO', cc => 'XCC');
174 while (my ($field, $pfx) = splice(@x, 0, 2)) {
175 my $val = $smsg->{$field};
176 index_text($self, $val, 1, $pfx) if $val ne '';
180 sub index_diff_inc ($$$$) {
181 my ($self, $text, $pfx, $xnq) = @_;
183 index_text($self, join("\n", @$xnq), 1, 'XNQ');
186 index_text($self, $text, 1, $pfx);
189 sub index_old_diff_fn {
190 my ($self, $seen, $fa, $fb, $xnq) = @_;
192 # no renames or space support for traditional diffs,
193 # find the number of leading common paths to strip:
194 my @fa = split('/', $fa);
195 my @fb = split('/', $fb);
196 while (scalar(@fa) && scalar(@fb)) {
197 $fa = join('/', @fa);
198 $fb = join('/', @fb);
200 unless ($seen->{$fa}++) {
201 index_diff_inc($self, $fa, 'XDFN', $xnq);
211 sub index_diff ($$$) {
212 my ($self, $txt, $doc) = @_;
217 foreach (split(/\n/, $txt)) {
218 if ($in_diff && s/^ //) { # diff context
219 index_diff_inc($self, $_, 'XDFCTX', $xnq);
220 } elsif (/^-- $/) { # email signature begins
222 } elsif (m!^diff --git "?[^/]+/.+ "?[^/]+/.+\z!) {
223 # wait until "---" and "+++" to capture filenames
226 } elsif (m/^diff -(.+) (\S+) (\S+)$/) {
227 my ($opt, $fa, $fb) = ($1, $2, $3);
229 # only support unified:
230 next unless $opt =~ /[uU]/;
231 $in_diff = index_old_diff_fn($self, \%seen, $fa, $fb,
233 } elsif (m!^--- ("?[^/]+/.+)!) {
235 $fn = (split('/', git_unquote($fn), 2))[1];
236 $seen{$fn}++ or index_diff_inc($self, $fn, 'XDFN', $xnq);
238 } elsif (m!^\+\+\+ ("?[^/]+/.+)!) {
240 $fn = (split('/', git_unquote($fn), 2))[1];
241 $seen{$fn}++ or index_diff_inc($self, $fn, 'XDFN', $xnq);
243 } elsif (/^--- (\S+)/) {
246 } elsif (defined $in_diff && /^\+\+\+ (\S+)/) {
247 $in_diff = index_old_diff_fn($self, \%seen, $in_diff,
249 } elsif ($in_diff && s/^\+//) { # diff added
250 index_diff_inc($self, $_, 'XDFB', $xnq);
251 } elsif ($in_diff && s/^-//) { # diff removed
252 index_diff_inc($self, $_, 'XDFA', $xnq);
253 } elsif (m!^index ([a-f0-9]+)\.\.([a-f0-9]+)!) {
254 my ($ba, $bb) = ($1, $2);
255 index_git_blob_id($doc, 'XDFPRE', $ba);
256 index_git_blob_id($doc, 'XDFPOST', $bb);
258 } elsif (/^@@ (?:\S+) (?:\S+) @@\s*$/) {
259 # traditional diff w/o -p
260 } elsif (/^@@ (?:\S+) (?:\S+) @@\s*(\S+.*)$/) {
261 # hunk header context
262 index_diff_inc($self, $1, 'XDFHH', $xnq);
263 # ignore the following lines:
264 } elsif (/^(?:dis)similarity index/ ||
265 /^(?:old|new) mode/ ||
266 /^(?:deleted|new) file mode/ ||
267 /^(?:copy|rename) (?:from|to) / ||
268 /^(?:dis)?similarity index / ||
269 /^\\ No newline at end of file/ ||
270 /^Binary files .* differ/) {
273 # possible to be in diff context, some mail may be
274 # stripped by MUA or even GNU diff(1). "git apply"
275 # treats a bare "\n" as diff context, too
278 warn "non-diff line: $_\n" if DEBUG && $_ ne '';
283 index_text($self, join("\n", @xnq), 1, 'XNQ');
286 sub index_xapian { # msg_iter callback
287 my $part = $_[0]->[0]; # ignore $depth and $idx
288 my ($self, $doc) = @{$_[1]};
289 my $ct = $part->content_type || 'text/plain';
290 my $fn = $part->filename;
291 if (defined $fn && $fn ne '') {
292 index_text($self, $fn, 1, 'XFN');
294 if ($part->{is_submsg}) {
295 my $mids = mids_for_index($part);
296 index_ids($self, $doc, $part, $mids);
297 my $smsg = bless {}, 'PublicInbox::Smsg';
298 $smsg->populate($part);
299 index_headers($self, $smsg);
302 my ($s, undef) = msg_part_text($part, $ct);
303 defined $s or return;
304 $_[0]->[0] = $part = undef; # free memory
306 # split off quoted and unquoted blocks:
307 my @sections = PublicInbox::MsgIter::split_quotes($s);
308 undef $s; # free memory
309 for my $txt (@sections) {
311 index_text($self, $txt, 0, 'XQUOT');
313 # does it look like a diff?
314 if ($txt =~ /^(?:diff|---|\+\+\+) /ms) {
315 index_diff($self, $txt, $doc);
317 index_text($self, $txt, 1, 'XNQ');
320 undef $txt; # free memory
324 sub index_list_id ($$$) {
325 my ($self, $doc, $hdr) = @_;
326 for my $l ($hdr->header_raw('List-Id')) {
327 $l =~ /<([^>]+)>/ or next;
329 $doc->add_boolean_term('G' . $lid);
330 index_text($self, $lid, 1, 'XL'); # probabilistic
334 sub index_ids ($$$$) {
335 my ($self, $doc, $hdr, $mids) = @_;
336 for my $mid (@$mids) {
337 index_text($self, $mid, 1, 'XM');
339 # because too many Message-IDs are prefixed with
341 if ($mid =~ /\w{12,}/) {
342 my @long = ($mid =~ /(\w{3,}+)/g);
343 index_text($self, join(' ', @long), 1, 'XM');
346 $doc->add_boolean_term('Q' . $_) for @$mids;
347 index_list_id($self, $doc, $hdr);
350 sub eml2doc ($$$;$) {
351 my ($self, $eml, $smsg, $mids) = @_;
352 $mids //= mids_for_index($eml);
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 add_val($doc, PublicInbox::Search::THREADID, $smsg->{tid});
364 my $tg = term_generator($self);
365 $tg->set_document($doc);
366 index_headers($self, $smsg);
368 if (defined(my $eidx_key = $smsg->{eidx_key})) {
369 $doc->add_boolean_term('O'.$eidx_key) if $eidx_key ne '.';
371 msg_iter($eml, \&index_xapian, [ $self, $doc ]);
372 index_ids($self, $doc, $eml, $mids);
374 # by default, we maintain compatibility with v1.5.0 and earlier
375 # by writing to docdata.glass, users who never exect to downgrade can
377 if (!$self->{-skip_docdata}) {
378 # WWW doesn't need {to} or {cc}, only NNTP
379 $smsg->{to} = $smsg->{cc} = '';
380 PublicInbox::OverIdx::parse_references($smsg, $eml, $mids);
381 my $data = $smsg->to_doc_data;
382 $doc->set_data($data);
385 if (my $altid = $self->{-altid}) {
386 foreach my $alt (@$altid) {
387 my $pfx = $alt->{xprefix};
388 foreach my $mid (@$mids) {
389 my $id = $alt->mid2alt($mid);
390 next unless defined $id;
391 $doc->add_boolean_term($pfx . $id);
398 sub add_xapian ($$$$) {
399 my ($self, $eml, $smsg, $mids) = @_;
400 my $doc = eml2doc($self, $eml, $smsg, $mids);
401 $self->{xdb}->replace_document($smsg->{num}, $doc);
404 sub _msgmap_init ($) {
406 die "BUG: _msgmap_init is only for v1\n" if $self->{ibx}->version != 1;
407 $self->{mm} //= eval {
408 require PublicInbox::Msgmap;
409 my $rw = $self->{ibx}->{-no_fsync} ? 2 : 1;
410 PublicInbox::Msgmap->new($self->{ibx}->{inboxdir}, $rw);
415 # mime = PublicInbox::Eml or Email::MIME object
416 my ($self, $mime, $smsg, $sync) = @_;
417 begin_txn_lazy($self);
418 my $mids = mids_for_index($mime);
419 $smsg //= bless { blob => '' }, 'PublicInbox::Smsg'; # test-only compat
420 $smsg->{mid} //= $mids->[0]; # v1 compatibility
421 $smsg->{num} //= do { # v1
423 index_mm($self, $mime, $smsg->{blob}, $sync);
427 $smsg->populate($mime, $sync);
428 $smsg->{bytes} //= length($mime->as_string);
431 # order matters, overview stores every possible piece of
432 # data in doc_data (deflated). Xapian only stores a subset
433 # of the fields which exist in over.sqlite3. We may stop
434 # storing doc_data in Xapian sometime after we get multi-inbox
436 if (my $oidx = $self->{oidx}) { # v1 only
437 $oidx->add_overview($mime, $smsg);
439 if (need_xapian($self)) {
440 add_xapian($self, $mime, $smsg, $mids);
445 warn "failed to index message <".join('> <',@$mids).">: $@\n";
452 my ($self, $docid) = @_;
453 my $doc = eval { $self->{xdb}->get_document($docid) };
455 warn "E: $@\n" if $@;
456 warn "E: #$docid missing in Xapian\n";
462 my ($self, $docid, $eidx_key, $eml) = @_;
463 begin_txn_lazy($self);
464 my $doc = _get_doc($self, $docid) or return;
465 term_generator($self)->set_document($doc);
466 $doc->add_boolean_term('O'.$eidx_key) if $eidx_key ne '.';
467 index_list_id($self, $doc, $eml);
468 $self->{xdb}->replace_document($docid, $doc);
471 sub remove_eidx_info {
472 my ($self, $docid, $eidx_key, $eml) = @_;
473 begin_txn_lazy($self);
474 my $doc = _get_doc($self, $docid) or return;
475 eval { $doc->remove_term('O'.$eidx_key) };
476 warn "W: ->remove_term O$eidx_key: $@\n" if $@;
477 for my $l ($eml ? $eml->header_raw('List-Id') : ()) {
478 $l =~ /<([^>]+)>/ or next;
480 eval { $doc->remove_term('G' . $lid) };
481 warn "W: ->remove_term G$lid: $@\n" if $@;
483 # nb: we don't remove the XL probabilistic terms
484 # since terms may overlap if cross-posted.
486 # IOW, a message which has both <foo.example.com>
487 # and <bar.example.com> would have overlapping
488 # "XLexample" and "XLcom" as terms and which we
489 # wouldn't know if they're safe to remove if we just
490 # unindex <foo.example.com> while preserving
493 # In any case, this entire sub is will likely never
494 # be needed and users using the "l:" prefix are probably
497 $self->{xdb}->replace_document($docid, $doc);
501 my ($self, $docid, @kw) = @_;
502 begin_txn_lazy($self);
503 my $doc = _get_doc($self, $docid) or return;
504 my %keep = map { $_ => 1 } @kw;
507 my $end = $doc->termlist_end;
508 for (my $cur = $doc->termlist_begin; $cur != $end; $cur++) {
510 last if $cur == $end;
511 my $kw = $cur->get_termname;
512 $kw =~ s/\AK//s or next;
513 $keep{$kw} ? delete($add{$kw}) : push(@rm, $kw);
515 return unless (scalar(@rm) + scalar(keys %add));
516 $doc->remove_term('K'.$_) for @rm;
517 $doc->add_boolean_term('K'.$_) for (keys %add);
518 $self->{xdb}->replace_document($docid, $doc);
522 my ($self, $docid, @kw) = @_;
523 begin_txn_lazy($self);
524 my $doc = _get_doc($self, $docid) or return;
525 $doc->add_boolean_term('K'.$_) for @kw;
526 $self->{xdb}->replace_document($docid, $doc);
529 sub remove_keywords {
530 my ($self, $docid, @kw) = @_;
531 begin_txn_lazy($self);
532 my $doc = _get_doc($self, $docid) or return;
535 $doc->remove_term('K'.$_);
538 $self->{xdb}->replace_document($docid, $doc) if $replace;
541 sub smsg_from_doc ($) {
543 my $data = $doc->get_data or return;
544 my $smsg = bless {}, 'PublicInbox::Smsg';
545 $smsg->{ts} = int_val($doc, PublicInbox::Search::TS());
546 my $dt = int_val($doc, PublicInbox::Search::DT());
547 my ($yyyy, $mon, $dd, $hh, $mm, $ss) = unpack('A4A2A2A2A2A2', $dt);
548 $smsg->{ds} = timegm($ss, $mm, $hh, $dd, $mon - 1, $yyyy);
549 $smsg->load_from_data($data);
554 my ($self, @docids) = @_;
555 my $xdb = $self->{xdb} or return;
556 for my $docid (@docids) {
557 eval { $xdb->delete_document($docid) };
558 warn "E: #$docid not in in Xapian? $@\n" if $@;
562 sub remove_by_docid {
563 my ($self, $num) = @_;
564 die "BUG: remove_by_docid is v2-only\n" if $self->{oidx};
565 $self->begin_txn_lazy;
566 xdb_remove($self, $num) if need_xapian($self);
569 sub index_git_blob_id {
570 my ($doc, $pfx, $objid) = @_;
572 my $len = length($objid);
573 for (my $len = length($objid); $len >= 7; ) {
574 $doc->add_term($pfx.$objid);
575 $objid = substr($objid, 0, --$len);
581 my ($self, $oid, $eml) = @_;
582 my $mids = mids($eml);
585 for my $mid (@$mids) {
586 my @removed = $self->{oidx}->remove_oid($oid, $mid);
587 $nr += scalar @removed;
588 $tmp{$_}++ for @removed;
591 my $m = join('> <', @$mids);
592 warn "W: <$m> missing for removal from overview\n";
594 while (my ($num, $nr) = each %tmp) {
595 warn "BUG: $num appears >1 times ($nr) for $oid\n" if $nr != 1;
598 $self->{mm}->num_delete($_) for (keys %tmp);
599 } else { # just in case msgmap and over.sqlite3 become desynched:
600 $self->{mm}->mid_delete($mids->[0]);
602 xdb_remove($self, keys %tmp) if need_xapian($self);
606 my ($self, $mime, $oid, $sync) = @_;
607 my $mids = mids($mime);
608 my $mm = $self->{mm};
609 if ($sync->{reindex}) {
610 my $oidx = $self->{oidx};
611 for my $mid (@$mids) {
612 my ($num, undef) = $oidx->num_mid0_for_oid($oid, $mid);
613 return $num if defined $num;
615 $mm->num_for($mids->[0]) // $mm->mid_insert($mids->[0]);
617 # fallback to num_for since filters like RubyLang set the number
618 $mm->mid_insert($mids->[0]) // $mm->num_for($mids->[0]);
622 # returns the number of bytes to add if given a non-CRLF arg
623 sub crlf_adjust ($) {
624 if (index($_[0], "\r\n") < 0) {
625 # common case is LF-only, every \n needs an \r;
626 # so favor a cheap tr// over an expensive m//g
628 } else { # count number of '\n' w/o '\r', expensive:
629 scalar(my @n = ($_[0] =~ m/(?<!\r)\n/g));
633 sub is_bad_blob ($$$$) {
634 my ($oid, $type, $size, $expect_oid) = @_;
635 if ($type ne 'blob') {
636 carp "W: $expect_oid is not a blob (type=$type)";
639 croak "BUG: $oid != $expect_oid" if $oid ne $expect_oid;
640 $size == 0 ? 1 : 0; # size == 0 means purged
643 sub index_both { # git->cat_async callback
644 my ($bref, $oid, $type, $size, $sync) = @_;
645 return if is_bad_blob($oid, $type, $size, $sync->{oid});
646 my ($nr, $max) = @$sync{qw(nr max)};
649 $size += crlf_adjust($$bref);
650 my $smsg = bless { bytes => $size, blob => $oid }, 'PublicInbox::Smsg';
651 my $self = $sync->{sidx};
652 local $self->{current_info} = "$self->{current_info}: $oid";
653 my $eml = PublicInbox::Eml->new($bref);
654 $smsg->{num} = index_mm($self, $eml, $oid, $sync) or
655 die "E: could not generate NNTP article number for $oid";
656 add_message($self, $eml, $smsg, $sync);
658 my $cur_cmt = $sync->{cur_cmt} // die 'BUG: {cur_cmt} missing';
659 ${$sync->{latest_cmt}} = $cur_cmt;
662 sub unindex_both { # git->cat_async callback
663 my ($bref, $oid, $type, $size, $sync) = @_;
664 return if is_bad_blob($oid, $type, $size, $sync->{oid});
665 my $self = $sync->{sidx};
666 local $self->{current_info} = "$self->{current_info}: $oid";
667 unindex_eml($self, $oid, PublicInbox::Eml->new($bref));
668 # may be undef if leftover
669 if (defined(my $cur_cmt = $sync->{cur_cmt})) {
670 ${$sync->{latest_cmt}} = $cur_cmt;
677 ($self->{ibx} // $self->{eidx})->with_umask(@_);
680 # called by public-inbox-index
682 my ($self, $opt) = @_;
683 delete $self->{lock_path} if $opt->{-skip_lock};
684 $self->with_umask(\&_index_sync, $self, $opt);
685 if ($opt->{reindex} && !$opt->{quit}) {
687 delete @again{qw(rethread reindex)};
688 index_sync($self, \%again);
689 $opt->{quit} = $again{quit}; # propagate to caller
693 sub check_size { # check_async cb for -index --max-size=...
694 my ($oid, $type, $size, $arg, $git) = @_;
695 (($type // '') eq 'blob') or die "E: bad $oid in $git->{git_dir}";
696 if ($size <= $arg->{max_size}) {
697 $git->cat_async($oid, $arg->{index_oid}, $arg);
699 warn "W: skipping $oid ($size > $arg->{max_size})\n";
703 sub v1_checkpoint ($$;$) {
704 my ($self, $sync, $stk) = @_;
705 $self->{ibx}->git->async_wait_all;
707 # $newest may be undef
708 my $newest = $stk ? $stk->{latest_cmt} : ${$sync->{latest_cmt}};
709 if (defined($newest)) {
710 my $cur = $self->{mm}->last_commit || '';
711 if (need_update($self, $cur, $newest)) {
712 $self->{mm}->last_commit($newest);
715 ${$sync->{max}} = $self->{batch_bytes};
717 $self->{mm}->{dbh}->commit;
718 my $xdb = need_xapian($self) ? $self->{xdb} : undef;
719 if ($newest && $xdb) {
720 my $cur = $xdb->get_metadata('last_commit');
721 if (need_update($self, $cur, $newest)) {
722 $xdb->set_metadata('last_commit', $newest);
725 if ($stk) { # all done if $stk is passed
726 # let SearchView know a full --reindex was done so it can
727 # generate ->has_threadid-dependent links
728 if ($xdb && $sync->{reindex} && !ref($sync->{reindex})) {
729 my $n = $xdb->get_metadata('has_threadid');
730 $xdb->set_metadata('has_threadid', '1') if $n ne '1';
732 $self->{oidx}->rethread_done($sync->{-opt}); # all done
734 commit_txn_lazy($self);
735 $sync->{ibx}->git->cleanup;
736 my $nr = ${$sync->{nr}};
737 idx_release($self, $nr);
738 # let another process do some work...
739 if (my $pr = $sync->{-opt}->{-progress}) {
740 $pr->("indexed $nr/$sync->{ntodo}\n") if $nr;
742 if (!$stk && !$sync->{quit}) { # more to come
743 begin_txn_lazy($self);
744 $self->{mm}->{dbh}->begin_work;
750 my ($self, $sync, $stk) = @_;
751 my $git = $sync->{ibx}->git;
752 my $max = $self->{batch_bytes};
755 $sync->{max} = \$max;
756 $sync->{sidx} = $self;
757 $sync->{latest_cmt} = \(my $latest_cmt);
759 $self->{mm}->{dbh}->begin_work;
760 if (my @leftovers = keys %{delete($sync->{D}) // {}}) {
761 warn('W: unindexing '.scalar(@leftovers)." leftovers\n");
762 for my $oid (@leftovers) {
763 last if $sync->{quit};
764 $oid = unpack('H*', $oid);
765 $git->cat_async($oid, \&unindex_both, $sync);
768 if ($sync->{max_size} = $sync->{-opt}->{max_size}) {
769 $sync->{index_oid} = \&index_both;
771 while (my ($f, $at, $ct, $oid, $cur_cmt) = $stk->pop_rec) {
772 my $arg = { %$sync, cur_cmt => $cur_cmt, oid => $oid };
773 last if $sync->{quit};
775 $arg->{autime} = $at;
776 $arg->{cotime} = $ct;
777 if ($sync->{max_size}) {
778 $git->check_async($oid, \&check_size, $arg);
780 $git->cat_async($oid, \&index_both, $arg);
782 v1_checkpoint($self, $sync) if $max <= 0;
783 } elsif ($f eq 'd') {
784 $git->cat_async($oid, \&unindex_both, $arg);
787 v1_checkpoint($self, $sync, $sync->{quit} ? undef : $stk);
790 sub log2stack ($$$) {
791 my ($sync, $git, $range) = @_;
792 my $D = $sync->{D}; # OID_BIN => NR (if reindexing, undef otherwise)
794 if ($sync->{ibx}->version == 1) {
795 my $path = $hex.'{2}/'.$hex.'{38}';
796 $add = qr!\A:000000 100644 \S+ ($OID) A\t$path$!;
797 $del = qr!\A:100644 000000 ($OID) \S+ D\t$path$!;
799 $del = qr!\A:\d{6} 100644 $OID ($OID) [AM]\td$!;
800 $add = qr!\A:\d{6} 100644 $OID ($OID) [AM]\tm$!;
803 # Count the new files so they can be added newest to oldest
804 # and still have numbers increasing from oldest to newest
805 my $fh = $git->popen(qw(log --raw -r --pretty=tformat:%at-%ct-%H
806 --no-notes --no-color --no-renames --no-abbrev),
808 my ($at, $ct, $stk, $cmt);
810 return if $sync->{quit};
811 if (/\A([0-9]+)-([0-9]+)-($OID)$/o) {
812 ($at, $ct, $cmt) = ($1 + 0, $2 + 0, $3);
813 $stk //= PublicInbox::IdxStack->new($cmt);
816 if ($D) { # reindex case
817 $D->{pack('H*', $oid)}++;
818 } else { # non-reindex case:
819 $stk->push_rec('d', $at, $ct, $oid, $cmt);
824 my $oid_bin = pack('H*', $oid);
825 my $nr = --$D->{$oid_bin};
826 delete($D->{$oid_bin}) if $nr <= 0;
827 # nr < 0 (-1) means it never existed
830 $stk->push_rec('m', $at, $ct, $oid, $cmt);
833 close $fh or die "git log failed: \$?=$?";
834 $stk //= PublicInbox::IdxStack->new;
838 sub prepare_stack ($$) {
839 my ($sync, $range) = @_;
840 my $git = $sync->{ibx}->git;
842 if (index($range, '..') < 0) {
843 # don't show annoying git errors to users who run -index
845 $git->qx(qw(rev-parse -q --verify), "$range^0");
846 return PublicInbox::IdxStack->new->read_prepare if $?;
848 $sync->{D} = $sync->{reindex} ? {} : undef; # OID_BIN => NR
849 log2stack($sync, $git, $range);
852 # --is-ancestor requires git 1.8.0+
853 sub is_ancestor ($$$) {
854 my ($git, $cur, $tip) = @_;
855 return 0 unless $git->check($cur);
856 my $cmd = [ 'git', "--git-dir=$git->{git_dir}",
857 qw(merge-base --is-ancestor), $cur, $tip ];
858 my $pid = spawn($cmd);
859 waitpid($pid, 0) == $pid or die join(' ', @$cmd) .' did not finish';
863 sub need_update ($$$) {
864 my ($self, $cur, $new) = @_;
865 my $git = $self->{ibx}->git;
866 return 1 if $cur && !is_ancestor($git, $cur, $new);
867 my $range = $cur eq '' ? $new : "$cur..$new";
868 chomp(my $n = $git->qx(qw(rev-list --count), $range));
869 ($n eq '' || $n > 0);
872 # The last git commit we indexed with Xapian or SQLite (msgmap)
873 # This needs to account for cases where Xapian or SQLite is
874 # out-of-date with respect to the other.
876 my ($self, $mm) = @_;
877 my $lm = $mm->last_commit || '';
879 if (need_xapian($self)) {
880 $lx = $self->{xdb}->get_metadata('last_commit') || '';
884 # Use last_commit from msgmap if it is older or unset
885 if (!$lm || ($lx && $lm && is_ancestor($self->{ibx}->git, $lm, $lx))) {
891 sub reindex_from ($$) {
892 my ($reindex, $last_commit) = @_;
893 return $last_commit unless $reindex;
894 ref($reindex) eq 'HASH' ? $reindex->{from} : '';
900 # we set {-opt}->{quit} too, so ->index_sync callers
901 # can abort multi-inbox loops this way
902 $sync->{quit} = $sync->{-opt}->{quit} = 1;
903 warn "gracefully quitting\n";
907 # indexes all unindexed messages (v1 only)
909 my ($self, $opt) = @_;
910 my $tip = $opt->{ref} || 'HEAD';
911 my $ibx = $self->{ibx};
912 local $self->{current_info} = "$ibx->{inboxdir}";
913 $self->{batch_bytes} = $opt->{batch_size} // $BATCH_BYTES;
914 $ibx->git->batch_prepare;
915 my $pr = $opt->{-progress};
916 my $sync = { reindex => $opt->{reindex}, -opt => $opt, ibx => $ibx };
917 my $quit = quit_cb($sync);
918 local $SIG{QUIT} = $quit;
919 local $SIG{INT} = $quit;
920 local $SIG{TERM} = $quit;
921 my $xdb = $self->begin_txn_lazy;
922 $self->{oidx}->rethread_prepare($opt);
923 my $mm = _msgmap_init($self);
924 if ($sync->{reindex}) {
925 my $last = $mm->last_commit;
929 # somebody just blindly added --reindex when indexing
930 # for the first time, allow it:
931 undef $sync->{reindex};
934 my $last_commit = _last_x_commit($self, $mm);
935 my $lx = reindex_from($sync->{reindex}, $last_commit);
936 my $range = $lx eq '' ? $tip : "$lx..$tip";
937 $pr->("counting changes\n\t$range ... ") if $pr;
938 my $stk = prepare_stack($sync, $range);
939 $sync->{ntodo} = $stk ? $stk->num_records : 0;
940 $pr->("$sync->{ntodo}\n") if $pr; # continue previous line
941 process_stack($self, $sync, $stk) if !$sync->{quit};
945 # order matters for unlocking
946 $_[0]->{xdb} = undef;
947 $_[0]->{lockfh} = undef;
952 my $xdb = $self->{xdb} || idx_acquire($self);
953 $self->{oidx}->begin_lazy if $self->{oidx};
954 $xdb->begin_transaction if $xdb;
961 $self->with_umask(\&_begin_txn, $self) if !$self->{txn};
964 # store 'indexlevel=medium' in v2 shard=0 and v1 (only one shard)
965 # This metadata is read by Admin::detect_indexlevel:
966 sub set_metadata_once {
969 return if $self->{shard}; # only continue if undef or 0, not >0
970 my $xdb = $self->{xdb};
972 if (delete($self->{-set_has_threadid_once})) {
973 $xdb->set_metadata('has_threadid', '1');
975 if (delete($self->{-set_indexlevel_once})) {
976 my $level = $xdb->get_metadata('indexlevel');
977 if (!$level || $level ne 'medium') {
978 $xdb->set_metadata('indexlevel', 'medium');
981 if (delete($self->{-set_skip_docdata_once})) {
982 $xdb->get_metadata('skip_docdata') or
983 $xdb->set_metadata('skip_docdata', '1');
989 if (my $eidx = $self->{eidx}) {
990 $eidx->git->async_wait_all;
991 $eidx->{transact_bytes} = 0;
993 if (my $xdb = $self->{xdb}) {
994 set_metadata_once($self);
995 $xdb->commit_transaction;
997 $self->{oidx}->commit_lazy if $self->{oidx};
1000 sub commit_txn_lazy {
1002 delete($self->{txn}) and
1003 $self->with_umask(\&_commit_txn, $self);
1006 sub eidx_shard_new {
1007 my ($class, $eidx, $shard) = @_;
1010 xpfx => $eidx->{xpfx},
1011 indexlevel => $eidx->{indexlevel},
1016 $self->{-set_indexlevel_once} = 1 if $self->{indexlevel} eq 'medium';
1020 # ensure there's no stale Xapian docs by treating $over as canonical
1022 my ($self, $over) = @_;
1023 begin_txn_lazy($self);
1024 my $sth = $over->dbh->prepare(<<'');
1025 SELECT COUNT(*) FROM over WHERE num = ?
1027 my $xdb = $self->{xdb};
1028 my $cur = $xdb->postlist_begin('');
1029 my $end = $xdb->postlist_end('');
1030 my $xdir = $self->xdir;
1031 for (; $cur != $end; $cur++) {
1032 my $docid = $cur->get_docid;
1033 $sth->execute($docid);
1034 my $x = $sth->fetchrow_array;
1036 warn "I: removing $xdir #$docid, not in `over'\n";
1037 $xdb->delete_document($docid);