syncable_cli/telemetry/
client.rs

1use crate::config::types::Config;
2use crate::telemetry::user::UserId;
3use serde_json::json;
4use std::collections::HashMap;
5use std::time::Duration;
6use reqwest::Client;
7use tokio::sync::Mutex;
8use std::sync::Arc;
9
10// PostHog API endpoint and key - Using EU endpoint to match your successful curl test
11const POSTHOG_API_ENDPOINT: &str = "https://eu.i.posthog.com/capture/";
12const POSTHOG_PROJECT_API_KEY: &str = "phc_t5zrCHU3yiU52lcUfOP3SiCSxdhJcmB2I3m06dGTk2D";
13
14pub struct TelemetryClient {
15    user_id: UserId,
16    http_client: Client,
17    pending_tasks: Arc<Mutex<Vec<tokio::task::JoinHandle<()>>>>,
18}
19
20impl TelemetryClient {
21    pub async fn new(_config: &Config) -> Result<Self, Box<dyn std::error::Error>> {
22        let user_id = UserId::load_or_create()?;
23        let http_client = Client::new();
24        let pending_tasks = Arc::new(Mutex::new(Vec::new()));
25
26        Ok(Self {
27            user_id,
28            http_client,
29            pending_tasks,
30        })
31    }
32    
33    // Helper function to create common properties
34    fn create_common_properties(&self) -> HashMap<String, serde_json::Value> {
35        let mut properties = HashMap::new();
36        properties.insert("version".to_string(), json!(env!("CARGO_PKG_VERSION")));
37        properties.insert("os".to_string(), json!(std::env::consts::OS));
38        properties.insert("personal_id".to_string(), json!(rand::random::<u32>()));
39        properties.insert("distinct_id".to_string(), json!(self.user_id.id.clone()));
40        properties
41    }
42    
43    pub fn track_event(&self, name: &str, properties: HashMap<String, serde_json::Value>) {
44        let mut event_properties = self.create_common_properties();
45        
46        // Merge provided properties
47        for (key, value) in properties {
48            event_properties.insert(key, value);
49        }
50        
51        let event_name = name.to_string();
52        let client = self.http_client.clone();
53        let pending_tasks = self.pending_tasks.clone();
54        
55        log::debug!("Tracking event: {}", event_name);
56        
57        // Send the event asynchronously
58        let handle = tokio::spawn(async move {
59            // Create the event payload according to PostHog API
60            let payload = json!({
61                "api_key": POSTHOG_PROJECT_API_KEY,
62                "event": event_name,
63                "properties": event_properties,
64                "timestamp": chrono::Utc::now().format("%Y-%m-%dT%H:%M:%SZ").to_string(),
65            });
66            
67            log::debug!("Sending telemetry payload: {:?}", payload);
68            
69            match client
70                .post(POSTHOG_API_ENDPOINT)
71                .json(&payload)
72                .send()
73                .await
74            {
75                Ok(response) => {
76                    if response.status().is_success() {
77                        log::debug!("Successfully sent telemetry event: {}", event_name);
78                    } else {
79                        let status = response.status();
80                        let body = response.text().await.unwrap_or_else(|_| "Unknown error".to_string());
81                        log::warn!("Failed to send telemetry event '{}': HTTP {} - {}", event_name, status, body);
82                    }
83                }
84                Err(e) => {
85                    log::warn!("Failed to send telemetry event '{}': {}", event_name, e);
86                }
87            }
88        });
89        
90        // Keep track of the task
91        let pending_tasks_clone = pending_tasks.clone();
92        tokio::spawn(async move {
93            pending_tasks_clone.lock().await.push(handle);
94        });
95    }
96    
97    // Specific methods for the actual commands
98    pub fn track_analyze(&self, properties: HashMap<String, serde_json::Value>) {
99        self.track_event("analyze", properties);
100    }
101    
102    pub fn track_generate(&self, properties: HashMap<String, serde_json::Value>) {
103        self.track_event("generate", properties);
104    }
105    
106    pub fn track_validate(&self, properties: HashMap<String, serde_json::Value>) {
107        self.track_event("validate", properties);
108    }
109    
110    pub fn track_support(&self, properties: HashMap<String, serde_json::Value>) {
111        self.track_event("support", properties);
112    }
113    
114    pub fn track_dependencies(&self, properties: HashMap<String, serde_json::Value>) {
115        self.track_event("dependencies", properties);
116    }
117    
118    // Updated to accept properties
119    pub fn track_vulnerabilities(&self, properties: HashMap<String, serde_json::Value>) {
120        self.track_event("Vulnerability Scan", properties);
121    }
122    
123    // Updated to accept properties
124    pub fn track_security(&self, properties: HashMap<String, serde_json::Value>) {
125        self.track_event("Security Scan", properties);
126    }
127    
128    pub fn track_tools(&self, properties: HashMap<String, serde_json::Value>) {
129        self.track_event("tools", properties);
130    }
131    
132    // Existing specific methods for events
133    pub fn track_security_scan(&self) {
134        // Deprecated: Use track_security with properties instead
135    }
136    
137    // Updated to accept properties
138    pub fn track_analyze_folder(&self, properties: HashMap<String, serde_json::Value>) {
139        self.track_event("Analyze Folder", properties);
140    }
141    
142    pub fn track_vulnerability_scan(&self) {
143        // Deprecated: Use track_vulnerabilities with properties instead
144    }
145    
146    // Flush method to ensure all events are sent before the program exits
147    pub async fn flush(&self) {
148        // Collect all pending tasks
149        let mut tasks = Vec::new();
150        {
151            let mut pending_tasks = self.pending_tasks.lock().await;
152            tasks.extend(pending_tasks.drain(..));
153        }
154        
155        // Wait for all tasks to complete
156        if !tasks.is_empty() {
157            log::debug!("Waiting for {} telemetry tasks to complete", tasks.len());
158            futures_util::future::join_all(tasks).await;
159        }
160        
161        // Give a bit more time for network requests to complete
162        tokio::time::sleep(Duration::from_millis(500)).await;
163    }
164}