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;
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 my $mids = mids_for_index($mime);
418 $smsg //= bless { blob => '' }, 'PublicInbox::Smsg'; # test-only compat
419 $smsg->{mid} //= $mids->[0]; # v1 compatibility
420 $smsg->{num} //= do { # v1
422 index_mm($self, $mime, $smsg->{blob}, $sync);
426 $smsg->populate($mime, $sync);
427 $smsg->{bytes} //= length($mime->as_string);
430 # order matters, overview stores every possible piece of
431 # data in doc_data (deflated). Xapian only stores a subset
432 # of the fields which exist in over.sqlite3. We may stop
433 # storing doc_data in Xapian sometime after we get multi-inbox
435 if (my $oidx = $self->{oidx}) { # v1 only
436 $oidx->add_overview($mime, $smsg);
438 if (need_xapian($self)) {
439 add_xapian($self, $mime, $smsg, $mids);
444 warn "failed to index message <".join('> <',@$mids).">: $@\n";
451 my ($self, $docid) = @_;
452 my $doc = eval { $self->{xdb}->get_document($docid) };
454 warn "E: $@\n" if $@;
455 warn "E: #$docid missing in Xapian\n";
461 my ($self, $docid, $eidx_key, $eml) = @_;
462 begin_txn_lazy($self);
463 my $doc = _get_doc($self, $docid) or return;
464 term_generator($self)->set_document($doc);
465 $doc->add_boolean_term('O'.$eidx_key) if $eidx_key ne '.';
466 index_list_id($self, $doc, $eml);
467 $self->{xdb}->replace_document($docid, $doc);
470 sub remove_eidx_info {
471 my ($self, $docid, $eidx_key, $eml) = @_;
472 begin_txn_lazy($self);
473 my $doc = _get_doc($self, $docid) or return;
474 eval { $doc->remove_term('O'.$eidx_key) };
475 warn "W: ->remove_term O$eidx_key: $@\n" if $@;
476 for my $l ($eml ? $eml->header_raw('List-Id') : ()) {
477 $l =~ /<([^>]+)>/ or next;
479 eval { $doc->remove_term('G' . $lid) };
480 warn "W: ->remove_term G$lid: $@\n" if $@;
482 # nb: we don't remove the XL probabilistic terms
483 # since terms may overlap if cross-posted.
485 # IOW, a message which has both <foo.example.com>
486 # and <bar.example.com> would have overlapping
487 # "XLexample" and "XLcom" as terms and which we
488 # wouldn't know if they're safe to remove if we just
489 # unindex <foo.example.com> while preserving
492 # In any case, this entire sub is will likely never
493 # be needed and users using the "l:" prefix are probably
496 $self->{xdb}->replace_document($docid, $doc);
500 my ($self, $docid, @kw) = @_;
501 begin_txn_lazy($self);
502 my $doc = _get_doc($self, $docid) or return;
503 my %keep = map { $_ => 1 } @kw;
506 my $end = $doc->termlist_end;
507 for (my $cur = $doc->termlist_begin; $cur != $end; $cur++) {
509 last if $cur == $end;
510 my $kw = $cur->get_termname;
511 $kw =~ s/\AK//s or next;
512 $keep{$kw} ? delete($add{$kw}) : push(@rm, $kw);
514 return unless (scalar(@rm) + scalar(keys %add));
515 $doc->remove_term('K'.$_) for @rm;
516 $doc->add_boolean_term('K'.$_) for (keys %add);
517 $self->{xdb}->replace_document($docid, $doc);
521 my ($self, $docid, @kw) = @_;
522 begin_txn_lazy($self);
523 my $doc = _get_doc($self, $docid) or return;
524 $doc->add_boolean_term('K'.$_) for @kw;
525 $self->{xdb}->replace_document($docid, $doc);
528 sub remove_keywords {
529 my ($self, $docid, @kw) = @_;
530 begin_txn_lazy($self);
531 my $doc = _get_doc($self, $docid) or return;
534 $doc->remove_term('K'.$_);
537 $self->{xdb}->replace_document($docid, $doc) if $replace;
540 sub smsg_from_doc ($) {
542 my $data = $doc->get_data or return;
543 my $smsg = bless {}, 'PublicInbox::Smsg';
544 $smsg->{ts} = int_val($doc, PublicInbox::Search::TS());
545 my $dt = int_val($doc, PublicInbox::Search::DT());
546 my ($yyyy, $mon, $dd, $hh, $mm, $ss) = unpack('A4A2A2A2A2A2', $dt);
547 $smsg->{ds} = timegm($ss, $mm, $hh, $dd, $mon - 1, $yyyy);
548 $smsg->load_from_data($data);
553 my ($self, @docids) = @_;
554 my $xdb = $self->{xdb} or return;
555 for my $docid (@docids) {
556 eval { $xdb->delete_document($docid) };
557 warn "E: #$docid not in in Xapian? $@\n" if $@;
561 sub remove_by_docid {
562 my ($self, $num) = @_;
563 die "BUG: remove_by_docid is v2-only\n" if $self->{oidx};
564 $self->begin_txn_lazy;
565 xdb_remove($self, $num) if need_xapian($self);
568 sub index_git_blob_id {
569 my ($doc, $pfx, $objid) = @_;
571 my $len = length($objid);
572 for (my $len = length($objid); $len >= 7; ) {
573 $doc->add_term($pfx.$objid);
574 $objid = substr($objid, 0, --$len);
580 my ($self, $oid, $eml) = @_;
581 my $mids = mids($eml);
584 for my $mid (@$mids) {
585 my @removed = $self->{oidx}->remove_oid($oid, $mid);
586 $nr += scalar @removed;
587 $tmp{$_}++ for @removed;
590 my $m = join('> <', @$mids);
591 warn "W: <$m> missing for removal from overview\n";
593 while (my ($num, $nr) = each %tmp) {
594 warn "BUG: $num appears >1 times ($nr) for $oid\n" if $nr != 1;
597 $self->{mm}->num_delete($_) for (keys %tmp);
598 } else { # just in case msgmap and over.sqlite3 become desynched:
599 $self->{mm}->mid_delete($mids->[0]);
601 xdb_remove($self, keys %tmp) if need_xapian($self);
605 my ($self, $mime, $oid, $sync) = @_;
606 my $mids = mids($mime);
607 my $mm = $self->{mm};
608 if ($sync->{reindex}) {
609 my $oidx = $self->{oidx};
610 for my $mid (@$mids) {
611 my ($num, undef) = $oidx->num_mid0_for_oid($oid, $mid);
612 return $num if defined $num;
614 $mm->num_for($mids->[0]) // $mm->mid_insert($mids->[0]);
616 # fallback to num_for since filters like RubyLang set the number
617 $mm->mid_insert($mids->[0]) // $mm->num_for($mids->[0]);
621 # returns the number of bytes to add if given a non-CRLF arg
622 sub crlf_adjust ($) {
623 if (index($_[0], "\r\n") < 0) {
624 # common case is LF-only, every \n needs an \r;
625 # so favor a cheap tr// over an expensive m//g
627 } else { # count number of '\n' w/o '\r', expensive:
628 scalar(my @n = ($_[0] =~ m/(?<!\r)\n/g));
632 sub is_bad_blob ($$$$) {
633 my ($oid, $type, $size, $expect_oid) = @_;
634 if ($type ne 'blob') {
635 carp "W: $expect_oid is not a blob (type=$type)";
638 croak "BUG: $oid != $expect_oid" if $oid ne $expect_oid;
639 $size == 0 ? 1 : 0; # size == 0 means purged
642 sub index_both { # git->cat_async callback
643 my ($bref, $oid, $type, $size, $sync) = @_;
644 return if is_bad_blob($oid, $type, $size, $sync->{oid});
645 my ($nr, $max) = @$sync{qw(nr max)};
648 $size += crlf_adjust($$bref);
649 my $smsg = bless { bytes => $size, blob => $oid }, 'PublicInbox::Smsg';
650 my $self = $sync->{sidx};
651 local $self->{current_info} = "$self->{current_info}: $oid";
652 my $eml = PublicInbox::Eml->new($bref);
653 $smsg->{num} = index_mm($self, $eml, $oid, $sync) or
654 die "E: could not generate NNTP article number for $oid";
655 add_message($self, $eml, $smsg, $sync);
657 my $cur_cmt = $sync->{cur_cmt} // die 'BUG: {cur_cmt} missing';
658 ${$sync->{latest_cmt}} = $cur_cmt;
661 sub unindex_both { # git->cat_async callback
662 my ($bref, $oid, $type, $size, $sync) = @_;
663 return if is_bad_blob($oid, $type, $size, $sync->{oid});
664 my $self = $sync->{sidx};
665 local $self->{current_info} = "$self->{current_info}: $oid";
666 unindex_eml($self, $oid, PublicInbox::Eml->new($bref));
667 # may be undef if leftover
668 if (defined(my $cur_cmt = $sync->{cur_cmt})) {
669 ${$sync->{latest_cmt}} = $cur_cmt;
676 ($self->{ibx} // $self->{eidx})->with_umask(@_);
679 # called by public-inbox-index
681 my ($self, $opt) = @_;
682 delete $self->{lock_path} if $opt->{-skip_lock};
683 $self->with_umask(\&_index_sync, $self, $opt);
684 if ($opt->{reindex} && !$opt->{quit}) {
686 delete @again{qw(rethread reindex)};
687 index_sync($self, \%again);
688 $opt->{quit} = $again{quit}; # propagate to caller
692 sub check_size { # check_async cb for -index --max-size=...
693 my ($oid, $type, $size, $arg, $git) = @_;
694 (($type // '') eq 'blob') or die "E: bad $oid in $git->{git_dir}";
695 if ($size <= $arg->{max_size}) {
696 $git->cat_async($oid, $arg->{index_oid}, $arg);
698 warn "W: skipping $oid ($size > $arg->{max_size})\n";
702 sub v1_checkpoint ($$;$) {
703 my ($self, $sync, $stk) = @_;
704 $self->{ibx}->git->async_wait_all;
706 # $newest may be undef
707 my $newest = $stk ? $stk->{latest_cmt} : ${$sync->{latest_cmt}};
708 if (defined($newest)) {
709 my $cur = $self->{mm}->last_commit || '';
710 if (need_update($self, $cur, $newest)) {
711 $self->{mm}->last_commit($newest);
714 ${$sync->{max}} = $self->{batch_bytes};
716 $self->{mm}->{dbh}->commit;
717 my $xdb = need_xapian($self) ? $self->{xdb} : undef;
718 if ($newest && $xdb) {
719 my $cur = $xdb->get_metadata('last_commit');
720 if (need_update($self, $cur, $newest)) {
721 $xdb->set_metadata('last_commit', $newest);
724 if ($stk) { # all done if $stk is passed
725 # let SearchView know a full --reindex was done so it can
726 # generate ->has_threadid-dependent links
727 if ($xdb && $sync->{reindex} && !ref($sync->{reindex})) {
728 my $n = $xdb->get_metadata('has_threadid');
729 $xdb->set_metadata('has_threadid', '1') if $n ne '1';
731 $self->{oidx}->rethread_done($sync->{-opt}); # all done
733 commit_txn_lazy($self);
734 $sync->{ibx}->git->cleanup;
735 my $nr = ${$sync->{nr}};
736 idx_release($self, $nr);
737 # let another process do some work...
738 if (my $pr = $sync->{-opt}->{-progress}) {
739 $pr->("indexed $nr/$sync->{ntodo}\n") if $nr;
741 if (!$stk && !$sync->{quit}) { # more to come
742 begin_txn_lazy($self);
743 $self->{mm}->{dbh}->begin_work;
749 my ($self, $sync, $stk) = @_;
750 my $git = $sync->{ibx}->git;
751 my $max = $self->{batch_bytes};
754 $sync->{max} = \$max;
755 $sync->{sidx} = $self;
756 $sync->{latest_cmt} = \(my $latest_cmt);
758 $self->{mm}->{dbh}->begin_work;
759 if (my @leftovers = keys %{delete($sync->{D}) // {}}) {
760 warn('W: unindexing '.scalar(@leftovers)." leftovers\n");
761 for my $oid (@leftovers) {
762 last if $sync->{quit};
763 $oid = unpack('H*', $oid);
764 $git->cat_async($oid, \&unindex_both, $sync);
767 if ($sync->{max_size} = $sync->{-opt}->{max_size}) {
768 $sync->{index_oid} = \&index_both;
770 while (my ($f, $at, $ct, $oid, $cur_cmt) = $stk->pop_rec) {
771 my $arg = { %$sync, cur_cmt => $cur_cmt, oid => $oid };
772 last if $sync->{quit};
774 $arg->{autime} = $at;
775 $arg->{cotime} = $ct;
776 if ($sync->{max_size}) {
777 $git->check_async($oid, \&check_size, $arg);
779 $git->cat_async($oid, \&index_both, $arg);
781 v1_checkpoint($self, $sync) if $max <= 0;
782 } elsif ($f eq 'd') {
783 $git->cat_async($oid, \&unindex_both, $arg);
786 v1_checkpoint($self, $sync, $sync->{quit} ? undef : $stk);
789 sub log2stack ($$$) {
790 my ($sync, $git, $range) = @_;
791 my $D = $sync->{D}; # OID_BIN => NR (if reindexing, undef otherwise)
793 if ($sync->{ibx}->version == 1) {
794 my $path = $hex.'{2}/'.$hex.'{38}';
795 $add = qr!\A:000000 100644 \S+ ($OID) A\t$path$!;
796 $del = qr!\A:100644 000000 ($OID) \S+ D\t$path$!;
798 $del = qr!\A:\d{6} 100644 $OID ($OID) [AM]\td$!;
799 $add = qr!\A:\d{6} 100644 $OID ($OID) [AM]\tm$!;
802 # Count the new files so they can be added newest to oldest
803 # and still have numbers increasing from oldest to newest
804 my $fh = $git->popen(qw(log --raw -r --pretty=tformat:%at-%ct-%H
805 --no-notes --no-color --no-renames --no-abbrev),
807 my ($at, $ct, $stk, $cmt);
809 return if $sync->{quit};
810 if (/\A([0-9]+)-([0-9]+)-($OID)$/o) {
811 ($at, $ct, $cmt) = ($1 + 0, $2 + 0, $3);
812 $stk //= PublicInbox::IdxStack->new($cmt);
815 if ($D) { # reindex case
816 $D->{pack('H*', $oid)}++;
817 } else { # non-reindex case:
818 $stk->push_rec('d', $at, $ct, $oid, $cmt);
823 my $oid_bin = pack('H*', $oid);
824 my $nr = --$D->{$oid_bin};
825 delete($D->{$oid_bin}) if $nr <= 0;
826 # nr < 0 (-1) means it never existed
829 $stk->push_rec('m', $at, $ct, $oid, $cmt);
832 close $fh or die "git log failed: \$?=$?";
833 $stk //= PublicInbox::IdxStack->new;
837 sub prepare_stack ($$) {
838 my ($sync, $range) = @_;
839 my $git = $sync->{ibx}->git;
841 if (index($range, '..') < 0) {
842 # don't show annoying git errors to users who run -index
844 $git->qx(qw(rev-parse -q --verify), "$range^0");
845 return PublicInbox::IdxStack->new->read_prepare if $?;
847 $sync->{D} = $sync->{reindex} ? {} : undef; # OID_BIN => NR
848 log2stack($sync, $git, $range);
851 # --is-ancestor requires git 1.8.0+
852 sub is_ancestor ($$$) {
853 my ($git, $cur, $tip) = @_;
854 return 0 unless $git->check($cur);
855 my $cmd = [ 'git', "--git-dir=$git->{git_dir}",
856 qw(merge-base --is-ancestor), $cur, $tip ];
857 my $pid = spawn($cmd);
858 waitpid($pid, 0) == $pid or die join(' ', @$cmd) .' did not finish';
862 sub need_update ($$$) {
863 my ($self, $cur, $new) = @_;
864 my $git = $self->{ibx}->git;
865 return 1 if $cur && !is_ancestor($git, $cur, $new);
866 my $range = $cur eq '' ? $new : "$cur..$new";
867 chomp(my $n = $git->qx(qw(rev-list --count), $range));
868 ($n eq '' || $n > 0);
871 # The last git commit we indexed with Xapian or SQLite (msgmap)
872 # This needs to account for cases where Xapian or SQLite is
873 # out-of-date with respect to the other.
875 my ($self, $mm) = @_;
876 my $lm = $mm->last_commit || '';
878 if (need_xapian($self)) {
879 $lx = $self->{xdb}->get_metadata('last_commit') || '';
883 # Use last_commit from msgmap if it is older or unset
884 if (!$lm || ($lx && $lm && is_ancestor($self->{ibx}->git, $lm, $lx))) {
890 sub reindex_from ($$) {
891 my ($reindex, $last_commit) = @_;
892 return $last_commit unless $reindex;
893 ref($reindex) eq 'HASH' ? $reindex->{from} : '';
899 # we set {-opt}->{quit} too, so ->index_sync callers
900 # can abort multi-inbox loops this way
901 $sync->{quit} = $sync->{-opt}->{quit} = 1;
902 warn "gracefully quitting\n";
906 # indexes all unindexed messages (v1 only)
908 my ($self, $opt) = @_;
909 my $tip = $opt->{ref} || 'HEAD';
910 my $ibx = $self->{ibx};
911 local $self->{current_info} = "$ibx->{inboxdir}";
912 $self->{batch_bytes} = $opt->{batch_size} // $BATCH_BYTES;
913 $ibx->git->batch_prepare;
914 my $pr = $opt->{-progress};
915 my $sync = { reindex => $opt->{reindex}, -opt => $opt, ibx => $ibx };
916 my $quit = quit_cb($sync);
917 local $SIG{QUIT} = $quit;
918 local $SIG{INT} = $quit;
919 local $SIG{TERM} = $quit;
920 my $xdb = $self->begin_txn_lazy;
921 $self->{oidx}->rethread_prepare($opt);
922 my $mm = _msgmap_init($self);
923 if ($sync->{reindex}) {
924 my $last = $mm->last_commit;
928 # somebody just blindly added --reindex when indexing
929 # for the first time, allow it:
930 undef $sync->{reindex};
933 my $last_commit = _last_x_commit($self, $mm);
934 my $lx = reindex_from($sync->{reindex}, $last_commit);
935 my $range = $lx eq '' ? $tip : "$lx..$tip";
936 $pr->("counting changes\n\t$range ... ") if $pr;
937 my $stk = prepare_stack($sync, $range);
938 $sync->{ntodo} = $stk ? $stk->num_records : 0;
939 $pr->("$sync->{ntodo}\n") if $pr; # continue previous line
940 process_stack($self, $sync, $stk) if !$sync->{quit};
944 # order matters for unlocking
945 $_[0]->{xdb} = undef;
946 $_[0]->{lockfh} = undef;
951 my $xdb = $self->{xdb} || idx_acquire($self);
952 $self->{oidx}->begin_lazy if $self->{oidx};
953 $xdb->begin_transaction if $xdb;
960 $self->with_umask(\&_begin_txn, $self) if !$self->{txn};
963 # store 'indexlevel=medium' in v2 shard=0 and v1 (only one shard)
964 # This metadata is read by Admin::detect_indexlevel:
965 sub set_metadata_once {
968 return if $self->{shard}; # only continue if undef or 0, not >0
969 my $xdb = $self->{xdb};
971 if (delete($self->{-set_has_threadid_once})) {
972 $xdb->set_metadata('has_threadid', '1');
974 if (delete($self->{-set_indexlevel_once})) {
975 my $level = $xdb->get_metadata('indexlevel');
976 if (!$level || $level ne 'medium') {
977 $xdb->set_metadata('indexlevel', 'medium');
980 if (delete($self->{-set_skip_docdata_once})) {
981 $xdb->get_metadata('skip_docdata') or
982 $xdb->set_metadata('skip_docdata', '1');
988 if (my $eidx = $self->{eidx}) {
989 $eidx->git->async_wait_all;
990 $eidx->{transact_bytes} = 0;
992 if (my $xdb = $self->{xdb}) {
993 set_metadata_once($self);
994 $xdb->commit_transaction;
996 $self->{oidx}->commit_lazy if $self->{oidx};
999 sub commit_txn_lazy {
1001 delete($self->{txn}) and
1002 $self->with_umask(\&_commit_txn, $self);
1007 if (need_xapian($self)) {
1008 die "$$ $0 xdb not released\n" if $self->{xdb};
1010 die "$$ $0 still in transaction\n" if $self->{txn};
1013 sub eidx_shard_new {
1014 my ($class, $eidx, $shard) = @_;
1017 xpfx => $eidx->{xpfx},
1018 indexlevel => $eidx->{indexlevel},
1023 $self->{-set_indexlevel_once} = 1 if $self->{indexlevel} eq 'medium';
1027 # ensure there's no stale Xapian docs by treating $over as canonical
1029 my ($self, $over) = @_;
1030 begin_txn_lazy($self);
1031 my $sth = $over->dbh->prepare(<<'');
1032 SELECT COUNT(*) FROM over WHERE num = ?
1034 my $xdb = $self->{xdb};
1035 my $cur = $xdb->postlist_begin('');
1036 my $end = $xdb->postlist_end('');
1037 my $xdir = $self->xdir;
1038 for (; $cur != $end; $cur++) {
1039 my $docid = $cur->get_docid;
1040 $sth->execute($docid);
1041 my $x = $sth->fetchrow_array;
1043 warn "I: removing $xdir #$docid, not in `over'\n";
1044 $xdb->delete_document($docid);