]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/LeiOverview.pm
lei_overview: start implementing format detection
[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) {
46                 'maildir'; # the default
47         } elsif (-f _ || -p _) {
48                 $lei->fail("unable to determine mbox family of $dst\n");
49         } elsif (-d _) { # TODO: MH?
50                 'maildir';
51         } else {
52                 $lei->fail("unable to determine format of $dst\n");
53         }
54 }
55
56 sub new {
57         my ($class, $lei) = @_;
58         my $opt = $lei->{opt};
59         my $dst = $opt->{output} // '-';
60         $dst = '/dev/stdout' if $dst eq '-';
61
62         my $fmt = $opt->{'format'};
63         $fmt = lc($fmt) if defined $fmt;
64         if ($dst =~ s/\A([a-z0-9]+)://is) { # e.g. Maildir:/home/user/Mail/
65                 my $ofmt = lc $1;
66                 $fmt //= $ofmt;
67                 return $lei->fail(<<"") if $fmt ne $ofmt;
68 --format=$fmt and --output=$ofmt conflict
69
70         }
71         $fmt //= 'json' if $dst eq '/dev/stdout';
72         $fmt //= detect_fmt($lei, $dst) or return;
73
74         if (index($dst, '://') < 0) { # not a URL, so assume path
75                  $dst = File::Spec->canonpath($dst);
76         } # else URL
77
78         my $self = bless { fmt => $fmt, dst => $dst }, $class;
79         $lei->{ovv} = $self;
80         my $json;
81         if ($fmt =~ /\A($JSONL|(?:concat)?json)\z/) {
82                 $json = $self->{json} = ref(PublicInbox::Config->json);
83         }
84         my ($isatty, $seekable);
85         if ($dst eq '/dev/stdout') {
86                 $isatty = -t $lei->{1};
87                 $lei->start_pager if $isatty;
88                 $opt->{pretty} //= $isatty;
89                 if (!$isatty && -f _) {
90                         my $fl = fcntl($lei->{1}, F_GETFL, 0) //
91                                 return $lei->fail("fcntl(stdout): $!");
92                         ovv_out_lk_init($self) unless ($fl & O_APPEND);
93                 } else {
94                         ovv_out_lk_init($self);
95                 }
96         }
97         if (!$json) {
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         $lei->{dedupe} //= PublicInbox::LeiDedupe->new($lei);
104         $self;
105 }
106
107 # called once by parent
108 sub ovv_begin {
109         my ($self, $lei) = @_;
110         if ($self->{fmt} eq 'json') {
111                 print { $lei->{1} } '[';
112         } # TODO HTML/Atom/...
113 }
114
115 # called once by parent (via PublicInbox::EOFpipe)
116 sub ovv_end {
117         my ($self, $lei) = @_;
118         my $out = $lei->{1} or return;
119         if ($self->{fmt} eq 'json') {
120                 # JSON doesn't allow trailing commas, and preventing
121                 # trailing commas is a PITA when parallelizing outputs
122                 print $out "null]\n";
123         } elsif ($self->{fmt} eq 'concatjson') {
124                 print $out "\n";
125         }
126 }
127
128 sub ovv_atfork_child {
129         my ($self) = @_;
130         # reopen dedupe here
131 }
132
133 # prepares an smsg for JSON
134 sub _unbless_smsg {
135         my ($smsg, $mitem) = @_;
136
137         delete @$smsg{qw(lines bytes num tid)};
138         $smsg->{rt} = _iso8601(delete $smsg->{ts}); # JMAP receivedAt
139         $smsg->{dt} = _iso8601(delete $smsg->{ds}); # JMAP UTCDate
140         $smsg->{relevance} = get_pct($mitem) if $mitem;
141
142         if (my $r = delete $smsg->{references}) {
143                 $smsg->{refs} = [
144                                 map { "<$_>" } ($r =~ m/$MID_EXTRACT/go) ];
145         }
146         if (my $m = delete($smsg->{mid})) {
147                 $smsg->{'m'} = "<$m>";
148         }
149         for my $f (qw(from to cc)) {
150                 my $v = delete $smsg->{$f} or next;
151                 $smsg->{substr($f, 0, 1)} = pairs($v);
152         }
153         $smsg->{'s'} = delete $smsg->{subject};
154         # can we be bothered to parse From/To/Cc into arrays?
155         scalar { %$smsg }; # unbless
156 }
157
158 sub ovv_atexit_child {
159         my ($self, $lei) = @_;
160         if (my $l2m = delete $lei->{l2m}) {
161                 # gracefully stop lei2mail processes after all
162                 # ->write_mail work is complete
163                 delete $l2m->{-wq_s1};
164                 if (my $rd = delete $l2m->{each_smsg_done}) {
165                         read($rd, my $buf, 1); # wait for EOF
166                 }
167         }
168         # order matters, git->{-tmp}->DESTROY must not fire until
169         # {each_smsg_done} hits EOF above
170         if (my $git = delete $self->{git}) {
171                 $git->async_wait_all;
172         }
173         if (my $bref = delete $lei->{ovv_buf}) {
174                 my $out = $lei->{1} or return;
175                 my $lk = $self->lock_for_scope;
176                 print $out $$bref;
177         }
178 }
179
180 # JSON module ->pretty output wastes too much vertical white space,
181 # this (IMHO) provides better use of screen real-estate while not
182 # being excessively compact:
183 sub _json_pretty {
184         my ($json, $k, $v) = @_;
185         if (ref $v eq 'ARRAY') {
186                 if (@$v) {
187                         my $sep = ",\n" . (' ' x (length($k) + 7));
188                         if (ref($v->[0])) { # f/t/c
189                                 $v = '[' . join($sep, map {
190                                         my $pair = $json->encode($_);
191                                         $pair =~ s/(null|"),"/$1, "/g;
192                                         $pair;
193                                 } @$v) . ']';
194                         } else { # references
195                                 $v = '[' . join($sep, map {
196                                         substr($json->encode([$_]), 1, -1);
197                                 } @$v) . ']';
198                         }
199                 } else {
200                         $v = '[]';
201                 }
202         }
203         qq{  "$k": }.$v;
204 }
205
206 sub ovv_each_smsg_cb { # runs in wq worker usually
207         my ($self, $lei, $ibxish) = @_;
208         my $json;
209         $lei->{1}->autoflush(1);
210         if (my $pkg = $self->{json}) {
211                 $json = $pkg->new;
212                 $json->utf8->canonical;
213                 $json->ascii(1) if $lei->{opt}->{ascii};
214         }
215         my $l2m = $lei->{l2m};
216         if ($l2m && $l2m->{-wq_s1}) {
217                 my ($lei_ipc, @io) = $lei->atfork_parent_wq($l2m);
218                 # n.b. $io[0] = qry_status_wr, $io[1] = mbox|stdout,
219                 # $io[4] becomes a notification pipe that triggers EOF
220                 # in this wq worker when all outstanding ->write_mail
221                 # calls are complete
222                 die "BUG: \$io[4] $io[4] unexpected" if $io[4];
223                 pipe($l2m->{each_smsg_done}, $io[4]) or die "pipe: $!";
224                 fcntl($io[4], 1031, 4096) if $^O eq 'linux';
225                 delete @$lei_ipc{qw(l2m opt mset_opt cmd)};
226                 my $git = $ibxish->git; # (LeiXSearch|Inbox|ExtSearch)->git
227                 $self->{git} = $git;
228                 my $git_dir = $git->{git_dir};
229                 sub {
230                         my ($smsg, $mitem) = @_;
231                         my $kw = []; # TODO get from mitem
232                         $l2m->wq_do('write_mail', \@io, $git_dir,
233                                         $smsg->{blob}, $lei_ipc, $kw)
234                 }
235         } elsif ($l2m) {
236                 my $wcb = $l2m->write_cb($lei);
237                 my $git = $ibxish->git; # (LeiXSearch|Inbox|ExtSearch)->git
238                 $self->{git} = $git; # for ovv_atexit_child
239                 my $g2m = $l2m->can('git_to_mail');
240                 sub {
241                         my ($smsg, $mitem) = @_;
242                         my $kw = []; # TODO get from mitem
243                         $git->cat_async($smsg->{blob}, $g2m, [ $wcb, $kw ]);
244                 };
245         } elsif ($self->{fmt} =~ /\A(concat)?json\z/ && $lei->{opt}->{pretty}) {
246                 my $EOR = ($1//'') eq 'concat' ? "\n}" : "\n},";
247                 $lei->{ovv_buf} = \(my $buf = '');
248                 sub { # DIY prettiness :P
249                         my ($smsg, $mitem) = @_;
250                         $smsg = _unbless_smsg($smsg, $mitem);
251                         $buf .= "{\n";
252                         $buf .= join(",\n", map {
253                                 my $v = $smsg->{$_};
254                                 if (ref($v)) {
255                                         _json_pretty($json, $_, $v);
256                                 } else {
257                                         $v = $json->encode([$v]);
258                                         qq{  "$_": }.substr($v, 1, -1);
259                                 }
260                         } sort keys %$smsg);
261                         $buf .= $EOR;
262                         if (length($buf) > 65536) {
263                                 my $lk = $self->lock_for_scope;
264                                 print { $lei->{1} } $buf;
265                                 $buf = '';
266                         }
267                 }
268         } elsif ($json) {
269                 my $ORS = $self->{fmt} eq 'json' ? ",\n" : "\n"; # JSONL
270                 $lei->{ovv_buf} = \(my $buf = '');
271                 sub {
272                         my ($smsg, $mitem) = @_;
273                         delete @$smsg{qw(tid num)};
274                         $buf .= $json->encode(_unbless_smsg(@_)) . $ORS;
275                         if (length($buf) > 65536) {
276                                 my $lk = $self->lock_for_scope;
277                                 print { $lei->{1} } $buf;
278                                 $buf = '';
279                         }
280                 }
281         } elsif ($self->{fmt} eq 'oid') {
282                 sub {
283                         my ($smsg, $mitem) = @_;
284                 }
285         } # else { ...
286 }
287
288 no warnings 'once';
289 *DESTROY = \&ovv_out_lk_cancel;
290
291 1;