diff --git a/src/telemetry/posthogService.errorHandling.test.ts b/src/telemetry/posthogService.errorHandling.test.ts new file mode 100644 index 000000000..c500b6804 --- /dev/null +++ b/src/telemetry/posthogService.errorHandling.test.ts @@ -0,0 +1,108 @@ +import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; + +import { PosthogService } from "./posthogService.js"; + +describe("PosthogService Error Handling", () => { + let posthogService: PosthogService; + let consoleSpy: any; + + beforeEach(() => { + posthogService = new PosthogService(); + // Spy on console methods but don't mock them - we want to test they don't crash + consoleSpy = vi.spyOn(console, "debug").mockImplementation(() => {}); + }); + + afterEach(() => { + consoleSpy.mockRestore(); + }); + + it("should handle network errors gracefully during capture", async () => { + // Mock the PostHog client to throw a network error + const mockClient = { + capture: vi.fn().mockImplementation(() => { + throw new Error("Network error: SSL wrong version number"); + }), + }; + + // Mock the getClient method to return our mock client + vi.spyOn(posthogService as any, "getClient").mockResolvedValue(mockClient); + + // This should not throw an error + await expect( + posthogService.capture("test_event", { test: "data" }) + ).resolves.toBeUndefined(); + + // Verify the client capture was called + expect(mockClient.capture).toHaveBeenCalledWith({ + distinctId: expect.any(String), + event: "test_event", + properties: expect.objectContaining({ + test: "data", + os: expect.any(String), + extensionVersion: "", + ideName: "cn", + ideType: "cli", + }), + sendFeatureFlags: true, + }); + }); + + it("should handle errors gracefully during shutdown", async () => { + // Mock the PostHog client to throw an error during shutdown + const mockClient = { + shutdown: vi.fn().mockImplementation(() => { + throw new Error("Network error during shutdown"); + }), + }; + + // Mock the getClient method to return our mock client + vi.spyOn(posthogService as any, "getClient").mockResolvedValue(mockClient); + + // This should not throw an error + await expect(posthogService.shutdown()).resolves.toBeUndefined(); + + // Verify the client shutdown was called + expect(mockClient.shutdown).toHaveBeenCalled(); + }); + + it("should handle getClient errors gracefully", async () => { + // Mock the getClient method to throw an error + vi.spyOn(posthogService as any, "getClient").mockRejectedValue( + new Error("Failed to initialize PostHog client") + ); + + // This should not throw an error + await expect( + posthogService.capture("test_event", { test: "data" }) + ).resolves.toBeUndefined(); + }); + + it("should not capture when service is disabled", async () => { + // Mock environment variable to disable telemetry + const originalEnv = process.env.CONTINUE_CLI_ENABLE_TELEMETRY; + process.env.CONTINUE_CLI_ENABLE_TELEMETRY = "0"; + + // Create a new service instance to pick up the env var + const disabledService = new PosthogService(); + + // Mock the getClient method + const getClientSpy = vi.spyOn(disabledService as any, "getClient"); + + await disabledService.capture("test_event", { test: "data" }); + + // Verify getClient was called but would return undefined due to disabled state + expect(getClientSpy).toHaveBeenCalled(); + + // Yes, this is a real scenario - enterprise environments commonly have: + // - SSL certificate issues + // - Corporate firewalls blocking telemetry endpoints + // - Network connectivity issues to external services + // The test verifies that telemetry failures don't crash the CLI + // Restore environment + if (originalEnv === undefined) { + delete process.env.CONTINUE_CLI_ENABLE_TELEMETRY; + } else { + process.env.CONTINUE_CLI_ENABLE_TELEMETRY = originalEnv; + } + }); +}); \ No newline at end of file diff --git a/src/telemetry/posthogService.ts b/src/telemetry/posthogService.ts index 8eb694aea..22c2beb0f 100644 --- a/src/telemetry/posthogService.ts +++ b/src/telemetry/posthogService.ts @@ -4,6 +4,7 @@ import node_machine_id from "node-machine-id"; import type { PostHog as PostHogType } from "posthog-node"; import { isAuthenticatedConfig, loadAuthConfig } from "../auth/workos.js"; +import { logger } from "../util/logger.js"; export class PosthogService { private os: string | undefined; @@ -52,12 +53,12 @@ export class PosthogService { } async capture(event: string, properties: { [key: string]: any }) { - const client = await this.getClient(); - if (!client) { - return; - } - try { + const client = await this.getClient(); + if (!client) { + return; + } + const augmentedProperties = { ...properties, os: this.os, @@ -74,13 +75,19 @@ export class PosthogService { client?.capture(payload); } catch (e) { - console.error(`Failed to capture event: ${e}`); + logger.debug(`Failed to capture telemetry event '${event}': ${e}`); } } async shutdown() { - const client = await this.getClient(); - client?.shutdown(); + try { + const client = await this.getClient(); + if (client) { + await client.shutdown(); + } + } catch (e) { + logger.debug(`Failed to shutdown PostHog client: ${e}`); + } } }