package EPrints::KlarasConnect::RateLimit;

# Fixed-window counters in one small table, shared by every Apache child.
# One INSERT .. ON DUPLICATE KEY UPDATE per check, no read-modify-write
# race. Bucket names are hashed so an IP or pseudonym is never stored.

use strict;
use warnings;

use Digest::SHA ();
use EPrints::KlarasConnect::Schema;

# Limits per window. Generous for a person, tight for a script.
our %LIMITS = (
	member_ip    => [ 600, 60 ],      # failed member tokens, per IP per minute
	member_sub   => [ 300, 60 ],      # per member pseudonym per minute
	search_sub   => [ 60, 60 ],       # searches per pseudonym per minute
	search_terms_sub => [ 200, 86400 ],   # search terms kept per pseudonym per day
	download_sub => [ 120, 3600 ],    # file downloads per pseudonym per hour
	events_sub   => [ 120, 3600 ],    # event batches per pseudonym per hour
	anon_ip      => [ 120, 60 ],      # unauthenticated requests per IP per minute
	tick_ip      => [ 20, 3600 ],     # rejected panel ticks per IP per hour
	verify_ip    => [ 600, 3600 ],    # verification answers per IP per hour
);

# Returns 1 when allowed, 0 when over the limit. When the table cannot be
# written the request is allowed (availability over strictness) and the
# problem is logged once per child.
my $LOGGED;
sub hit
{
	my( $repo, $kind, $key, $now ) = @_;

	my $limit = $LIMITS{$kind} or die "klaras_connect: unknown limit '$kind'\n";
	my( $max, $window ) = @$limit;
	$now = time if !defined $now;
	my $start = $now - ( $now % $window );

	my $bucket = Digest::SHA::sha1_hex( $repo->get_id . "|$kind|" . ( defined $key ? $key : '' ) );

	return 1 if !EPrints::KlarasConnect::Schema::ensure( $repo );
	my $dbh = EPrints::KlarasConnect::Schema::dbh( $repo );

	my $hits = eval {
		local $dbh->{RaiseError} = 1; local $dbh->{PrintError} = 0;
		$dbh->do(
			'INSERT INTO klaras_connect_ratelimit (bucket, window_start, hits) VALUES (?, ?, 1) '
			. 'ON DUPLICATE KEY UPDATE hits = IF(window_start = VALUES(window_start), hits + 1, 1), '
			. 'window_start = VALUES(window_start)',
			undef, $bucket, $start,
		);
		my( $h ) = $dbh->selectrow_array(
			'SELECT hits FROM klaras_connect_ratelimit WHERE bucket = ?', undef, $bucket );
		$h;
	};
	if( !defined $hits )
	{
		$repo->log( "klaras_connect: rate limiter unavailable: $@" ) if !$LOGGED++;
		return 1;
	}

	return $hits <= $max ? 1 : 0;
}

# Returns 1 the first time $key is seen, 0 every later time (a replay).
# Keys are kept a day (see prune), so callers must reject anything older
# than that on their own. Allows when the table cannot be written,
# like hit().
sub once
{
	my( $repo, $kind, $key, $at ) = @_;
	return 1 if !EPrints::KlarasConnect::Schema::ensure( $repo );
	my $dbh = EPrints::KlarasConnect::Schema::dbh( $repo );
	my $bucket = Digest::SHA::sha1_hex( $repo->get_id . "|once|$kind|$key" );
	my $rows = eval {
		local $dbh->{RaiseError} = 1; local $dbh->{PrintError} = 0;
		$dbh->do( 'INSERT IGNORE INTO klaras_connect_ratelimit (bucket, window_start, hits) VALUES (?, ?, 1)',
			undef, $bucket, defined $at ? $at : time );
	};
	if( !defined $rows )
	{
		$repo->log( "klaras_connect: replay check unavailable: $@" ) if !$LOGGED++;
		return 1;
	}
	return $rows > 0 ? 1 : 0;
}

# Seconds until the current window for $kind ends (for Retry-After).
sub retry_after
{
	my( $kind, $now ) = @_;
	my $window = $LIMITS{$kind}->[1];
	$now = time if !defined $now;
	return $window - ( $now % $window );
}

sub prune
{
	my( $repo, $now ) = @_;
	$now = time if !defined $now;
	return if !EPrints::KlarasConnect::Schema::ensure( $repo );
	my $dbh = EPrints::KlarasConnect::Schema::dbh( $repo );
	eval {
		local $dbh->{RaiseError} = 1; local $dbh->{PrintError} = 0;
		# Keep every window still running: the longest is a day.
		my( $longest ) = sort { $b <=> $a } map { $_->[1] } values %LIMITS;
		$dbh->do( 'DELETE FROM klaras_connect_ratelimit WHERE window_start < ?', undef, $now - $longest - 3600 );
	};
}

1;
