1 # Copyright (C) 2021 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
4 # pretends to be like LeiDedupe and also PublicInbox::Inbox
5 package PublicInbox::LeiSavedSearch;
8 use parent qw(PublicInbox::Lock);
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?
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)
23 $val =~ s/([\n\t\b])/$cquote{$1}/g;
27 sub ARRAY_FIELDS () { qw(only include exclude) }
29 qw(external local remote import-remote import-before threads)
34 my $ret = eval { PublicInbox::Config->git_config_dump($f, $lei->{2}) };
40 sub lss_dir_for ($$;$) {
41 my ($lei, $dstref, $on_fs) = @_;
43 if ($$dstref =~ m,\Aimaps?://,i) { # already canonicalized
44 require PublicInbox::URIimap;
45 my $uri = PublicInbox::URIimap->new($$dstref)->canonical;
49 # can't use Cwd::abs_path since dirname($$dstref) may not exist
50 $$dstref = $lei->rel2abs($$dstref);
54 ($pfx) = ($pfx =~ m{([^/]+)/*\z}); # basename
55 my $lss_dir = $lei->share_path . '/saved-searches/';
56 my $d = "$lss_dir$pfx-".sha256_hex($$dstref);
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) {
62 my $want = pack('dd', @cur[1,0]); # st_ino + st_dev
64 for my $g ("$pfx-*", '*') {
65 my @maybe = glob("$lss_dir$g/lei.saved-search");
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;
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";
90 close $fh or die "close $f: $!";
91 my $cfg = cfg_dump($lei, $f);
93 my $out = $cfg ? $cfg->get_all('lei.q.output') : [];
100 sub translate_dedupe ($$$) {
101 my ($self, $lei, $dd) = @_;
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");
108 sub up { # updating existing saved search via "lei up"
109 my ($cls, $lei, $dst) = @_;
111 my $self = bless { ale => $lei->ale }, $cls;
113 output2lssdir($self, $lei, \$dir, \$f) or
114 return $lei->fail("--save was not used with $dst cwd=".
116 $self->{-cfg} = cfg_dump($lei, $f) // return $lei->fail;
117 $self->{-ovf} = "$dir/over.sqlite3";
119 $self->{lock_path} = "$self->{-f}.flock";
123 sub new { # new saved search "lei q --save"
124 my ($cls, $lei) = @_;
125 my $self = bless { ale => $lei->ale }, $cls;
127 my $dst = $lei->{ovv}->{dst};
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);
135 my $dir = lss_dir_for($lei, \$dst);
136 File::Path::make_path($dir); # raises on error
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';
145 $q = join("\n", map { "\tq = ".cquote_val($_) } @$q);
147 $q = "\tq = ".cquote_val($q);
149 $dst = "$lei->{ovv}->{fmt}:$dst" if $dst !~ m!\Aimaps?://!i;
151 ; to refresh with new results, run: lei up $sq_dst
157 print $fh "\tdedupe = $dd\n" if $dd;
158 for my $k (ARRAY_FIELDS) {
159 my $ary = $lei->{opt}->{$k} // next;
161 print $fh "\t$k = ".cquote_val($x)."\n";
164 for my $k (BOOL_FIELDS) {
165 my $val = $lei->{opt}->{$k} // next;
166 print $fh "\t$k = ".($val ? 1 : 0)."\n";
168 close($fh) or return $lei->fail("close $f: $!");
169 $self->{lock_path} = "$self->{-f}.flock";
170 $self->{-ovf} = "$dir/over.sqlite3";
174 sub description { $_[0]->{qstr} } # for WWW
176 sub cfg_set { # called by LeiXSearch
177 my ($self, @args) = @_;
178 my $lk = $self->lock_for_scope; # git-config doesn't wait
179 run_die([qw(git config -f), $self->{'-f'}, @args]);
182 # drop-in for LeiDedupe API
184 my ($self, $eml, $smsg) = @_;
185 my $oidx = $self->{oidx} // die 'BUG: no {oidx}';
187 if ($self->{-dedupe_mid}) {
188 $lk //= $self->lock_for_scope_fast;
189 for my $mid (@{mids_for_index($eml)}) {
191 return 1 if $oidx->next_by_mid($mid, \$id, \$prv);
194 my $blob = $smsg ? $smsg->{blob} : git_sha(1, $eml)->hexdigest;
195 $lk //= $self->lock_for_scope_fast;
196 return 1 if $oidx->blob_exists($blob);
197 if (my $xoids = PublicInbox::LeiSearch::xoids_for($self, $eml, 1)) {
198 for my $docid (values %$xoids) {
199 $oidx->add_xref3($docid, -1, $blob, '.');
202 if ($self->{-dedupe_oid}) {
203 exists $xoids->{$blob} ? 1 : undef;
208 # n.b. above xoids_for fills out eml->{-lei_fake_mid} if needed
210 $smsg = bless {}, 'PublicInbox::Smsg';
212 $smsg->populate($eml);
214 $smsg->{blob} //= $blob;
216 $smsg->{num} = $oidx->adj_counter('eidx_docid', '+');
217 $oidx->add_overview($eml, $smsg);
218 $oidx->add_xref3($smsg->{num}, -1, $blob, '.');
226 $self->{oidx} //= do {
227 my $creat = !-f $self->{-ovf};
228 my $lk = $self->lock_for_scope; # git-config doesn't wait
229 my $oidx = PublicInbox::OverIdx->new($self->{-ovf});
230 $oidx->{-no_fsync} = 1;
233 $oidx->{dbh}->do('PRAGMA journal_mode = WAL');
234 $oidx->eidx_prep; # for xref3
240 sub over { $_[0]->{oidx} } # for xoids_for
242 # don't use ale->git directly since is_dup is called inside
243 # ale->git->cat_async callbacks
244 sub git { $_[0]->{git} //= PublicInbox::Git->new($_[0]->{ale}->git->{git_dir}) }
249 my $lockfh = delete $self->{lockfh}; # from lock_for_scope_fast;
250 my $oidx = delete($self->{oidx}) // return;
256 prepare_dedupe($self);
257 my $lk = $self->lock_for_scope_fast;
258 for my $t (qw(xref3 over id2num)) {
259 $self->{oidx}->{dbh}->do("DELETE FROM $t");
270 # find existing directory containing a `lei.saved-search' file based on
271 # $dir_ref which is an output
273 my ($self, $lei, $dir_ref, $fn_ref) = @_;
274 my $dst = $$dir_ref; # imap://$MAILBOX, /path/to/maildir, /path/to/mbox
275 my $dir = lss_dir_for($lei, \$dst, 1);
276 my $f = "$dir/lei.saved-search";
278 $self->{-cfg} = cfg_dump($lei, $f) // return;
286 # cf. LeiDedupe->has_entries
288 my $oidx = $_[0]->{oidx} // die 'BUG: no {oidx}';
289 my @n = $oidx->{dbh}->selectrow_array('SELECT num FROM over LIMIT 1');
290 scalar(@n) ? 1 : undef;
294 *nntp_url = \&cloneurl;
295 *base_url = \&PublicInbox::Inbox::base_url;
296 *smsg_eml = \&PublicInbox::Inbox::smsg_eml;
297 *smsg_by_mid = \&PublicInbox::Inbox::smsg_by_mid;
298 *msg_by_mid = \&PublicInbox::Inbox::msg_by_mid;
299 *modified = \&PublicInbox::Inbox::modified;
300 *recent = \&PublicInbox::Inbox::recent;
301 *max_git_epoch = *nntp_usable = *msg_by_path = \&mm; # undef
302 *isrch = *search = \&mm; # TODO
303 *DESTROY = \&pause_dedupe;