Elffuss BraidHub

kikocis/continue public

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