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