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::Search qw(xap_terms);
15 use PublicInbox::InboxWritable;
16 use PublicInbox::MID qw(mids_for_index mids);
17 use PublicInbox::MsgIter;
18 use PublicInbox::IdxStack;
19 use Carp qw(croak carp);
20 use POSIX qw(strftime);
21 use Time::Local qw(timegm);
22 use PublicInbox::OverIdx;
23 use PublicInbox::Spawn qw(spawn nodatacow_dir);
24 use PublicInbox::Git qw(git_unquote);
25 use PublicInbox::MsgTime qw(msg_timestamp msg_datestamp);
26 use PublicInbox::Address;
27 our @EXPORT_OK = qw(log2stack is_ancestor check_size prepare_stack
28 index_text term_generator add_val is_bad_blob);
29 my $X = \%PublicInbox::Search::X;
30 our ($DB_CREATE_OR_OPEN, $DB_OPEN);
32 our $BATCH_BYTES = $ENV{XAPIAN_FLUSH_THRESHOLD} ? 0x7fffffff : 1_000_000;
33 use constant DEBUG => !!$ENV{DEBUG};
35 my $xapianlevels = qr/\A(?:full|medium)\z/;
37 my $OID = $hex .'{40,}';
38 my @VMD_MAP = (kw => 'K', L => 'L');
39 our $INDEXLEVELS = qr/\A(?:full|medium|basic)\z/;
42 my ($class, $ibx, $creat, $shard) = @_;
43 ref $ibx or die "BUG: expected PublicInbox::Inbox object: $ibx";
44 my $inboxdir = $ibx->{inboxdir};
45 my $version = $ibx->version;
46 my $indexlevel = 'full';
47 my $altid = $ibx->{altid};
49 require PublicInbox::AltId;
50 $altid = [ map { PublicInbox::AltId->new($ibx, $_); } @$altid ];
52 if ($ibx->{indexlevel}) {
53 if ($ibx->{indexlevel} =~ $INDEXLEVELS) {
54 $indexlevel = $ibx->{indexlevel};
56 die("Invalid indexlevel $ibx->{indexlevel}\n");
59 $ibx = PublicInbox::InboxWritable->new($ibx);
60 my $self = PublicInbox::Search->new($ibx);
63 $self->{-altid} = $altid;
64 $self->{indexlevel} = $indexlevel;
65 $self->{-set_indexlevel_once} = 1 if $indexlevel eq 'medium';
66 if ($ibx->{-skip_docdata}) {
67 $self->{-set_skip_docdata_once} = 1;
68 $self->{-skip_docdata} = 1;
71 $self->{lock_path} = "$inboxdir/ssoma.lock";
72 my $dir = $self->xdir;
73 $self->{oidx} = PublicInbox::OverIdx->new("$dir/over.sqlite3");
74 $self->{oidx}->{-no_fsync} = 1 if $ibx->{-no_fsync};
75 } elsif ($version == 2) {
76 defined $shard or die "shard is required for v2\n";
78 $self->{shard} = $shard;
79 $self->{lock_path} = undef;
81 die "unsupported inbox version=$version\n";
83 $self->{creat} = ($creat || 0) == 1;
87 sub need_xapian ($) { $_[0]->{indexlevel} =~ $xapianlevels }
90 my ($self, $wake) = @_;
91 if (need_xapian($self)) {
92 my $xdb = delete $self->{xdb} or croak 'not acquired';
95 $self->lock_release($wake) if $self->{creat};
99 sub load_xapian_writable () {
100 return 1 if $X->{WritableDatabase};
101 PublicInbox::Search::load_xapian() or return;
102 my $xap = $PublicInbox::Search::Xap;
103 for (qw(Document TermGenerator WritableDatabase)) {
104 $X->{$_} = $xap.'::'.$_;
106 eval 'require '.$X->{WritableDatabase} or die;
107 *sortable_serialise = $xap.'::sortable_serialise';
108 $DB_CREATE_OR_OPEN = eval($xap.'::DB_CREATE_OR_OPEN()');
109 $DB_OPEN = eval($xap.'::DB_OPEN()');
110 my $ver = (eval($xap.'::major_version()') << 16) |
111 (eval($xap.'::minor_version()') << 8) |
112 eval($xap.'::revision()');
113 $DB_NO_SYNC = 0x4 if $ver >= 0x10400;
114 # Xapian v1.2.21..v1.2.24 were missing close-on-exec on OFD locks
115 $X->{CLOEXEC_UNSET} = 1 if $ver >= 0x010215 && $ver <= 0x010218;
122 my $dir = $self->xdir;
123 if (need_xapian($self)) {
124 croak 'already acquired' if $self->{xdb};
125 load_xapian_writable();
126 $flag = $self->{creat} ? $DB_CREATE_OR_OPEN : $DB_OPEN;
128 if ($self->{creat}) {
132 # don't create empty Xapian directories if we don't need Xapian
133 my $is_shard = defined($self->{shard});
134 if (!-d $dir && (!$is_shard ||
135 ($is_shard && need_xapian($self)))) {
136 File::Path::mkpath($dir);
138 $self->{-set_has_threadid_once} = 1;
141 return unless defined $flag;
142 $flag |= $DB_NO_SYNC if ($self->{ibx} // $self->{eidx})->{-no_fsync};
143 my $xdb = eval { ($X->{WritableDatabase})->new($dir, $flag) };
144 croak "Failed opening $dir: $@" if $@;
149 my ($doc, $col, $num) = @_;
150 $num = sortable_serialise($num);
151 $doc->add_value($col, $num);
154 sub term_generator ($) { # write-only
157 $self->{term_generator} //= do {
158 my $tg = $X->{TermGenerator}->new;
159 $tg->set_stemmer(PublicInbox::Search::stemmer($self));
164 sub index_phrase ($$$$) {
165 my ($self, $text, $wdf_inc, $prefix) = @_;
167 my $tg = term_generator($self);
168 $tg->index_text($text, $wdf_inc, $prefix);
169 $tg->increase_termpos;
172 sub index_text ($$$$) {
173 my ($self, $text, $wdf_inc, $prefix) = @_;
175 if ($self->{indexlevel} eq 'full') {
176 index_phrase($self, $text, $wdf_inc, $prefix);
178 my $tg = term_generator($self);
179 $tg->index_text_without_positions($text, $wdf_inc, $prefix);
183 sub index_headers ($$) {
184 my ($self, $smsg) = @_;
185 my @x = (from => 'A', to => 'XTO', cc => 'XCC'); # A: Author
186 while (my ($field, $pfx) = splice(@x, 0, 2)) {
187 my $val = $smsg->{$field};
189 # include "(comments)" after the address, too, so not using
190 # PublicInbox::Address::names or pairs
191 index_text($self, $val, 1, $pfx);
193 # we need positional info for email addresses since they
194 # can be considered phrases
195 if ($self->{indexlevel} eq 'medium') {
196 for my $addr (PublicInbox::Address::emails($val)) {
197 index_phrase($self, $addr, 1, $pfx);
201 @x = (subject => 'S');
202 while (my ($field, $pfx) = splice(@x, 0, 2)) {
203 my $val = $smsg->{$field};
204 index_text($self, $val, 1, $pfx) if $val ne '';
208 sub index_diff_inc ($$$$) {
209 my ($self, $text, $pfx, $xnq) = @_;
211 index_text($self, join("\n", @$xnq), 1, 'XNQ');
214 if ($pfx eq 'XDFN') {
215 index_phrase($self, $text, 1, $pfx);
217 index_text($self, $text, 1, $pfx);
221 sub index_old_diff_fn {
222 my ($self, $seen, $fa, $fb, $xnq) = @_;
224 # no renames or space support for traditional diffs,
225 # find the number of leading common paths to strip:
226 my @fa = split('/', $fa);
227 my @fb = split('/', $fb);
228 while (scalar(@fa) && scalar(@fb)) {
229 $fa = join('/', @fa);
230 $fb = join('/', @fb);
232 unless ($seen->{$fa}++) {
233 index_diff_inc($self, $fa, 'XDFN', $xnq);
243 sub index_diff ($$$) {
244 my ($self, $txt, $doc) = @_;
249 foreach (split(/\n/, $txt)) {
250 if ($in_diff && s/^ //) { # diff context
251 index_diff_inc($self, $_, 'XDFCTX', $xnq);
252 } elsif (/^-- $/) { # email signature begins
254 } elsif (m!^diff --git "?[^/]+/.+ "?[^/]+/.+\z!) {
255 # wait until "---" and "+++" to capture filenames
258 } elsif (m/^diff -(.+) (\S+) (\S+)$/) {
259 my ($opt, $fa, $fb) = ($1, $2, $3);
261 # only support unified:
262 next unless $opt =~ /[uU]/;
263 $in_diff = index_old_diff_fn($self, \%seen, $fa, $fb,
265 } elsif (m!^--- ("?[^/]+/.+)!) {
267 $fn = (split('/', git_unquote($fn), 2))[1];
268 $seen{$fn}++ or index_diff_inc($self, $fn, 'XDFN', $xnq);
270 } elsif (m!^\+\+\+ ("?[^/]+/.+)!) {
272 $fn = (split('/', git_unquote($fn), 2))[1];
273 $seen{$fn}++ or index_diff_inc($self, $fn, 'XDFN', $xnq);
275 } elsif (/^--- (\S+)/) {
278 } elsif (defined $in_diff && /^\+\+\+ (\S+)/) {
279 $in_diff = index_old_diff_fn($self, \%seen, $in_diff,
281 } elsif ($in_diff && s/^\+//) { # diff added
282 index_diff_inc($self, $_, 'XDFB', $xnq);
283 } elsif ($in_diff && s/^-//) { # diff removed
284 index_diff_inc($self, $_, 'XDFA', $xnq);
285 } elsif (m!^index ([a-f0-9]+)\.\.([a-f0-9]+)!) {
286 my ($ba, $bb) = ($1, $2);
287 index_git_blob_id($doc, 'XDFPRE', $ba);
288 index_git_blob_id($doc, 'XDFPOST', $bb);
290 } elsif (/^@@ (?:\S+) (?:\S+) @@\s*$/) {
291 # traditional diff w/o -p
292 } elsif (/^@@ (?:\S+) (?:\S+) @@\s*(\S+.*)$/) {
293 # hunk header context
294 index_diff_inc($self, $1, 'XDFHH', $xnq);
295 # ignore the following lines:
296 } elsif (/^(?:dis)similarity index/ ||
297 /^(?:old|new) mode/ ||
298 /^(?:deleted|new) file mode/ ||
299 /^(?:copy|rename) (?:from|to) / ||
300 /^(?:dis)?similarity index / ||
301 /^\\ No newline at end of file/ ||
302 /^Binary files .* differ/) {
305 # possible to be in diff context, some mail may be
306 # stripped by MUA or even GNU diff(1). "git apply"
307 # treats a bare "\n" as diff context, too
310 warn "non-diff line: $_\n" if DEBUG && $_ ne '';
315 index_text($self, join("\n", @xnq), 1, 'XNQ');
318 sub index_xapian { # msg_iter callback
319 my $part = $_[0]->[0]; # ignore $depth and $idx
320 my ($self, $doc) = @{$_[1]};
321 my $ct = $part->content_type || 'text/plain';
322 my $fn = $part->filename;
323 if (defined $fn && $fn ne '') {
324 index_phrase($self, $fn, 1, 'XFN');
326 if ($part->{is_submsg}) {
327 my $mids = mids_for_index($part);
328 index_ids($self, $doc, $part, $mids);
329 my $smsg = bless {}, 'PublicInbox::Smsg';
330 $smsg->populate($part);
331 index_headers($self, $smsg);
334 my ($s, undef) = msg_part_text($part, $ct);
335 defined $s or return;
336 $_[0]->[0] = $part = undef; # free memory
338 # split off quoted and unquoted blocks:
339 my @sections = PublicInbox::MsgIter::split_quotes($s);
340 undef $s; # free memory
341 for my $txt (@sections) {
343 index_text($self, $txt, 0, 'XQUOT');
345 # does it look like a diff?
346 if ($txt =~ /^(?:diff|---|\+\+\+) /ms) {
347 index_diff($self, $txt, $doc);
349 index_text($self, $txt, 1, 'XNQ');
352 undef $txt; # free memory
356 sub index_list_id ($$$) {
357 my ($self, $doc, $hdr) = @_;
358 for my $l ($hdr->header_raw('List-Id')) {
359 $l =~ /<([^>]+)>/ or next;
361 $doc->add_boolean_term('G' . $lid);
362 index_phrase($self, $lid, 1, 'XL'); # probabilistic
366 sub index_ids ($$$$) {
367 my ($self, $doc, $hdr, $mids) = @_;
368 for my $mid (@$mids) {
369 index_phrase($self, $mid, 1, 'XM');
371 # because too many Message-IDs are prefixed with
373 if ($mid =~ /\w{12,}/) {
374 my @long = ($mid =~ /(\w{3,}+)/g);
375 index_phrase($self, join(' ', @long), 1, 'XM');
378 $doc->add_boolean_term('Q' . $_) for @$mids;
379 index_list_id($self, $doc, $hdr);
382 sub eml2doc ($$$;$) {
383 my ($self, $eml, $smsg, $mids) = @_;
384 $mids //= mids_for_index($eml);
385 my $doc = $X->{Document}->new;
386 add_val($doc, PublicInbox::Search::TS(), $smsg->{ts});
387 my @ds = gmtime($smsg->{ds});
388 my $yyyymmdd = strftime('%Y%m%d', @ds);
389 add_val($doc, PublicInbox::Search::YYYYMMDD(), $yyyymmdd);
390 my $dt = strftime('%Y%m%d%H%M%S', @ds);
391 add_val($doc, PublicInbox::Search::DT(), $dt);
392 add_val($doc, PublicInbox::Search::BYTES(), $smsg->{bytes});
393 add_val($doc, PublicInbox::Search::UID(), $smsg->{num});
394 add_val($doc, PublicInbox::Search::THREADID, $smsg->{tid});
396 my $tg = term_generator($self);
397 $tg->set_document($doc);
398 index_headers($self, $smsg);
400 if (defined(my $eidx_key = $smsg->{eidx_key})) {
401 $doc->add_boolean_term('O'.$eidx_key) if $eidx_key ne '.';
403 msg_iter($eml, \&index_xapian, [ $self, $doc ]);
404 index_ids($self, $doc, $eml, $mids);
406 # by default, we maintain compatibility with v1.5.0 and earlier
407 # by writing to docdata.glass, users who never exect to downgrade can
409 if (!$self->{-skip_docdata}) {
410 # WWW doesn't need {to} or {cc}, only NNTP
411 $smsg->{to} = $smsg->{cc} = '';
412 $smsg->parse_references($eml, $mids);
413 my $data = $smsg->to_doc_data;
414 $doc->set_data($data);
417 if (my $altid = $self->{-altid}) {
418 foreach my $alt (@$altid) {
419 my $pfx = $alt->{xprefix};
420 foreach my $mid (@$mids) {
421 my $id = $alt->mid2alt($mid);
422 next unless defined $id;
423 $doc->add_boolean_term($pfx . $id);
430 sub add_xapian ($$$$) {
431 my ($self, $eml, $smsg, $mids) = @_;
432 begin_txn_lazy($self);
433 my $merge_vmd = delete $smsg->{-merge_vmd};
434 my $doc = eml2doc($self, $eml, $smsg, $mids);
435 if (my $old = $merge_vmd ? _get_doc($self, $smsg->{num}) : undef) {
437 while (my ($field, $pfx) = splice(@x, 0, 2)) {
438 my $vals = xap_terms($pfx, $old);
439 $doc->add_boolean_term($pfx.$_) for keys %$vals;
442 $self->{xdb}->replace_document($smsg->{num}, $doc);
445 sub _msgmap_init ($) {
447 die "BUG: _msgmap_init is only for v1\n" if $self->{ibx}->version != 1;
448 $self->{mm} //= eval {
449 require PublicInbox::Msgmap;
450 my $rw = $self->{ibx}->{-no_fsync} ? 2 : 1;
451 PublicInbox::Msgmap->new($self->{ibx}->{inboxdir}, $rw);
456 # mime = PublicInbox::Eml or Email::MIME object
457 my ($self, $mime, $smsg, $sync) = @_;
458 begin_txn_lazy($self);
459 my $mids = mids_for_index($mime);
460 $smsg //= bless { blob => '' }, 'PublicInbox::Smsg'; # test-only compat
461 $smsg->{mid} //= $mids->[0]; # v1 compatibility
462 $smsg->{num} //= do { # v1
464 index_mm($self, $mime, $smsg->{blob}, $sync);
468 $smsg->populate($mime, $sync);
469 $smsg->{bytes} //= length($mime->as_string);
472 # order matters, overview stores every possible piece of
473 # data in doc_data (deflated). Xapian only stores a subset
474 # of the fields which exist in over.sqlite3. We may stop
475 # storing doc_data in Xapian sometime after we get multi-inbox
477 if (my $oidx = $self->{oidx}) { # v1 only
478 $oidx->add_overview($mime, $smsg);
480 if (need_xapian($self)) {
481 add_xapian($self, $mime, $smsg, $mids);
486 warn "failed to index message <".join('> <',@$mids).">: $@\n";
493 my ($self, $docid) = @_;
494 my $doc = eval { $self->{xdb}->get_document($docid) };
496 warn "E: $@\n" if $@;
497 warn "E: #$docid missing in Xapian\n";
503 my ($self, $docid, $eidx_key, $eml) = @_;
504 begin_txn_lazy($self);
505 my $doc = _get_doc($self, $docid) or return;
506 term_generator($self)->set_document($doc);
508 # '.' is special for lei_store
509 $doc->add_boolean_term('O'.$eidx_key) if $eidx_key ne '.';
511 index_list_id($self, $doc, $eml);
512 $self->{xdb}->replace_document($docid, $doc);
515 sub remove_eidx_info {
516 my ($self, $docid, $eidx_key, $eml) = @_;
517 begin_txn_lazy($self);
518 my $doc = _get_doc($self, $docid) or return;
519 eval { $doc->remove_term('O'.$eidx_key) };
520 warn "W: ->remove_term O$eidx_key: $@\n" if $@;
521 for my $l ($eml ? $eml->header_raw('List-Id') : ()) {
522 $l =~ /<([^>]+)>/ or next;
524 eval { $doc->remove_term('G' . $lid) };
525 warn "W: ->remove_term G$lid: $@\n" if $@;
527 # nb: we don't remove the XL probabilistic terms
528 # since terms may overlap if cross-posted.
530 # IOW, a message which has both <foo.example.com>
531 # and <bar.example.com> would have overlapping
532 # "XLexample" and "XLcom" as terms and which we
533 # wouldn't know if they're safe to remove if we just
534 # unindex <foo.example.com> while preserving
537 # In any case, this entire sub is will likely never
538 # be needed and users using the "l:" prefix are probably
541 $self->{xdb}->replace_document($docid, $doc);
545 my ($self, $docid, $vmd) = @_;
546 begin_txn_lazy($self);
547 my $doc = _get_doc($self, $docid) or return;
548 my ($end, @rm, @add);
550 while (my ($field, $pfx) = splice(@x, 0, 2)) {
551 my $set = $vmd->{$field} // next;
552 my %keep = map { $_ => 1 } @$set;
554 $end //= $doc->termlist_end;
555 for (my $cur = $doc->termlist_begin; $cur != $end; $cur++) {
557 last if $cur == $end;
558 my $v = $cur->get_termname;
559 $v =~ s/\A$pfx//s or next;
560 $keep{$v} ? delete($add{$v}) : push(@rm, $pfx.$v);
562 push(@add, map { $pfx.$_ } keys %add);
564 return unless scalar(@rm) || scalar(@add);
565 $doc->remove_term($_) for @rm;
566 $doc->add_boolean_term($_) for @add;
567 $self->{xdb}->replace_document($docid, $doc);
570 sub apply_vmd_mod ($$) {
571 my ($doc, $vmd_mod) = @_;
574 while (my ($field, $pfx) = splice(@x, 0, 2)) {
575 # field: "label" or "kw"
576 for my $val (@{$vmd_mod->{"-$field"} // []}) {
578 $doc->remove_term($pfx . $val);
582 for my $val (@{$vmd_mod->{"+$field"} // []}) {
583 $doc->add_boolean_term($pfx . $val);
591 my ($self, $docid, $vmd) = @_;
592 begin_txn_lazy($self);
593 my $doc = _get_doc($self, $docid) or return;
596 while (my ($field, $pfx) = splice(@x, 0, 2)) {
597 my $add = $vmd->{$field} // next;
598 $doc->add_boolean_term($pfx . $_) for @$add;
599 $updated += scalar(@$add);
601 $updated += apply_vmd_mod($doc, $vmd);
602 $self->{xdb}->replace_document($docid, $doc) if $updated;
606 my ($self, $docid, $vmd) = @_;
607 begin_txn_lazy($self);
608 my $doc = _get_doc($self, $docid) or return;
611 while (my ($field, $pfx) = splice(@x, 0, 2)) {
612 my $rm = $vmd->{$field} // next;
615 $doc->remove_term($pfx . $_);
620 $self->{xdb}->replace_document($docid, $doc) if $replace;
624 my ($self, $docid, $vmd_mod) = @_;
625 begin_txn_lazy($self);
626 my $doc = _get_doc($self, $docid) or return;
627 my $updated = apply_vmd_mod($doc, $vmd_mod);
628 $self->{xdb}->replace_document($docid, $doc) if $updated;
633 my ($self, @docids) = @_;
634 $self->begin_txn_lazy;
635 my $xdb = $self->{xdb} or return;
636 for my $docid (@docids) {
637 eval { $xdb->delete_document($docid) };
638 warn "E: #$docid not in in Xapian? $@\n" if $@;
642 sub index_git_blob_id {
643 my ($doc, $pfx, $objid) = @_;
645 my $len = length($objid);
646 for (my $len = length($objid); $len >= 7; ) {
647 $doc->add_term($pfx.$objid);
648 $objid = substr($objid, 0, --$len);
654 my ($self, $oid, $eml) = @_;
655 my $mids = mids($eml);
658 for my $mid (@$mids) {
659 my @removed = $self->{oidx}->remove_oid($oid, $mid);
660 $nr += scalar @removed;
661 $tmp{$_}++ for @removed;
664 my $m = join('> <', @$mids);
665 warn "W: <$m> missing for removal from overview\n";
667 while (my ($num, $nr) = each %tmp) {
668 warn "BUG: $num appears >1 times ($nr) for $oid\n" if $nr != 1;
671 $self->{mm}->num_delete($_) for (keys %tmp);
672 } else { # just in case msgmap and over.sqlite3 become desynched:
673 $self->{mm}->mid_delete($mids->[0]);
675 xdb_remove($self, keys %tmp) if need_xapian($self);
679 my ($self, $mime, $oid, $sync) = @_;
680 my $mids = mids($mime);
681 my $mm = $self->{mm};
682 if ($sync->{reindex}) {
683 my $oidx = $self->{oidx};
684 for my $mid (@$mids) {
685 my ($num, undef) = $oidx->num_mid0_for_oid($oid, $mid);
686 return $num if defined $num;
688 $mm->num_for($mids->[0]) // $mm->mid_insert($mids->[0]);
690 # fallback to num_for since filters like RubyLang set the number
691 $mm->mid_insert($mids->[0]) // $mm->num_for($mids->[0]);
695 sub is_bad_blob ($$$$) {
696 my ($oid, $type, $size, $expect_oid) = @_;
697 if ($type ne 'blob') {
698 carp "W: $expect_oid is not a blob (type=$type)";
701 croak "BUG: $oid != $expect_oid" if $oid ne $expect_oid;
702 $size == 0 ? 1 : 0; # size == 0 means purged
705 sub index_both { # git->cat_async callback
706 my ($bref, $oid, $type, $size, $sync) = @_;
707 return if is_bad_blob($oid, $type, $size, $sync->{oid});
708 my ($nr, $max) = @$sync{qw(nr max)};
711 my $smsg = bless { blob => $oid }, 'PublicInbox::Smsg';
712 $smsg->set_bytes($$bref, $size);
713 my $self = $sync->{sidx};
714 local $self->{current_info} = "$self->{current_info}: $oid";
715 my $eml = PublicInbox::Eml->new($bref);
716 $smsg->{num} = index_mm($self, $eml, $oid, $sync) or
717 die "E: could not generate NNTP article number for $oid";
718 add_message($self, $eml, $smsg, $sync);
720 my $cur_cmt = $sync->{cur_cmt} // die 'BUG: {cur_cmt} missing';
721 ${$sync->{latest_cmt}} = $cur_cmt;
724 sub unindex_both { # git->cat_async callback
725 my ($bref, $oid, $type, $size, $sync) = @_;
726 return if is_bad_blob($oid, $type, $size, $sync->{oid});
727 my $self = $sync->{sidx};
728 local $self->{current_info} = "$self->{current_info}: $oid";
729 unindex_eml($self, $oid, PublicInbox::Eml->new($bref));
730 # may be undef if leftover
731 if (defined(my $cur_cmt = $sync->{cur_cmt})) {
732 ${$sync->{latest_cmt}} = $cur_cmt;
739 ($self->{ibx} // $self->{eidx})->with_umask(@_);
742 # called by public-inbox-index
744 my ($self, $opt) = @_;
745 delete $self->{lock_path} if $opt->{-skip_lock};
746 $self->with_umask(\&_index_sync, $self, $opt);
747 if ($opt->{reindex} && !$opt->{quit}) {
749 delete @again{qw(rethread reindex)};
750 index_sync($self, \%again);
751 $opt->{quit} = $again{quit}; # propagate to caller
755 sub check_size { # check_async cb for -index --max-size=...
756 my ($oid, $type, $size, $arg, $git) = @_;
757 (($type // '') eq 'blob') or die "E: bad $oid in $git->{git_dir}";
758 if ($size <= $arg->{max_size}) {
759 $git->cat_async($oid, $arg->{index_oid}, $arg);
761 warn "W: skipping $oid ($size > $arg->{max_size})\n";
765 sub v1_checkpoint ($$;$) {
766 my ($self, $sync, $stk) = @_;
767 $self->{ibx}->git->async_wait_all;
769 # $newest may be undef
770 my $newest = $stk ? $stk->{latest_cmt} : ${$sync->{latest_cmt}};
771 if (defined($newest)) {
772 my $cur = $self->{mm}->last_commit || '';
773 if (need_update($self, $cur, $newest)) {
774 $self->{mm}->last_commit($newest);
777 ${$sync->{max}} = $self->{batch_bytes};
779 $self->{mm}->{dbh}->commit;
780 my $xdb = need_xapian($self) ? $self->{xdb} : undef;
781 if ($newest && $xdb) {
782 my $cur = $xdb->get_metadata('last_commit');
783 if (need_update($self, $cur, $newest)) {
784 $xdb->set_metadata('last_commit', $newest);
787 if ($stk) { # all done if $stk is passed
788 # let SearchView know a full --reindex was done so it can
789 # generate ->has_threadid-dependent links
790 if ($xdb && $sync->{reindex} && !ref($sync->{reindex})) {
791 my $n = $xdb->get_metadata('has_threadid');
792 $xdb->set_metadata('has_threadid', '1') if $n ne '1';
794 $self->{oidx}->rethread_done($sync->{-opt}); # all done
796 commit_txn_lazy($self);
797 $sync->{ibx}->git->cleanup;
798 my $nr = ${$sync->{nr}};
799 idx_release($self, $nr);
800 # let another process do some work...
801 if (my $pr = $sync->{-opt}->{-progress}) {
802 $pr->("indexed $nr/$sync->{ntodo}\n") if $nr;
804 if (!$stk && !$sync->{quit}) { # more to come
805 begin_txn_lazy($self);
806 $self->{mm}->{dbh}->begin_work;
812 my ($self, $sync, $stk) = @_;
813 my $git = $sync->{ibx}->git;
814 my $max = $self->{batch_bytes};
817 $sync->{max} = \$max;
818 $sync->{sidx} = $self;
819 $sync->{latest_cmt} = \(my $latest_cmt);
821 $self->{mm}->{dbh}->begin_work;
822 if (my @leftovers = keys %{delete($sync->{D}) // {}}) {
823 warn('W: unindexing '.scalar(@leftovers)." leftovers\n");
824 for my $oid (@leftovers) {
825 last if $sync->{quit};
826 $oid = unpack('H*', $oid);
827 $git->cat_async($oid, \&unindex_both, $sync);
830 if ($sync->{max_size} = $sync->{-opt}->{max_size}) {
831 $sync->{index_oid} = \&index_both;
833 while (my ($f, $at, $ct, $oid, $cur_cmt) = $stk->pop_rec) {
834 my $arg = { %$sync, cur_cmt => $cur_cmt, oid => $oid };
835 last if $sync->{quit};
837 $arg->{autime} = $at;
838 $arg->{cotime} = $ct;
839 if ($sync->{max_size}) {
840 $git->check_async($oid, \&check_size, $arg);
842 $git->cat_async($oid, \&index_both, $arg);
844 v1_checkpoint($self, $sync) if $max <= 0;
845 } elsif ($f eq 'd') {
846 $git->cat_async($oid, \&unindex_both, $arg);
849 v1_checkpoint($self, $sync, $sync->{quit} ? undef : $stk);
852 sub log2stack ($$$) {
853 my ($sync, $git, $range) = @_;
854 my $D = $sync->{D}; # OID_BIN => NR (if reindexing, undef otherwise)
856 if ($sync->{ibx}->version == 1) {
857 my $path = $hex.'{2}/'.$hex.'{38}';
858 $add = qr!\A:000000 100644 \S+ ($OID) A\t$path$!;
859 $del = qr!\A:100644 000000 ($OID) \S+ D\t$path$!;
861 $del = qr!\A:\d{6} 100644 $OID ($OID) [AM]\td$!;
862 $add = qr!\A:\d{6} 100644 $OID ($OID) [AM]\tm$!;
865 # Count the new files so they can be added newest to oldest
866 # and still have numbers increasing from oldest to newest
867 my $fh = $git->popen(qw(log --raw -r --pretty=tformat:%at-%ct-%H
868 --no-notes --no-color --no-renames --no-abbrev),
870 my ($at, $ct, $stk, $cmt);
872 return if $sync->{quit};
873 if (/\A([0-9]+)-([0-9]+)-($OID)$/o) {
874 ($at, $ct, $cmt) = ($1 + 0, $2 + 0, $3);
875 $stk //= PublicInbox::IdxStack->new($cmt);
878 if ($D) { # reindex case
879 $D->{pack('H*', $oid)}++;
880 } else { # non-reindex case:
881 $stk->push_rec('d', $at, $ct, $oid, $cmt);
886 my $oid_bin = pack('H*', $oid);
887 my $nr = --$D->{$oid_bin};
888 delete($D->{$oid_bin}) if $nr <= 0;
889 # nr < 0 (-1) means it never existed
892 $stk->push_rec('m', $at, $ct, $oid, $cmt);
895 close $fh or die "git log failed: \$?=$?";
896 $stk //= PublicInbox::IdxStack->new;
900 sub prepare_stack ($$) {
901 my ($sync, $range) = @_;
902 my $git = $sync->{ibx}->git;
904 if (index($range, '..') < 0) {
905 # don't show annoying git errors to users who run -index
907 $git->qx(qw(rev-parse -q --verify), "$range^0");
908 return PublicInbox::IdxStack->new->read_prepare if $?;
910 $sync->{D} = $sync->{reindex} ? {} : undef; # OID_BIN => NR
911 log2stack($sync, $git, $range);
914 # --is-ancestor requires git 1.8.0+
915 sub is_ancestor ($$$) {
916 my ($git, $cur, $tip) = @_;
917 return 0 unless $git->check($cur);
918 my $cmd = [ 'git', "--git-dir=$git->{git_dir}",
919 qw(merge-base --is-ancestor), $cur, $tip ];
920 my $pid = spawn($cmd);
921 waitpid($pid, 0) == $pid or die join(' ', @$cmd) .' did not finish';
925 sub need_update ($$$) {
926 my ($self, $cur, $new) = @_;
927 my $git = $self->{ibx}->git;
928 return 1 if $cur && !is_ancestor($git, $cur, $new);
929 my $range = $cur eq '' ? $new : "$cur..$new";
930 chomp(my $n = $git->qx(qw(rev-list --count), $range));
931 ($n eq '' || $n > 0);
934 # The last git commit we indexed with Xapian or SQLite (msgmap)
935 # This needs to account for cases where Xapian or SQLite is
936 # out-of-date with respect to the other.
938 my ($self, $mm) = @_;
939 my $lm = $mm->last_commit || '';
941 if (need_xapian($self)) {
942 $lx = $self->{xdb}->get_metadata('last_commit') || '';
946 # Use last_commit from msgmap if it is older or unset
947 if (!$lm || ($lx && $lm && is_ancestor($self->{ibx}->git, $lm, $lx))) {
953 sub reindex_from ($$) {
954 my ($reindex, $last_commit) = @_;
955 return $last_commit unless $reindex;
956 ref($reindex) eq 'HASH' ? $reindex->{from} : '';
962 # we set {-opt}->{quit} too, so ->index_sync callers
963 # can abort multi-inbox loops this way
964 $sync->{quit} = $sync->{-opt}->{quit} = 1;
965 warn "gracefully quitting\n";
969 # indexes all unindexed messages (v1 only)
971 my ($self, $opt) = @_;
972 my $tip = $opt->{ref} || 'HEAD';
973 my $ibx = $self->{ibx};
974 local $self->{current_info} = "$ibx->{inboxdir}";
975 $self->{batch_bytes} = $opt->{batch_size} // $BATCH_BYTES;
976 $ibx->git->batch_prepare;
977 my $pr = $opt->{-progress};
978 my $sync = { reindex => $opt->{reindex}, -opt => $opt, ibx => $ibx };
979 my $quit = quit_cb($sync);
980 local $SIG{QUIT} = $quit;
981 local $SIG{INT} = $quit;
982 local $SIG{TERM} = $quit;
983 my $xdb = $self->begin_txn_lazy;
984 $self->{oidx}->rethread_prepare($opt);
985 my $mm = _msgmap_init($self);
986 if ($sync->{reindex}) {
987 my $last = $mm->last_commit;
991 # somebody just blindly added --reindex when indexing
992 # for the first time, allow it:
993 undef $sync->{reindex};
996 my $last_commit = _last_x_commit($self, $mm);
997 my $lx = reindex_from($sync->{reindex}, $last_commit);
998 my $range = $lx eq '' ? $tip : "$lx..$tip";
999 $pr->("counting changes\n\t$range ... ") if $pr;
1000 my $stk = prepare_stack($sync, $range);
1001 $sync->{ntodo} = $stk ? $stk->num_records : 0;
1002 $pr->("$sync->{ntodo}\n") if $pr; # continue previous line
1003 process_stack($self, $sync, $stk) if !$sync->{quit};
1007 # order matters for unlocking
1008 $_[0]->{xdb} = undef;
1009 $_[0]->{lockfh} = undef;
1014 my $xdb = $self->{xdb} || idx_acquire($self);
1015 $self->{oidx}->begin_lazy if $self->{oidx};
1016 $xdb->begin_transaction if $xdb;
1021 sub begin_txn_lazy {
1023 $self->with_umask(\&_begin_txn, $self) if !$self->{txn};
1026 # store 'indexlevel=medium' in v2 shard=0 and v1 (only one shard)
1027 # This metadata is read by Admin::detect_indexlevel:
1028 sub set_metadata_once {
1031 return if $self->{shard}; # only continue if undef or 0, not >0
1032 my $xdb = $self->{xdb};
1034 if (delete($self->{-set_has_threadid_once})) {
1035 $xdb->set_metadata('has_threadid', '1');
1037 if (delete($self->{-set_indexlevel_once})) {
1038 my $level = $xdb->get_metadata('indexlevel');
1039 if (!$level || $level ne 'medium') {
1040 $xdb->set_metadata('indexlevel', 'medium');
1043 if (delete($self->{-set_skip_docdata_once})) {
1044 $xdb->get_metadata('skip_docdata') or
1045 $xdb->set_metadata('skip_docdata', '1');
1051 if (my $eidx = $self->{eidx}) {
1052 $eidx->git->async_wait_all;
1053 $eidx->{transact_bytes} = 0;
1055 if (my $xdb = $self->{xdb}) {
1056 set_metadata_once($self);
1057 $xdb->commit_transaction;
1059 $self->{oidx}->commit_lazy if $self->{oidx};
1062 sub commit_txn_lazy {
1064 delete($self->{txn}) and
1065 $self->with_umask(\&_commit_txn, $self);
1068 sub eidx_shard_new {
1069 my ($class, $eidx, $shard) = @_;
1072 xpfx => $eidx->{xpfx},
1073 indexlevel => $eidx->{indexlevel},
1078 $self->{-set_indexlevel_once} = 1 if $self->{indexlevel} eq 'medium';
1082 # ensure there's no stale Xapian docs by treating $over as canonical
1084 my ($self, $over) = @_;
1085 begin_txn_lazy($self);
1086 my $sth = $over->dbh->prepare(<<'');
1087 SELECT COUNT(*) FROM over WHERE num = ?
1089 my $xdb = $self->{xdb};
1090 my $cur = $xdb->postlist_begin('');
1091 my $end = $xdb->postlist_end('');
1092 my $xdir = $self->xdir;
1093 for (; $cur != $end; $cur++) {
1094 my $docid = $cur->get_docid;
1095 $sth->execute($docid);
1096 my $x = $sth->fetchrow_array;
1098 warn "I: removing $xdir #$docid, not in `over'\n";
1099 $xdb->delete_document($docid);