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);
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?
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)
22 $val =~ s/([\n\t\b])/$cquote{$1}/g;
26 sub ARRAY_FIELDS () { qw(only include exclude) }
28 qw(external local remote import-remote import-before threads)
31 sub lss_dir_for ($$;$) {
32 my ($lei, $dstref, $on_fs) = @_;
34 if ($$dstref =~ m,\Aimaps?://,i) { # already canonicalized
35 require PublicInbox::URIimap;
36 my $uri = PublicInbox::URIimap->new($$dstref)->canonical;
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;
45 @n = ($$dstref =~ m{([^/]+)/*\z}); # basename
47 push @n, sha256_hex($$dstref);
48 my $lss_dir = $lei->share_path . '/saved-searches/';
49 my $d = $lss_dir . join('-', @n);
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) {
55 my $want = pack('dd', @cur[1,0]); # st_ino + st_dev
57 for my $g ("$n[0]-*", '*') {
58 my @maybe = glob("$lss_dir$g/lei.saved-search");
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;
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";
83 close $fh or die "close $f: $!";
84 my $cfg = PublicInbox::Config->git_config_dump($f);
86 my $out = $cfg->get_all('lei.q.output') or return ();
93 sub translate_dedupe ($$$) {
94 my ($self, $lei, $dd) = @_;
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");
101 sub up { # updating existing saved search via "lei up"
102 my ($cls, $lei, $dst) = @_;
104 my $self = bless { ale => $lei->ale }, $cls;
106 output2lssdir($self, $lei, \$dir, \$f) or
107 return $lei->fail("--save was not used with $dst cwd=".
109 $self->{-cfg} = PublicInbox::Config->git_config_dump($f);
110 $self->{-ovf} = "$dir/over.sqlite3";
112 $self->{lock_path} = "$self->{-f}.flock";
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);
122 File::Path::make_path($dir); # raises on error
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';
131 $q = join("\n", map { "\tq = ".cquote_val($_) } @$q);
133 $q = "\tq = ".cquote_val($q);
135 $dst = "$lei->{ovv}->{fmt}:$dst" if $dst !~ m!\Aimaps?://!i;
137 ; to refresh with new results, run: lei up $sq_dst
143 print $fh "\tdedupe = $dd\n" if $dd;
144 for my $k (ARRAY_FIELDS) {
145 my $ary = $lei->{opt}->{$k} // next;
147 print $fh "\t$k = ".cquote_val($x)."\n";
150 for my $k (BOOL_FIELDS) {
151 my $val = $lei->{opt}->{$k} // next;
152 print $fh "\t$k = ".($val ? 1 : 0)."\n";
154 close($fh) or return $lei->fail("close $f: $!");
155 $self->{lock_path} = "$self->{-f}.flock";
156 $self->{-ovf} = "$dir/over.sqlite3";
160 sub description { $_[0]->{qstr} } # for WWW
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]);
168 # drop-in for LeiDedupe API
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)}) {
178 return 1 if $oidx->next_by_mid($mid, \$id, \$prv);
181 if (my $xoids = PublicInbox::LeiSearch::xoids_for($self, $eml, 1)) {
182 for my $docid (values %$xoids) {
183 $oidx->add_xref3($docid, -1, $blob, '.');
186 if ($self->{-dedupe_oid}) {
187 $smsg->{blob} //= git_sha(1, $eml)->hexdigest;
188 exists $xoids->{$smsg->{blob}} ? 1 : undef;
193 # n.b. above xoids_for fills out eml->{-lei_fake_mid} if needed
195 $smsg = bless {}, 'PublicInbox::Smsg';
197 $smsg->populate($eml);
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}, '.');
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;
218 $oidx->{dbh}->do('PRAGMA journal_mode = WAL');
219 $oidx->eidx_prep; # for xref3
225 sub over { $_[0]->{oidx} } # for xoids_for
227 sub git { $_[0]->{ale}->git }
231 $self->{ale}->git->cleanup;
232 my $lockfh = delete $self->{lockfh}; # from lock_for_scope_fast;
233 my $oidx = delete($self->{oidx}) // return;
243 # find existing directory containing a `lei.saved-search' file based on
244 # $dir_ref which is an output
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";
251 $self->{-cfg} = PublicInbox::Config->git_config_dump($f);
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;