]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/LeiOverview.pm
1d62ffe253d19d8100d70c5782962a4ecd761ccd
[public-inbox.git] / lib / PublicInbox / LeiOverview.pm
1 # Copyright (C) 2021 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
3
4 # per-mitem/smsg iterators for search results
5 # "ovv" => "Overview viewer"
6 package PublicInbox::LeiOverview;
7 use strict;
8 use v5.10.1;
9 use parent qw(PublicInbox::Lock);
10 use POSIX qw(strftime);
11 use Fcntl qw(F_GETFL O_APPEND);
12 use File::Spec;
13 use File::Temp ();
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;
20
21 # cf. https://en.wikipedia.org/wiki/JSON_streaming
22 my $JSONL = 'ldjson|ndjson|jsonl'; # 3 names for the same thing
23
24 sub _iso8601 ($) { strftime('%Y-%m-%dT%H:%M:%SZ', gmtime($_[0])) }
25
26 # we open this in the parent process before ->wq_do handoff
27 sub ovv_out_lk_init ($) {
28         my ($self) = @_;
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;
33 }
34
35 sub ovv_out_lk_cancel ($) {
36         my ($self) = @_;
37         ($self->{tmp_lk_id}//'') eq "$self.$$" and
38                 unlink(delete($self->{lock_path}));
39 }
40
41 sub detect_fmt ($$) {
42         my ($lei, $dst) = @_;
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");
49         } else {
50                 $lei->fail("unable to determine format of $dst\n");
51         }
52 }
53
54 sub new {
55         my ($class, $lei) = @_;
56         my $opt = $lei->{opt};
57         my $dst = $opt->{output} // '-';
58         $dst = '/dev/stdout' if $dst eq '-';
59
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/
63                 my $ofmt = lc $1;
64                 $fmt //= $ofmt;
65                 return $lei->fail(<<"") if $fmt ne $ofmt;
66 --format=$fmt and --output=$ofmt conflict
67
68         }
69         $fmt //= 'json' if $dst eq '/dev/stdout';
70         $fmt //= detect_fmt($lei, $dst) or return;
71
72         if (index($dst, '://') < 0) { # not a URL, so assume path
73                  $dst = File::Spec->canonpath($dst);
74         } # else URL
75
76         my $self = bless { fmt => $fmt, dst => $dst }, $class;
77         $lei->{ovv} = $self;
78         my $json;
79         if ($fmt =~ /\A($JSONL|(?:concat)?json)\z/) {
80                 $json = $self->{json} = ref(PublicInbox::Config->json);
81         }
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);
91                 } else {
92                         ovv_out_lk_init($self);
93                 }
94         }
95         if ($json) {
96                 $lei->{dedupe} //= PublicInbox::LeiDedupe->new($lei);
97         } else {
98                 # default to the cheapest sort since MUA usually resorts
99                 $lei->{opt}->{'sort'} //= 'docid' if $dst ne '/dev/stdout';
100                 $lei->{l2m} = eval { PublicInbox::LeiToMail->new($lei) };
101                 return $lei->fail($@) if $@;
102         }
103         $self;
104 }
105
106 # called once by parent
107 sub ovv_begin {
108         my ($self, $lei) = @_;
109         if ($self->{fmt} eq 'json') {
110                 $lei->out('[');
111         } # TODO HTML/Atom/...
112 }
113
114 # called once by parent (via PublicInbox::EOFpipe)
115 sub ovv_end {
116         my ($self, $lei) = @_;
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                 $lei->out("null]\n");
121         } elsif ($self->{fmt} eq 'concatjson') {
122                 $lei->out("\n");
123         }
124 }
125
126 # prepares an smsg for JSON
127 sub _unbless_smsg {
128         my ($smsg, $mitem) = @_;
129
130         delete @$smsg{qw(lines bytes num tid)};
131         $smsg->{rt} = _iso8601(delete $smsg->{ts}); # JMAP receivedAt
132         $smsg->{dt} = _iso8601(delete $smsg->{ds}); # JMAP UTCDate
133         $smsg->{pct} = get_pct($mitem) if $mitem;
134         if (my $r = delete $smsg->{references}) {
135                 $smsg->{refs} = [ map { "<$_>" } ($r =~ m/$MID_EXTRACT/go) ];
136         }
137         if (my $m = delete($smsg->{mid})) {
138                 $smsg->{'m'} = "<$m>";
139         }
140         for my $f (qw(from to cc)) {
141                 my $v = delete $smsg->{$f} or next;
142                 $smsg->{substr($f, 0, 1)} = pairs($v);
143         }
144         $smsg->{'s'} = delete $smsg->{subject};
145         # can we be bothered to parse From/To/Cc into arrays?
146         scalar { %$smsg }; # unbless
147 }
148
149 sub ovv_atexit_child {
150         my ($self, $lei) = @_;
151         if (my $l2m = delete $lei->{l2m}) {
152                 # gracefully stop lei2mail processes after all
153                 # ->write_mail work is complete
154                 delete $l2m->{-wq_s1};
155                 if (my $rd = delete $l2m->{each_smsg_done}) {
156                         read($rd, my $buf, 1); # wait for EOF
157                 }
158         }
159         # order matters, git->{-tmp}->DESTROY must not fire until
160         # {each_smsg_done} hits EOF above
161         if (my $git = delete $self->{git}) {
162                 $git->async_wait_all;
163         }
164         if (my $bref = delete $lei->{ovv_buf}) {
165                 my $lk = $self->lock_for_scope;
166                 $lei->out($$bref);
167         }
168 }
169
170 # JSON module ->pretty output wastes too much vertical white space,
171 # this (IMHO) provides better use of screen real-estate while not
172 # being excessively compact:
173 sub _json_pretty {
174         my ($json, $k, $v) = @_;
175         if (ref $v eq 'ARRAY') {
176                 if (@$v) {
177                         my $sep = ",\n" . (' ' x (length($k) + 7));
178                         if (ref($v->[0])) { # f/t/c
179                                 $v = '[' . join($sep, map {
180                                         my $pair = $json->encode($_);
181                                         $pair =~ s/(null|"),"/$1, "/g;
182                                         $pair;
183                                 } @$v) . ']';
184                         } else { # references
185                                 $v = '[' . join($sep, map {
186                                         substr($json->encode([$_]), 1, -1);
187                                 } @$v) . ']';
188                         }
189                 } else {
190                         $v = '[]';
191                 }
192         }
193         qq{  "$k": }.$v;
194 }
195
196 sub ovv_each_smsg_cb { # runs in wq worker usually
197         my ($self, $lei, $ibxish) = @_;
198         my ($json, $dedupe);
199         $lei->{1}->autoflush(1);
200         if (my $pkg = $self->{json}) {
201                 $json = $pkg->new;
202                 $json->utf8->canonical;
203                 $json->ascii(1) if $lei->{opt}->{ascii};
204         }
205         my $l2m = $lei->{l2m};
206         if (!$l2m) {
207                 $dedupe = $lei->{dedupe} // die 'BUG: {dedupe} missing';
208                 $dedupe->prepare_dedupe;
209         }
210         $lei->{ovv_buf} = \(my $buf = '') if !$l2m;
211         if ($l2m && !$ibxish) { # remote https?:// mboxrd
212                 delete $l2m->{-wq_s1};
213                 my $g2m = $l2m->can('git_to_mail');
214                 my $wcb = $l2m->write_cb($lei);
215                 sub {
216                         my ($smsg, undef, $eml) = @_; # no mitem in $_[1]
217                         $wcb->(undef, $smsg, $eml);
218                 };
219         } elsif ($l2m && $l2m->{-wq_s1}) {
220                 my ($lei_ipc, @io) = $lei->atfork_parent_wq($l2m);
221                 # $io[-1] becomes a notification pipe that triggers EOF
222                 # in this wq worker when all outstanding ->write_mail
223                 # calls are complete
224                 pipe($l2m->{each_smsg_done}, $io[$#io + 1]) or die "pipe: $!";
225                 fcntl($io[-1], 1031, 4096) if $^O eq 'linux'; # F_SETPIPE_SZ
226                 delete @$lei_ipc{qw(l2m opt mset_opt cmd)};
227                 $lei_ipc->{each_smsg_not_done} = $#io;
228                 my $git = $ibxish->git; # (LeiXSearch|Inbox|ExtSearch)->git
229                 $self->{git} = $git;
230                 my $git_dir = $git->{git_dir};
231                 sub {
232                         my ($smsg, $mitem) = @_;
233                         $smsg->{pct} = get_pct($mitem) if $mitem;
234                         $l2m->wq_do('write_mail', \@io, $git_dir, $smsg,
235                                         $lei_ipc);
236                 }
237         } elsif ($l2m) {
238                 my $wcb = $l2m->write_cb($lei);
239                 my $git = $ibxish->git; # (LeiXSearch|Inbox|ExtSearch)->git
240                 $self->{git} = $git; # for ovv_atexit_child
241                 my $g2m = $l2m->can('git_to_mail');
242                 sub {
243                         my ($smsg, $mitem) = @_;
244                         $smsg->{pct} = get_pct($mitem) if $mitem;
245                         $git->cat_async($smsg->{blob}, $g2m, [ $wcb, $smsg ]);
246                 };
247         } elsif ($self->{fmt} =~ /\A(concat)?json\z/ && $lei->{opt}->{pretty}) {
248                 my $EOR = ($1//'') eq 'concat' ? "\n}" : "\n},";
249                 sub { # DIY prettiness :P
250                         my ($smsg, $mitem) = @_;
251                         return if $dedupe->is_smsg_dup($smsg);
252                         $smsg = _unbless_smsg($smsg, $mitem);
253                         $buf .= "{\n";
254                         $buf .= join(",\n", map {
255                                 my $v = $smsg->{$_};
256                                 if (ref($v)) {
257                                         _json_pretty($json, $_, $v);
258                                 } else {
259                                         $v = $json->encode([$v]);
260                                         qq{  "$_": }.substr($v, 1, -1);
261                                 }
262                         } sort keys %$smsg);
263                         $buf .= $EOR;
264                         return if length($buf) < 65536;
265                         my $lk = $self->lock_for_scope;
266                         $lei->out($buf);
267                         $buf = '';
268                 }
269         } elsif ($json) {
270                 my $ORS = $self->{fmt} eq 'json' ? ",\n" : "\n"; # JSONL
271                 sub {
272                         my ($smsg, $mitem) = @_;
273                         return if $dedupe->is_smsg_dup($smsg);
274                         $buf .= $json->encode(_unbless_smsg(@_)) . $ORS;
275                         return if length($buf) < 65536;
276                         my $lk = $self->lock_for_scope;
277                         $lei->out($buf);
278                         $buf = '';
279                 }
280         } # else { ...
281 }
282
283 no warnings 'once';
284 *DESTROY = \&ovv_out_lk_cancel;
285
286 1;