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