]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/LeiSavedSearch.pm
lei config --edit: use controlling terminal
[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 lss_dir_for ($$;$) {
33         my ($lei, $dstref, $on_fs) = @_;
34         my $pfx;
35         if ($$dstref =~ m,\Aimaps?://,i) { # already canonicalized
36                 require PublicInbox::URIimap;
37                 my $uri = PublicInbox::URIimap->new($$dstref)->canonical;
38                 $$dstref = $$uri;
39                 $pfx = $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                 $pfx = $$dstref;
45         }
46         ($pfx) = ($pfx =~ m{([^/]+)/*\z}); # basename
47         my $lss_dir = $lei->share_path . '/saved-searches/';
48         my $d = "$lss_dir$pfx-".sha256_hex($$dstref);
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 ("$pfx-*", '*') {
57                         my @maybe = glob("$lss_dir$g/lei.saved-search");
58                         for my $f (@maybe) {
59                                 $c = $lei->cfg_dump($f) // next;
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 = $lei->cfg_dump($f);
84         unlink($f);
85         my $out = $cfg ? $cfg->get_all('lei.q.output') : [];
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} = $lei->cfg_dump($f) // return $lei->fail;
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 ; `maxuid' and `lastresult' lines are maintained by "lei up" for optimization
145 [lei]
146 $q
147 [lei "q"]
148         output = $dst
149 EOM
150         print $fh "\tdedupe = $dd\n" if $dd;
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         close($fh) or return $lei->fail("close $f: $!");
162         $self->{lock_path} = "$self->{-f}.flock";
163         $self->{-ovf} = "$dir/over.sqlite3";
164         $self;
165 }
166
167 sub description { $_[0]->{qstr} } # for WWW
168
169 sub cfg_set { # called by LeiXSearch
170         my ($self, @args) = @_;
171         my $lk = $self->lock_for_scope; # git-config doesn't wait
172         run_die([qw(git config -f), $self->{'-f'}, @args]);
173 }
174
175 # drop-in for LeiDedupe API
176 sub is_dup {
177         my ($self, $eml, $smsg) = @_;
178         my $oidx = $self->{oidx} // die 'BUG: no {oidx}';
179         my $lk;
180         if ($self->{-dedupe_mid}) {
181                 $lk //= $self->lock_for_scope_fast;
182                 for my $mid (@{mids_for_index($eml)}) {
183                         my ($id, $prv);
184                         return 1 if $oidx->next_by_mid($mid, \$id, \$prv);
185                 }
186         }
187         my $blob = $smsg ? $smsg->{blob} : git_sha(1, $eml)->hexdigest;
188         $lk //= $self->lock_for_scope_fast;
189         return 1 if $oidx->blob_exists($blob);
190         if (my $xoids = PublicInbox::LeiSearch::xoids_for($self, $eml, 1)) {
191                 for my $docid (values %$xoids) {
192                         $oidx->add_xref3($docid, -1, $blob, '.');
193                 }
194                 $oidx->commit_lazy;
195                 if ($self->{-dedupe_oid}) {
196                         exists $xoids->{$blob} ? 1 : undef;
197                 } else {
198                         1;
199                 }
200         } else {
201                 # n.b. above xoids_for fills out eml->{-lei_fake_mid} if needed
202                 unless ($smsg) {
203                         $smsg = bless {}, 'PublicInbox::Smsg';
204                         $smsg->{bytes} = 0;
205                         $smsg->populate($eml);
206                 }
207                 $smsg->{blob} //= $blob;
208                 $oidx->begin_lazy;
209                 $smsg->{num} = $oidx->adj_counter('eidx_docid', '+');
210                 $oidx->add_overview($eml, $smsg);
211                 $oidx->add_xref3($smsg->{num}, -1, $blob, '.');
212                 $oidx->commit_lazy;
213                 undef;
214         }
215 }
216
217 sub prepare_dedupe {
218         my ($self) = @_;
219         $self->{oidx} //= do {
220                 my $creat = !-f $self->{-ovf};
221                 my $lk = $self->lock_for_scope; # git-config doesn't wait
222                 my $oidx = PublicInbox::OverIdx->new($self->{-ovf});
223                 $oidx->{-no_fsync} = 1;
224                 $oidx->dbh;
225                 if ($creat) {
226                         $oidx->{dbh}->do('PRAGMA journal_mode = WAL');
227                         $oidx->eidx_prep; # for xref3
228                 }
229                 $oidx
230         };
231 }
232
233 sub over { $_[0]->{oidx} } # for xoids_for
234
235 # don't use ale->git directly since is_dup is called inside
236 # ale->git->cat_async callbacks
237 sub git { $_[0]->{git} //= PublicInbox::Git->new($_[0]->{ale}->git->{git_dir}) }
238
239 sub pause_dedupe {
240         my ($self) = @_;
241         git($self)->cleanup;
242         my $lockfh = delete $self->{lockfh}; # from lock_for_scope_fast;
243         my $oidx = delete($self->{oidx}) // return;
244         $oidx->commit_lazy;
245 }
246
247 sub reset_dedupe {
248         my ($self) = @_;
249         prepare_dedupe($self);
250         my $lk = $self->lock_for_scope_fast;
251         for my $t (qw(xref3 over id2num)) {
252                 $self->{oidx}->{dbh}->do("DELETE FROM $t");
253         }
254         pause_dedupe($self);
255 }
256
257 sub mm { undef }
258
259 sub altid_map { {} }
260
261 sub cloneurl { [] }
262
263 # find existing directory containing a `lei.saved-search' file based on
264 # $dir_ref which is an output
265 sub output2lssdir {
266         my ($self, $lei, $dir_ref, $fn_ref) = @_;
267         my $dst = $$dir_ref; # imap://$MAILBOX, /path/to/maildir, /path/to/mbox
268         my $dir = lss_dir_for($lei, \$dst, 1);
269         my $f = "$dir/lei.saved-search";
270         if (-f $f && -r _) {
271                 $self->{-cfg} = $lei->cfg_dump($f) // return;
272                 $$dir_ref = $dir;
273                 $$fn_ref = $f;
274                 return 1;
275         }
276         undef;
277 }
278
279 # cf. LeiDedupe->has_entries
280 sub has_entries {
281         my $oidx = $_[0]->{oidx} // die 'BUG: no {oidx}';
282         my @n = $oidx->{dbh}->selectrow_array('SELECT num FROM over LIMIT 1');
283         scalar(@n) ? 1 : undef;
284 }
285
286 no warnings 'once';
287 *nntp_url = \&cloneurl;
288 *base_url = \&PublicInbox::Inbox::base_url;
289 *smsg_eml = \&PublicInbox::Inbox::smsg_eml;
290 *smsg_by_mid = \&PublicInbox::Inbox::smsg_by_mid;
291 *msg_by_mid = \&PublicInbox::Inbox::msg_by_mid;
292 *modified = \&PublicInbox::Inbox::modified;
293 *recent = \&PublicInbox::Inbox::recent;
294 *max_git_epoch = *nntp_usable = *msg_by_path = \&mm; # undef
295 *isrch = *search = \&mm; # TODO
296 *DESTROY = \&pause_dedupe;
297
298 1;