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 my $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)
32 sub lss_dir_for ($$;$) {
33 my ($lei, $dstref, $on_fs) = @_;
35 if ($$dstref =~ m,\Aimaps?://,i) { # already canonicalized
36 require PublicInbox::URIimap;
37 my $uri = PublicInbox::URIimap->new($$dstref)->canonical;
41 # can't use Cwd::abs_path since dirname($$dstref) may not exist
42 $$dstref = $lei->rel2abs($$dstref);
44 @n = ($$dstref =~ m{([^/]+)/*\z}); # basename
46 push @n, sha256_hex($$dstref);
47 my $lss_dir = $lei->share_path . '/saved-searches/';
48 my $d = $lss_dir . join('-', @n);
50 # fall-back to looking up by st_ino + st_dev in case we're in
51 # a symlinked or bind-mounted path
52 if ($on_fs && !-d $d && -e $$dstref) {
54 my $want = pack('dd', @cur[1,0]); # st_ino + st_dev
56 for my $g ("$n[0]-*", '*') {
57 my @maybe = glob("$lss_dir$g/lei.saved-search");
59 $c = PublicInbox::Config->git_config_dump($f);
60 $o = $c->{'lei.q.output'} // next;
61 $o =~ s!$LOCAL_PFX!! or next;
62 @st = stat($o) or next;
63 next if pack('dd', @st[1,0]) ne $want;
64 $f =~ m!\A(.+?)/[^/]+\z! and return $1;
73 my $lss_dir = $lei->share_path.'/saved-searches';
74 return () unless -d $lss_dir;
75 # TODO: persist the cache? Use another format?
76 my $f = $lei->cache_dir."/saved-tmp.$$.".time.'.config';
77 open my $fh, '>', $f or die "open $f: $!";
78 print $fh "[include]\n";
79 for my $p (glob("$lss_dir/*/lei.saved-search")) {
80 print $fh "\tpath = ", cquote_val($p), "\n";
82 close $fh or die "close $f: $!";
83 my $cfg = PublicInbox::Config->git_config_dump($f);
85 my $out = $cfg->get_all('lei.q.output') or return ();
92 sub translate_dedupe ($$$) {
93 my ($self, $lei, $dd) = @_;
95 return 1 if $dd eq 'content'; # the default
96 return $self->{"-dedupe_$dd"} = 1 if ($dd eq 'oid' || $dd eq 'mid');
97 $lei->fail("--dedupe=$dd unsupported with --save");
100 sub up { # updating existing saved search via "lei up"
101 my ($cls, $lei, $dst) = @_;
103 my $self = bless { ale => $lei->ale }, $cls;
105 output2lssdir($self, $lei, \$dir, \$f) or
106 return $lei->fail("--save was not used with $dst cwd=".
108 $self->{-cfg} = PublicInbox::Config->git_config_dump($f);
109 $self->{-ovf} = "$dir/over.sqlite3";
111 $self->{lock_path} = "$self->{-f}.flock";
115 sub new { # new saved search "lei q --save"
116 my ($cls, $lei) = @_;
117 my $self = bless { ale => $lei->ale }, $cls;
119 my $dst = $lei->{ovv}->{dst};
121 # canonicalize away relative paths into the config
122 if ($lei->{ovv}->{fmt} eq 'maildir' &&
123 $dst =~ m!(?:/*|\A)\.\.(?:/*|\z)! && !-d $dst) {
124 File::Path::make_path($dst);
125 $lei->{ovv}->{dst} = $dst = $lei->abs_path($dst);
127 my $dir = lss_dir_for($lei, \$dst);
128 File::Path::make_path($dir); # raises on error
130 my $f = $self->{'-f'} = "$dir/lei.saved-search";
131 my $dd = $lei->{opt}->{dedupe};
132 translate_dedupe($self, $lei, $dd) or return;
133 open my $fh, '>', $f or return $lei->fail("open $f: $!");
134 my $sq_dst = PublicInbox::Config::squote_maybe($dst);
135 my $q = $lei->{mset_opt}->{q_raw} // die 'BUG: {q_raw} missing';
137 $q = join("\n", map { "\tq = ".cquote_val($_) } @$q);
139 $q = "\tq = ".cquote_val($q);
141 $dst = "$lei->{ovv}->{fmt}:$dst" if $dst !~ m!\Aimaps?://!i;
143 ; to refresh with new results, run: lei up $sq_dst
149 print $fh "\tdedupe = $dd\n" if $dd;
150 for my $k (ARRAY_FIELDS) {
151 my $ary = $lei->{opt}->{$k} // next;
153 print $fh "\t$k = ".cquote_val($x)."\n";
156 for my $k (BOOL_FIELDS) {
157 my $val = $lei->{opt}->{$k} // next;
158 print $fh "\t$k = ".($val ? 1 : 0)."\n";
160 close($fh) or return $lei->fail("close $f: $!");
161 $self->{lock_path} = "$self->{-f}.flock";
162 $self->{-ovf} = "$dir/over.sqlite3";
166 sub description { $_[0]->{qstr} } # for WWW
168 sub cfg_set { # called by LeiXSearch
169 my ($self, @args) = @_;
170 my $lk = $self->lock_for_scope; # git-config doesn't wait
171 run_die([qw(git config -f), $self->{'-f'}, @args]);
174 # drop-in for LeiDedupe API
176 my ($self, $eml, $smsg) = @_;
177 my $oidx = $self->{oidx} // die 'BUG: no {oidx}';
179 if ($self->{-dedupe_mid}) {
180 $lk //= $self->lock_for_scope_fast;
181 for my $mid (@{mids_for_index($eml)}) {
183 return 1 if $oidx->next_by_mid($mid, \$id, \$prv);
186 my $blob = $smsg ? $smsg->{blob} : git_sha(1, $eml)->hexdigest;
187 $lk //= $self->lock_for_scope_fast;
188 return 1 if $oidx->blob_exists($blob);
189 if (my $xoids = PublicInbox::LeiSearch::xoids_for($self, $eml, 1)) {
190 for my $docid (values %$xoids) {
191 $oidx->add_xref3($docid, -1, $blob, '.');
194 if ($self->{-dedupe_oid}) {
195 exists $xoids->{$blob} ? 1 : undef;
200 # n.b. above xoids_for fills out eml->{-lei_fake_mid} if needed
202 $smsg = bless {}, 'PublicInbox::Smsg';
204 $smsg->populate($eml);
206 $smsg->{blob} //= $blob;
208 $smsg->{num} = $oidx->adj_counter('eidx_docid', '+');
209 $oidx->add_overview($eml, $smsg);
210 $oidx->add_xref3($smsg->{num}, -1, $blob, '.');
218 $self->{oidx} //= do {
219 my $creat = !-f $self->{-ovf};
220 my $lk = $self->lock_for_scope; # git-config doesn't wait
221 my $oidx = PublicInbox::OverIdx->new($self->{-ovf});
222 $oidx->{-no_fsync} = 1;
225 $oidx->{dbh}->do('PRAGMA journal_mode = WAL');
226 $oidx->eidx_prep; # for xref3
232 sub over { $_[0]->{oidx} } # for xoids_for
234 # don't use ale->git directly since is_dup is called inside
235 # ale->git->cat_async callbacks
236 sub git { $_[0]->{git} //= PublicInbox::Git->new($_[0]->{ale}->git->{git_dir}) }
241 my $lockfh = delete $self->{lockfh}; # from lock_for_scope_fast;
242 my $oidx = delete($self->{oidx}) // return;
252 # find existing directory containing a `lei.saved-search' file based on
253 # $dir_ref which is an output
255 my ($self, $lei, $dir_ref, $fn_ref) = @_;
256 my $dst = $$dir_ref; # imap://$MAILBOX, /path/to/maildir, /path/to/mbox
257 my $dir = lss_dir_for($lei, \$dst, 1);
258 my $f = "$dir/lei.saved-search";
260 $self->{-cfg} = PublicInbox::Config->git_config_dump($f);
269 my ($self, $lei) = @_;
270 if (ref($self->{-cfg}->{'lei.q.output'})) {
271 delete $self->{-cfg}->{'lei.q.output'}; # invalid
273 $self->{-f} has multiple values of lei.q.output
274 please remove redundant ones
277 $lei->{-lss_for_edit} = $self;
281 my ($self, $lei) = @_;
282 my $cfg = PublicInbox::Config->git_config_dump($self->{'-f'});
283 my $new_out = $cfg->{'lei.q.output'} // '';
284 return $lei->fail(<<EOM) if ref $new_out;
285 $self->{-f} has multiple values of lei.q.output
288 return $lei->fail(<<EOM) if $new_out eq '';
289 $self->{-f} needs lei.q.output
292 my $old_out = $self->{-cfg}->{'lei.q.output'} // '';
293 return if $old_out eq $new_out;
294 my $old_path = $old_out;
295 my $new_path = $new_out;
296 s!$LOCAL_PFX!! for ($old_path, $new_path);
297 my $dir_old = lss_dir_for($lei, \$old_path, 1);
298 my $dir_new = lss_dir_for($lei, \$new_path);
299 return if $dir_new eq $dir_old; # no change, likely
301 ($old_out =~ m!\Av2:!i || $new_out =~ m!\Av2:!) and
302 return $lei->fail(<<EOM);
303 conversions from/to v2 inboxes not supported at this time
306 return $lei->fail(<<EOM) if -e $dir_new;
307 lei.q.output changed from `$old_out' to `$new_out'
308 However, $dir_new exists
310 # start the conversion asynchronously
311 my $old_sq = PublicInbox::Config::squote_maybe($old_out);
312 my $new_sq = PublicInbox::Config::squote_maybe($new_out);
313 $lei->puts("lei.q.output changed from $old_sq to $new_sq");
314 $lei->qerr("# lei convert $old_sq -o $new_sq");
315 my $v = !$lei->{opt}->{quiet};
316 $lei->{opt} = { output => $new_out, verbose => $v };
317 require PublicInbox::LeiConvert;
318 PublicInbox::LeiConvert::lei_convert($lei, $old_out);
320 $lei->fail(<<EOM) if -e $dir_old && !rename($dir_old, $dir_new);
321 E: rename($dir_old, $dir_new) error: $!
325 # cf. LeiDedupe->has_entries
327 my $oidx = $_[0]->{oidx} // die 'BUG: no {oidx}';
328 my @n = $oidx->{dbh}->selectrow_array('SELECT num FROM over LIMIT 1');
329 scalar(@n) ? 1 : undef;
333 *nntp_url = \&cloneurl;
334 *base_url = \&PublicInbox::Inbox::base_url;
335 *smsg_eml = \&PublicInbox::Inbox::smsg_eml;
336 *smsg_by_mid = \&PublicInbox::Inbox::smsg_by_mid;
337 *msg_by_mid = \&PublicInbox::Inbox::msg_by_mid;
338 *modified = \&PublicInbox::Inbox::modified;
339 *recent = \&PublicInbox::Inbox::recent;
340 *max_git_epoch = *nntp_usable = *msg_by_path = \&mm; # undef
341 *isrch = *search = \&mm; # TODO
342 *DESTROY = \&pause_dedupe;