]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/V2Writable.pm
rename {pi_config} fields to {pi_cfg}
[public-inbox.git] / lib / PublicInbox / V2Writable.pm
1 # Copyright (C) 2018-2020 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
3
4 # This interface wraps and mimics PublicInbox::Import
5 # Used to write to V2 inboxes (see L<public-inbox-v2-format(5)>).
6 package PublicInbox::V2Writable;
7 use strict;
8 use v5.10.1;
9 use parent qw(PublicInbox::Lock);
10 use PublicInbox::SearchIdxShard;
11 use PublicInbox::Eml;
12 use PublicInbox::Git;
13 use PublicInbox::Import;
14 use PublicInbox::MID qw(mids references);
15 use PublicInbox::ContentHash qw(content_hash content_digest);
16 use PublicInbox::InboxWritable;
17 use PublicInbox::OverIdx;
18 use PublicInbox::Msgmap;
19 use PublicInbox::Spawn qw(spawn popen_rd);
20 use PublicInbox::SearchIdx qw(log2stack crlf_adjust is_ancestor check_size);
21 use IO::Handle; # ->autoflush
22 use File::Temp ();
23
24 my $OID = qr/[a-f0-9]{40,}/;
25 # an estimate of the post-packed size to the raw uncompressed size
26 my $PACKING_FACTOR = 0.4;
27
28 # SATA storage lags behind what CPUs are capable of, so relying on
29 # nproc(1) can be misleading and having extra Xapian shards is a
30 # waste of FDs and space.  It can also lead to excessive IO latency
31 # and slow things down.  Users on NVME or other fast storage can
32 # use the NPROC env or switches in our script/public-inbox-* programs
33 # to increase Xapian shards
34 our $NPROC_MAX_DEFAULT = 4;
35
36 sub detect_nproc () {
37         # getconf(1) is POSIX, but *NPROCESSORS* vars are not
38         for (qw(_NPROCESSORS_ONLN NPROCESSORS_ONLN)) {
39                 `getconf $_ 2>/dev/null` =~ /^(\d+)$/ and return $1;
40         }
41         for my $nproc (qw(nproc gnproc)) { # GNU coreutils nproc
42                 `$nproc 2>/dev/null` =~ /^(\d+)$/ and return $1;
43         }
44
45         # should we bother with `sysctl hw.ncpu`?  Those only give
46         # us total processor count, not online processor count.
47         undef
48 }
49
50 sub nproc_shards ($) {
51         my ($creat_opt) = @_;
52         my $n = $creat_opt->{nproc} if ref($creat_opt) eq 'HASH';
53         $n //= $ENV{NPROC};
54         if (!$n) {
55                 # assume 2 cores if not detectable or zero
56                 state $NPROC_DETECTED = detect_nproc() || 2;
57                 $n = $NPROC_DETECTED;
58                 $n = $NPROC_MAX_DEFAULT if $n > $NPROC_MAX_DEFAULT;
59         }
60
61         # subtract for the main process and git-fast-import
62         $n -= 1;
63         $n < 1 ? 1 : $n;
64 }
65
66 sub count_shards ($) {
67         my ($self) = @_;
68         if (my $ibx = $self->{ibx}) {
69                 # always load existing shards in case core count changes:
70                 # Also, shard count may change while -watch is running
71                 my $srch = $ibx->search or return 0;
72                 delete $ibx->{search};
73                 $srch->{nshard} // 0
74         } else { # ExtSearchIdx
75                 $self->{nshard} // do {
76                         if ($self->xdb_sharded) {
77                                 $self->{nshard} // die 'BUG: {nshard} unset';
78                         } else {
79                                 0;
80                         }
81                 }
82         }
83 }
84
85 sub new {
86         # $creat may be any true value, or 0/undef.  A hashref is true,
87         # and $creat->{nproc} may be set to an integer
88         my ($class, $v2ibx, $creat) = @_;
89         $v2ibx = PublicInbox::InboxWritable->new($v2ibx);
90         my $dir = $v2ibx->assert_usable_dir;
91         unless (-d $dir) {
92                 if ($creat) {
93                         require File::Path;
94                         File::Path::mkpath($dir);
95                 } else {
96                         die "$dir does not exist\n";
97                 }
98         }
99         $v2ibx->umask_prepare;
100
101         my $xpfx = "$dir/xap" . PublicInbox::Search::SCHEMA_VERSION;
102         my $self = {
103                 ibx => $v2ibx,
104                 im => undef, #  PublicInbox::Import
105                 parallel => 1,
106                 transact_bytes => 0,
107                 total_bytes => 0,
108                 current_info => '',
109                 xpfx => $xpfx,
110                 oidx => PublicInbox::OverIdx->new("$xpfx/over.sqlite3"),
111                 lock_path => "$dir/inbox.lock",
112                 # limit each git repo (epoch) to 1GB or so
113                 rotate_bytes => int((1024 * 1024 * 1024) / $PACKING_FACTOR),
114                 last_commit => [], # git epoch -> commit
115         };
116         $self->{oidx}->{-no_fsync} = 1 if $v2ibx->{-no_fsync};
117         $self->{shards} = count_shards($self) || nproc_shards($creat);
118         bless $self, $class;
119 }
120
121 # public (for now?)
122 sub init_inbox {
123         my ($self, $shards, $skip_epoch, $skip_artnum) = @_;
124         if (defined $shards) {
125                 $self->{parallel} = 0 if $shards == 0;
126                 $self->{shards} = $shards if $shards > 0;
127         }
128         $self->idx_init;
129         $self->{mm}->skip_artnum($skip_artnum) if defined $skip_artnum;
130         my $epoch_max = -1;
131         $self->{ibx}->git_dir_latest(\$epoch_max);
132         if (defined $skip_epoch && $epoch_max == -1) {
133                 $epoch_max = $skip_epoch;
134         }
135         $self->git_init($epoch_max >= 0 ? $epoch_max : 0);
136         $self->done;
137 }
138
139 # returns undef on duplicate or spam
140 # mimics Import::add and wraps it for v2
141 sub add {
142         my ($self, $eml, $check_cb) = @_;
143         $self->{ibx}->with_umask(\&_add, $self, $eml, $check_cb);
144 }
145
146 sub idx_shard ($$) {
147         my ($self, $num) = @_;
148         $self->{idx_shards}->[$num % scalar(@{$self->{idx_shards}})];
149 }
150
151 # indexes a message, returns true if checkpointing is needed
152 sub do_idx ($$$$) {
153         my ($self, $msgref, $mime, $smsg) = @_;
154         $smsg->{bytes} = $smsg->{raw_bytes} + crlf_adjust($$msgref);
155         $self->{oidx}->add_overview($mime, $smsg);
156         my $idx = idx_shard($self, $smsg->{num});
157         $idx->index_raw($msgref, $mime, $smsg);
158         my $n = $self->{transact_bytes} += $smsg->{raw_bytes};
159         $n >= $self->{batch_bytes};
160 }
161
162 sub _add {
163         my ($self, $mime, $check_cb) = @_;
164
165         # spam check:
166         if ($check_cb) {
167                 $mime = $check_cb->($mime, $self->{ibx}) or return;
168         }
169
170         # All pipes (> $^F) known to Perl 5.6+ have FD_CLOEXEC set,
171         # as does SQLite 3.4.1+ (released in 2007-07-20), and
172         # Xapian 1.3.2+ (released 2015-03-15).
173         # For the most part, we can spawn git-fast-import without
174         # leaking FDs to it...
175         $self->idx_init;
176
177         my ($num, $mid0) = v2_num_for($self, $mime);
178         defined $num or return; # duplicate
179         defined $mid0 or die "BUG: \$mid0 undefined\n";
180         my $im = $self->importer;
181         my $smsg = bless { mid => $mid0, num => $num }, 'PublicInbox::Smsg';
182         my $cmt = $im->add($mime, undef, $smsg); # sets $smsg->{ds|ts|blob}
183         $cmt = $im->get_mark($cmt);
184         $self->{last_commit}->[$self->{epoch_max}] = $cmt;
185
186         my $msgref = delete $smsg->{-raw_email};
187         if (do_idx($self, $msgref, $mime, $smsg)) {
188                 $self->checkpoint;
189         }
190
191         $cmt;
192 }
193
194 sub v2_num_for {
195         my ($self, $mime) = @_;
196         my $mids = mids($mime);
197         if (@$mids) {
198                 my $mid = $mids->[0];
199                 my $num = $self->{mm}->mid_insert($mid);
200                 if (defined $num) { # common case
201                         return ($num, $mid);
202                 }
203
204                 # crap, Message-ID is already known, hope somebody just resent:
205                 foreach my $m (@$mids) {
206                         # read-only lookup now safe to do after above barrier
207                         # easy, don't store duplicates
208                         # note: do not add more diagnostic info here since
209                         # it gets noisy on public-inbox-watch restarts
210                         return () if content_exists($self, $mime, $m);
211                 }
212
213                 # AltId may pre-populate article numbers (e.g. X-Mail-Count
214                 # or NNTP article number), use that article number if it's
215                 # not in Over.
216                 my $altid = $self->{ibx}->{altid};
217                 if ($altid && grep(/:file=msgmap\.sqlite3\z/, @$altid)) {
218                         my $num = $self->{mm}->num_for($mid);
219
220                         if (defined $num && !$self->{oidx}->get_art($num)) {
221                                 return ($num, $mid);
222                         }
223                 }
224
225                 # very unlikely:
226                 warn "<$mid> reused for mismatched content\n";
227
228                 # try the rest of the mids
229                 for(my $i = $#$mids; $i >= 1; $i--) {
230                         my $m = $mids->[$i];
231                         $num = $self->{mm}->mid_insert($m);
232                         if (defined $num) {
233                                 warn "alternative <$m> for <$mid> found\n";
234                                 return ($num, $m);
235                         }
236                 }
237         }
238         # none of the existing Message-IDs are good, generate a new one:
239         v2_num_for_harder($self, $mime);
240 }
241
242 sub v2_num_for_harder {
243         my ($self, $eml) = @_;
244
245         my $dig = content_digest($eml);
246         my $mid0 = PublicInbox::Import::digest2mid($dig, $eml);
247         my $num = $self->{mm}->mid_insert($mid0);
248         unless (defined $num) {
249                 # it's hard to spoof the last Received: header
250                 my @recvd = $eml->header_raw('Received');
251                 $dig->add("Received: $_") foreach (@recvd);
252                 $mid0 = PublicInbox::Import::digest2mid($dig, $eml);
253                 $num = $self->{mm}->mid_insert($mid0);
254
255                 # fall back to a random Message-ID and give up determinism:
256                 until (defined($num)) {
257                         $dig->add(rand);
258                         $mid0 = PublicInbox::Import::digest2mid($dig, $eml);
259                         warn "using random Message-ID <$mid0> as fallback\n";
260                         $num = $self->{mm}->mid_insert($mid0);
261                 }
262         }
263         PublicInbox::Import::append_mid($eml, $mid0);
264         ($num, $mid0);
265 }
266
267 sub _idx_init { # with_umask callback
268         my ($self, $opt) = @_;
269         $self->lock_acquire unless $opt && $opt->{-skip_lock};
270         $self->{oidx}->create;
271
272         # xcpdb can change shard count while -watch is idle
273         my $nshards = count_shards($self);
274         $self->{shards} = $nshards if $nshards && $nshards != $self->{shards};
275         $self->{batch_bytes} = $opt->{batch_size} //
276                                 $PublicInbox::SearchIdx::BATCH_BYTES;
277         $self->{batch_bytes} *= $self->{shards} if $self->{parallel};
278
279         # need to create all shards before initializing msgmap FD
280         # idx_shards must be visible to all forked processes
281         my $max = $self->{shards} - 1;
282         my $idx = $self->{idx_shards} = [];
283         push @$idx, PublicInbox::SearchIdxShard->new($self, $_) for (0..$max);
284         my $ibx = $self->{ibx} or return; # ExtIdxSearch
285
286         # Now that all subprocesses are up, we can open the FDs
287         # for SQLite:
288         my $mm = $self->{mm} = PublicInbox::Msgmap->new_file(
289                                 "$ibx->{inboxdir}/msgmap.sqlite3",
290                                 $ibx->{-no_fsync} ? 2 : 1);
291         $mm->{dbh}->begin_work;
292 }
293
294 sub parallel_init ($$) {
295         my ($self, $indexlevel) = @_;
296         if (($indexlevel // 'full') eq 'basic') {
297                 $self->{parallel} = 0;
298         } else {
299                 pipe(my ($r, $w)) or die "pipe failed: $!";
300                 # pipe for barrier notifications doesn't need to be big,
301                 # 1031: F_SETPIPE_SZ
302                 fcntl($w, 1031, 4096) if $^O eq 'linux';
303                 $self->{bnote} = [ $r, $w ];
304                 $w->autoflush(1);
305         }
306 }
307
308 # idempotent
309 sub idx_init {
310         my ($self, $opt) = @_;
311         return if $self->{idx_shards};
312         my $ibx = $self->{ibx};
313
314         # do not leak read-only FDs to child processes, we only have these
315         # FDs for duplicate detection so they should not be
316         # frequently activated.
317         delete @$ibx{qw(mm search)};
318         $ibx->git->cleanup;
319
320         parallel_init($self, $ibx->{indexlevel});
321         $ibx->umask_prepare;
322         $ibx->with_umask(\&_idx_init, $self, $opt);
323 }
324
325 # returns an array mapping [ epoch => latest_commit ]
326 # latest_commit may be undef if nothing was done to that epoch
327 # $replace_map = { $object_id => $strref, ... }
328 sub _replace_oids ($$$) {
329         my ($self, $mime, $replace_map) = @_;
330         $self->done;
331         my $ibx = $self->{ibx};
332         my $pfx = "$ibx->{inboxdir}/git";
333         my $rewrites = []; # epoch => commit
334         my $max = $self->{epoch_max};
335
336         unless (defined($max)) {
337                 defined(my $latest = $ibx->git_dir_latest(\$max)) or return;
338                 $self->{epoch_max} = $max;
339         }
340
341         foreach my $i (0..$max) {
342                 my $git_dir = "$pfx/$i.git";
343                 -d $git_dir or next;
344                 my $git = PublicInbox::Git->new($git_dir);
345                 my $im = $self->import_init($git, 0, 1);
346                 $rewrites->[$i] = $im->replace_oids($mime, $replace_map);
347                 $im->done;
348         }
349         $rewrites;
350 }
351
352 sub content_hashes ($) {
353         my ($mime) = @_;
354         my @chashes = ( content_hash($mime) );
355
356         # We still support Email::MIME, here, and
357         # Email::MIME->as_string doesn't always round-trip, so we may
358         # use a second content_hash
359         my $rt = content_hash(PublicInbox::Eml->new(\($mime->as_string)));
360         push @chashes, $rt if $chashes[0] ne $rt;
361         \@chashes;
362 }
363
364 sub content_matches ($$) {
365         my ($chashes, $existing) = @_;
366         my $chash = content_hash($existing);
367         foreach (@$chashes) {
368                 return 1 if $_ eq $chash
369         }
370         0
371 }
372
373 # used for removing or replacing (purging)
374 sub rewrite_internal ($$;$$$) {
375         my ($self, $old_eml, $cmt_msg, $new_eml, $sref) = @_;
376         $self->idx_init;
377         my ($im, $need_reindex, $replace_map);
378         if ($sref) {
379                 $replace_map = {}; # oid => sref
380                 $need_reindex = [] if $new_eml;
381         } else {
382                 $im = $self->importer;
383         }
384         my $oidx = $self->{oidx};
385         my $chashes = content_hashes($old_eml);
386         my $removed = [];
387         my $mids = mids($old_eml);
388
389         # We avoid introducing new blobs into git since the raw content
390         # can be slightly different, so we do not need the user-supplied
391         # message now that we have the mids and content_hash
392         $old_eml = undef;
393         my $mark;
394
395         foreach my $mid (@$mids) {
396                 my %gone; # num => [ smsg, $mime, raw ]
397                 my ($id, $prev);
398                 while (my $smsg = $oidx->next_by_mid($mid, \$id, \$prev)) {
399                         my $msg = get_blob($self, $smsg);
400                         if (!defined($msg)) {
401                                 warn "broken smsg for $mid\n";
402                                 next; # continue
403                         }
404                         my $orig = $$msg;
405                         my $cur = PublicInbox::Eml->new($msg);
406                         if (content_matches($chashes, $cur)) {
407                                 $gone{$smsg->{num}} = [ $smsg, $cur, \$orig ];
408                         }
409                 }
410                 my $n = scalar keys %gone;
411                 next unless $n;
412                 if ($n > 1) {
413                         warn "BUG: multiple articles linked to <$mid>\n",
414                                 join(',', sort keys %gone), "\n";
415                 }
416                 foreach my $num (keys %gone) {
417                         my ($smsg, $mime, $orig) = @{$gone{$num}};
418                         # $removed should only be set once assuming
419                         # no bugs in our deduplication code:
420                         $removed = [ undef, $mime, $smsg ];
421                         my $oid = $smsg->{blob};
422                         if ($replace_map) {
423                                 $replace_map->{$oid} = $sref;
424                         } else {
425                                 ($mark, undef) = $im->remove($orig, $cmt_msg);
426                                 $removed->[0] = $mark;
427                         }
428                         $orig = undef;
429                         if ($need_reindex) { # ->replace
430                                 push @$need_reindex, $smsg;
431                         } else { # ->purge or ->remove
432                                 $self->{mm}->num_delete($num);
433                         }
434                         unindex_oid_aux($self, $oid, $mid);
435                 }
436         }
437
438         if (defined $mark) {
439                 my $cmt = $im->get_mark($mark);
440                 $self->{last_commit}->[$self->{epoch_max}] = $cmt;
441         }
442         if ($replace_map && scalar keys %$replace_map) {
443                 my $rewrites = _replace_oids($self, $new_eml, $replace_map);
444                 return { rewrites => $rewrites, need_reindex => $need_reindex };
445         }
446         defined($mark) ? $removed : undef;
447 }
448
449 # public (see PublicInbox::Import->remove), but note the 3rd element
450 # (retval[2]) is not part of the stable API shared with Import->remove
451 sub remove {
452         my ($self, $eml, $cmt_msg) = @_;
453         my $r = $self->{ibx}->with_umask(\&rewrite_internal,
454                                                 $self, $eml, $cmt_msg);
455         defined($r) && defined($r->[0]) ? @$r: undef;
456 }
457
458 sub _replace ($$;$$) {
459         my ($self, $old_eml, $new_eml, $sref) = @_;
460         my $arg = [ $self, $old_eml, undef, $new_eml, $sref ];
461         my $rewritten = $self->{ibx}->with_umask(\&rewrite_internal,
462                         $self, $old_eml, undef, $new_eml, $sref) or return;
463
464         my $rewrites = $rewritten->{rewrites};
465         # ->done is called if there are rewrites since we gc+prune from git
466         $self->idx_init if @$rewrites;
467
468         for my $i (0..$#$rewrites) {
469                 defined(my $cmt = $rewrites->[$i]) or next;
470                 $self->{last_commit}->[$i] = $cmt;
471         }
472         $rewritten;
473 }
474
475 # public
476 sub purge {
477         my ($self, $mime) = @_;
478         my $rewritten = _replace($self, $mime, undef, \'') or return;
479         $rewritten->{rewrites}
480 }
481
482 # returns the git object_id of $fh, does not write the object to FS
483 sub git_hash_raw ($$) {
484         my ($self, $raw) = @_;
485         # grab the expected OID we have to reindex:
486         pipe(my($in, $w)) or die "pipe: $!";
487         my $git_dir = $self->git->{git_dir};
488         my $cmd = ['git', "--git-dir=$git_dir", qw(hash-object --stdin)];
489         my $r = popen_rd($cmd, undef, { 0 => $in });
490         print $w $$raw or die "print \$w: $!";
491         close $w or die "close \$w: $!";
492         local $/ = "\n";
493         chomp(my $oid = <$r>);
494         close $r or die "git hash-object failed: $?";
495         $oid =~ /\A$OID\z/ or die "OID not expected: $oid";
496         $oid;
497 }
498
499 sub _check_mids_match ($$$) {
500         my ($old_list, $new_list, $hdrs) = @_;
501         my %old_mids = map { $_ => 1 } @$old_list;
502         my %new_mids = map { $_ => 1 } @$new_list;
503         my @old = keys %old_mids;
504         my @new = keys %new_mids;
505         my $err = "$hdrs may not be changed when replacing\n";
506         die $err if scalar(@old) != scalar(@new);
507         delete @new_mids{@old};
508         delete @old_mids{@new};
509         die $err if (scalar(keys %old_mids) || scalar(keys %new_mids));
510 }
511
512 # Changing Message-IDs or References with ->replace isn't supported.
513 # The rules for dealing with messages with multiple or conflicting
514 # Message-IDs are pretty complex and rethreading hasn't been fully
515 # implemented, yet.
516 sub check_mids_match ($$) {
517         my ($old, $new) = @_;
518         _check_mids_match(mids($old), mids($new), 'Message-ID(s)');
519         _check_mids_match(references($old), references($new),
520                         'References/In-Reply-To');
521 }
522
523 # public
524 sub replace ($$$) {
525         my ($self, $old_mime, $new_mime) = @_;
526
527         check_mids_match($old_mime, $new_mime);
528
529         # mutt will always add Content-Length:, Status:, Lines: when editing
530         PublicInbox::Import::drop_unwanted_headers($new_mime);
531
532         my $raw = $new_mime->as_string;
533         my $expect_oid = git_hash_raw($self, \$raw);
534         my $rewritten = _replace($self, $old_mime, $new_mime, \$raw) or return;
535         my $need_reindex = $rewritten->{need_reindex};
536
537         # just in case we have bugs in deduplication code:
538         my $n = scalar(@$need_reindex);
539         if ($n > 1) {
540                 my $list = join(', ', map {
541                                         "$_->{num}: <$_->{mid}>"
542                                 } @$need_reindex);
543                 warn <<"";
544 W: rewritten $n messages matching content of original message (expected: 1).
545 W: possible bug in public-inbox, NNTP article IDs and Message-IDs follow:
546 W: $list
547
548         }
549
550         # make sure we really got the OID:
551         my ($blob, $type, $bytes) = $self->git->check($expect_oid);
552         $blob eq $expect_oid or die "BUG: $expect_oid not found after replace";
553
554         # don't leak FDs to Xapian:
555         $self->git->cleanup;
556
557         # reindex modified messages:
558         for my $smsg (@$need_reindex) {
559                 my $new_smsg = bless {
560                         blob => $blob,
561                         raw_bytes => $bytes,
562                         num => $smsg->{num},
563                         mid => $smsg->{mid},
564                 }, 'PublicInbox::Smsg';
565                 my $sync = { autime => $smsg->{ds}, cotime => $smsg->{ts} };
566                 $new_smsg->populate($new_mime, $sync);
567                 do_idx($self, \$raw, $new_mime, $new_smsg);
568         }
569         $rewritten->{rewrites};
570 }
571
572 sub last_epoch_commit ($$;$) {
573         my ($self, $i, $cmt) = @_;
574         my $v = PublicInbox::Search::SCHEMA_VERSION();
575         $self->{mm}->last_commit_xap($v, $i, $cmt);
576 }
577
578 sub set_last_commits ($) { # this is NOT for ExtSearchIdx
579         my ($self) = @_;
580         defined(my $epoch_max = $self->{epoch_max}) or return;
581         my $last_commit = $self->{last_commit};
582         foreach my $i (0..$epoch_max) {
583                 defined(my $cmt = $last_commit->[$i]) or next;
584                 $last_commit->[$i] = undef;
585                 last_epoch_commit($self, $i, $cmt);
586         }
587 }
588
589 sub barrier_init {
590         my ($self, $n) = @_;
591         $self->{bnote} or return;
592         --$n;
593         my $barrier = { map { $_ => 1 } (0..$n) };
594 }
595
596 sub barrier_wait {
597         my ($self, $barrier) = @_;
598         my $bnote = $self->{bnote} or return;
599         my $r = $bnote->[0];
600         while (scalar keys %$barrier) {
601                 defined(my $l = readline($r)) or die "EOF on barrier_wait: $!";
602                 $l =~ /\Abarrier (\d+)/ or die "bad line on barrier_wait: $l";
603                 delete $barrier->{$1} or die "bad shard[$1] on barrier wait";
604         }
605 }
606
607 # public
608 sub checkpoint ($;$) {
609         my ($self, $wait) = @_;
610
611         if (my $im = $self->{im}) {
612                 if ($wait) {
613                         $im->barrier;
614                 } else {
615                         $im->checkpoint;
616                 }
617         }
618         my $shards = $self->{idx_shards};
619         if ($shards) {
620                 my $mm = $self->{mm};
621                 my $dbh = $mm->{dbh} if $mm;
622
623                 # SQLite msgmap data is second in importance
624                 $dbh->commit if $dbh;
625
626                 # SQLite overview is third
627                 $self->{oidx}->commit_lazy;
628
629                 # Now deal with Xapian
630                 if ($wait) {
631                         my $barrier = barrier_init($self, scalar @$shards);
632
633                         # each shard needs to issue a barrier command
634                         $_->shard_barrier for @$shards;
635
636                         # wait for each Xapian shard
637                         barrier_wait($self, $barrier);
638                 } else {
639                         $_->shard_commit for @$shards;
640                 }
641
642                 my $midx = $self->{midx}; # misc index
643                 $midx->commit_txn if $midx;
644
645                 # last_commit is special, don't commit these until
646                 # Xapian shards are done:
647                 $dbh->begin_work if $dbh;
648                 set_last_commits($self);
649                 if ($dbh) {
650                         $dbh->commit;
651                         $dbh->begin_work;
652                 }
653                 $midx->begin_txn if $midx;
654         }
655         $self->{total_bytes} += $self->{transact_bytes};
656         $self->{transact_bytes} = 0;
657 }
658
659 # issue a write barrier to ensure all data is visible to other processes
660 # and read-only ops.  Order of data importance is: git > SQLite > Xapian
661 # public
662 sub barrier { checkpoint($_[0], 1) };
663
664 # true if locked and active
665 sub active { !!$_[0]->{im} }
666
667 # public
668 sub done {
669         my ($self) = @_;
670         my $err = '';
671         if (my $im = delete $self->{im}) {
672                 eval { $im->done }; # PublicInbox::Import::done
673                 $err .= "import done: $@\n" if $@;
674         }
675         if (!$err) {
676                 eval { checkpoint($self) };
677                 $err .= "checkpoint: $@\n" if $@;
678         }
679         if (my $mm = delete $self->{mm}) {
680                 my $m = $err ? 'rollback' : 'commit';
681                 eval { $mm->{dbh}->$m };
682                 $err .= "msgmap $m: $@\n" if $@;
683         }
684         my $shards = delete $self->{idx_shards};
685         if ($shards) {
686                 for (@$shards) {
687                         eval { $_->shard_close };
688                         $err .= "shard close: $@\n" if $@;
689                 }
690         }
691         eval { $self->{oidx}->dbh_close };
692         $err .= "over close: $@\n" if $@;
693         delete $self->{midx};
694         delete $self->{bnote};
695         my $nbytes = $self->{total_bytes};
696         $self->{total_bytes} = 0;
697         $self->lock_release(!!$nbytes) if $shards;
698         $self->git->cleanup;
699         die $err if $err;
700 }
701
702 sub write_alternates ($$$) {
703         my ($info_dir, $mode, $out) = @_;
704         my $fh = File::Temp->new(TEMPLATE => 'alt-XXXXXXXX', DIR => $info_dir);
705         my $tmp = $fh->filename;
706         print $fh @$out or die "print $tmp: $!\n";
707         chmod($mode, $fh) or die "fchmod $tmp: $!\n";
708         close $fh or die "close $tmp $!\n";
709         my $alt = "$info_dir/alternates";
710         rename($tmp, $alt) or die "rename $tmp => $alt: $!\n";
711         $fh->unlink_on_destroy(0);
712 }
713
714 sub fill_alternates ($$) {
715         my ($self, $epoch) = @_;
716
717         my $pfx = "$self->{ibx}->{inboxdir}/git";
718         my $all = "$self->{ibx}->{inboxdir}/all.git";
719         PublicInbox::Import::init_bare($all) unless -d $all;
720         my $info_dir = "$all/objects/info";
721         my $alt = "$info_dir/alternates";
722         my (%alt, $new);
723         my $mode = 0644;
724         if (-e $alt) {
725                 open(my $fh, '<', $alt) or die "open < $alt: $!\n";
726                 $mode = (stat($fh))[2] & 07777;
727
728                 # we assign a sort score to every alternate and favor
729                 # the newest (highest numbered) one because loose objects
730                 # require scanning epochs and only the latest epoch is
731                 # expected to see loose objects
732                 my $score;
733                 my $other = 0; # in case admin adds non-epoch repos
734                 %alt = map {;
735                         if (m!\A\Q../../\E([0-9]+)\.git/objects\z!) {
736                                 $score = $1 + 0;
737                         } else {
738                                 $score = --$other;
739                         }
740                         $_ => $score;
741                 } split(/\n+/, do { local $/; <$fh> });
742         }
743
744         foreach my $i (0..$epoch) {
745                 my $dir = "../../git/$i.git/objects";
746                 if (!exists($alt{$dir}) && -d "$pfx/$i.git") {
747                         $alt{$dir} = $i;
748                         $new = 1;
749                 }
750         }
751         return unless $new;
752         write_alternates($info_dir, $mode,
753                 [join("\n", sort { $alt{$b} <=> $alt{$a} } keys %alt), "\n"]);
754 }
755
756 sub git_init {
757         my ($self, $epoch) = @_;
758         my $git_dir = "$self->{ibx}->{inboxdir}/git/$epoch.git";
759         PublicInbox::Import::init_bare($git_dir);
760         my @cmd = (qw/git config/, "--file=$git_dir/config",
761                         'include.path', '../../all.git/config');
762         PublicInbox::Import::run_die(\@cmd);
763         fill_alternates($self, $epoch);
764         $git_dir
765 }
766
767 sub importer {
768         my ($self) = @_;
769         my $im = $self->{im};
770         if ($im) {
771                 if ($im->{bytes_added} < $self->{rotate_bytes}) {
772                         return $im;
773                 } else {
774                         $self->{im} = undef;
775                         $im->done;
776                         $im = undef;
777                         $self->checkpoint;
778                         my $git_dir = $self->git_init(++$self->{epoch_max});
779                         my $git = PublicInbox::Git->new($git_dir);
780                         return $self->import_init($git, 0);
781                 }
782         }
783         my $epoch = 0;
784         my $max;
785         my $latest = $self->{ibx}->git_dir_latest(\$max);
786         if (defined $latest) {
787                 my $git = PublicInbox::Git->new($latest);
788                 my $packed_bytes = $git->packed_bytes;
789                 my $unpacked_bytes = $packed_bytes / $PACKING_FACTOR;
790
791                 if ($unpacked_bytes >= $self->{rotate_bytes}) {
792                         $epoch = $max + 1;
793                 } else {
794                         $self->{epoch_max} = $max;
795                         return $self->import_init($git, $packed_bytes);
796                 }
797         }
798         $self->{epoch_max} = $epoch;
799         $latest = $self->git_init($epoch);
800         $self->import_init(PublicInbox::Git->new($latest), 0);
801 }
802
803 sub import_init {
804         my ($self, $git, $packed_bytes, $tmp) = @_;
805         my $im = PublicInbox::Import->new($git, undef, undef, $self->{ibx});
806         $im->{bytes_added} = int($packed_bytes / $PACKING_FACTOR);
807         $im->{lock_path} = undef;
808         $im->{path_type} = 'v2';
809         $self->{im} = $im unless $tmp;
810         $im;
811 }
812
813 # XXX experimental
814 sub diff ($$$) {
815         my ($mid, $cur, $new) = @_;
816
817         my $ah = File::Temp->new(TEMPLATE => 'email-cur-XXXXXXXX', TMPDIR => 1);
818         print $ah $cur->as_string or die "print: $!";
819         $ah->flush or die "flush: $!";
820         PublicInbox::Import::drop_unwanted_headers($new);
821         my $bh = File::Temp->new(TEMPLATE => 'email-new-XXXXXXXX', TMPDIR => 1);
822         print $bh $new->as_string or die "print: $!";
823         $bh->flush or die "flush: $!";
824         my $cmd = [ qw(diff -u), $ah->filename, $bh->filename ];
825         print STDERR "# MID conflict <$mid>\n";
826         my $pid = spawn($cmd, undef, { 1 => 2 });
827         waitpid($pid, 0) == $pid or die "diff did not finish";
828 }
829
830 sub get_blob ($$) {
831         my ($self, $smsg) = @_;
832         if (my $im = $self->{im}) {
833                 my $msg = $im->cat_blob($smsg->{blob});
834                 return $msg if $msg;
835         }
836         # older message, should be in alternates
837         $self->{ibx}->msg_by_smsg($smsg);
838 }
839
840 sub content_exists ($$$) {
841         my ($self, $mime, $mid) = @_;
842         my $oidx = $self->{oidx};
843         my $chashes = content_hashes($mime);
844         my ($id, $prev);
845         while (my $smsg = $oidx->next_by_mid($mid, \$id, \$prev)) {
846                 my $msg = get_blob($self, $smsg);
847                 if (!defined($msg)) {
848                         warn "broken smsg for $mid\n";
849                         next;
850                 }
851                 my $cur = PublicInbox::Eml->new($msg);
852                 return 1 if content_matches($chashes, $cur);
853
854                 # XXX DEBUG_DIFF is experimental and may be removed
855                 diff($mid, $cur, $mime) if $ENV{DEBUG_DIFF};
856         }
857         undef;
858 }
859
860 sub atfork_child {
861         my ($self) = @_;
862         if (my $shards = $self->{idx_shards}) {
863                 $_->atfork_child foreach @$shards;
864         }
865         if (my $im = $self->{im}) {
866                 $im->atfork_child;
867         }
868         die "unexpected mm" if $self->{mm};
869         close $self->{bnote}->[0] or die "close bnote[0]: $!\n";
870         $self->{bnote}->[1];
871 }
872
873 sub reindex_checkpoint ($$) {
874         my ($self, $sync) = @_;
875
876         $self->git->async_wait_all;
877         $self->update_last_commit($sync);
878         ${$sync->{need_checkpoint}} = 0;
879         my $mm_tmp = $sync->{mm_tmp};
880         $mm_tmp->atfork_prepare if $mm_tmp;
881         die 'BUG: {im} during reindex' if $self->{im};
882         if ($self->{ibx_map}) {
883                 checkpoint($self, 1); # no need to release lock on pure index
884         } else {
885                 $self->done; # release lock
886         }
887
888         if (my $pr = $sync->{-opt}->{-progress}) {
889                 $pr->(sprintf($sync->{-regen_fmt}, ${$sync->{nr}}));
890         }
891
892         # allow -watch or -mda to write...
893         $self->idx_init($sync->{-opt}); # reacquire lock
894         $mm_tmp->atfork_parent if $mm_tmp;
895 }
896
897 sub index_oid { # cat_async callback
898         my ($bref, $oid, $type, $size, $arg) = @_;
899         my $self = $arg->{self};
900         local $self->{current_info} = "$self->{current_info} $oid";
901         return if $size == 0; # purged
902         my ($num, $mid0);
903         my $eml = PublicInbox::Eml->new($$bref);
904         my $mids = mids($eml);
905         my $chash = content_hash($eml);
906
907         if (scalar(@$mids) == 0) {
908                 warn "E: $oid has no Message-ID, skipping\n";
909                 return;
910         }
911
912         # {unindexed} is unlikely
913         if ((my $unindexed = $arg->{unindexed}) && scalar(@$mids) == 1) {
914                 $num = delete($unindexed->{$mids->[0]});
915                 if (defined $num) {
916                         $mid0 = $mids->[0];
917                         $self->{mm}->mid_set($num, $mid0);
918                         delete($arg->{unindexed}) if !keys(%$unindexed);
919                 }
920         }
921         if (!defined($num)) { # reuse if reindexing (or duplicates)
922                 my $oidx = $self->{oidx};
923                 for my $mid (@$mids) {
924                         ($num, $mid0) = $oidx->num_mid0_for_oid($oid, $mid);
925                         last if defined $num;
926                 }
927         }
928         $mid0 //= do { # is this a number we got before?
929                 $num = $arg->{mm_tmp}->num_for($mids->[0]);
930                 defined($num) ? $mids->[0] : undef;
931         };
932         if (!defined($num)) {
933                 for (my $i = $#$mids; $i >= 1; $i--) {
934                         $num = $arg->{mm_tmp}->num_for($mids->[$i]);
935                         if (defined($num)) {
936                                 $mid0 = $mids->[$i];
937                                 last;
938                         }
939                 }
940         }
941         if (defined($num)) {
942                 $arg->{mm_tmp}->num_delete($num);
943         } else { # never seen
944                 $num = $self->{mm}->mid_insert($mids->[0]);
945                 if (defined($num)) {
946                         $mid0 = $mids->[0];
947                 } else { # rare, try the rest of them, backwards
948                         for (my $i = $#$mids; $i >= 1; $i--) {
949                                 $num = $self->{mm}->mid_insert($mids->[$i]);
950                                 if (defined($num)) {
951                                         $mid0 = $mids->[$i];
952                                         last;
953                                 }
954                         }
955                 }
956         }
957         if (!defined($num)) {
958                 warn "E: $oid <", join('> <', @$mids), "> is a duplicate\n";
959                 return;
960         }
961         ++${$arg->{nr}};
962         my $smsg = bless {
963                 raw_bytes => $size,
964                 num => $num,
965                 blob => $oid,
966                 mid => $mid0,
967         }, 'PublicInbox::Smsg';
968         $smsg->populate($eml, $arg);
969         if (do_idx($self, $bref, $eml, $smsg)) {
970                 ${$arg->{need_checkpoint}} = 1;
971         }
972         ${$arg->{latest_cmt}} = $arg->{cur_cmt} // die 'BUG: {cur_cmt} missing';
973 }
974
975 # only update last_commit for $i on reindex iff newer than current
976 sub update_last_commit {
977         my ($self, $sync, $stk) = @_;
978         my $unit = $sync->{unit} // return;
979         my $latest_cmt = $stk ? $stk->{latest_cmt} : ${$sync->{latest_cmt}};
980         defined($latest_cmt) or return;
981         my $last = last_epoch_commit($self, $unit->{epoch});
982         if (defined $last && is_ancestor($self->git, $last, $latest_cmt)) {
983                 my @cmd = (qw(rev-list --count), "$last..$latest_cmt");
984                 chomp(my $n = $unit->{git}->qx(@cmd));
985                 return if $n ne '' && $n == 0;
986         }
987         last_epoch_commit($self, $unit->{epoch}, $latest_cmt);
988 }
989
990 sub last_commits {
991         my ($self, $sync) = @_;
992         my $heads = [];
993         for (my $i = $sync->{epoch_max}; $i >= 0; $i--) {
994                 $heads->[$i] = last_epoch_commit($self, $i);
995         }
996         $heads;
997 }
998
999 # returns a revision range for git-log(1)
1000 sub log_range ($$$) {
1001         my ($sync, $unit, $tip) = @_;
1002         my $opt = $sync->{-opt};
1003         my $pr = $opt->{-progress} if (($opt->{verbose} || 0) > 1);
1004         my $i = $unit->{epoch};
1005         my $cur = $sync->{ranges}->[$i] or do {
1006                 $pr->("$i.git indexing all of $tip\n") if $pr;
1007                 return $tip; # all of it
1008         };
1009
1010         # fast equality check to avoid (v)fork+execve overhead
1011         if ($cur eq $tip) {
1012                 $sync->{ranges}->[$i] = undef;
1013                 return;
1014         }
1015
1016         my $range = "$cur..$tip";
1017         $pr->("$i.git checking contiguity... ") if $pr;
1018         my $git = $unit->{git};
1019         if (is_ancestor($sync->{self}->git, $cur, $tip)) { # common case
1020                 $pr->("OK\n") if $pr;
1021                 my $n = $git->qx(qw(rev-list --count), $range);
1022                 chomp($n);
1023                 if ($n == 0) {
1024                         $sync->{ranges}->[$i] = undef;
1025                         $pr->("$i.git has nothing new\n") if $pr;
1026                         return; # nothing to do
1027                 }
1028                 $pr->("$i.git has $n changes since $cur\n") if $pr;
1029         } else {
1030                 $pr->("FAIL\n") if $pr;
1031                 warn <<"";
1032 discontiguous range: $range
1033 Rewritten history? (in $git->{git_dir})
1034
1035                 chomp(my $base = $git->qx('merge-base', $tip, $cur));
1036                 if ($base) {
1037                         $range = "$base..$tip";
1038                         warn "found merge-base: $base\n"
1039                 } else {
1040                         $range = $tip;
1041                         warn "discarding history at $cur\n";
1042                 }
1043                 warn <<"";
1044 reindexing $git->{git_dir}
1045 starting at $range
1046
1047                 # $cur^0 may no longer exist if pruned by git
1048                 if ($git->qx(qw(rev-parse -q --verify), "$cur^0")) {
1049                         $unit->{unindex_range} = "$base..$cur";
1050                 } elsif ($base && $git->qx(qw(rev-parse -q --verify), $base)) {
1051                         $unit->{unindex_range} = "$base..";
1052                 } else {
1053                         warn "W: unable to unindex before $range\n";
1054                 }
1055         }
1056         $range;
1057 }
1058
1059 # overridden by ExtSearchIdx
1060 sub artnum_max { $_[0]->{mm}->num_highwater }
1061
1062 sub sync_prepare ($$) {
1063         my ($self, $sync) = @_;
1064         $sync->{ranges} = sync_ranges($self, $sync);
1065         my $pr = $sync->{-opt}->{-progress};
1066         my $regen_max = 0;
1067         my $head = $sync->{ibx}->{ref_head} || 'HEAD';
1068         my $pfx;
1069         if ($pr) {
1070                 ($pfx) = ($sync->{ibx}->{inboxdir} =~ m!([^/]+)\z!g);
1071                 $pfx //= $sync->{ibx}->{inboxdir};
1072         }
1073
1074         # reindex stops at the current heads and we later rerun index_sync
1075         # without {reindex}
1076         my $reindex_heads = $self->last_commits($sync) if $sync->{reindex};
1077
1078         if ($sync->{max_size} = $sync->{-opt}->{max_size}) {
1079                 $sync->{index_oid} = $self->can('index_oid');
1080         }
1081         for (my $i = $sync->{epoch_max}; $i >= 0; $i--) {
1082                 my $git_dir = $sync->{ibx}->git_dir_n($i);
1083                 -d $git_dir or next; # missing epochs are fine
1084                 my $git = PublicInbox::Git->new($git_dir);
1085                 my $unit = { git => $git, epoch => $i };
1086                 if ($reindex_heads) {
1087                         $head = $reindex_heads->[$i] or next;
1088                 }
1089                 chomp(my $tip = $git->qx(qw(rev-parse -q --verify), $head));
1090                 next if $?; # new repo
1091
1092                 my $range = log_range($sync, $unit, $tip) or next;
1093                 # can't use 'rev-list --count' if we use --diff-filter
1094                 $pr->("$pfx $i.git counting $range ... ") if $pr;
1095                 # Don't bump num_highwater on --reindex by using {D}.
1096                 # We intentionally do NOT use {D} in the non-reindex case
1097                 # because we want NNTP article number gaps from unindexed
1098                 # messages to show up in mirrors, too.
1099                 $sync->{D} //= $sync->{reindex} ? {} : undef; # OID_BIN => NR
1100                 my $stk = log2stack($sync, $git, $range);
1101                 return 0 if $sync->{quit};
1102                 my $nr = $stk ? $stk->num_records : 0;
1103                 $pr->("$nr\n") if $pr;
1104                 $unit->{stack} = $stk; # may be undef
1105                 unshift @{$sync->{todo}}, $unit;
1106                 $regen_max += $nr;
1107         }
1108         return 0 if $sync->{quit};
1109
1110         # XXX this should not happen unless somebody bypasses checks in
1111         # our code and blindly injects "d" file history into git repos
1112         if (my @leftovers = keys %{delete($sync->{D}) // {}}) {
1113                 warn('W: unindexing '.scalar(@leftovers)." leftovers\n");
1114                 local $self->{current_info} = 'leftover ';
1115                 my $unindex_oid = $self->can('unindex_oid');
1116                 for my $oid (@leftovers) {
1117                         last if $sync->{quit};
1118                         $oid = unpack('H*', $oid);
1119                         my $req = { %$sync, oid => $oid };
1120                         $self->git->cat_async($oid, $unindex_oid, $req);
1121                 }
1122                 $self->git->cat_async_wait;
1123         }
1124         return 0 if $sync->{quit};
1125         if (!$regen_max) {
1126                 $sync->{-regen_fmt} = "%u/?\n";
1127                 return 0;
1128         }
1129
1130         # reindex should NOT see new commits anymore, if we do,
1131         # it's a problem and we need to notice it via die()
1132         my $pad = length($regen_max) + 1;
1133         $sync->{-regen_fmt} = "% ${pad}u/$regen_max\n";
1134         $sync->{nr} = \(my $nr = 0);
1135         return -1 if $sync->{reindex};
1136         $regen_max + $self->artnum_max || 0;
1137 }
1138
1139 sub unindex_oid_aux ($$$) {
1140         my ($self, $oid, $mid) = @_;
1141         my @removed = $self->{oidx}->remove_oid($oid, $mid);
1142         for my $num (@removed) {
1143                 my $idx = idx_shard($self, $num);
1144                 $idx->shard_remove($num);
1145         }
1146 }
1147
1148 sub unindex_oid ($$;$) { # git->cat_async callback
1149         my ($bref, $oid, $type, $size, $sync) = @_;
1150         my $self = $sync->{self};
1151         local $self->{current_info} = "$self->{current_info} $oid";
1152         my $unindexed = $sync->{in_unindex} ? $sync->{unindexed} : undef;
1153         my $mm = $self->{mm};
1154         my $mids = mids(PublicInbox::Eml->new($bref));
1155         undef $$bref;
1156         my $oidx = $self->{oidx};
1157         foreach my $mid (@$mids) {
1158                 my %gone;
1159                 my ($id, $prev);
1160                 while (my $smsg = $oidx->next_by_mid($mid, \$id, \$prev)) {
1161                         $gone{$smsg->{num}} = 1 if $oid eq $smsg->{blob};
1162                 }
1163                 my $n = scalar(keys(%gone)) or next;
1164                 if ($n > 1) {
1165                         warn "BUG: multiple articles linked to $oid\n",
1166                                 join(',',sort keys %gone), "\n";
1167                 }
1168                 foreach my $num (keys %gone) {
1169                         if ($unindexed) {
1170                                 my $mid0 = $mm->mid_for($num);
1171                                 $unindexed->{$mid0} = $num;
1172                         }
1173                         $mm->num_delete($num);
1174                 }
1175                 unindex_oid_aux($self, $oid, $mid);
1176         }
1177 }
1178
1179 sub git { $_[0]->{ibx}->git }
1180
1181 # this is rare, it only happens when we get discontiguous history in
1182 # a mirror because the source used -purge or -edit
1183 sub unindex_todo ($$$) {
1184         my ($self, $sync, $unit) = @_;
1185         my $unindex_range = delete($unit->{unindex_range}) // return;
1186         my $unindexed = $sync->{unindexed} //= {}; # $mid0 => $num
1187         my $before = scalar keys %$unindexed;
1188         # order does not matter, here:
1189         my $fh = $unit->{git}->popen(qw(log --raw -r --no-notes --no-color
1190                                 --no-abbrev --no-renames), $unindex_range);
1191         local $sync->{in_unindex} = 1;
1192         my $unindex_oid = $self->can('unindex_oid');
1193         while (<$fh>) {
1194                 /\A:\d{6} 100644 $OID ($OID) [AM]\tm$/o or next;
1195                 $self->git->cat_async($1, $unindex_oid, { %$sync, oid => $1 });
1196         }
1197         close $fh or die "git log failed: \$?=$?";
1198         $self->git->cat_async_wait;
1199
1200         return unless $sync->{-opt}->{prune};
1201         my $after = scalar keys %$unindexed;
1202         return if $before == $after;
1203
1204         # ensure any blob can not longer be accessed via dumb HTTP
1205         PublicInbox::Import::run_die(['git',
1206                 "--git-dir=$unit->{git}->{git_dir}",
1207                 qw(-c gc.reflogExpire=now gc --prune=all --quiet)]);
1208 }
1209
1210 sub sync_ranges ($$) {
1211         my ($self, $sync) = @_;
1212         my $reindex = $sync->{reindex};
1213         return $self->last_commits($sync) unless $reindex;
1214         return [] if ref($reindex) ne 'HASH';
1215
1216         my $ranges = $reindex->{from}; # arrayref;
1217         if (ref($ranges) ne 'ARRAY') {
1218                 die 'BUG: $reindex->{from} not an ARRAY';
1219         }
1220         $ranges;
1221 }
1222
1223 sub index_xap_only { # git->cat_async callback
1224         my ($bref, $oid, $type, $size, $smsg) = @_;
1225         my $self = $smsg->{self};
1226         my $idx = idx_shard($self, $smsg->{num});
1227         $smsg->{raw_bytes} = $size;
1228         $idx->index_raw($bref, undef, $smsg);
1229         $self->{transact_bytes} += $size;
1230 }
1231
1232 sub index_xap_step ($$$;$) {
1233         my ($self, $sync, $beg, $step) = @_;
1234         my $end = $sync->{art_end};
1235         return if $beg > $end; # nothing to do
1236
1237         $step //= $self->{shards};
1238         my $ibx = $self->{ibx};
1239         if (my $pr = $sync->{-opt}->{-progress}) {
1240                 $pr->("Xapian indexlevel=$ibx->{indexlevel} ".
1241                         "$beg..$end (% $step)\n");
1242         }
1243         for (my $num = $beg; $num <= $end; $num += $step) {
1244                 last if $sync->{quit};
1245                 my $smsg = $ibx->over->get_art($num) or next;
1246                 $smsg->{self} = $self;
1247                 $ibx->git->cat_async($smsg->{blob}, \&index_xap_only, $smsg);
1248                 if ($self->{transact_bytes} >= $self->{batch_bytes}) {
1249                         ${$sync->{nr}} = $num;
1250                         reindex_checkpoint($self, $sync);
1251                 }
1252         }
1253 }
1254
1255 sub index_todo ($$$) {
1256         my ($self, $sync, $unit) = @_;
1257         return if $sync->{quit};
1258         unindex_todo($self, $sync, $unit);
1259         my $stk = delete($unit->{stack}) or return;
1260         my $all = $self->git;
1261         my $index_oid = $self->can('index_oid');
1262         my $unindex_oid = $self->can('unindex_oid');
1263         my $pfx;
1264         if ($unit->{git}->{git_dir} =~ m!/([^/]+)/git/([0-9]+\.git)\z!) {
1265                 $pfx = "$1 $2"; # v2
1266         } else { # v1
1267                 ($pfx) = ($unit->{git}->{git_dir} =~ m!/([^/]+)\z!g);
1268                 $pfx //= $unit->{git}->{git_dir};
1269         }
1270         local $self->{current_info} = "$pfx ";
1271         local $sync->{latest_cmt} = \(my $latest_cmt);
1272         local $sync->{unit} = $unit;
1273         while (my ($f, $at, $ct, $oid, $cmt) = $stk->pop_rec) {
1274                 if ($sync->{quit}) {
1275                         warn "waiting to quit...\n";
1276                         $all->async_wait_all;
1277                         $self->update_last_commit($sync);
1278                         return;
1279                 }
1280                 my $req = {
1281                         %$sync,
1282                         autime => $at,
1283                         cotime => $ct,
1284                         oid => $oid,
1285                         cur_cmt => $cmt
1286                 };
1287                 if ($f eq 'm') {
1288                         if ($sync->{max_size}) {
1289                                 $all->check_async($oid, \&check_size, $req);
1290                         } else {
1291                                 $all->cat_async($oid, $index_oid, $req);
1292                         }
1293                 } elsif ($f eq 'd') {
1294                         $all->cat_async($oid, $unindex_oid, $req);
1295                 }
1296                 if (${$sync->{need_checkpoint}}) {
1297                         reindex_checkpoint($self, $sync);
1298                 }
1299         }
1300         $all->async_wait_all;
1301         $self->update_last_commit($sync, $stk);
1302 }
1303
1304 sub xapian_only {
1305         my ($self, $opt, $sync, $art_beg) = @_;
1306         my $seq = $opt->{sequential_shard};
1307         $art_beg //= 0;
1308         local $self->{parallel} = 0 if $seq;
1309         $self->idx_init($opt); # acquire lock
1310         if (my $art_end = $self->{ibx}->mm->max) {
1311                 $sync //= {
1312                         need_checkpoint => \(my $bool = 0),
1313                         -opt => $opt,
1314                         self => $self,
1315                         nr => \(my $nr = 0),
1316                         -regen_fmt => "%u/?\n",
1317                 };
1318                 $sync->{art_end} = $art_end;
1319                 if ($seq || !$self->{parallel}) {
1320                         my $shard_end = $self->{shards} - 1;
1321                         for my $i (0..$shard_end) {
1322                                 last if $sync->{quit};
1323                                 index_xap_step($self, $sync, $art_beg + $i);
1324                                 if ($i != $shard_end) {
1325                                         reindex_checkpoint($self, $sync);
1326                                 }
1327                         }
1328                 } else { # parallel (maybe)
1329                         index_xap_step($self, $sync, $art_beg, 1);
1330                 }
1331         }
1332         $self->git->cat_async_wait;
1333         $self->done;
1334 }
1335
1336 # public, called by public-inbox-index
1337 sub index_sync {
1338         my ($self, $opt) = @_;
1339         $opt //= {};
1340         return xapian_only($self, $opt) if $opt->{xapian_only};
1341
1342         my $pr = $opt->{-progress};
1343         my $epoch_max;
1344         my $latest = $self->{ibx}->git_dir_latest(\$epoch_max);
1345         return unless defined $latest;
1346
1347         my $seq = $opt->{sequential_shard};
1348         my $art_beg; # the NNTP article number we start xapian_only at
1349         my $idxlevel = $self->{ibx}->{indexlevel};
1350         local $self->{ibx}->{indexlevel} = 'basic' if $seq;
1351
1352         $self->idx_init($opt); # acquire lock
1353         fill_alternates($self, $epoch_max);
1354         $self->{oidx}->rethread_prepare($opt);
1355         my $sync = {
1356                 need_checkpoint => \(my $bool = 0),
1357                 reindex => $opt->{reindex},
1358                 -opt => $opt,
1359                 self => $self,
1360                 ibx => $self->{ibx},
1361                 epoch_max => $epoch_max,
1362         };
1363         my $quit = PublicInbox::SearchIdx::quit_cb($sync);
1364         local $SIG{QUIT} = $quit;
1365         local $SIG{INT} = $quit;
1366         local $SIG{TERM} = $quit;
1367
1368         if (sync_prepare($self, $sync)) {
1369                 # tmp_clone seems to fail if inside a transaction, so
1370                 # we rollback here (because we opened {mm} for reading)
1371                 # Note: we do NOT rely on DBI transactions for atomicity;
1372                 # only for batch performance.
1373                 $self->{mm}->{dbh}->rollback;
1374                 $self->{mm}->{dbh}->begin_work;
1375                 $sync->{mm_tmp} =
1376                         $self->{mm}->tmp_clone($self->{ibx}->{inboxdir});
1377
1378                 # xapian_only works incrementally w/o --reindex
1379                 if ($seq && !$opt->{reindex}) {
1380                         $art_beg = $sync->{mm_tmp}->max || -1;
1381                         $art_beg++;
1382                 }
1383         }
1384         # work forwards through history
1385         index_todo($self, $sync, $_) for @{delete($sync->{todo}) // []};
1386         $self->{oidx}->rethread_done($opt) unless $sync->{quit};
1387         $self->done;
1388
1389         if (my $nr = $sync->{nr}) {
1390                 my $pr = $sync->{-opt}->{-progress};
1391                 $pr->('all.git '.sprintf($sync->{-regen_fmt}, $$nr)) if $pr;
1392         }
1393
1394         my $quit_warn;
1395         # deal with Xapian shards sequentially
1396         if ($seq && delete($sync->{mm_tmp})) {
1397                 if ($sync->{quit}) {
1398                         $quit_warn = 1;
1399                 } else {
1400                         $self->{ibx}->{indexlevel} = $idxlevel;
1401                         xapian_only($self, $opt, $sync, $art_beg);
1402                         $quit_warn = 1 if $sync->{quit};
1403                 }
1404         }
1405
1406         # --reindex on the command-line
1407         if (!$sync->{quit} && $opt->{reindex} &&
1408                         !ref($opt->{reindex}) && $idxlevel ne 'basic') {
1409                 $self->lock_acquire;
1410                 my $s0 = PublicInbox::SearchIdx->new($self->{ibx}, 0, 0);
1411                 if (my $xdb = $s0->idx_acquire) {
1412                         my $n = $xdb->get_metadata('has_threadid');
1413                         $xdb->set_metadata('has_threadid', '1') if $n ne '1';
1414                 }
1415                 $s0->idx_release;
1416                 $self->lock_release;
1417         }
1418
1419         # reindex does not pick up new changes, so we rerun w/o it:
1420         if ($opt->{reindex} && !$sync->{quit}) {
1421                 my %again = %$opt;
1422                 $sync = undef;
1423                 delete @again{qw(rethread reindex -skip_lock)};
1424                 index_sync($self, \%again);
1425                 $opt->{quit} = $again{quit}; # propagate to caller
1426         }
1427         warn <<EOF if $quit_warn;
1428 W: interrupted, --xapian-only --reindex required upon restart
1429 EOF
1430 }
1431
1432 1;