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
impl PostgresLimiter
Sourcepub const fn new(pool: PgPool) -> Self
pub const fn new(pool: PgPool) -> Self
Creates a limiter using pool.
Call Self::migrate during application startup before admitting
requests.
Sourcepub const fn with_config(pool: PgPool, config: PostgresConfig) -> Self
pub const fn with_config(pool: PgPool, config: PostgresConfig) -> Self
Creates a limiter using an explicit runtime configuration.
Sourcepub fn with_observer(self, observer: Arc<dyn Observer>) -> Self
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.
Sourcepub const fn config(&self) -> PostgresConfig
pub const fn config(&self) -> PostgresConfig
Returns the backend runtime configuration.
Sourcepub async fn migrate(&self) -> Result<(), MigrateError>
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.
Sourcepub async fn check(&self, check: &Check<'_>) -> Result<Decision, CheckError>
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.
Sourcepub async fn check_all(
&self,
checks: &[Check<'_>],
) -> Result<BatchDecision, CheckError>
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
Denial::StorageCapacity 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.
Sourcepub async fn cleanup_expired(
&self,
maximum_rows: u32,
) -> Result<u64, MaintenanceError>
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
impl Clone for PostgresLimiter
Source§fn clone(&self) -> PostgresLimiter
fn clone(&self) -> PostgresLimiter
1.0.0 (const: unstable) · Source§fn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
source. Read moreSource§impl Debug for PostgresLimiter
impl Debug for PostgresLimiter
Source§impl Limiter for PostgresLimiter
impl Limiter for PostgresLimiter
Source§type Policy = FixedWindowPolicy
type Policy = FixedWindowPolicy
Source§type Error = CheckError
type Error = CheckError
Auto Trait Implementations§
impl !RefUnwindSafe for PostgresLimiter
impl !UnwindSafe for PostgresLimiter
impl Freeze for PostgresLimiter
impl Send for PostgresLimiter
impl Sync for PostgresLimiter
impl Unpin for PostgresLimiter
impl UnsafeUnpin for PostgresLimiter
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
Source§impl<T> Instrument for T
impl<T> Instrument for T
Source§fn instrument(self, span: Span) -> Instrumented<Self>
fn instrument(self, span: Span) -> Instrumented<Self>
Source§fn in_current_span(self) -> Instrumented<Self>
fn in_current_span(self) -> Instrumented<Self>
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self>
fn into_either(self, into_left: bool) -> Either<Self, Self>
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 moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
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