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