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