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