]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/LeiSavedSearch.pm
lei q: make --save the default
[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         require File::Path;
119         my $dst = $lei->{ovv}->{dst};
120
121         # canonicalize away relative paths into the config
122         if ($lei->{ovv}->{fmt} eq 'maildir' &&
123                         $dst =~ m!(?:/*|\A)\.\.(?:/*|\z)! && !-d $dst) {
124                 File::Path::make_path($dst);
125                 $lei->{ovv}->{dst} = $dst = $lei->abs_path($dst);
126         }
127         my $dir = lss_dir_for($lei, \$dst);
128         File::Path::make_path($dir); # raises on error
129         $self->{-cfg} = {};
130         my $f = $self->{'-f'} = "$dir/lei.saved-search";
131         my $dd = $lei->{opt}->{dedupe};
132         translate_dedupe($self, $lei, $dd) or return;
133         open my $fh, '>', $f or return $lei->fail("open $f: $!");
134         my $sq_dst = PublicInbox::Config::squote_maybe($dst);
135         my $q = $lei->{mset_opt}->{q_raw} // die 'BUG: {q_raw} missing';
136         if (ref $q) {
137                 $q = join("\n", map { "\tq = ".cquote_val($_) } @$q);
138         } else {
139                 $q = "\tq = ".cquote_val($q);
140         }
141         $dst = "$lei->{ovv}->{fmt}:$dst" if $dst !~ m!\Aimaps?://!i;
142         print $fh <<EOM;
143 ; to refresh with new results, run: lei up $sq_dst
144 [lei]
145 $q
146 [lei "q"]
147         output = $dst
148 EOM
149         print $fh "\tdedupe = $dd\n" if $dd;
150         for my $k (ARRAY_FIELDS) {
151                 my $ary = $lei->{opt}->{$k} // next;
152                 for my $x (@$ary) {
153                         print $fh "\t$k = ".cquote_val($x)."\n";
154                 }
155         }
156         for my $k (BOOL_FIELDS) {
157                 my $val = $lei->{opt}->{$k} // next;
158                 print $fh "\t$k = ".($val ? 1 : 0)."\n";
159         }
160         close($fh) or return $lei->fail("close $f: $!");
161         $self->{lock_path} = "$self->{-f}.flock";
162         $self->{-ovf} = "$dir/over.sqlite3";
163         $self;
164 }
165
166 sub description { $_[0]->{qstr} } # for WWW
167
168 sub cfg_set { # called by LeiXSearch
169         my ($self, @args) = @_;
170         my $lk = $self->lock_for_scope; # git-config doesn't wait
171         run_die([qw(git config -f), $self->{'-f'}, @args]);
172 }
173
174 # drop-in for LeiDedupe API
175 sub is_dup {
176         my ($self, $eml, $smsg) = @_;
177         my $oidx = $self->{oidx} // die 'BUG: no {oidx}';
178         my $lk;
179         if ($self->{-dedupe_mid}) {
180                 $lk //= $self->lock_for_scope_fast;
181                 for my $mid (@{mids_for_index($eml)}) {
182                         my ($id, $prv);
183                         return 1 if $oidx->next_by_mid($mid, \$id, \$prv);
184                 }
185         }
186         my $blob = $smsg ? $smsg->{blob} : git_sha(1, $eml)->hexdigest;
187         $lk //= $self->lock_for_scope_fast;
188         return 1 if $oidx->blob_exists($blob);
189         if (my $xoids = PublicInbox::LeiSearch::xoids_for($self, $eml, 1)) {
190                 for my $docid (values %$xoids) {
191                         $oidx->add_xref3($docid, -1, $blob, '.');
192                 }
193                 $oidx->commit_lazy;
194                 if ($self->{-dedupe_oid}) {
195                         exists $xoids->{$blob} ? 1 : undef;
196                 } else {
197                         1;
198                 }
199         } else {
200                 # n.b. above xoids_for fills out eml->{-lei_fake_mid} if needed
201                 unless ($smsg) {
202                         $smsg = bless {}, 'PublicInbox::Smsg';
203                         $smsg->{bytes} = 0;
204                         $smsg->populate($eml);
205                 }
206                 $smsg->{blob} //= $blob;
207                 $oidx->begin_lazy;
208                 $smsg->{num} = $oidx->adj_counter('eidx_docid', '+');
209                 $oidx->add_overview($eml, $smsg);
210                 $oidx->add_xref3($smsg->{num}, -1, $blob, '.');
211                 $oidx->commit_lazy;
212                 undef;
213         }
214 }
215
216 sub prepare_dedupe {
217         my ($self) = @_;
218         $self->{oidx} //= do {
219                 my $creat = !-f $self->{-ovf};
220                 my $lk = $self->lock_for_scope; # git-config doesn't wait
221                 my $oidx = PublicInbox::OverIdx->new($self->{-ovf});
222                 $oidx->{-no_fsync} = 1;
223                 $oidx->dbh;
224                 if ($creat) {
225                         $oidx->{dbh}->do('PRAGMA journal_mode = WAL');
226                         $oidx->eidx_prep; # for xref3
227                 }
228                 $oidx
229         };
230 }
231
232 sub over { $_[0]->{oidx} } # for xoids_for
233
234 # don't use ale->git directly since is_dup is called inside
235 # ale->git->cat_async callbacks
236 sub git { $_[0]->{git} //= PublicInbox::Git->new($_[0]->{ale}->git->{git_dir}) }
237
238 sub pause_dedupe {
239         my ($self) = @_;
240         git($self)->cleanup;
241         my $lockfh = delete $self->{lockfh}; # from lock_for_scope_fast;
242         my $oidx = delete($self->{oidx}) // return;
243         $oidx->commit_lazy;
244 }
245
246 sub reset_dedupe {
247         my ($self) = @_;
248         prepare_dedupe($self);
249         my $lk = $self->lock_for_scope_fast;
250         for my $t (qw(xref3 over id2num)) {
251                 $self->{oidx}->{dbh}->do("DELETE FROM $t");
252         }
253         pause_dedupe($self);
254 }
255
256 sub mm { undef }
257
258 sub altid_map { {} }
259
260 sub cloneurl { [] }
261
262 # find existing directory containing a `lei.saved-search' file based on
263 # $dir_ref which is an output
264 sub output2lssdir {
265         my ($self, $lei, $dir_ref, $fn_ref) = @_;
266         my $dst = $$dir_ref; # imap://$MAILBOX, /path/to/maildir, /path/to/mbox
267         my $dir = lss_dir_for($lei, \$dst, 1);
268         my $f = "$dir/lei.saved-search";
269         if (-f $f && -r _) {
270                 $self->{-cfg} = PublicInbox::Config->git_config_dump($f);
271                 $$dir_ref = $dir;
272                 $$fn_ref = $f;
273                 return 1;
274         }
275         undef;
276 }
277
278 sub edit_begin {
279         my ($self, $lei) = @_;
280         if (ref($self->{-cfg}->{'lei.q.output'})) {
281                 delete $self->{-cfg}->{'lei.q.output'}; # invalid
282                 $lei->err(<<EOM);
283 $self->{-f} has multiple values of lei.q.output
284 please remove redundant ones
285 EOM
286         }
287         $lei->{-lss_for_edit} = $self;
288 }
289
290 sub edit_done {
291         my ($self, $lei) = @_;
292         my $cfg = PublicInbox::Config->git_config_dump($self->{'-f'});
293         my $new_out = $cfg->{'lei.q.output'} // '';
294         return $lei->fail(<<EOM) if ref $new_out;
295 $self->{-f} has multiple values of lei.q.output
296 please edit again
297 EOM
298         return $lei->fail(<<EOM) if $new_out eq '';
299 $self->{-f} needs lei.q.output
300 please edit again
301 EOM
302         my $old_out = $self->{-cfg}->{'lei.q.output'} // '';
303         return if $old_out eq $new_out;
304         my $old_path = $old_out;
305         my $new_path = $new_out;
306         s!$LOCAL_PFX!! for ($old_path, $new_path);
307         my $dir_old = lss_dir_for($lei, \$old_path, 1);
308         my $dir_new = lss_dir_for($lei, \$new_path);
309         return if $dir_new eq $dir_old; # no change, likely
310
311         ($old_out =~ m!\Av2:!i || $new_out =~ m!\Av2:!) and
312                 return $lei->fail(<<EOM);
313 conversions from/to v2 inboxes not supported at this time
314 EOM
315
316         return $lei->fail(<<EOM) if -e $dir_new;
317 lei.q.output changed from `$old_out' to `$new_out'
318 However, $dir_new exists
319 EOM
320         # start the conversion asynchronously
321         my $old_sq = PublicInbox::Config::squote_maybe($old_out);
322         my $new_sq = PublicInbox::Config::squote_maybe($new_out);
323         $lei->puts("lei.q.output changed from $old_sq to $new_sq");
324         $lei->qerr("# lei convert $old_sq -o $new_sq");
325         my $v = !$lei->{opt}->{quiet};
326         $lei->{opt} = { output => $new_out, verbose => $v };
327         require PublicInbox::LeiConvert;
328         PublicInbox::LeiConvert::lei_convert($lei, $old_out);
329
330         $lei->fail(<<EOM) if -e $dir_old && !rename($dir_old, $dir_new);
331 E: rename($dir_old, $dir_new) error: $!
332 EOM
333 }
334
335 # cf. LeiDedupe->has_entries
336 sub has_entries {
337         my $oidx = $_[0]->{oidx} // die 'BUG: no {oidx}';
338         my @n = $oidx->{dbh}->selectrow_array('SELECT num FROM over LIMIT 1');
339         scalar(@n) ? 1 : undef;
340 }
341
342 no warnings 'once';
343 *nntp_url = \&cloneurl;
344 *base_url = \&PublicInbox::Inbox::base_url;
345 *smsg_eml = \&PublicInbox::Inbox::smsg_eml;
346 *smsg_by_mid = \&PublicInbox::Inbox::smsg_by_mid;
347 *msg_by_mid = \&PublicInbox::Inbox::msg_by_mid;
348 *modified = \&PublicInbox::Inbox::modified;
349 *recent = \&PublicInbox::Inbox::recent;
350 *max_git_epoch = *nntp_usable = *msg_by_path = \&mm; # undef
351 *isrch = *search = \&mm; # TODO
352 *DESTROY = \&pause_dedupe;
353
354 1;