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
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
//! Structured Logging Integration Tests for Gemini API Client
//!
//! These tests verify structured logging capabilities including:
//! - HTTP request/response logging with structured fields
//! - Performance monitoring and metrics logging  
//! - Error condition logging with context
//! - Log level filtering and configuration
//! - Structured data capture and validation
//! - Integration with tracing ecosystem
//!
//! All tests use the logging feature flag and validate actual log output.


use std::sync::{ Arc, Mutex };
use std::time::Duration;
use api_gemini::
{
  client ::Client,
};
use tracing::Level;
use tracing_subscriber::
{
fmt ::{ self, format::FmtSpan },
  Registry,
  EnvFilter,
};
use core::cell::RefCell;
use tracing_subscriber::layer::Layer;
use tracing::{ Event, Subscriber, Instrument };

/// Captured log entry for testing
#[ derive( Debug, Clone ) ]
pub struct LogEntry
{
  /// Log level
  pub level: Level,
  /// Log message
  pub message: String,
  /// Log target
  pub target: String,
  /// Structured fields
  pub fields: std::collections::HashMap<  String, String  >,
  /// Timestamp
  pub timestamp: std::time::SystemTime,
}

/// Custom tracing layer that captures structured fields for testing
#[ derive( Debug ) ]
#[ allow( dead_code ) ]
struct CaptureLayer;

impl CaptureLayer
{
  #[ allow( dead_code ) ]
  fn new() -> Self
  {
    Self
  }
}

impl< S > Layer< S > for CaptureLayer
where
S: Subscriber,
{
  fn on_event( &self, event: &Event< '_ >, _ctx: tracing_subscriber::layer::Context< '_, S > )
  {
    let mut fields = std::collections::HashMap::new();
    let mut message = String::new();
  
    // Create visitor to extract fields
  let mut visitor = FieldVisitor { fields : &mut fields, message : &mut message };
    event.record( &mut visitor );
  
    // For now, skip span context extraction - this will be improved
    // The basic event logging is working correctly
  
    let entry = LogEntry {
      level: *event.metadata().level(),
      message: message.clone(),
      target: event.metadata().target().to_string(),
      fields,
      timestamp: std::time::SystemTime::now(),
    };
  
    // Store the captured log entry
    TEST_CAPTURE.with( |logs| logs.borrow_mut().push( entry ) );
  }
}

/// Visitor to extract structured fields from tracing events
#[ allow( dead_code ) ]
struct FieldVisitor< 'a >
{
  fields: &'a mut std::collections::HashMap<  String, String  >,
  message: &'a mut String,
}

impl tracing::field::Visit for FieldVisitor< '_ >
{
  fn record_debug( &mut self, field: &tracing::field::Field, value: &dyn core::fmt::Debug )
  {
    if field.name() == "message"
    {
    *self.message = format!( "{value:?}" );
    } else {
    self.fields.insert( field.name().to_string(), format!( "{value:?}" ) );
    }
  }
  
  fn record_str( &mut self, field: &tracing::field::Field, value: &str )
  {
    if field.name() == "message"
    {
      *self.message = value.to_string();
    } else {
      self.fields.insert( field.name().to_string(), value.to_string() );
    }
  }
  
  fn record_f64( &mut self, field: &tracing::field::Field, value: f64 )
  {
    self.fields.insert( field.name().to_string(), value.to_string() );
  }
  
  fn record_u64( &mut self, field: &tracing::field::Field, value: u64 )
  {
    self.fields.insert( field.name().to_string(), value.to_string() );
  }
  
  fn record_i64( &mut self, field: &tracing::field::Field, value: i64 )
  {
    self.fields.insert( field.name().to_string(), value.to_string() );
  }
}

/// Custom test subscriber that captures logs for verification
#[ derive( Debug ) ]
pub struct TestLogCapture
{
  /// Shared log entries storage for test verification
  pub entries: Arc< Mutex< Vec< LogEntry > > >,
}

impl TestLogCapture
{
  /// Create new test log capture system with shared storage
  #[ must_use ]
  pub fn new() -> ( Self, Arc< Mutex< Vec< LogEntry > > > )
  {
    let entries = Arc::new( Mutex::new( Vec::new() ) );
    let capture = Self {
      entries: entries.clone(),
    };
    ( capture, entries )
  }

  /// Clear all captured log entries
  /// Clears all captured log entries
  /// 
  /// # Panics
  /// 
  /// Panics if the mutex is poisoned
  pub fn clear( &self )
  {
    self.entries.lock().unwrap().clear();
  }
}

/// Create client with logging enabled for tests
#[ allow( dead_code ) ]
fn create_logging_client() -> Client
{
  // Set environment variable to enable HTTP logging
  std ::env::set_var( "GEMINI_ENABLE_HTTP_LOGGING", "1" );

  // Create client - logging will be enabled via environment variable
  Client::new()
  .expect( "Failed to create client for logging tests" )
}

/// Test basic HTTP request logging with structured fields
#[ tokio::test ]
#[ cfg( feature = "logging" ) ]
async fn test_http_request_logging_basic()
{
  let _guard = setup_test_logging();
  
  let client = create_logging_client();
  let models_api = client.models();
  
  // This should fail initially - we need enhanced structured logging
  let result = models_api.list().await;
  
  // Verify structured logging captured request details
  match result 
  {
    Ok( models ) => 
    {
      assert!( !models.models.is_empty() );
      
      // Verify logs contain structured fields
      let logs = get_captured_logs();
      
      // Should have request start log
      let start_log = logs.iter().find( |entry| 
      entry.message.contains( "Starting HTTP request" ) &&
      entry.fields.contains_key( "url" ) &&
      entry.fields.contains_key( "method" ) &&
      entry.fields.contains_key( "request_id" )
      );
      assert!( start_log.is_some(), "Missing structured request start log" );
      
      // Should have success completion log  
      let success_log = logs.iter().find( |entry|
      entry.message.contains( "HTTP request completed successfully" ) &&
      entry.fields.contains_key( "duration_ms" ) &&
      entry.fields.contains_key( "status_code" ) &&
      entry.fields.contains_key( "response_size_bytes" )
      );
      assert!( success_log.is_some(), "Missing structured success log" );
    },
  Err( e ) => panic!( "HTTP request failed : {e}" ),
  }
}

/// Test error condition logging with structured context
#[ tokio::test ]  
#[ cfg( feature = "logging" ) ]
async fn test_error_logging_structured()
{
  let _guard = setup_test_logging();
  
  let client = create_logging_client();
  let models_api = client.models();
  
  // Attempt to get a non-existent model to trigger error logging
  let result = models_api.get( "models/non-existent-model" ).await;
  
  match result
  {
    Err( _error ) =>
    {
      let logs = get_captured_logs();
      
      // Should have structured error log
      let error_log = logs.iter().find( |entry|
      entry.level == Level::ERROR &&
      entry.fields.contains_key( "error_type" ) &&
      entry.fields.contains_key( "error_message" ) &&
      entry.fields.contains_key( "url" ) &&
      entry.fields.contains_key( "duration_ms" )
      );
    assert!( error_log.is_some(), "Missing structured error log : {logs:?}" );
      
      // Verify error context is captured
      let error_entry = error_log.unwrap();
      assert!( error_entry.fields.get( "error_type" ).unwrap().contains( "ApiError" ) );
    },
    Ok( _ ) => panic!( "Expected error for non-existent model" ),
  }
}

/// Test performance monitoring with timing metrics
#[ tokio::test ]
#[ cfg( feature = "logging" ) ]  
async fn test_performance_monitoring_logging()
{
  let _guard = setup_test_logging();
  
  let client = create_logging_client();
  let models_api = client.models();
  let model = models_api.by_name( "text-embedding-004" );
  
  // Perform operation that should be monitored
  let result = model.embed_text( "Performance monitoring test" ).await;
  
  match result
  {
    Ok( embedding ) =>
    {
      assert!( !embedding.is_empty() );
      
      let logs = get_captured_logs();
      
      // Should have performance metrics
      let perf_logs: Vec< _ > = logs.iter().filter( |entry|
      entry.fields.contains_key( "duration_ms" ) &&
      entry.fields.contains_key( "operation" )
      ).collect();
      
      assert!( !perf_logs.is_empty(), "Missing performance monitoring logs" );
      
      // Verify timing data is reasonable
      for log in perf_logs
      {
        let duration_str = log.fields.get( "duration_ms" ).unwrap();
        let duration: f64 = duration_str.parse().unwrap();
      assert!( (0.0..30000.0).contains(&duration), "Invalid duration : {duration}" );
      }
    },
  Err( e ) => panic!( "Embed text failed : {e}" ),
  }
}

/// Test log level filtering and configuration
#[ tokio::test ]
#[ cfg( feature = "logging" ) ]
async fn test_log_level_filtering()
{
  // Test with INFO level - should capture info and above
  let _guard = setup_test_logging_with_level( Level::INFO );
  
  let client = create_logging_client();
  let models_api = client.models();
  
  let _ = models_api.list().await;
  
  let logs = get_captured_logs();
  
  // Should have INFO and ERROR logs, but no DEBUG logs
  let has_info = logs.iter().any( |entry| entry.level == Level::INFO );
  let has_debug = logs.iter().any( |entry| entry.level == Level::DEBUG );
  let has_error = logs.iter().any( |entry| entry.level == Level::ERROR );
  
  // Depending on the operation outcome, we should have structured logs
  assert!( has_info || has_error, "Missing INFO/ERROR level logs" );
  assert!( !has_debug, "DEBUG logs should be filtered out at INFO level" );
}

/// Test streaming operation logging  
#[ tokio::test ]
#[ cfg( all( feature = "logging", feature = "streaming" ) ) ]
async fn test_streaming_logging()
{
  let _guard = setup_test_logging();
  
  let client = create_logging_client();
  let models_api = client.models();
  let model = models_api.by_name( "gemini-1.5-pro" );
  
  // Test streaming with logging - for now just use regular generate_text
  // xxx : Implement generate_text_stream when streaming is enhanced
  let result = model.generate_text( "Count from 1 to 3" ).await;
  
  match result
  {
    Ok( text ) =>
    {
      assert!( !text.is_empty() );
      
      let logs = get_captured_logs();
      
      // Should have general request logs (streaming uses regular HTTP logging for now)
      let request_logs: Vec< _ > = logs.iter().filter( |entry|
      entry.fields.contains_key( "operation" ) ||
      entry.fields.contains_key( "request_id" ) ||
      entry.message.contains( "HTTP request" )
      ).collect();
      
      assert!( !request_logs.is_empty(), "Missing HTTP request logs" );
    },
    Err( e ) => 
    {
      // If streaming isn't implemented yet, that's expected
    println!( "Streaming not implemented yet : {e}" );
    }
  }
}

/// Test batch operations logging with correlation IDs
#[ tokio::test ]
#[ cfg( feature = "logging" ) ]

async fn test_batch_operations_logging()
{
  let _guard = setup_test_logging();
  
  let client = create_logging_client();
  let models_api = client.models();
  let model = models_api.by_name( "text-embedding-004" );
  
  let texts = vec![
  "Batch logging test 1",
  "Batch logging test 2", 
  "Batch logging test 3",
  ];
  
  let result = model.batch_embed_texts( &texts ).await;
  
  match result
  {
    Ok( embeddings ) =>
    {
      assert_eq!( embeddings.len(), texts.len() );
      
      let logs = get_captured_logs();
      
      // Should have batch operation logs with correlation
      let batch_logs: Vec< _ > = logs.iter().filter( |entry|
      entry.fields.contains_key( "batch_id" ) ||
      entry.fields.contains_key( "batch_size" ) ||
      entry.message.contains( "batch" )
      ).collect();
      
      assert!( !batch_logs.is_empty(), "Missing batch operation logs" );
      
      // Verify batch correlation ID is consistent
      if let Some( first_log ) = batch_logs.first()
      {
        if let Some( batch_id ) = first_log.fields.get( "batch_id" )
        {
          let same_batch_id = batch_logs.iter().all( |log|
          log.fields.get( "batch_id" ) == Some(batch_id)
          );
          assert!( same_batch_id, "Batch correlation ID should be consistent" );
        }
      }
    },
  Err( e ) => panic!( "Batch embed failed : {e}" ),
  }
}

/// Test sensitive data redaction in logs
#[ tokio::test ]
#[ cfg( feature = "logging" ) ]
async fn test_sensitive_data_redaction()
{
  let _guard = setup_test_logging();
  
  let client = create_logging_client();
  let models_api = client.models();
  
  // Make a request - API key should be redacted in logs
  let _ = models_api.list().await;
  
  let logs = get_captured_logs();
  
  // Verify no API key appears in any log message or field
  for log in logs
  {
    assert!( !log.message.contains( "AIza" ), "API key leaked in log message" );
  
    for value in log.fields.values()
    {
    assert!( !value.contains( "AIza" ), "API key leaked in log field : {value}" );
    }
  }
}

/// Test custom span creation and context propagation
#[ tokio::test ]
#[ cfg( feature = "logging" ) ]
async fn test_span_context_propagation()
{
  let _guard = setup_test_logging();
  
  // Create custom span for operation context
  let operation_span = tracing::info_span!(
  "embedding_operation",
  operation_id = "test-123",
  user_context = "integration_test"
  );
  
  let result = async {
    let client = create_logging_client();
    let models_api = client.models();
    let model = models_api.by_name( "text-embedding-004" );
  
    model.embed_text( "Context propagation test" ).await
  }.instrument( operation_span ).await;
  
  match result
  {
    Ok( embedding ) =>
    {
      assert!( !embedding.is_empty() );
      
      let logs = get_captured_logs();
      
      // Should have basic HTTP request logs (span context extraction not yet implemented)
      let request_logs: Vec< _ > = logs.iter().filter( |entry|
      entry.fields.contains_key( "operation" ) ||
      entry.fields.contains_key( "request_id" ) ||
      entry.message.contains( "HTTP request" )
      ).collect();
      
      assert!( !request_logs.is_empty(), "Missing HTTP request logs for operation" );
    },
  Err( e ) => panic!( "Context propagation test failed : {e}" ),
  }
}

/// Test log sampling and rate limiting  
#[ tokio::test ]
#[ cfg( feature = "logging" ) ]
async fn test_log_sampling()
{
  let _guard = setup_test_logging();
  
  let client = create_logging_client();
  let models_api = client.models();
  
  // Make multiple rapid requests
  let mut results = Vec::new();
  for _i in 0..10
  {
    let result = models_api.list().await;
    results.push( result );
  
    // Small delay to avoid overwhelming
    tokio ::time::sleep( Duration::from_millis( 10 ) ).await;
  }
  
  // All requests should succeed  
  for result in results
  {
    assert!( result.is_ok() );
  }
  
  let logs = get_captured_logs();
  
  // Should have reasonable number of logs (not excessive)
  let request_logs: Vec< _ > = logs.iter().filter( |entry|
  entry.message.contains( "HTTP request" )
  ).collect();
  
  // Should have logs but reasonable amount (each request generates start + completion logs)
  assert!( !request_logs.is_empty(), "Should have some request logs" );
  // Each request generates 2 logs (start + completion), so 10 requests = ~20 logs, but allow some tolerance
assert!( request_logs.len() <= 35, "Too many logs - sampling may be needed : found {}", request_logs.len() );
}

// Helper functions for test setup

thread_local! {
static TEST_CAPTURE: RefCell< Vec< LogEntry > > = const { RefCell::new( Vec::new() ) };
}

#[ allow( dead_code ) ]
fn setup_test_logging() -> tracing::subscriber::DefaultGuard
{
  setup_test_logging_with_level( Level::DEBUG )
}

#[ allow( dead_code ) ]
fn setup_test_logging_with_level( level: Level ) -> tracing::subscriber::DefaultGuard
{
  use tracing_subscriber::layer::SubscriberExt;
  
  // Clear any existing logs
  TEST_CAPTURE.with( |logs| logs.borrow_mut().clear() );
  
  // Create custom layer that captures structured fields
  let capture_layer = CaptureLayer::new();
  
  let subscriber = Registry::default()
  .with( EnvFilter::from_default_env()
.add_directive( format!( "api_gemini={level}" ).parse().unwrap() )
  )
  .with( capture_layer )
  .with( fmt::layer()
  .with_test_writer()
  .with_target( true )
  .with_span_events( FmtSpan::CLOSE )
  );
  
  tracing ::subscriber::set_default( subscriber )
}

#[ allow( dead_code ) ]
fn get_captured_logs() -> Vec< LogEntry >
{
  TEST_CAPTURE.with( |logs| logs.borrow().clone() )
}

// Helper to simulate HTTP operation logging - used for future test expansion
#[ allow( dead_code ) ]
fn simulate_http_log( level: Level, message: &str, fields: std::collections::HashMap<  String, String  > )
{
  let entry = LogEntry {
    level,
    message: message.to_string(),
    target: "api_gemini::internal::http".to_string(),
    fields,
    timestamp: std::time::SystemTime::now(),
  };
  
  TEST_CAPTURE.with( |logs| logs.borrow_mut().push( entry ) );
}