fix: Skip creating `usage_anonymous_id` when TABBY_DISABLE_USAGE_COLLECTION is set (#864)

* dont write file if tracking is disabled

* remove comment, id is optional

* Update usage.rs

---------

Co-authored-by: Meng Zhang <meng@tabbyml.com>
wsxiaoys-patch-3
Magnus F 2023-11-23 16:46:07 +01:00 committed by GitHub
parent 9746865b8f
commit 821ca2dead
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 26 additions and 23 deletions

View File

@ -11,7 +11,7 @@ static USAGE_API_ENDPOINT: &str = "https://app.tabbyml.com/api/usage";
struct UsageTracker { struct UsageTracker {
id: String, id: String,
client: Option<Client>, client: Client,
} }
impl UsageTracker { impl UsageTracker {
@ -42,32 +42,27 @@ impl UsageTracker {
} }
let id = fs::read_to_string(usage_id_file()).expect("Failed to read usage id"); let id = fs::read_to_string(usage_id_file()).expect("Failed to read usage id");
let client = if std::env::var("TABBY_DISABLE_USAGE_COLLECTION").is_ok() { Self {
None id,
} else { client: Client::new(),
Some(Client::new()) }
};
Self { id, client }
} }
async fn capture<T>(&self, event: &str, properties: T) async fn capture<T>(&self, event: &str, properties: T)
where where
T: Serialize, T: Serialize,
{ {
if let Some(client) = &self.client { let payload = Payload {
let payload = Payload { distinct_id: &self.id,
distinct_id: self.id.as_ref(), event,
event, properties,
properties, };
}; self.client
client .post(USAGE_API_ENDPOINT)
.post(USAGE_API_ENDPOINT) .json(&payload)
.json(&payload) .send()
.send() .await
.await .ok();
.ok();
}
} }
} }
@ -80,12 +75,20 @@ struct Payload<'a, T> {
} }
lazy_static! { lazy_static! {
static ref TRACKER: UsageTracker = UsageTracker::new(); static ref TRACKER: Option<UsageTracker> = {
if std::env::var("TABBY_DISABLE_USAGE_COLLECTION").is_ok() {
None
} else {
Some(UsageTracker::new())
}
};
} }
pub async fn capture<T>(event: &str, properties: T) pub async fn capture<T>(event: &str, properties: T)
where where
T: Serialize, T: Serialize,
{ {
TRACKER.capture(event, properties).await if let Some(tracker) = TRACKER.as_ref() {
tracker.capture(event, properties).await;
}
} }