1 # Copyright (C) 2021 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
4 # front-end for the "lei import" sub-command
5 package PublicInbox::LeiImport;
8 use parent qw(PublicInbox::IPC);
9 use PublicInbox::MboxReader;
12 sub _import_eml { # MboxReader callback
13 my ($eml, $sto, $set_kw) = @_;
14 $sto->ipc_do('set_eml', $eml, $set_kw ? $sto->mbox_keywords($eml) : ());
17 sub import_done_wait { # dwaitpid callback
19 my ($imp, $lei) = @$arg;
20 $lei->child_error($?, 'non-fatal errors during import') if $?;
21 my $ign = $lei->{sto}->ipc_do('done'); # PublicInbox::LeiStore::done
25 sub import_done { # EOF callback for main daemon
27 my $imp = delete $lei->{imp} or return;
28 $imp->wq_wait_old(\&import_done_wait, $lei);
31 sub call { # the main "lei import" method
32 my ($cls, $lei, @argv) = @_;
33 my $sto = $lei->_lei_store(1);
34 $sto->write_prepare($lei);
35 $lei->{opt}->{kw} //= 1;
36 my $fmt = $lei->{opt}->{'format'};
37 my $self = $lei->{imp} = bless {}, $cls;
38 return $lei->fail('--format unspecified') if !$fmt;
39 $self->{0} = $lei->{0} if $lei->{opt}->{stdin};
41 '!' => [ $lei->can('fail_handler'), $lei ],
42 'x_it' => [ $lei->can('x_it'), $lei ],
43 'child_error' => [ $lei->can('child_error'), $lei ],
44 '' => [ \&import_done, $lei ],
46 ($lei->{pkt_op_c}, $lei->{pkt_op_p}) = PublicInbox::PktOp->pair($ops);
47 my $j = $lei->{opt}->{jobs} // scalar(@argv) || 1;
48 my $nproc = $self->detect_nproc;
49 $j = $nproc if $j > $nproc;
50 $self->wq_workers_start('lei_import', $j, $lei->oldset, {lei => $lei});
51 my $op = delete $lei->{pkt_op_c};
52 delete $lei->{pkt_op_p};
53 $self->wq_io_do('import_stdin', []) if $self->{0};
55 $self->wq_io_do('import_path_url', [], $x);
58 $lei->event_step_init; # wait for shutdowns
59 if ($lei->{oneshot}) {
60 while ($op->{sock}) { $op->event_step }
64 sub ipc_atfork_child {
66 $self->{lei}->lei_atfork_child;
67 $self->SUPER::ipc_atfork_child;
71 my ($lei, $fh, $x) = @_;
72 my $set_kw = $lei->{opt}->{kw};
73 my $fmt = $lei->{opt}->{'format'};
76 my $buf = do { local $/; <$fh> } //
77 return $lei->child_error(1 >> 8, <<"");
80 my $eml = PublicInbox::Eml->new(\$buf);
81 _import_eml($eml, $lei->{sto}, $set_kw);
83 my $cb = PublicInbox::MboxReader->can($fmt);
84 $cb or return $lei->child_error(1 >> 8, <<"");
85 --format $fmt unsupported for $x
87 $cb->(undef, $fh, \&_import_eml, $lei->{sto}, $set_kw);
90 $lei->child_error(1 >> 8, "<stdin>: $@") if $@;
95 my $lei = $self->{lei};
98 open my $fh, '<', $x or return $lei->child_error(1 >> 8, <<"");
101 _import_fh($lei, $fh, $x);
103 $lei->fail("$x unsupported (TODO)");
109 _import_fh($self->{lei}, $self->{0}, '<stdin>');