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 },
78}
79
80#[cfg(debug_assertions)]
81const MAX_QUEUE_LEN: usize = 1;
82
83#[cfg(not(debug_assertions))]
84const MAX_QUEUE_LEN: usize = 10;
85
86#[cfg(debug_assertions)]
87const DEBOUNCE_INTERVAL: Duration = Duration::from_secs(1);
88
89#[cfg(not(debug_assertions))]
90const DEBOUNCE_INTERVAL: Duration = Duration::from_secs(30);
91
92impl Telemetry {
93 pub fn new(client: Arc<dyn HttpClient>, cx: &AppContext) -> Arc<Self> {
94 let platform = cx.platform();
95 let release_channel = if cx.has_global::<ReleaseChannel>() {
96 Some(cx.global::<ReleaseChannel>().display_name())
97 } else {
98 None
99 };
100 // TODO: Replace all hardware stuff with nested SystemSpecs json
101 let this = Arc::new(Self {
102 http_client: client,
103 executor: cx.background().clone(),
104 state: Mutex::new(TelemetryState {
105 os_name: platform.os_name().into(),
106 os_version: platform.os_version().ok().map(|v| v.to_string().into()),
107 architecture: env::consts::ARCH,
108 app_version: platform.app_version().ok().map(|v| v.to_string().into()),
109 release_channel,
110 installation_id: None,
111 metrics_id: None,
112 clickhouse_events_queue: Default::default(),
113 flush_clickhouse_events_task: Default::default(),
114 log_file: None,
115 is_staff: None,
116 }),
117 });
118
119 this
120 }
121
122 pub fn log_file_path(&self) -> Option<PathBuf> {
123 Some(self.state.lock().log_file.as_ref()?.path().to_path_buf())
124 }
125
126 pub fn start(self: &Arc<Self>, installation_id: Option<String>) {
127 let mut state = self.state.lock();
128 state.installation_id = installation_id.map(|id| id.into());
129 let has_clickhouse_events = !state.clickhouse_events_queue.is_empty();
130 drop(state);
131
132 if has_clickhouse_events {
133 self.flush_clickhouse_events();
134 }
135 }
136
137 /// This method takes the entire TelemetrySettings struct in order to force client code
138 /// to pull the struct out of the settings global. Do not remove!
139 pub fn set_authenticated_user_info(
140 self: &Arc<Self>,
141 metrics_id: Option<String>,
142 is_staff: bool,
143 cx: &AppContext,
144 ) {
145 if !settings::get::<TelemetrySettings>(cx).metrics {
146 return;
147 }
148
149 let mut state = self.state.lock();
150 let metrics_id: Option<Arc<str>> = metrics_id.map(|id| id.into());
151 state.metrics_id = metrics_id.clone();
152 state.is_staff = Some(is_staff);
153 drop(state);
154 }
155
156 pub fn report_clickhouse_event(
157 self: &Arc<Self>,
158 event: ClickhouseEvent,
159 telemetry_settings: TelemetrySettings,
160 ) {
161 if !telemetry_settings.metrics {
162 return;
163 }
164
165 let mut state = self.state.lock();
166 let signed_in = state.metrics_id.is_some();
167 state
168 .clickhouse_events_queue
169 .push(ClickhouseEventWrapper { signed_in, event });
170
171 if state.installation_id.is_some() {
172 if state.clickhouse_events_queue.len() >= MAX_QUEUE_LEN {
173 drop(state);
174 self.flush_clickhouse_events();
175 } else {
176 let this = self.clone();
177 let executor = self.executor.clone();
178 state.flush_clickhouse_events_task = Some(self.executor.spawn(async move {
179 executor.timer(DEBOUNCE_INTERVAL).await;
180 this.flush_clickhouse_events();
181 }));
182 }
183 }
184 }
185
186 pub fn metrics_id(self: &Arc<Self>) -> Option<Arc<str>> {
187 self.state.lock().metrics_id.clone()
188 }
189
190 pub fn installation_id(self: &Arc<Self>) -> Option<Arc<str>> {
191 self.state.lock().installation_id.clone()
192 }
193
194 pub fn is_staff(self: &Arc<Self>) -> Option<bool> {
195 self.state.lock().is_staff
196 }
197
198 fn flush_clickhouse_events(self: &Arc<Self>) {
199 let mut state = self.state.lock();
200 let mut events = mem::take(&mut state.clickhouse_events_queue);
201 state.flush_clickhouse_events_task.take();
202 drop(state);
203
204 let this = self.clone();
205 self.executor
206 .spawn(
207 async move {
208 let mut json_bytes = Vec::new();
209
210 if let Some(file) = &mut this.state.lock().log_file {
211 let file = file.as_file_mut();
212 for event in &mut events {
213 json_bytes.clear();
214 serde_json::to_writer(&mut json_bytes, event)?;
215 file.write_all(&json_bytes)?;
216 file.write(b"\n")?;
217 }
218 }
219
220 {
221 let state = this.state.lock();
222 json_bytes.clear();
223 serde_json::to_writer(
224 &mut json_bytes,
225 &ClickhouseEventRequestBody {
226 token: ZED_SECRET_CLIENT_TOKEN,
227 installation_id: state.installation_id.clone(),
228 is_staff: state.is_staff.clone(),
229 app_version: state.app_version.clone(),
230 os_name: state.os_name,
231 os_version: state.os_version.clone(),
232 architecture: state.architecture,
233
234 release_channel: state.release_channel,
235 events,
236 },
237 )?;
238 }
239
240 this.http_client
241 .post_json(CLICKHOUSE_EVENTS_URL.as_str(), json_bytes.into())
242 .await?;
243 anyhow::Ok(())
244 }
245 .log_err(),
246 )
247 .detach();
248 }
249}