]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/LeiSavedSearch.pm
lei: saved searches support --dedupe=<mid|oid>
[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
17 # move this to PublicInbox::Config if other things use it:
18 my %cquote = ("\n" => '\\n', "\t" => '\\t', "\b" => '\\b');
19 sub cquote_val ($) { # cf. git-config(1)
20         my ($val) = @_;
21         $val =~ s/([\n\t\b])/$cquote{$1}/g;
22         $val;
23 }
24
25 sub ARRAY_FIELDS () { qw(only include exclude) }
26 sub BOOL_FIELDS () {
27         qw(external local remote import-remote import-before threads)
28 }
29
30 sub lss_dir_for ($$) {
31         my ($lei, $dstref) = @_;
32         my @n;
33         if ($$dstref =~ m,\Aimaps?://,i) { # already canonicalized
34                 require PublicInbox::URIimap;
35                 my $uri = PublicInbox::URIimap->new($$dstref)->canonical;
36                 $$dstref = $$uri;
37                 @n = ($uri->mailbox);
38         } else { # basename
39                 $$dstref = $lei->rel2abs($$dstref);
40                 $$dstref .= '/' if -d $$dstref;
41                 $$dstref =~ tr!/!/!s;
42                 @n = ($$dstref =~ m{([^/]+)/*\z});
43         }
44         push @n, sha256_hex($$dstref);
45         $lei->share_path . '/saved-searches/' . join('-', @n);
46 }
47
48 sub list {
49         my ($lei, $pfx) = @_;
50         my $lss_dir = $lei->share_path.'/saved-searches/';
51         return () unless -d $lss_dir;
52         # TODO: persist the cache?  Use another format?
53         my $f = $lei->cache_dir."/saved-tmp.$$.".time.'.config';
54         open my $fh, '>', $f or die "open $f: $!";
55         print $fh "[include]\n";
56         for my $p (glob("$lss_dir/*/lei.saved-search")) {
57                 print $fh "\tpath = ", cquote_val($p), "\n";
58         }
59         close $fh or die "close $f: $!";
60         my $cfg = PublicInbox::Config->git_config_dump($f);
61         unlink($f);
62         my $out = $cfg->get_all('lei.q.output') or return ();
63         map {;
64                 s!\A(?:maildir|mh|mbox.+|mmdf):!!i;
65                 $_;
66         } @$out
67 }
68
69 sub translate_dedupe ($$$) {
70         my ($self, $lei, $dd) = @_;
71         $dd //= 'content';
72         return 1 if $dd eq 'content'; # the default
73         return $self->{"-dedupe_$dd"} = 1 if ($dd eq 'oid' || $dd eq 'mid');
74         $lei->fail("--dedupe=$dd unsupported with --save");
75 }
76
77 sub up { # updating existing saved search via "lei up"
78         my ($cls, $lei, $dst) = @_;
79         my $f;
80         my $self = bless { ale => $lei->ale }, $cls;
81         my $dir = $dst;
82         output2lssdir($self, $lei, \$dir, \$f) or
83                 return $lei->fail("--save was not used with $dst cwd=".
84                                         $lei->rel2abs('.'));
85         $self->{-cfg} = PublicInbox::Config->git_config_dump($f);
86         $self->{-ovf} = "$dir/over.sqlite3";
87         $self->{'-f'} = $f;
88         $self->{lock_path} = "$self->{-f}.flock";
89         $self;
90 }
91
92 sub new { # new saved search "lei q --save"
93         my ($cls, $lei) = @_;
94         my $self = bless { ale => $lei->ale }, $cls;
95         my $dst = $lei->{ovv}->{dst};
96         my $dir = lss_dir_for($lei, \$dst);
97         require File::Path;
98         File::Path::make_path($dir); # raises on error
99         $self->{-cfg} = {};
100         my $f = $self->{'-f'} = "$dir/lei.saved-search";
101         my $dd = $lei->{opt}->{dedupe};
102         translate_dedupe($self, $lei, $dd) or return;
103         open my $fh, '>', $f or return $lei->fail("open $f: $!");
104         my $sq_dst = PublicInbox::Config::squote_maybe($dst);
105         my $q = $lei->{mset_opt}->{q_raw} // die 'BUG: {q_raw} missing';
106         if (ref $q) {
107                 $q = join("\n", map { "\tq = ".cquote_val($_) } @$q);
108         } else {
109                 $q = "\tq = ".cquote_val($q);
110         }
111         $dst = "$lei->{ovv}->{fmt}:$dst" if $dst !~ m!\Aimaps?://!i;
112         print $fh <<EOM;
113 ; to refresh with new results, run: lei up $sq_dst
114 [lei]
115         $q
116 [lei "q"]
117         output = $dst
118 EOM
119         print $fh "\tdedupe = $dd\n" if $dd;
120         for my $k (ARRAY_FIELDS) {
121                 my $ary = $lei->{opt}->{$k} // next;
122                 for my $x (@$ary) {
123                         print $fh "\t$k = ".cquote_val($x)."\n";
124                 }
125         }
126         for my $k (BOOL_FIELDS) {
127                 my $val = $lei->{opt}->{$k} // next;
128                 print $fh "\t$k = ".($val ? 1 : 0)."\n";
129         }
130         close($fh) or return $lei->fail("close $f: $!");
131         $self->{lock_path} = "$self->{-f}.flock";
132         $self->{-ovf} = "$dir/over.sqlite3";
133         $self;
134 }
135
136 sub description { $_[0]->{qstr} } # for WWW
137
138 sub cfg_set { # called by LeiXSearch
139         my ($self, @args) = @_;
140         my $lk = $self->lock_for_scope; # git-config doesn't wait
141         run_die([qw(git config -f), $self->{'-f'}, @args]);
142 }
143
144 # drop-in for LeiDedupe API
145 sub is_dup {
146         my ($self, $eml, $smsg) = @_;
147         my $oidx = $self->{oidx} // die 'BUG: no {oidx}';
148         my $blob = $smsg ? $smsg->{blob} : undef;
149         my $lk = $self->lock_for_scope_fast;
150         return 1 if $blob && $oidx->blob_exists($blob);
151         if ($self->{-dedupe_mid}) {
152                 for my $mid (@{mids_for_index($eml)}) {
153                         my ($id, $prv);
154                         return 1 if $oidx->next_by_mid($mid, \$id, \$prv);
155                 }
156         }
157         if (my $xoids = PublicInbox::LeiSearch::xoids_for($self, $eml, 1)) {
158                 for my $docid (values %$xoids) {
159                         $oidx->add_xref3($docid, -1, $blob, '.');
160                 }
161                 $oidx->commit_lazy;
162                 if ($self->{-dedupe_oid}) {
163                         $smsg->{blob} //= git_sha(1, $eml)->hexdigest;
164                         exists $xoids->{$smsg->{blob}} ? 1 : undef;
165                 } else {
166                         1;
167                 }
168         } else {
169                 # n.b. above xoids_for fills out eml->{-lei_fake_mid} if needed
170                 unless ($smsg) {
171                         $smsg = bless {}, 'PublicInbox::Smsg';
172                         $smsg->{bytes} = 0;
173                         $smsg->populate($eml);
174                 }
175                 $oidx->begin_lazy;
176                 $smsg->{num} = $oidx->adj_counter('eidx_docid', '+');
177                 $smsg->{blob} //= git_sha(1, $eml)->hexdigest;
178                 $oidx->add_overview($eml, $smsg);
179                 $oidx->add_xref3($smsg->{num}, -1, $smsg->{blob}, '.');
180                 $oidx->commit_lazy;
181                 undef;
182         }
183 }
184
185 sub prepare_dedupe {
186         my ($self) = @_;
187         $self->{oidx} //= do {
188                 my $creat = !-f $self->{-ovf};
189                 my $lk = $self->lock_for_scope; # git-config doesn't wait
190                 my $oidx = PublicInbox::OverIdx->new($self->{-ovf});
191                 $oidx->{-no_fsync} = 1;
192                 $oidx->dbh;
193                 if ($creat) {
194                         $oidx->{dbh}->do('PRAGMA journal_mode = WAL');
195                         $oidx->eidx_prep; # for xref3
196                 }
197                 $oidx
198         };
199 }
200
201 sub over { $_[0]->{oidx} } # for xoids_for
202
203 sub git { $_[0]->{ale}->git }
204
205 sub pause_dedupe {
206         my ($self) = @_;
207         $self->{ale}->git->cleanup;
208         my $lockfh = delete $self->{lockfh}; # from lock_for_scope_fast;
209         my $oidx = delete($self->{oidx}) // return;
210         $oidx->commit_lazy;
211 }
212
213 sub mm { undef }
214
215 sub altid_map { {} }
216
217 sub cloneurl { [] }
218
219 # find existing directory containing a `lei.saved-search' file based on
220 # $dir_ref which is an output
221 sub output2lssdir {
222         my ($self, $lei, $dir_ref, $fn_ref) = @_;
223         my $dst = $$dir_ref; # imap://$MAILBOX, /path/to/maildir, /path/to/mbox
224         my $dir = lss_dir_for($lei, \$dst);
225         my $f = "$dir/lei.saved-search";
226         if (-f $f && -r _) {
227                 $self->{-cfg} = PublicInbox::Config->git_config_dump($f);
228                 $$dir_ref = $dir;
229                 $$fn_ref = $f;
230                 return 1;
231         }
232         undef;
233 }
234
235 no warnings 'once';
236 *nntp_url = \&cloneurl;
237 *base_url = \&PublicInbox::Inbox::base_url;
238 *smsg_eml = \&PublicInbox::Inbox::smsg_eml;
239 *smsg_by_mid = \&PublicInbox::Inbox::smsg_by_mid;
240 *msg_by_mid = \&PublicInbox::Inbox::msg_by_mid;
241 *modified = \&PublicInbox::Inbox::modified;
242 *recent = \&PublicInbox::Inbox::recent;
243 *max_git_epoch = *nntp_usable = *msg_by_path = \&mm; # undef
244 *isrch = *search = \&mm; # TODO
245 *DESTROY = \&pause_dedupe;
246
247 1;