Skip to main content

runlimit_postgres/
config.rs

1use std::time::Duration;
2
3use thiserror::Error;
4
5use crate::HARD_MAX_ROWS_PER_SHARD;
6
7/// Runtime bounds for `PostgreSQL` admission work.
8///
9/// With the `serde` feature, this is an object containing
10/// `maximum_rows_per_shard`, `max_batch_size`, `pool_acquire_timeout`, and
11/// `operation_timeout`. Durations use Serde's exact
12/// `{ "secs": ..., "nanos": ... }` representation. Every field may be omitted
13/// when deserializing to use the constructor defaults.
14#[derive(Clone, Copy, Debug, Eq, PartialEq)]
15pub struct PostgresConfig {
16    maximum_rows_per_shard: u32,
17    max_batch_size: usize,
18    pool_acquire_timeout: Duration,
19    operation_timeout: Duration,
20}
21
22impl PostgresConfig {
23    /// Default configured row limit for each of the 256 capacity shards.
24    pub const DEFAULT_MAXIMUM_ROWS_PER_SHARD: u32 = 4_096;
25
26    /// Default maximum number of checks in one atomic batch.
27    pub const DEFAULT_MAX_BATCH_SIZE: usize = 32;
28
29    /// Default budget for acquiring a connection from the pool.
30    pub const DEFAULT_POOL_ACQUIRE_TIMEOUT: Duration = Duration::from_secs(3);
31
32    /// Default deadline for database work after acquiring a connection.
33    pub const DEFAULT_OPERATION_TIMEOUT: Duration = Duration::from_secs(3);
34
35    /// Largest accepted pool-acquisition budget.
36    pub const MAXIMUM_POOL_ACQUIRE_TIMEOUT: Duration = Duration::from_secs(60);
37
38    /// Largest accepted database-operation deadline.
39    pub const MAXIMUM_OPERATION_TIMEOUT: Duration = Duration::from_secs(60);
40
41    /// Returns the conservative defaults suitable for an online admission
42    /// path.
43    pub const fn new() -> Self {
44        Self {
45            maximum_rows_per_shard: Self::DEFAULT_MAXIMUM_ROWS_PER_SHARD,
46            max_batch_size: Self::DEFAULT_MAX_BATCH_SIZE,
47            pool_acquire_timeout: Self::DEFAULT_POOL_ACQUIRE_TIMEOUT,
48            operation_timeout: Self::DEFAULT_OPERATION_TIMEOUT,
49        }
50    }
51
52    /// Sets the configured admission limit for one capacity shard.
53    ///
54    /// The database migration independently enforces
55    /// [`HARD_MAX_ROWS_PER_SHARD`] for compatibility with older replicas.
56    /// Configuring a lower value makes this limiter deny new keys sooner.
57    /// Existing keys remain usable, including when the ledger is already above
58    /// the newly configured value.
59    ///
60    /// # Errors
61    ///
62    /// Returns an error if `maximum` is zero or exceeds the database-enforced
63    /// hard maximum.
64    pub fn with_maximum_rows_per_shard(
65        mut self,
66        maximum: u32,
67    ) -> Result<Self, PostgresConfigError> {
68        if maximum == 0 {
69            return Err(PostgresConfigError::ZeroMaximumRowsPerShard);
70        }
71        if maximum > HARD_MAX_ROWS_PER_SHARD {
72            return Err(PostgresConfigError::MaximumRowsPerShardTooLarge {
73                actual: maximum,
74                maximum: HARD_MAX_ROWS_PER_SHARD,
75            });
76        }
77        self.maximum_rows_per_shard = maximum;
78        Ok(self)
79    }
80
81    /// Sets the maximum number of checks that may retain locks in one batch.
82    ///
83    /// # Errors
84    ///
85    /// Returns an error if `maximum` is zero.
86    pub fn with_max_batch_size(mut self, maximum: usize) -> Result<Self, PostgresConfigError> {
87        if maximum == 0 {
88            return Err(PostgresConfigError::ZeroBatchSize);
89        }
90        self.max_batch_size = maximum;
91        Ok(self)
92    }
93
94    /// Sets the budget for acquiring a connection from the pool.
95    ///
96    /// A successful acquisition receives a fresh
97    /// [`Self::operation_timeout`] budget. This timeout is intentionally not
98    /// applied to schema migrations.
99    ///
100    /// # Errors
101    ///
102    /// Returns an error if `timeout` is zero or exceeds 60 seconds.
103    pub fn with_pool_acquire_timeout(
104        mut self,
105        timeout: Duration,
106    ) -> Result<Self, PostgresConfigError> {
107        if timeout.is_zero() {
108            return Err(PostgresConfigError::ZeroPoolAcquireTimeout);
109        }
110        if timeout > Self::MAXIMUM_POOL_ACQUIRE_TIMEOUT {
111            return Err(PostgresConfigError::PoolAcquireTimeoutTooLong {
112                actual: timeout,
113                maximum: Self::MAXIMUM_POOL_ACQUIRE_TIMEOUT,
114            });
115        }
116        self.pool_acquire_timeout = timeout;
117        Ok(self)
118    }
119
120    /// Sets the deadline for database work after acquiring a connection.
121    ///
122    /// The fresh deadline covers transaction begin, lock waits, statements,
123    /// rollback, and commit. It is intentionally not applied to pool
124    /// acquisition or schema migrations.
125    ///
126    /// # Errors
127    ///
128    /// Returns an error if `timeout` is zero or exceeds 60 seconds.
129    pub fn with_operation_timeout(
130        mut self,
131        timeout: Duration,
132    ) -> Result<Self, PostgresConfigError> {
133        if timeout.is_zero() {
134            return Err(PostgresConfigError::ZeroOperationTimeout);
135        }
136        if timeout > Self::MAXIMUM_OPERATION_TIMEOUT {
137            return Err(PostgresConfigError::OperationTimeoutTooLong {
138                actual: timeout,
139                maximum: Self::MAXIMUM_OPERATION_TIMEOUT,
140            });
141        }
142        self.operation_timeout = timeout;
143        Ok(self)
144    }
145
146    /// Returns the maximum accepted batch length.
147    pub const fn max_batch_size(&self) -> usize {
148        self.max_batch_size
149    }
150
151    /// Returns the configured admission limit for one capacity shard.
152    pub const fn maximum_rows_per_shard(self) -> u32 {
153        self.maximum_rows_per_shard
154    }
155
156    /// Returns the budget for acquiring a connection from the pool.
157    pub const fn pool_acquire_timeout(self) -> Duration {
158        self.pool_acquire_timeout
159    }
160
161    /// Returns the deadline applied after a connection is acquired.
162    pub const fn operation_timeout(self) -> Duration {
163        self.operation_timeout
164    }
165}
166
167impl Default for PostgresConfig {
168    fn default() -> Self {
169        Self::new()
170    }
171}
172
173#[cfg(feature = "serde")]
174#[derive(serde::Serialize)]
175struct PostgresConfigRef {
176    maximum_rows_per_shard: u32,
177    max_batch_size: usize,
178    pool_acquire_timeout: Duration,
179    operation_timeout: Duration,
180}
181
182#[cfg(feature = "serde")]
183#[derive(serde::Deserialize)]
184#[serde(deny_unknown_fields)]
185struct PostgresConfigWire {
186    #[serde(default = "default_postgres_maximum_rows_per_shard")]
187    maximum_rows_per_shard: u32,
188    #[serde(default = "default_postgres_max_batch_size")]
189    max_batch_size: usize,
190    #[serde(default = "default_postgres_pool_acquire_timeout")]
191    pool_acquire_timeout: Duration,
192    #[serde(default = "default_postgres_operation_timeout")]
193    operation_timeout: Duration,
194}
195
196#[cfg(feature = "serde")]
197const fn default_postgres_maximum_rows_per_shard() -> u32 {
198    PostgresConfig::DEFAULT_MAXIMUM_ROWS_PER_SHARD
199}
200
201#[cfg(feature = "serde")]
202const fn default_postgres_max_batch_size() -> usize {
203    PostgresConfig::DEFAULT_MAX_BATCH_SIZE
204}
205
206#[cfg(feature = "serde")]
207const fn default_postgres_pool_acquire_timeout() -> Duration {
208    PostgresConfig::DEFAULT_POOL_ACQUIRE_TIMEOUT
209}
210
211#[cfg(feature = "serde")]
212const fn default_postgres_operation_timeout() -> Duration {
213    PostgresConfig::DEFAULT_OPERATION_TIMEOUT
214}
215
216#[cfg(feature = "serde")]
217impl serde::Serialize for PostgresConfig {
218    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
219    where
220        S: serde::Serializer,
221    {
222        serde::Serialize::serialize(
223            &PostgresConfigRef {
224                maximum_rows_per_shard: self.maximum_rows_per_shard(),
225                max_batch_size: self.max_batch_size(),
226                pool_acquire_timeout: self.pool_acquire_timeout(),
227                operation_timeout: self.operation_timeout(),
228            },
229            serializer,
230        )
231    }
232}
233
234#[cfg(feature = "serde")]
235impl<'de> serde::Deserialize<'de> for PostgresConfig {
236    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
237    where
238        D: serde::Deserializer<'de>,
239    {
240        let wire = <PostgresConfigWire as serde::Deserialize>::deserialize(deserializer)?;
241        Self::new()
242            .with_maximum_rows_per_shard(wire.maximum_rows_per_shard)
243            .and_then(|config| config.with_max_batch_size(wire.max_batch_size))
244            .and_then(|config| config.with_pool_acquire_timeout(wire.pool_acquire_timeout))
245            .and_then(|config| config.with_operation_timeout(wire.operation_timeout))
246            .map_err(serde::de::Error::custom)
247    }
248}
249
250/// Invalid `PostgreSQL` backend configuration.
251#[derive(Clone, Copy, Debug, Error, Eq, PartialEq)]
252#[non_exhaustive]
253pub enum PostgresConfigError {
254    /// A zero per-shard maximum would reject every new storage key.
255    #[error("maximum_rows_per_shard must be greater than zero")]
256    ZeroMaximumRowsPerShard,
257    /// The configured bound exceeds the ceiling enforced by the database
258    /// migration.
259    #[error("maximum_rows_per_shard ({actual}) exceeds database-enforced maximum ({maximum})")]
260    MaximumRowsPerShardTooLarge {
261        /// Supplied per-shard row bound.
262        actual: u32,
263        /// Largest database-enforced bound.
264        maximum: u32,
265    },
266    /// A zero maximum batch size would reject every nonempty batch.
267    #[error("max_batch_size must be greater than zero")]
268    ZeroBatchSize,
269    /// A zero acquisition budget cannot permit waiting for a pool connection.
270    #[error("PostgreSQL pool acquisition timeout must be greater than zero")]
271    ZeroPoolAcquireTimeout,
272    /// A pool-acquisition budget longer than one minute is not operationally
273    /// bounded enough for this backend.
274    #[error("PostgreSQL pool acquisition timeout {actual:?} exceeds maximum {maximum:?}")]
275    PoolAcquireTimeoutTooLong {
276        /// Supplied timeout.
277        actual: Duration,
278        /// Largest accepted timeout.
279        maximum: Duration,
280    },
281    /// A zero deadline cannot permit database work.
282    #[error("PostgreSQL rate-limit operation timeout must be greater than zero")]
283    ZeroOperationTimeout,
284    /// An admission deadline longer than one minute is not operationally
285    /// bounded enough for this backend.
286    #[error("PostgreSQL rate-limit operation timeout {actual:?} exceeds maximum {maximum:?}")]
287    OperationTimeoutTooLong {
288        /// Supplied timeout.
289        actual: Duration,
290        /// Largest accepted timeout.
291        maximum: Duration,
292    },
293}