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