api_ollama 0.2.0

Ollama local LLM runtime API client for HTTP communication.
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
636
637
638
639
640
//! Health check types and implementation for monitoring endpoint availability.
//!
//! Provides health monitoring, status tracking, and background health checking
//! capabilities for Ollama endpoints.

#[ cfg( feature = "health_checks" ) ]
mod private
{
  use core::time::Duration;
  use std::sync::{ Arc, Mutex };
  use super::super::*;
  use error_tools::format_err;

  /// Health check strategy options
  #[ derive( Debug, Clone, PartialEq ) ]
  pub enum HealthCheckStrategy
  {
    /// Simple ping check
    Ping,
    /// Lightweight API call check
    ApiCall,
    /// Version endpoint check
    VersionCheck,
  }

  /// Configuration for health check behavior
  #[ derive( Debug, Clone ) ]
  pub struct HealthCheckConfig
  {
    /// Interval between health checks
    interval : Duration,
    /// Timeout for each health check
    timeout : Duration,
    /// Health check strategy to use
    strategy : HealthCheckStrategy,
    /// Number of consecutive failures before marking as unhealthy
    failure_threshold : u32,
    /// Number of consecutive successes required for recovery
    recovery_threshold : u32,
    /// Whether to integrate with circuit breaker
    circuit_breaker_integration : bool,
  }

  impl HealthCheckConfig
  {
    /// Create new health check configuration with defaults
    #[ inline ]
    #[ must_use ]
    pub fn new() -> Self
    {
      Self
      {
        interval : Duration::from_secs( 30 ),
        timeout : Duration::from_secs( 5 ),
        strategy : HealthCheckStrategy::Ping,
        failure_threshold : 3,
        recovery_threshold : 2,
        circuit_breaker_integration : false,
      }
    }

    /// Set health check interval
    #[ inline ]
    #[ must_use ]
    pub fn with_interval( mut self, interval : Duration ) -> Self
    {
      self.interval = interval;
      self
    }

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

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

    /// Set failure threshold
    #[ inline ]
    #[ must_use ]
    pub fn with_failure_threshold( mut self, threshold : u32 ) -> Self
    {
      self.failure_threshold = threshold;
      self
    }

    /// Set recovery threshold
    #[ inline ]
    #[ must_use ]
    pub fn with_recovery_threshold( mut self, threshold : u32 ) -> Self
    {
      self.recovery_threshold = threshold;
      self
    }

    /// Enable circuit breaker integration
    #[ inline ]
    #[ must_use ]
    pub fn with_circuit_breaker_integration( mut self, enabled : bool ) -> Self
    {
      self.circuit_breaker_integration = enabled;
      self
    }

    /// Get interval
    #[ inline ]
    #[ must_use ]
    pub fn interval( &self ) -> Duration
    {
      self.interval
    }

    /// Get timeout
    #[ inline ]
    #[ must_use ]
    pub fn timeout( &self ) -> Duration
    {
      self.timeout
    }

    /// Get strategy
    #[ inline ]
    #[ must_use ]
    pub fn strategy( &self ) -> &HealthCheckStrategy
    {
      &self.strategy
    }

    /// Get failure threshold
    #[ inline ]
    #[ must_use ]
    pub fn failure_threshold( &self ) -> u32
    {
      self.failure_threshold
    }

    /// Get recovery threshold
    #[ inline ]
    #[ must_use ]
    pub fn recovery_threshold( &self ) -> u32
    {
      self.recovery_threshold
    }

    /// Check if circuit breaker integration is enabled
    #[ inline ]
    #[ must_use ]
    pub fn circuit_breaker_integration( &self ) -> bool
    {
      self.circuit_breaker_integration
    }

    /// Validate configuration
    #[ inline ]
    pub fn validate( &self ) -> OllamaResult< () >
    {
      if self.interval < Duration::from_millis( 100 )
      {
        return Err( format_err!( "Health check interval must be at least 100ms" ) );
      }

      if self.timeout >= self.interval
      {
        return Err( format_err!( "Health check timeout must be less than interval" ) );
      }

      if self.failure_threshold == 0
      {
        return Err( format_err!( "Failure threshold must be greater than 0" ) );
      }

      if self.recovery_threshold == 0
      {
        return Err( format_err!( "Recovery threshold must be greater than 0" ) );
      }

      Ok( () )
    }
  }

  impl Default for HealthCheckConfig
  {
    #[ inline ]
    fn default() -> Self
    {
      Self::new()
    }
  }

  /// Health status information for an endpoint
  #[ derive( Debug, Clone ) ]
  pub struct HealthStatus
  {
    /// Overall health of the endpoint
    overall_health : EndpointHealth,
    /// Total health checks performed
    total_checks : u64,
    /// Number of successful checks
    successful_checks : u64,
    /// Number of failed checks
    failed_checks : u64,
    /// Response times for recent checks
    response_times : Vec< Duration >,
    /// Last check timestamp
    last_check_time : Option< std::time::Instant >,
    /// Whether circuit breaker is open
    circuit_breaker_open : bool,
    /// Consecutive failure count
    consecutive_failures : u32,
    /// Consecutive success count
    consecutive_successes : u32,
  }

  impl HealthStatus
  {
    /// Create new health status
    #[ inline ]
    #[ must_use ]
    pub fn new() -> Self
    {
      Self
      {
        overall_health : EndpointHealth::Unknown,
        total_checks : 0,
        successful_checks : 0,
        failed_checks : 0,
        response_times : Vec::new(),
        last_check_time : None,
        circuit_breaker_open : false,
        consecutive_failures : 0,
        consecutive_successes : 0,
      }
    }

    /// Get overall health
    #[ inline ]
    #[ must_use ]
    pub fn overall_health( &self ) -> EndpointHealth
    {
      self.overall_health.clone()
    }

    /// Get total checks performed
    #[ inline ]
    #[ must_use ]
    pub fn total_checks( &self ) -> u64
    {
      self.total_checks
    }

    /// Get successful checks count
    #[ inline ]
    #[ must_use ]
    pub fn successful_checks( &self ) -> u64
    {
      self.successful_checks
    }

    /// Get failed checks count
    #[ inline ]
    #[ must_use ]
    pub fn failed_checks( &self ) -> u64
    {
      self.failed_checks
    }

    /// Get response times
    #[ inline ]
    #[ must_use ]
    pub fn get_response_times( &self ) -> &Vec< Duration >
    {
      &self.response_times
    }

    /// Check if circuit breaker is open
    #[ inline ]
    #[ must_use ]
    pub fn circuit_breaker_open( &self ) -> bool
    {
      self.circuit_breaker_open
    }

    /// Record successful health check
    #[ inline ]
    pub fn record_success( &mut self, response_time : Duration )
    {
      self.total_checks += 1;
      self.successful_checks += 1;
      self.consecutive_failures = 0;
      self.consecutive_successes += 1;
      self.response_times.push( response_time );
      self.last_check_time = Some( std::time::Instant::now() );

      // Keep only last 10 response times
      if self.response_times.len() > 10
      {
        self.response_times.remove( 0 );
      }

      // Update health status based on recent performance
      if self.consecutive_successes >= 2
      {
        self.overall_health = EndpointHealth::Healthy;
        self.circuit_breaker_open = false;
      }
    }

    /// Record failed health check
    #[ inline ]
    pub fn record_failure( &mut self, failure_threshold : u32 )
    {
      self.total_checks += 1;
      self.failed_checks += 1;
      self.consecutive_successes = 0;
      self.consecutive_failures += 1;
      self.last_check_time = Some( std::time::Instant::now() );

      // Update health status based on consecutive failures
      if self.consecutive_failures >= failure_threshold
      {
        self.overall_health = EndpointHealth::Unhealthy;
      }
      else if self.consecutive_failures > 1
      {
        self.overall_health = EndpointHealth::Degraded;
      }
    }

    /// Mark circuit breaker as open
    #[ inline ]
    pub fn set_circuit_breaker_open( &mut self, open : bool )
    {
      self.circuit_breaker_open = open;
    }
  }

  impl Default for HealthStatus
  {
    #[ inline ]
    fn default() -> Self
    {
      Self::new()
    }
  }

  /// Health metrics for monitoring and reporting
  #[ derive( Debug, Clone ) ]
  pub struct HealthMetrics
  {
    /// Total health checks performed
    pub total_checks : u64,
    /// Average response time
    pub average_response_time : Option< Duration >,
    /// Uptime percentage
    pub uptime_percentage : f64,
    /// Last successful check time
    pub last_successful_check : Option< std::time::Instant >,
    /// Health check start time
    pub monitoring_start_time : std::time::Instant,
  }

  impl HealthMetrics
  {
    /// Create new health metrics
    #[ inline ]
    #[ must_use ]
    pub fn new() -> Self
    {
      Self
      {
        total_checks : 0,
        average_response_time : None,
        uptime_percentage : 0.0,
        last_successful_check : None,
        monitoring_start_time : std::time::Instant::now(),
      }
    }
  }

  impl Default for HealthMetrics
  {
    #[ inline ]
    fn default() -> Self
    {
      Self::new()
    }
  }

  /// Health check manager for background monitoring
  #[ derive( Debug ) ]
  pub struct HealthCheckManager
  {
    /// Health check configuration
    config : HealthCheckConfig,
    /// Current health status
    status : Arc< Mutex< HealthStatus > >,
    /// Health metrics
    metrics : Arc< Mutex< HealthMetrics > >,
    /// Background task handle
    task_handle : Option< tokio::task::JoinHandle< () > >,
    /// Shutdown signal sender
    shutdown_tx : Option< tokio::sync::oneshot::Sender< () > >,
    /// Endpoint URL for health checks
    endpoint_url : String,
    /// HTTP client for health checks
    client : reqwest::Client,
    /// Simulated failure flag for testing
    simulate_failure : Arc< core::sync::atomic::AtomicBool >,
  }

  impl HealthCheckManager
  {
    /// Create new health check manager
    #[ inline ]
    #[ must_use ]
    pub fn new( endpoint_url : String, config : HealthCheckConfig ) -> OllamaResult< Self >
    {
      config.validate()?;

      let client = reqwest::Client::builder()
        .timeout( config.timeout )
        .build()
        .map_err( | e | format_err!( "Failed to create HTTP client : {}", e ) )?;

      Ok( Self
      {
        config,
        status : Arc::new( Mutex::new( HealthStatus::new() ) ),
        metrics : Arc::new( Mutex::new( HealthMetrics::new() ) ),
        task_handle : None,
        shutdown_tx : None,
        endpoint_url,
        client,
        simulate_failure : Arc::new( std::sync::atomic::AtomicBool::new( false ) ),
      })
    }

    /// Start background health monitoring
    #[ inline ]
    pub async fn start_monitoring( &mut self )
    {
      if self.task_handle.is_some()
      {
        return; // Already running
      }

      let ( shutdown_tx, mut shutdown_rx ) = tokio::sync::oneshot::channel();
      self.shutdown_tx = Some( shutdown_tx );

      let status = self.status.clone();
      let metrics = self.metrics.clone();
      let config = self.config.clone();
      let endpoint_url = self.endpoint_url.clone();
      let client = self.client.clone();
      let simulate_failure = self.simulate_failure.clone();

      let handle = tokio::spawn( async move
      {
        let mut interval = tokio::time::interval( config.interval );

        loop
        {
          tokio ::select! {
            _ = interval.tick()
            =>
            {
              let start_time = std::time::Instant::now();
              let success = if simulate_failure.load( std::sync::atomic::Ordering::Relaxed )
              {
                false
              }
              else
              {
                Self::perform_health_check( &client, &endpoint_url, &config ).await
              };

              let response_time = start_time.elapsed();

              // Update status and metrics
              if let Ok( mut status ) = status.lock()
              {
                if success
                {
                  status.record_success( response_time );
                }
                else
                {
                  status.record_failure( config.failure_threshold );

                  // Trigger circuit breaker if integration is enabled and health is now unhealthy
                  if config.circuit_breaker_integration() && status.overall_health() == EndpointHealth::Unhealthy
                  {
                    status.set_circuit_breaker_open( true );
                  }
                }
              }

              if let Ok( mut metrics ) = metrics.lock()
              {
                metrics.total_checks += 1;
                if success
                {
                  metrics.last_successful_check = Some( start_time );
                }

                // Calculate uptime percentage
                let _total_duration = start_time.duration_since( metrics.monitoring_start_time );
                if let Ok( status ) = status.lock()
                {
                  if status.total_checks() > 0
                  {
                    metrics.uptime_percentage = ( status.successful_checks() as f64 / status.total_checks() as f64 ) * 100.0;
                  }

                  // Calculate average response time
                  let response_times = status.get_response_times();
                  if !response_times.is_empty()
                  {
                    let total : Duration = response_times.iter().sum();
                    metrics.average_response_time = Some( total / response_times.len() as u32 );
                  }
                }
              }
            }
            _ = &mut shutdown_rx
            =>
            {
              break;
            }
          }
        }
      });

      self.task_handle = Some( handle );
    }

    /// Stop background health monitoring
    #[ inline ]
    pub async fn stop_monitoring( &mut self )
    {
      if let Some( shutdown_tx ) = self.shutdown_tx.take()
      {
        let _ = shutdown_tx.send( () );
      }

      if let Some( handle ) = self.task_handle.take()
      {
        let _ = handle.await;
      }
    }

    /// Get current health status
    #[ inline ]
    #[ must_use ]
    pub fn get_health_status( &self ) -> HealthStatus
    {
      self.status.lock().map( |status| status.clone() ).unwrap_or_default()
    }

    /// Get health metrics
    #[ inline ]
    #[ must_use ]
    pub fn get_health_metrics( &self ) -> HealthMetrics
    {
      self.metrics.lock().map( |metrics| metrics.clone() ).unwrap_or_default()
    }

    /// Simulate endpoint failure for testing
    #[ inline ]
    pub fn simulate_endpoint_failure( &self )
    {
      self.simulate_failure.store( true, std::sync::atomic::Ordering::Relaxed );
    }

    /// Restore endpoint for testing
    #[ inline ]
    pub fn restore_endpoint( &self )
    {
      self.simulate_failure.store( false, std::sync::atomic::Ordering::Relaxed );
    }

    /// Perform a single health check
    async fn perform_health_check( client : &reqwest::Client, endpoint_url : &str, config : &HealthCheckConfig ) -> bool
    {
      match config.strategy
      {
        HealthCheckStrategy::Ping =>
        {
          // Simple ping - just try to connect
          let url = format!( "{endpoint_url}/api/tags" );
          client.get( &url ).send().await.is_ok()
        },
        HealthCheckStrategy::ApiCall =>
        {
          // Try a lightweight API call
          let url = format!( "{endpoint_url}/api/tags" );
          match client.get( &url ).send().await
          {
            Ok( response ) => response.status().is_success(),
            Err( _ ) => false,
          }
        },
        HealthCheckStrategy::VersionCheck =>
        {
          // Try to get version information
          let url = format!( "{endpoint_url}/api/version" );
          match client.get( &url ).send().await
          {
            Ok( response ) => response.status().is_success(),
            Err( _ ) => false,
          }
        },
      }
    }
  }
}

#[ cfg( feature = "health_checks" ) ]
crate ::mod_interface!
{
  exposed use
  {
    HealthCheckStrategy,
    HealthCheckConfig,
    HealthStatus,
    HealthMetrics,
  };
  orphan use private::HealthCheckManager;
}