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