Skip to main content

PostgresLimiter

Struct PostgresLimiter 

Source
pub struct PostgresLimiter { /* private fields */ }
Expand description

A replica-safe rate limiter backed by a PostgreSQL pool.

Cloning this value is cheap because PgPool is internally reference counted.

Implementations§

Source§

impl PostgresLimiter

Source

pub const fn new(pool: PgPool) -> Self

Creates a limiter using pool.

Call Self::migrate during application startup before admitting requests.

Source

pub const fn with_config(pool: PgPool, config: PostgresConfig) -> Self

Creates a limiter using an explicit runtime configuration.

Source

pub fn with_observer(self, observer: Arc<dyn Observer>) -> Self

Returns this limiter with an operational observer.

Observer callbacks run only after a database operation has released its connection. Callback panics are isolated and cannot change admission or cleanup results.

Source

pub const fn pool(&self) -> &PgPool

Returns the underlying connection pool.

Source

pub const fn config(&self) -> PostgresConfig

Returns the backend runtime configuration.

Source

pub async fn migrate(&self) -> Result<(), MigrateError>

Applies the bundled Runlimit database migrations.

Unrelated successful versions in _sqlx_migrations are ignored, which permits a shared migration history only when every other participating SQLx migrator also sets Migrator::set_ignore_missing to true. Known Runlimit versions still receive SQLx’s checksum validation. Applications that keep a strict host migrator should instead vendor the bundled SQL into their application-owned migration stream.

Migration locking is session scoped. An acquired connection is returned to the pool only after a successful run and unlock; an error or cancellation closes it instead.

§Errors

Returns an error if migration metadata cannot be read or PostgreSQL rejects a migration.

Source

pub async fn check(&self, check: &Check<'_>) -> Result<Decision, CheckError>

Checks and, when allowed, consumes one fixed-window quota.

A denied decision does not change the stored counter.

§Errors

Returns CheckError::DefinitelyNotConsumed for failures before a successful commit and CheckError::CommitOutcomeUnknown when commit confirmation is unavailable. An internal single-response invariant failure reports whether the batch was rolled back or committed.

Source

pub async fn check_all( &self, checks: &[Check<'_>], ) -> Result<BatchDecision, CheckError>

Atomically checks and consumes every quota in checks.

Rows are acquired in a deterministic storage-key order to avoid deadlocks between overlapping batches. Returned allowed decisions retain the caller’s input order. Repeated occurrences of the same storage key are rejected before a connection is acquired because their independent decision metadata would be ambiguous.

New keys lock their capacity-ledger rows in shard order. If the earliest caller-ordered failure is the configured shard bound, the batch returns runlimit_core::Denial::storage_capacity with no retry duration and changes neither quota nor storage. Existing and expired target rows need no new slot.

If any check is denied, the backend attempts an explicit rollback and the returned denial index is the earliest denied item in caller order. A rollback error or deadline does not replace the denial because no counter was changed; instead, the connection is discarded so socket closure rolls the transaction back. Passing an empty slice succeeds without acquiring a database connection.

§Errors

Pool-acquisition or operation timeout before commit is CheckError::TimedOutBeforeCommit. Other database failures before commit are CheckError::DefinitelyNotConsumed. Any commit error is conservatively classified as CheckError::CommitOutcomeUnknown.

Source

pub async fn cleanup_expired( &self, maximum_rows: u32, ) -> Result<u64, MaintenanceError>

Deletes at most maximum_rows expired windows and releases their capacity-ledger slots in the same transaction.

Cleanup uses FOR UPDATE SKIP LOCKED, so it does not wait behind active checks and cannot remove a row concurrently being renewed. A zero limit performs no database work.

§Errors

Returns an error if PostgreSQL rejects the maintenance transaction or if either PostgresConfig::pool_acquire_timeout or the fresh PostgresConfig::operation_timeout budget is exceeded. A commit error or commit timeout means rows may have been removed; inspect MaintenanceError::may_have_removed_rows. Cleanup only targets already-expired rows and never consumes quota.

Trait Implementations§

Source§

impl Clone for PostgresLimiter

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for PostgresLimiter

Source§

fn fmt(&self, formatter: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Limiter for PostgresLimiter

Source§

type Policy = FixedWindowPolicy

Policy algorithm supported by this backend.
Source§

type Error = CheckError

Backend-specific operational failure.
Source§

fn check( &self, check: &Check<'_>, ) -> impl Future<Output = Result<Decision, Self::Error>> + Send

Evaluates and, when allowed, consumes one check.
Source§

fn check_all( &self, checks: &[Check<'_>], ) -> impl Future<Output = Result<BatchDecision, Self::Error>> + Send

Evaluates a batch atomically. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more