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