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 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;
34 sub ovv_out_lk_cancel ($) {
36 my $lock_path = delete $self->{"lk_id.$self.$$"} or return;
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");
49 $lei->fail("unable to determine format of $dst\n");
54 my ($class, $lei) = @_;
55 my $opt = $lei->{opt};
56 my $dst = $opt->{output} // '-';
57 $dst = '/dev/stdout' if $dst eq '-';
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/
64 return $lei->fail(<<"") if $fmt ne $ofmt;
65 --format=$fmt and --output=$ofmt conflict
68 $fmt //= 'json' if $dst eq '/dev/stdout';
69 $fmt //= detect_fmt($lei, $dst) or return;
71 if (index($dst, '://') < 0) { # not a URL, so assume path
72 $dst = File::Spec->canonpath($dst);
75 my $self = bless { fmt => $fmt, dst => $dst }, $class;
78 if ($fmt =~ /\A($JSONL|(?:concat)?json)\z/) {
79 $json = $self->{json} = ref(PublicInbox::Config->json);
81 my ($isatty, $seekable);
82 if ($dst eq '/dev/stdout') {
83 $isatty = -t $lei->{1};
84 $opt->{pretty} //= $isatty;
85 if (!$isatty && -f _) {
86 my $fl = fcntl($lei->{1}, F_GETFL, 0) //
87 return $lei->fail("fcntl(stdout): $!");
88 ovv_out_lk_init($self) unless ($fl & O_APPEND);
90 ovv_out_lk_init($self);
92 } elsif (!$opt->{quiet}) {
93 $lei->{-progress} = 1;
96 $lei->{dedupe} //= PublicInbox::LeiDedupe->new($lei);
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 $@;
106 # called once by parent
108 my ($self, $lei) = @_;
109 if ($self->{fmt} eq 'json') {
111 } # TODO HTML/Atom/...
114 # called once by parent (via PublicInbox::EOFpipe)
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') {
126 # prepares an smsg for JSON
128 my ($smsg, $mitem) = @_;
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) ];
137 if (my $m = delete($smsg->{mid})) {
138 $smsg->{'m'} = "<$m>";
140 for my $f (qw(from to cc)) {
141 my $v = delete $smsg->{$f} or next;
142 $smsg->{substr($f, 0, 1)} = pairs($v);
144 $smsg->{'s'} = delete $smsg->{subject};
145 # can we be bothered to parse From/To/Cc into arrays?
146 scalar { %$smsg }; # unbless
149 sub ovv_atexit_child {
150 my ($self, $lei) = @_;
151 if (my $l2m = $lei->{l2m}) {
152 # wait for ->write_mail work we submitted to lei2mail
153 if (my $rd = delete $l2m->{each_smsg_done}) {
154 read($rd, my $buf, 1); # wait for EOF
157 # order matters, git->{-tmp}->DESTROY must not fire until
158 # {each_smsg_done} hits EOF above
159 if (my $git = delete $self->{git}) {
160 $git->async_wait_all;
162 if (my $bref = delete $lei->{ovv_buf}) {
163 my $lk = $self->lock_for_scope;
168 # JSON module ->pretty output wastes too much vertical white space,
169 # this (IMHO) provides better use of screen real-estate while not
170 # being excessively compact:
172 my ($json, $k, $v) = @_;
173 if (ref $v eq 'ARRAY') {
175 my $sep = ",\n" . (' ' x (length($k) + 7));
176 if (ref($v->[0])) { # f/t/c
177 $v = '[' . join($sep, map {
178 my $pair = $json->encode($_);
179 $pair =~ s/(null|"),"/$1, "/g;
182 } else { # references
183 $v = '[' . join($sep, map {
184 substr($json->encode([$_]), 1, -1);
194 sub ovv_each_smsg_cb { # runs in wq worker usually
195 my ($self, $lei, $ibxish) = @_;
197 $lei->{1}->autoflush(1);
198 if (my $pkg = $self->{json}) {
200 $json->utf8->canonical;
201 $json->ascii(1) if $lei->{opt}->{ascii};
203 my $l2m = $lei->{l2m};
205 $dedupe = $lei->{dedupe} // die 'BUG: {dedupe} missing';
206 $dedupe->prepare_dedupe;
208 $lei->{ovv_buf} = \(my $buf = '') if !$l2m;
209 if ($l2m && !$ibxish) { # remote https?:// mboxrd
210 my $g2m = $l2m->can('git_to_mail');
211 my $wcb = $l2m->write_cb($lei);
213 my ($smsg, undef, $eml) = @_; # no mitem in $_[1]
214 $wcb->(undef, $smsg, $eml);
216 } elsif ($l2m && $l2m->{-wq_s1}) {
217 # $io->[0] becomes a notification pipe that triggers EOF
218 # in this wq worker when all outstanding ->write_mail
221 pipe($l2m->{each_smsg_done}, $io->[0]) or die "pipe: $!";
222 fcntl($io->[0], 1031, 4096) if $^O eq 'linux'; # F_SETPIPE_SZ
223 my $git = $ibxish->git; # (LeiXSearch|Inbox|ExtSearch)->git
225 my $git_dir = $git->{git_dir};
227 my ($smsg, $mitem) = @_;
228 $smsg->{pct} = get_pct($mitem) if $mitem;
229 $l2m->wq_do('write_mail', $io, $git_dir, $smsg);
231 } elsif ($self->{fmt} =~ /\A(concat)?json\z/ && $lei->{opt}->{pretty}) {
232 my $EOR = ($1//'') eq 'concat' ? "\n}" : "\n},";
233 sub { # DIY prettiness :P
234 my ($smsg, $mitem) = @_;
235 return if $dedupe->is_smsg_dup($smsg);
236 $smsg = _unbless_smsg($smsg, $mitem);
238 $buf .= join(",\n", map {
241 _json_pretty($json, $_, $v);
243 $v = $json->encode([$v]);
244 qq{ "$_": }.substr($v, 1, -1);
248 return if length($buf) < 65536;
249 my $lk = $self->lock_for_scope;
254 my $ORS = $self->{fmt} eq 'json' ? ",\n" : "\n"; # JSONL
256 my ($smsg, $mitem) = @_;
257 return if $dedupe->is_smsg_dup($smsg);
258 $buf .= $json->encode(_unbless_smsg(@_)) . $ORS;
259 return if length($buf) < 65536;
260 my $lk = $self->lock_for_scope;
265 die "TODO: unhandled case $self->{fmt}"
270 *DESTROY = \&ovv_out_lk_cancel;