feat(cli): skip telemetry if there is no internet connection
This commit is contained in:
parent
e37b9b0bce
commit
8c8efd7ed1
1 changed files with 33 additions and 2 deletions
|
|
@ -1,3 +1,4 @@
|
|||
import dns from "dns/promises";
|
||||
import os from "node:os";
|
||||
|
||||
import node_machine_id from "node-machine-id";
|
||||
|
|
@ -15,13 +16,36 @@ export class PosthogService {
|
|||
this.uniqueId = this.getEventUserId();
|
||||
}
|
||||
|
||||
private _hasInternetConnection: boolean | undefined = undefined;
|
||||
private async hasInternetConnection() {
|
||||
const refetchConnection = async () => {
|
||||
try {
|
||||
await dns.lookup("app.posthog.com");
|
||||
this._hasInternetConnection = true;
|
||||
} catch {
|
||||
this._hasInternetConnection = false;
|
||||
}
|
||||
};
|
||||
|
||||
if (typeof this._hasInternetConnection !== "undefined") {
|
||||
void refetchConnection(); // check in background if connection became available
|
||||
return this._hasInternetConnection;
|
||||
}
|
||||
|
||||
await refetchConnection();
|
||||
return this._hasInternetConnection;
|
||||
}
|
||||
|
||||
get isEnabled() {
|
||||
return process.env.CONTINUE_CLI_ENABLE_TELEMETRY !== "0";
|
||||
}
|
||||
|
||||
private _client: PostHogType | undefined;
|
||||
private async getClient() {
|
||||
if (this.isEnabled) {
|
||||
if (!(await this.hasInternetConnection())) {
|
||||
this._client = undefined;
|
||||
logger.warn("No internet connection, skipping telemetry");
|
||||
} else if (this.isEnabled) {
|
||||
if (!this._client) {
|
||||
const { PostHog } = await import("posthog-node");
|
||||
this._client = new PostHog(
|
||||
|
|
@ -30,6 +54,7 @@ export class PosthogService {
|
|||
host: "https://app.posthog.com",
|
||||
},
|
||||
);
|
||||
logger.debug("Initialized telemetry");
|
||||
}
|
||||
} else {
|
||||
this._client = undefined;
|
||||
|
|
@ -83,7 +108,13 @@ export class PosthogService {
|
|||
try {
|
||||
const client = await this.getClient();
|
||||
if (client) {
|
||||
await client.shutdown();
|
||||
// Set a timeout for shutdown to prevent hanging
|
||||
const shutdownPromise = client.shutdown();
|
||||
const timeoutPromise = new Promise((_, reject) =>
|
||||
setTimeout(() => reject(new Error("Shutdown timeout")), 5000),
|
||||
);
|
||||
|
||||
await Promise.race([shutdownPromise, timeoutPromise]);
|
||||
}
|
||||
} catch (e) {
|
||||
logger.debug(`Failed to shutdown PostHog client: ${e}`);
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue