api_claude 0.4.0

Claude API for accessing Anthropic's 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
//! Health Check Module
//!
//! This module provides stateless health monitoring utilities for Anthropic Claude API endpoints.
//! Following the "Thin Client, Rich API" principle, this module offers utilities for
//! one-time health checks without maintaining client-side state or automatic behaviors.
//!
//! # Key Principles
//!
//! - **Stateless Operation**: Each health check is independent
//! - **Explicit Invocation**: No automatic background checks
//! - **Transparent Results**: Clear visibility into endpoint health
//! - **Configurable Thresholds**: Developer controls what "healthy" means

mod private
{
  use std::
  {
    time::{ Duration, Instant, SystemTime },
  };
  use serde::{ Deserialize, Serialize };

  /// Health status for an endpoint
  #[ derive( Debug, Clone, PartialEq, Serialize, Deserialize ) ]
  pub enum EndpointHealthStatus
  {
    /// Endpoint is healthy and responding normally
    Healthy,
    /// Endpoint is degraded but functional (slow response)
    Degraded,
    /// Endpoint is unhealthy and not responding
    Unhealthy,
  }

  /// Health check strategy
  #[ derive( Debug, Clone, PartialEq, Serialize, Deserialize ) ]
  pub enum HealthCheckStrategy
  {
    /// Simple connectivity check (minimal overhead)
    Ping,
    /// Lightweight API call (more accurate but higher overhead)
    LightweightApi,
  }

  /// Health check result for a single endpoint
  #[ derive( Debug, Clone, Serialize, Deserialize ) ]
  pub struct HealthCheckResult
  {
    /// The endpoint URL that was checked
    pub endpoint_url : String,
    /// Health status of the endpoint
    pub status : EndpointHealthStatus,
    /// Response time in milliseconds
    pub response_time_ms : u64,
    /// Optional error message if unhealthy
    pub error_message : Option< String >,
    /// Timestamp when check was performed
    pub timestamp : SystemTime,
  }

  impl HealthCheckResult
  {
    /// Check if the endpoint is healthy
    #[ inline ]
    #[ must_use ]
    pub fn is_healthy( &self ) -> bool
    {
      matches!( self.status, EndpointHealthStatus::Healthy )
    }

    /// Check if the endpoint is available (healthy or degraded)
    #[ inline ]
    #[ must_use ]
    pub fn is_available( &self ) -> bool
    {
      matches!( self.status, EndpointHealthStatus::Healthy | EndpointHealthStatus::Degraded )
    }

    /// Get response time as Duration
    #[ inline ]
    #[ must_use ]
    pub fn response_time( &self ) -> Duration
    {
      Duration::from_millis( self.response_time_ms )
    }
  }

  /// Configuration for health checks
  #[ derive( Debug, Clone, PartialEq, Serialize, Deserialize ) ]
  pub struct HealthCheckConfig
  {
    /// Timeout for health check requests (in milliseconds)
    pub timeout_ms : u64,
    /// Strategy to use for health checks
    pub strategy : HealthCheckStrategy,
    /// Response time threshold for degraded status (in milliseconds)
    pub degraded_threshold_ms : u64,
    /// Response time threshold for unhealthy status (in milliseconds)
    pub unhealthy_threshold_ms : u64,
  }

  impl Default for HealthCheckConfig
  {
    #[ inline ]
    fn default() -> Self
    {
      Self
      {
        timeout_ms : 5000,
        strategy : HealthCheckStrategy::LightweightApi,
        degraded_threshold_ms : 1000,
        unhealthy_threshold_ms : 5000,
      }
    }
  }

  impl HealthCheckConfig
  {
    /// Create a new health check configuration with defaults
    #[ inline ]
    #[ must_use ]
    pub fn new() -> Self
    {
      Self::default()
    }

    /// Set the timeout for health check requests
    #[ inline ]
    #[ must_use ]
    pub fn with_timeout_ms( mut self, timeout_ms : u64 ) -> Self
    {
      self.timeout_ms = timeout_ms;
      self
    }

    /// Set the health check strategy
    #[ inline ]
    #[ must_use ]
    pub fn with_strategy( mut self, strategy : HealthCheckStrategy ) -> Self
    {
      self.strategy = strategy;
      self
    }

    /// Set the degraded threshold
    #[ inline ]
    #[ must_use ]
    pub fn with_degraded_threshold_ms( mut self, threshold_ms : u64 ) -> Self
    {
      self.degraded_threshold_ms = threshold_ms;
      self
    }

    /// Set the unhealthy threshold
    #[ inline ]
    #[ must_use ]
    pub fn with_unhealthy_threshold_ms( mut self, threshold_ms : u64 ) -> Self
    {
      self.unhealthy_threshold_ms = threshold_ms;
      self
    }

    /// Set timeout as Duration (convenience method)
    #[ inline ]
    #[ must_use ]
    #[ allow( clippy::cast_possible_truncation ) ]
    pub fn with_timeout( self, timeout : core::time::Duration ) -> Self
    {
      self.with_timeout_ms( timeout.as_millis() as u64 )
    }

    /// Set interval (same as timeout for health checks)
    #[ inline ]
    #[ must_use ]
    pub fn with_interval( self, interval : core::time::Duration ) -> Self
    {
      self.with_timeout( interval )
    }

    /// Validate the configuration
    #[ inline ]
    #[ must_use ]
    pub fn is_valid( &self ) -> bool
    {
      self.timeout_ms > 0
      && self.degraded_threshold_ms > 0
      && self.unhealthy_threshold_ms >= self.degraded_threshold_ms
      && self.timeout_ms >= self.unhealthy_threshold_ms
    }
  }

  /// Stateless health check utilities
  ///
  /// Provides one-time health check operations without maintaining state.
  /// Each check is independent and returns results immediately.
  #[ derive( Debug ) ]
  pub struct HealthChecker;

  impl HealthChecker
  {
    /// Perform a single health check on the given endpoint
    ///
    /// This is a stateless operation that returns results immediately.
    /// No state is maintained between checks.
    ///
    /// # Arguments
    ///
    /// * `endpoint_url` - The base URL of the endpoint to check
    /// * `config` - Health check configuration
    ///
    /// # Example
    ///
    /// ```ignore
    /// use api_claude::{ HealthChecker, HealthCheckConfig, HealthCheckStrategy };
    ///
    /// let config = HealthCheckConfig::new()
    ///   .with_strategy( HealthCheckStrategy::Ping )
    ///   .with_timeout_ms( 3000 );
    ///
    /// let result = HealthChecker::check_endpoint(
    ///   "https://api.anthropic.com",
    ///   &config
    /// ).await;
    ///
    /// if result.is_healthy() {
    ///   println!( "Endpoint is healthy!" );
    /// }
    /// ```
    pub async fn check_endpoint(
      endpoint_url : &str,
      config : &HealthCheckConfig
    ) -> HealthCheckResult
    {
      let start_time = Instant::now();

      let ( status, error_message ) = match config.strategy
      {
        HealthCheckStrategy::Ping => Self::ping_check( endpoint_url, config ).await,
        HealthCheckStrategy::LightweightApi => Self::lightweight_api_check( endpoint_url, config ).await,
      };

      let response_time_ms = u64::try_from( start_time.elapsed().as_millis() ).unwrap_or( u64::MAX );

      // Determine status based on response time if initially healthy
      let final_status = match status
      {
        EndpointHealthStatus::Healthy if response_time_ms >= config.unhealthy_threshold_ms => EndpointHealthStatus::Unhealthy,
        EndpointHealthStatus::Healthy if response_time_ms >= config.degraded_threshold_ms => EndpointHealthStatus::Degraded,
        other => other,
      };

      HealthCheckResult
      {
        endpoint_url : endpoint_url.to_string(),
        status : final_status,
        response_time_ms,
        error_message,
        timestamp : SystemTime::now(),
      }
    }

    /// Perform ping-style connectivity check
    ///
    /// This is a lightweight check that verifies basic connectivity.
    /// For Anthropic API, this performs a minimal HTTP request.
    async fn ping_check(
      endpoint_url : &str,
      config : &HealthCheckConfig
    ) -> ( EndpointHealthStatus, Option< String > )
    {
      // Create a simple HTTP client for connectivity check
      let timeout = Duration::from_millis( config.timeout_ms );
      let client = match reqwest::Client::builder()
        .timeout( timeout )
        .build()
      {
        Ok( c ) => c,
        Err( e ) => return ( EndpointHealthStatus::Unhealthy, Some( format!( "Failed to create client : {e}" ) ) ),
      };

      // Try to connect to the endpoint (HEAD request is most lightweight)
      match client.head( endpoint_url ).send().await
      {
        Ok( response ) if response.status().is_success() || response.status().as_u16() == 405 =>
        {
          // 405 Method Not Allowed is ok for HEAD requests - means endpoint is up
          ( EndpointHealthStatus::Healthy, None )
        },
        Ok( response ) =>
        {
          ( EndpointHealthStatus::Unhealthy, Some( format!( "HTTP {}", response.status() ) ) )
        },
        Err( e ) if e.is_timeout() =>
        {
          ( EndpointHealthStatus::Unhealthy, Some( "Request timeout".to_string() ) )
        },
        Err( e ) if e.is_connect() =>
        {
          ( EndpointHealthStatus::Unhealthy, Some( "Connection failed".to_string() ) )
        },
        Err( e ) =>
        {
          ( EndpointHealthStatus::Unhealthy, Some( format!( "Request failed : {e}" ) ) )
        },
      }
    }

    /// Perform lightweight API call health check
    ///
    /// This makes an actual API call to verify the endpoint is functional.
    /// More accurate than ping but higher overhead.
    async fn lightweight_api_check(
      endpoint_url : &str,
      config : &HealthCheckConfig
    ) -> ( EndpointHealthStatus, Option< String > )
    {
      // For Anthropic API, we don't have a dedicated health endpoint
      // We'll use a connectivity check similar to ping but with API-specific validation
      let timeout = Duration::from_millis( config.timeout_ms );
      let client = match reqwest::Client::builder()
        .timeout( timeout )
        .build()
      {
        Ok( c ) => c,
        Err( e ) => return ( EndpointHealthStatus::Unhealthy, Some( format!( "Failed to create client : {e}" ) ) ),
      };

      // Try OPTIONS request to check if endpoint is responding
      match client.request( reqwest::Method::OPTIONS, endpoint_url ).send().await
      {
        Ok( response ) if response.status().is_success() || response.status().as_u16() == 405 || response.status().as_u16() == 404 =>
        {
          // 404 or 405 on OPTIONS is ok - means server is responding
          ( EndpointHealthStatus::Healthy, None )
        },
        Ok( response ) if response.status().is_server_error() =>
        {
          ( EndpointHealthStatus::Unhealthy, Some( format!( "Server error : {}", response.status() ) ) )
        },
        Ok( response ) =>
        {
          // Other status codes might indicate issues but server is responding
          ( EndpointHealthStatus::Degraded, Some( format!( "HTTP {}", response.status() ) ) )
        },
        Err( e ) if e.is_timeout() =>
        {
          ( EndpointHealthStatus::Unhealthy, Some( "Request timeout".to_string() ) )
        },
        Err( e ) if e.is_connect() =>
        {
          ( EndpointHealthStatus::Unhealthy, Some( "Connection failed".to_string() ) )
        },
        Err( e ) =>
        {
          ( EndpointHealthStatus::Unhealthy, Some( format!( "Request failed : {e}" ) ) )
        },
      }
    }

    /// Check multiple endpoints concurrently
    ///
    /// Returns results for all endpoints. Useful for failover scenarios
    /// where you need to check multiple backup endpoints.
    pub async fn check_multiple_endpoints(
      endpoints : &[ &str ],
      config : &HealthCheckConfig
    ) -> Vec< HealthCheckResult >
    {
      let mut handles = Vec::new();

      for endpoint in endpoints
      {
        let endpoint = ( *endpoint ).to_string();
        let config = config.clone();
        let handle = tokio::spawn( async move
        {
          Self::check_endpoint( &endpoint, &config ).await
        });
        handles.push( handle );
      }

      let mut results = Vec::new();
      for handle in handles
      {
        if let Ok( result ) = handle.await
        {
          results.push( result );
        }
      }

      results
    }
  }

  /// Health metrics aggregator for multiple check results
  #[ derive( Debug, Clone, Serialize, Deserialize ) ]
  pub struct HealthMetrics
  {
    /// Total number of endpoints checked
    pub total_endpoints : usize,
    /// Number of healthy endpoints
    pub healthy_count : usize,
    /// Number of degraded endpoints
    pub degraded_count : usize,
    /// Number of unhealthy endpoints
    pub unhealthy_count : usize,
    /// Average response time across all checks
    pub average_response_time_ms : u64,
    /// Minimum response time
    pub min_response_time_ms : u64,
    /// Maximum response time
    pub max_response_time_ms : u64,
  }

  impl HealthMetrics
  {
    /// Create health metrics from a collection of health check results
    #[ must_use ]
    pub fn from_results( results : &[ HealthCheckResult ] ) -> Self
    {
      if results.is_empty()
      {
        return Self
        {
          total_endpoints : 0,
          healthy_count : 0,
          degraded_count : 0,
          unhealthy_count : 0,
          average_response_time_ms : 0,
          min_response_time_ms : 0,
          max_response_time_ms : 0,
        };
      }

      let total_endpoints = results.len();
      let healthy_count = results.iter().filter( | r | matches!( r.status, EndpointHealthStatus::Healthy ) ).count();
      let degraded_count = results.iter().filter( | r | matches!( r.status, EndpointHealthStatus::Degraded ) ).count();
      let unhealthy_count = results.iter().filter( | r | matches!( r.status, EndpointHealthStatus::Unhealthy ) ).count();

      let response_times : Vec< u64 > = results.iter().map( | r | r.response_time_ms ).collect();
      let total_response_time : u64 = response_times.iter().sum();
      let average_response_time_ms = total_response_time / total_endpoints as u64;
      let min_response_time_ms = *response_times.iter().min().unwrap_or( &0 );
      let max_response_time_ms = *response_times.iter().max().unwrap_or( &0 );

      Self
      {
        total_endpoints,
        healthy_count,
        degraded_count,
        unhealthy_count,
        average_response_time_ms,
        min_response_time_ms,
        max_response_time_ms,
      }
    }

    /// Get the percentage of healthy endpoints
    #[ inline ]
    #[ must_use ]
    pub fn healthy_percentage( &self ) -> f64
    {
      if self.total_endpoints == 0
      {
        0.0
      }
      else
      {
        ( self.healthy_count as f64 / self.total_endpoints as f64 ) * 100.0
      }
    }

    /// Get the percentage of available endpoints (healthy + degraded)
    #[ inline ]
    #[ must_use ]
    pub fn available_percentage( &self ) -> f64
    {
      if self.total_endpoints == 0
      {
        0.0
      }
      else
      {
        ( ( self.healthy_count + self.degraded_count ) as f64 / self.total_endpoints as f64 ) * 100.0
      }
    }
  }
}

crate::mod_interface!
{
  exposed use private::EndpointHealthStatus;
  exposed use private::HealthCheckStrategy;
  exposed use private::HealthCheckResult;
  exposed use private::HealthCheckConfig;
  exposed use private::HealthChecker;
  exposed use private::HealthMetrics;
}