NAME

Role::Object::RateLimiter - Add a rate limiter to your class

SYNOPSIS

package My::Responder;
use Moo;
with 'Role::Object::RateLimiter';

# Set up our rate limiter (any time before attempting to use it):
has limit_events => (
  is        => 'ro',
  required  => 1,
);

has limit_seconds => (
  is        => 'ro',
  required  => 1,
);

sub BUILD {
  my ($self) = @_;
  $self->delayed(
    events  => $self->limit_events,
    seconds => $self->limit_seconds
  );
}

# do_stuff but only if we're not rate-limited:
sub respond {
  my ($self) = @_;
  if (my $delay = $self->delayed) {
    sleep $delay
  }
  $self->do_stuff
}

sub respond_nonblocking {
  my ($self) = @_;
  return if $self->delayed;
  $self->do_stuff
}

DESCRIPTION

This is a small role wrapping Object::RateLimiter to make it slightly more convenient to add rate limiting to objects.

Currently only HASH-type objects are supported.

Although the "SYNOPSIS" uses Moo, this role uses Role::Tiny and can also be composed via Role::Tiny::With.

See Object::RateLimiter for more details.

delayed

# Set up the rate limiter:
$self->delayed(events => 4, seconds => 5);

# Check if this event should be delayed;
# returns number of seconds to wait:
my $delay = $self->delayed;

If called with arguments, passes them to Object::RateLimiter's constructor and returns the newly initialized rate limiter; any existing rate limiter is replaced.

If called without arguments, records an entry in the Object::RateLimiter's event history and returns the number of seconds until the event should be allowed (or zero if not delayed).

See "delay" in Object::RateLimiter.

clear_delayed

Clear the current event history.

get_rate_limiter

Returns the current Object::RateLimiter instance.

AUTHOR

Jon Portnoy <avenj@cobaltirc.org>