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