1mod event_coalescer;
2
3use crate::TelemetrySettings;
4use anyhow::Result;
5use clock::SystemClock;
6use futures::channel::mpsc;
7use futures::{Future, FutureExt, StreamExt};
8use gpui::{App, AppContext as _, BackgroundExecutor, Task};
9use http_client::{self, AsyncBody, HttpClient, HttpClientWithUrl, Method, Request};
10use parking_lot::Mutex;
11use regex::Regex;
12use release_channel::ReleaseChannel;
13use settings::{Settings, SettingsStore};
14use sha2::{Digest, Sha256};
15use std::collections::HashSet;
16use std::fs::File;
17use std::io::Write;
18use std::sync::LazyLock;
19use std::time::Instant;
20use std::{env, mem, path::PathBuf, sync::Arc, time::Duration};
21use telemetry_events::{AssistantEventData, AssistantPhase, Event, EventRequestBody, EventWrapper};
22use util::{ResultExt, TryFutureExt};
23use worktree::{UpdatedEntriesSet, WorktreeId};
24
25use self::event_coalescer::EventCoalescer;
26
27pub struct Telemetry {
28 clock: Arc<dyn SystemClock>,
29 http_client: Arc<HttpClientWithUrl>,
30 executor: BackgroundExecutor,
31 state: Arc<Mutex<TelemetryState>>,
32}
33
34struct TelemetryState {
35 settings: TelemetrySettings,
36 system_id: Option<Arc<str>>, // Per system
37 installation_id: Option<Arc<str>>, // Per app installation (different for dev, nightly, preview, and stable)
38 session_id: Option<String>, // Per app launch
39 metrics_id: Option<Arc<str>>, // Per logged-in user
40 release_channel: Option<&'static str>,
41 architecture: &'static str,
42 events_queue: Vec<EventWrapper>,
43 flush_events_task: Option<Task<()>>,
44 log_file: Option<File>,
45 is_staff: Option<bool>,
46 first_event_date_time: Option<Instant>,
47 event_coalescer: EventCoalescer,
48 max_queue_size: usize,
49 worktrees_with_project_type_events_sent: HashSet<WorktreeId>,
50
51 os_name: String,
52 app_version: String,
53 os_version: Option<String>,
54}
55
56#[cfg(debug_assertions)]
57const MAX_QUEUE_LEN: usize = 5;
58
59#[cfg(not(debug_assertions))]
60const MAX_QUEUE_LEN: usize = 50;
61
62#[cfg(debug_assertions)]
63const FLUSH_INTERVAL: Duration = Duration::from_secs(1);
64
65#[cfg(not(debug_assertions))]
66const FLUSH_INTERVAL: Duration = Duration::from_secs(60 * 5);
67static ZED_CLIENT_CHECKSUM_SEED: LazyLock<Option<Vec<u8>>> = LazyLock::new(|| {
68 option_env!("ZED_CLIENT_CHECKSUM_SEED")
69 .map(|s| s.as_bytes().into())
70 .or_else(|| {
71 env::var("ZED_CLIENT_CHECKSUM_SEED")
72 .ok()
73 .map(|s| s.as_bytes().into())
74 })
75});
76
77static DOTNET_PROJECT_FILES_REGEX: LazyLock<Regex> = LazyLock::new(|| {
78 Regex::new(r"^(global\.json|Directory\.Build\.props|.*\.(csproj|fsproj|vbproj|sln))$").unwrap()
79});
80
81pub fn os_name() -> String {
82 #[cfg(target_os = "macos")]
83 {
84 "macOS".to_string()
85 }
86 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
87 {
88 format!("Linux {}", gpui::guess_compositor())
89 }
90
91 #[cfg(target_os = "windows")]
92 {
93 "Windows".to_string()
94 }
95}
96
97/// Note: This might do blocking IO! Only call from background threads
98pub fn os_version() -> String {
99 #[cfg(target_os = "macos")]
100 {
101 use cocoa::base::nil;
102 use cocoa::foundation::NSProcessInfo;
103
104 unsafe {
105 let process_info = cocoa::foundation::NSProcessInfo::processInfo(nil);
106 let version = process_info.operatingSystemVersion();
107 gpui::SemanticVersion::new(
108 version.majorVersion as usize,
109 version.minorVersion as usize,
110 version.patchVersion as usize,
111 )
112 .to_string()
113 }
114 }
115 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
116 {
117 use std::path::Path;
118
119 let content = if let Ok(file) = std::fs::read_to_string(&Path::new("/etc/os-release")) {
120 file
121 } else if let Ok(file) = std::fs::read_to_string(&Path::new("/usr/lib/os-release")) {
122 file
123 } else {
124 log::error!("Failed to load /etc/os-release, /usr/lib/os-release");
125 "".to_string()
126 };
127 let mut name = "unknown";
128 let mut version = "unknown";
129
130 for line in content.lines() {
131 match line.split_once('=') {
132 Some(("ID", val)) => name = val.trim_matches('"'),
133 Some(("VERSION_ID", val)) => version = val.trim_matches('"'),
134 _ => {}
135 }
136 }
137
138 format!("{} {}", name, version)
139 }
140
141 #[cfg(target_os = "windows")]
142 {
143 let mut info = unsafe { std::mem::zeroed() };
144 let status = unsafe { windows::Wdk::System::SystemServices::RtlGetVersion(&mut info) };
145 if status.is_ok() {
146 gpui::SemanticVersion::new(
147 info.dwMajorVersion as _,
148 info.dwMinorVersion as _,
149 info.dwBuildNumber as _,
150 )
151 .to_string()
152 } else {
153 "unknown".to_string()
154 }
155 }
156}
157
158impl Telemetry {
159 pub fn new(
160 clock: Arc<dyn SystemClock>,
161 client: Arc<HttpClientWithUrl>,
162 cx: &mut App,
163 ) -> Arc<Self> {
164 let release_channel =
165 ReleaseChannel::try_global(cx).map(|release_channel| release_channel.display_name());
166
167 TelemetrySettings::register(cx);
168
169 let state = Arc::new(Mutex::new(TelemetryState {
170 settings: *TelemetrySettings::get_global(cx),
171 architecture: env::consts::ARCH,
172 release_channel,
173 system_id: None,
174 installation_id: None,
175 session_id: None,
176 metrics_id: None,
177 events_queue: Vec::new(),
178 flush_events_task: None,
179 log_file: None,
180 is_staff: None,
181 first_event_date_time: None,
182 event_coalescer: EventCoalescer::new(clock.clone()),
183 max_queue_size: MAX_QUEUE_LEN,
184 worktrees_with_project_type_events_sent: HashSet::new(),
185
186 os_version: None,
187 os_name: os_name(),
188 app_version: release_channel::AppVersion::global(cx).to_string(),
189 }));
190 Self::log_file_path();
191
192 cx.background_spawn({
193 let state = state.clone();
194 let os_version = os_version();
195 state.lock().os_version = Some(os_version);
196 async move {
197 if let Some(tempfile) = File::create(Self::log_file_path()).log_err() {
198 state.lock().log_file = Some(tempfile);
199 }
200 }
201 })
202 .detach();
203
204 cx.observe_global::<SettingsStore>({
205 let state = state.clone();
206
207 move |cx| {
208 let mut state = state.lock();
209 state.settings = *TelemetrySettings::get_global(cx);
210 }
211 })
212 .detach();
213
214 let this = Arc::new(Self {
215 clock,
216 http_client: client,
217 executor: cx.background_executor().clone(),
218 state,
219 });
220
221 let (tx, mut rx) = mpsc::unbounded();
222 ::telemetry::init(tx);
223
224 cx.background_spawn({
225 let this = Arc::downgrade(&this);
226 async move {
227 while let Some(event) = rx.next().await {
228 let Some(state) = this.upgrade() else { break };
229 state.report_event(Event::Flexible(event))
230 }
231 }
232 })
233 .detach();
234
235 // We should only ever have one instance of Telemetry, leak the subscription to keep it alive
236 // rather than store in TelemetryState, complicating spawn as subscriptions are not Send
237 std::mem::forget(cx.on_app_quit({
238 let this = this.clone();
239 move |_| this.shutdown_telemetry()
240 }));
241
242 this
243 }
244
245 #[cfg(any(test, feature = "test-support"))]
246 fn shutdown_telemetry(self: &Arc<Self>) -> impl Future<Output = ()> + use<> {
247 Task::ready(())
248 }
249
250 // Skip calling this function in tests.
251 // TestAppContext ends up calling this function on shutdown and it panics when trying to find the TelemetrySettings
252 #[cfg(not(any(test, feature = "test-support")))]
253 fn shutdown_telemetry(self: &Arc<Self>) -> impl Future<Output = ()> + use<> {
254 telemetry::event!("App Closed");
255 // TODO: close final edit period and make sure it's sent
256 Task::ready(())
257 }
258
259 pub fn log_file_path() -> PathBuf {
260 paths::logs_dir().join("telemetry.log")
261 }
262
263 pub fn has_checksum_seed(&self) -> bool {
264 ZED_CLIENT_CHECKSUM_SEED.is_some()
265 }
266
267 pub fn start(
268 self: &Arc<Self>,
269 system_id: Option<String>,
270 installation_id: Option<String>,
271 session_id: String,
272 cx: &App,
273 ) {
274 let mut state = self.state.lock();
275 state.system_id = system_id.map(|id| id.into());
276 state.installation_id = installation_id.map(|id| id.into());
277 state.session_id = Some(session_id);
278 state.app_version = release_channel::AppVersion::global(cx).to_string();
279 state.os_name = os_name();
280 }
281
282 pub fn metrics_enabled(self: &Arc<Self>) -> bool {
283 let state = self.state.lock();
284 let enabled = state.settings.metrics;
285 drop(state);
286 enabled
287 }
288
289 pub fn set_authenticated_user_info(
290 self: &Arc<Self>,
291 metrics_id: Option<String>,
292 is_staff: bool,
293 ) {
294 let mut state = self.state.lock();
295
296 if !state.settings.metrics {
297 return;
298 }
299
300 let metrics_id: Option<Arc<str>> = metrics_id.map(|id| id.into());
301 state.metrics_id.clone_from(&metrics_id);
302 state.is_staff = Some(is_staff);
303 drop(state);
304 }
305
306 pub fn report_assistant_event(self: &Arc<Self>, event: AssistantEventData) {
307 let event_type = match event.phase {
308 AssistantPhase::Response => "Assistant Responded",
309 AssistantPhase::Invoked => "Assistant Invoked",
310 AssistantPhase::Accepted => "Assistant Response Accepted",
311 AssistantPhase::Rejected => "Assistant Response Rejected",
312 };
313
314 telemetry::event!(
315 event_type,
316 conversation_id = event.conversation_id,
317 kind = event.kind,
318 phase = event.phase,
319 message_id = event.message_id,
320 model = event.model,
321 model_provider = event.model_provider,
322 response_latency = event.response_latency,
323 error_message = event.error_message,
324 language_name = event.language_name,
325 );
326 }
327
328 pub fn log_edit_event(self: &Arc<Self>, environment: &'static str, is_via_ssh: bool) {
329 let mut state = self.state.lock();
330 let period_data = state.event_coalescer.log_event(environment);
331 drop(state);
332
333 if let Some((start, end, environment)) = period_data {
334 let duration = end
335 .saturating_duration_since(start)
336 .min(Duration::from_secs(60 * 60 * 24))
337 .as_millis() as i64;
338
339 telemetry::event!(
340 "Editor Edited",
341 duration = duration,
342 environment = environment,
343 is_via_ssh = is_via_ssh
344 );
345 }
346 }
347
348 pub fn report_discovered_project_type_events(
349 self: &Arc<Self>,
350 worktree_id: WorktreeId,
351 updated_entries_set: &UpdatedEntriesSet,
352 ) {
353 let Some(project_type_names) = self.detect_project_types(worktree_id, updated_entries_set)
354 else {
355 return;
356 };
357
358 for project_type_name in project_type_names {
359 telemetry::event!("Project Opened", project_type = project_type_name);
360 }
361 }
362
363 fn detect_project_types(
364 self: &Arc<Self>,
365 worktree_id: WorktreeId,
366 updated_entries_set: &UpdatedEntriesSet,
367 ) -> Option<Vec<String>> {
368 let mut state = self.state.lock();
369
370 if state
371 .worktrees_with_project_type_events_sent
372 .contains(&worktree_id)
373 {
374 return None;
375 }
376
377 let mut project_types: HashSet<String> = HashSet::new();
378
379 for (path, _, _) in updated_entries_set.iter() {
380 let Some(file_name) = path.file_name().and_then(|f| f.to_str()) else {
381 continue;
382 };
383
384 if file_name == "pnpm-lock.yaml" {
385 project_types.insert("pnpm".to_string());
386 } else if file_name == "yarn.lock" {
387 project_types.insert("yarn".to_string());
388 } else if file_name == "package.json" {
389 project_types.insert("node".to_string());
390 } else if DOTNET_PROJECT_FILES_REGEX.is_match(file_name) {
391 project_types.insert("dotnet".to_string());
392 }
393 }
394
395 if !project_types.is_empty() {
396 state
397 .worktrees_with_project_type_events_sent
398 .insert(worktree_id);
399 }
400
401 let mut project_names_vec: Vec<String> = project_types.into_iter().collect();
402 project_names_vec.sort();
403 Some(project_names_vec)
404 }
405
406 fn report_event(self: &Arc<Self>, event: Event) {
407 let mut state = self.state.lock();
408 // RUST_LOG=telemetry=trace to debug telemetry events
409 log::trace!(target: "telemetry", "{:?}", event);
410
411 if !state.settings.metrics {
412 return;
413 }
414
415 if state.flush_events_task.is_none() {
416 let this = self.clone();
417 state.flush_events_task = Some(self.executor.spawn(async move {
418 this.executor.timer(FLUSH_INTERVAL).await;
419 this.flush_events().detach();
420 }));
421 }
422
423 let date_time = self.clock.utc_now();
424
425 let milliseconds_since_first_event = match state.first_event_date_time {
426 Some(first_event_date_time) => date_time
427 .saturating_duration_since(first_event_date_time)
428 .min(Duration::from_secs(60 * 60 * 24))
429 .as_millis() as i64,
430 None => {
431 state.first_event_date_time = Some(date_time);
432 0
433 }
434 };
435
436 let signed_in = state.metrics_id.is_some();
437 state.events_queue.push(EventWrapper {
438 signed_in,
439 milliseconds_since_first_event,
440 event,
441 });
442
443 if state.installation_id.is_some() && state.events_queue.len() >= state.max_queue_size {
444 drop(state);
445 self.flush_events().detach();
446 }
447 }
448
449 pub fn metrics_id(self: &Arc<Self>) -> Option<Arc<str>> {
450 self.state.lock().metrics_id.clone()
451 }
452
453 pub fn system_id(self: &Arc<Self>) -> Option<Arc<str>> {
454 self.state.lock().system_id.clone()
455 }
456
457 pub fn installation_id(self: &Arc<Self>) -> Option<Arc<str>> {
458 self.state.lock().installation_id.clone()
459 }
460
461 pub fn is_staff(self: &Arc<Self>) -> Option<bool> {
462 self.state.lock().is_staff
463 }
464
465 fn build_request(
466 self: &Arc<Self>,
467 // We take in the JSON bytes buffer so we can reuse the existing allocation.
468 mut json_bytes: Vec<u8>,
469 event_request: &EventRequestBody,
470 ) -> Result<Request<AsyncBody>> {
471 json_bytes.clear();
472 serde_json::to_writer(&mut json_bytes, event_request)?;
473
474 let checksum = calculate_json_checksum(&json_bytes).unwrap_or_default();
475
476 Ok(Request::builder()
477 .method(Method::POST)
478 .uri(
479 self.http_client
480 .build_zed_api_url("/telemetry/events", &[])?
481 .as_ref(),
482 )
483 .header("Content-Type", "application/json")
484 .header("x-zed-checksum", checksum)
485 .body(json_bytes.into())?)
486 }
487
488 pub fn flush_events(self: &Arc<Self>) -> Task<()> {
489 let mut state = self.state.lock();
490 state.first_event_date_time = None;
491 let events = mem::take(&mut state.events_queue);
492 state.flush_events_task.take();
493 drop(state);
494 if events.is_empty() {
495 return Task::ready(());
496 }
497
498 let this = self.clone();
499 self.executor.spawn(
500 async move {
501 let mut json_bytes = Vec::new();
502
503 if let Some(file) = &mut this.state.lock().log_file {
504 for event in &events {
505 json_bytes.clear();
506 serde_json::to_writer(&mut json_bytes, event)?;
507 file.write_all(&json_bytes)?;
508 file.write_all(b"\n")?;
509 }
510 }
511
512 let request_body = {
513 let state = this.state.lock();
514
515 EventRequestBody {
516 system_id: state.system_id.as_deref().map(Into::into),
517 installation_id: state.installation_id.as_deref().map(Into::into),
518 session_id: state.session_id.clone(),
519 metrics_id: state.metrics_id.as_deref().map(Into::into),
520 is_staff: state.is_staff,
521 app_version: state.app_version.clone(),
522 os_name: state.os_name.clone(),
523 os_version: state.os_version.clone(),
524 architecture: state.architecture.to_string(),
525
526 release_channel: state.release_channel.map(Into::into),
527 events,
528 }
529 };
530
531 let request = this.build_request(json_bytes, &request_body)?;
532 let response = this.http_client.send(request).await?;
533 if response.status() != 200 {
534 log::error!("Failed to send events: HTTP {:?}", response.status());
535 }
536 anyhow::Ok(())
537 }
538 .log_err()
539 .map(|_| ()),
540 )
541 }
542}
543
544pub fn calculate_json_checksum(json: &impl AsRef<[u8]>) -> Option<String> {
545 let Some(checksum_seed) = &*ZED_CLIENT_CHECKSUM_SEED else {
546 return None;
547 };
548
549 let mut summer = Sha256::new();
550 summer.update(checksum_seed);
551 summer.update(json);
552 summer.update(checksum_seed);
553 let mut checksum = String::new();
554 for byte in summer.finalize().as_slice() {
555 use std::fmt::Write;
556 write!(&mut checksum, "{:02x}", byte).unwrap();
557 }
558
559 Some(checksum)
560}
561
562#[cfg(test)]
563mod tests {
564 use super::*;
565 use clock::FakeSystemClock;
566 use gpui::TestAppContext;
567 use http_client::FakeHttpClient;
568 use std::collections::HashMap;
569 use telemetry_events::FlexibleEvent;
570 use worktree::{PathChange, ProjectEntryId, WorktreeId};
571
572 #[gpui::test]
573 fn test_telemetry_flush_on_max_queue_size(cx: &mut TestAppContext) {
574 init_test(cx);
575 let clock = Arc::new(FakeSystemClock::new());
576 let http = FakeHttpClient::with_200_response();
577 let system_id = Some("system_id".to_string());
578 let installation_id = Some("installation_id".to_string());
579 let session_id = "session_id".to_string();
580
581 cx.update(|cx| {
582 let telemetry = Telemetry::new(clock.clone(), http, cx);
583
584 telemetry.state.lock().max_queue_size = 4;
585 telemetry.start(system_id, installation_id, session_id, cx);
586
587 assert!(is_empty_state(&telemetry));
588
589 let first_date_time = clock.utc_now();
590 let event_properties = HashMap::from_iter([(
591 "test_key".to_string(),
592 serde_json::Value::String("test_value".to_string()),
593 )]);
594
595 let event = FlexibleEvent {
596 event_type: "test".to_string(),
597 event_properties,
598 };
599
600 telemetry.report_event(Event::Flexible(event.clone()));
601 assert_eq!(telemetry.state.lock().events_queue.len(), 1);
602 assert!(telemetry.state.lock().flush_events_task.is_some());
603 assert_eq!(
604 telemetry.state.lock().first_event_date_time,
605 Some(first_date_time)
606 );
607
608 clock.advance(Duration::from_millis(100));
609
610 telemetry.report_event(Event::Flexible(event.clone()));
611 assert_eq!(telemetry.state.lock().events_queue.len(), 2);
612 assert!(telemetry.state.lock().flush_events_task.is_some());
613 assert_eq!(
614 telemetry.state.lock().first_event_date_time,
615 Some(first_date_time)
616 );
617
618 clock.advance(Duration::from_millis(100));
619
620 telemetry.report_event(Event::Flexible(event.clone()));
621 assert_eq!(telemetry.state.lock().events_queue.len(), 3);
622 assert!(telemetry.state.lock().flush_events_task.is_some());
623 assert_eq!(
624 telemetry.state.lock().first_event_date_time,
625 Some(first_date_time)
626 );
627
628 clock.advance(Duration::from_millis(100));
629
630 // Adding a 4th event should cause a flush
631 telemetry.report_event(Event::Flexible(event));
632 assert!(is_empty_state(&telemetry));
633 });
634 }
635
636 #[gpui::test]
637 async fn test_telemetry_flush_on_flush_interval(
638 executor: BackgroundExecutor,
639 cx: &mut TestAppContext,
640 ) {
641 init_test(cx);
642 let clock = Arc::new(FakeSystemClock::new());
643 let http = FakeHttpClient::with_200_response();
644 let system_id = Some("system_id".to_string());
645 let installation_id = Some("installation_id".to_string());
646 let session_id = "session_id".to_string();
647
648 cx.update(|cx| {
649 let telemetry = Telemetry::new(clock.clone(), http, cx);
650 telemetry.state.lock().max_queue_size = 4;
651 telemetry.start(system_id, installation_id, session_id, cx);
652
653 assert!(is_empty_state(&telemetry));
654 let first_date_time = clock.utc_now();
655
656 let event_properties = HashMap::from_iter([(
657 "test_key".to_string(),
658 serde_json::Value::String("test_value".to_string()),
659 )]);
660
661 let event = FlexibleEvent {
662 event_type: "test".to_string(),
663 event_properties,
664 };
665
666 telemetry.report_event(Event::Flexible(event));
667 assert_eq!(telemetry.state.lock().events_queue.len(), 1);
668 assert!(telemetry.state.lock().flush_events_task.is_some());
669 assert_eq!(
670 telemetry.state.lock().first_event_date_time,
671 Some(first_date_time)
672 );
673
674 let duration = Duration::from_millis(1);
675
676 // Test 1 millisecond before the flush interval limit is met
677 executor.advance_clock(FLUSH_INTERVAL - duration);
678
679 assert!(!is_empty_state(&telemetry));
680
681 // Test the exact moment the flush interval limit is met
682 executor.advance_clock(duration);
683
684 assert!(is_empty_state(&telemetry));
685 });
686 }
687
688 #[gpui::test]
689 fn test_project_discovery_does_not_double_report(cx: &mut gpui::TestAppContext) {
690 init_test(cx);
691
692 let clock = Arc::new(FakeSystemClock::new());
693 let http = FakeHttpClient::with_200_response();
694 let telemetry = cx.update(|cx| Telemetry::new(clock.clone(), http, cx));
695 let worktree_id = 1;
696
697 // Scan of empty worktree finds nothing
698 test_project_discovery_helper(telemetry.clone(), vec![], Some(vec![]), worktree_id);
699
700 // Files added, second scan of worktree 1 finds project type
701 test_project_discovery_helper(
702 telemetry.clone(),
703 vec!["package.json"],
704 Some(vec!["node"]),
705 worktree_id,
706 );
707
708 // Third scan of worktree does not double report, as we already reported
709 test_project_discovery_helper(telemetry.clone(), vec!["package.json"], None, worktree_id);
710 }
711
712 #[gpui::test]
713 fn test_pnpm_project_discovery(cx: &mut gpui::TestAppContext) {
714 init_test(cx);
715
716 let clock = Arc::new(FakeSystemClock::new());
717 let http = FakeHttpClient::with_200_response();
718 let telemetry = cx.update(|cx| Telemetry::new(clock.clone(), http, cx));
719
720 test_project_discovery_helper(
721 telemetry.clone(),
722 vec!["package.json", "pnpm-lock.yaml"],
723 Some(vec!["node", "pnpm"]),
724 1,
725 );
726 }
727
728 #[gpui::test]
729 fn test_yarn_project_discovery(cx: &mut gpui::TestAppContext) {
730 init_test(cx);
731
732 let clock = Arc::new(FakeSystemClock::new());
733 let http = FakeHttpClient::with_200_response();
734 let telemetry = cx.update(|cx| Telemetry::new(clock.clone(), http, cx));
735
736 test_project_discovery_helper(
737 telemetry.clone(),
738 vec!["package.json", "yarn.lock"],
739 Some(vec!["node", "yarn"]),
740 1,
741 );
742 }
743
744 #[gpui::test]
745 fn test_dotnet_project_discovery(cx: &mut gpui::TestAppContext) {
746 init_test(cx);
747
748 let clock = Arc::new(FakeSystemClock::new());
749 let http = FakeHttpClient::with_200_response();
750 let telemetry = cx.update(|cx| Telemetry::new(clock.clone(), http, cx));
751
752 // Using different worktrees, as production code blocks from reporting a
753 // project type for the same worktree multiple times
754
755 test_project_discovery_helper(
756 telemetry.clone().clone(),
757 vec!["global.json"],
758 Some(vec!["dotnet"]),
759 1,
760 );
761 test_project_discovery_helper(
762 telemetry.clone(),
763 vec!["Directory.Build.props"],
764 Some(vec!["dotnet"]),
765 2,
766 );
767 test_project_discovery_helper(
768 telemetry.clone(),
769 vec!["file.csproj"],
770 Some(vec!["dotnet"]),
771 3,
772 );
773 test_project_discovery_helper(
774 telemetry.clone(),
775 vec!["file.fsproj"],
776 Some(vec!["dotnet"]),
777 4,
778 );
779 test_project_discovery_helper(
780 telemetry.clone(),
781 vec!["file.vbproj"],
782 Some(vec!["dotnet"]),
783 5,
784 );
785 test_project_discovery_helper(telemetry.clone(), vec!["file.sln"], Some(vec!["dotnet"]), 6);
786
787 // Each worktree should only send a single project type event, even when
788 // encountering multiple files associated with that project type
789 test_project_discovery_helper(
790 telemetry,
791 vec!["global.json", "Directory.Build.props"],
792 Some(vec!["dotnet"]),
793 7,
794 );
795 }
796
797 // TODO:
798 // Test settings
799 // Update FakeHTTPClient to keep track of the number of requests and assert on it
800
801 fn init_test(cx: &mut TestAppContext) {
802 cx.update(|cx| {
803 let settings_store = SettingsStore::test(cx);
804 cx.set_global(settings_store);
805 });
806 }
807
808 fn is_empty_state(telemetry: &Telemetry) -> bool {
809 telemetry.state.lock().events_queue.is_empty()
810 && telemetry.state.lock().flush_events_task.is_none()
811 && telemetry.state.lock().first_event_date_time.is_none()
812 }
813
814 fn test_project_discovery_helper(
815 telemetry: Arc<Telemetry>,
816 file_paths: Vec<&str>,
817 expected_project_types: Option<Vec<&str>>,
818 worktree_id_num: usize,
819 ) {
820 let worktree_id = WorktreeId::from_usize(worktree_id_num);
821 let entries: Vec<_> = file_paths
822 .into_iter()
823 .enumerate()
824 .map(|(i, path)| {
825 (
826 Arc::from(std::path::Path::new(path)),
827 ProjectEntryId::from_proto(i as u64 + 1),
828 PathChange::Added,
829 )
830 })
831 .collect();
832 let updated_entries: UpdatedEntriesSet = Arc::from(entries.as_slice());
833
834 let detected_project_types = telemetry.detect_project_types(worktree_id, &updated_entries);
835
836 let expected_project_types =
837 expected_project_types.map(|types| types.iter().map(|&t| t.to_string()).collect());
838
839 assert_eq!(detected_project_types, expected_project_types);
840 }
841}