api_huggingface 0.4.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
//! Failover Implementation
//!
//! Provides automatic failover to backup endpoints when primary endpoints fail.
//!
//! ## Strategies
//!
//! - **Priority**: Try endpoints in order until one succeeds
//! - **`RoundRobin`**: Distribute requests evenly across endpoints
//! - **Random**: Select random endpoint for each request
//! - **Sticky**: Stick to one endpoint until it fails
//!
//! ## Usage
//!
//! ```no_run
//! # use api_huggingface::reliability::{FailoverManager, FailoverConfig, FailoverStrategy};
//! # use std::time::Duration;
//! # async fn example( ) -> Result< ( ), Box< dyn std::error::Error > > {
//! let failover = FailoverManager::new(
//!   FailoverConfig {
//!     endpoints : vec![
//!       "https://api-inference.huggingface.co".to_string( ),
//!       "https://api-inference-backup.huggingface.co".to_string( ),
//!     ],
//!     strategy : FailoverStrategy::Priority,
//!     max_retries : 3,
//!     failure_window : Duration::from_secs( 300 ),
//!     failure_threshold : 5,
//!   }
//! ).map_err( |e| format!( "{:?}", e ))?;
//!
//! let _endpoint = failover.select_endpoint( ).await.map_err( |e| format!( "{:?}", e ))?;
//! # Ok( ( ))
//! # }
//! ```

use std::sync::Arc;
use std::time::Instant;
use core::time::Duration;
use tokio::sync::RwLock;
use rand::RngExt;

/// Failover strategy
#[ derive( Debug, Clone, Copy, PartialEq, Eq ) ]
pub enum FailoverStrategy 
{
  /// Try endpoints in priority order
  Priority,
  /// Distribute requests evenly across endpoints
  RoundRobin,
  /// Select random endpoint for each request
  Random,
  /// Stick to one endpoint until it fails
  Sticky,
}

/// Failover configuration
#[ derive( Debug, Clone ) ]
pub struct FailoverConfig 
{
  /// List of endpoint URLs in priority order
  pub endpoints : Vec< String >,
  /// Failover strategy to use
  pub strategy : FailoverStrategy,
  /// Maximum retry attempts per request
  pub max_retries : u32,
  /// Time window for tracking endpoint failures
  pub failure_window : Duration,
  /// Number of failures before marking endpoint unhealthy
  pub failure_threshold : u32,
}

impl Default for FailoverConfig 
{
  #[ inline ]
  fn default() -> Self 
  {
  Self {
      endpoints : vec![ ],
      strategy : FailoverStrategy::Priority,
      max_retries : 3,
      failure_window : Duration::from_secs( 60 ),
      failure_threshold : 5,
  }
  }
}

/// Endpoint health status
#[ derive( Debug, Clone ) ]
struct EndpointHealth 
{
  /// Endpoint URL
  url : String,
  /// Recent failure timestamps
  failures : Vec< Instant >,
  /// Total requests sent to this endpoint
  requests : u64,
  /// Total successful requests
  successes : u64,
  /// Last successful request time
  last_success : Option< Instant >,
  /// Is endpoint currently healthy
  healthy : bool,
}

impl EndpointHealth 
{
  /// Create new endpoint health tracker
  #[ inline ]
  fn new( url : String ) -> Self 
  {
  Self {
      url,
      failures : Vec::new( ),
      requests : 0,
      successes : 0,
      last_success : None,
      healthy : true,
  }
  }

  /// Record a successful request
  #[ inline ]
  fn record_success( &mut self ) 
  {
  self.requests += 1;
  self.successes += 1;
  self.last_success = Some( Instant::now( ));
  self.healthy = true;
  }

  /// Record a failed request
  #[ inline ]
  fn record_failure( &mut self, failure_window : Duration, failure_threshold : u32 ) 
  {
  self.requests += 1;
  let now = Instant::now( );
  self.failures.push( now );

  // Remove failures outside the window
  self.failures.retain( |&t| now.duration_since( t ) < failure_window );

  // Update health status
  if self.failures.len( ) >= failure_threshold as usize
  {
      self.healthy = false;
  }
  }

  /// Get failure count in current window
  #[ inline ]
  fn failure_count( &mut self, failure_window : Duration ) -> usize 
  {
  let now = Instant::now( );
  self.failures.retain( |&t| now.duration_since( t ) < failure_window );
  self.failures.len( )
  }

  /// Get success rate
  #[ inline ]
  fn success_rate( &self ) -> f64
  {
  if self.requests == 0
  {
      1.0
  } else {
      self.successes as f64 / self.requests as f64
  }
  }
}

/// Failover manager state
#[ derive( Debug ) ]
struct FailoverState 
{
  /// Endpoint health tracking
  endpoints : Vec< EndpointHealth >,
  /// Current index for round-robin
  round_robin_index : usize,
  /// Current sticky endpoint index
  sticky_index : Option< usize >,
}

/// Failover manager for multi-endpoint failover
#[ derive( Debug, Clone ) ]
pub struct FailoverManager 
{
  config : FailoverConfig,
  state : Arc< RwLock< FailoverState > >,
}

impl FailoverManager 
{
  /// Create new failover manager with given configuration
  ///
  /// # Errors
  ///
  /// Returns `FailoverError::NoEndpoints` if no endpoints are configured.
  #[ inline ]
  pub fn new( config : FailoverConfig ) -> Result< Self, FailoverError > 
  {
  if config.endpoints.is_empty( )
  {
      return Err( FailoverError::NoEndpoints );
  }

  let endpoints = config.endpoints.iter( )
      .map( |url| EndpointHealth::new( url.clone( )) )
      .collect( );

  Ok( Self {
      config,
      state : Arc::new( RwLock::new( FailoverState {
  endpoints,
  round_robin_index : 0,
  sticky_index : None,
      } )),
  } )
  }

  /// Select next endpoint based on strategy
  ///
  /// # Errors
  ///
  /// Returns `FailoverError::AllEndpointsUnhealthy` if no healthy endpoints available.
  #[ inline ]
  pub async fn select_endpoint( &self ) -> Result< String, FailoverError > 
  {
  let mut state = self.state.write( ).await;

  match self.config.strategy
  {
      FailoverStrategy::Priority => {
  // Try endpoints in order, prefer healthy ones
  for endpoint in &state.endpoints
  {
          if endpoint.healthy
          {
      return Ok( endpoint.url.clone( ));
          }
  }
  // If all unhealthy, try first one anyway
  state.endpoints.first( )
          .map( |e| e.url.clone( ))
          .ok_or( FailoverError::NoEndpoints )
      }

      FailoverStrategy::RoundRobin => {
  let healthy_count = state.endpoints.iter( ).filter( |e| e.healthy ).count( );
  if healthy_count == 0
  {
          return Err( FailoverError::AllEndpointsUnhealthy );
  }

  // Find next healthy endpoint
  let start_index = state.round_robin_index;
  loop
  {
          let current_index = state.round_robin_index;
          let endpoint_url = state.endpoints[current_index ].url.clone( );
          let endpoint_healthy = state.endpoints[current_index ].healthy;

          state.round_robin_index = ( state.round_robin_index + 1 ) % state.endpoints.len( );

          if endpoint_healthy
          {
      return Ok( endpoint_url );
          }

          // Prevent infinite loop
          if state.round_robin_index == start_index
          {
      return Err( FailoverError::AllEndpointsUnhealthy );
          }
  }
      }

      FailoverStrategy::Random => {
  let healthy : Vec< _ > = state.endpoints.iter( )
          .filter( |e| e.healthy )
          .collect( );

  if healthy.is_empty( )
  {
          return Err( FailoverError::AllEndpointsUnhealthy );
  }

  let mut rng = rand::rng( );
  let index = rng.random_range( 0..healthy.len( ));
  Ok( healthy[index ].url.clone( ))
      }

      FailoverStrategy::Sticky => {
  // If no sticky endpoint or it's unhealthy, select new one
  if let Some( idx ) = state.sticky_index
  {
          if idx < state.endpoints.len( ) && state.endpoints[idx ].healthy
          {
      return Ok( state.endpoints[idx ].url.clone( ));
          }
  }

  // Select first healthy endpoint
  for i in 0..state.endpoints.len( )
  {
          if state.endpoints[i ].healthy
          {
      let url = state.endpoints[i ].url.clone( );
      state.sticky_index = Some( i );
      return Ok( url );
          }
  }

  Err( FailoverError::AllEndpointsUnhealthy )
      }
  }
  }

  /// Execute operation with failover retry logic
  ///
  /// Tries the operation with different endpoints until success or max retries reached.
  ///
  /// # Errors
  ///
  /// Returns `FailoverError::AllRetriesFailed` if all retry attempts fail.
  /// Returns `FailoverError::Operation` wrapping the underlying error if operation fails.
  #[ inline ]
  pub async fn execute_with_failover< F, T, E >( &self, mut f : F ) -> Result< T, FailoverError< E > >
  where
  F : FnMut( String ) -> core::pin::Pin< Box< dyn core::future::Future< Output = Result< T, E > > + Send > >,
  E: core::fmt::Display,
  {
  let mut attempts = 0;
  let mut last_error = None;

  while attempts <= self.config.max_retries
  {
      attempts += 1;

      let endpoint = match self.select_endpoint( ).await
      {
  Ok( ep ) => ep,
  Err( e ) => return Err( FailoverError::SelectionFailed( e.to_string( )) ),
      };

      let endpoint_clone = endpoint.clone( );
      match f( endpoint.clone( )).await
      {
  Ok( result ) => {
          self.record_success( &endpoint_clone ).await;
          return Ok( result );
  }
  Err( e ) => {
          self.record_failure( &endpoint_clone ).await;
          last_error = Some( e );

          // Exponential backoff before retry: 500ms, 1s, 2s, 4s (capped at 5s)
          // This gives the API time to recover from rate limiting or transient issues
          if attempts <= self.config.max_retries
          {
            // Fix(BUG-002): cap exponent before multiply to prevent u64 overflow.
            // Root cause: 500 * 2^(attempts-1) overflows u64 when attempts-1 >= 56
            //   (500 * 2^56 > u64::MAX); .min(5000) was applied post-overflow — too late.
            // Pitfall: cap the exponent, not the result; post-multiply clamping cannot
            //   prevent the overflow that happens during arithmetic itself.
            let exp = ( attempts - 1 ).min( 13 );
            let delay_ms = 500 * 2u64.pow( exp );
            tokio::time::sleep( Duration::from_millis( delay_ms.min( 5000 ) ) ).await;
          }
  }
      }
  }

  if let Some( err ) = last_error
  {
      Err( FailoverError::AllRetriesFailed {
  attempts,
  last_error : err.to_string( ),
      } )
  } else {
      Err( FailoverError::AllEndpointsUnhealthy )
  }
  }

  /// Record successful request for endpoint
  #[ inline ]
  pub async fn record_success( &self, endpoint : &str ) 
  {
  let mut state = self.state.write( ).await;
  if let Some( ep ) = state.endpoints.iter_mut( ).find( |e| e.url == endpoint )
  {
      ep.record_success( );
  }
  }

  /// Record failed request for endpoint
  #[ inline ]
  pub async fn record_failure( &self, endpoint : &str ) 
  {
  let mut state = self.state.write( ).await;
  if let Some( ep ) = state.endpoints.iter_mut( ).find( |e| e.url == endpoint )
  {
      ep.record_failure( self.config.failure_window, self.config.failure_threshold );
  }
  }

  /// Get health status of all endpoints
  #[ inline ]
  pub async fn health_status( &self ) -> Vec< EndpointHealthStatus > 
  {
  let mut state = self.state.write( ).await;
  state.endpoints.iter_mut( ).map( |ep| {
      EndpointHealthStatus {
  url : ep.url.clone( ),
  healthy : ep.healthy,
  requests : ep.requests,
  successes : ep.successes,
  success_rate : ep.success_rate( ),
  failure_count : ep.failure_count( self.config.failure_window ),
      }
  } ).collect( )
  }

  /// Reset all endpoint health status
  #[ inline ]
  pub async fn reset( &self ) 
  {
  let mut state = self.state.write( ).await;
  for endpoint in &mut state.endpoints
  {
      endpoint.failures.clear( );
      endpoint.requests = 0;
      endpoint.successes = 0;
      endpoint.last_success = None;
      endpoint.healthy = true;
  }
  state.round_robin_index = 0;
  state.sticky_index = None;
  }
}

/// Endpoint health status ( public view )
#[ derive( Debug, Clone, PartialEq ) ]
pub struct EndpointHealthStatus 
{
  /// Endpoint URL
  pub url : String,
  /// Is endpoint healthy
  pub healthy : bool,
  /// Total requests
  pub requests : u64,
  /// Successful requests
  pub successes : u64,
  /// Success rate ( 0.0 - 1.0 )
  pub success_rate : f64,
  /// Current failure count in window
  pub failure_count : usize,
}

/// Failover errors
#[ derive( Debug ) ]
pub enum FailoverError< E = String > 
{
  /// No endpoints configured
  NoEndpoints,
  /// All endpoints are unhealthy
  AllEndpointsUnhealthy,
  /// Endpoint selection failed
  SelectionFailed( String ),
  /// All retry attempts failed
  AllRetriesFailed {
  /// Number of attempts made
  attempts : u32,
  /// Last error message
  last_error : String,
  },
  /// Operation failed
  Operation( E ),
}

impl< E > core::fmt::Display for FailoverError< E >
where
  E: core::fmt::Display,
{
  #[ inline ]
  fn fmt( &self, f : &mut core::fmt::Formatter< '_ > ) -> core::fmt::Result 
  {
  match self
  {
      Self::NoEndpoints => write!( f, "No endpoints configured" ),
      Self::AllEndpointsUnhealthy => write!( f, "All endpoints are unhealthy" ),
      Self::SelectionFailed( msg ) => write!( f, "Endpoint selection failed : {msg}" ),
      Self::AllRetriesFailed { attempts, last_error } => {
  write!( f, "All {attempts} retry attempts failed, last error : {last_error}" )
      }
      Self::Operation( e ) => write!( f, "Operation failed : {e}" ),
  }
  }
}

impl< E > std::error::Error for FailoverError< E >
where
  E: std::error::Error + 'static,
{
  #[ inline ]
  fn source( &self ) -> Option< &( dyn std::error::Error + 'static ) > 
  {
  match self
  {
      Self::Operation( e ) => Some( e ),
      _ => None,
  }
  }
}