]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/LeiXSearch.pm
imap+nntp: share COMPRESS implementation
[public-inbox.git] / lib / PublicInbox / LeiXSearch.pm
1 # Copyright (C) all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
3
4 # Combine any combination of PublicInbox::Search,
5 # PublicInbox::ExtSearch, and PublicInbox::LeiSearch objects
6 # into one Xapian DB
7 package PublicInbox::LeiXSearch;
8 use strict;
9 use v5.10.1;
10 use parent qw(PublicInbox::LeiSearch PublicInbox::IPC);
11 use PublicInbox::DS qw(now);
12 use File::Temp 0.19 (); # 0.19 for ->newdir
13 use File::Spec ();
14 use PublicInbox::Search qw(xap_terms);
15 use PublicInbox::Spawn qw(popen_rd spawn which);
16 use PublicInbox::MID qw(mids);
17 use PublicInbox::Smsg;
18 use PublicInbox::AutoReap;
19 use PublicInbox::Eml;
20 use PublicInbox::LEI;
21 use Fcntl qw(SEEK_SET F_SETFL O_APPEND O_RDWR);
22 use PublicInbox::ContentHash qw(git_sha);
23 use POSIX qw(strftime);
24
25 sub new {
26         my ($class) = @_;
27         PublicInbox::Search::load_xapian();
28         bless {
29                 qp_flags => $PublicInbox::Search::QP_FLAGS |
30                                 PublicInbox::Search::FLAG_PURE_NOT(),
31         }, $class
32 }
33
34 sub attach_external {
35         my ($self, $ibxish) = @_; # ibxish = ExtSearch or Inbox
36         my $desc = $ibxish->{inboxdir} // $ibxish->{topdir};
37         my $srch = $ibxish->search //
38                 return warn("$desc not indexed for Xapian ($@ $!)\n");
39         my @shards = $srch->xdb_shards_flat or
40                 return warn("$desc has no Xapian shards\n");
41
42         if (delete $self->{xdb}) { # XXX: do we need this?
43                 # clobber existing {xdb} if amending
44                 my $expect = delete $self->{nshard};
45                 my $shards = delete $self->{shards_flat};
46                 scalar(@$shards) == $expect or die
47                         "BUG: {nshard}$expect != shards=".scalar(@$shards);
48
49                 my $prev = {};
50                 for my $old_ibxish (@{$self->{shard2ibx}}) {
51                         next if $prev == $old_ibxish;
52                         $prev = $old_ibxish;
53                         my @shards = $old_ibxish->search->xdb_shards_flat;
54                         push @{$self->{shards_flat}}, @shards;
55                 }
56                 my $nr = scalar(@{$self->{shards_flat}});
57                 $nr == $expect or die
58                         "BUG: reloaded $nr shards, expected $expect"
59         }
60         push @{$self->{shards_flat}}, @shards;
61         push(@{$self->{shard2ibx}}, $ibxish) for (@shards);
62 }
63
64 # returns a list of local inboxes (or count in scalar context)
65 sub locals { @{$_[0]->{locals} // []} }
66
67 sub remotes { @{$_[0]->{remotes} // []} }
68
69 # called by PublicInbox::Search::xdb (usually via ->mset)
70 sub xdb_shards_flat { @{$_[0]->{shards_flat} // []} }
71
72 sub _mitem_kw { # retry_reopen callback
73         my ($srch, $smsg, $mitem, $flagged) = @_;
74         my $doc = $mitem->get_document;
75         my $kw = xap_terms('K', $doc);
76         $kw->{flagged} = 1 if $flagged;
77         my @L = xap_terms('L', $doc);
78         # we keep the empty {kw} array here to prevent expensive work in
79         # ->xsmsg_vmd, _unbless_smsg will clobber it iff it's empty
80         $smsg->{kw} = [ sort keys %$kw ];
81         $smsg->{L} = \@L if scalar(@L);
82 }
83
84 sub mitem_kw ($$$;$) {
85         my ($srch, $smsg, $mitem, $flagged) = @_;
86         $srch->retry_reopen(\&_mitem_kw, $smsg, $mitem, $flagged);
87 }
88
89 # like over->get_art
90 sub smsg_for {
91         my ($self, $mitem) = @_;
92         # cf. https://trac.xapian.org/wiki/FAQ/MultiDatabaseDocumentID
93         my $nshard = $self->{nshard};
94         my $docid = $mitem->get_docid;
95         my $shard = ($docid - 1) % $nshard;
96         my $num = int(($docid - 1) / $nshard) + 1;
97         my $ibx = $self->{shard2ibx}->[$shard];
98         my $smsg = $ibx->over->get_art($num);
99         return if $smsg->{bytes} == 0; # external message
100         if ($ibx->can('msg_keywords')) {
101                 mitem_kw($self, $smsg, $mitem);
102         }
103         $smsg;
104 }
105
106 sub recent {
107         my ($self, $qstr, $opt) = @_;
108         $opt //= {};
109         $opt->{relevance} //= -2;
110         $self->mset($qstr //= 'z:1..', $opt);
111 }
112
113 sub over {}
114
115 sub _check_mset_limit ($$$) {
116         my ($lei, $desc, $mset) = @_;
117         return if defined($lei->{opt}->{limit}); # user requested limit
118         my $est = $mset->get_matches_estimated;
119         my $tot = $lei->{mset_opt}->{total};
120         $est > $tot and $lei->qerr(<<"");
121 # $desc estimated matches ($est) exceeds default --limit=$tot
122
123 }
124
125 sub _mset_more ($$) {
126         my ($mset, $mo) = @_;
127         my $size = $mset->size;
128         $size >= $mo->{limit} && (($mo->{offset} += $size) < $mo->{total});
129 }
130
131 # $startq will EOF when do_augment is done augmenting and allow
132 # query_combined_mset and query_thread_mset to proceed.
133 sub wait_startq ($) {
134         my ($lei) = @_;
135         my $startq = delete $lei->{startq} or return;
136         while (1) {
137                 my $n = sysread($startq, my $do_augment_done, 1);
138                 if (defined $n) {
139                         return if $n == 0; # no MUA
140                         if ($do_augment_done eq 'q') {
141                                 $lei->{opt}->{quiet} = 1;
142                                 delete $lei->{opt}->{verbose};
143                                 delete $lei->{-progress};
144                         } else {
145                                 die "BUG: do_augment_done=`$do_augment_done'";
146                         }
147                         return;
148                 }
149                 die "wait_startq: $!" unless $!{EINTR};
150         }
151 }
152
153 sub mset_progress {
154         my $lei = shift;
155         return if $lei->{early_mua} || !$lei->{-progress};
156         if ($lei->{pkt_op_p}) {
157                 $lei->{pkt_op_p}->pkt_do('mset_progress', @_);
158         } else { # single lei-daemon consumer
159                 my ($desc, $mset_size, $mset_total_est) = @_;
160                 $lei->{-mset_total} += $mset_size if $mset_total_est ne '?';
161                 $lei->qerr("# $desc $mset_size/$mset_total_est");
162         }
163 }
164
165 sub l2m_progress {
166         my ($lei, $nr_write, $nr_seen) = @_;
167         $lei->{-nr_write} += $nr_write;
168         $lei->{-nr_seen} += $nr_seen;
169 }
170
171 sub query_one_mset { # for --threads and l2m w/o sort
172         my ($self, $ibxish) = @_;
173         local $0 = "$0 query_one_mset";
174         my $lei = $self->{lei};
175         my ($srch, $over) = ($ibxish->search, $ibxish->over);
176         my $dir = $ibxish->{inboxdir} // $ibxish->{topdir};
177         return warn("$dir not indexed by Xapian\n") unless ($srch && $over);
178         bless $srch, 'PublicInbox::LeiSearch'; # for ->qparse_new
179         my $mo = { %{$lei->{mset_opt}} }; # copy
180         my $mset;
181         my $each_smsg = $lei->{ovv}->ovv_each_smsg_cb($lei);
182         my $can_kw = !!$ibxish->can('msg_keywords');
183         my $threads = $lei->{opt}->{threads} // 0;
184         my $fl = $threads > 1 ? 1 : undef;
185         my $lss = $lei->{lss};
186         my $maxk = "external.$dir.maxuid";
187         my $stop_at = $lss ? $lss->{-cfg}->{$maxk} : undef;
188         if (defined $stop_at) {
189                 ref($stop_at) and
190                         return warn("$maxk=$stop_at has multiple values\n");
191                 ($stop_at =~ /[^0-9]/) and
192                         return warn("$maxk=$stop_at not numeric\n");
193         }
194         my $first_ids;
195         do {
196                 $mset = $srch->mset($mo->{qstr}, $mo);
197                 mset_progress($lei, $dir, $mo->{offset} + $mset->size,
198                                 $mset->get_matches_estimated);
199                 wait_startq($lei); # wait for keyword updates
200                 my $ids = $srch->mset_to_artnums($mset, $mo);
201                 @$ids = grep { $_ > $stop_at } @$ids if defined($stop_at);
202                 my $i = 0;
203                 if ($threads) {
204                         # copy $ids if $lss since over->expand_thread
205                         # shifts @{$ctx->{ids}}
206                         $first_ids = [ @$ids ] if $lss;
207                         my $ctx = { ids => $ids };
208                         my %n2item = map { ($ids->[$i++], $_) } $mset->items;
209                         while ($over->expand_thread($ctx)) {
210                                 for my $n (@{$ctx->{xids}}) {
211                                         my $smsg = $over->get_art($n) or next;
212                                         my $mitem = delete $n2item{$n};
213                                         next if $smsg->{bytes} == 0;
214                                         if ($mitem && $can_kw) {
215                                                 mitem_kw($srch, $smsg, $mitem,
216                                                         $fl);
217                                         } elsif ($mitem && $fl) {
218                                                 # call ->xsmsg_vmd, later
219                                                 $smsg->{lei_q_tt_flagged} = 1;
220                                         }
221                                         $each_smsg->($smsg, $mitem);
222                                 }
223                                 @{$ctx->{xids}} = ();
224                         }
225                 } else {
226                         $first_ids = $ids;
227                         my @items = $mset->items;
228                         for my $n (@$ids) {
229                                 my $mitem = $items[$i++];
230                                 my $smsg = $over->get_art($n) or next;
231                                 next if $smsg->{bytes} == 0;
232                                 mitem_kw($srch, $smsg, $mitem, $fl) if $can_kw;
233                                 $each_smsg->($smsg, $mitem);
234                         }
235                 }
236         } while (_mset_more($mset, $mo));
237         _check_mset_limit($lei, $dir, $mset);
238         if ($lss && scalar(@$first_ids)) {
239                 undef $stop_at;
240                 my $max = $first_ids->[0];
241                 $lss->cfg_set($maxk, $max);
242                 undef $lss;
243         }
244         undef $each_smsg; # may commit
245         $lei->{ovv}->ovv_atexit_child($lei);
246 }
247
248 sub query_combined_mset { # non-parallel for non-"--threads" users
249         my ($self) = @_;
250         local $0 = "$0 query_combined_mset";
251         my $lei = $self->{lei};
252         my $mo = { %{$lei->{mset_opt}} };
253         my $mset;
254         for my $loc (locals($self)) {
255                 attach_external($self, $loc);
256         }
257         my $each_smsg = $lei->{ovv}->ovv_each_smsg_cb($lei);
258         do {
259                 $mset = $self->mset($mo->{qstr}, $mo);
260                 mset_progress($lei, 'xsearch', $mo->{offset} + $mset->size,
261                                 $mset->get_matches_estimated);
262                 wait_startq($lei); # wait for keyword updates
263                 for my $mitem ($mset->items) {
264                         my $smsg = smsg_for($self, $mitem) or next;
265                         $each_smsg->($smsg, $mitem);
266                 }
267         } while (_mset_more($mset, $mo));
268         _check_mset_limit($lei, 'xsearch', $mset);
269         undef $each_smsg; # may commit
270         $lei->{ovv}->ovv_atexit_child($lei);
271 }
272
273 sub _smsg_fill ($$) {
274         my ($smsg, $eml) = @_;
275         $smsg->populate($eml);
276         $smsg->parse_references($eml, mids($eml));
277         $smsg->{$_} //= '' for qw(from to cc ds subject references mid);
278         delete @$smsg{qw(From Subject -ds -ts)};
279 }
280
281 sub each_remote_eml { # callback for MboxReader->mboxrd
282         my ($eml, $self, $lei, $each_smsg) = @_;
283         my $xoids = $lei->{ale}->xoids_for($eml, 1);
284         my $smsg = bless {}, 'PublicInbox::Smsg';
285         if ($self->{import_sto} && !$xoids) {
286                 my ($res, $kw) = $self->{import_sto}->wq_do('add_eml', $eml);
287                 if (ref($res) eq ref($smsg)) { # totally new message
288                         $smsg = $res;
289                         $self->{-sto_imported} = 1;
290                 }
291                 $smsg->{kw} = $kw; # short-circuit xsmsg_vmd
292         }
293         $smsg->{blob} //= $xoids ? (keys(%$xoids))[0]
294                                 : $lei->git_oid($eml)->hexdigest;
295         _smsg_fill($smsg, $eml);
296         wait_startq($lei);
297         my $nr = ++$lei->{-nr_remote_eml}; # needed for lss->cfg_set
298         if ($lei->{-progress}) {
299                 my $now = now();
300                 my $next = $lei->{-next_progress} //= ($now + 1);
301                 if ($now > $next) {
302                         $lei->{-next_progress} = $now + 1;
303                         mset_progress($lei, $lei->{-current_url}, $nr, '?');
304                 }
305         }
306         $each_smsg->($smsg, undef, $eml);
307 }
308
309 sub fudge_qstr_time ($$$) {
310         my ($lei, $uri, $qstr) = @_;
311         return ($qstr, undef) unless $lei->{lss};
312         my $cfg = $lei->{lss}->{-cfg} // die 'BUG: no lss->{-cfg}';
313         my $cfg_key = "external.$uri.lastresult";
314         my $lr = $cfg->{$cfg_key} or return ($qstr, $cfg_key);
315         if ($lr !~ /\A\-?[0-9]+\z/) {
316                 $lei->child_error(0,
317                         "$cfg->{-f}: $cfg_key=$lr not an integer, ignoring");
318                 return ($qstr, $cfg_key);
319         }
320         my $rft = $lei->{opt}->{'remote-fudge-time'};
321         if ($rft && $rft !~ /\A-?[0-9]+\z/) {
322                 my @t = $lei->{lss}->git->date_parse($rft);
323                 my $diff = time - $t[0];
324                 $lei->qerr("# $rft => $diff seconds");
325                 $rft = $diff;
326         }
327         $lr -= ($rft || (48 * 60 * 60));
328         $lei->qerr("# $uri limiting to ".
329                 strftime('%Y-%m-%d %k:%M %z', localtime($lr)). ' and newer');
330         # this should really be rt: (received-time), but no stable
331         # public-inbox releases support it, yet.
332         my $dt = 'dt:'.strftime('%Y%m%d%H%M%S', gmtime($lr)).'..';
333         if ($qstr =~ /\S/) {
334                 substr($qstr, 0, 0, '(');
335                 $qstr .= ') AND ';
336         }
337         ($qstr .= $dt, $cfg_key);
338 }
339
340 sub query_remote_mboxrd {
341         my ($self, $uris) = @_;
342         local $0 = "$0 query_remote_mboxrd";
343         local $SIG{TERM} = sub { exit(0) }; # for DESTROY (File::Temp, $reap)
344         my $lei = $self->{lei};
345         my $opt = $lei->{opt};
346         chomp(my $qstr = $lei->{mset_opt}->{qstr});
347         $qstr =~ s/[ \n\t]+/ /sg; # make URLs less ugly
348         my @qform = (x => 'm');
349         push(@qform, t => 1) if $opt->{threads};
350         my $verbose = $opt->{verbose};
351         my $reap_tail;
352         my $cerr = File::Temp->new(TEMPLATE => 'curl.err-XXXX', TMPDIR => 1);
353         fcntl($cerr, F_SETFL, O_APPEND|O_RDWR) or warn "set O_APPEND: $!";
354         my $rdr = { 2 => $cerr };
355         if ($verbose) {
356                 # spawn a process to force line-buffering, otherwise curl
357                 # will write 1 character at-a-time and parallel outputs
358                 # mmmaaayyy llloookkk llliiikkkeee ttthhhiiisss
359                 my $o = { 1 => $lei->{2}, 2 => $lei->{2} };
360                 my $pid = spawn(['tail', '-f', $cerr->filename], undef, $o);
361                 $reap_tail = PublicInbox::AutoReap->new($pid);
362         }
363         my $curl = PublicInbox::LeiCurl->new($lei, $self->{curl}) or return;
364         push @$curl, '-s', '-d', '';
365         my $each_smsg = $lei->{ovv}->ovv_each_smsg_cb($lei);
366         $self->{import_sto} = $lei->{sto} if $lei->{opt}->{'import-remote'};
367         for my $uri (@$uris) {
368                 $lei->{-current_url} = $uri->as_string;
369                 $lei->{-nr_remote_eml} = 0;
370                 my $start = time;
371                 my ($q, $key) = fudge_qstr_time($lei, $uri, $qstr);
372                 $uri->query_form(@qform, q => $q);
373                 my $cmd = $curl->for_uri($lei, $uri);
374                 $lei->qerr("# $cmd");
375                 my ($fh, $pid) = popen_rd($cmd, undef, $rdr);
376                 my $reap_curl = PublicInbox::AutoReap->new($pid);
377                 $fh = IO::Uncompress::Gunzip->new($fh, MultiStream => 1);
378                 PublicInbox::MboxReader->mboxrd($fh, \&each_remote_eml, $self,
379                                                 $lei, $each_smsg);
380                 if (delete($self->{-sto_imported})) {
381                         my $wait = $self->{import_sto}->wq_do('done');
382                 }
383                 $reap_curl->join;
384                 if ($? == 0) {
385                         # don't update if no results, maybe MTA is down
386                         my $nr = $lei->{-nr_remote_eml};
387                         $lei->{lss}->cfg_set($key, $start) if $key && $nr;
388                         mset_progress($lei, $lei->{-current_url}, $nr, $nr);
389                         next;
390                 }
391                 my $err;
392                 if (-s $cerr) {
393                         seek($cerr, 0, SEEK_SET) //
394                                         warn "seek($cmd stderr): $!";
395                         $err = do { local $/; <$cerr> } //
396                                         warn "read($cmd stderr): $!";
397                         truncate($cerr, 0) // warn "truncate($cmd stderr): $!";
398                 }
399                 $err //= '';
400                 next if (($? >> 8) == 22 && $err =~ /\b404\b/);
401                 $uri->query_form(q => $qstr);
402                 $lei->child_error($?, "E: <$uri> $err");
403         }
404         undef $each_smsg;
405         $lei->{ovv}->ovv_atexit_child($lei);
406 }
407
408 sub git { $_[0]->{git} // die 'BUG: git uninitialized' }
409
410 sub xsearch_done_wait { # dwaitpid callback
411         my ($arg, $pid) = @_;
412         my ($wq, $lei) = @$arg;
413         return if !$?;
414         my $s = $? & 127;
415         return $lei->child_error($?) if $s == 13 || $s == 15;
416         $lei->child_error($?, 'non-fatal error from '.ref($wq)." \$?=$?");
417 }
418
419 sub query_done { # EOF callback for main daemon
420         my ($lei) = @_;
421         local $PublicInbox::LEI::current_lei = $lei;
422         eval {
423                 my $l2m = delete $lei->{l2m};
424                 delete $lei->{lxs};
425                 ($lei->{opt}->{'mail-sync'} && !$lei->{sto}) and
426                         warn "BUG: {sto} missing with --mail-sync";
427                 $lei->sto_done_request if $lei->{sto};
428                 if (my $v2w = delete $lei->{v2w}) {
429                         my $wait = $v2w->wq_do('done'); # may die
430                         $v2w->wq_close;
431                 }
432                 $lei->{ovv}->ovv_end($lei);
433                 if ($l2m) { # close() calls LeiToMail reap_compress
434                         if (my $out = delete $lei->{old_1}) {
435                                 if (my $mbout = $lei->{1}) {
436                                         close($mbout) or die <<"";
437 Error closing $lei->{ovv}->{dst}: \$!=$! \$?=$?
438
439                                 }
440                                 $lei->{1} = $out;
441                         }
442                         if ($l2m->lock_free) {
443                                 $l2m->poke_dst;
444                                 $lei->poke_mua;
445                         } else { # mbox users
446                                 delete $l2m->{mbl}; # drop dotlock
447                         }
448                 }
449                 if ($lei->{-progress}) {
450                         my $tot = $lei->{-mset_total} // 0;
451                         my $nr_w = $lei->{-nr_write} // 0;
452                         my $d = ($lei->{-nr_seen} // 0) - $nr_w;
453                         my $x = "$tot matches";
454                         $x .= ", $d duplicates" if $d;
455                         if ($l2m) {
456                                 my $m = "# $nr_w written to " .
457                                         "$lei->{ovv}->{dst} ($x)";
458                                 $nr_w ? $lei->qfin($m) : $lei->qerr($m);
459                         } else {
460                                 $lei->qerr("# $x");
461                         }
462                 }
463                 $lei->start_mua if $l2m && !$l2m->lock_free;
464                 $lei->dclose;
465         };
466         $lei->fail($@) if $@;
467 }
468
469 sub do_post_augment {
470         my ($lei) = @_;
471         local $PublicInbox::LEI::current_lei = $lei;
472         my $l2m = $lei->{l2m} or return; # client disconnected
473         eval {
474                 $lei->fchdir;
475                 $l2m->post_augment($lei);
476         };
477         my $err = $@;
478         if ($err) {
479                 if (my $lxs = delete $lei->{lxs}) {
480                         $lxs->wq_kill('-TERM');
481                         $lxs->wq_close;
482                 }
483                 $lei->fail("$err");
484         }
485         if (!$err && delete $lei->{early_mua}) { # non-augment case
486                 eval { $lei->start_mua };
487                 $lei->fail($@) if $@;
488         }
489         close(delete $lei->{au_done}); # triggers wait_startq in lei_xsearch
490 }
491
492 sub incr_post_augment { # called whenever an l2m shard finishes augment
493         my ($lei) = @_;
494         my $l2m = $lei->{l2m} or return; # client disconnected
495         return if ++$lei->{nr_post_augment} != $l2m->{-wq_nr_workers};
496         do_post_augment($lei);
497 }
498
499 my $MAX_PER_HOST = 4;
500
501 sub concurrency {
502         my ($self, $opt) = @_;
503         my $nl = $opt->{threads} ? locals($self) : 1;
504         my $nr = remotes($self);
505         $nr = $MAX_PER_HOST if $nr > $MAX_PER_HOST;
506         $nl + $nr;
507 }
508
509 sub start_query ($$) { # always runs in main (lei-daemon) process
510         my ($self, $lei) = @_;
511         local $PublicInbox::LEI::current_lei = $lei;
512         if ($self->{opt_threads} || ($lei->{l2m} && !$self->{opt_sort})) {
513                 for my $ibxish (locals($self)) {
514                         $self->wq_io_do('query_one_mset', [], $ibxish);
515                 }
516         } elsif (locals($self)) {
517                 $self->wq_io_do('query_combined_mset', []);
518         }
519         my $i = 0;
520         my $q = [];
521         for my $uri (remotes($self)) {
522                 push @{$q->[$i++ % $MAX_PER_HOST]}, $uri;
523         }
524         for my $uris (@$q) {
525                 $self->wq_io_do('query_remote_mboxrd', [], $uris);
526         }
527         if ($self->{-do_lcat}) {
528                 $self->wq_io_do('lcat_dump', []);
529         }
530         $self->wq_close; # lei_xsearch workers stop when done
531 }
532
533 sub incr_start_query { # called whenever an l2m shard starts do_post_auth
534         my ($self, $lei) = @_;
535         my $l2m = $lei->{l2m};
536         return if ++$self->{nr_start_query} != $l2m->{-wq_nr_workers};
537         start_query($self, $lei);
538 }
539
540 sub ipc_atfork_child {
541         my ($self) = @_;
542         $self->{lei}->_lei_atfork_child;
543         $self->SUPER::ipc_atfork_child;
544 }
545
546 sub do_query {
547         my ($self, $lei) = @_;
548         my $l2m = $lei->{l2m};
549         my $ops = {
550                 'sigpipe_handler' => [ $lei ],
551                 'fail_handler' => [ $lei ],
552                 'do_post_augment' => [ \&do_post_augment, $lei ],
553                 'incr_post_augment' => [ \&incr_post_augment, $lei ],
554                 '' => [ \&query_done, $lei ],
555                 'mset_progress' => [ \&mset_progress, $lei ],
556                 'l2m_progress' => [ \&l2m_progress, $lei ],
557                 'x_it' => [ $lei ],
558                 'child_error' => [ $lei ],
559                 'incr_start_query' => [ $self, $lei ],
560         };
561         $lei->{auth}->op_merge($ops, $l2m, $lei) if $l2m && $lei->{auth};
562         my $end = $lei->pkt_op_pair;
563         $lei->{1}->autoflush(1);
564         $lei->start_pager if delete $lei->{need_pager};
565         $lei->{ovv}->ovv_begin($lei);
566         die 'BUG: xdb|over open' if $lei->{lse}->{xdb} || $lei->{lse}->{over};
567         if ($l2m) {
568                 $l2m->pre_augment($lei);
569                 if ($lei->{opt}->{augment} && delete $lei->{early_mua}) {
570                         $lei->start_mua;
571                 }
572                 my $F_SETPIPE_SZ = $^O eq 'linux' ? 1031 : undef;
573                 if ($l2m->{-wq_nr_workers} > 1 &&
574                                 $l2m->{base_type} =~ /\A(?:maildir|mbox)\z/) {
575                         # setup two barriers to coordinate ->has_entries
576                         # between l2m workers
577                         pipe(my ($a_r, $a_w)) or die "pipe: $!";
578                         fcntl($a_r, $F_SETPIPE_SZ, 4096) if $F_SETPIPE_SZ;
579                         pipe(my ($b_r, $b_w)) or die "pipe: $!";
580                         fcntl($b_r, $F_SETPIPE_SZ, 4096) if $F_SETPIPE_SZ;
581                         $l2m->{au_peers} = [ $a_r, $a_w, $b_r, $b_w ];
582                 }
583                 $l2m->wq_workers_start('lei2mail', undef,
584                                         $lei->oldset, { lei => $lei });
585                 $l2m->wq_wait_async(\&xsearch_done_wait, $lei);
586                 pipe($lei->{startq}, $lei->{au_done}) or die "pipe: $!";
587                 fcntl($lei->{startq}, $F_SETPIPE_SZ, 4096) if $F_SETPIPE_SZ;
588                 delete $l2m->{au_peers};
589         }
590         $self->wq_workers_start('lei_xsearch', undef,
591                                 $lei->oldset, { lei => $lei });
592         $self->wq_wait_async(\&xsearch_done_wait, $lei);
593         my $op_c = delete $lei->{pkt_op_c};
594         delete $lei->{pkt_op_p};
595         @$end = ();
596         $self->{opt_threads} = $lei->{opt}->{threads};
597         $self->{opt_sort} = $lei->{opt}->{'sort'};
598         $self->{-do_lcat} = !!(delete $lei->{lcat_todo});
599         if ($l2m) {
600                 $l2m->net_merge_all_done($lei) unless $lei->{auth};
601         } else {
602                 start_query($self, $lei);
603         }
604         $lei->event_step_init; # wait for shutdowns
605         $lei->wait_wq_events($op_c, $ops);
606 }
607
608 sub add_uri {
609         my ($self, $uri) = @_;
610         if (my $curl = $self->{curl} //= which('curl') // 0) {
611                 require PublicInbox::MboxReader;
612                 require IO::Uncompress::Gunzip;
613                 require PublicInbox::LeiCurl;
614                 push @{$self->{remotes}}, $uri;
615         } else {
616                 warn "curl missing, ignoring $uri\n";
617         }
618 }
619
620 sub prepare_external {
621         my ($self, $loc, $boost) = @_; # n.b. already ordered by boost
622         if (ref $loc) { # already a URI, or PublicInbox::Inbox-like object
623                 return add_uri($self, $loc) if $loc->can('scheme');
624         } elsif ($loc =~ m!\Ahttps?://!) {
625                 require URI;
626                 return add_uri($self, URI->new($loc));
627         } elsif (-f "$loc/ei.lock") {
628                 require PublicInbox::ExtSearch;
629                 die "`\\n' not allowed in `$loc'\n" if index($loc, "\n") >= 0;
630                 $loc = PublicInbox::ExtSearch->new($loc);
631         } elsif (-f "$loc/inbox.lock" || -d "$loc/public-inbox") {
632                 die "`\\n' not allowed in `$loc'\n" if index($loc, "\n") >= 0;
633                 require PublicInbox::Inbox; # v2, v1
634                 $loc = bless { inboxdir => $loc }, 'PublicInbox::Inbox';
635         } elsif (!-e $loc) {
636                 warn "W: $loc gone, perhaps run: lei forget-external $loc\n";
637                 return;
638         } else {
639                 warn "W: $loc ignored, unable to determine external type\n";
640                 return;
641         }
642         push @{$self->{locals}}, $loc;
643 }
644
645 sub _lcat_i { # LeiMailSync->each_src iterator callback
646         my ($oidbin, $id, $each_smsg) = @_;
647         $each_smsg->({blob => unpack('H*', $oidbin), pct => 100});
648 }
649
650 sub _lcat2smsg { # git->cat_async callback
651         my ($bref, $oid, $type, $size, $smsg) = @_;
652         if ($bref) {
653                 my $eml = PublicInbox::Eml->new($bref);
654                 my $json_dump = delete $smsg->{-json_dump};
655                 bless $smsg, 'PublicInbox::Smsg';
656                 _smsg_fill($smsg, $eml);
657                 $json_dump->($smsg, undef, $eml);
658         }
659 }
660
661 sub lcat_dump { # via wq_io_do
662         my ($self) = @_;
663         my $lei = $self->{lei};
664         my $each_smsg = $lei->{ovv}->ovv_each_smsg_cb($lei);
665         my $git = $lei->{ale}->git;
666         if (!$lei->{l2m}) {
667                 my $json_dump = $each_smsg;
668                 $each_smsg = sub {
669                         my ($smsg) = @_;
670                         $smsg->{-json_dump} = $json_dump;
671                         $git->cat_async($smsg->{blob}, \&_lcat2smsg, $smsg);
672                 };
673         }
674         my $lms;
675         for my $ent (@{$lei->{lcat_todo}}) {
676                 if (ref $ent eq 'HASH') { # { fid => $fid ,.. }
677                         $lms //= $lei->{lse}->lms;
678                         $lms->each_src($ent, \&_lcat_i, $each_smsg);
679                 } else { # oidhex
680                         $each_smsg->({ blob => $ent, pct => 100 });
681                 }
682         }
683         $git->async_wait_all;
684         undef $each_smsg; # may commit
685         $lei->{ovv}->ovv_atexit_child($lei);
686 }
687
688 1;