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 or flags
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;
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);
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);
59 xpfx => $inboxdir, # for xpfx_init
62 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;
72 $self->{lock_path} = "$inboxdir/ssoma.lock";
73 my $dir = $self->xdir;
74 $self->{oidx} = PublicInbox::OverIdx->new("$dir/over.sqlite3");
75 $self->{oidx}->{-no_fsync} = 1 if $ibx->{-no_fsync};
76 } elsif ($version == 2) {
77 defined $shard or die "shard is required for v2\n";
79 $self->{shard} = $shard;
80 $self->{lock_path} = undef;
82 die "unsupported inbox version=$version\n";
84 $self->{creat} = ($creat || 0) == 1;
88 sub need_xapian ($) { $_[0]->{indexlevel} =~ $xapianlevels }
91 my ($self, $wake) = @_;
92 if (need_xapian($self)) {
93 my $xdb = delete $self->{xdb} or croak 'not acquired';
96 $self->lock_release($wake) if $self->{creat};
100 sub load_xapian_writable () {
101 return 1 if $X->{WritableDatabase};
102 PublicInbox::Search::load_xapian() or return;
103 my $xap = $PublicInbox::Search::Xap;
104 for (qw(Document TermGenerator WritableDatabase)) {
105 $X->{$_} = $xap.'::'.$_;
107 eval 'require '.$X->{WritableDatabase} or die;
108 *sortable_serialise = $xap.'::sortable_serialise';
109 *sortable_unserialise = $xap.'::sortable_unserialise';
110 $DB_CREATE_OR_OPEN = eval($xap.'::DB_CREATE_OR_OPEN()');
111 $DB_OPEN = eval($xap.'::DB_OPEN()');
112 my $ver = (eval($xap.'::major_version()') << 16) |
113 (eval($xap.'::minor_version()') << 8);
114 $DB_NO_SYNC = 0x4 if $ver >= 0x10400;
121 my $dir = $self->xdir;
122 if (need_xapian($self)) {
123 croak 'already acquired' if $self->{xdb};
124 load_xapian_writable();
125 $flag = $self->{creat} ? $DB_CREATE_OR_OPEN : $DB_OPEN;
127 if ($self->{creat}) {
131 # don't create empty Xapian directories if we don't need Xapian
132 my $is_shard = defined($self->{shard});
133 if (!-d $dir && (!$is_shard ||
134 ($is_shard && need_xapian($self)))) {
135 File::Path::mkpath($dir);
137 $self->{-set_has_threadid_once} = 1;
140 return unless defined $flag;
141 $flag |= $DB_NO_SYNC if ($self->{ibx} // $self->{eidx})->{-no_fsync};
142 my $xdb = eval { ($X->{WritableDatabase})->new($dir, $flag) };
143 croak "Failed opening $dir: $@" if $@;
148 my ($doc, $col, $num) = @_;
149 $num = sortable_serialise($num);
150 $doc->add_value($col, $num);
153 sub term_generator ($) { # write-only
156 $self->{term_generator} //= do {
157 my $tg = $X->{TermGenerator}->new;
158 $tg->set_stemmer(PublicInbox::Search::stemmer($self));
163 sub index_text ($$$$) {
164 my ($self, $text, $wdf_inc, $prefix) = @_;
165 my $tg = term_generator($self); # man Search::Xapian::TermGenerator
167 if ($self->{indexlevel} eq 'full') {
168 $tg->index_text($text, $wdf_inc, $prefix);
169 $tg->increase_termpos;
171 $tg->index_text_without_positions($text, $wdf_inc, $prefix);
175 sub index_headers ($$) {
176 my ($self, $smsg) = @_;
177 my @x = (from => 'A', # Author
178 subject => 'S', to => 'XTO', cc => 'XCC');
179 while (my ($field, $pfx) = splice(@x, 0, 2)) {
180 my $val = $smsg->{$field};
181 index_text($self, $val, 1, $pfx) if $val ne '';
185 sub index_diff_inc ($$$$) {
186 my ($self, $text, $pfx, $xnq) = @_;
188 index_text($self, join("\n", @$xnq), 1, 'XNQ');
191 index_text($self, $text, 1, $pfx);
194 sub index_old_diff_fn {
195 my ($self, $seen, $fa, $fb, $xnq) = @_;
197 # no renames or space support for traditional diffs,
198 # find the number of leading common paths to strip:
199 my @fa = split('/', $fa);
200 my @fb = split('/', $fb);
201 while (scalar(@fa) && scalar(@fb)) {
202 $fa = join('/', @fa);
203 $fb = join('/', @fb);
205 unless ($seen->{$fa}++) {
206 index_diff_inc($self, $fa, 'XDFN', $xnq);
216 sub index_diff ($$$) {
217 my ($self, $txt, $doc) = @_;
222 foreach (split(/\n/, $txt)) {
223 if ($in_diff && s/^ //) { # diff context
224 index_diff_inc($self, $_, 'XDFCTX', $xnq);
225 } elsif (/^-- $/) { # email signature begins
227 } elsif (m!^diff --git "?[^/]+/.+ "?[^/]+/.+\z!) {
228 # wait until "---" and "+++" to capture filenames
231 } elsif (m/^diff -(.+) (\S+) (\S+)$/) {
232 my ($opt, $fa, $fb) = ($1, $2, $3);
234 # only support unified:
235 next unless $opt =~ /[uU]/;
236 $in_diff = index_old_diff_fn($self, \%seen, $fa, $fb,
238 } elsif (m!^--- ("?[^/]+/.+)!) {
240 $fn = (split('/', git_unquote($fn), 2))[1];
241 $seen{$fn}++ or index_diff_inc($self, $fn, 'XDFN', $xnq);
243 } elsif (m!^\+\+\+ ("?[^/]+/.+)!) {
245 $fn = (split('/', git_unquote($fn), 2))[1];
246 $seen{$fn}++ or index_diff_inc($self, $fn, 'XDFN', $xnq);
248 } elsif (/^--- (\S+)/) {
251 } elsif (defined $in_diff && /^\+\+\+ (\S+)/) {
252 $in_diff = index_old_diff_fn($self, \%seen, $in_diff,
254 } elsif ($in_diff && s/^\+//) { # diff added
255 index_diff_inc($self, $_, 'XDFB', $xnq);
256 } elsif ($in_diff && s/^-//) { # diff removed
257 index_diff_inc($self, $_, 'XDFA', $xnq);
258 } elsif (m!^index ([a-f0-9]+)\.\.([a-f0-9]+)!) {
259 my ($ba, $bb) = ($1, $2);
260 index_git_blob_id($doc, 'XDFPRE', $ba);
261 index_git_blob_id($doc, 'XDFPOST', $bb);
263 } elsif (/^@@ (?:\S+) (?:\S+) @@\s*$/) {
264 # traditional diff w/o -p
265 } elsif (/^@@ (?:\S+) (?:\S+) @@\s*(\S+.*)$/) {
266 # hunk header context
267 index_diff_inc($self, $1, 'XDFHH', $xnq);
268 # ignore the following lines:
269 } elsif (/^(?:dis)similarity index/ ||
270 /^(?:old|new) mode/ ||
271 /^(?:deleted|new) file mode/ ||
272 /^(?:copy|rename) (?:from|to) / ||
273 /^(?:dis)?similarity index / ||
274 /^\\ No newline at end of file/ ||
275 /^Binary files .* differ/) {
278 # possible to be in diff context, some mail may be
279 # stripped by MUA or even GNU diff(1). "git apply"
280 # treats a bare "\n" as diff context, too
283 warn "non-diff line: $_\n" if DEBUG && $_ ne '';
288 index_text($self, join("\n", @xnq), 1, 'XNQ');
291 sub index_xapian { # msg_iter callback
292 my $part = $_[0]->[0]; # ignore $depth and $idx
293 my ($self, $doc) = @{$_[1]};
294 my $ct = $part->content_type || 'text/plain';
295 my $fn = $part->filename;
296 if (defined $fn && $fn ne '') {
297 index_text($self, $fn, 1, 'XFN');
299 if ($part->{is_submsg}) {
300 my $mids = mids_for_index($part);
301 index_ids($self, $doc, $part, $mids);
302 my $smsg = bless {}, 'PublicInbox::Smsg';
303 $smsg->populate($part);
304 index_headers($self, $smsg);
307 my ($s, undef) = msg_part_text($part, $ct);
308 defined $s or return;
309 $_[0]->[0] = $part = undef; # free memory
311 # split off quoted and unquoted blocks:
312 my @sections = PublicInbox::MsgIter::split_quotes($s);
313 undef $s; # free memory
314 for my $txt (@sections) {
316 index_text($self, $txt, 0, 'XQUOT');
318 # does it look like a diff?
319 if ($txt =~ /^(?:diff|---|\+\+\+) /ms) {
320 index_diff($self, $txt, $doc);
322 index_text($self, $txt, 1, 'XNQ');
325 undef $txt; # free memory
329 sub index_list_id ($$$) {
330 my ($self, $doc, $hdr) = @_;
331 for my $l ($hdr->header_raw('List-Id')) {
332 $l =~ /<([^>]+)>/ or next;
334 $doc->add_boolean_term('G' . $lid);
335 index_text($self, $lid, 1, 'XL'); # probabilistic
339 sub index_ids ($$$$) {
340 my ($self, $doc, $hdr, $mids) = @_;
341 for my $mid (@$mids) {
342 index_text($self, $mid, 1, 'XM');
344 # because too many Message-IDs are prefixed with
346 if ($mid =~ /\w{12,}/) {
347 my @long = ($mid =~ /(\w{3,}+)/g);
348 index_text($self, join(' ', @long), 1, 'XM');
351 $doc->add_boolean_term('Q' . $_) for @$mids;
352 index_list_id($self, $doc, $hdr);
355 sub add_xapian ($$$$) {
356 my ($self, $eml, $smsg, $mids) = @_;
357 my $doc = $X->{Document}->new;
358 add_val($doc, PublicInbox::Search::TS(), $smsg->{ts});
359 my @ds = gmtime($smsg->{ds});
360 my $yyyymmdd = strftime('%Y%m%d', @ds);
361 add_val($doc, PublicInbox::Search::YYYYMMDD(), $yyyymmdd);
362 my $dt = strftime('%Y%m%d%H%M%S', @ds);
363 add_val($doc, PublicInbox::Search::DT(), $dt);
364 add_val($doc, PublicInbox::Search::BYTES(), $smsg->{bytes});
365 add_val($doc, PublicInbox::Search::UID(), $smsg->{num});
366 add_val($doc, PublicInbox::Search::THREADID, $smsg->{tid});
368 my $tg = term_generator($self);
369 $tg->set_document($doc);
370 index_headers($self, $smsg);
372 if (defined(my $eidx_key = $smsg->{eidx_key})) {
373 $doc->add_boolean_term('O'.$eidx_key);
375 msg_iter($eml, \&index_xapian, [ $self, $doc ]);
376 index_ids($self, $doc, $eml, $mids);
378 # by default, we maintain compatibility with v1.5.0 and earlier
379 # by writing to docdata.glass, users who never exect to downgrade can
381 if (!$self->{-skip_docdata}) {
382 # WWW doesn't need {to} or {cc}, only NNTP
383 $smsg->{to} = $smsg->{cc} = '';
384 PublicInbox::OverIdx::parse_references($smsg, $eml, $mids);
385 my $data = $smsg->to_doc_data;
386 $doc->set_data($data);
389 if (my $altid = $self->{-altid}) {
390 foreach my $alt (@$altid) {
391 my $pfx = $alt->{xprefix};
392 foreach my $mid (@$mids) {
393 my $id = $alt->mid2alt($mid);
394 next unless defined $id;
395 $doc->add_boolean_term($pfx . $id);
399 $self->{xdb}->replace_document($smsg->{num}, $doc);
402 sub _msgmap_init ($) {
404 die "BUG: _msgmap_init is only for v1\n" if $self->{ibx_ver} != 1;
405 $self->{mm} //= eval {
406 require PublicInbox::Msgmap;
407 my $rw = $self->{ibx}->{-no_fsync} ? 2 : 1;
408 PublicInbox::Msgmap->new($self->{ibx}->{inboxdir}, $rw);
413 # mime = PublicInbox::Eml or Email::MIME object
414 my ($self, $mime, $smsg, $sync) = @_;
415 my $mids = mids_for_index($mime);
416 $smsg //= bless { blob => '' }, 'PublicInbox::Smsg'; # test-only compat
417 $smsg->{mid} //= $mids->[0]; # v1 compatibility
418 $smsg->{num} //= do { # v1
420 index_mm($self, $mime, $smsg->{blob}, $sync);
424 $smsg->populate($mime, $sync);
425 $smsg->{bytes} //= length($mime->as_string);
428 # order matters, overview stores every possible piece of
429 # data in doc_data (deflated). Xapian only stores a subset
430 # of the fields which exist in over.sqlite3. We may stop
431 # storing doc_data in Xapian sometime after we get multi-inbox
433 if (my $oidx = $self->{oidx}) { # v1 only
434 $oidx->add_overview($mime, $smsg);
436 if (need_xapian($self)) {
437 add_xapian($self, $mime, $smsg, $mids);
442 warn "failed to index message <".join('> <',@$mids).">: $@\n";
449 my ($self, $docid, $oid) = @_;
450 my $doc = eval { $self->{xdb}->get_document($docid) };
452 warn "E: $@\n" if $@;
453 warn "E: #$docid $oid missing in Xapian\n";
459 my ($self, $docid, $oid, $eidx_key, $eml) = @_;
460 begin_txn_lazy($self);
461 my $doc = _get_doc($self, $docid, $oid) or return;
462 term_generator($self)->set_document($doc);
463 $doc->add_boolean_term('O'.$eidx_key);
464 index_list_id($self, $doc, $eml);
465 $self->{xdb}->replace_document($docid, $doc);
468 sub remove_eidx_info {
469 my ($self, $docid, $oid, $eidx_key, $eml) = @_;
470 begin_txn_lazy($self);
471 my $doc = _get_doc($self, $docid, $oid) or return;
472 eval { $doc->remove_term('O'.$eidx_key) };
473 warn "W: ->remove_term O$eidx_key: $@\n" if $@;
474 for my $l ($eml->header_raw('List-Id')) {
475 $l =~ /<([^>]+)>/ or next;
477 eval { $doc->remove_term('G' . $lid) };
478 warn "W: ->remove_term G$lid: $@\n" if $@;
480 # nb: we don't remove the XL probabilistic terms
481 # since terms may overlap if cross-posted.
483 # IOW, a message which has both <foo.example.com>
484 # and <bar.example.com> would have overlapping
485 # "XLexample" and "XLcom" as terms and which we
486 # wouldn't know if they're safe to remove if we just
487 # unindex <foo.example.com> while preserving
490 # In any case, this entire sub is will likely never
491 # be needed and users using the "l:" prefix are probably
494 $self->{xdb}->replace_document($docid, $doc);
498 my ($doc, $col) = @_;
499 sortable_unserialise($doc->get_value($col));
502 sub smsg_from_doc ($) {
504 my $data = $doc->get_data or return;
505 my $smsg = bless {}, 'PublicInbox::Smsg';
506 $smsg->{ts} = get_val($doc, PublicInbox::Search::TS());
507 my $dt = get_val($doc, PublicInbox::Search::DT());
508 my ($yyyy, $mon, $dd, $hh, $mm, $ss) = unpack('A4A2A2A2A2A2', $dt);
509 $smsg->{ds} = timegm($ss, $mm, $hh, $dd, $mon - 1, $yyyy);
510 $smsg->load_from_data($data);
515 my ($self, $oid, @removed) = @_;
516 my $xdb = $self->{xdb} or return;
517 for my $num (@removed) {
518 my $doc = _get_doc($self, $num, $oid) or next;
519 my $smsg = smsg_from_doc($doc);
520 my $blob = $smsg->{blob}; # may be undef if --skip-docdata
521 if (!defined($blob) || $blob eq $oid) {
522 $xdb->delete_document($num);
524 warn "E: #$num $oid != $blob in Xapian\n";
530 my ($self, $oid, $num) = @_;
531 die "BUG: remove_by_oid is v2-only\n" if $self->{oidx};
532 $self->begin_txn_lazy;
533 xdb_remove($self, $oid, $num) if need_xapian($self);
536 sub index_git_blob_id {
537 my ($doc, $pfx, $objid) = @_;
539 my $len = length($objid);
540 for (my $len = length($objid); $len >= 7; ) {
541 $doc->add_term($pfx.$objid);
542 $objid = substr($objid, 0, --$len);
548 my ($self, $oid, $eml) = @_;
549 my $mids = mids($eml);
552 for my $mid (@$mids) {
553 my @removed = $self->{oidx}->remove_oid($oid, $mid);
554 $nr += scalar @removed;
555 $tmp{$_}++ for @removed;
558 my $m = join('> <', @$mids);
559 warn "W: <$m> missing for removal from overview\n";
561 while (my ($num, $nr) = each %tmp) {
562 warn "BUG: $num appears >1 times ($nr) for $oid\n" if $nr != 1;
565 $self->{mm}->num_delete($_) for (keys %tmp);
566 } else { # just in case msgmap and over.sqlite3 become desynched:
567 $self->{mm}->mid_delete($mids->[0]);
569 xdb_remove($self, $oid, keys %tmp) if need_xapian($self);
573 my ($self, $mime, $oid, $sync) = @_;
574 my $mids = mids($mime);
575 my $mm = $self->{mm};
576 if ($sync->{reindex}) {
577 my $oidx = $self->{oidx};
578 for my $mid (@$mids) {
579 my ($num, undef) = $oidx->num_mid0_for_oid($oid, $mid);
580 return $num if defined $num;
582 $mm->num_for($mids->[0]) // $mm->mid_insert($mids->[0]);
584 # fallback to num_for since filters like RubyLang set the number
585 $mm->mid_insert($mids->[0]) // $mm->num_for($mids->[0]);
589 # returns the number of bytes to add if given a non-CRLF arg
590 sub crlf_adjust ($) {
591 if (index($_[0], "\r\n") < 0) {
592 # common case is LF-only, every \n needs an \r;
593 # so favor a cheap tr// over an expensive m//g
595 } else { # count number of '\n' w/o '\r', expensive:
596 scalar(my @n = ($_[0] =~ m/(?<!\r)\n/g));
600 sub index_both { # git->cat_async callback
601 my ($bref, $oid, $type, $size, $sync) = @_;
602 my ($nr, $max) = @$sync{qw(nr max)};
605 $size += crlf_adjust($$bref);
606 my $smsg = bless { bytes => $size, blob => $oid }, 'PublicInbox::Smsg';
607 my $self = $sync->{sidx};
608 my $eml = PublicInbox::Eml->new($bref);
609 $smsg->{num} = index_mm($self, $eml, $oid, $sync) or
610 die "E: could not generate NNTP article number for $oid";
611 add_message($self, $eml, $smsg, $sync);
612 my $cur_cmt = $sync->{cur_cmt} // die 'BUG: {cur_cmt} missing';
613 ${$sync->{latest_cmt}} = $cur_cmt;
616 sub unindex_both { # git->cat_async callback
617 my ($bref, $oid, $type, $size, $sync) = @_;
618 unindex_eml($sync->{sidx}, $oid, PublicInbox::Eml->new($bref));
619 # may be undef if leftover
620 if (defined(my $cur_cmt = $sync->{cur_cmt})) {
621 ${$sync->{latest_cmt}} = $cur_cmt;
627 ($self->{ibx} // $self->{eidx})->with_umask(@_);
630 # called by public-inbox-index
632 my ($self, $opt) = @_;
633 delete $self->{lock_path} if $opt->{-skip_lock};
634 $self->with_umask(\&_index_sync, $self, $opt);
635 if ($opt->{reindex} && !$opt->{quit}) {
637 delete @again{qw(rethread reindex)};
638 index_sync($self, \%again);
639 $opt->{quit} = $again{quit}; # propagate to caller
643 sub check_size { # check_async cb for -index --max-size=...
644 my ($oid, $type, $size, $arg, $git) = @_;
645 (($type // '') eq 'blob') or die "E: bad $oid in $git->{git_dir}";
646 if ($size <= $arg->{max_size}) {
647 $git->cat_async($oid, $arg->{index_oid}, $arg);
649 warn "W: skipping $oid ($size > $arg->{max_size})\n";
653 sub v1_checkpoint ($$;$) {
654 my ($self, $sync, $stk) = @_;
655 $self->{ibx}->git->async_wait_all;
657 # $newest may be undef
658 my $newest = $stk ? $stk->{latest_cmt} : ${$sync->{latest_cmt}};
659 if (defined($newest)) {
660 my $cur = $self->{mm}->last_commit || '';
661 if (need_update($self, $cur, $newest)) {
662 $self->{mm}->last_commit($newest);
665 ${$sync->{max}} = $self->{batch_bytes};
667 $self->{mm}->{dbh}->commit;
668 my $xdb = need_xapian($self) ? $self->{xdb} : undef;
669 if ($newest && $xdb) {
670 my $cur = $xdb->get_metadata('last_commit');
671 if (need_update($self, $cur, $newest)) {
672 $xdb->set_metadata('last_commit', $newest);
675 if ($stk) { # all done if $stk is passed
676 # let SearchView know a full --reindex was done so it can
677 # generate ->has_threadid-dependent links
678 if ($xdb && $sync->{reindex} && !ref($sync->{reindex})) {
679 my $n = $xdb->get_metadata('has_threadid');
680 $xdb->set_metadata('has_threadid', '1') if $n ne '1';
682 $self->{oidx}->rethread_done($sync->{-opt}); # all done
684 commit_txn_lazy($self);
685 $sync->{ibx}->git->cleanup;
686 my $nr = ${$sync->{nr}};
687 idx_release($self, $nr);
688 # let another process do some work...
689 if (my $pr = $sync->{-opt}->{-progress}) {
690 $pr->("indexed $nr/$sync->{ntodo}\n") if $nr;
692 if (!$stk && !$sync->{quit}) { # more to come
693 begin_txn_lazy($self);
694 $self->{mm}->{dbh}->begin_work;
700 my ($self, $sync, $stk) = @_;
701 my $git = $sync->{ibx}->git;
702 my $max = $self->{batch_bytes};
705 $sync->{max} = \$max;
706 $sync->{sidx} = $self;
707 $sync->{latest_cmt} = \(my $latest_cmt);
709 $self->{mm}->{dbh}->begin_work;
710 if (my @leftovers = keys %{delete($sync->{D}) // {}}) {
711 warn('W: unindexing '.scalar(@leftovers)." leftovers\n");
712 for my $oid (@leftovers) {
713 last if $sync->{quit};
714 $oid = unpack('H*', $oid);
715 $git->cat_async($oid, \&unindex_both, $sync);
718 if ($sync->{max_size} = $sync->{-opt}->{max_size}) {
719 $sync->{index_oid} = \&index_both;
721 while (my ($f, $at, $ct, $oid, $cur_cmt) = $stk->pop_rec) {
722 my $arg = { %$sync, cur_cmt => $cur_cmt };
723 last if $sync->{quit};
725 $arg->{autime} = $at;
726 $arg->{cotime} = $ct;
727 if ($sync->{max_size}) {
728 $git->check_async($oid, \&check_size, $arg);
730 $git->cat_async($oid, \&index_both, $arg);
732 v1_checkpoint($self, $sync) if $max <= 0;
733 } elsif ($f eq 'd') {
734 $git->cat_async($oid, \&unindex_both, $arg);
737 v1_checkpoint($self, $sync, $sync->{quit} ? undef : $stk);
740 sub log2stack ($$$) {
741 my ($sync, $git, $range) = @_;
742 my $D = $sync->{D}; # OID_BIN => NR (if reindexing, undef otherwise)
744 if ($sync->{ibx}->version == 1) {
745 my $path = $hex.'{2}/'.$hex.'{38}';
746 $add = qr!\A:000000 100644 \S+ ($OID) A\t$path$!;
747 $del = qr!\A:100644 000000 ($OID) \S+ D\t$path$!;
749 $del = qr!\A:\d{6} 100644 $OID ($OID) [AM]\td$!;
750 $add = qr!\A:\d{6} 100644 $OID ($OID) [AM]\tm$!;
753 # Count the new files so they can be added newest to oldest
754 # and still have numbers increasing from oldest to newest
755 my $fh = $git->popen(qw(log --raw -r --pretty=tformat:%at-%ct-%H
756 --no-notes --no-color --no-renames --no-abbrev),
758 my ($at, $ct, $stk, $cmt);
760 return if $sync->{quit};
761 if (/\A([0-9]+)-([0-9]+)-($OID)$/o) {
762 ($at, $ct, $cmt) = ($1 + 0, $2 + 0, $3);
763 $stk //= PublicInbox::IdxStack->new($cmt);
766 if ($D) { # reindex case
767 $D->{pack('H*', $oid)}++;
768 } else { # non-reindex case:
769 $stk->push_rec('d', $at, $ct, $oid, $cmt);
774 my $oid_bin = pack('H*', $oid);
775 my $nr = --$D->{$oid_bin};
776 delete($D->{$oid_bin}) if $nr <= 0;
777 # nr < 0 (-1) means it never existed
780 $stk->push_rec('m', $at, $ct, $oid, $cmt);
783 close $fh or die "git log failed: \$?=$?";
784 $stk //= PublicInbox::IdxStack->new;
788 sub prepare_stack ($$) {
789 my ($sync, $range) = @_;
790 my $git = $sync->{ibx}->git;
792 if (index($range, '..') < 0) {
793 # don't show annoying git errors to users who run -index
795 $git->qx(qw(rev-parse -q --verify), "$range^0");
796 return PublicInbox::IdxStack->new->read_prepare if $?;
798 $sync->{D} = $sync->{reindex} ? {} : undef; # OID_BIN => NR
799 log2stack($sync, $git, $range);
802 # --is-ancestor requires git 1.8.0+
803 sub is_ancestor ($$$) {
804 my ($git, $cur, $tip) = @_;
805 return 0 unless $git->check($cur);
806 my $cmd = [ 'git', "--git-dir=$git->{git_dir}",
807 qw(merge-base --is-ancestor), $cur, $tip ];
808 my $pid = spawn($cmd);
809 waitpid($pid, 0) == $pid or die join(' ', @$cmd) .' did not finish';
813 sub need_update ($$$) {
814 my ($self, $cur, $new) = @_;
815 my $git = $self->{ibx}->git;
816 return 1 if $cur && !is_ancestor($git, $cur, $new);
817 my $range = $cur eq '' ? $new : "$cur..$new";
818 chomp(my $n = $git->qx(qw(rev-list --count), $range));
819 ($n eq '' || $n > 0);
822 # The last git commit we indexed with Xapian or SQLite (msgmap)
823 # This needs to account for cases where Xapian or SQLite is
824 # out-of-date with respect to the other.
826 my ($self, $mm) = @_;
827 my $lm = $mm->last_commit || '';
829 if (need_xapian($self)) {
830 $lx = $self->{xdb}->get_metadata('last_commit') || '';
834 # Use last_commit from msgmap if it is older or unset
835 if (!$lm || ($lx && $lm && is_ancestor($self->{ibx}->git, $lm, $lx))) {
841 sub reindex_from ($$) {
842 my ($reindex, $last_commit) = @_;
843 return $last_commit unless $reindex;
844 ref($reindex) eq 'HASH' ? $reindex->{from} : '';
850 # we set {-opt}->{quit} too, so ->index_sync callers
851 # can abort multi-inbox loops this way
852 $sync->{quit} = $sync->{-opt}->{quit} = 1;
853 warn "gracefully quitting\n";
857 # indexes all unindexed messages (v1 only)
859 my ($self, $opt) = @_;
860 my $tip = $opt->{ref} || 'HEAD';
861 my $ibx = $self->{ibx};
862 $self->{batch_bytes} = $opt->{batch_size} // $BATCH_BYTES;
863 $ibx->git->batch_prepare;
864 my $pr = $opt->{-progress};
865 my $sync = { reindex => $opt->{reindex}, -opt => $opt, ibx => $ibx };
866 my $quit = quit_cb($sync);
867 local $SIG{QUIT} = $quit;
868 local $SIG{INT} = $quit;
869 local $SIG{TERM} = $quit;
870 my $xdb = $self->begin_txn_lazy;
871 $self->{oidx}->rethread_prepare($opt);
872 my $mm = _msgmap_init($self);
873 if ($sync->{reindex}) {
874 my $last = $mm->last_commit;
878 # somebody just blindly added --reindex when indexing
879 # for the first time, allow it:
880 undef $sync->{reindex};
883 my $last_commit = _last_x_commit($self, $mm);
884 my $lx = reindex_from($sync->{reindex}, $last_commit);
885 my $range = $lx eq '' ? $tip : "$lx..$tip";
886 $pr->("counting changes\n\t$range ... ") if $pr;
887 my $stk = prepare_stack($sync, $range);
888 $sync->{ntodo} = $stk ? $stk->num_records : 0;
889 $pr->("$sync->{ntodo}\n") if $pr; # continue previous line
890 process_stack($self, $sync, $stk) if !$sync->{quit};
894 # order matters for unlocking
895 $_[0]->{xdb} = undef;
896 $_[0]->{lockfh} = undef;
901 my $xdb = $self->{xdb} || idx_acquire($self);
902 $self->{oidx}->begin_lazy if $self->{oidx};
903 $xdb->begin_transaction if $xdb;
910 $self->with_umask(\&_begin_txn, $self) if !$self->{txn};
913 # store 'indexlevel=medium' in v2 shard=0 and v1 (only one shard)
914 # This metadata is read by Admin::detect_indexlevel:
915 sub set_metadata_once {
918 return if $self->{shard}; # only continue if undef or 0, not >0
919 my $xdb = $self->{xdb};
921 if (delete($self->{-set_has_threadid_once})) {
922 $xdb->set_metadata('has_threadid', '1');
924 if (delete($self->{-set_indexlevel_once})) {
925 my $level = $xdb->get_metadata('indexlevel');
926 if (!$level || $level ne 'medium') {
927 $xdb->set_metadata('indexlevel', 'medium');
930 if (delete($self->{-set_skip_docdata_once})) {
931 $xdb->get_metadata('skip_docdata') or
932 $xdb->set_metadata('skip_docdata', '1');
938 if (my $xdb = $self->{xdb}) {
939 set_metadata_once($self);
940 $xdb->commit_transaction;
942 $self->{oidx}->commit_lazy if $self->{oidx};
945 sub commit_txn_lazy {
947 delete($self->{txn}) and
948 $self->with_umask(\&_commit_txn, $self);
953 if (need_xapian($self)) {
954 die "$$ $0 xdb not released\n" if $self->{xdb};
956 die "$$ $0 still in transaction\n" if $self->{txn};
960 my ($class, $eidx, $shard) = @_;
963 xpfx => $eidx->{xpfx},
964 indexlevel => $eidx->{indexlevel},
969 $self->{-set_indexlevel_once} = 1 if $self->{indexlevel} eq 'medium';