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