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. Server-side timeouts are refreshed from the
124    /// remaining budget before each statement and commit, so an earlier lock
125    /// wait cannot give a later statement a fresh full-length timeout.
126    /// It is intentionally not applied to pool
127    /// acquisition or schema migrations.
128    ///
129    /// # Errors
130    ///
131    /// Returns an error if `timeout` is zero or exceeds 60 seconds.
132    pub fn with_operation_timeout(
133        mut self,
134        timeout: Duration,
135    ) -> Result<Self, PostgresConfigError> {
136        if timeout.is_zero() {
137            return Err(PostgresConfigError::ZeroOperationTimeout);
138        }
139        if timeout > Self::MAXIMUM_OPERATION_TIMEOUT {
140            return Err(PostgresConfigError::OperationTimeoutTooLong {
141                actual: timeout,
142                maximum: Self::MAXIMUM_OPERATION_TIMEOUT,
143            });
144        }
145        self.operation_timeout = timeout;
146        Ok(self)
147    }
148
149    /// Returns the maximum accepted batch length.
150    pub const fn max_batch_size(&self) -> usize {
151        self.max_batch_size
152    }
153
154    /// Returns the configured admission limit for one capacity shard.
155    pub const fn maximum_rows_per_shard(self) -> u32 {
156        self.maximum_rows_per_shard
157    }
158
159    /// Returns the budget for acquiring a connection from the pool.
160    pub const fn pool_acquire_timeout(self) -> Duration {
161        self.pool_acquire_timeout
162    }
163
164    /// Returns the deadline applied after a connection is acquired.
165    pub const fn operation_timeout(self) -> Duration {
166        self.operation_timeout
167    }
168}
169
170impl Default for PostgresConfig {
171    fn default() -> Self {
172        Self::new()
173    }
174}
175
176#[cfg(feature = "serde")]
177#[derive(serde::Serialize)]
178struct PostgresConfigRef {
179    maximum_rows_per_shard: u32,
180    max_batch_size: usize,
181    pool_acquire_timeout: Duration,
182    operation_timeout: Duration,
183}
184
185#[cfg(feature = "serde")]
186#[derive(serde::Deserialize)]
187#[serde(deny_unknown_fields)]
188struct PostgresConfigWire {
189    #[serde(default = "default_postgres_maximum_rows_per_shard")]
190    maximum_rows_per_shard: u32,
191    #[serde(default = "default_postgres_max_batch_size")]
192    max_batch_size: usize,
193    #[serde(default = "default_postgres_pool_acquire_timeout")]
194    pool_acquire_timeout: Duration,
195    #[serde(default = "default_postgres_operation_timeout")]
196    operation_timeout: Duration,
197}
198
199#[cfg(feature = "serde")]
200const fn default_postgres_maximum_rows_per_shard() -> u32 {
201    PostgresConfig::DEFAULT_MAXIMUM_ROWS_PER_SHARD
202}
203
204#[cfg(feature = "serde")]
205const fn default_postgres_max_batch_size() -> usize {
206    PostgresConfig::DEFAULT_MAX_BATCH_SIZE
207}
208
209#[cfg(feature = "serde")]
210const fn default_postgres_pool_acquire_timeout() -> Duration {
211    PostgresConfig::DEFAULT_POOL_ACQUIRE_TIMEOUT
212}
213
214#[cfg(feature = "serde")]
215const fn default_postgres_operation_timeout() -> Duration {
216    PostgresConfig::DEFAULT_OPERATION_TIMEOUT
217}
218
219#[cfg(feature = "serde")]
220impl serde::Serialize for PostgresConfig {
221    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
222    where
223        S: serde::Serializer,
224    {
225        serde::Serialize::serialize(
226            &PostgresConfigRef {
227                maximum_rows_per_shard: self.maximum_rows_per_shard(),
228                max_batch_size: self.max_batch_size(),
229                pool_acquire_timeout: self.pool_acquire_timeout(),
230                operation_timeout: self.operation_timeout(),
231            },
232            serializer,
233        )
234    }
235}
236
237#[cfg(feature = "serde")]
238impl<'de> serde::Deserialize<'de> for PostgresConfig {
239    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
240    where
241        D: serde::Deserializer<'de>,
242    {
243        let wire = <PostgresConfigWire as serde::Deserialize>::deserialize(deserializer)?;
244        Self::new()
245            .with_maximum_rows_per_shard(wire.maximum_rows_per_shard)
246            .and_then(|config| config.with_max_batch_size(wire.max_batch_size))
247            .and_then(|config| config.with_pool_acquire_timeout(wire.pool_acquire_timeout))
248            .and_then(|config| config.with_operation_timeout(wire.operation_timeout))
249            .map_err(serde::de::Error::custom)
250    }
251}
252
253/// Invalid `PostgreSQL` backend configuration.
254#[derive(Clone, Copy, Debug, Error, Eq, PartialEq)]
255#[non_exhaustive]
256pub enum PostgresConfigError {
257    /// A zero per-shard maximum would reject every new storage key.
258    #[error("maximum_rows_per_shard must be greater than zero")]
259    ZeroMaximumRowsPerShard,
260    /// The configured bound exceeds the ceiling enforced by the database
261    /// migration.
262    #[error("maximum_rows_per_shard ({actual}) exceeds database-enforced maximum ({maximum})")]
263    MaximumRowsPerShardTooLarge {
264        /// Supplied per-shard row bound.
265        actual: u32,
266        /// Largest database-enforced bound.
267        maximum: u32,
268    },
269    /// A zero maximum batch size would reject every nonempty batch.
270    #[error("max_batch_size must be greater than zero")]
271    ZeroBatchSize,
272    /// A zero acquisition budget cannot permit waiting for a pool connection.
273    #[error("PostgreSQL pool acquisition timeout must be greater than zero")]
274    ZeroPoolAcquireTimeout,
275    /// A pool-acquisition budget longer than one minute is not operationally
276    /// bounded enough for this backend.
277    #[error("PostgreSQL pool acquisition timeout {actual:?} exceeds maximum {maximum:?}")]
278    PoolAcquireTimeoutTooLong {
279        /// Supplied timeout.
280        actual: Duration,
281        /// Largest accepted timeout.
282        maximum: Duration,
283    },
284    /// A zero deadline cannot permit database work.
285    #[error("PostgreSQL rate-limit operation timeout must be greater than zero")]
286    ZeroOperationTimeout,
287    /// An admission deadline longer than one minute is not operationally
288    /// bounded enough for this backend.
289    #[error("PostgreSQL rate-limit operation timeout {actual:?} exceeds maximum {maximum:?}")]
290    OperationTimeoutTooLong {
291        /// Supplied timeout.
292        actual: Duration,
293        /// Largest accepted timeout.
294        maximum: Duration,
295    },
296}