Define telemetry settings in the client crate

This commit is contained in:
Max Brunsfeld 2023-05-10 12:17:52 -07:00
parent 9b06be2aa2
commit aa6ea920e2
17 changed files with 100 additions and 120 deletions

2
Cargo.lock generated
View File

@ -1155,6 +1155,7 @@ dependencies = [
"postage",
"rand 0.8.5",
"rpc",
"schemars",
"serde",
"serde_derive",
"settings",
@ -8315,6 +8316,7 @@ name = "welcome"
version = "0.1.0"
dependencies = [
"anyhow",
"client",
"db",
"editor",
"fs",

View File

@ -85,6 +85,7 @@ parking_lot = { version = "0.11.1" }
postage = { version = "0.5", features = ["futures-traits"] }
rand = { version = "0.8.5" }
regex = { version = "1.5" }
schemars = { version = "0.8" }
serde = { version = "1.0", features = ["derive", "rc"] }
serde_derive = { version = "1.0", features = ["deserialize_in_place"] }
serde_json = { version = "1.0", features = ["preserve_order", "raw_value"] }

View File

@ -1,7 +1,7 @@
mod update_notification;
use anyhow::{anyhow, Context, Result};
use client::{Client, ZED_APP_PATH, ZED_APP_VERSION, ZED_SECRET_CLIENT_TOKEN};
use client::{Client, TelemetrySettings, ZED_APP_PATH, ZED_APP_VERSION, ZED_SECRET_CLIENT_TOKEN};
use db::kvp::KEY_VALUE_STORE;
use gpui::{
actions, platform::AppVersion, AppContext, AsyncAppContext, Entity, ModelContext, ModelHandle,
@ -10,7 +10,7 @@ use gpui::{
use isahc::AsyncBody;
use serde::Deserialize;
use serde_derive::Serialize;
use settings::{Setting, Settings, SettingsStore};
use settings::{Setting, SettingsStore};
use smol::{fs::File, io::AsyncReadExt, process::Command};
use std::{ffi::OsString, sync::Arc, time::Duration};
use update_notification::UpdateNotification;
@ -279,7 +279,7 @@ impl AutoUpdater {
let release_channel = cx
.has_global::<ReleaseChannel>()
.then(|| cx.global::<ReleaseChannel>().display_name());
let telemetry = cx.global::<Settings>().telemetry().metrics();
let telemetry = settings::get_setting::<TelemetrySettings>(None, cx).metrics;
(installation_id, release_channel, telemetry)
});

View File

@ -31,6 +31,7 @@ log.workspace = true
parking_lot.workspace = true
postage.workspace = true
rand.workspace = true
schemars.workspace = true
smol.workspace = true
thiserror.workspace = true
time.workspace = true

View File

@ -15,19 +15,17 @@ use futures::{
TryStreamExt,
};
use gpui::{
actions,
platform::AppVersion,
serde_json::{self},
AnyModelHandle, AnyWeakModelHandle, AnyWeakViewHandle, AppContext, AsyncAppContext, Entity,
ModelHandle, Task, View, ViewContext, WeakViewHandle,
actions, platform::AppVersion, serde_json, AnyModelHandle, AnyWeakModelHandle,
AnyWeakViewHandle, AppContext, AsyncAppContext, Entity, ModelHandle, Task, View, ViewContext,
WeakViewHandle,
};
use lazy_static::lazy_static;
use parking_lot::RwLock;
use postage::watch;
use rand::prelude::*;
use rpc::proto::{AnyTypedEnvelope, EntityMessage, EnvelopedMessage, PeerId, RequestMessage};
use serde::Deserialize;
use settings::Settings;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use std::{
any::TypeId,
collections::HashMap,
@ -73,6 +71,8 @@ pub const CONNECTION_TIMEOUT: Duration = Duration::from_secs(5);
actions!(client, [SignIn, SignOut]);
pub fn init(client: Arc<Client>, cx: &mut AppContext) {
settings::register_setting::<TelemetrySettings>(cx);
cx.add_global_action({
let client = client.clone();
move |_: &SignIn, cx| {
@ -326,6 +326,41 @@ impl<T: Entity> Drop for PendingEntitySubscription<T> {
}
}
#[derive(Copy, Clone)]
pub struct TelemetrySettings {
pub diagnostics: bool,
pub metrics: bool,
}
#[derive(Clone, Serialize, Deserialize, JsonSchema)]
pub struct TelemetrySettingsContent {
pub diagnostics: Option<bool>,
pub metrics: Option<bool>,
}
impl settings::Setting for TelemetrySettings {
const KEY: Option<&'static str> = Some("telemetry");
type FileContent = TelemetrySettingsContent;
fn load(
default_value: &Self::FileContent,
user_values: &[&Self::FileContent],
_: &AppContext,
) -> Self {
Self {
diagnostics: user_values
.first()
.and_then(|v| v.diagnostics)
.unwrap_or(default_value.diagnostics.unwrap()),
metrics: user_values
.first()
.and_then(|v| v.metrics)
.unwrap_or(default_value.metrics.unwrap()),
}
}
}
impl Client {
pub fn new(http: Arc<dyn HttpClient>, cx: &AppContext) -> Arc<Self> {
Arc::new(Self {
@ -447,9 +482,7 @@ impl Client {
}));
}
Status::SignedOut | Status::UpgradeRequired => {
let telemetry_settings = cx.read(|cx| cx.global::<Settings>().telemetry());
self.telemetry
.set_authenticated_user_info(None, false, telemetry_settings);
cx.read(|cx| self.telemetry.set_authenticated_user_info(None, false, cx));
state._reconnect_task.take();
}
_ => {}
@ -740,7 +773,7 @@ impl Client {
self.telemetry().report_mixpanel_event(
"read credentials from keychain",
Default::default(),
cx.global::<Settings>().telemetry(),
*settings::get_setting::<TelemetrySettings>(None, cx),
);
});
}
@ -1033,7 +1066,9 @@ impl Client {
let executor = cx.background();
let telemetry = self.telemetry.clone();
let http = self.http.clone();
let metrics_enabled = cx.read(|cx| cx.global::<Settings>().telemetry());
let telemetry_settings =
cx.read(|cx| *settings::get_setting::<TelemetrySettings>(None, cx));
executor.clone().spawn(async move {
// Generate a pair of asymmetric encryption keys. The public key will be used by the
@ -1120,7 +1155,7 @@ impl Client {
telemetry.report_mixpanel_event(
"authenticate with browser",
Default::default(),
metrics_enabled,
telemetry_settings,
);
Ok(Credentials {

View File

@ -1,4 +1,4 @@
use crate::{ZED_SECRET_CLIENT_TOKEN, ZED_SERVER_URL};
use crate::{TelemetrySettings, ZED_SECRET_CLIENT_TOKEN, ZED_SERVER_URL};
use db::kvp::KEY_VALUE_STORE;
use gpui::{
executor::Background,
@ -9,7 +9,6 @@ use lazy_static::lazy_static;
use parking_lot::Mutex;
use serde::Serialize;
use serde_json::json;
use settings::TelemetrySettings;
use std::{
io::Write,
mem,
@ -241,9 +240,9 @@ impl Telemetry {
self: &Arc<Self>,
metrics_id: Option<String>,
is_staff: bool,
telemetry_settings: TelemetrySettings,
cx: &AppContext,
) {
if !telemetry_settings.metrics() {
if !settings::get_setting::<TelemetrySettings>(None, cx).metrics {
return;
}
@ -285,7 +284,7 @@ impl Telemetry {
event: ClickhouseEvent,
telemetry_settings: TelemetrySettings,
) {
if !telemetry_settings.metrics() {
if !telemetry_settings.metrics {
return;
}
@ -321,7 +320,7 @@ impl Telemetry {
properties: Value,
telemetry_settings: TelemetrySettings,
) {
if !telemetry_settings.metrics() {
if !telemetry_settings.metrics {
return;
}

View File

@ -5,7 +5,6 @@ use futures::{channel::mpsc, future, AsyncReadExt, Future, StreamExt};
use gpui::{AsyncAppContext, Entity, ImageData, ModelContext, ModelHandle, Task};
use postage::{sink::Sink, watch};
use rpc::proto::{RequestMessage, UsersResponse};
use settings::Settings;
use staff_mode::StaffMode;
use std::sync::{Arc, Weak};
use util::http::HttpClient;
@ -144,11 +143,13 @@ impl UserStore {
let fetch_metrics_id =
client.request(proto::GetPrivateUserInfo {}).log_err();
let (user, info) = futures::join!(fetch_user, fetch_metrics_id);
cx.read(|cx| {
client.telemetry.set_authenticated_user_info(
info.as_ref().map(|info| info.metrics_id.clone()),
info.as_ref().map(|info| info.staff).unwrap_or(false),
cx.read(|cx| cx.global::<Settings>().telemetry()),
);
cx,
)
});
cx.update(|cx| {
cx.update_default_global(|staff_mode: &mut StaffMode, _| {

View File

@ -366,7 +366,7 @@ async fn configure_disabled_globs(
fn toggle_copilot_globally(fs: Arc<dyn Fs>, cx: &mut AppContext) {
let show_copilot_suggestions = cx.global::<Settings>().show_copilot_suggestions(None, None);
update_settings_file(fs, cx, move |file_contents| {
update_settings_file::<Settings>(fs, cx, move |file_contents| {
file_contents.editor.show_copilot_suggestions = Some((!show_copilot_suggestions).into())
});
}
@ -376,7 +376,7 @@ fn toggle_copilot_for_language(language: Arc<str>, fs: Arc<dyn Fs>, cx: &mut App
.global::<Settings>()
.show_copilot_suggestions(Some(&language), None);
update_settings_file(fs, cx, move |file_contents| {
update_settings_file::<Settings>(fs, cx, move |file_contents| {
file_contents.languages.insert(
language,
settings::EditorSettings {
@ -388,7 +388,7 @@ fn toggle_copilot_for_language(language: Arc<str>, fs: Arc<dyn Fs>, cx: &mut App
}
fn hide_copilot(fs: Arc<dyn Fs>, cx: &mut AppContext) {
update_settings_file(fs, cx, move |file_contents| {
update_settings_file::<Settings>(fs, cx, move |file_contents| {
file_contents.features.copilot = Some(false)
});
}

View File

@ -22,7 +22,7 @@ pub mod test;
use aho_corasick::AhoCorasick;
use anyhow::{anyhow, Result};
use blink_manager::BlinkManager;
use client::ClickhouseEvent;
use client::{ClickhouseEvent, TelemetrySettings};
use clock::ReplicaId;
use collections::{BTreeMap, Bound, HashMap, HashSet, VecDeque};
use copilot::Copilot;
@ -6873,7 +6873,7 @@ impl Editor {
.untyped_user_settings()
.get("vim_mode")
== Some(&serde_json::Value::Bool(true));
let telemetry_settings = *settings::get_setting::<TelemetrySettings>(None, cx);
let settings = cx.global::<Settings>();
let extension = Path::new(file.file_name(cx))
@ -6887,7 +6887,7 @@ impl Editor {
_ => name,
},
json!({ "File Extension": extension, "Vim Mode": vim_mode, "In Clickhouse": true }),
settings.telemetry(),
telemetry_settings,
);
let event = ClickhouseEvent::Editor {
file_extension: extension.map(ToString::to_string),
@ -6903,7 +6903,7 @@ impl Editor {
.as_deref(),
),
};
telemetry.report_clickhouse_event(event, settings.telemetry())
telemetry.report_clickhouse_event(event, telemetry_settings)
}
}

View File

@ -27,7 +27,7 @@ glob.workspace = true
json_comments = "0.2"
lazy_static.workspace = true
postage.workspace = true
schemars = "0.8"
schemars.workspace = true
serde.workspace = true
serde_derive.workspace = true
serde_json.workspace = true

View File

@ -58,8 +58,6 @@ pub struct Settings {
pub language_overrides: HashMap<Arc<str>, EditorSettings>,
pub lsp: HashMap<Arc<str>, LspSettings>,
pub theme: Arc<Theme>,
pub telemetry_defaults: TelemetrySettings,
pub telemetry_overrides: TelemetrySettings,
pub base_keymap: BaseKeymap,
}
@ -133,8 +131,6 @@ impl Setting for Settings {
language_overrides: Default::default(),
lsp: defaults.lsp.clone(),
theme: themes.get(defaults.theme.as_ref().unwrap()).unwrap(),
telemetry_defaults: defaults.telemetry,
telemetry_overrides: Default::default(),
base_keymap: Default::default(),
features: Features {
copilot: defaults.features.copilot.unwrap(),
@ -260,30 +256,6 @@ impl BaseKeymap {
}
}
#[derive(Copy, Clone, Debug, Default, Serialize, Deserialize, JsonSchema)]
pub struct TelemetrySettings {
diagnostics: Option<bool>,
metrics: Option<bool>,
}
impl TelemetrySettings {
pub fn metrics(&self) -> bool {
self.metrics.unwrap()
}
pub fn diagnostics(&self) -> bool {
self.diagnostics.unwrap()
}
pub fn set_metrics(&mut self, value: bool) {
self.metrics = Some(value);
}
pub fn set_diagnostics(&mut self, value: bool) {
self.diagnostics = Some(value);
}
}
#[derive(Clone, Debug, Default)]
pub struct CopilotSettings {
pub disabled_globs: Vec<glob::Pattern>,
@ -569,8 +541,6 @@ pub struct SettingsFileContent {
#[serde(default)]
pub theme: Option<String>,
#[serde(default)]
pub telemetry: TelemetrySettings,
#[serde(default)]
pub base_keymap: Option<BaseKeymap>,
#[serde(default)]
pub features: FeaturesContent,
@ -685,8 +655,6 @@ impl Settings {
language_overrides: Default::default(),
lsp: defaults.lsp.clone(),
theme: themes.get(&defaults.theme.unwrap()).unwrap(),
telemetry_defaults: defaults.telemetry,
telemetry_overrides: Default::default(),
base_keymap: Default::default(),
features: Features {
copilot: defaults.features.copilot.unwrap(),
@ -758,7 +726,6 @@ impl Settings {
self.terminal_overrides.copy_on_select = data.terminal.copy_on_select;
self.terminal_overrides = data.terminal;
self.language_overrides = data.languages;
self.telemetry_overrides = data.telemetry;
self.lsp = data.lsp;
}
@ -869,27 +836,6 @@ impl Settings {
})
}
pub fn telemetry(&self) -> TelemetrySettings {
TelemetrySettings {
diagnostics: Some(self.telemetry_diagnostics()),
metrics: Some(self.telemetry_metrics()),
}
}
pub fn telemetry_diagnostics(&self) -> bool {
self.telemetry_overrides
.diagnostics
.or(self.telemetry_defaults.diagnostics)
.expect("missing default")
}
pub fn telemetry_metrics(&self) -> bool {
self.telemetry_overrides
.metrics
.or(self.telemetry_defaults.metrics)
.expect("missing default")
}
fn terminal_setting<F, R>(&self, f: F) -> R
where
F: Fn(&TerminalSettings) -> Option<R>,
@ -963,11 +909,6 @@ impl Settings {
language_overrides: Default::default(),
lsp: Default::default(),
theme: gpui::fonts::with_font_cache(cx.font_cache().clone(), Default::default),
telemetry_defaults: TelemetrySettings {
diagnostics: Some(true),
metrics: Some(true),
},
telemetry_overrides: Default::default(),
base_keymap: Default::default(),
features: Features { copilot: true },
}

View File

@ -1,6 +1,6 @@
use crate::{
settings_store::parse_json_with_comments, settings_store::SettingsStore, KeymapFileContent,
Setting, Settings, SettingsFileContent, DEFAULT_SETTINGS_ASSET_PATH,
Setting, Settings, DEFAULT_SETTINGS_ASSET_PATH,
};
use anyhow::Result;
use assets::Assets;
@ -158,10 +158,10 @@ async fn load_settings(fs: &Arc<dyn Fs>) -> Result<String> {
}
}
pub fn update_settings_file(
pub fn update_settings_file<T: Setting>(
fs: Arc<dyn Fs>,
cx: &mut AppContext,
update: impl 'static + Send + FnOnce(&mut SettingsFileContent),
update: impl 'static + Send + FnOnce(&mut T::FileContent),
) {
cx.spawn(|cx| async move {
let old_text = cx
@ -172,10 +172,7 @@ pub fn update_settings_file(
})
.await?;
let edits = cx.read(|cx| {
cx.global::<SettingsStore>()
.update::<Settings>(&old_text, update)
});
let edits = cx.read(|cx| cx.global::<SettingsStore>().update::<T>(&old_text, update));
let mut new_text = old_text;
for (range, replacement) in edits.into_iter().rev() {

View File

@ -129,7 +129,7 @@ impl PickerDelegate for ThemeSelectorDelegate {
self.selection_completed = true;
let theme_name = cx.global::<Settings>().theme.meta.name.clone();
update_settings_file(self.fs.clone(), cx, |settings_content| {
update_settings_file::<Settings>(self.fs.clone(), cx, |settings_content| {
settings_content.theme = Some(theme_name);
});

View File

@ -13,6 +13,7 @@ test-support = []
[dependencies]
anyhow.workspace = true
log.workspace = true
client = { path = "../client" }
editor = { path = "../editor" }
fs = { path = "../fs" }
fuzzy = { path = "../fuzzy" }

View File

@ -122,7 +122,7 @@ impl PickerDelegate for BaseKeymapSelectorDelegate {
fn confirm(&mut self, cx: &mut ViewContext<BaseKeymapSelector>) {
if let Some(selection) = self.matches.get(self.selected_index) {
let base_keymap = BaseKeymap::from_names(&selection.string);
update_settings_file(self.fs.clone(), cx, move |settings| {
update_settings_file::<Settings>(self.fs.clone(), cx, move |settings| {
settings.base_keymap = Some(base_keymap)
});
}

View File

@ -2,6 +2,7 @@ mod base_keymap_picker;
use std::{borrow::Cow, sync::Arc};
use client::TelemetrySettings;
use db::kvp::KEY_VALUE_STORE;
use gpui::{
elements::{Flex, Label, ParentElement},
@ -63,10 +64,7 @@ impl View for WelcomePage {
let width = theme.welcome.page_width;
let (diagnostics, metrics) = {
let telemetry = settings.telemetry();
(telemetry.diagnostics(), telemetry.metrics())
};
let telemetry_settings = *settings::get_setting::<TelemetrySettings>(None, cx);
enum Metrics {}
enum Diagnostics {}
@ -166,15 +164,17 @@ impl View for WelcomePage {
.with_style(theme.welcome.usage_note.container),
),
&theme.welcome.checkbox,
metrics,
telemetry_settings.metrics,
0,
cx,
|this, checked, cx| {
if let Some(workspace) = this.workspace.upgrade(cx) {
let fs = workspace.read(cx).app_state().fs.clone();
update_settings_file(fs, cx, move |file| {
file.telemetry.set_metrics(checked)
})
update_settings_file::<TelemetrySettings>(
fs,
cx,
move |setting| setting.metrics = Some(checked),
)
}
},
)
@ -185,15 +185,17 @@ impl View for WelcomePage {
theme::ui::checkbox::<Diagnostics, Self, _>(
"Send crash reports",
&theme.welcome.checkbox,
diagnostics,
telemetry_settings.diagnostics,
0,
cx,
|this, checked, cx| {
if let Some(workspace) = this.workspace.upgrade(cx) {
let fs = workspace.read(cx).app_state().fs.clone();
update_settings_file(fs, cx, move |file| {
file.telemetry.set_diagnostics(checked)
})
update_settings_file::<TelemetrySettings>(
fs,
cx,
move |setting| setting.diagnostics = Some(checked),
)
}
},
)

View File

@ -8,7 +8,7 @@ use cli::{
ipc::{self, IpcSender},
CliRequest, CliResponse, IpcHandshake,
};
use client::{self, UserStore, ZED_APP_VERSION, ZED_SECRET_CLIENT_TOKEN};
use client::{self, TelemetrySettings, UserStore, ZED_APP_VERSION, ZED_SECRET_CLIENT_TOKEN};
use db::kvp::KEY_VALUE_STORE;
use editor::Editor;
use futures::{
@ -187,7 +187,7 @@ fn main() {
client.telemetry().report_mixpanel_event(
"start app",
Default::default(),
cx.global::<Settings>().telemetry(),
*settings::get_setting::<TelemetrySettings>(None, cx),
);
let app_state = Arc::new(AppState {
@ -407,7 +407,7 @@ fn init_panic_hook(app_version: String) {
}
fn upload_previous_panics(http: Arc<dyn HttpClient>, cx: &mut AppContext) {
let diagnostics_telemetry = cx.global::<Settings>().telemetry_diagnostics();
let telemetry_settings = *settings::get_setting::<TelemetrySettings>(None, cx);
cx.background()
.spawn({
@ -437,7 +437,7 @@ fn upload_previous_panics(http: Arc<dyn HttpClient>, cx: &mut AppContext) {
continue;
};
if diagnostics_telemetry {
if telemetry_settings.diagnostics {
let panic_data_text = smol::fs::read_to_string(&child_path)
.await
.context("error reading panic file")?;