]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/LeiSavedSearch.pm
imap+nntp: share COMPRESS implementation
[public-inbox.git] / lib / PublicInbox / LeiSavedSearch.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 # pretends to be like LeiDedupe and also PublicInbox::Inbox
5 package PublicInbox::LeiSavedSearch;
6 use strict;
7 use v5.10.1;
8 use parent qw(PublicInbox::Lock);
9 use PublicInbox::Git;
10 use PublicInbox::OverIdx;
11 use PublicInbox::LeiSearch;
12 use PublicInbox::Config;
13 use PublicInbox::Spawn qw(run_die);
14 use PublicInbox::ContentHash qw(git_sha);
15 use PublicInbox::MID qw(mids_for_index);
16 use Digest::SHA qw(sha256_hex);
17 our $LOCAL_PFX = qr!\A(?:maildir|mh|mbox.+|mmdf|v2):!i; # TODO: put in LeiToMail?
18
19 # move this to PublicInbox::Config if other things use it:
20 my %cquote = ("\n" => '\\n', "\t" => '\\t', "\b" => '\\b');
21 sub cquote_val ($) { # cf. git-config(1)
22         my ($val) = @_;
23         $val =~ s/([\n\t\b])/$cquote{$1}/g;
24         $val =~ s/\"/\\\"/g;
25         $val;
26 }
27
28 sub ARRAY_FIELDS () { qw(only include exclude) }
29 sub BOOL_FIELDS () {
30         qw(external local remote import-remote import-before threads)
31 }
32
33 sub SINGLE_FIELDS () { qw(limit dedupe output) }
34
35 sub lss_dir_for ($$;$) {
36         my ($lei, $dstref, $on_fs) = @_;
37         my $pfx;
38         if ($$dstref =~ m,\Aimaps?://,i) { # already canonicalized
39                 require PublicInbox::URIimap;
40                 my $uri = PublicInbox::URIimap->new($$dstref)->canonical;
41                 $$dstref = $$uri;
42                 $pfx = $uri->mailbox;
43         } else {
44                 # can't use Cwd::abs_path since dirname($$dstref) may not exist
45                 $$dstref = $lei->rel2abs($$dstref);
46                 $$dstref =~ tr!/!/!s;
47                 $pfx = $$dstref;
48         }
49         ($pfx) = ($pfx =~ m{([^/]+)/*\z}); # basename
50         my $lss_dir = $lei->share_path . '/saved-searches/';
51         my $d = "$lss_dir$pfx-".sha256_hex($$dstref);
52
53         # fall-back to looking up by st_ino + st_dev in case we're in
54         # a symlinked or bind-mounted path
55         if ($on_fs && !-d $d && -e $$dstref) {
56                 my @cur = stat(_);
57                 my $want = pack('dd', @cur[1,0]); # st_ino + st_dev
58                 my ($c, $o, @st);
59                 for my $g ("$pfx-*", '*') {
60                         my @maybe = glob("$lss_dir$g/lei.saved-search");
61                         for my $f (@maybe) {
62                                 $c = $lei->cfg_dump($f) // next;
63                                 $o = $c->{'lei.q.output'} // next;
64                                 $o =~ s!$LOCAL_PFX!! or next;
65                                 @st = stat($o) or next;
66                                 next if pack('dd', @st[1,0]) ne $want;
67                                 $f =~ m!\A(.+?)/[^/]+\z! and return $1;
68                         }
69                 }
70         }
71         $d;
72 }
73
74 sub list {
75         my ($lei, $pfx) = @_;
76         my $lss_dir = $lei->share_path.'/saved-searches';
77         return () unless -d $lss_dir;
78         # TODO: persist the cache?  Use another format?
79         my $f = $lei->cache_dir."/saved-tmp.$$.".time.'.config';
80         open my $fh, '>', $f or die "open $f: $!";
81         print $fh "[include]\n";
82         for my $p (glob("$lss_dir/*/lei.saved-search")) {
83                 print $fh "\tpath = ", cquote_val($p), "\n";
84         }
85         close $fh or die "close $f: $!";
86         my $cfg = $lei->cfg_dump($f);
87         unlink($f);
88         my $out = $cfg ? $cfg->get_all('lei.q.output') : [];
89         map {;
90                 s!$LOCAL_PFX!!;
91                 $_;
92         } @$out
93 }
94
95 sub translate_dedupe ($$) {
96         my ($self, $lei) = @_;
97         my $dd = $lei->{opt}->{dedupe} // 'content';
98         return 1 if $dd eq 'content'; # the default
99         return $self->{"-dedupe_$dd"} = 1 if ($dd eq 'oid' || $dd eq 'mid');
100         die("--dedupe=$dd requires --no-save\n");
101 }
102
103 sub up { # updating existing saved search via "lei up"
104         my ($cls, $lei, $dst) = @_;
105         my $f;
106         my $self = bless { ale => $lei->ale }, $cls;
107         my $dir = $dst;
108         output2lssdir($self, $lei, \$dir, \$f) or
109                 return die("--no-save was used with $dst cwd=".
110                                         $lei->rel2abs('.')."\n");
111         $self->{-cfg} = $lei->cfg_dump($f) // return $lei->child_error;
112         $self->{-ovf} = "$dir/over.sqlite3";
113         $self->{'-f'} = $f;
114         $self->{lock_path} = "$self->{-f}.flock";
115         $self;
116 }
117
118 sub new { # new saved search "lei q --save"
119         my ($cls, $lei) = @_;
120         my $self = bless { ale => $lei->ale }, $cls;
121         require File::Path;
122         my $dst = $lei->{ovv}->{dst};
123
124         # canonicalize away relative paths into the config
125         if ($lei->{ovv}->{fmt} eq 'maildir' &&
126                         $dst =~ m!(?:/*|\A)\.\.(?:/*|\z)! && !-d $dst) {
127                 File::Path::make_path($dst);
128                 $lei->{ovv}->{dst} = $dst = $lei->abs_path($dst);
129         }
130         my $dir = lss_dir_for($lei, \$dst);
131         File::Path::make_path($dir); # raises on error
132         $self->{-cfg} = {};
133         my $f = $self->{'-f'} = "$dir/lei.saved-search";
134         translate_dedupe($self, $lei) or return;
135         open my $fh, '>', $f or return $lei->fail("open $f: $!");
136         my $sq_dst = PublicInbox::Config::squote_maybe($dst);
137         my $q = $lei->{mset_opt}->{q_raw} // die 'BUG: {q_raw} missing';
138         if (ref $q) {
139                 $q = join("\n", map { "\tq = ".cquote_val($_) } @$q);
140         } else {
141                 $q = "\tq = ".cquote_val($q);
142         }
143         $dst = "$lei->{ovv}->{fmt}:$dst" if $dst !~ m!\Aimaps?://!i;
144         $lei->{opt}->{output} = $dst;
145         print $fh <<EOM;
146 ; to refresh with new results, run: lei up $sq_dst
147 ; `maxuid' and `lastresult' lines are maintained by "lei up" for optimization
148 [lei]
149 $q
150 [lei "q"]
151 EOM
152         for my $k (ARRAY_FIELDS) {
153                 my $ary = $lei->{opt}->{$k} // next;
154                 for my $x (@$ary) {
155                         print $fh "\t$k = ".cquote_val($x)."\n";
156                 }
157         }
158         for my $k (BOOL_FIELDS) {
159                 my $val = $lei->{opt}->{$k} // next;
160                 print $fh "\t$k = ".($val ? 1 : 0)."\n";
161         }
162         for my $k (SINGLE_FIELDS) {
163                 my $val = $lei->{opt}->{$k} // next;
164                 print $fh "\t$k = $val\n";
165         }
166         $lei->{opt}->{stdin} and print $fh <<EOM;
167 [lei "internal"]
168         rawstr = 1 # stdin was used initially
169 EOM
170         close($fh) or return $lei->fail("close $f: $!");
171         $self->{lock_path} = "$self->{-f}.flock";
172         $self->{-ovf} = "$dir/over.sqlite3";
173         $self;
174 }
175
176 sub description { $_[0]->{qstr} } # for WWW
177
178 sub cfg_set { # called by LeiXSearch
179         my ($self, @args) = @_;
180         my $lk = $self->lock_for_scope; # git-config doesn't wait
181         run_die([qw(git config -f), $self->{'-f'}, @args]);
182 }
183
184 # drop-in for LeiDedupe API
185 sub is_dup {
186         my ($self, $eml, $smsg) = @_;
187         my $oidx = $self->{oidx} // die 'BUG: no {oidx}';
188         my $lk;
189         if ($self->{-dedupe_mid}) {
190                 $lk //= $self->lock_for_scope_fast;
191                 for my $mid (@{mids_for_index($eml)}) {
192                         my ($id, $prv);
193                         return 1 if $oidx->next_by_mid($mid, \$id, \$prv);
194                 }
195         }
196         my $blob = $smsg ? $smsg->{blob} : git_sha(1, $eml)->hexdigest;
197         $lk //= $self->lock_for_scope_fast;
198         return 1 if $oidx->blob_exists($blob);
199         if (my $xoids = PublicInbox::LeiSearch::xoids_for($self, $eml, 1)) {
200                 for my $docid (values %$xoids) {
201                         $oidx->add_xref3($docid, -1, $blob, '.');
202                 }
203                 $oidx->commit_lazy;
204                 if ($self->{-dedupe_oid}) {
205                         exists $xoids->{$blob} ? 1 : undef;
206                 } else {
207                         1;
208                 }
209         } else {
210                 # n.b. above xoids_for fills out eml->{-lei_fake_mid} if needed
211                 unless ($smsg) {
212                         $smsg = bless {}, 'PublicInbox::Smsg';
213                         $smsg->{bytes} = 0;
214                         $smsg->populate($eml);
215                 }
216                 $smsg->{blob} //= $blob;
217                 $oidx->begin_lazy;
218                 $smsg->{num} = $oidx->adj_counter('eidx_docid', '+');
219                 $oidx->add_overview($eml, $smsg);
220                 $oidx->add_xref3($smsg->{num}, -1, $blob, '.');
221                 $oidx->commit_lazy;
222                 undef;
223         }
224 }
225
226 sub prepare_dedupe {
227         my ($self) = @_;
228         $self->{oidx} //= do {
229                 my $creat = !-f $self->{-ovf};
230                 my $lk = $self->lock_for_scope; # git-config doesn't wait
231                 my $oidx = PublicInbox::OverIdx->new($self->{-ovf});
232                 $oidx->{-no_fsync} = 1;
233                 $oidx->dbh;
234                 if ($creat) {
235                         $oidx->{dbh}->do('PRAGMA journal_mode = WAL');
236                         $oidx->eidx_prep; # for xref3
237                 }
238                 $oidx
239         };
240 }
241
242 sub over { $_[0]->{oidx} } # for xoids_for
243
244 # don't use ale->git directly since is_dup is called inside
245 # ale->git->cat_async callbacks
246 sub git { $_[0]->{git} //= PublicInbox::Git->new($_[0]->{ale}->git->{git_dir}) }
247
248 sub pause_dedupe {
249         my ($self) = @_;
250         git($self)->cleanup;
251         my $lockfh = delete $self->{lockfh}; # from lock_for_scope_fast;
252         my $oidx = delete($self->{oidx}) // return;
253         $oidx->commit_lazy;
254 }
255
256 sub reset_dedupe {
257         my ($self) = @_;
258         prepare_dedupe($self);
259         my $lk = $self->lock_for_scope_fast;
260         for my $t (qw(xref3 over id2num)) {
261                 $self->{oidx}->{dbh}->do("DELETE FROM $t");
262         }
263         pause_dedupe($self);
264 }
265
266 sub mm { undef }
267
268 sub altid_map { {} }
269
270 sub cloneurl { [] }
271
272 # find existing directory containing a `lei.saved-search' file based on
273 # $dir_ref which is an output
274 sub output2lssdir {
275         my ($self, $lei, $dir_ref, $fn_ref) = @_;
276         my $dst = $$dir_ref; # imap://$MAILBOX, /path/to/maildir, /path/to/mbox
277         my $dir = lss_dir_for($lei, \$dst, 1);
278         my $f = "$dir/lei.saved-search";
279         if (-f $f && -r _) {
280                 $self->{-cfg} = $lei->cfg_dump($f) // return;
281                 $$dir_ref = $dir;
282                 $$fn_ref = $f;
283                 return 1;
284         }
285         undef;
286 }
287
288 # cf. LeiDedupe->has_entries
289 sub has_entries {
290         my $oidx = $_[0]->{oidx} // die 'BUG: no {oidx}';
291         my @n = $oidx->{dbh}->selectrow_array('SELECT num FROM over LIMIT 1');
292         scalar(@n) ? 1 : undef;
293 }
294
295 no warnings 'once';
296 *nntp_url = \&cloneurl;
297 *base_url = \&PublicInbox::Inbox::base_url;
298 *smsg_eml = \&PublicInbox::Inbox::smsg_eml;
299 *smsg_by_mid = \&PublicInbox::Inbox::smsg_by_mid;
300 *msg_by_mid = \&PublicInbox::Inbox::msg_by_mid;
301 *modified = \&PublicInbox::Inbox::modified;
302 *recent = \&PublicInbox::Inbox::recent;
303 *max_git_epoch = *nntp_usable = *msg_by_path = \&mm; # undef
304 *isrch = *search = \&mm; # TODO
305 *DESTROY = \&pause_dedupe;
306
307 1;