cstats-core 0.1.1

Core library for cstats - statistical analysis and metrics collection
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
//! API client implementation

use chrono::{DateTime, Datelike, Timelike, Utc};
use reqwest::{
    header::{HeaderMap, HeaderValue, AUTHORIZATION, USER_AGENT},
    Client,
};
use std::sync::Arc;
use std::time::Duration;

use crate::{
    cache::FileCache,
    config::{ApiConfig, CacheConfig},
    Error, Result,
};

use super::{
    AnthropicConfig, AnthropicUsageStats, CostBreakdown, HttpClient, MetricData, RateLimitInfo,
    StatisticsData, UsageSummary,
};

/// High-level API client for cstats operations
#[derive(Debug, Clone)]
pub struct ApiClient {
    http: HttpClient,
    anthropic: Option<AnthropicApiClient>,
}

impl ApiClient {
    /// Create a new API client
    pub fn new(config: ApiConfig) -> Result<Self> {
        let http = HttpClient::new(config.clone())?;

        let anthropic = if let Some(anthropic_config) = config.anthropic {
            Some(AnthropicApiClient::new(anthropic_config)?.with_usage_tracking())
        } else {
            None
        };

        Ok(Self { http, anthropic })
    }

    /// Create API client with cache enabled
    pub fn with_cache(config: ApiConfig, cache_config: CacheConfig) -> Result<Self> {
        let http = HttpClient::new(config.clone())?;

        let cache = Arc::new(FileCache::new(cache_config));

        let anthropic = if let Some(anthropic_config) = config.anthropic {
            // Only create client if API key is not empty
            if !anthropic_config.api_key.is_empty() {
                Some(
                    AnthropicApiClient::new(anthropic_config)?
                        .with_cache(cache.clone())
                        .with_usage_tracking(),
                )
            } else {
                None
            }
        } else {
            None
        };

        Ok(Self { http, anthropic })
    }

    /// Create API client from loaded configuration with cache
    pub async fn from_config_with_cache(config: crate::config::Config) -> Result<Self> {
        let api_config = config.api;
        let cache_config = config.cache;

        let client = Self::with_cache(api_config, cache_config)?;

        // Initialize cache directory if anthropic client is configured
        if let Some(anthropic_client) = &client.anthropic {
            if let Some(cache) = &anthropic_client.cache {
                cache.init().await?;
            }
        }

        Ok(client)
    }

    /// Create API client from environment variables with cache (loads config file with env overrides)
    pub async fn from_env_with_cache() -> Result<Self> {
        // Load config from file first, then apply env overrides
        let config = crate::config::Config::load().await?;
        Self::from_config_with_cache(config).await
    }

    /// Get the Anthropic API client if configured
    pub fn anthropic(&self) -> Option<&AnthropicApiClient> {
        self.anthropic.as_ref()
    }

    /// Fetch Claude Code usage statistics from Anthropic API
    pub async fn fetch_claude_usage_stats(
        &self,
        start_time: DateTime<Utc>,
        end_time: DateTime<Utc>,
    ) -> Result<AnthropicUsageStats> {
        let anthropic_client = self
            .anthropic
            .as_ref()
            .ok_or_else(|| Error::config("Anthropic API not configured"))?;

        anthropic_client
            .fetch_usage_stats(start_time, end_time)
            .await
    }

    /// Fetch rate limit information from Anthropic API
    pub async fn fetch_rate_limit_info(&self) -> Result<RateLimitInfo> {
        let anthropic_client = self
            .anthropic
            .as_ref()
            .ok_or_else(|| Error::config("Anthropic API not configured"))?;

        anthropic_client.fetch_rate_limit_info().await
    }

    /// Fetch billing information from Anthropic API
    pub async fn fetch_billing_info(
        &self,
        start_time: DateTime<Utc>,
        end_time: DateTime<Utc>,
    ) -> Result<CostBreakdown> {
        let anthropic_client = self
            .anthropic
            .as_ref()
            .ok_or_else(|| Error::config("Anthropic API not configured"))?;

        anthropic_client
            .fetch_billing_info(start_time, end_time)
            .await
    }

    /// Fetch usage stats for the last 24 hours
    pub async fn fetch_daily_usage_stats(&self) -> Result<AnthropicUsageStats> {
        let end_time = Utc::now();
        let start_time = end_time - chrono::Duration::days(1);
        self.fetch_claude_usage_stats(start_time, end_time).await
    }

    /// Fetch usage stats for the last 7 days
    pub async fn fetch_weekly_usage_stats(&self) -> Result<AnthropicUsageStats> {
        let end_time = Utc::now();
        let start_time = end_time - chrono::Duration::days(7);
        self.fetch_claude_usage_stats(start_time, end_time).await
    }

    /// Fetch usage stats for the last 30 days
    pub async fn fetch_monthly_usage_stats(&self) -> Result<AnthropicUsageStats> {
        let end_time = Utc::now();
        let start_time = end_time - chrono::Duration::days(30);
        self.fetch_claude_usage_stats(start_time, end_time).await
    }

    /// Fetch usage stats for the current month
    pub async fn fetch_current_month_usage_stats(&self) -> Result<AnthropicUsageStats> {
        let now = Utc::now();
        let start_time = now
            .with_day(1)
            .unwrap()
            .with_hour(0)
            .unwrap()
            .with_minute(0)
            .unwrap()
            .with_second(0)
            .unwrap();
        self.fetch_claude_usage_stats(start_time, now).await
    }

    /// Fetch billing info for the current month
    pub async fn fetch_current_month_billing(&self) -> Result<CostBreakdown> {
        let now = Utc::now();
        let start_time = now
            .with_day(1)
            .unwrap()
            .with_hour(0)
            .unwrap()
            .with_minute(0)
            .unwrap()
            .with_second(0)
            .unwrap();
        self.fetch_billing_info(start_time, now).await
    }

    /// Get a comprehensive usage summary
    pub async fn get_usage_summary(&self) -> Result<UsageSummary> {
        let _anthropic_client = self
            .anthropic
            .as_ref()
            .ok_or_else(|| Error::config("Anthropic API not configured"))?;

        let (daily_stats, weekly_stats, monthly_stats, rate_limit) = tokio::try_join!(
            self.fetch_daily_usage_stats(),
            self.fetch_weekly_usage_stats(),
            self.fetch_monthly_usage_stats(),
            self.fetch_rate_limit_info()
        )?;

        Ok(UsageSummary {
            daily: daily_stats,
            weekly: weekly_stats,
            monthly: monthly_stats,
            rate_limit,
            timestamp: Utc::now(),
        })
    }

    /// Submit statistics data to the API
    pub async fn submit_statistics(&self, data: &StatisticsData) -> Result<()> {
        if let Some(base_url) = &self.http.config().base_url {
            let url = format!("{}/api/v1/statistics", base_url);
            let response = self.http.client().post(&url).json(data).send().await?;

            if !response.status().is_success() {
                return Err(Error::api(format!(
                    "Failed to submit statistics: {}",
                    response.status()
                )));
            }
        }

        Ok(())
    }

    /// Retrieve metrics from the API
    pub async fn get_metrics(&self, query: &str) -> Result<Vec<MetricData>> {
        if let Some(base_url) = &self.http.config().base_url {
            let url = format!("{}/api/v1/metrics?q={}", base_url, query);
            let response = self.http.client().get(&url).send().await?;

            if !response.status().is_success() {
                return Err(Error::api(format!(
                    "Failed to get metrics: {}",
                    response.status()
                )));
            }

            let metrics: Vec<MetricData> = response.json().await?;
            return Ok(metrics);
        }

        // Return empty vec if no base URL configured
        Ok(vec![])
    }

    /// Health check for the API
    pub async fn health_check(&self) -> Result<bool> {
        if let Some(base_url) = &self.http.config().base_url {
            let url = format!("{}/health", base_url);
            let response = self.http.client().get(&url).send().await?;

            Ok(response.status().is_success())
        } else {
            Ok(true) // Consider healthy if no API configured
        }
    }
}

/// Anthropic API client for Claude Code usage statistics
///
/// Note: This client provides a wrapper around Anthropic's API with mock implementations
/// for usage statistics, billing, and rate limit endpoints that are not publicly available.
/// The client can still be used for actual API calls to supported endpoints.
#[derive(Debug, Clone)]
pub struct AnthropicApiClient {
    client: Client,
    config: AnthropicConfig,
    cache: Option<Arc<FileCache>>,
    usage_tracker: Option<Arc<super::LocalUsageTracker>>,
}

impl AnthropicApiClient {
    /// Create a new Anthropic API client
    pub fn new(config: AnthropicConfig) -> Result<Self> {
        let mut headers = HeaderMap::new();
        headers.insert(
            AUTHORIZATION,
            HeaderValue::from_str(&format!("Bearer {}", config.api_key))
                .map_err(|e| Error::config(format!("Invalid API key format: {}", e)))?,
        );
        headers.insert(USER_AGENT, HeaderValue::from_static("cstats-client/1.0.0"));
        headers.insert("anthropic-version", HeaderValue::from_static("2023-06-01"));

        let client = Client::builder()
            .timeout(Duration::from_secs(config.timeout_seconds))
            .default_headers(headers)
            .build()
            .map_err(Error::Http)?;

        Ok(Self {
            client,
            config,
            cache: None,
            usage_tracker: None,
        })
    }

    /// Create client from environment variables
    pub fn from_env() -> Result<Self> {
        let api_key = std::env::var("ANTHROPIC_API_KEY")
            .map_err(|_| Error::config("ANTHROPIC_API_KEY environment variable not set"))?;

        let mut config = AnthropicConfig {
            api_key,
            ..Default::default()
        };

        // Override defaults with environment variables if present
        if let Ok(base_url) = std::env::var("ANTHROPIC_BASE_URL") {
            config.base_url = base_url;
        }

        if let Ok(timeout) = std::env::var("ANTHROPIC_TIMEOUT_SECONDS") {
            if let Ok(timeout_val) = timeout.parse() {
                config.timeout_seconds = timeout_val;
            }
        }

        Self::new(config)
    }

    /// Enable caching with the specified cache instance
    pub fn with_cache(mut self, cache: Arc<FileCache>) -> Self {
        self.cache = Some(cache);
        self
    }

    /// Enable local usage tracking
    pub fn with_usage_tracking(mut self) -> Self {
        self.usage_tracker = Some(Arc::new(super::LocalUsageTracker::new()));
        self
    }

    /// Get the usage tracker if enabled
    pub fn usage_tracker(&self) -> Option<&Arc<super::LocalUsageTracker>> {
        self.usage_tracker.as_ref()
    }

    /// Fetch usage statistics for the specified period
    ///
    /// Note: Anthropic's API does not provide public usage statistics endpoints.
    /// If local usage tracking is enabled, this returns tracked data.
    /// Otherwise, it returns mock data explaining the limitation.
    pub async fn fetch_usage_stats(
        &self,
        start_time: DateTime<Utc>,
        end_time: DateTime<Utc>,
    ) -> Result<AnthropicUsageStats> {
        // If local usage tracking is enabled, use that
        if let Some(tracker) = &self.usage_tracker {
            tracing::info!(
                "Returning locally tracked usage statistics for period {} to {}",
                start_time,
                end_time
            );
            return tracker.get_usage_stats(start_time, end_time).await;
        }

        tracing::warn!(
            "Anthropic API does not provide public usage statistics endpoints. \
             Returning mock data for period {} to {}. \
             Enable local usage tracking for actual statistics.",
            start_time,
            end_time
        );

        // Return mock usage statistics that indicate the API limitation
        Ok(self.create_mock_usage_stats(start_time, end_time))
    }

    /// Fetch current rate limit information
    ///
    /// Note: Anthropic's API does not provide public rate limit endpoints.
    /// This method returns estimated rate limits based on known service tier limits.
    /// Rate limits are enforced through response headers and HTTP 429 responses.
    pub async fn fetch_rate_limit_info(&self) -> Result<RateLimitInfo> {
        // If local usage tracking is enabled, get estimates from there
        if let Some(tracker) = &self.usage_tracker {
            return tracker.get_rate_limit_info().await;
        }

        tracing::warn!(
            "Anthropic API does not provide public rate limit endpoints. \
             Returning estimated rate limits based on service tier. \
             Actual rate limits are enforced through response headers."
        );

        // Return estimated rate limits based on Anthropic's documented limits
        // These are conservative estimates and actual limits may vary by service tier
        Ok(RateLimitInfo {
            requests_per_minute: 1000, // Conservative estimate for API tier
            requests_remaining: 1000,  // Cannot determine actual remaining
            reset_time: Utc::now() + chrono::Duration::seconds(60),
            tokens_per_minute: Some(50_000), // Conservative estimate
            tokens_remaining: Some(50_000),  // Cannot determine actual remaining
        })
    }

    /// Fetch billing information
    ///
    /// Note: Anthropic's API does not provide public billing endpoints.
    /// This method returns a mock implementation that explains the limitation.
    /// For actual billing information, use the Anthropic Console at console.anthropic.com.
    pub async fn fetch_billing_info(
        &self,
        start_time: DateTime<Utc>,
        end_time: DateTime<Utc>,
    ) -> Result<CostBreakdown> {
        tracing::warn!(
            "Anthropic API does not provide public billing endpoints. \
             Returning mock data for period {} to {}. \
             For actual billing information, visit the Anthropic Console at console.anthropic.com.",
            start_time,
            end_time
        );

        // Return mock billing information that indicates the API limitation
        Ok(self.create_mock_cost_breakdown(start_time, end_time))
    }

    /// Test API connectivity by making a minimal API call
    ///
    /// Note: Anthropic's API does not have a dedicated health endpoint.
    /// This method tests connectivity by making a token counting request.
    pub async fn health_check(&self) -> Result<bool> {
        // Create a minimal token counting request to test connectivity
        let test_payload = serde_json::json!({
            "model": "claude-3-haiku-20240307",
            "messages": [{
                "role": "user",
                "content": "Hello"
            }]
        });

        match self
            .client
            .post(format!("{}/v1/messages/count-tokens", self.config.base_url))
            .json(&test_payload)
            .send()
            .await
        {
            Ok(response) => {
                // Accept both 200 (success) and 401 (unauthorized) as "healthy"
                // 401 means the API is responding but our test key is invalid
                let status = response.status();
                Ok(status.is_success() || status == reqwest::StatusCode::UNAUTHORIZED)
            }
            Err(_) => Ok(false),
        }
    }

    /// Create mock usage statistics that indicate API limitations
    fn create_mock_usage_stats(
        &self,
        start_time: DateTime<Utc>,
        end_time: DateTime<Utc>,
    ) -> AnthropicUsageStats {
        use super::{ApiCallStats, TokenUsage, UsagePeriod};
        use std::collections::HashMap;

        AnthropicUsageStats {
            token_usage: TokenUsage {
                input_tokens: 0,
                output_tokens: 0,
                total_tokens: 0,
                by_model: HashMap::new(),
            },
            api_calls: ApiCallStats {
                total_calls: 0,
                successful_calls: 0,
                failed_calls: 0,
                avg_response_time_ms: 0.0,
                by_model: HashMap::new(),
                hourly_breakdown: vec![],
            },
            costs: self.create_mock_cost_breakdown(start_time, end_time),
            model_usage: vec![],
            period: UsagePeriod {
                start: start_time,
                end: end_time,
                period_type: "mock".to_string(),
            },
        }
    }

    /// Create mock cost breakdown that indicates API limitations
    fn create_mock_cost_breakdown(
        &self,
        _start_time: DateTime<Utc>,
        _end_time: DateTime<Utc>,
    ) -> CostBreakdown {
        use super::TokenCostBreakdown;
        use std::collections::HashMap;

        CostBreakdown {
            total_cost_usd: 0.0,
            by_model: HashMap::new(),
            by_token_type: TokenCostBreakdown {
                input_cost_usd: 0.0,
                output_cost_usd: 0.0,
            },
            estimated_monthly_cost_usd: 0.0,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::{ApiConfig, Config};

    /// Example usage of the Anthropic API client
    /// This test demonstrates how to use the client (won't run without API key)
    #[tokio::test]
    #[ignore = "Integration test - requires ANTHROPIC_API_KEY environment variable"]
    async fn example_anthropic_api_usage() -> Result<()> {
        // Create client from environment variables
        let client = ApiClient::from_env_with_cache().await?;

        // Test API connectivity
        if let Some(anthropic_client) = client.anthropic() {
            let is_healthy = anthropic_client.health_check().await?;
            println!("API health check: {}", is_healthy);

            // Fetch rate limit info
            match client.fetch_rate_limit_info().await {
                Ok(rate_limit) => {
                    println!(
                        "Rate limit - Remaining: {}, Reset: {:?}",
                        rate_limit.requests_remaining, rate_limit.reset_time
                    );
                }
                Err(e) => println!("Failed to fetch rate limit info: {}", e),
            }

            // Fetch usage stats for different periods
            match client.fetch_daily_usage_stats().await {
                Ok(daily_stats) => {
                    println!(
                        "Daily usage - Total tokens: {}",
                        daily_stats.token_usage.total_tokens
                    );
                    println!(
                        "Daily usage - API calls: {}",
                        daily_stats.api_calls.total_calls
                    );
                    println!(
                        "Daily usage - Total cost: ${:.4}",
                        daily_stats.costs.total_cost_usd
                    );
                }
                Err(e) => println!("Failed to fetch daily usage stats: {}", e),
            }

            // Fetch comprehensive usage summary
            match client.get_usage_summary().await {
                Ok(summary) => {
                    println!("Usage Summary:");
                    println!("  Daily tokens: {}", summary.daily.token_usage.total_tokens);
                    println!(
                        "  Weekly tokens: {}",
                        summary.weekly.token_usage.total_tokens
                    );
                    println!(
                        "  Monthly tokens: {}",
                        summary.monthly.token_usage.total_tokens
                    );
                    println!(
                        "  Rate limit remaining: {}",
                        summary.rate_limit.requests_remaining
                    );
                }
                Err(e) => println!("Failed to fetch usage summary: {}", e),
            }

            // Fetch current month billing
            match client.fetch_current_month_billing().await {
                Ok(billing) => {
                    println!("Current month billing: ${:.4}", billing.total_cost_usd);
                    for (model, cost) in billing.by_model.iter() {
                        println!("  {}: ${:.4}", model, cost.cost_usd);
                    }
                }
                Err(e) => println!("Failed to fetch billing info: {}", e),
            }
        } else {
            println!("Anthropic API not configured");
        }

        Ok(())
    }

    /// Test configuration loading
    #[tokio::test]
    async fn test_config_from_env() -> Result<()> {
        // This test shows how configuration would work
        let config = Config::from_env()?;

        // The config should have default values if no env vars are set
        assert_eq!(config.api.timeout_seconds, 30);
        assert_eq!(config.api.retry_attempts, 3);

        Ok(())
    }

    /// Test creating client without Anthropic configuration
    #[tokio::test]
    async fn test_client_without_anthropic() -> Result<()> {
        let config = ApiConfig::default();
        let client = ApiClient::new(config)?;

        // Should succeed but anthropic client should be None
        assert!(client.anthropic().is_none());

        // Trying to fetch Claude stats should return an error
        let result = client.fetch_daily_usage_stats().await;
        assert!(result.is_err());

        Ok(())
    }
}