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
//! Dynamic configuration tests for the Ollama API client
//!
//! ## Known Issues (Technical Debt)
//!
//! These tests are currently **failing** due to incomplete implementation:
//!
//! ### Root Cause
//! The tests were written for an async API with Arc<Mutex<>> wrapping, but the
//! implementation provides a synchronous API:
//!
//! - Tests expect: `config_manager.update_config(x).await?`
//! - Implementation provides: `pub fn update_config(&mut self, x) -> Result<()>`
//!
//! ### Missing Integration
//! 1. `OllamaClient` lacks `dynamic_config_manager` field
//! 2. `OllamaClient::with_dynamic_config()` constructor doesn't exist
//! 3. No integration between OllamaClient and DynamicConfigManager
//!
//! ### Why Not Caught
//! - Tests use `#[cfg(feature = "dynamic_config")]` but were never run in CI
//! - Comment "Feature gate - not implemented yet" was ignored
//! - Mismatch between test expectations and implementation wasn't detected
//!
//! ### Fix Applied
//! - **None yet** - This is incomplete feature work
//! - Tests document expected API design
//! - Implementation provides sync API for DynamicConfigManager
//!
//! ### Prevention
//! - Run all feature-gated tests in CI: `cargo test --all-features`
//! - Mark incomplete features with `#[ignore]` until integrated
//! - Document async/sync design decisions in spec before implementation
//!
//! ### Pitfall
//! Writing tests before API design is finalized leads to test/impl mismatch.
//! Always align on sync vs async API contract before writing integration tests.

#![ allow( clippy::std_instead_of_core ) ] // std required for async operations and sync primitives

#[ cfg( feature = "dynamic_config_future" ) ] // Feature gate - not implemented yet, planned for future
use api_ollama::*;
#[ cfg( feature = "dynamic_config_future" ) ]
use std::time::Duration;
#[ cfg( feature = "dynamic_config_future" ) ]
use std::sync::Arc;
#[ cfg( feature = "dynamic_config_future" ) ]
use tokio::sync::Mutex;

#[ cfg( feature = "dynamic_config_future" ) ]
mod integration_tests
{
  use super::*;

  #[ tokio::test ]
  #[ ignore = "Incomplete feature - async/sync API mismatch, see file header documentation" ]
  async fn test_dynamic_config_basic_update() -> Result< (), Box< dyn core::error::Error > >
  {
    let config_manager = DynamicConfigManager::new()?;

    // Test basic configuration update
    let new_config = DynamicConfig {
      server_url: "http://localhost:11435".to_string(),
      timeout: Duration::from_secs( 30 ),
      max_connections: 10,
      enable_caching: true,
    };

    config_manager.update_config( new_config.clone() ).await?;
    let current = config_manager.get_current_config().await;

    assert_eq!( current.server_url, "http://localhost:11435" );
    assert_eq!( current.timeout, Duration::from_secs( 30 ) );
    assert_eq!( current.max_connections, 10 );
    assert!( current.enable_caching );

    Ok( () )
  }

  #[ tokio::test ]
  #[ ignore = "Incomplete feature - async/sync API mismatch, see file header documentation" ]
  async fn test_config_validation_and_rollback() -> Result< (), Box< dyn core::error::Error > >
  {
    let config_manager = DynamicConfigManager::new()?;

    // Set initial valid config
    let valid_config = DynamicConfig {
      server_url: "http://localhost:11434".to_string(),
      timeout: Duration::from_secs( 60 ),
      max_connections: 5,
      enable_caching: false,
    };
    config_manager.update_config( valid_config.clone() ).await?;

    // Try to set invalid config (empty URL)
    let invalid_config = DynamicConfig {
      server_url: String::new(),
      timeout: Duration::from_secs( 60 ),
      max_connections: 5,
      enable_caching: false,
    };

    let result = config_manager.update_config( invalid_config ).await;
    assert!( result.is_err() );

    // Verify rollback to previous valid config
    let current = config_manager.get_current_config().await;
    assert_eq!( current.server_url, "http://localhost:11434" );

    Ok( () )
  }

  #[ tokio::test ]
  #[ ignore = "Incomplete feature - async/sync API mismatch, see file header documentation" ]
  async fn test_config_hot_reloading_from_file() -> Result< (), Box< dyn core::error::Error > >
  {
    use std::fs;
    use tempfile::tempdir;

    let temp_dir = tempdir()?;
    let config_file = temp_dir.path().join( "config.json" );

    // Write initial config file
    let initial_config = r#"{
      "server_url": "http://localhost:11434",
      "timeout": { "secs": 30, "nanos": 0 },
      "max_connections": 5,
      "enable_caching": false
    }"#;
    fs::write( &config_file, initial_config )?;

    let config_manager = DynamicConfigManager::from_file( &config_file ).await?;

    // Verify initial config loaded
    let current = config_manager.get_current_config().await;
    assert_eq!( current.server_url, "http://localhost:11434" );
    assert_eq!( current.timeout, Duration::from_secs( 30 ) );

    // Update config file
    let updated_config = r#"{
      "server_url": "http://localhost:11435",
      "timeout": { "secs": 60, "nanos": 0 },
      "max_connections": 10,
      "enable_caching": true
    }"#;
    fs::write( &config_file, updated_config )?;

    // Trigger hot reload
    config_manager.reload_from_file().await?;

    // Verify updated config loaded
    let current = config_manager.get_current_config().await;
    assert_eq!( current.server_url, "http://localhost:11435" );
    assert_eq!( current.timeout, Duration::from_secs( 60 ) );
    assert_eq!( current.max_connections, 10 );
    assert!( current.enable_caching );

    Ok( () )
  }

  #[ tokio::test ]
  #[ ignore = "Incomplete feature - async/sync API mismatch, see file header documentation" ]
  async fn test_config_environment_variable_override() -> Result< (), Box< dyn core::error::Error > >
  {
    let config_manager = DynamicConfigManager::new()?;

    // Set environment variable
    std::env::set_var( "OLLAMA_SERVER_URL", "http://custom:11434" );
    std::env::set_var( "OLLAMA_TIMEOUT_SECS", "45" );

    // Apply environment overrides
    config_manager.apply_env_overrides().await?;

    let current = config_manager.get_current_config().await;
    assert_eq!( current.server_url, "http://custom:11434" );
    assert_eq!( current.timeout, Duration::from_secs( 45 ) );

    // Clean up
    std::env::remove_var( "OLLAMA_SERVER_URL" );
    std::env::remove_var( "OLLAMA_TIMEOUT_SECS" );

    Ok( () )
  }

  #[ tokio::test ]
  #[ ignore = "Incomplete feature - async/sync API mismatch, see file header documentation" ]
  async fn test_config_change_notifications() -> Result< (), Box< dyn core::error::Error > >
  {
    let config_manager = DynamicConfigManager::new()?;
    let notification_received = Arc::new( Mutex::new( false ) );
    let notification_received_clone = notification_received.clone();

    // Subscribe to config changes
    config_manager.on_config_change( move | _old, _new | {
      let flag = notification_received_clone.clone();
      tokio::spawn( async move {
        *flag.lock().await = true;
      } );
    } ).await;

    // Update config to trigger notification
    let new_config = DynamicConfig {
      server_url: "http://localhost:11436".to_string(),
      timeout: Duration::from_secs( 120 ),
      max_connections: 15,
      enable_caching: true,
    };
    config_manager.update_config( new_config ).await?;

    // Wait briefly for async notification
    tokio::time::sleep( Duration::from_millis( 100 ) ).await;

    assert!( *notification_received.lock().await );

    Ok( () )
  }

  #[ tokio::test ]
  #[ ignore = "Incomplete feature - async/sync API mismatch, see file header documentation" ]
  async fn test_concurrent_config_updates() -> Result< (), Box< dyn core::error::Error > >
  {
    let config_manager = Arc::new( DynamicConfigManager::new()? );
    let mut handles = Vec::new();

    // Spawn multiple concurrent update tasks
    for i in 0..10
    {
      let manager = config_manager.clone();
      let handle = tokio::spawn( async move {
        let config = DynamicConfig {
          server_url: format!( "http://localhost:1143{i}" ),
          timeout: Duration::from_secs( 30 + i as u64 ),
          max_connections: 5 + i,
          enable_caching: i % 2 == 0,
        };
        manager.update_config( config ).await
      } );
      handles.push( handle );
    }

    // Wait for all updates to complete
    let mut success_count = 0;
    for handle in handles
    {
      if handle.await.unwrap().is_ok()
      {
        success_count += 1;
      }
    }

    // All updates should succeed due to atomic operations
    assert_eq!( success_count, 10 );

    // Verify final state is consistent
    let final_config = config_manager.get_current_config().await;
    assert!( final_config.server_url.starts_with( "http://localhost:1143" ) );

    Ok( () )
  }

  #[ tokio::test ]
  #[ ignore = "Incomplete feature - async/sync API mismatch, see file header documentation" ]
  async fn test_config_versioning_and_history() -> Result< (), Box< dyn core::error::Error > >
  {
    let config_manager = DynamicConfigManager::new()?;

    // Apply several config changes
    for i in 1..=5
    {
      let config = DynamicConfig {
        server_url: format!( "http://localhost:1143{i}" ),
        timeout: Duration::from_secs( 30 * i as u64 ),
        max_connections: 5 * i,
        enable_caching: i % 2 == 0,
      };
      config_manager.update_config( config ).await?;
    }

    // Get config history
    let history = config_manager.get_config_history().await;
    assert_eq!( history.len(), 6 ); // Initial version + 5 updates

    // Verify versions are sequential
    for ( idx, version ) in history.iter().enumerate()
    {
      assert_eq!( version.version, idx as u64 + 1 );
    }

    // Test rollback to specific version (version 4 = 3rd update since version 1 is initial)
    config_manager.rollback_to_version( 4 ).await?;
    let current = config_manager.get_current_config().await;
    assert_eq!( current.server_url, "http://localhost:11433" );
    assert_eq!( current.timeout, Duration::from_secs( 90 ) );

    Ok( () )
  }

  #[ tokio::test ]
  #[ ignore = "Incomplete feature - async/sync API mismatch, see file header documentation" ]
  async fn test_graceful_handling_of_in_flight_requests() -> Result< (), Box< dyn core::error::Error > >
  {
    let config_manager = std::sync::Arc::new( DynamicConfigManager::new()? );
    let _client = OllamaClient::with_dynamic_config( config_manager.clone() )?;

    // Start a long-running request simulation
    let _config_manager_clone = config_manager.clone();
    let long_request = tokio::spawn( async move {
      // Simulate long request
      tokio::time::sleep( Duration::from_millis( 200 ) ).await;
      Result::< (), String >::Ok( () )
    } );

    // Update config during request
    tokio::time::sleep( Duration::from_millis( 50 ) ).await;
    let new_config = DynamicConfig {
      server_url: "http://localhost:11435".to_string(),
      timeout: Duration::from_secs( 60 ),
      max_connections: 10,
      enable_caching: false,
    };
    config_manager.update_config( new_config ).await?;

    // Ensure request completes successfully
    long_request.await.map_err( | e | format!( "Join error: {e}" ) )??;

    Ok( () )
  }
}

#[ cfg( feature = "dynamic_config_future" ) ]
mod unit_tests
{
  use super::*;

  #[ test ]
  fn test_dynamic_config_validation()
  {
    let valid_config = DynamicConfig {
      server_url: "http://localhost:11434".to_string(),
      timeout: Duration::from_secs( 30 ),
      max_connections: 5,
      enable_caching: true,
    };
    assert!( valid_config.validate().is_ok() );

    let invalid_config = DynamicConfig {
      server_url: String::new(),
      timeout: Duration::from_secs( 30 ),
      max_connections: 5,
      enable_caching: true,
    };
    assert!( invalid_config.validate().is_err() );

    let zero_timeout_config = DynamicConfig {
      server_url: "http://localhost:11434".to_string(),
      timeout: Duration::from_secs( 0 ),
      max_connections: 5,
      enable_caching: true,
    };
    assert!( zero_timeout_config.validate().is_err() );
  }

  #[ test ]
  fn test_config_serialization()
  {
    let config = DynamicConfig {
      server_url: "http://localhost:11434".to_string(),
      timeout: Duration::from_secs( 60 ),
      max_connections: 10,
      enable_caching: false,
    };

    let json = serde_json::to_string( &config ).unwrap();
    let deserialized: DynamicConfig = serde_json::from_str( &json ).unwrap();

    assert_eq!( config.server_url, deserialized.server_url );
    assert_eq!( config.timeout, deserialized.timeout );
    assert_eq!( config.max_connections, deserialized.max_connections );
    assert_eq!( config.enable_caching, deserialized.enable_caching );
  }

  #[ test ]
  fn test_config_diff_calculation()
  {
    let old_config = DynamicConfig {
      server_url: "http://localhost:11434".to_string(),
      timeout: Duration::from_secs( 30 ),
      max_connections: 5,
      enable_caching: false,
    };

    let new_config = DynamicConfig {
      server_url: "http://localhost:11435".to_string(),
      timeout: Duration::from_secs( 60 ),
      max_connections: 5,
      enable_caching: true,
    };

    let diff = ConfigDiff::calculate( &old_config, &new_config );
    assert!( diff.server_url_changed );
    assert!( diff.timeout_changed );
    assert!( !diff.max_connections_changed );
    assert!( diff.caching_changed );
  }

  #[ test ]
  fn test_config_backup_and_restore()
  {
    let config = DynamicConfig {
      server_url: "http://localhost:11434".to_string(),
      timeout: Duration::from_secs( 30 ),
      max_connections: 5,
      enable_caching: true,
    };

    let backup = ConfigBackup::from_config( &config );
    let restored = backup.to_config();

    assert_eq!( config.server_url, restored.server_url );
    assert_eq!( config.timeout, restored.timeout );
    assert_eq!( config.max_connections, restored.max_connections );
    assert_eq!( config.enable_caching, restored.enable_caching );
  }
}