user/dev discussion of public-inbox itself
 help / color / mirror / code / Atom feed
8ceaaf018ec628a6cba2132304304797ce733f4f blob 8603 bytes (raw)

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
 
# Copyright (C) 2021 all contributors <meta@public-inbox.org>
# License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>

# pretends to be like LeiDedupe and also PublicInbox::Inbox
package PublicInbox::LeiSavedSearch;
use strict;
use v5.10.1;
use parent qw(PublicInbox::Lock);
use PublicInbox::Git;
use PublicInbox::OverIdx;
use PublicInbox::LeiSearch;
use PublicInbox::Config;
use PublicInbox::Spawn qw(run_die);
use PublicInbox::ContentHash qw(git_sha);
use PublicInbox::MID qw(mids_for_index);
use Digest::SHA qw(sha256_hex);
our $LOCAL_PFX = qr!\A(?:maildir|mh|mbox.+|mmdf|v2):!i; # TODO: put in LeiToMail?

# move this to PublicInbox::Config if other things use it:
my %cquote = ("\n" => '\\n', "\t" => '\\t', "\b" => '\\b');
sub cquote_val ($) { # cf. git-config(1)
	my ($val) = @_;
	$val =~ s/([\n\t\b])/$cquote{$1}/g;
	$val;
}

sub ARRAY_FIELDS () { qw(only include exclude) }
sub BOOL_FIELDS () {
	qw(external local remote import-remote import-before threads)
}

sub cfg_dump ($$) {
	my ($lei, $f) = @_;
	my $ret = eval { PublicInbox::Config->git_config_dump($f, $lei->{2}) };
	return $ret if !$@;
	$lei->err($@);
	undef;
}

sub lss_dir_for ($$;$) {
	my ($lei, $dstref, $on_fs) = @_;
	my @n;
	if ($$dstref =~ m,\Aimaps?://,i) { # already canonicalized
		require PublicInbox::URIimap;
		my $uri = PublicInbox::URIimap->new($$dstref)->canonical;
		$$dstref = $$uri;
		@n = ($uri->mailbox);
	} else {
		# can't use Cwd::abs_path since dirname($$dstref) may not exist
		$$dstref = $lei->rel2abs($$dstref);
		$$dstref =~ tr!/!/!s;
		@n = ($$dstref =~ m{([^/]+)/*\z}); # basename
	}
	push @n, sha256_hex($$dstref);
	my $lss_dir = $lei->share_path . '/saved-searches/';
	my $d = $lss_dir . join('-', @n);

	# fall-back to looking up by st_ino + st_dev in case we're in
	# a symlinked or bind-mounted path
	if ($on_fs && !-d $d && -e $$dstref) {
		my @cur = stat(_);
		my $want = pack('dd', @cur[1,0]); # st_ino + st_dev
		my ($c, $o, @st);
		for my $g ("$n[0]-*", '*') {
			my @maybe = glob("$lss_dir$g/lei.saved-search");
			for my $f (@maybe) {
				$c = cfg_dump($lei, $f) // next;
				$o = $c->{'lei.q.output'} // next;
				$o =~ s!$LOCAL_PFX!! or next;
				@st = stat($o) or next;
				next if pack('dd', @st[1,0]) ne $want;
				$f =~ m!\A(.+?)/[^/]+\z! and return $1;
			}
		}
	}
	$d;
}

sub list {
	my ($lei, $pfx) = @_;
	my $lss_dir = $lei->share_path.'/saved-searches';
	return () unless -d $lss_dir;
	# TODO: persist the cache?  Use another format?
	my $f = $lei->cache_dir."/saved-tmp.$$.".time.'.config';
	open my $fh, '>', $f or die "open $f: $!";
	print $fh "[include]\n";
	for my $p (glob("$lss_dir/*/lei.saved-search")) {
		print $fh "\tpath = ", cquote_val($p), "\n";
	}
	close $fh or die "close $f: $!";
	my $cfg = cfg_dump($lei, $f);
	unlink($f);
	my $out = $cfg ? $cfg->get_all('lei.q.output') : [];
	map {;
		s!$LOCAL_PFX!!;
		$_;
	} @$out
}

sub translate_dedupe ($$$) {
	my ($self, $lei, $dd) = @_;
	$dd //= 'content';
	return 1 if $dd eq 'content'; # the default
	return $self->{"-dedupe_$dd"} = 1 if ($dd eq 'oid' || $dd eq 'mid');
	$lei->fail("--dedupe=$dd unsupported with --save");
}

sub up { # updating existing saved search via "lei up"
	my ($cls, $lei, $dst) = @_;
	my $f;
	my $self = bless { ale => $lei->ale }, $cls;
	my $dir = $dst;
	output2lssdir($self, $lei, \$dir, \$f) or
		return $lei->fail("--save was not used with $dst cwd=".
					$lei->rel2abs('.'));
	$self->{-cfg} = cfg_dump($lei, $f) // return $lei->fail;
	$self->{-ovf} = "$dir/over.sqlite3";
	$self->{'-f'} = $f;
	$self->{lock_path} = "$self->{-f}.flock";
	$self;
}

sub new { # new saved search "lei q --save"
	my ($cls, $lei) = @_;
	my $self = bless { ale => $lei->ale }, $cls;
	require File::Path;
	my $dst = $lei->{ovv}->{dst};

	# canonicalize away relative paths into the config
	if ($lei->{ovv}->{fmt} eq 'maildir' &&
			$dst =~ m!(?:/*|\A)\.\.(?:/*|\z)! && !-d $dst) {
		File::Path::make_path($dst);
		$lei->{ovv}->{dst} = $dst = $lei->abs_path($dst);
	}
	my $dir = lss_dir_for($lei, \$dst);
	File::Path::make_path($dir); # raises on error
	$self->{-cfg} = {};
	my $f = $self->{'-f'} = "$dir/lei.saved-search";
	my $dd = $lei->{opt}->{dedupe};
	translate_dedupe($self, $lei, $dd) or return;
	open my $fh, '>', $f or return $lei->fail("open $f: $!");
	my $sq_dst = PublicInbox::Config::squote_maybe($dst);
	my $q = $lei->{mset_opt}->{q_raw} // die 'BUG: {q_raw} missing';
	if (ref $q) {
		$q = join("\n", map { "\tq = ".cquote_val($_) } @$q);
	} else {
		$q = "\tq = ".cquote_val($q);
	}
	$dst = "$lei->{ovv}->{fmt}:$dst" if $dst !~ m!\Aimaps?://!i;
	print $fh <<EOM;
; to refresh with new results, run: lei up $sq_dst
[lei]
$q
[lei "q"]
	output = $dst
EOM
	print $fh "\tdedupe = $dd\n" if $dd;
	for my $k (ARRAY_FIELDS) {
		my $ary = $lei->{opt}->{$k} // next;
		for my $x (@$ary) {
			print $fh "\t$k = ".cquote_val($x)."\n";
		}
	}
	for my $k (BOOL_FIELDS) {
		my $val = $lei->{opt}->{$k} // next;
		print $fh "\t$k = ".($val ? 1 : 0)."\n";
	}
	close($fh) or return $lei->fail("close $f: $!");
	$self->{lock_path} = "$self->{-f}.flock";
	$self->{-ovf} = "$dir/over.sqlite3";
	$self;
}

sub description { $_[0]->{qstr} } # for WWW

sub cfg_set { # called by LeiXSearch
	my ($self, @args) = @_;
	my $lk = $self->lock_for_scope; # git-config doesn't wait
	run_die([qw(git config -f), $self->{'-f'}, @args]);
}

# drop-in for LeiDedupe API
sub is_dup {
	my ($self, $eml, $smsg) = @_;
	my $oidx = $self->{oidx} // die 'BUG: no {oidx}';
	my $lk;
	if ($self->{-dedupe_mid}) {
		$lk //= $self->lock_for_scope_fast;
		for my $mid (@{mids_for_index($eml)}) {
			my ($id, $prv);
			return 1 if $oidx->next_by_mid($mid, \$id, \$prv);
		}
	}
	my $blob = $smsg ? $smsg->{blob} : git_sha(1, $eml)->hexdigest;
	$lk //= $self->lock_for_scope_fast;
	return 1 if $oidx->blob_exists($blob);
	if (my $xoids = PublicInbox::LeiSearch::xoids_for($self, $eml, 1)) {
		for my $docid (values %$xoids) {
			$oidx->add_xref3($docid, -1, $blob, '.');
		}
		$oidx->commit_lazy;
		if ($self->{-dedupe_oid}) {
			exists $xoids->{$blob} ? 1 : undef;
		} else {
			1;
		}
	} else {
		# n.b. above xoids_for fills out eml->{-lei_fake_mid} if needed
		unless ($smsg) {
			$smsg = bless {}, 'PublicInbox::Smsg';
			$smsg->{bytes} = 0;
			$smsg->populate($eml);
		}
		$smsg->{blob} //= $blob;
		$oidx->begin_lazy;
		$smsg->{num} = $oidx->adj_counter('eidx_docid', '+');
		$oidx->add_overview($eml, $smsg);
		$oidx->add_xref3($smsg->{num}, -1, $blob, '.');
		$oidx->commit_lazy;
		undef;
	}
}

sub prepare_dedupe {
	my ($self) = @_;
	$self->{oidx} //= do {
		my $creat = !-f $self->{-ovf};
		my $lk = $self->lock_for_scope; # git-config doesn't wait
		my $oidx = PublicInbox::OverIdx->new($self->{-ovf});
		$oidx->{-no_fsync} = 1;
		$oidx->dbh;
		if ($creat) {
			$oidx->{dbh}->do('PRAGMA journal_mode = WAL');
			$oidx->eidx_prep; # for xref3
		}
		$oidx
	};
}

sub over { $_[0]->{oidx} } # for xoids_for

# don't use ale->git directly since is_dup is called inside
# ale->git->cat_async callbacks
sub git { $_[0]->{git} //= PublicInbox::Git->new($_[0]->{ale}->git->{git_dir}) }

sub pause_dedupe {
	my ($self) = @_;
	git($self)->cleanup;
	my $lockfh = delete $self->{lockfh}; # from lock_for_scope_fast;
	my $oidx = delete($self->{oidx}) // return;
	$oidx->commit_lazy;
}

sub reset_dedupe {
	my ($self) = @_;
	prepare_dedupe($self);
	my $lk = $self->lock_for_scope_fast;
	for my $t (qw(xref3 over id2num)) {
		$self->{oidx}->{dbh}->do("DELETE FROM $t");
	}
	pause_dedupe($self);
}

sub mm { undef }

sub altid_map { {} }

sub cloneurl { [] }

# find existing directory containing a `lei.saved-search' file based on
# $dir_ref which is an output
sub output2lssdir {
	my ($self, $lei, $dir_ref, $fn_ref) = @_;
	my $dst = $$dir_ref; # imap://$MAILBOX, /path/to/maildir, /path/to/mbox
	my $dir = lss_dir_for($lei, \$dst, 1);
	my $f = "$dir/lei.saved-search";
	if (-f $f && -r _) {
		$self->{-cfg} = cfg_dump($lei, $f) // return;
		$$dir_ref = $dir;
		$$fn_ref = $f;
		return 1;
	}
	undef;
}

# cf. LeiDedupe->has_entries
sub has_entries {
	my $oidx = $_[0]->{oidx} // die 'BUG: no {oidx}';
	my @n = $oidx->{dbh}->selectrow_array('SELECT num FROM over LIMIT 1');
	scalar(@n) ? 1 : undef;
}

no warnings 'once';
*nntp_url = \&cloneurl;
*base_url = \&PublicInbox::Inbox::base_url;
*smsg_eml = \&PublicInbox::Inbox::smsg_eml;
*smsg_by_mid = \&PublicInbox::Inbox::smsg_by_mid;
*msg_by_mid = \&PublicInbox::Inbox::msg_by_mid;
*modified = \&PublicInbox::Inbox::modified;
*recent = \&PublicInbox::Inbox::recent;
*max_git_epoch = *nntp_usable = *msg_by_path = \&mm; # undef
*isrch = *search = \&mm; # TODO
*DESTROY = \&pause_dedupe;

1;
debug log:

solving 8ceaaf01 ...
found 8ceaaf01 in https://80x24.org/public-inbox.git

Code repositories for project(s) associated with this inbox:

	https://80x24.org/public-inbox.git

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for read-only IMAP folder(s) and NNTP newsgroup(s).