1use crate::{TelemetrySettings, ZED_SECRET_CLIENT_TOKEN, ZED_SERVER_URL};
2use gpui::{executor::Background, serde_json, AppContext, Task};
3use lazy_static::lazy_static;
4use parking_lot::Mutex;
5use serde::Serialize;
6use std::{env, io::Write, mem, path::PathBuf, sync::Arc, time::Duration};
7use tempfile::NamedTempFile;
8use util::http::HttpClient;
9use util::{channel::ReleaseChannel, TryFutureExt};
10
11pub struct Telemetry {
12 http_client: Arc<dyn HttpClient>,
13 executor: Arc<Background>,
14 state: Mutex<TelemetryState>,
15}
16
17#[derive(Default)]
18struct TelemetryState {
19 metrics_id: Option<Arc<str>>, // Per logged-in user
20 installation_id: Option<Arc<str>>, // Per app installation
21 app_version: Option<Arc<str>>,
22 release_channel: Option<&'static str>,
23 os_name: &'static str,
24 os_version: Option<Arc<str>>,
25 architecture: &'static str,
26 clickhouse_events_queue: Vec<ClickhouseEventWrapper>,
27 flush_clickhouse_events_task: Option<Task<()>>,
28 log_file: Option<NamedTempFile>,
29 is_staff: Option<bool>,
30}
31
32const CLICKHOUSE_EVENTS_URL_PATH: &'static str = "/api/events";
33
34lazy_static! {
35 static ref CLICKHOUSE_EVENTS_URL: String =
36 format!("{}{}", *ZED_SERVER_URL, CLICKHOUSE_EVENTS_URL_PATH);
37}
38
39#[derive(Serialize, Debug)]
40struct ClickhouseEventRequestBody {
41 token: &'static str,
42 installation_id: Option<Arc<str>>,
43 is_staff: Option<bool>,
44 app_version: Option<Arc<str>>,
45 os_name: &'static str,
46 os_version: Option<Arc<str>>,
47 architecture: &'static str,
48 release_channel: Option<&'static str>,
49 events: Vec<ClickhouseEventWrapper>,
50}
51
52#[derive(Serialize, Debug)]
53struct ClickhouseEventWrapper {
54 signed_in: bool,
55 #[serde(flatten)]
56 event: ClickhouseEvent,
57}
58
59#[derive(Serialize, Debug)]
60#[serde(tag = "type")]
61pub enum ClickhouseEvent {
62 Editor {
63 operation: &'static str,
64 file_extension: Option<String>,
65 vim_mode: bool,
66 copilot_enabled: bool,
67 copilot_enabled_for_language: bool,
68 },
69 Copilot {
70 suggestion_id: Option<String>,
71 suggestion_accepted: bool,
72 file_extension: Option<String>,
73 },
74 Call {
75 operation: &'static str,
76 room_id: u64,
77 channel_id: Option<u64>,
78 },
79}
80
81#[cfg(debug_assertions)]
82const MAX_QUEUE_LEN: usize = 1;
83
84#[cfg(not(debug_assertions))]
85const MAX_QUEUE_LEN: usize = 10;
86
87#[cfg(debug_assertions)]
88const DEBOUNCE_INTERVAL: Duration = Duration::from_secs(1);
89
90#[cfg(not(debug_assertions))]
91const DEBOUNCE_INTERVAL: Duration = Duration::from_secs(30);
92
93impl Telemetry {
94 pub fn new(client: Arc<dyn HttpClient>, cx: &AppContext) -> Arc<Self> {
95 let platform = cx.platform();
96 let release_channel = if cx.has_global::<ReleaseChannel>() {
97 Some(cx.global::<ReleaseChannel>().display_name())
98 } else {
99 None
100 };
101 // TODO: Replace all hardware stuff with nested SystemSpecs json
102 let this = Arc::new(Self {
103 http_client: client,
104 executor: cx.background().clone(),
105 state: Mutex::new(TelemetryState {
106 os_name: platform.os_name().into(),
107 os_version: platform.os_version().ok().map(|v| v.to_string().into()),
108 architecture: env::consts::ARCH,
109 app_version: platform.app_version().ok().map(|v| v.to_string().into()),
110 release_channel,
111 installation_id: None,
112 metrics_id: None,
113 clickhouse_events_queue: Default::default(),
114 flush_clickhouse_events_task: Default::default(),
115 log_file: None,
116 is_staff: None,
117 }),
118 });
119
120 this
121 }
122
123 pub fn log_file_path(&self) -> Option<PathBuf> {
124 Some(self.state.lock().log_file.as_ref()?.path().to_path_buf())
125 }
126
127 pub fn start(self: &Arc<Self>, installation_id: Option<String>) {
128 let mut state = self.state.lock();
129 state.installation_id = installation_id.map(|id| id.into());
130 let has_clickhouse_events = !state.clickhouse_events_queue.is_empty();
131 drop(state);
132
133 if has_clickhouse_events {
134 self.flush_clickhouse_events();
135 }
136 }
137
138 /// This method takes the entire TelemetrySettings struct in order to force client code
139 /// to pull the struct out of the settings global. Do not remove!
140 pub fn set_authenticated_user_info(
141 self: &Arc<Self>,
142 metrics_id: Option<String>,
143 is_staff: bool,
144 cx: &AppContext,
145 ) {
146 if !settings::get::<TelemetrySettings>(cx).metrics {
147 return;
148 }
149
150 let mut state = self.state.lock();
151 let metrics_id: Option<Arc<str>> = metrics_id.map(|id| id.into());
152 state.metrics_id = metrics_id.clone();
153 state.is_staff = Some(is_staff);
154 drop(state);
155 }
156
157 pub fn report_clickhouse_event(
158 self: &Arc<Self>,
159 event: ClickhouseEvent,
160 telemetry_settings: TelemetrySettings,
161 ) {
162 if !telemetry_settings.metrics {
163 return;
164 }
165
166 let mut state = self.state.lock();
167 let signed_in = state.metrics_id.is_some();
168 state
169 .clickhouse_events_queue
170 .push(ClickhouseEventWrapper { signed_in, event });
171
172 if state.installation_id.is_some() {
173 if state.clickhouse_events_queue.len() >= MAX_QUEUE_LEN {
174 drop(state);
175 self.flush_clickhouse_events();
176 } else {
177 let this = self.clone();
178 let executor = self.executor.clone();
179 state.flush_clickhouse_events_task = Some(self.executor.spawn(async move {
180 executor.timer(DEBOUNCE_INTERVAL).await;
181 this.flush_clickhouse_events();
182 }));
183 }
184 }
185 }
186
187 pub fn metrics_id(self: &Arc<Self>) -> Option<Arc<str>> {
188 self.state.lock().metrics_id.clone()
189 }
190
191 pub fn installation_id(self: &Arc<Self>) -> Option<Arc<str>> {
192 self.state.lock().installation_id.clone()
193 }
194
195 pub fn is_staff(self: &Arc<Self>) -> Option<bool> {
196 self.state.lock().is_staff
197 }
198
199 fn flush_clickhouse_events(self: &Arc<Self>) {
200 let mut state = self.state.lock();
201 let mut events = mem::take(&mut state.clickhouse_events_queue);
202 state.flush_clickhouse_events_task.take();
203 drop(state);
204
205 let this = self.clone();
206 self.executor
207 .spawn(
208 async move {
209 let mut json_bytes = Vec::new();
210
211 if let Some(file) = &mut this.state.lock().log_file {
212 let file = file.as_file_mut();
213 for event in &mut events {
214 json_bytes.clear();
215 serde_json::to_writer(&mut json_bytes, event)?;
216 file.write_all(&json_bytes)?;
217 file.write(b"\n")?;
218 }
219 }
220
221 {
222 let state = this.state.lock();
223 json_bytes.clear();
224 serde_json::to_writer(
225 &mut json_bytes,
226 &ClickhouseEventRequestBody {
227 token: ZED_SECRET_CLIENT_TOKEN,
228 installation_id: state.installation_id.clone(),
229 is_staff: state.is_staff.clone(),
230 app_version: state.app_version.clone(),
231 os_name: state.os_name,
232 os_version: state.os_version.clone(),
233 architecture: state.architecture,
234
235 release_channel: state.release_channel,
236 events,
237 },
238 )?;
239 }
240
241 this.http_client
242 .post_json(CLICKHOUSE_EVENTS_URL.as_str(), json_bytes.into())
243 .await?;
244 anyhow::Ok(())
245 }
246 .log_err(),
247 )
248 .detach();
249 }
250}