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 # per-mitem/smsg iterators for search results
5 # "ovv" => "Overview viewer"
6 package PublicInbox::LeiOverview;
9 use parent qw(PublicInbox::Lock);
10 use POSIX qw(strftime);
11 use Fcntl qw(F_GETFL O_APPEND);
14 use PublicInbox::MID qw($MID_EXTRACT);
15 use PublicInbox::Address qw(pairs);
16 use PublicInbox::Config;
17 use PublicInbox::Search qw(get_pct);
18 use PublicInbox::LeiDedupe;
19 use PublicInbox::LeiToMail;
21 # cf. https://en.wikipedia.org/wiki/JSON_streaming
22 my $JSONL = 'ldjson|ndjson|jsonl'; # 3 names for the same thing
24 sub _iso8601 ($) { strftime('%Y-%m-%dT%H:%M:%SZ', gmtime($_[0])) }
26 # we open this in the parent process before ->wq_do handoff
27 sub ovv_out_lk_init ($) {
29 $self->{tmp_lk_id} = "$self.$$";
30 my $tmp = File::Temp->new("lei-ovv.dst.$$.lock-XXXXXX",
31 TMPDIR => 1, UNLINK => 0);
32 $self->{lock_path} = $tmp->filename;
35 sub ovv_out_lk_cancel ($) {
37 ($self->{tmp_lk_id}//'') eq "$self.$$" and
38 unlink(delete($self->{lock_path}));
43 if ($dst =~ m!\A([:/]+://)!) {
44 $lei->fail("$1 support not implemented, yet\n");
45 } elsif (!-e $dst || -d _) {
46 'maildir'; # the default TODO: MH?
47 } elsif (-f _ || -p _) {
48 $lei->fail("unable to determine mbox family of $dst\n");
50 $lei->fail("unable to determine format of $dst\n");
55 my ($class, $lei) = @_;
56 my $opt = $lei->{opt};
57 my $dst = $opt->{output} // '-';
58 $dst = '/dev/stdout' if $dst eq '-';
60 my $fmt = $opt->{'format'};
61 $fmt = lc($fmt) if defined $fmt;
62 if ($dst =~ s/\A([a-z0-9]+)://is) { # e.g. Maildir:/home/user/Mail/
65 return $lei->fail(<<"") if $fmt ne $ofmt;
66 --format=$fmt and --output=$ofmt conflict
69 $fmt //= 'json' if $dst eq '/dev/stdout';
70 $fmt //= detect_fmt($lei, $dst) or return;
72 if (index($dst, '://') < 0) { # not a URL, so assume path
73 $dst = File::Spec->canonpath($dst);
76 my $self = bless { fmt => $fmt, dst => $dst }, $class;
79 if ($fmt =~ /\A($JSONL|(?:concat)?json)\z/) {
80 $json = $self->{json} = ref(PublicInbox::Config->json);
82 my ($isatty, $seekable);
83 if ($dst eq '/dev/stdout') {
84 $isatty = -t $lei->{1};
85 $lei->start_pager if $isatty;
86 $opt->{pretty} //= $isatty;
87 if (!$isatty && -f _) {
88 my $fl = fcntl($lei->{1}, F_GETFL, 0) //
89 return $lei->fail("fcntl(stdout): $!");
90 ovv_out_lk_init($self) unless ($fl & O_APPEND);
92 ovv_out_lk_init($self);
96 # default to the cheapest sort since MUA usually resorts
97 $lei->{opt}->{'sort'} //= 'docid' if $dst ne '/dev/stdout';
98 $lei->{l2m} = eval { PublicInbox::LeiToMail->new($lei) };
99 return $lei->fail($@) if $@;
101 $lei->{dedupe} //= PublicInbox::LeiDedupe->new($lei);
105 # called once by parent
107 my ($self, $lei) = @_;
108 if ($self->{fmt} eq 'json') {
109 print { $lei->{1} } '[';
110 } # TODO HTML/Atom/...
113 # called once by parent (via PublicInbox::EOFpipe)
115 my ($self, $lei) = @_;
116 my $out = $lei->{1} or return;
117 if ($self->{fmt} eq 'json') {
118 # JSON doesn't allow trailing commas, and preventing
119 # trailing commas is a PITA when parallelizing outputs
120 print $out "null]\n";
121 } elsif ($self->{fmt} eq 'concatjson') {
126 sub ovv_atfork_child {
131 # prepares an smsg for JSON
133 my ($smsg, $mitem) = @_;
135 delete @$smsg{qw(lines bytes num tid)};
136 $smsg->{rt} = _iso8601(delete $smsg->{ts}); # JMAP receivedAt
137 $smsg->{dt} = _iso8601(delete $smsg->{ds}); # JMAP UTCDate
138 $smsg->{pct} = get_pct($mitem) if $mitem;
139 if (my $r = delete $smsg->{references}) {
140 $smsg->{refs} = [ map { "<$_>" } ($r =~ m/$MID_EXTRACT/go) ];
142 if (my $m = delete($smsg->{mid})) {
143 $smsg->{'m'} = "<$m>";
145 for my $f (qw(from to cc)) {
146 my $v = delete $smsg->{$f} or next;
147 $smsg->{substr($f, 0, 1)} = pairs($v);
149 $smsg->{'s'} = delete $smsg->{subject};
150 # can we be bothered to parse From/To/Cc into arrays?
151 scalar { %$smsg }; # unbless
154 sub ovv_atexit_child {
155 my ($self, $lei) = @_;
156 if (my $l2m = delete $lei->{l2m}) {
157 # gracefully stop lei2mail processes after all
158 # ->write_mail work is complete
159 delete $l2m->{-wq_s1};
160 if (my $rd = delete $l2m->{each_smsg_done}) {
161 read($rd, my $buf, 1); # wait for EOF
164 # order matters, git->{-tmp}->DESTROY must not fire until
165 # {each_smsg_done} hits EOF above
166 if (my $git = delete $self->{git}) {
167 $git->async_wait_all;
169 if (my $bref = delete $lei->{ovv_buf}) {
170 my $out = $lei->{1} or return;
171 my $lk = $self->lock_for_scope;
176 # JSON module ->pretty output wastes too much vertical white space,
177 # this (IMHO) provides better use of screen real-estate while not
178 # being excessively compact:
180 my ($json, $k, $v) = @_;
181 if (ref $v eq 'ARRAY') {
183 my $sep = ",\n" . (' ' x (length($k) + 7));
184 if (ref($v->[0])) { # f/t/c
185 $v = '[' . join($sep, map {
186 my $pair = $json->encode($_);
187 $pair =~ s/(null|"),"/$1, "/g;
190 } else { # references
191 $v = '[' . join($sep, map {
192 substr($json->encode([$_]), 1, -1);
202 sub ovv_each_smsg_cb { # runs in wq worker usually
203 my ($self, $lei, $ibxish) = @_;
205 $lei->{1}->autoflush(1);
206 my $dedupe = $lei->{dedupe} // die 'BUG: {dedupe} missing';
207 if (my $pkg = $self->{json}) {
209 $json->utf8->canonical;
210 $json->ascii(1) if $lei->{opt}->{ascii};
212 my $l2m = $lei->{l2m} or $dedupe->prepare_dedupe;
213 if ($l2m && !$ibxish) { # remote https?:// mboxrd
214 delete $l2m->{-wq_s1};
215 my $g2m = $l2m->can('git_to_mail');
216 my $wcb = $l2m->write_cb($lei);
218 my ($smsg, undef, $eml) = @_; # no mitem in $_[1]
219 $wcb->(undef, $smsg, $eml);
221 } elsif ($l2m && $l2m->{-wq_s1}) {
222 my ($lei_ipc, @io) = $lei->atfork_parent_wq($l2m);
223 # $io[-1] becomes a notification pipe that triggers EOF
224 # in this wq worker when all outstanding ->write_mail
226 pipe($l2m->{each_smsg_done}, $io[$#io + 1]) or die "pipe: $!";
227 fcntl($io[-1], 1031, 4096) if $^O eq 'linux'; # F_SETPIPE_SZ
228 delete @$lei_ipc{qw(l2m opt mset_opt cmd)};
229 $lei_ipc->{each_smsg_not_done} = $#io;
230 my $git = $ibxish->git; # (LeiXSearch|Inbox|ExtSearch)->git
232 my $git_dir = $git->{git_dir};
234 my ($smsg, $mitem) = @_;
235 $smsg->{pct} = get_pct($mitem) if $mitem;
236 $l2m->wq_do('write_mail', \@io, $git_dir, $smsg,
240 my $wcb = $l2m->write_cb($lei);
241 my $git = $ibxish->git; # (LeiXSearch|Inbox|ExtSearch)->git
242 $self->{git} = $git; # for ovv_atexit_child
243 my $g2m = $l2m->can('git_to_mail');
244 $dedupe->prepare_dedupe;
246 my ($smsg, $mitem) = @_;
247 $smsg->{pct} = get_pct($mitem) if $mitem;
248 $git->cat_async($smsg->{blob}, $g2m, [ $wcb, $smsg ]);
250 } elsif ($self->{fmt} =~ /\A(concat)?json\z/ && $lei->{opt}->{pretty}) {
251 my $EOR = ($1//'') eq 'concat' ? "\n}" : "\n},";
252 $lei->{ovv_buf} = \(my $buf = '');
253 sub { # DIY prettiness :P
254 my ($smsg, $mitem) = @_;
255 return if $dedupe->is_smsg_dup($smsg);
256 $smsg = _unbless_smsg($smsg, $mitem);
258 $buf .= join(",\n", map {
261 _json_pretty($json, $_, $v);
263 $v = $json->encode([$v]);
264 qq{ "$_": }.substr($v, 1, -1);
268 if (length($buf) > 65536) {
269 my $lk = $self->lock_for_scope;
270 print { $lei->{1} } $buf;
275 my $ORS = $self->{fmt} eq 'json' ? ",\n" : "\n"; # JSONL
276 $lei->{ovv_buf} = \(my $buf = '');
278 my ($smsg, $mitem) = @_;
279 return if $dedupe->is_smsg_dup($smsg);
280 $buf .= $json->encode(_unbless_smsg(@_)) . $ORS;
281 if (length($buf) > 65536) {
282 my $lk = $self->lock_for_scope;
283 print { $lei->{1} } $buf;
291 *DESTROY = \&ovv_out_lk_cancel;