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;
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);
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;
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 $DB_NO_SYNC = 0x4 if $ver >= 0x10400;
119 my $dir = $self->xdir;
120 if (need_xapian($self)) {
121 croak 'already acquired' if $self->{xdb};
122 load_xapian_writable();
123 $flag = $self->{creat} ? $DB_CREATE_OR_OPEN : $DB_OPEN;
125 if ($self->{creat}) {
129 # don't create empty Xapian directories if we don't need Xapian
130 my $is_shard = defined($self->{shard});
131 if (!-d $dir && (!$is_shard ||
132 ($is_shard && need_xapian($self)))) {
133 File::Path::mkpath($dir);
135 $self->{-set_has_threadid_once} = 1;
138 return unless defined $flag;
139 $flag |= $DB_NO_SYNC if ($self->{ibx} // $self->{eidx})->{-no_fsync};
140 my $xdb = eval { ($X->{WritableDatabase})->new($dir, $flag) };
141 croak "Failed opening $dir: $@" if $@;
146 my ($doc, $col, $num) = @_;
147 $num = sortable_serialise($num);
148 $doc->add_value($col, $num);
151 sub term_generator ($) { # write-only
154 $self->{term_generator} //= do {
155 my $tg = $X->{TermGenerator}->new;
156 $tg->set_stemmer(PublicInbox::Search::stemmer($self));
161 sub index_text ($$$$) {
162 my ($self, $text, $wdf_inc, $prefix) = @_;
163 my $tg = term_generator($self); # man Search::Xapian::TermGenerator
165 if ($self->{indexlevel} eq 'full') {
166 $tg->index_text($text, $wdf_inc, $prefix);
167 $tg->increase_termpos;
169 $tg->index_text_without_positions($text, $wdf_inc, $prefix);
173 sub index_headers ($$) {
174 my ($self, $smsg) = @_;
175 my @x = (from => 'A', # Author
176 subject => 'S', to => 'XTO', cc => 'XCC');
177 while (my ($field, $pfx) = splice(@x, 0, 2)) {
178 my $val = $smsg->{$field};
179 index_text($self, $val, 1, $pfx) if $val ne '';
183 sub index_diff_inc ($$$$) {
184 my ($self, $text, $pfx, $xnq) = @_;
186 index_text($self, join("\n", @$xnq), 1, 'XNQ');
189 index_text($self, $text, 1, $pfx);
192 sub index_old_diff_fn {
193 my ($self, $seen, $fa, $fb, $xnq) = @_;
195 # no renames or space support for traditional diffs,
196 # find the number of leading common paths to strip:
197 my @fa = split('/', $fa);
198 my @fb = split('/', $fb);
199 while (scalar(@fa) && scalar(@fb)) {
200 $fa = join('/', @fa);
201 $fb = join('/', @fb);
203 unless ($seen->{$fa}++) {
204 index_diff_inc($self, $fa, 'XDFN', $xnq);
214 sub index_diff ($$$) {
215 my ($self, $txt, $doc) = @_;
220 foreach (split(/\n/, $txt)) {
221 if ($in_diff && s/^ //) { # diff context
222 index_diff_inc($self, $_, 'XDFCTX', $xnq);
223 } elsif (/^-- $/) { # email signature begins
225 } elsif (m!^diff --git "?[^/]+/.+ "?[^/]+/.+\z!) {
226 # wait until "---" and "+++" to capture filenames
229 } elsif (m/^diff -(.+) (\S+) (\S+)$/) {
230 my ($opt, $fa, $fb) = ($1, $2, $3);
232 # only support unified:
233 next unless $opt =~ /[uU]/;
234 $in_diff = index_old_diff_fn($self, \%seen, $fa, $fb,
236 } elsif (m!^--- ("?[^/]+/.+)!) {
238 $fn = (split('/', git_unquote($fn), 2))[1];
239 $seen{$fn}++ or index_diff_inc($self, $fn, 'XDFN', $xnq);
241 } elsif (m!^\+\+\+ ("?[^/]+/.+)!) {
243 $fn = (split('/', git_unquote($fn), 2))[1];
244 $seen{$fn}++ or index_diff_inc($self, $fn, 'XDFN', $xnq);
246 } elsif (/^--- (\S+)/) {
249 } elsif (defined $in_diff && /^\+\+\+ (\S+)/) {
250 $in_diff = index_old_diff_fn($self, \%seen, $in_diff,
252 } elsif ($in_diff && s/^\+//) { # diff added
253 index_diff_inc($self, $_, 'XDFB', $xnq);
254 } elsif ($in_diff && s/^-//) { # diff removed
255 index_diff_inc($self, $_, 'XDFA', $xnq);
256 } elsif (m!^index ([a-f0-9]+)\.\.([a-f0-9]+)!) {
257 my ($ba, $bb) = ($1, $2);
258 index_git_blob_id($doc, 'XDFPRE', $ba);
259 index_git_blob_id($doc, 'XDFPOST', $bb);
261 } elsif (/^@@ (?:\S+) (?:\S+) @@\s*$/) {
262 # traditional diff w/o -p
263 } elsif (/^@@ (?:\S+) (?:\S+) @@\s*(\S+.*)$/) {
264 # hunk header context
265 index_diff_inc($self, $1, 'XDFHH', $xnq);
266 # ignore the following lines:
267 } elsif (/^(?:dis)similarity index/ ||
268 /^(?:old|new) mode/ ||
269 /^(?:deleted|new) file mode/ ||
270 /^(?:copy|rename) (?:from|to) / ||
271 /^(?:dis)?similarity index / ||
272 /^\\ No newline at end of file/ ||
273 /^Binary files .* differ/) {
276 # possible to be in diff context, some mail may be
277 # stripped by MUA or even GNU diff(1). "git apply"
278 # treats a bare "\n" as diff context, too
281 warn "non-diff line: $_\n" if DEBUG && $_ ne '';
286 index_text($self, join("\n", @xnq), 1, 'XNQ');
289 sub index_xapian { # msg_iter callback
290 my $part = $_[0]->[0]; # ignore $depth and $idx
291 my ($self, $doc) = @{$_[1]};
292 my $ct = $part->content_type || 'text/plain';
293 my $fn = $part->filename;
294 if (defined $fn && $fn ne '') {
295 index_text($self, $fn, 1, 'XFN');
297 if ($part->{is_submsg}) {
298 my $mids = mids_for_index($part);
299 index_ids($self, $doc, $part, $mids);
300 my $smsg = bless {}, 'PublicInbox::Smsg';
301 $smsg->populate($part);
302 index_headers($self, $smsg);
305 my ($s, undef) = msg_part_text($part, $ct);
306 defined $s or return;
307 $_[0]->[0] = $part = undef; # free memory
309 # split off quoted and unquoted blocks:
310 my @sections = PublicInbox::MsgIter::split_quotes($s);
311 undef $s; # free memory
312 for my $txt (@sections) {
314 index_text($self, $txt, 0, 'XQUOT');
316 # does it look like a diff?
317 if ($txt =~ /^(?:diff|---|\+\+\+) /ms) {
318 index_diff($self, $txt, $doc);
320 index_text($self, $txt, 1, 'XNQ');
323 undef $txt; # free memory
327 sub index_list_id ($$$) {
328 my ($self, $doc, $hdr) = @_;
329 for my $l ($hdr->header_raw('List-Id')) {
330 $l =~ /<([^>]+)>/ or next;
332 $doc->add_boolean_term('G' . $lid);
333 index_text($self, $lid, 1, 'XL'); # probabilistic
337 sub index_ids ($$$$) {
338 my ($self, $doc, $hdr, $mids) = @_;
339 for my $mid (@$mids) {
340 index_text($self, $mid, 1, 'XM');
342 # because too many Message-IDs are prefixed with
344 if ($mid =~ /\w{12,}/) {
345 my @long = ($mid =~ /(\w{3,}+)/g);
346 index_text($self, join(' ', @long), 1, 'XM');
349 $doc->add_boolean_term('Q' . $_) for @$mids;
350 index_list_id($self, $doc, $hdr);
353 sub eml2doc ($$$;$) {
354 my ($self, $eml, $smsg, $mids) = @_;
355 $mids //= mids_for_index($eml);
356 my $doc = $X->{Document}->new;
357 add_val($doc, PublicInbox::Search::TS(), $smsg->{ts});
358 my @ds = gmtime($smsg->{ds});
359 my $yyyymmdd = strftime('%Y%m%d', @ds);
360 add_val($doc, PublicInbox::Search::YYYYMMDD(), $yyyymmdd);
361 my $dt = strftime('%Y%m%d%H%M%S', @ds);
362 add_val($doc, PublicInbox::Search::DT(), $dt);
363 add_val($doc, PublicInbox::Search::BYTES(), $smsg->{bytes});
364 add_val($doc, PublicInbox::Search::UID(), $smsg->{num});
365 add_val($doc, PublicInbox::Search::THREADID, $smsg->{tid});
367 my $tg = term_generator($self);
368 $tg->set_document($doc);
369 index_headers($self, $smsg);
371 if (defined(my $eidx_key = $smsg->{eidx_key})) {
372 $doc->add_boolean_term('O'.$eidx_key);
374 msg_iter($eml, \&index_xapian, [ $self, $doc ]);
375 index_ids($self, $doc, $eml, $mids);
377 # by default, we maintain compatibility with v1.5.0 and earlier
378 # by writing to docdata.glass, users who never exect to downgrade can
380 if (!$self->{-skip_docdata}) {
381 # WWW doesn't need {to} or {cc}, only NNTP
382 $smsg->{to} = $smsg->{cc} = '';
383 PublicInbox::OverIdx::parse_references($smsg, $eml, $mids);
384 my $data = $smsg->to_doc_data;
385 $doc->set_data($data);
388 if (my $altid = $self->{-altid}) {
389 foreach my $alt (@$altid) {
390 my $pfx = $alt->{xprefix};
391 foreach my $mid (@$mids) {
392 my $id = $alt->mid2alt($mid);
393 next unless defined $id;
394 $doc->add_boolean_term($pfx . $id);
401 sub add_xapian ($$$$) {
402 my ($self, $eml, $smsg, $mids) = @_;
403 my $doc = eml2doc($self, $eml, $smsg, $mids);
404 $self->{xdb}->replace_document($smsg->{num}, $doc);
407 sub _msgmap_init ($) {
409 die "BUG: _msgmap_init is only for v1\n" if $self->{ibx_ver} != 1;
410 $self->{mm} //= eval {
411 require PublicInbox::Msgmap;
412 my $rw = $self->{ibx}->{-no_fsync} ? 2 : 1;
413 PublicInbox::Msgmap->new($self->{ibx}->{inboxdir}, $rw);
418 # mime = PublicInbox::Eml or Email::MIME object
419 my ($self, $mime, $smsg, $sync) = @_;
420 my $mids = mids_for_index($mime);
421 $smsg //= bless { blob => '' }, 'PublicInbox::Smsg'; # test-only compat
422 $smsg->{mid} //= $mids->[0]; # v1 compatibility
423 $smsg->{num} //= do { # v1
425 index_mm($self, $mime, $smsg->{blob}, $sync);
429 $smsg->populate($mime, $sync);
430 $smsg->{bytes} //= length($mime->as_string);
433 # order matters, overview stores every possible piece of
434 # data in doc_data (deflated). Xapian only stores a subset
435 # of the fields which exist in over.sqlite3. We may stop
436 # storing doc_data in Xapian sometime after we get multi-inbox
438 if (my $oidx = $self->{oidx}) { # v1 only
439 $oidx->add_overview($mime, $smsg);
441 if (need_xapian($self)) {
442 add_xapian($self, $mime, $smsg, $mids);
447 warn "failed to index message <".join('> <',@$mids).">: $@\n";
454 my ($self, $docid) = @_;
455 my $doc = eval { $self->{xdb}->get_document($docid) };
457 warn "E: $@\n" if $@;
458 warn "E: #$docid missing in Xapian\n";
464 my ($self, $docid, $eidx_key, $eml) = @_;
465 begin_txn_lazy($self);
466 my $doc = _get_doc($self, $docid) or return;
467 term_generator($self)->set_document($doc);
468 $doc->add_boolean_term('O'.$eidx_key);
469 index_list_id($self, $doc, $eml);
470 $self->{xdb}->replace_document($docid, $doc);
473 sub remove_eidx_info {
474 my ($self, $docid, $eidx_key, $eml) = @_;
475 begin_txn_lazy($self);
476 my $doc = _get_doc($self, $docid) or return;
477 eval { $doc->remove_term('O'.$eidx_key) };
478 warn "W: ->remove_term O$eidx_key: $@\n" if $@;
479 for my $l ($eml ? $eml->header_raw('List-Id') : ()) {
480 $l =~ /<([^>]+)>/ or next;
482 eval { $doc->remove_term('G' . $lid) };
483 warn "W: ->remove_term G$lid: $@\n" if $@;
485 # nb: we don't remove the XL probabilistic terms
486 # since terms may overlap if cross-posted.
488 # IOW, a message which has both <foo.example.com>
489 # and <bar.example.com> would have overlapping
490 # "XLexample" and "XLcom" as terms and which we
491 # wouldn't know if they're safe to remove if we just
492 # unindex <foo.example.com> while preserving
495 # In any case, this entire sub is will likely never
496 # be needed and users using the "l:" prefix are probably
499 $self->{xdb}->replace_document($docid, $doc);
502 sub smsg_from_doc ($) {
504 my $data = $doc->get_data or return;
505 my $smsg = bless {}, 'PublicInbox::Smsg';
506 $smsg->{ts} = int_val($doc, PublicInbox::Search::TS());
507 my $dt = int_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, @docids) = @_;
516 my $xdb = $self->{xdb} or return;
517 for my $docid (@docids) {
518 eval { $xdb->delete_document($docid) };
519 warn "E: #$docid not in in Xapian? $@\n" if $@;
523 sub remove_by_docid {
524 my ($self, $num) = @_;
525 die "BUG: remove_by_docid is v2-only\n" if $self->{oidx};
526 $self->begin_txn_lazy;
527 xdb_remove($self, $num) if need_xapian($self);
530 sub index_git_blob_id {
531 my ($doc, $pfx, $objid) = @_;
533 my $len = length($objid);
534 for (my $len = length($objid); $len >= 7; ) {
535 $doc->add_term($pfx.$objid);
536 $objid = substr($objid, 0, --$len);
542 my ($self, $oid, $eml) = @_;
543 my $mids = mids($eml);
546 for my $mid (@$mids) {
547 my @removed = $self->{oidx}->remove_oid($oid, $mid);
548 $nr += scalar @removed;
549 $tmp{$_}++ for @removed;
552 my $m = join('> <', @$mids);
553 warn "W: <$m> missing for removal from overview\n";
555 while (my ($num, $nr) = each %tmp) {
556 warn "BUG: $num appears >1 times ($nr) for $oid\n" if $nr != 1;
559 $self->{mm}->num_delete($_) for (keys %tmp);
560 } else { # just in case msgmap and over.sqlite3 become desynched:
561 $self->{mm}->mid_delete($mids->[0]);
563 xdb_remove($self, keys %tmp) if need_xapian($self);
567 my ($self, $mime, $oid, $sync) = @_;
568 my $mids = mids($mime);
569 my $mm = $self->{mm};
570 if ($sync->{reindex}) {
571 my $oidx = $self->{oidx};
572 for my $mid (@$mids) {
573 my ($num, undef) = $oidx->num_mid0_for_oid($oid, $mid);
574 return $num if defined $num;
576 $mm->num_for($mids->[0]) // $mm->mid_insert($mids->[0]);
578 # fallback to num_for since filters like RubyLang set the number
579 $mm->mid_insert($mids->[0]) // $mm->num_for($mids->[0]);
583 # returns the number of bytes to add if given a non-CRLF arg
584 sub crlf_adjust ($) {
585 if (index($_[0], "\r\n") < 0) {
586 # common case is LF-only, every \n needs an \r;
587 # so favor a cheap tr// over an expensive m//g
589 } else { # count number of '\n' w/o '\r', expensive:
590 scalar(my @n = ($_[0] =~ m/(?<!\r)\n/g));
594 sub is_bad_blob ($$$$) {
595 my ($oid, $type, $size, $expect_oid) = @_;
596 if ($type ne 'blob') {
597 carp "W: $expect_oid is not a blob (type=$type)";
600 croak "BUG: $oid != $expect_oid" if $oid ne $expect_oid;
601 $size == 0 ? 1 : 0; # size == 0 means purged
604 sub index_both { # git->cat_async callback
605 my ($bref, $oid, $type, $size, $sync) = @_;
606 return if is_bad_blob($oid, $type, $size, $sync->{oid});
607 my ($nr, $max) = @$sync{qw(nr max)};
610 $size += crlf_adjust($$bref);
611 my $smsg = bless { bytes => $size, blob => $oid }, 'PublicInbox::Smsg';
612 my $self = $sync->{sidx};
613 local $self->{current_info} = "$self->{current_info}: $oid";
614 my $eml = PublicInbox::Eml->new($bref);
615 $smsg->{num} = index_mm($self, $eml, $oid, $sync) or
616 die "E: could not generate NNTP article number for $oid";
617 add_message($self, $eml, $smsg, $sync);
619 my $cur_cmt = $sync->{cur_cmt} // die 'BUG: {cur_cmt} missing';
620 ${$sync->{latest_cmt}} = $cur_cmt;
623 sub unindex_both { # git->cat_async callback
624 my ($bref, $oid, $type, $size, $sync) = @_;
625 return if is_bad_blob($oid, $type, $size, $sync->{oid});
626 my $self = $sync->{sidx};
627 local $self->{current_info} = "$self->{current_info}: $oid";
628 unindex_eml($self, $oid, PublicInbox::Eml->new($bref));
629 # may be undef if leftover
630 if (defined(my $cur_cmt = $sync->{cur_cmt})) {
631 ${$sync->{latest_cmt}} = $cur_cmt;
638 ($self->{ibx} // $self->{eidx})->with_umask(@_);
641 # called by public-inbox-index
643 my ($self, $opt) = @_;
644 delete $self->{lock_path} if $opt->{-skip_lock};
645 $self->with_umask(\&_index_sync, $self, $opt);
646 if ($opt->{reindex} && !$opt->{quit}) {
648 delete @again{qw(rethread reindex)};
649 index_sync($self, \%again);
650 $opt->{quit} = $again{quit}; # propagate to caller
654 sub check_size { # check_async cb for -index --max-size=...
655 my ($oid, $type, $size, $arg, $git) = @_;
656 (($type // '') eq 'blob') or die "E: bad $oid in $git->{git_dir}";
657 if ($size <= $arg->{max_size}) {
658 $git->cat_async($oid, $arg->{index_oid}, $arg);
660 warn "W: skipping $oid ($size > $arg->{max_size})\n";
664 sub v1_checkpoint ($$;$) {
665 my ($self, $sync, $stk) = @_;
666 $self->{ibx}->git->async_wait_all;
668 # $newest may be undef
669 my $newest = $stk ? $stk->{latest_cmt} : ${$sync->{latest_cmt}};
670 if (defined($newest)) {
671 my $cur = $self->{mm}->last_commit || '';
672 if (need_update($self, $cur, $newest)) {
673 $self->{mm}->last_commit($newest);
676 ${$sync->{max}} = $self->{batch_bytes};
678 $self->{mm}->{dbh}->commit;
679 my $xdb = need_xapian($self) ? $self->{xdb} : undef;
680 if ($newest && $xdb) {
681 my $cur = $xdb->get_metadata('last_commit');
682 if (need_update($self, $cur, $newest)) {
683 $xdb->set_metadata('last_commit', $newest);
686 if ($stk) { # all done if $stk is passed
687 # let SearchView know a full --reindex was done so it can
688 # generate ->has_threadid-dependent links
689 if ($xdb && $sync->{reindex} && !ref($sync->{reindex})) {
690 my $n = $xdb->get_metadata('has_threadid');
691 $xdb->set_metadata('has_threadid', '1') if $n ne '1';
693 $self->{oidx}->rethread_done($sync->{-opt}); # all done
695 commit_txn_lazy($self);
696 $sync->{ibx}->git->cleanup;
697 my $nr = ${$sync->{nr}};
698 idx_release($self, $nr);
699 # let another process do some work...
700 if (my $pr = $sync->{-opt}->{-progress}) {
701 $pr->("indexed $nr/$sync->{ntodo}\n") if $nr;
703 if (!$stk && !$sync->{quit}) { # more to come
704 begin_txn_lazy($self);
705 $self->{mm}->{dbh}->begin_work;
711 my ($self, $sync, $stk) = @_;
712 my $git = $sync->{ibx}->git;
713 my $max = $self->{batch_bytes};
716 $sync->{max} = \$max;
717 $sync->{sidx} = $self;
718 $sync->{latest_cmt} = \(my $latest_cmt);
720 $self->{mm}->{dbh}->begin_work;
721 if (my @leftovers = keys %{delete($sync->{D}) // {}}) {
722 warn('W: unindexing '.scalar(@leftovers)." leftovers\n");
723 for my $oid (@leftovers) {
724 last if $sync->{quit};
725 $oid = unpack('H*', $oid);
726 $git->cat_async($oid, \&unindex_both, $sync);
729 if ($sync->{max_size} = $sync->{-opt}->{max_size}) {
730 $sync->{index_oid} = \&index_both;
732 while (my ($f, $at, $ct, $oid, $cur_cmt) = $stk->pop_rec) {
733 my $arg = { %$sync, cur_cmt => $cur_cmt, oid => $oid };
734 last if $sync->{quit};
736 $arg->{autime} = $at;
737 $arg->{cotime} = $ct;
738 if ($sync->{max_size}) {
739 $git->check_async($oid, \&check_size, $arg);
741 $git->cat_async($oid, \&index_both, $arg);
743 v1_checkpoint($self, $sync) if $max <= 0;
744 } elsif ($f eq 'd') {
745 $git->cat_async($oid, \&unindex_both, $arg);
748 v1_checkpoint($self, $sync, $sync->{quit} ? undef : $stk);
751 sub log2stack ($$$) {
752 my ($sync, $git, $range) = @_;
753 my $D = $sync->{D}; # OID_BIN => NR (if reindexing, undef otherwise)
755 if ($sync->{ibx}->version == 1) {
756 my $path = $hex.'{2}/'.$hex.'{38}';
757 $add = qr!\A:000000 100644 \S+ ($OID) A\t$path$!;
758 $del = qr!\A:100644 000000 ($OID) \S+ D\t$path$!;
760 $del = qr!\A:\d{6} 100644 $OID ($OID) [AM]\td$!;
761 $add = qr!\A:\d{6} 100644 $OID ($OID) [AM]\tm$!;
764 # Count the new files so they can be added newest to oldest
765 # and still have numbers increasing from oldest to newest
766 my $fh = $git->popen(qw(log --raw -r --pretty=tformat:%at-%ct-%H
767 --no-notes --no-color --no-renames --no-abbrev),
769 my ($at, $ct, $stk, $cmt);
771 return if $sync->{quit};
772 if (/\A([0-9]+)-([0-9]+)-($OID)$/o) {
773 ($at, $ct, $cmt) = ($1 + 0, $2 + 0, $3);
774 $stk //= PublicInbox::IdxStack->new($cmt);
777 if ($D) { # reindex case
778 $D->{pack('H*', $oid)}++;
779 } else { # non-reindex case:
780 $stk->push_rec('d', $at, $ct, $oid, $cmt);
785 my $oid_bin = pack('H*', $oid);
786 my $nr = --$D->{$oid_bin};
787 delete($D->{$oid_bin}) if $nr <= 0;
788 # nr < 0 (-1) means it never existed
791 $stk->push_rec('m', $at, $ct, $oid, $cmt);
794 close $fh or die "git log failed: \$?=$?";
795 $stk //= PublicInbox::IdxStack->new;
799 sub prepare_stack ($$) {
800 my ($sync, $range) = @_;
801 my $git = $sync->{ibx}->git;
803 if (index($range, '..') < 0) {
804 # don't show annoying git errors to users who run -index
806 $git->qx(qw(rev-parse -q --verify), "$range^0");
807 return PublicInbox::IdxStack->new->read_prepare if $?;
809 $sync->{D} = $sync->{reindex} ? {} : undef; # OID_BIN => NR
810 log2stack($sync, $git, $range);
813 # --is-ancestor requires git 1.8.0+
814 sub is_ancestor ($$$) {
815 my ($git, $cur, $tip) = @_;
816 return 0 unless $git->check($cur);
817 my $cmd = [ 'git', "--git-dir=$git->{git_dir}",
818 qw(merge-base --is-ancestor), $cur, $tip ];
819 my $pid = spawn($cmd);
820 waitpid($pid, 0) == $pid or die join(' ', @$cmd) .' did not finish';
824 sub need_update ($$$) {
825 my ($self, $cur, $new) = @_;
826 my $git = $self->{ibx}->git;
827 return 1 if $cur && !is_ancestor($git, $cur, $new);
828 my $range = $cur eq '' ? $new : "$cur..$new";
829 chomp(my $n = $git->qx(qw(rev-list --count), $range));
830 ($n eq '' || $n > 0);
833 # The last git commit we indexed with Xapian or SQLite (msgmap)
834 # This needs to account for cases where Xapian or SQLite is
835 # out-of-date with respect to the other.
837 my ($self, $mm) = @_;
838 my $lm = $mm->last_commit || '';
840 if (need_xapian($self)) {
841 $lx = $self->{xdb}->get_metadata('last_commit') || '';
845 # Use last_commit from msgmap if it is older or unset
846 if (!$lm || ($lx && $lm && is_ancestor($self->{ibx}->git, $lm, $lx))) {
852 sub reindex_from ($$) {
853 my ($reindex, $last_commit) = @_;
854 return $last_commit unless $reindex;
855 ref($reindex) eq 'HASH' ? $reindex->{from} : '';
861 # we set {-opt}->{quit} too, so ->index_sync callers
862 # can abort multi-inbox loops this way
863 $sync->{quit} = $sync->{-opt}->{quit} = 1;
864 warn "gracefully quitting\n";
868 # indexes all unindexed messages (v1 only)
870 my ($self, $opt) = @_;
871 my $tip = $opt->{ref} || 'HEAD';
872 my $ibx = $self->{ibx};
873 local $self->{current_info} = "$ibx->{inboxdir}";
874 $self->{batch_bytes} = $opt->{batch_size} // $BATCH_BYTES;
875 $ibx->git->batch_prepare;
876 my $pr = $opt->{-progress};
877 my $sync = { reindex => $opt->{reindex}, -opt => $opt, ibx => $ibx };
878 my $quit = quit_cb($sync);
879 local $SIG{QUIT} = $quit;
880 local $SIG{INT} = $quit;
881 local $SIG{TERM} = $quit;
882 my $xdb = $self->begin_txn_lazy;
883 $self->{oidx}->rethread_prepare($opt);
884 my $mm = _msgmap_init($self);
885 if ($sync->{reindex}) {
886 my $last = $mm->last_commit;
890 # somebody just blindly added --reindex when indexing
891 # for the first time, allow it:
892 undef $sync->{reindex};
895 my $last_commit = _last_x_commit($self, $mm);
896 my $lx = reindex_from($sync->{reindex}, $last_commit);
897 my $range = $lx eq '' ? $tip : "$lx..$tip";
898 $pr->("counting changes\n\t$range ... ") if $pr;
899 my $stk = prepare_stack($sync, $range);
900 $sync->{ntodo} = $stk ? $stk->num_records : 0;
901 $pr->("$sync->{ntodo}\n") if $pr; # continue previous line
902 process_stack($self, $sync, $stk) if !$sync->{quit};
906 # order matters for unlocking
907 $_[0]->{xdb} = undef;
908 $_[0]->{lockfh} = undef;
913 my $xdb = $self->{xdb} || idx_acquire($self);
914 $self->{oidx}->begin_lazy if $self->{oidx};
915 $xdb->begin_transaction if $xdb;
922 $self->with_umask(\&_begin_txn, $self) if !$self->{txn};
925 # store 'indexlevel=medium' in v2 shard=0 and v1 (only one shard)
926 # This metadata is read by Admin::detect_indexlevel:
927 sub set_metadata_once {
930 return if $self->{shard}; # only continue if undef or 0, not >0
931 my $xdb = $self->{xdb};
933 if (delete($self->{-set_has_threadid_once})) {
934 $xdb->set_metadata('has_threadid', '1');
936 if (delete($self->{-set_indexlevel_once})) {
937 my $level = $xdb->get_metadata('indexlevel');
938 if (!$level || $level ne 'medium') {
939 $xdb->set_metadata('indexlevel', 'medium');
942 if (delete($self->{-set_skip_docdata_once})) {
943 $xdb->get_metadata('skip_docdata') or
944 $xdb->set_metadata('skip_docdata', '1');
950 if (my $eidx = $self->{eidx}) {
951 $eidx->git->async_wait_all;
952 $eidx->{transact_bytes} = 0;
954 if (my $xdb = $self->{xdb}) {
955 set_metadata_once($self);
956 $xdb->commit_transaction;
958 $self->{oidx}->commit_lazy if $self->{oidx};
961 sub commit_txn_lazy {
963 delete($self->{txn}) and
964 $self->with_umask(\&_commit_txn, $self);
969 if (need_xapian($self)) {
970 die "$$ $0 xdb not released\n" if $self->{xdb};
972 die "$$ $0 still in transaction\n" if $self->{txn};
976 my ($class, $eidx, $shard) = @_;
979 xpfx => $eidx->{xpfx},
980 indexlevel => $eidx->{indexlevel},
985 $self->{-set_indexlevel_once} = 1 if $self->{indexlevel} eq 'medium';
989 # ensure there's no stale Xapian docs by treating $over as canonical
991 my ($self, $over) = @_;
992 begin_txn_lazy($self);
993 my $sth = $over->dbh->prepare(<<'');
994 SELECT COUNT(*) FROM over WHERE num = ?
996 my $xdb = $self->{xdb};
997 my $cur = $xdb->postlist_begin('');
998 my $end = $xdb->postlist_end('');
999 my $xdir = $self->xdir;
1000 for (; $cur != $end; $cur++) {
1001 my $docid = $cur->get_docid;
1002 $sth->execute($docid);
1003 my $x = $sth->fetchrow_array;
1005 warn "I: removing $xdir #$docid, not in `over'\n";
1006 $xdb->delete_document($docid);