hyperinfer-core 0.2.1

Core types and traits for HyperInfer LLM Gateway
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
//! Rate limiting utilities for HyperInfer
//!
//! Provides distributed quota enforcement using Redis and GCRA algorithm.

use redis::aio::ConnectionManager;
use redis::Client;

pub const USAGE_TOKENS_KEY_PREFIX: &str = "hyperinfer:usage:tokens:";
pub const USAGE_REQUESTS_KEY_PREFIX: &str = "hyperinfer:usage:requests:";

const GCRA_SCRIPT: &str = r#"
local key = KEYS[1]
local limit_per_min = tonumber(ARGV[1])
local window_ms = tonumber(ARGV[2])
local now_ms = tonumber(ARGV[3])
local cost = tonumber(ARGV[4])

if not limit_per_min then
    return {1, 0}
end
if limit_per_min <= 0 then
    return {0, 0}
end

local emission_interval_ms = window_ms / limit_per_min
local tat = redis.call('GET', key)

if not tat then
    tat = now_ms
else
    tat = tonumber(tat)
end

local new_tat = math.max(tat, now_ms) + cost * emission_interval_ms
local allow_at = new_tat - window_ms

if allow_at <= now_ms then
    local ttl_secs = math.max(1, math.ceil((new_tat - now_ms) / 1000))
    redis.call('SET', key, tostring(new_tat), 'EX', ttl_secs)
    return {1, 0}
else
    return {0, math.ceil(allow_at - now_ms)}
end
"#;

const USAGE_KEY_TTL_SECS: u64 = 86_400; // 24 hours
const TPM_WINDOW_MS: u64 = 60_000; // 1 minute in milliseconds

const RPM_SCRIPT: &str = r#"
local key = KEYS[1]
local limit = tonumber(ARGV[1])
local window = tonumber(ARGV[2])

local current = redis.call('INCR', key)
if current == 1 then
    redis.call('EXPIRE', key, window)
end

if current > limit then
    local ttl = redis.call('TTL', key)
    return {0, 0, ttl}
end
return {1, limit - current, 0}
"#;

// Quota is now defined in crate::types and imported above.

#[derive(Clone)]
pub struct RateLimiter {
    redis_manager: Option<ConnectionManager>,
    default_rpm: u64,
    default_tpm: u64,
}

impl RateLimiter {
    pub async fn new(
        redis_url: Option<&str>,
    ) -> Result<Self, Box<dyn std::error::Error + Send + Sync>> {
        let redis_manager = match redis_url {
            Some(url) => {
                let client = Client::open(url)?;
                Some(ConnectionManager::new(client).await?)
            }
            None => None,
        };
        Ok(Self {
            redis_manager,
            default_rpm: 60,
            default_tpm: 100000,
        })
    }

    /// Create a RateLimiter from an existing ConnectionManager.
    /// This allows sharing a single Redis connection across subsystems.
    pub fn from_connection_manager(manager: ConnectionManager) -> Self {
        Self {
            redis_manager: Some(manager),
            default_rpm: 60,
            default_tpm: 100000,
        }
    }

    pub async fn is_allowed(
        &self,
        key: &str,
        amount: u64,
    ) -> Result<bool, Box<dyn std::error::Error + Send + Sync>> {
        self.is_allowed_with_quota(key, amount, None).await
    }

    pub async fn is_allowed_with_quota(
        &self,
        key: &str,
        amount: u64,
        quota: Option<&crate::types::Quota>,
    ) -> Result<bool, Box<dyn std::error::Error + Send + Sync>> {
        let rpm_limit = quota
            .and_then(|q| q.max_requests_per_minute)
            .unwrap_or(self.default_rpm);
        let tpm_limit = quota
            .and_then(|q| q.max_tokens_per_minute)
            .unwrap_or(self.default_tpm);

        if let Some(ref manager) = self.redis_manager {
            let mut conn = manager.clone();

            let result: Vec<u64> = redis::cmd("EVAL")
                .arg(RPM_SCRIPT)
                .arg(1)
                .arg(format!("hyperinfer:ratelimit:rpm:{}", key))
                .arg(rpm_limit)
                .arg(60)
                .query_async(&mut conn)
                .await?;

            let allowed = result.first().copied().unwrap_or(0);
            if allowed == 0 {
                return Ok(false);
            }

            let tpm_key = format!("hyperinfer:ratelimit:tpm:{}", key);
            let now_ms = std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .map_err(|e| Box::new(e) as Box<dyn std::error::Error + Send + Sync>)?
                .as_millis() as u64;
            let tpm_result: Vec<u64> = redis::cmd("EVAL")
                .arg(GCRA_SCRIPT)
                .arg(1)
                .arg(&tpm_key)
                .arg(tpm_limit)
                .arg(TPM_WINDOW_MS)
                .arg(now_ms)
                .arg(amount)
                .query_async(&mut conn)
                .await?;

            Ok(tpm_result.first().copied().unwrap_or(0) == 1)
        } else {
            Ok(true)
        }
    }

    pub async fn check_rpm(
        &self,
        key: &str,
        limit: u64,
    ) -> Result<(bool, u64), Box<dyn std::error::Error + Send + Sync>> {
        if let Some(ref manager) = self.redis_manager {
            let mut conn = manager.clone();

            let result: Vec<u64> = redis::cmd("EVAL")
                .arg(RPM_SCRIPT)
                .arg(1)
                .arg(format!("hyperinfer:ratelimit:rpm:{}", key))
                .arg(limit)
                .arg(60)
                .query_async(&mut conn)
                .await?;

            let allowed = result.first().copied().unwrap_or(0) == 1;
            let remaining = result.get(1).copied().unwrap_or(0);
            Ok((allowed, remaining))
        } else {
            Ok((true, limit))
        }
    }

    pub async fn check_tpm(
        &self,
        key: &str,
        limit: u64,
        tokens: u64,
    ) -> Result<bool, Box<dyn std::error::Error + Send + Sync>> {
        if let Some(ref manager) = self.redis_manager {
            let mut conn = manager.clone();

            let now_ms = std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .map_err(|e| Box::new(e) as Box<dyn std::error::Error + Send + Sync>)?
                .as_millis() as u64;

            let result: Vec<u64> = redis::cmd("EVAL")
                .arg(GCRA_SCRIPT)
                .arg(1)
                .arg(format!("hyperinfer:ratelimit:tpm:{}", key))
                .arg(limit)
                .arg(TPM_WINDOW_MS)
                .arg(now_ms)
                .arg(tokens)
                .query_async(&mut conn)
                .await?;

            Ok(result.first().copied().unwrap_or(0) == 1)
        } else {
            Ok(true)
        }
    }

    /// Charge additional tokens against the TPM limiter (e.g., for actual usage
    /// that exceeded the pre-request estimate). Does not affect RPM.
    pub async fn charge_tokens(
        &self,
        key: &str,
        tokens: u64,
        quota: Option<&crate::types::Quota>,
    ) -> Result<bool, Box<dyn std::error::Error + Send + Sync>> {
        if tokens == 0 {
            return Ok(true);
        }
        let tpm_limit = quota
            .and_then(|q| q.max_tokens_per_minute)
            .unwrap_or(self.default_tpm);

        if let Some(ref manager) = self.redis_manager {
            let mut conn = manager.clone();
            let tpm_key = format!("hyperinfer:ratelimit:tpm:{}", key);
            let now_ms = std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .map_err(|e| Box::new(e) as Box<dyn std::error::Error + Send + Sync>)?
                .as_millis() as u64;
            let result: Vec<u64> = redis::cmd("EVAL")
                .arg(GCRA_SCRIPT)
                .arg(1)
                .arg(&tpm_key)
                .arg(tpm_limit)
                .arg(TPM_WINDOW_MS)
                .arg(now_ms)
                .arg(tokens)
                .query_async(&mut conn)
                .await?;
            Ok(result.first().copied().unwrap_or(0) == 1)
        } else {
            Ok(true)
        }
    }

    pub async fn record_usage(
        &self,
        key: &str,
        tokens_used: u64,
    ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
        if let Some(ref manager) = self.redis_manager {
            let mut conn = manager.clone();
            let tokens_key = format!("{}{}", USAGE_TOKENS_KEY_PREFIX, key);
            let requests_key = format!("{}{}", USAGE_REQUESTS_KEY_PREFIX, key);

            redis::pipe()
                .atomic()
                .cmd("INCRBY")
                .arg(&tokens_key)
                .arg(tokens_used)
                .cmd("EXPIRE")
                .arg(&tokens_key)
                .arg(USAGE_KEY_TTL_SECS)
                .cmd("INCR")
                .arg(&requests_key)
                .cmd("EXPIRE")
                .arg(&requests_key)
                .arg(USAGE_KEY_TTL_SECS)
                .query_async::<()>(&mut conn)
                .await?;
        }
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::types::Quota;

    #[tokio::test]
    async fn test_rate_limiter_new_without_redis() {
        let result = RateLimiter::new(None).await;
        assert!(result.is_ok());
        let limiter = result.unwrap();
        assert_eq!(limiter.default_rpm, 60);
        assert_eq!(limiter.default_tpm, 100000);
    }

    #[tokio::test]
    async fn test_rate_limiter_is_allowed_without_redis() {
        let limiter = RateLimiter::new(None).await.unwrap();
        let result = limiter.is_allowed("test-key", 1).await;
        assert!(result.is_ok());
        // Without Redis, should always allow
        assert!(result.unwrap());
    }

    #[tokio::test]
    async fn test_rate_limiter_check_rpm_without_redis() {
        let limiter = RateLimiter::new(None).await.unwrap();
        let result = limiter.check_rpm("test-key", 100).await;
        assert!(result.is_ok());
        let (allowed, remaining) = result.unwrap();
        // Without Redis, should always allow
        assert!(allowed);
        assert_eq!(remaining, 100);
    }

    #[tokio::test]
    async fn test_rate_limiter_check_tpm_without_redis() {
        let limiter = RateLimiter::new(None).await.unwrap();
        let result = limiter.check_tpm("test-key", 1000, 100).await;
        assert!(result.is_ok());
        // Without Redis, should always allow
        assert!(result.unwrap());
    }

    #[tokio::test]
    async fn test_rate_limiter_record_usage_without_redis() {
        let limiter = RateLimiter::new(None).await.unwrap();
        let result = limiter.record_usage("test-key", 50).await;
        assert!(result.is_ok());
    }

    #[test]
    fn test_quota_creation() {
        let quota = Quota {
            max_requests_per_minute: Some(60),
            max_tokens_per_minute: Some(100000),
            budget_cents: Some(1000),
        };

        assert_eq!(quota.max_requests_per_minute, Some(60));
        assert_eq!(quota.max_tokens_per_minute, Some(100000));
        assert_eq!(quota.budget_cents, Some(1000));
    }

    #[test]
    fn test_quota_with_none_values() {
        let quota = Quota {
            max_requests_per_minute: None,
            max_tokens_per_minute: None,
            budget_cents: None,
        };

        assert_eq!(quota.max_requests_per_minute, None);
        assert_eq!(quota.max_tokens_per_minute, None);
        assert_eq!(quota.budget_cents, None);
    }

    #[test]
    fn test_quota_clone() {
        let quota = Quota {
            max_requests_per_minute: Some(100),
            max_tokens_per_minute: Some(50000),
            budget_cents: Some(2000),
        };

        let cloned = quota.clone();
        assert_eq!(
            quota.max_requests_per_minute,
            cloned.max_requests_per_minute
        );
        assert_eq!(quota.max_tokens_per_minute, cloned.max_tokens_per_minute);
        assert_eq!(quota.budget_cents, cloned.budget_cents);
    }

    #[tokio::test]
    async fn test_rate_limiter_is_allowed_with_zero_amount() {
        let limiter = RateLimiter::new(None).await.unwrap();
        let result = limiter.is_allowed("test-key", 0).await;
        assert!(result.is_ok());
        assert!(result.unwrap());
    }

    #[tokio::test]
    async fn test_rate_limiter_is_allowed_with_large_amount() {
        let limiter = RateLimiter::new(None).await.unwrap();
        let result = limiter.is_allowed("test-key", 999999).await;
        assert!(result.is_ok());
        assert!(result.unwrap());
    }

    #[tokio::test]
    async fn test_rate_limiter_check_rpm_with_different_limits() {
        let limiter = RateLimiter::new(None).await.unwrap();

        let result1 = limiter.check_rpm("key1", 10).await;
        assert!(result1.is_ok());
        assert_eq!(result1.unwrap().1, 10);

        let result2 = limiter.check_rpm("key2", 1000).await;
        assert!(result2.is_ok());
        assert_eq!(result2.unwrap().1, 1000);
    }

    #[tokio::test]
    async fn test_rate_limiter_record_usage_multiple_times() {
        let limiter = RateLimiter::new(None).await.unwrap();

        assert!(limiter.record_usage("key", 100).await.is_ok());
        assert!(limiter.record_usage("key", 200).await.is_ok());
        assert!(limiter.record_usage("key", 300).await.is_ok());
    }
}