api_gemini 0.5.0

Gemini's API for accessing large language models (LLMs).
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
//! Failover management for the Gemini API client.
//!
//! This module provides explicit failover functionality following the "Thin Client, Rich API" principle.
//! All failover operations are explicit and triggered by user code, not automatic behaviors.

mod private
{
  use serde::{ Deserialize, Serialize };
  use core::time::Duration;
  use std::time::SystemTime;
  use std::sync::{ Arc, Mutex };
  use std::collections::HashMap;
  use futures::Future;

  /// Configuration for failover behavior
  #[ derive( Debug, Clone, PartialEq, Serialize, Deserialize ) ]
  pub struct FailoverConfig
  {
    /// Primary endpoint URL
    pub primary_endpoint : String,
    /// List of backup endpoint URLs
    pub backup_endpoints : Vec< String >,
    /// Timeout for endpoint health checks
    pub timeout : Duration,
    /// Maximum retry attempts per endpoint
    pub max_retries : u32,
    /// Failover strategy to use
    pub strategy : FailoverStrategy,
  }

  impl Default for FailoverConfig
  {
    #[ inline ]
    fn default() -> Self
    {
      Self {
        primary_endpoint : "https://generativelanguage.googleapis.com".to_string(),
        backup_endpoints : Vec::new(),
        timeout : Duration::from_secs( 5 ),
        max_retries : 3,
        strategy : FailoverStrategy::Priority,
      }
    }
  }

  /// Builder for creating failover configuration
  #[ derive( Debug, Clone ) ]
  pub struct FailoverConfigBuilder
  {
    config : FailoverConfig,
  }

  impl Default for FailoverConfigBuilder
  {
    #[ inline ]
    fn default() -> Self
    {
      Self {
        config : FailoverConfig::default(),
      }
    }
  }

  impl FailoverConfigBuilder
  {
    /// Create a new failover config builder
    #[ inline ]
    #[ must_use ]
    pub fn new() -> Self
    {
      Self {
        config : FailoverConfig::default(),
      }
    }

    /// Set the primary endpoint
    #[ inline ]
    #[ must_use ]
    pub fn primary_endpoint( mut self, endpoint : String ) -> Self
    {
      self.config.primary_endpoint = endpoint;
      self
    }

    /// Add a backup endpoint
    #[ inline ]
    #[ must_use ]
    pub fn backup_endpoint( mut self, endpoint : String ) -> Self
    {
      self.config.backup_endpoints.push( endpoint );
      self
    }

    /// Set the timeout for health checks
    #[ inline ]
    #[ must_use ]
    pub fn timeout( mut self, timeout : Duration ) -> Self
    {
      self.config.timeout = timeout;
      self
    }

    /// Set the maximum retry attempts
    #[ inline ]
    #[ must_use ]
    pub fn max_retries( mut self, retries : u32 ) -> Self
    {
      self.config.max_retries = retries;
      self
    }

    /// Set the failover strategy
    #[ inline ]
    #[ must_use ]
    pub fn strategy( mut self, strategy : FailoverStrategy ) -> Self
    {
      self.config.strategy = strategy;
      self
    }

    /// Build the configuration with validation
    ///
    /// # Errors
    ///
    /// Returns `Error` if the configuration is invalid:
    /// - Primary endpoint is empty
    /// - Timeout is zero
    /// - Max retries exceeds reasonable limits
    #[ inline ]
    pub fn build( self ) -> Result< FailoverConfig, crate::error::Error >
    {
      Self::validate_config( &self.config )?;
      Ok( self.config )
    }

    /// Validate the failover configuration
    #[ inline ]
    fn validate_config( config : &FailoverConfig ) -> Result< (), crate::error::Error >
    {
      if config.primary_endpoint.is_empty()
      {
        return Err( crate::error::Error::ConfigurationError(
          "Primary endpoint cannot be empty".to_string()
        ) );
      }

      if config.backup_endpoints.is_empty()
      {
        return Err( crate::error::Error::ConfigurationError(
          "At least one backup endpoint is required for failover".to_string()
        ) );
      }

      if config.timeout.is_zero()
      {
        return Err( crate::error::Error::ConfigurationError(
          "Timeout cannot be zero".to_string()
        ) );
      }

      if config.max_retries == 0
      {
        return Err( crate::error::Error::ConfigurationError(
          "Max retries must be at least 1".to_string()
        ) );
      }

      Ok( () )
    }
  }

  impl FailoverConfig
  {
    /// Create a new failover config builder
    #[ inline ]
    #[ must_use ]
    pub fn builder() -> FailoverConfigBuilder
    {
      FailoverConfigBuilder::new()
    }
  }

  /// Available failover strategies
  #[ derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize ) ]
  pub enum FailoverStrategy
  {
    /// Try backup endpoints in priority order
    Priority,
    /// Round-robin through available endpoints
    RoundRobin,
  }

  /// Health status of an endpoint
  #[ derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize ) ]
  pub enum HealthStatus
  {
    /// Endpoint is healthy and responsive
    Healthy,
    /// Endpoint is unhealthy or unresponsive
    Unhealthy,
    /// Endpoint status is unknown
    Unknown,
  }

  /// Health information for a specific endpoint
  #[ derive( Debug, Clone ) ]
  pub struct EndpointHealth
  {
    /// The endpoint URL
    pub endpoint : String,
    /// Current health status
    pub status : HealthStatus,
    /// Last time this endpoint was checked
    pub last_check : SystemTime,
    /// Response time of last successful request
    pub response_time : Option< Duration >,
    /// Number of consecutive failures
    pub consecutive_failures : u32,
  }

  /// Result of checking endpoint health
  #[ derive( Debug, Clone ) ]
  pub struct HealthCheckResult
  {
    /// Whether the primary endpoint is healthy
    pub primary_healthy : bool,
    /// Whether backup endpoints are available
    pub backup_available : bool,
    /// Detailed health status for all endpoints
    pub endpoint_health : Vec< EndpointHealth >,
    /// Recommended next endpoint to try
    pub recommended_endpoint : Option< String >,
  }

  /// Metrics for failover operations
  #[ derive( Debug, Clone ) ]
  pub struct FailoverMetrics
  {
    /// Total number of configured endpoints
    pub total_endpoints : usize,
    /// Number of times failover has occurred
    pub failover_count : u64,
    /// Health status of all endpoints
    pub endpoint_health : Vec< EndpointHealth >,
    /// Current active endpoint
    pub active_endpoint : String,
  }

  /// Failover management interface
  #[ allow( missing_debug_implementations ) ] // Cannot derive Debug due to function pointers
  pub struct FailoverManager
  {
    client : crate::client::Client,
    config : FailoverConfig,
    metrics : Arc< Mutex< FailoverMetrics > >,
    round_robin_index : Arc< Mutex< usize > >,
    endpoint_health : Arc< Mutex< HashMap<  String, EndpointHealth  > > >,
  }

  impl FailoverManager
  {
    /// Create a new failover manager
    #[ inline ]
    #[ must_use ]
    pub fn new( client : crate::client::Client, config : FailoverConfig ) -> Self
    {
      let total_endpoints = 1 + config.backup_endpoints.len();
      let metrics = FailoverMetrics {
        total_endpoints,
        failover_count : 0,
        endpoint_health : Vec::new(),
        active_endpoint : config.primary_endpoint.clone(),
      };

      Self {
        client,
        config,
        metrics : Arc::new( Mutex::new( metrics ) ),
        round_robin_index : Arc::new( Mutex::new( 0 ) ),
        endpoint_health : Arc::new( Mutex::new( HashMap::new() ) ),
      }
    }

    /// Get the current failover configuration
    #[ inline ]
    #[ must_use ]
    pub fn current_config( &self ) -> &FailoverConfig
    {
      &self.config
    }

    /// Check the health of all configured endpoints
    ///
    /// # Errors
    ///
    /// Returns `Error` if health check operations fail due to:
    /// - Network connectivity issues
    /// - Endpoint timeout or unavailability
    /// - Configuration validation errors
    ///
    /// # Panics
    ///
    /// Panics if mutex locks are poisoned (rare runtime error).
    #[ inline ]
    pub async fn check_endpoint_health( &self ) -> Result< HealthCheckResult, crate::error::Error >
    {
      let mut endpoint_health = Vec::new();
      let mut backup_available = false;

      // Check primary endpoint
      let primary_health = self.check_single_endpoint( &self.config.primary_endpoint ).await;
      let primary_healthy = primary_health.status == HealthStatus::Healthy;
      endpoint_health.push( primary_health );

      // Check backup endpoints
      for backup in &self.config.backup_endpoints
      {
        let backup_health = self.check_single_endpoint( backup ).await;
        if backup_health.status == HealthStatus::Healthy
        {
          backup_available = true;
        }
        endpoint_health.push( backup_health );
      }

      // Update stored health information
      {
        let mut stored_health = self.endpoint_health.lock().unwrap();
        for health in &endpoint_health
        {
          stored_health.insert( health.endpoint.clone(), health.clone() );
        }
      }

      let recommended_endpoint = if !primary_healthy && backup_available
      {
        self.get_next_healthy_endpoint().ok()
      } else {
        None
      };

      Ok( HealthCheckResult {
        primary_healthy,
        backup_available,
        endpoint_health,
        recommended_endpoint,
      } )
    }

    /// Check health of a single endpoint
    async fn check_single_endpoint( &self, endpoint : &str ) -> EndpointHealth
    {
      let start_time = SystemTime::now();

      // Create HTTP client for health check
      let client = reqwest::Client::builder()
        .timeout( self.config.timeout )
        .build()
        .unwrap_or_default();

      // Perform HEAD request to check endpoint health
      let result = client.head( endpoint ).send().await;

      let ( status, response_time, consecutive_failures ) = match result
      {
        Ok( response ) => {
          if response.status().is_success() || response.status().is_redirection()
          {
            ( HealthStatus::Healthy, start_time.elapsed().ok(), 0 )
          } else {
            ( HealthStatus::Unhealthy, None, 1 )
          }
        },
        Err( _ ) => ( HealthStatus::Unhealthy, None, 1 ),
      };

      EndpointHealth {
        endpoint : endpoint.to_string(),
        status,
        last_check : start_time,
        response_time,
        consecutive_failures,
      }
    }

    /// Get the next endpoint to try based on strategy
    ///
    /// # Errors
    ///
    /// Returns `Error` if no backup endpoints are configured.
    ///
    /// # Panics
    ///
    /// Panics if mutex locks are poisoned (rare runtime error).
    #[ inline ]
    pub fn get_next_endpoint( &self ) -> Result< String, crate::error::Error >
    {
      match self.config.strategy
      {
        FailoverStrategy::Priority => {
          // Return first backup endpoint in priority order
          self.config.backup_endpoints.first()
            .cloned()
            .map_or_else(
              || Err( crate::error::Error::ConfigurationError(
                "No backup endpoints configured".to_string()
              ) ),
              Ok
            )
        },
        FailoverStrategy::RoundRobin => {
          let mut index = self.round_robin_index.lock().unwrap();
          let backup_count = self.config.backup_endpoints.len();

          if backup_count == 0
          {
            return Err( crate::error::Error::ConfigurationError(
              "No backup endpoints configured".to_string()
            ) );
          }

          let selected = &self.config.backup_endpoints[ *index % backup_count ];
          *index = ( *index + 1 ) % backup_count;

          Ok( selected.clone() )
        },
      }
    }

    /// Get the next healthy endpoint
    #[ inline ]
    fn get_next_healthy_endpoint( &self ) -> Result< String, crate::error::Error >
    {
      // For now, just use the first backup endpoint
      // In a full implementation, this would check health of all backups
      self.config.backup_endpoints.first()
        .cloned()
        .map_or_else(
          || Err( crate::error::Error::ConfigurationError(
            "No backup endpoints available".to_string()
          ) ),
          Ok
        )
    }

    /// Switch to backup endpoint explicitly
    ///
    /// # Errors
    ///
    /// Returns `Error` if:
    /// - No backup endpoints are available
    /// - Client creation fails with backup endpoint
    ///
    /// # Panics
    ///
    /// Panics if mutex locks are poisoned (rare runtime error).
    #[ inline ]
    pub fn switch_to_backup( &self ) -> Result< crate::client::Client, crate::error::Error >
    {
      let backup_endpoint = self.get_next_endpoint()?;

      // Create new client with backup endpoint
      // For now, we'll create a simplified client. In a full implementation,
      // we would extract the API key and other settings from the original client.
      let backup_client = crate::client::Client::builder()
        .api_key( std::env::var( "GEMINI_API_KEY" ).unwrap_or_else( |_| "test-key".to_string() ) )
        .base_url( backup_endpoint.clone() )
        .build()?;

      // Update metrics
      {
        let mut metrics = self.metrics.lock().unwrap();
        metrics.failover_count += 1;
        metrics.active_endpoint = backup_endpoint;
      }

      Ok( backup_client )
    }

    /// Execute a request with failover handling
    ///
    /// # Errors
    ///
    /// Returns `Error` if:
    /// - Both primary and backup endpoints fail
    /// - No backup endpoints are configured and primary fails
    /// - Client creation fails
    #[ inline ]
    pub async fn execute_with_failover< F, Fut, T >(
      &self,
      operation : F
    ) -> Result< T, crate::error::Error >
    where
      F: Fn( crate::client::Client ) -> Fut,
      Fut : Future< Output = Result< T, crate::error::Error > >,
    {
      // Try primary endpoint first
      if let Ok( result ) = operation( self.client.clone() ).await
      {
        Ok( result )
      } else {
        // Primary failed, try backup
        let backup_client = self.switch_to_backup()?;
        operation( backup_client ).await
      }
    }

    /// Get current failover metrics
    ///
    /// # Panics
    ///
    /// Panics if mutex locks are poisoned (rare runtime error).
    #[ inline ]
    #[ must_use ]
    pub fn get_metrics( &self ) -> FailoverMetrics
    {
      let mut metrics = self.metrics.lock().unwrap();

      // Update endpoint health in metrics
      let stored_health = self.endpoint_health.lock().unwrap();
      metrics.endpoint_health = stored_health.values().cloned().collect();

      metrics.clone()
    }
  }

  /// Failover builder for the client
  #[ derive( Debug ) ]
  pub struct FailoverBuilder
  {
    client : crate::client::Client,
  }

  impl FailoverBuilder
  {
    /// Create a new failover builder
    #[ inline ]
    #[ must_use ]
    pub fn new( client : crate::client::Client ) -> Self
    {
      Self { client }
    }

    /// Configure failover with the given configuration
    #[ inline ]
    #[ must_use ]
    pub fn configure( self, config : FailoverConfig ) -> FailoverManager
    {
      FailoverManager::new( self.client, config )
    }
  }
}

::mod_interface::mod_interface!
{
  exposed use private::FailoverConfig;
  exposed use private::FailoverConfigBuilder;
  exposed use private::FailoverStrategy;
  exposed use private::HealthStatus;
  exposed use private::EndpointHealth;
  exposed use private::HealthCheckResult;
  exposed use private::FailoverMetrics;
  exposed use private::FailoverManager;
  exposed use private::FailoverBuilder;
}