ctb_workspace_ipc/router/
token_bucket.rs

1// SPDX-License-Identifier: AGPL-3.0-or-later
2/*
3This file is part of Collective Toolbox, a database and document workspace and utilities.
4Copyright (C) 2026 Collective Toolbox Developers
5Contact: info@collectivetoolbox.com
6
7This program is free software: you can redistribute it and/or modify it under
8the terms of the GNU Affero General Public License as published by the Free
9Software Foundation, either version 3 of the License, or (at your option) any
10later version.
11
12This program is distributed in the hope that it will be useful, but WITHOUT ANY
13WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
15
16You should have received a copy of the GNU Affero General Public License along
17with this program.  If not, see <https://www.gnu.org/licenses/>.
18*/
19
20//! Rate limiting token bucket implementation for IPC message streams.
21
22#[allow(
23    unused_imports,
24    clippy::wildcard_imports,
25    reason = "Standard workspace module prelude"
26)]
27use crate::utilities::*;
28
29use crate::types::ConnectionId;
30use tokio::time::Instant;
31
32/// Key for rate limiting (connection, service, method).
33#[derive(Clone, Debug, Eq, PartialEq, Hash)]
34pub(super) struct RateKey {
35    conn_id: ConnectionId,
36    service: String,
37    method: String,
38}
39
40impl RateKey {
41    pub(super) fn bytes(
42        conn_id: ConnectionId,
43        service: String,
44        method: String,
45    ) -> Self {
46        Self {
47            conn_id,
48            service,
49            method,
50        }
51    }
52}
53
54/// Simple token bucket for rate limiting.
55#[derive(Debug)]
56pub(super) struct TokenBucket {
57    capacity: u128,
58    tokens: u128,
59    last_refill: Instant,
60    rate_bytes_per_sec: u64,
61}
62
63impl TokenBucket {
64    pub(super) fn new(rate: u64, capacity: u64, now: Instant) -> Self {
65        Self {
66            capacity: u128::from(capacity),
67            tokens: u128::from(capacity),
68            last_refill: now,
69            rate_bytes_per_sec: rate,
70        }
71    }
72
73    pub(super) fn try_take(&mut self, amount: u64, now: Instant) -> bool {
74        let elapsed = now.duration_since(self.last_refill);
75        let elapsed_ns = elapsed.as_nanos();
76        // Reason for fallback: token refill division calculation overflow adds 0 tokens to bucket capacity
77        let added_tokens = elapsed_ns
78            .saturating_mul(u128::from(self.rate_bytes_per_sec))
79            .checked_div(1_000_000_000)
80            .unwrap_or(0);
81        self.tokens =
82            self.tokens.saturating_add(added_tokens).min(self.capacity);
83        self.last_refill = now;
84
85        let amount_u128 = u128::from(amount);
86        if self.tokens >= amount_u128 {
87            self.tokens = self.tokens.saturating_sub(amount_u128);
88            true
89        } else {
90            false
91        }
92    }
93}