api_huggingface 0.6.1

HuggingFace's API for accessing large language models (LLMs) and embeddings.
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
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
//! Integration tests for Rate Limiting
//!
//! These tests use REAL `HuggingFace` API calls to verify rate limiting behavior.
//! NO MOCKING is used - all tests interact with actual endpoints.
//!
//! ## Test Strategy
//!
//! - Use real `HuggingFace` API endpoints
//! - Test actual rate limiting with real requests
//! - Test token refill mechanics with timing

#![ allow( clippy::doc_markdown ) ]
//! - Test all time windows ( per-second, per-minute, per-hour )
//!
//! ## Running Tests
//!
//! These tests require:
//! - HuggingFace API key ( `HUGGINGFACE_API_KEY` or `INFERENCE_API_KEY` env var )
//! - Network connectivity
//! - Real API quota/limits
//!
//! Run with:
//! ```bash
//! cargo test --test rate_limiting_tests --all-features -- --ignored
//! ```

mod inc;

use api_huggingface::reliability::{ RateLimiter, RateLimiterConfig };
use core::time::Duration;
use std::time::Instant;

#[ cfg( feature = "integration" ) ]
use api_huggingface::{
  Client,
  environment::HuggingFaceEnvironmentImpl,
  providers::ChatMessage,
  Secret,
};

#[ cfg( feature = "integration" ) ]
fn create_integration_client() -> Client< HuggingFaceEnvironmentImpl >
{
  let api_key = crate::inc::get_api_key_for_integration();
  let secret = Secret::new( api_key );
  let env = HuggingFaceEnvironmentImpl::build( secret, None )
    .expect( "Failed to build environment" );
  Client::build( env ).expect( "Failed to create client" )
}

// ============================================================================
// Basic Rate Limiting Tests
// ============================================================================

#[ tokio::test ]
async fn test_rate_limiter_per_second_limit() 
{
  let config = RateLimiterConfig {
  requests_per_second : Some( 2 ),
  requests_per_minute : None,
  requests_per_hour : None,
  };
  let limiter = RateLimiter::new( config );

  // First two requests should succeed
  assert!( limiter.try_acquire( ).await.is_ok( ));
  assert!( limiter.try_acquire( ).await.is_ok( ));

  // Third request should fail ( rate limited )
  assert!( limiter.try_acquire( ).await.is_err( ));
}

#[ tokio::test ]
async fn test_rate_limiter_per_minute_limit() 
{
  let config = RateLimiterConfig {
  requests_per_second : None,
  requests_per_minute : Some( 3 ),
  requests_per_hour : None,
  };
  let limiter = RateLimiter::new( config );

  // First three requests should succeed
  for _ in 0..3
  {
  assert!( limiter.try_acquire( ).await.is_ok( ));
  }

  // Fourth request should fail
  assert!( limiter.try_acquire( ).await.is_err( ));
}

#[ tokio::test ]
async fn test_rate_limiter_per_hour_limit() 
{
  let config = RateLimiterConfig {
  requests_per_second : None,
  requests_per_minute : None,
  requests_per_hour : Some( 5 ),
  };
  let limiter = RateLimiter::new( config );

  // First five requests should succeed
  for _ in 0..5
  {
  assert!( limiter.try_acquire( ).await.is_ok( ));
  }

  // Sixth request should fail
  assert!( limiter.try_acquire( ).await.is_err( ));
}

// ============================================================================
// Token Refill Tests
// ============================================================================

#[ tokio::test ]
async fn test_rate_limiter_token_refill() 
{
  let config = RateLimiterConfig {
  requests_per_second : Some( 10 ),
  requests_per_minute : None,
  requests_per_hour : None,
  };
  let limiter = RateLimiter::new( config );

  // Consume all tokens
  for _ in 0..10
  {
  assert!( limiter.try_acquire( ).await.is_ok( ));
  }

  // Should be rate limited
  assert!( limiter.try_acquire( ).await.is_err( ));

  // Wait for token refill ( 100ms = 1 token )
  tokio::time::sleep( Duration::from_millis( 150 )).await;

  // Should have at least one token now
  assert!( limiter.try_acquire( ).await.is_ok( ));
}

#[ tokio::test ]
async fn test_rate_limiter_gradual_refill() 
{
  let config = RateLimiterConfig {
  requests_per_second : Some( 10 ),
  requests_per_minute : None,
  requests_per_hour : None,
  };
  let limiter = RateLimiter::new( config );

  // Consume all tokens
  for _ in 0..10
  {
  limiter.try_acquire( ).await.unwrap( );
  }

  // Wait for 500ms ( should refill ~5 tokens )
  tokio::time::sleep( Duration::from_millis( 500 )).await;

  // Should be able to consume ~5 tokens
  let mut count = 0;
  for _ in 0..10
  {
  if limiter.try_acquire( ).await.is_ok( )
  {
      count += 1;
  } else {
      break;
  }
  }

  // Should have gotten at least 4 tokens ( accounting for timing variance )
  assert!( count >= 4, "Expected at least 4 tokens, got {count}" );
}

// ============================================================================
// Multiple Time Windows Tests
// ============================================================================

#[ tokio::test ]
async fn test_rate_limiter_multiple_windows() 
{
  let config = RateLimiterConfig {
  requests_per_second : Some( 5 ),
  requests_per_minute : Some( 10 ),
  requests_per_hour : None,
  };
  let limiter = RateLimiter::new( config );

  // Consume 5 requests ( hits per-second limit )
  for _ in 0..5
  {
  assert!( limiter.try_acquire( ).await.is_ok( ));
  }

  // Should be rate limited by per-second window
  let result = limiter.try_acquire( ).await;
  assert!( result.is_err( ));
}

#[ tokio::test ]
async fn test_rate_limiter_minute_limit_after_second_refill() 
{
  let config = RateLimiterConfig {
  requests_per_second : Some( 3 ),
  requests_per_minute : Some( 5 ),
  requests_per_hour : None,
  };
  let limiter = RateLimiter::new( config );

  // Consume 3 requests ( hits per-second limit )
  for _ in 0..3
  {
  limiter.try_acquire( ).await.unwrap( );
  }

  // Wait for per-second refill
  tokio::time::sleep( Duration::from_secs( 1 )).await;

  // Consume 2 more ( now at 5 total for minute )
  limiter.try_acquire( ).await.unwrap( );
  limiter.try_acquire( ).await.unwrap( );

  // Wait for per-second refill again
  tokio::time::sleep( Duration::from_secs( 1 )).await;

  // Try another - should be blocked by per-minute limit
  assert!( limiter.try_acquire( ).await.is_err( ));
}

// ============================================================================
// Blocking Acquire Tests
// ============================================================================

#[ tokio::test ]
async fn test_rate_limiter_acquire_blocks_and_succeeds() 
{
  let config = RateLimiterConfig {
  requests_per_second : Some( 2 ),
  requests_per_minute : None,
  requests_per_hour : None,
  };
  let limiter = RateLimiter::new( config );

  // Consume all tokens
  limiter.try_acquire( ).await.unwrap( );
  limiter.try_acquire( ).await.unwrap( );

  // This should block until token available
  let start = Instant::now( );
  limiter.acquire( ).await.unwrap( );
  let elapsed = start.elapsed( );

  // Should have waited at least 400ms ( allowing some margin )
  assert!( elapsed >= Duration::from_millis( 400 ), "Expected wait >=400ms, got {elapsed:?}" );
}

#[ tokio::test ]
async fn test_rate_limiter_acquire_with_available_tokens() 
{
  let config = RateLimiterConfig {
  requests_per_second : Some( 5 ),
  requests_per_minute : None,
  requests_per_hour : None,
  };
  let limiter = RateLimiter::new( config );

  // Acquire should not block when tokens available
  let start = Instant::now( );
  limiter.acquire( ).await.unwrap( );
  let elapsed = start.elapsed( );

  // Should be nearly instant
  assert!( elapsed < Duration::from_millis( 50 ), "Expected instant acquire, got {elapsed:?}" );
}

// ============================================================================
// Available Tokens Tests
// ============================================================================

#[ tokio::test ]
async fn test_rate_limiter_available_tokens_initial() 
{
  let config = RateLimiterConfig {
  requests_per_second : Some( 10 ),
  requests_per_minute : Some( 100 ),
  requests_per_hour : Some( 1000 ),
  };
  let limiter = RateLimiter::new( config );

  let tokens = limiter.available_tokens( ).await;
  assert_eq!( tokens.per_second, Some( 10 ));
  assert_eq!( tokens.per_minute, Some( 100 ));
  assert_eq!( tokens.per_hour, Some( 1000 ));
}

#[ tokio::test ]
async fn test_rate_limiter_available_tokens_after_consumption() 
{
  let config = RateLimiterConfig {
  requests_per_second : Some( 5 ),
  requests_per_minute : Some( 10 ),
  requests_per_hour : None,
  };
  let limiter = RateLimiter::new( config );

  // Consume 2 tokens
  limiter.try_acquire( ).await.unwrap( );
  limiter.try_acquire( ).await.unwrap( );

  let tokens = limiter.available_tokens( ).await;
  assert_eq!( tokens.per_second, Some( 3 ));
  assert_eq!( tokens.per_minute, Some( 8 ));
  assert_eq!( tokens.per_hour, None );
}

#[ tokio::test ]
async fn test_rate_limiter_available_tokens_tracks_refill() 
{
  let config = RateLimiterConfig {
  requests_per_second : Some( 10 ),
  requests_per_minute : None,
  requests_per_hour : None,
  };
  let limiter = RateLimiter::new( config );

  // Consume all tokens
  for _ in 0..10
  {
  limiter.try_acquire( ).await.unwrap( );
  }

  let tokens_before = limiter.available_tokens( ).await;
  assert_eq!( tokens_before.per_second, Some( 0 ));

  // Wait for refill
  tokio::time::sleep( Duration::from_millis( 200 )).await;

  let tokens_after = limiter.available_tokens( ).await;
  assert!( tokens_after.per_second.unwrap( ) >= 1 );
}

// ============================================================================
// Reset Tests
// ============================================================================

#[ tokio::test ]
async fn test_rate_limiter_reset() 
{
  let config = RateLimiterConfig {
  requests_per_second : Some( 3 ),
  requests_per_minute : Some( 5 ),
  requests_per_hour : None,
  };
  let limiter = RateLimiter::new( config );

  // Consume all tokens
  for _ in 0..3
  {
  limiter.try_acquire( ).await.unwrap( );
  }

  // Should be rate limited
  assert!( limiter.try_acquire( ).await.is_err( ));

  // Reset
  limiter.reset( ).await;

  // Should have full tokens again
  let tokens = limiter.available_tokens( ).await;
  assert_eq!( tokens.per_second, Some( 3 ));
  assert_eq!( tokens.per_minute, Some( 5 ));

  // Should be able to acquire
  assert!( limiter.try_acquire( ).await.is_ok( ));
}

// ============================================================================
// Real API Integration Tests
// ============================================================================

#[ cfg( feature = "integration" ) ]
#[ tokio::test ]
async fn test_rate_limiter_with_real_api_calls()
{
  let client = create_integration_client();
  // Use per-minute limit so the bucket does not refill during API call latency.
  let config = RateLimiterConfig {
  requests_per_second : None,
  requests_per_minute : Some( 2 ),
  requests_per_hour : None,
  };
  let limiter = RateLimiter::new( config );

  // Make 2 real API calls with rate limiting — both must succeed.
  for i in 0..2
  {
  limiter.acquire( ).await.unwrap( );

  let result = client.providers( ).chat_completion(
      "meta-llama/Llama-3.3-70B-Instruct",
      vec![ChatMessage {
  role : "user".to_string( ),
  content : format!( "Say the number {i}" ),
  tool_calls : None,
  tool_call_id : None,
      } ],
      Some( 10 ),
      None,
      None,
  ).await;

  assert!( result.is_ok( ), "API call {i} should succeed" );
  }

  // Per-minute bucket is now exhausted — immediate try_acquire must fail.
  let rate_limited = limiter.try_acquire( ).await;
  assert!( rate_limited.is_err( ), "Rate limiter must block after per-minute quota exhausted" );
}

#[ cfg( feature = "integration" ) ]
#[ tokio::test ]
async fn test_rate_limiter_prevents_api_overload()
{
  let client = create_integration_client();
  let config = RateLimiterConfig {
  requests_per_second : Some( 3 ),
  requests_per_minute : Some( 5 ),
  requests_per_hour : None,
  };
  let limiter = RateLimiter::new( config );

  let mut successful_calls = 0;
  let mut rate_limited_calls = 0;

  // Try to make 10 calls rapidly
  for i in 0..10
  {
  if limiter.try_acquire( ).await.is_ok( )
  {
      let result = client.providers( ).chat_completion(
  "meta-llama/Llama-3.3-70B-Instruct",
  vec![ChatMessage {
          role : "user".to_string( ),
          content : format!( "Count {i}" ),
          tool_calls : None,
          tool_call_id : None,
  } ],
  Some( 5 ),
  None,
  None,
      ).await;

      if result.is_ok( )
      {
  successful_calls += 1;
      }
  } else {
      rate_limited_calls += 1;
  }
  }

  // Should have limited some calls
  assert!( rate_limited_calls > 0, "Expected some calls to be rate limited" );
  assert!( successful_calls <= 5, "Should not exceed minute limit" );
}

// ============================================================================
// Concurrent Access Tests
// ============================================================================

#[ tokio::test ]
async fn test_rate_limiter_concurrent_acquire() 
{
  let config = RateLimiterConfig {
  requests_per_second : Some( 10 ),
  requests_per_minute : None,
  requests_per_hour : None,
  };
  let limiter = RateLimiter::new( config );

  let mut handles = vec![ ];

  // Spawn 15 concurrent tasks trying to acquire
  for _ in 0..15
  {
  let l = limiter.clone( );
  let handle = tokio::spawn( async move {
      l.acquire( ).await
  } );
  handles.push( handle );
  }

  // All should eventually succeed ( some will wait )
  for handle in handles
  {
  let result = handle.await.expect( "Task should complete" );
  assert!( result.is_ok( ));
  }
}

#[ tokio::test ]
async fn test_rate_limiter_concurrent_try_acquire() 
{
  let config = RateLimiterConfig {
  requests_per_second : Some( 5 ),
  requests_per_minute : None,
  requests_per_hour : None,
  };
  let limiter = RateLimiter::new( config );

  let mut handles = vec![ ];

  // Spawn 10 concurrent tasks trying to acquire ( no blocking )
  for _ in 0..10
  {
  let l = limiter.clone( );
  let handle = tokio::spawn( async move {
      l.try_acquire( ).await
  } );
  handles.push( handle );
  }

  let mut succeeded = 0;
  let mut failed = 0;

  for handle in handles
  {
  let result = handle.await.expect( "Task should complete" );
  if result.is_ok( )
  {
      succeeded += 1;
  } else {
      failed += 1;
  }
  }

  // Approximately 5 should succeed, 5 should fail
  assert!( succeeded <= 5, "Should not exceed limit" );
  assert!( failed >= 5, "Some should be rate limited" );
}

// ============================================================================
// Bug Reproducer Tests
// ============================================================================

/// bug_reproducer(BUG-001)
#[ tokio::test ]
async fn test_rate_limiter_zero_capacity_try_acquire_no_panic()
{
  // Root Cause: TokenBucket::new(0, refill_duration) sets refill_rate = 0.0/duration = 0.0.
  //   try_consume() always returns false (tokens=0.0 < 1.0). time_until_token() then computes
  //   tokens_needed / refill_rate = 1.0 / 0.0 = +Infinity (f64 silent div-by-zero).
  //   Duration::from_secs_f64(+Infinity) panics unconditionally in Rust's stdlib.
  // Why Not Caught: No existing test used capacity=0; minimum tested capacity was 1.
  // Fix Applied: time_until_token() guards seconds.is_finite() before converting;
  //   returns Some(Duration::MAX) when refill_rate=0.0 to signal permanently empty bucket.
  // Prevention: Always test boundary value 0 for all numeric configuration fields.
  // Pitfall: Duration::from_secs_f64() panics on non-finite floats. f64 div-by-zero yields
  //   +Infinity silently — the panic only surfaces at the Duration conversion call site.
  let rl = RateLimiter::new( RateLimiterConfig
  {
    requests_per_second : Some( 0 ),
    requests_per_minute : None,
    requests_per_hour : None,
  } );
  let result = rl.try_acquire( ).await;
  assert!( result.is_err( ), "zero-capacity limiter must reject request without panicking" );
}

// ============================================================================
// Edge Case Tests
// ============================================================================

#[ tokio::test ]
async fn test_rate_limiter_no_limits()
{
  let config = RateLimiterConfig {
  requests_per_second : None,
  requests_per_minute : None,
  requests_per_hour : None,
  };
  let limiter = RateLimiter::new( config );

  // Should allow unlimited requests
  for _ in 0..100
  {
  assert!( limiter.try_acquire( ).await.is_ok( ));
  }
}

#[ tokio::test ]
async fn test_rate_limiter_default_config() 
{
  let config = RateLimiterConfig::default( );
  assert_eq!( config.requests_per_second, Some( 10 ));
  assert_eq!( config.requests_per_minute, Some( 500 ));
  assert_eq!( config.requests_per_hour, Some( 10000 ));

  let limiter = RateLimiter::new( config );

  // Should allow default limits
  for _ in 0..10
  {
  assert!( limiter.try_acquire( ).await.is_ok( ));
  }

  // 11th should fail
  assert!( limiter.try_acquire( ).await.is_err( ));
}

#[ tokio::test ]
async fn test_rate_limiter_very_low_limit() 
{
  let config = RateLimiterConfig {
  requests_per_second : Some( 1 ),
  requests_per_minute : None,
  requests_per_hour : None,
  };
  let limiter = RateLimiter::new( config );

  // First should succeed
  assert!( limiter.try_acquire( ).await.is_ok( ));

  // Second should fail immediately
  assert!( limiter.try_acquire( ).await.is_err( ));

  // Wait for refill
  tokio::time::sleep( Duration::from_secs( 1 )).await;

  // Should succeed again
  assert!( limiter.try_acquire( ).await.is_ok( ));
}