ctb_workspace_ipc/router/
token_bucket.rs1#[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#[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#[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 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}