Elffuss BraidHub

kikocis/continue public

7a512fed920f · 3.3 KiBRawPermalink
1import dns from "dns/promises";
2import os from "node:os";
3
4import node_machine_id from "node-machine-id";
5import type { PostHog as PostHogType } from "posthog-node";
6
7import { isAuthenticatedConfig, loadAuthConfig } from "../auth/workos.js";
8import { logger } from "../util/logger.js";
9
10export class PosthogService {
11 private os: string | undefined;
12 private uniqueId: string;
13
14 constructor() {
15 this.os = os.platform();
16 this.uniqueId = this.getEventUserId();
17 }
18
19 private _hasInternetConnection: boolean | undefined = undefined;
20 private async hasInternetConnection() {
21 const refetchConnection = async () => {
22 try {
23 await dns.lookup("app.posthog.com");
24 this._hasInternetConnection = true;
25 } catch {
26 this._hasInternetConnection = false;
27 }
28 };
29
30 if (typeof this._hasInternetConnection !== "undefined") {
31 void refetchConnection(); // check in background if connection became available
32 return this._hasInternetConnection;
33 }
34
35 await refetchConnection();
36 return this._hasInternetConnection;
37 }
38
39 get isEnabled() {
40 return process.env.CONTINUE_CLI_ENABLE_TELEMETRY !== "0";
41 }
42
43 private _client: PostHogType | undefined;
44 private async getClient() {
45 if (!(await this.hasInternetConnection())) {
46 this._client = undefined;
47 logger.warn("No internet connection, skipping telemetry");
48 } else if (this.isEnabled) {
49 if (!this._client) {
50 const { PostHog } = await import("posthog-node");
51 this._client = new PostHog(
52 "phc_JS6XFROuNbhJtVCEdTSYk6gl5ArRrTNMpCcguAXlSPs",
53 {
54 host: "https://app.posthog.com",
55 },
56 );
57 logger.debug("Initialized telemetry");
58 }
59 } else {
60 this._client = undefined;
61 }
62 return this._client;
63 }
64
65 /**
66 * - Continue user id if signed in
67 * - Unique machine id if not signed in
68 */
69 private getEventUserId(): string {
70 const authConfig = loadAuthConfig();
71
72 if (isAuthenticatedConfig(authConfig)) {
73 return authConfig.userId;
74 }
75
76 // Fall back to unique machine id if not signed in
77 return node_machine_id.machineIdSync();
78 }
79
80 async capture(event: string, properties: { [key: string]: any }) {
81 try {
82 const client = await this.getClient();
83 if (!client) {
84 return;
85 }
86
87 const augmentedProperties = {
88 ...properties,
89 os: this.os,
90 extensionVersion: "", // TODO cn version
91 ideName: "cn",
92 ideType: "cli",
93 };
94 const payload = {
95 distinctId: this.uniqueId,
96 event,
97 properties: augmentedProperties,
98 sendFeatureFlags: true,
99 };
100
101 client?.capture(payload);
102 } catch (e) {
103 logger.debug(`Failed to capture telemetry event '${event}': ${e}`);
104 }
105 }
106
107 async shutdown() {
108 try {
109 const client = await this.getClient();
110 if (client) {
111 // Set a timeout for shutdown to prevent hanging
112 const shutdownPromise = client.shutdown();
113 const timeoutPromise = new Promise((_, reject) =>
114 setTimeout(() => reject(new Error("Shutdown timeout")), 5000),
115 );
116
117 await Promise.race([shutdownPromise, timeoutPromise]);
118 }
119 } catch (e) {
120 logger.debug(`Failed to shutdown PostHog client: ${e}`);
121 }
122 }
123}
124
125export const posthogService = new PosthogService();