1use super::ips_file::IpsFile;
2use crate::{api::slack, AppState, Error, Result};
3use anyhow::{anyhow, Context};
4use aws_sdk_s3::primitives::ByteStream;
5use axum::{
6 body::Bytes,
7 headers::Header,
8 http::{HeaderMap, HeaderName, StatusCode},
9 routing::post,
10 Extension, Router, TypedHeader,
11};
12use rpc::ExtensionMetadata;
13use semantic_version::SemanticVersion;
14use serde::{Serialize, Serializer};
15use sha2::{Digest, Sha256};
16use std::sync::{Arc, OnceLock};
17use telemetry_events::{
18 ActionEvent, AppEvent, AssistantEvent, CallEvent, CpuEvent, EditEvent, EditorEvent, Event,
19 EventRequestBody, EventWrapper, ExtensionEvent, InlineCompletionEvent, MemoryEvent,
20 SettingEvent,
21};
22use uuid::Uuid;
23
24static CRASH_REPORTS_BUCKET: &str = "zed-crash-reports";
25
26pub fn router() -> Router {
27 Router::new()
28 .route("/telemetry/events", post(post_events))
29 .route("/telemetry/crashes", post(post_crash))
30 .route("/telemetry/panics", post(post_panic))
31 .route("/telemetry/hangs", post(post_hang))
32}
33
34pub struct ZedChecksumHeader(Vec<u8>);
35
36impl Header for ZedChecksumHeader {
37 fn name() -> &'static HeaderName {
38 static ZED_CHECKSUM_HEADER: OnceLock<HeaderName> = OnceLock::new();
39 ZED_CHECKSUM_HEADER.get_or_init(|| HeaderName::from_static("x-zed-checksum"))
40 }
41
42 fn decode<'i, I>(values: &mut I) -> Result<Self, axum::headers::Error>
43 where
44 Self: Sized,
45 I: Iterator<Item = &'i axum::http::HeaderValue>,
46 {
47 let checksum = values
48 .next()
49 .ok_or_else(axum::headers::Error::invalid)?
50 .to_str()
51 .map_err(|_| axum::headers::Error::invalid())?;
52
53 let bytes = hex::decode(checksum).map_err(|_| axum::headers::Error::invalid())?;
54 Ok(Self(bytes))
55 }
56
57 fn encode<E: Extend<axum::http::HeaderValue>>(&self, _values: &mut E) {
58 unimplemented!()
59 }
60}
61
62pub struct CloudflareIpCountryHeader(String);
63
64impl Header for CloudflareIpCountryHeader {
65 fn name() -> &'static HeaderName {
66 static CLOUDFLARE_IP_COUNTRY_HEADER: OnceLock<HeaderName> = OnceLock::new();
67 CLOUDFLARE_IP_COUNTRY_HEADER.get_or_init(|| HeaderName::from_static("cf-ipcountry"))
68 }
69
70 fn decode<'i, I>(values: &mut I) -> Result<Self, axum::headers::Error>
71 where
72 Self: Sized,
73 I: Iterator<Item = &'i axum::http::HeaderValue>,
74 {
75 let country_code = values
76 .next()
77 .ok_or_else(axum::headers::Error::invalid)?
78 .to_str()
79 .map_err(|_| axum::headers::Error::invalid())?;
80
81 Ok(Self(country_code.to_string()))
82 }
83
84 fn encode<E: Extend<axum::http::HeaderValue>>(&self, _values: &mut E) {
85 unimplemented!()
86 }
87}
88
89pub async fn post_crash(
90 Extension(app): Extension<Arc<AppState>>,
91 headers: HeaderMap,
92 body: Bytes,
93) -> Result<()> {
94 let report = IpsFile::parse(&body)?;
95 let version_threshold = SemanticVersion::new(0, 123, 0);
96
97 let bundle_id = &report.header.bundle_id;
98 let app_version = &report.app_version();
99
100 if bundle_id == "dev.zed.Zed-Dev" {
101 log::error!("Crash uploads from {} are ignored.", bundle_id);
102 return Ok(());
103 }
104
105 if app_version.is_none() || app_version.unwrap() < version_threshold {
106 log::error!(
107 "Crash uploads from {} are ignored.",
108 report.header.app_version
109 );
110 return Ok(());
111 }
112 let app_version = app_version.unwrap();
113
114 if let Some(blob_store_client) = app.blob_store_client.as_ref() {
115 let response = blob_store_client
116 .head_object()
117 .bucket(CRASH_REPORTS_BUCKET)
118 .key(report.header.incident_id.clone() + ".ips")
119 .send()
120 .await;
121
122 if response.is_ok() {
123 log::info!("We've already uploaded this crash");
124 return Ok(());
125 }
126
127 blob_store_client
128 .put_object()
129 .bucket(CRASH_REPORTS_BUCKET)
130 .key(report.header.incident_id.clone() + ".ips")
131 .acl(aws_sdk_s3::types::ObjectCannedAcl::PublicRead)
132 .body(ByteStream::from(body.to_vec()))
133 .send()
134 .await
135 .map_err(|e| log::error!("Failed to upload crash: {}", e))
136 .ok();
137 }
138
139 let recent_panic_on: Option<i64> = headers
140 .get("x-zed-panicked-on")
141 .and_then(|h| h.to_str().ok())
142 .and_then(|s| s.parse().ok());
143
144 let installation_id = headers
145 .get("x-zed-installation-id")
146 .and_then(|h| h.to_str().ok())
147 .map(|s| s.to_string())
148 .unwrap_or_default();
149
150 let mut recent_panic = None;
151
152 if let Some(recent_panic_on) = recent_panic_on {
153 let crashed_at = match report.timestamp() {
154 Ok(t) => Some(t),
155 Err(e) => {
156 log::error!("Can't parse {}: {}", report.header.timestamp, e);
157 None
158 }
159 };
160 if crashed_at.is_some_and(|t| (t.timestamp_millis() - recent_panic_on).abs() <= 30000) {
161 recent_panic = headers.get("x-zed-panic").and_then(|h| h.to_str().ok());
162 }
163 }
164
165 let description = report.description(recent_panic);
166 let summary = report.backtrace_summary();
167
168 tracing::error!(
169 service = "client",
170 version = %report.header.app_version,
171 os_version = %report.header.os_version,
172 bundle_id = %report.header.bundle_id,
173 incident_id = %report.header.incident_id,
174 installation_id = %installation_id,
175 description = %description,
176 backtrace = %summary,
177 "crash report");
178
179 if let Some(slack_panics_webhook) = app.config.slack_panics_webhook.clone() {
180 let payload = slack::WebhookBody::new(|w| {
181 w.add_section(|s| s.text(slack::Text::markdown(description)))
182 .add_section(|s| {
183 s.add_field(slack::Text::markdown(format!(
184 "*Version:*\n{} ({})",
185 bundle_id, app_version
186 )))
187 .add_field({
188 let hostname = app.config.blob_store_url.clone().unwrap_or_default();
189 let hostname = hostname.strip_prefix("https://").unwrap_or_else(|| {
190 hostname.strip_prefix("http://").unwrap_or_default()
191 });
192
193 slack::Text::markdown(format!(
194 "*Incident:*\n<https://{}.{}/{}.ips|{}…>",
195 CRASH_REPORTS_BUCKET,
196 hostname,
197 report.header.incident_id,
198 report
199 .header
200 .incident_id
201 .chars()
202 .take(8)
203 .collect::<String>(),
204 ))
205 })
206 })
207 .add_rich_text(|r| r.add_preformatted(|p| p.add_text(summary)))
208 });
209 let payload_json = serde_json::to_string(&payload).map_err(|err| {
210 log::error!("Failed to serialize payload to JSON: {err}");
211 Error::Internal(anyhow!(err))
212 })?;
213
214 reqwest::Client::new()
215 .post(slack_panics_webhook)
216 .header("Content-Type", "application/json")
217 .body(payload_json)
218 .send()
219 .await
220 .map_err(|err| {
221 log::error!("Failed to send payload to Slack: {err}");
222 Error::Internal(anyhow!(err))
223 })?;
224 }
225
226 Ok(())
227}
228
229pub async fn post_hang(
230 Extension(app): Extension<Arc<AppState>>,
231 TypedHeader(ZedChecksumHeader(checksum)): TypedHeader<ZedChecksumHeader>,
232 body: Bytes,
233) -> Result<()> {
234 let Some(expected) = calculate_json_checksum(app.clone(), &body) else {
235 return Err(Error::Http(
236 StatusCode::INTERNAL_SERVER_ERROR,
237 "events not enabled".into(),
238 ))?;
239 };
240
241 if checksum != expected {
242 return Err(Error::Http(
243 StatusCode::BAD_REQUEST,
244 "invalid checksum".into(),
245 ))?;
246 }
247
248 let incident_id = Uuid::new_v4().to_string();
249
250 // dump JSON into S3 so we can get frame offsets if we need to.
251 if let Some(blob_store_client) = app.blob_store_client.as_ref() {
252 blob_store_client
253 .put_object()
254 .bucket(CRASH_REPORTS_BUCKET)
255 .key(incident_id.clone() + ".hang.json")
256 .acl(aws_sdk_s3::types::ObjectCannedAcl::PublicRead)
257 .body(ByteStream::from(body.to_vec()))
258 .send()
259 .await
260 .map_err(|e| log::error!("Failed to upload crash: {}", e))
261 .ok();
262 }
263
264 let report: telemetry_events::HangReport = serde_json::from_slice(&body).map_err(|err| {
265 log::error!("can't parse report json: {err}");
266 Error::Internal(anyhow!(err))
267 })?;
268
269 let mut backtrace = "Possible hang detected on main thread:".to_string();
270 let unknown = "<unknown>".to_string();
271 for frame in report.backtrace.iter() {
272 backtrace.push_str(&format!("\n{}", frame.symbols.first().unwrap_or(&unknown)));
273 }
274
275 tracing::error!(
276 service = "client",
277 version = %report.app_version.unwrap_or_default().to_string(),
278 os_name = %report.os_name,
279 os_version = report.os_version.unwrap_or_default().to_string(),
280 incident_id = %incident_id,
281 installation_id = %report.installation_id.unwrap_or_default(),
282 backtrace = %backtrace,
283 "hang report");
284
285 Ok(())
286}
287
288pub async fn post_panic(
289 Extension(app): Extension<Arc<AppState>>,
290 TypedHeader(ZedChecksumHeader(checksum)): TypedHeader<ZedChecksumHeader>,
291 body: Bytes,
292) -> Result<()> {
293 let Some(expected) = calculate_json_checksum(app.clone(), &body) else {
294 return Err(Error::Http(
295 StatusCode::INTERNAL_SERVER_ERROR,
296 "events not enabled".into(),
297 ))?;
298 };
299
300 if checksum != expected {
301 return Err(Error::Http(
302 StatusCode::BAD_REQUEST,
303 "invalid checksum".into(),
304 ))?;
305 }
306
307 let report: telemetry_events::PanicRequest = serde_json::from_slice(&body)
308 .map_err(|_| Error::Http(StatusCode::BAD_REQUEST, "invalid json".into()))?;
309 let panic = report.panic;
310
311 if panic.os_name == "Linux" && panic.os_version == Some("1.0.0".to_string()) {
312 return Err(Error::Http(
313 StatusCode::BAD_REQUEST,
314 "invalid os version".into(),
315 ))?;
316 }
317
318 tracing::error!(
319 service = "client",
320 version = %panic.app_version,
321 os_name = %panic.os_name,
322 os_version = %panic.os_version.clone().unwrap_or_default(),
323 installation_id = %panic.installation_id.unwrap_or_default(),
324 description = %panic.payload,
325 backtrace = %panic.backtrace.join("\n"),
326 "panic report");
327
328 let backtrace = if panic.backtrace.len() > 25 {
329 let total = panic.backtrace.len();
330 format!(
331 "{}\n and {} more",
332 panic
333 .backtrace
334 .iter()
335 .take(20)
336 .cloned()
337 .collect::<Vec<_>>()
338 .join("\n"),
339 total - 20
340 )
341 } else {
342 panic.backtrace.join("\n")
343 };
344 let backtrace_with_summary = panic.payload + "\n" + &backtrace;
345
346 if let Some(slack_panics_webhook) = app.config.slack_panics_webhook.clone() {
347 let payload = slack::WebhookBody::new(|w| {
348 w.add_section(|s| s.text(slack::Text::markdown("Panic request".to_string())))
349 .add_section(|s| {
350 s.add_field(slack::Text::markdown(format!(
351 "*Version:*\n {} ",
352 panic.app_version
353 )))
354 .add_field({
355 slack::Text::markdown(format!(
356 "*OS:*\n{} {}",
357 panic.os_name,
358 panic.os_version.unwrap_or_default()
359 ))
360 })
361 })
362 .add_rich_text(|r| r.add_preformatted(|p| p.add_text(backtrace_with_summary)))
363 });
364 let payload_json = serde_json::to_string(&payload).map_err(|err| {
365 log::error!("Failed to serialize payload to JSON: {err}");
366 Error::Internal(anyhow!(err))
367 })?;
368
369 reqwest::Client::new()
370 .post(slack_panics_webhook)
371 .header("Content-Type", "application/json")
372 .body(payload_json)
373 .send()
374 .await
375 .map_err(|err| {
376 log::error!("Failed to send payload to Slack: {err}");
377 Error::Internal(anyhow!(err))
378 })?;
379 }
380
381 Ok(())
382}
383
384pub async fn post_events(
385 Extension(app): Extension<Arc<AppState>>,
386 TypedHeader(ZedChecksumHeader(checksum)): TypedHeader<ZedChecksumHeader>,
387 country_code_header: Option<TypedHeader<CloudflareIpCountryHeader>>,
388 body: Bytes,
389) -> Result<()> {
390 let Some(clickhouse_client) = app.clickhouse_client.clone() else {
391 Err(Error::Http(
392 StatusCode::NOT_IMPLEMENTED,
393 "not supported".into(),
394 ))?
395 };
396
397 let Some(expected) = calculate_json_checksum(app.clone(), &body) else {
398 return Err(Error::Http(
399 StatusCode::INTERNAL_SERVER_ERROR,
400 "events not enabled".into(),
401 ))?;
402 };
403
404 let checksum_matched = checksum == expected;
405
406 let request_body: telemetry_events::EventRequestBody =
407 serde_json::from_slice(&body).map_err(|err| {
408 log::error!("can't parse event json: {err}");
409 Error::Internal(anyhow!(err))
410 })?;
411
412 let mut to_upload = ToUpload::default();
413 let Some(last_event) = request_body.events.last() else {
414 return Err(Error::Http(StatusCode::BAD_REQUEST, "no events".into()))?;
415 };
416 let country_code = country_code_header.map(|h| h.0 .0);
417
418 let first_event_at = chrono::Utc::now()
419 - chrono::Duration::milliseconds(last_event.milliseconds_since_first_event);
420
421 for wrapper in &request_body.events {
422 match &wrapper.event {
423 Event::Editor(event) => to_upload.editor_events.push(EditorEventRow::from_event(
424 event.clone(),
425 &wrapper,
426 &request_body,
427 first_event_at,
428 country_code.clone(),
429 checksum_matched,
430 )),
431 // Needed for clients sending old copilot_event types
432 Event::Copilot(_) => {}
433 Event::InlineCompletion(event) => {
434 to_upload
435 .inline_completion_events
436 .push(InlineCompletionEventRow::from_event(
437 event.clone(),
438 &wrapper,
439 &request_body,
440 first_event_at,
441 country_code.clone(),
442 checksum_matched,
443 ))
444 }
445 Event::Call(event) => to_upload.call_events.push(CallEventRow::from_event(
446 event.clone(),
447 &wrapper,
448 &request_body,
449 first_event_at,
450 checksum_matched,
451 )),
452 Event::Assistant(event) => {
453 to_upload
454 .assistant_events
455 .push(AssistantEventRow::from_event(
456 event.clone(),
457 &wrapper,
458 &request_body,
459 first_event_at,
460 checksum_matched,
461 ))
462 }
463 Event::Cpu(event) => to_upload.cpu_events.push(CpuEventRow::from_event(
464 event.clone(),
465 &wrapper,
466 &request_body,
467 first_event_at,
468 checksum_matched,
469 )),
470 Event::Memory(event) => to_upload.memory_events.push(MemoryEventRow::from_event(
471 event.clone(),
472 &wrapper,
473 &request_body,
474 first_event_at,
475 checksum_matched,
476 )),
477 Event::App(event) => to_upload.app_events.push(AppEventRow::from_event(
478 event.clone(),
479 &wrapper,
480 &request_body,
481 first_event_at,
482 checksum_matched,
483 )),
484 Event::Setting(event) => to_upload.setting_events.push(SettingEventRow::from_event(
485 event.clone(),
486 &wrapper,
487 &request_body,
488 first_event_at,
489 checksum_matched,
490 )),
491 Event::Edit(event) => to_upload.edit_events.push(EditEventRow::from_event(
492 event.clone(),
493 &wrapper,
494 &request_body,
495 first_event_at,
496 checksum_matched,
497 )),
498 Event::Action(event) => to_upload.action_events.push(ActionEventRow::from_event(
499 event.clone(),
500 &wrapper,
501 &request_body,
502 first_event_at,
503 checksum_matched,
504 )),
505 Event::Extension(event) => {
506 let metadata = app
507 .db
508 .get_extension_version(&event.extension_id, &event.version)
509 .await?;
510 to_upload
511 .extension_events
512 .push(ExtensionEventRow::from_event(
513 event.clone(),
514 &wrapper,
515 &request_body,
516 metadata,
517 first_event_at,
518 checksum_matched,
519 ))
520 }
521 }
522 }
523
524 to_upload
525 .upload(&clickhouse_client)
526 .await
527 .map_err(|err| Error::Internal(anyhow!(err)))?;
528
529 Ok(())
530}
531
532#[derive(Default)]
533struct ToUpload {
534 editor_events: Vec<EditorEventRow>,
535 inline_completion_events: Vec<InlineCompletionEventRow>,
536 assistant_events: Vec<AssistantEventRow>,
537 call_events: Vec<CallEventRow>,
538 cpu_events: Vec<CpuEventRow>,
539 memory_events: Vec<MemoryEventRow>,
540 app_events: Vec<AppEventRow>,
541 setting_events: Vec<SettingEventRow>,
542 extension_events: Vec<ExtensionEventRow>,
543 edit_events: Vec<EditEventRow>,
544 action_events: Vec<ActionEventRow>,
545}
546
547impl ToUpload {
548 pub async fn upload(&self, clickhouse_client: &clickhouse::Client) -> anyhow::Result<()> {
549 const EDITOR_EVENTS_TABLE: &str = "editor_events";
550 Self::upload_to_table(EDITOR_EVENTS_TABLE, &self.editor_events, clickhouse_client)
551 .await
552 .with_context(|| format!("failed to upload to table '{EDITOR_EVENTS_TABLE}'"))?;
553
554 const INLINE_COMPLETION_EVENTS_TABLE: &str = "inline_completion_events";
555 Self::upload_to_table(
556 INLINE_COMPLETION_EVENTS_TABLE,
557 &self.inline_completion_events,
558 clickhouse_client,
559 )
560 .await
561 .with_context(|| format!("failed to upload to table '{INLINE_COMPLETION_EVENTS_TABLE}'"))?;
562
563 const ASSISTANT_EVENTS_TABLE: &str = "assistant_events";
564 Self::upload_to_table(
565 ASSISTANT_EVENTS_TABLE,
566 &self.assistant_events,
567 clickhouse_client,
568 )
569 .await
570 .with_context(|| format!("failed to upload to table '{ASSISTANT_EVENTS_TABLE}'"))?;
571
572 const CALL_EVENTS_TABLE: &str = "call_events";
573 Self::upload_to_table(CALL_EVENTS_TABLE, &self.call_events, clickhouse_client)
574 .await
575 .with_context(|| format!("failed to upload to table '{CALL_EVENTS_TABLE}'"))?;
576
577 const CPU_EVENTS_TABLE: &str = "cpu_events";
578 Self::upload_to_table(CPU_EVENTS_TABLE, &self.cpu_events, clickhouse_client)
579 .await
580 .with_context(|| format!("failed to upload to table '{CPU_EVENTS_TABLE}'"))?;
581
582 const MEMORY_EVENTS_TABLE: &str = "memory_events";
583 Self::upload_to_table(MEMORY_EVENTS_TABLE, &self.memory_events, clickhouse_client)
584 .await
585 .with_context(|| format!("failed to upload to table '{MEMORY_EVENTS_TABLE}'"))?;
586
587 const APP_EVENTS_TABLE: &str = "app_events";
588 Self::upload_to_table(APP_EVENTS_TABLE, &self.app_events, clickhouse_client)
589 .await
590 .with_context(|| format!("failed to upload to table '{APP_EVENTS_TABLE}'"))?;
591
592 const SETTING_EVENTS_TABLE: &str = "setting_events";
593 Self::upload_to_table(
594 SETTING_EVENTS_TABLE,
595 &self.setting_events,
596 clickhouse_client,
597 )
598 .await
599 .with_context(|| format!("failed to upload to table '{SETTING_EVENTS_TABLE}'"))?;
600
601 const EXTENSION_EVENTS_TABLE: &str = "extension_events";
602 Self::upload_to_table(
603 EXTENSION_EVENTS_TABLE,
604 &self.extension_events,
605 clickhouse_client,
606 )
607 .await
608 .with_context(|| format!("failed to upload to table '{EXTENSION_EVENTS_TABLE}'"))?;
609
610 const EDIT_EVENTS_TABLE: &str = "edit_events";
611 Self::upload_to_table(EDIT_EVENTS_TABLE, &self.edit_events, clickhouse_client)
612 .await
613 .with_context(|| format!("failed to upload to table '{EDIT_EVENTS_TABLE}'"))?;
614
615 const ACTION_EVENTS_TABLE: &str = "action_events";
616 Self::upload_to_table(ACTION_EVENTS_TABLE, &self.action_events, clickhouse_client)
617 .await
618 .with_context(|| format!("failed to upload to table '{ACTION_EVENTS_TABLE}'"))?;
619
620 Ok(())
621 }
622
623 async fn upload_to_table<T: clickhouse::Row + Serialize + std::fmt::Debug>(
624 table: &str,
625 rows: &[T],
626 clickhouse_client: &clickhouse::Client,
627 ) -> anyhow::Result<()> {
628 if !rows.is_empty() {
629 let mut insert = clickhouse_client.insert(table)?;
630
631 for event in rows {
632 insert.write(event).await?;
633 }
634
635 insert.end().await?;
636
637 let event_count = rows.len();
638 log::info!(
639 "wrote {event_count} {event_specifier} to '{table}'",
640 event_specifier = if event_count == 1 { "event" } else { "events" }
641 );
642 }
643
644 Ok(())
645 }
646}
647
648pub fn serialize_country_code<S>(country_code: &str, serializer: S) -> Result<S::Ok, S::Error>
649where
650 S: Serializer,
651{
652 if country_code.len() != 2 {
653 use serde::ser::Error;
654 return Err(S::Error::custom(
655 "country_code must be exactly 2 characters",
656 ));
657 }
658
659 let country_code = country_code.as_bytes();
660
661 serializer.serialize_u16(((country_code[1] as u16) << 8) + country_code[0] as u16)
662}
663
664#[derive(Serialize, Debug, clickhouse::Row)]
665pub struct EditorEventRow {
666 installation_id: String,
667 operation: String,
668 app_version: String,
669 file_extension: String,
670 os_name: String,
671 os_version: String,
672 release_channel: String,
673 signed_in: bool,
674 vim_mode: bool,
675 #[serde(serialize_with = "serialize_country_code")]
676 country_code: String,
677 region_code: String,
678 city: String,
679 time: i64,
680 copilot_enabled: bool,
681 copilot_enabled_for_language: bool,
682 historical_event: bool,
683 architecture: String,
684 is_staff: Option<bool>,
685 session_id: Option<String>,
686 major: Option<i32>,
687 minor: Option<i32>,
688 patch: Option<i32>,
689 checksum_matched: bool,
690}
691
692impl EditorEventRow {
693 fn from_event(
694 event: EditorEvent,
695 wrapper: &EventWrapper,
696 body: &EventRequestBody,
697 first_event_at: chrono::DateTime<chrono::Utc>,
698 country_code: Option<String>,
699 checksum_matched: bool,
700 ) -> Self {
701 let semver = body.semver();
702 let time =
703 first_event_at + chrono::Duration::milliseconds(wrapper.milliseconds_since_first_event);
704
705 Self {
706 app_version: body.app_version.clone(),
707 major: semver.map(|v| v.major() as i32),
708 minor: semver.map(|v| v.minor() as i32),
709 patch: semver.map(|v| v.patch() as i32),
710 checksum_matched,
711 release_channel: body.release_channel.clone().unwrap_or_default(),
712 os_name: body.os_name.clone(),
713 os_version: body.os_version.clone().unwrap_or_default(),
714 architecture: body.architecture.clone(),
715 installation_id: body.installation_id.clone().unwrap_or_default(),
716 session_id: body.session_id.clone(),
717 is_staff: body.is_staff,
718 time: time.timestamp_millis(),
719 operation: event.operation,
720 file_extension: event.file_extension.unwrap_or_default(),
721 signed_in: wrapper.signed_in,
722 vim_mode: event.vim_mode,
723 copilot_enabled: event.copilot_enabled,
724 copilot_enabled_for_language: event.copilot_enabled_for_language,
725 country_code: country_code.unwrap_or("XX".to_string()),
726 region_code: "".to_string(),
727 city: "".to_string(),
728 historical_event: false,
729 }
730 }
731}
732
733#[derive(Serialize, Debug, clickhouse::Row)]
734pub struct InlineCompletionEventRow {
735 installation_id: String,
736 provider: String,
737 suggestion_accepted: bool,
738 app_version: String,
739 file_extension: String,
740 os_name: String,
741 os_version: String,
742 release_channel: String,
743 signed_in: bool,
744 #[serde(serialize_with = "serialize_country_code")]
745 country_code: String,
746 region_code: String,
747 city: String,
748 time: i64,
749 is_staff: Option<bool>,
750 session_id: Option<String>,
751 major: Option<i32>,
752 minor: Option<i32>,
753 patch: Option<i32>,
754 checksum_matched: bool,
755}
756
757impl InlineCompletionEventRow {
758 fn from_event(
759 event: InlineCompletionEvent,
760 wrapper: &EventWrapper,
761 body: &EventRequestBody,
762 first_event_at: chrono::DateTime<chrono::Utc>,
763 country_code: Option<String>,
764 checksum_matched: bool,
765 ) -> Self {
766 let semver = body.semver();
767 let time =
768 first_event_at + chrono::Duration::milliseconds(wrapper.milliseconds_since_first_event);
769
770 Self {
771 app_version: body.app_version.clone(),
772 major: semver.map(|v| v.major() as i32),
773 minor: semver.map(|v| v.minor() as i32),
774 patch: semver.map(|v| v.patch() as i32),
775 checksum_matched,
776 release_channel: body.release_channel.clone().unwrap_or_default(),
777 os_name: body.os_name.clone(),
778 os_version: body.os_version.clone().unwrap_or_default(),
779 installation_id: body.installation_id.clone().unwrap_or_default(),
780 session_id: body.session_id.clone(),
781 is_staff: body.is_staff,
782 time: time.timestamp_millis(),
783 file_extension: event.file_extension.unwrap_or_default(),
784 signed_in: wrapper.signed_in,
785 country_code: country_code.unwrap_or("XX".to_string()),
786 region_code: "".to_string(),
787 city: "".to_string(),
788 provider: event.provider,
789 suggestion_accepted: event.suggestion_accepted,
790 }
791 }
792}
793
794#[derive(Serialize, Debug, clickhouse::Row)]
795pub struct CallEventRow {
796 // AppInfoBase
797 app_version: String,
798 major: Option<i32>,
799 minor: Option<i32>,
800 patch: Option<i32>,
801 release_channel: String,
802 os_name: String,
803 os_version: String,
804 checksum_matched: bool,
805
806 // ClientEventBase
807 installation_id: String,
808 session_id: Option<String>,
809 is_staff: Option<bool>,
810 time: i64,
811
812 // CallEventRow
813 operation: String,
814 room_id: Option<u64>,
815 channel_id: Option<u64>,
816}
817
818impl CallEventRow {
819 fn from_event(
820 event: CallEvent,
821 wrapper: &EventWrapper,
822 body: &EventRequestBody,
823 first_event_at: chrono::DateTime<chrono::Utc>,
824 checksum_matched: bool,
825 ) -> Self {
826 let semver = body.semver();
827 let time =
828 first_event_at + chrono::Duration::milliseconds(wrapper.milliseconds_since_first_event);
829
830 Self {
831 app_version: body.app_version.clone(),
832 major: semver.map(|v| v.major() as i32),
833 minor: semver.map(|v| v.minor() as i32),
834 patch: semver.map(|v| v.patch() as i32),
835 checksum_matched,
836 release_channel: body.release_channel.clone().unwrap_or_default(),
837 os_name: body.os_name.clone(),
838 os_version: body.os_version.clone().unwrap_or_default(),
839 installation_id: body.installation_id.clone().unwrap_or_default(),
840 session_id: body.session_id.clone(),
841 is_staff: body.is_staff,
842 time: time.timestamp_millis(),
843 operation: event.operation,
844 room_id: event.room_id,
845 channel_id: event.channel_id,
846 }
847 }
848}
849
850#[derive(Serialize, Debug, clickhouse::Row)]
851pub struct AssistantEventRow {
852 // AppInfoBase
853 app_version: String,
854 major: Option<i32>,
855 minor: Option<i32>,
856 patch: Option<i32>,
857 checksum_matched: bool,
858 release_channel: String,
859 os_name: String,
860 os_version: String,
861
862 // ClientEventBase
863 installation_id: Option<String>,
864 session_id: Option<String>,
865 is_staff: Option<bool>,
866 time: i64,
867
868 // AssistantEventRow
869 conversation_id: String,
870 kind: String,
871 model: String,
872 response_latency_in_ms: Option<i64>,
873 error_message: Option<String>,
874}
875
876impl AssistantEventRow {
877 fn from_event(
878 event: AssistantEvent,
879 wrapper: &EventWrapper,
880 body: &EventRequestBody,
881 first_event_at: chrono::DateTime<chrono::Utc>,
882 checksum_matched: bool,
883 ) -> Self {
884 let semver = body.semver();
885 let time =
886 first_event_at + chrono::Duration::milliseconds(wrapper.milliseconds_since_first_event);
887
888 Self {
889 app_version: body.app_version.clone(),
890 major: semver.map(|v| v.major() as i32),
891 minor: semver.map(|v| v.minor() as i32),
892 patch: semver.map(|v| v.patch() as i32),
893 checksum_matched,
894 release_channel: body.release_channel.clone().unwrap_or_default(),
895 os_name: body.os_name.clone(),
896 os_version: body.os_version.clone().unwrap_or_default(),
897 installation_id: body.installation_id.clone(),
898 session_id: body.session_id.clone(),
899 is_staff: body.is_staff,
900 time: time.timestamp_millis(),
901 conversation_id: event.conversation_id.unwrap_or_default(),
902 kind: event.kind.to_string(),
903 model: event.model,
904 response_latency_in_ms: event
905 .response_latency
906 .map(|latency| latency.as_millis() as i64),
907 error_message: event.error_message,
908 }
909 }
910}
911
912#[derive(Debug, clickhouse::Row, Serialize)]
913pub struct CpuEventRow {
914 installation_id: Option<String>,
915 is_staff: Option<bool>,
916 usage_as_percentage: f32,
917 core_count: u32,
918 app_version: String,
919 release_channel: String,
920 os_name: String,
921 os_version: String,
922 time: i64,
923 session_id: Option<String>,
924 // pub normalized_cpu_usage: f64, MATERIALIZED
925 major: Option<i32>,
926 minor: Option<i32>,
927 patch: Option<i32>,
928 checksum_matched: bool,
929}
930
931impl CpuEventRow {
932 fn from_event(
933 event: CpuEvent,
934 wrapper: &EventWrapper,
935 body: &EventRequestBody,
936 first_event_at: chrono::DateTime<chrono::Utc>,
937 checksum_matched: bool,
938 ) -> Self {
939 let semver = body.semver();
940 let time =
941 first_event_at + chrono::Duration::milliseconds(wrapper.milliseconds_since_first_event);
942
943 Self {
944 app_version: body.app_version.clone(),
945 major: semver.map(|v| v.major() as i32),
946 minor: semver.map(|v| v.minor() as i32),
947 patch: semver.map(|v| v.patch() as i32),
948 checksum_matched,
949 release_channel: body.release_channel.clone().unwrap_or_default(),
950 os_name: body.os_name.clone(),
951 os_version: body.os_version.clone().unwrap_or_default(),
952 installation_id: body.installation_id.clone(),
953 session_id: body.session_id.clone(),
954 is_staff: body.is_staff,
955 time: time.timestamp_millis(),
956 usage_as_percentage: event.usage_as_percentage,
957 core_count: event.core_count,
958 }
959 }
960}
961
962#[derive(Serialize, Debug, clickhouse::Row)]
963pub struct MemoryEventRow {
964 // AppInfoBase
965 app_version: String,
966 major: Option<i32>,
967 minor: Option<i32>,
968 patch: Option<i32>,
969 checksum_matched: bool,
970 release_channel: String,
971 os_name: String,
972 os_version: String,
973
974 // ClientEventBase
975 installation_id: Option<String>,
976 session_id: Option<String>,
977 is_staff: Option<bool>,
978 time: i64,
979
980 // MemoryEventRow
981 memory_in_bytes: u64,
982 virtual_memory_in_bytes: u64,
983}
984
985impl MemoryEventRow {
986 fn from_event(
987 event: MemoryEvent,
988 wrapper: &EventWrapper,
989 body: &EventRequestBody,
990 first_event_at: chrono::DateTime<chrono::Utc>,
991 checksum_matched: bool,
992 ) -> Self {
993 let semver = body.semver();
994 let time =
995 first_event_at + chrono::Duration::milliseconds(wrapper.milliseconds_since_first_event);
996
997 Self {
998 app_version: body.app_version.clone(),
999 major: semver.map(|v| v.major() as i32),
1000 minor: semver.map(|v| v.minor() as i32),
1001 patch: semver.map(|v| v.patch() as i32),
1002 checksum_matched,
1003 release_channel: body.release_channel.clone().unwrap_or_default(),
1004 os_name: body.os_name.clone(),
1005 os_version: body.os_version.clone().unwrap_or_default(),
1006 installation_id: body.installation_id.clone(),
1007 session_id: body.session_id.clone(),
1008 is_staff: body.is_staff,
1009 time: time.timestamp_millis(),
1010 memory_in_bytes: event.memory_in_bytes,
1011 virtual_memory_in_bytes: event.virtual_memory_in_bytes,
1012 }
1013 }
1014}
1015
1016#[derive(Serialize, Debug, clickhouse::Row)]
1017pub struct AppEventRow {
1018 // AppInfoBase
1019 app_version: String,
1020 major: Option<i32>,
1021 minor: Option<i32>,
1022 patch: Option<i32>,
1023 checksum_matched: bool,
1024 release_channel: String,
1025 os_name: String,
1026 os_version: String,
1027
1028 // ClientEventBase
1029 installation_id: Option<String>,
1030 session_id: Option<String>,
1031 is_staff: Option<bool>,
1032 time: i64,
1033
1034 // AppEventRow
1035 operation: String,
1036}
1037
1038impl AppEventRow {
1039 fn from_event(
1040 event: AppEvent,
1041 wrapper: &EventWrapper,
1042 body: &EventRequestBody,
1043 first_event_at: chrono::DateTime<chrono::Utc>,
1044 checksum_matched: bool,
1045 ) -> Self {
1046 let semver = body.semver();
1047 let time =
1048 first_event_at + chrono::Duration::milliseconds(wrapper.milliseconds_since_first_event);
1049
1050 Self {
1051 app_version: body.app_version.clone(),
1052 major: semver.map(|v| v.major() as i32),
1053 minor: semver.map(|v| v.minor() as i32),
1054 patch: semver.map(|v| v.patch() as i32),
1055 checksum_matched,
1056 release_channel: body.release_channel.clone().unwrap_or_default(),
1057 os_name: body.os_name.clone(),
1058 os_version: body.os_version.clone().unwrap_or_default(),
1059 installation_id: body.installation_id.clone(),
1060 session_id: body.session_id.clone(),
1061 is_staff: body.is_staff,
1062 time: time.timestamp_millis(),
1063 operation: event.operation,
1064 }
1065 }
1066}
1067
1068#[derive(Serialize, Debug, clickhouse::Row)]
1069pub struct SettingEventRow {
1070 // AppInfoBase
1071 app_version: String,
1072 major: Option<i32>,
1073 minor: Option<i32>,
1074 patch: Option<i32>,
1075 checksum_matched: bool,
1076 release_channel: String,
1077 os_name: String,
1078 os_version: String,
1079
1080 // ClientEventBase
1081 installation_id: Option<String>,
1082 session_id: Option<String>,
1083 is_staff: Option<bool>,
1084 time: i64,
1085 // SettingEventRow
1086 setting: String,
1087 value: String,
1088}
1089
1090impl SettingEventRow {
1091 fn from_event(
1092 event: SettingEvent,
1093 wrapper: &EventWrapper,
1094 body: &EventRequestBody,
1095 first_event_at: chrono::DateTime<chrono::Utc>,
1096 checksum_matched: bool,
1097 ) -> Self {
1098 let semver = body.semver();
1099 let time =
1100 first_event_at + chrono::Duration::milliseconds(wrapper.milliseconds_since_first_event);
1101
1102 Self {
1103 app_version: body.app_version.clone(),
1104 major: semver.map(|v| v.major() as i32),
1105 minor: semver.map(|v| v.minor() as i32),
1106 checksum_matched,
1107 patch: semver.map(|v| v.patch() as i32),
1108 release_channel: body.release_channel.clone().unwrap_or_default(),
1109 os_name: body.os_name.clone(),
1110 os_version: body.os_version.clone().unwrap_or_default(),
1111 installation_id: body.installation_id.clone(),
1112 session_id: body.session_id.clone(),
1113 is_staff: body.is_staff,
1114 time: time.timestamp_millis(),
1115 setting: event.setting,
1116 value: event.value,
1117 }
1118 }
1119}
1120
1121#[derive(Serialize, Debug, clickhouse::Row)]
1122pub struct ExtensionEventRow {
1123 // AppInfoBase
1124 app_version: String,
1125 major: Option<i32>,
1126 minor: Option<i32>,
1127 patch: Option<i32>,
1128 checksum_matched: bool,
1129 release_channel: String,
1130 os_name: String,
1131 os_version: String,
1132
1133 // ClientEventBase
1134 installation_id: Option<String>,
1135 session_id: Option<String>,
1136 is_staff: Option<bool>,
1137 time: i64,
1138
1139 // ExtensionEventRow
1140 extension_id: Arc<str>,
1141 extension_version: Arc<str>,
1142 dev: bool,
1143 schema_version: Option<i32>,
1144 wasm_api_version: Option<String>,
1145}
1146
1147impl ExtensionEventRow {
1148 fn from_event(
1149 event: ExtensionEvent,
1150 wrapper: &EventWrapper,
1151 body: &EventRequestBody,
1152 extension_metadata: Option<ExtensionMetadata>,
1153 first_event_at: chrono::DateTime<chrono::Utc>,
1154 checksum_matched: bool,
1155 ) -> Self {
1156 let semver = body.semver();
1157 let time =
1158 first_event_at + chrono::Duration::milliseconds(wrapper.milliseconds_since_first_event);
1159
1160 Self {
1161 app_version: body.app_version.clone(),
1162 major: semver.map(|v| v.major() as i32),
1163 minor: semver.map(|v| v.minor() as i32),
1164 patch: semver.map(|v| v.patch() as i32),
1165 checksum_matched,
1166 release_channel: body.release_channel.clone().unwrap_or_default(),
1167 os_name: body.os_name.clone(),
1168 os_version: body.os_version.clone().unwrap_or_default(),
1169 installation_id: body.installation_id.clone(),
1170 session_id: body.session_id.clone(),
1171 is_staff: body.is_staff,
1172 time: time.timestamp_millis(),
1173 extension_id: event.extension_id,
1174 extension_version: event.version,
1175 dev: extension_metadata.is_none(),
1176 schema_version: extension_metadata
1177 .as_ref()
1178 .and_then(|metadata| metadata.manifest.schema_version),
1179 wasm_api_version: extension_metadata.as_ref().and_then(|metadata| {
1180 metadata
1181 .manifest
1182 .wasm_api_version
1183 .as_ref()
1184 .map(|version| version.to_string())
1185 }),
1186 }
1187 }
1188}
1189
1190#[derive(Serialize, Debug, clickhouse::Row)]
1191pub struct EditEventRow {
1192 // AppInfoBase
1193 app_version: String,
1194 major: Option<i32>,
1195 minor: Option<i32>,
1196 patch: Option<i32>,
1197 checksum_matched: bool,
1198 release_channel: String,
1199 os_name: String,
1200 os_version: String,
1201
1202 // ClientEventBase
1203 installation_id: Option<String>,
1204 // Note: This column name has a typo in the ClickHouse table.
1205 #[serde(rename = "sesssion_id")]
1206 session_id: Option<String>,
1207 is_staff: Option<bool>,
1208 time: i64,
1209
1210 // EditEventRow
1211 period_start: i64,
1212 period_end: i64,
1213 environment: String,
1214}
1215
1216impl EditEventRow {
1217 fn from_event(
1218 event: EditEvent,
1219 wrapper: &EventWrapper,
1220 body: &EventRequestBody,
1221 first_event_at: chrono::DateTime<chrono::Utc>,
1222 checksum_matched: bool,
1223 ) -> Self {
1224 let semver = body.semver();
1225 let time =
1226 first_event_at + chrono::Duration::milliseconds(wrapper.milliseconds_since_first_event);
1227
1228 let period_start = time - chrono::Duration::milliseconds(event.duration);
1229 let period_end = time;
1230
1231 Self {
1232 app_version: body.app_version.clone(),
1233 major: semver.map(|v| v.major() as i32),
1234 minor: semver.map(|v| v.minor() as i32),
1235 patch: semver.map(|v| v.patch() as i32),
1236 checksum_matched,
1237 release_channel: body.release_channel.clone().unwrap_or_default(),
1238 os_name: body.os_name.clone(),
1239 os_version: body.os_version.clone().unwrap_or_default(),
1240 installation_id: body.installation_id.clone(),
1241 session_id: body.session_id.clone(),
1242 is_staff: body.is_staff,
1243 time: time.timestamp_millis(),
1244 period_start: period_start.timestamp_millis(),
1245 period_end: period_end.timestamp_millis(),
1246 environment: event.environment,
1247 }
1248 }
1249}
1250
1251#[derive(Serialize, Debug, clickhouse::Row)]
1252pub struct ActionEventRow {
1253 // AppInfoBase
1254 app_version: String,
1255 major: Option<i32>,
1256 minor: Option<i32>,
1257 patch: Option<i32>,
1258 checksum_matched: bool,
1259 release_channel: String,
1260 os_name: String,
1261 os_version: String,
1262
1263 // ClientEventBase
1264 installation_id: Option<String>,
1265 // Note: This column name has a typo in the ClickHouse table.
1266 #[serde(rename = "sesssion_id")]
1267 session_id: Option<String>,
1268 is_staff: Option<bool>,
1269 time: i64,
1270 // ActionEventRow
1271 source: String,
1272 action: String,
1273}
1274
1275impl ActionEventRow {
1276 fn from_event(
1277 event: ActionEvent,
1278 wrapper: &EventWrapper,
1279 body: &EventRequestBody,
1280 first_event_at: chrono::DateTime<chrono::Utc>,
1281 checksum_matched: bool,
1282 ) -> Self {
1283 let semver = body.semver();
1284 let time =
1285 first_event_at + chrono::Duration::milliseconds(wrapper.milliseconds_since_first_event);
1286
1287 Self {
1288 app_version: body.app_version.clone(),
1289 major: semver.map(|v| v.major() as i32),
1290 minor: semver.map(|v| v.minor() as i32),
1291 patch: semver.map(|v| v.patch() as i32),
1292 checksum_matched,
1293 release_channel: body.release_channel.clone().unwrap_or_default(),
1294 os_name: body.os_name.clone(),
1295 os_version: body.os_version.clone().unwrap_or_default(),
1296 installation_id: body.installation_id.clone(),
1297 session_id: body.session_id.clone(),
1298 is_staff: body.is_staff,
1299 time: time.timestamp_millis(),
1300 source: event.source,
1301 action: event.action,
1302 }
1303 }
1304}
1305
1306pub fn calculate_json_checksum(app: Arc<AppState>, json: &impl AsRef<[u8]>) -> Option<Vec<u8>> {
1307 let Some(checksum_seed) = app.config.zed_client_checksum_seed.as_ref() else {
1308 return None;
1309 };
1310
1311 let mut summer = Sha256::new();
1312 summer.update(checksum_seed);
1313 summer.update(&json);
1314 summer.update(checksum_seed);
1315 Some(summer.finalize().into_iter().collect())
1316}