]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/LeiSavedSearch.pm
lei up: support symlinked pathnames
[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::OverIdx;
10 use PublicInbox::LeiSearch;
11 use PublicInbox::Config;
12 use PublicInbox::Spawn qw(run_die);
13 use PublicInbox::ContentHash qw(git_sha);
14 use PublicInbox::MID qw(mids_for_index);
15 use Digest::SHA qw(sha256_hex);
16 my $LOCAL_PFX = qr!\A(?:maildir|mh|mbox.+|mmdf):!i; # TODO: put in LeiToMail?
17
18 # move this to PublicInbox::Config if other things use it:
19 my %cquote = ("\n" => '\\n', "\t" => '\\t', "\b" => '\\b');
20 sub cquote_val ($) { # cf. git-config(1)
21         my ($val) = @_;
22         $val =~ s/([\n\t\b])/$cquote{$1}/g;
23         $val;
24 }
25
26 sub ARRAY_FIELDS () { qw(only include exclude) }
27 sub BOOL_FIELDS () {
28         qw(external local remote import-remote import-before threads)
29 }
30
31 sub lss_dir_for ($$;$) {
32         my ($lei, $dstref, $on_fs) = @_;
33         my @n;
34         if ($$dstref =~ m,\Aimaps?://,i) { # already canonicalized
35                 require PublicInbox::URIimap;
36                 my $uri = PublicInbox::URIimap->new($$dstref)->canonical;
37                 $$dstref = $$uri;
38                 @n = ($uri->mailbox);
39         } else {
40                 # can't use Cwd::abs_path since dirname($$dstref) may not exist
41                 $$dstref = $lei->rel2abs($$dstref);
42                 # Maildirs have trailing '/' internally
43                 $$dstref .= '/' if -d $$dstref;
44                 $$dstref =~ tr!/!/!s;
45                 @n = ($$dstref =~ m{([^/]+)/*\z}); # basename
46         }
47         push @n, sha256_hex($$dstref);
48         my $lss_dir = $lei->share_path . '/saved-searches/';
49         my $d = $lss_dir . join('-', @n);
50
51         # fall-back to looking up by st_ino + st_dev in case we're in
52         # a symlinked or bind-mounted path
53         if ($on_fs && !-d $d && -e $$dstref) {
54                 my @cur = stat(_);
55                 my $want = pack('dd', @cur[1,0]); # st_ino + st_dev
56                 my ($c, $o, @st);
57                 for my $g ("$n[0]-*", '*') {
58                         my @maybe = glob("$lss_dir$g/lei.saved-search");
59                         for my $f (@maybe) {
60                                 $c = PublicInbox::Config->git_config_dump($f);
61                                 $o = $c->{'lei.q.output'} // next;
62                                 $o =~ s!$LOCAL_PFX!! or next;
63                                 @st = stat($o) or next;
64                                 next if pack('dd', @st[1,0]) ne $want;
65                                 $f =~ m!\A(.+?)/[^/]+\z! and return $1;
66                         }
67                 }
68         }
69         $d;
70 }
71
72 sub list {
73         my ($lei, $pfx) = @_;
74         my $lss_dir = $lei->share_path.'/saved-searches';
75         return () unless -d $lss_dir;
76         # TODO: persist the cache?  Use another format?
77         my $f = $lei->cache_dir."/saved-tmp.$$.".time.'.config';
78         open my $fh, '>', $f or die "open $f: $!";
79         print $fh "[include]\n";
80         for my $p (glob("$lss_dir/*/lei.saved-search")) {
81                 print $fh "\tpath = ", cquote_val($p), "\n";
82         }
83         close $fh or die "close $f: $!";
84         my $cfg = PublicInbox::Config->git_config_dump($f);
85         unlink($f);
86         my $out = $cfg->get_all('lei.q.output') or return ();
87         map {;
88                 s!$LOCAL_PFX!!;
89                 $_;
90         } @$out
91 }
92
93 sub translate_dedupe ($$$) {
94         my ($self, $lei, $dd) = @_;
95         $dd //= 'content';
96         return 1 if $dd eq 'content'; # the default
97         return $self->{"-dedupe_$dd"} = 1 if ($dd eq 'oid' || $dd eq 'mid');
98         $lei->fail("--dedupe=$dd unsupported with --save");
99 }
100
101 sub up { # updating existing saved search via "lei up"
102         my ($cls, $lei, $dst) = @_;
103         my $f;
104         my $self = bless { ale => $lei->ale }, $cls;
105         my $dir = $dst;
106         output2lssdir($self, $lei, \$dir, \$f) or
107                 return $lei->fail("--save was not used with $dst cwd=".
108                                         $lei->rel2abs('.'));
109         $self->{-cfg} = PublicInbox::Config->git_config_dump($f);
110         $self->{-ovf} = "$dir/over.sqlite3";
111         $self->{'-f'} = $f;
112         $self->{lock_path} = "$self->{-f}.flock";
113         $self;
114 }
115
116 sub new { # new saved search "lei q --save"
117         my ($cls, $lei) = @_;
118         my $self = bless { ale => $lei->ale }, $cls;
119         my $dst = $lei->{ovv}->{dst};
120         my $dir = lss_dir_for($lei, \$dst);
121         require File::Path;
122         File::Path::make_path($dir); # raises on error
123         $self->{-cfg} = {};
124         my $f = $self->{'-f'} = "$dir/lei.saved-search";
125         my $dd = $lei->{opt}->{dedupe};
126         translate_dedupe($self, $lei, $dd) or return;
127         open my $fh, '>', $f or return $lei->fail("open $f: $!");
128         my $sq_dst = PublicInbox::Config::squote_maybe($dst);
129         my $q = $lei->{mset_opt}->{q_raw} // die 'BUG: {q_raw} missing';
130         if (ref $q) {
131                 $q = join("\n", map { "\tq = ".cquote_val($_) } @$q);
132         } else {
133                 $q = "\tq = ".cquote_val($q);
134         }
135         $dst = "$lei->{ovv}->{fmt}:$dst" if $dst !~ m!\Aimaps?://!i;
136         print $fh <<EOM;
137 ; to refresh with new results, run: lei up $sq_dst
138 [lei]
139         $q
140 [lei "q"]
141         output = $dst
142 EOM
143         print $fh "\tdedupe = $dd\n" if $dd;
144         for my $k (ARRAY_FIELDS) {
145                 my $ary = $lei->{opt}->{$k} // next;
146                 for my $x (@$ary) {
147                         print $fh "\t$k = ".cquote_val($x)."\n";
148                 }
149         }
150         for my $k (BOOL_FIELDS) {
151                 my $val = $lei->{opt}->{$k} // next;
152                 print $fh "\t$k = ".($val ? 1 : 0)."\n";
153         }
154         close($fh) or return $lei->fail("close $f: $!");
155         $self->{lock_path} = "$self->{-f}.flock";
156         $self->{-ovf} = "$dir/over.sqlite3";
157         $self;
158 }
159
160 sub description { $_[0]->{qstr} } # for WWW
161
162 sub cfg_set { # called by LeiXSearch
163         my ($self, @args) = @_;
164         my $lk = $self->lock_for_scope; # git-config doesn't wait
165         run_die([qw(git config -f), $self->{'-f'}, @args]);
166 }
167
168 # drop-in for LeiDedupe API
169 sub is_dup {
170         my ($self, $eml, $smsg) = @_;
171         my $oidx = $self->{oidx} // die 'BUG: no {oidx}';
172         my $blob = $smsg ? $smsg->{blob} : undef;
173         my $lk = $self->lock_for_scope_fast;
174         return 1 if $blob && $oidx->blob_exists($blob);
175         if ($self->{-dedupe_mid}) {
176                 for my $mid (@{mids_for_index($eml)}) {
177                         my ($id, $prv);
178                         return 1 if $oidx->next_by_mid($mid, \$id, \$prv);
179                 }
180         }
181         if (my $xoids = PublicInbox::LeiSearch::xoids_for($self, $eml, 1)) {
182                 for my $docid (values %$xoids) {
183                         $oidx->add_xref3($docid, -1, $blob, '.');
184                 }
185                 $oidx->commit_lazy;
186                 if ($self->{-dedupe_oid}) {
187                         $smsg->{blob} //= git_sha(1, $eml)->hexdigest;
188                         exists $xoids->{$smsg->{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                 $oidx->begin_lazy;
200                 $smsg->{num} = $oidx->adj_counter('eidx_docid', '+');
201                 $smsg->{blob} //= git_sha(1, $eml)->hexdigest;
202                 $oidx->add_overview($eml, $smsg);
203                 $oidx->add_xref3($smsg->{num}, -1, $smsg->{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 sub git { $_[0]->{ale}->git }
228
229 sub pause_dedupe {
230         my ($self) = @_;
231         $self->{ale}->git->cleanup;
232         my $lockfh = delete $self->{lockfh}; # from lock_for_scope_fast;
233         my $oidx = delete($self->{oidx}) // return;
234         $oidx->commit_lazy;
235 }
236
237 sub mm { undef }
238
239 sub altid_map { {} }
240
241 sub cloneurl { [] }
242
243 # find existing directory containing a `lei.saved-search' file based on
244 # $dir_ref which is an output
245 sub output2lssdir {
246         my ($self, $lei, $dir_ref, $fn_ref) = @_;
247         my $dst = $$dir_ref; # imap://$MAILBOX, /path/to/maildir, /path/to/mbox
248         my $dir = lss_dir_for($lei, \$dst, 1);
249         my $f = "$dir/lei.saved-search";
250         if (-f $f && -r _) {
251                 $self->{-cfg} = PublicInbox::Config->git_config_dump($f);
252                 $$dir_ref = $dir;
253                 $$fn_ref = $f;
254                 return 1;
255         }
256         undef;
257 }
258
259 no warnings 'once';
260 *nntp_url = \&cloneurl;
261 *base_url = \&PublicInbox::Inbox::base_url;
262 *smsg_eml = \&PublicInbox::Inbox::smsg_eml;
263 *smsg_by_mid = \&PublicInbox::Inbox::smsg_by_mid;
264 *msg_by_mid = \&PublicInbox::Inbox::msg_by_mid;
265 *modified = \&PublicInbox::Inbox::modified;
266 *recent = \&PublicInbox::Inbox::recent;
267 *max_git_epoch = *nntp_usable = *msg_by_path = \&mm; # undef
268 *isrch = *search = \&mm; # TODO
269 *DESTROY = \&pause_dedupe;
270
271 1;