Merge pull request #2687 from continuedev/nate/catch-json-parse-err

catch JSON.parse errs, better logging for extension activation errs
This commit is contained in:
Nate Sesti 2024-10-25 16:14:21 -07:00 • committed by GitHub
commit 2c5cd283d3
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
6 changed files with 121 additions and 64 deletions

View file

@ -1,6 +1,6 @@
import fs from "node:fs";
import { getGlobalContextFilePath } from "./paths";
import { EmbeddingsProvider } from "../";
import { getGlobalContextFilePath } from "./paths";
export type GlobalContextType = {
indexingPaused: boolean;
@ -37,7 +37,15 @@ export class GlobalContext {
);
} else {
const data = fs.readFileSync(getGlobalContextFilePath(), "utf-8");
const parsed = JSON.parse(data);
let parsed;
try {
parsed = JSON.parse(data);
} catch (e: any) {
console.warn(`Error updating global context: ${e}`);
return;
}
parsed[key] = value;
fs.writeFileSync(
getGlobalContextFilePath(),
@ -54,7 +62,12 @@ export class GlobalContext {
}
const data = fs.readFileSync(getGlobalContextFilePath(), "utf-8");
const parsed = JSON.parse(data);
return parsed[key];
try {
const parsed = JSON.parse(data);
return parsed[key];
} catch (e: any) {
console.warn(`Error parsing global context: ${e}`);
return undefined;
}
}
}

View file

@ -3,6 +3,18 @@ import { PersistedSessionInfo, SessionInfo } from "../index.js";
import { ListHistoryOptions } from "../protocol/core.js";
import { getSessionFilePath, getSessionsListPath } from "./paths.js";
function safeParseArray<T>(
value: string,
errorMessage: string = "Error parsing array",
): T[] | undefined {
try {
return JSON.parse(value) as T[];
} catch (e: any) {
console.warn(`${errorMessage}: ${e}`);
return undefined;
}
}
class HistoryManager {
list(options: ListHistoryOptions): SessionInfo[] {
const filepath = getSessionsListPath();
@ -10,7 +22,9 @@ class HistoryManager {
return [];
}
const content = fs.readFileSync(filepath, "utf8");
let sessions = JSON.parse(content).filter((session: any) => {
let sessions = safeParseArray<SessionInfo>(content) ?? [];
sessions = sessions.filter((session: any) => {
// Filter out old format
return typeof session.session_id !== "string";
});
@ -35,14 +49,11 @@ class HistoryManager {
// Read and update the sessions list
const sessionsListFile = getSessionsListPath();
const sessionsListRaw = fs.readFileSync(sessionsListFile, "utf-8");
let sessionsList: SessionInfo[];
try {
sessionsList = JSON.parse(sessionsListRaw);
} catch (error) {
throw new Error(
`It looks like there is a JSON formatting error in your sessions.json file (${sessionsListFile}). Please fix this before creating a new session.`,
);
}
let sessionsList =
safeParseArray<SessionInfo>(
sessionsListRaw,
"Error parsing sessions.json",
) ?? [];
sessionsList = sessionsList.filter(
(session) => session.sessionId !== sessionId,

View file

@ -13,22 +13,34 @@ export class Telemetry {
event: string,
properties: { [key: string]: any },
sendToTeam: boolean = false,
isExtensionActivationError: boolean = false,
) {
if (process.env.NODE_ENV === "test") {
return;
}
try {
Telemetry.client?.capture({
const augmentedProperties = {
...properties,
os: Telemetry.os,
extensionVersion: Telemetry.ideInfo?.extensionVersion,
ideName: Telemetry.ideInfo?.name,
ideType: Telemetry.ideInfo?.ideType,
};
const payload = {
distinctId: Telemetry.uniqueId,
event,
properties: {
...properties,
os: Telemetry.os,
extensionVersion: Telemetry.ideInfo?.extensionVersion,
ideName: Telemetry.ideInfo?.name,
ideType: Telemetry.ideInfo?.ideType,
},
});
properties: augmentedProperties,
};
// In cases where an extremely early fatal error occurs, we may not have initialized yet
if (isExtensionActivationError && !Telemetry.client) {
const client = await Telemetry.getTelemetryClient();
client?.capture(payload);
return;
}
if (process.env.NODE_ENV === "test") {
return;
}
Telemetry.client?.capture(payload);
if (sendToTeam) {
void TeamAnalytics.capture(event, properties);
@ -42,6 +54,17 @@ export class Telemetry {
Telemetry.client?.shutdown();
}
static async getTelemetryClient() {
try {
const { PostHog } = await import("posthog-node");
return new PostHog("phc_JS6XFROuNbhJtVCEdTSYk6gl5ArRrTNMpCcguAXlSPs", {
host: "https://app.posthog.com",
});
} catch (e) {
console.error(`Failed to setup telemetry: ${e}`);
}
}
static async setup(allow: boolean, uniqueId: string, ideInfo: IdeInfo) {
Telemetry.uniqueId = uniqueId;
Telemetry.os = os.platform();
@ -49,20 +72,8 @@ export class Telemetry {
if (!allow || process.env.NODE_ENV === "test") {
Telemetry.client = undefined;
} else {
try {
if (!Telemetry.client) {
const { PostHog } = await import("posthog-node");
Telemetry.client = new PostHog(
"phc_JS6XFROuNbhJtVCEdTSYk6gl5ArRrTNMpCcguAXlSPs",
{
host: "https://app.posthog.com",
},
);
}
} catch (e) {
console.error(`Failed to setup telemetry: ${e}`);
}
} else if (!Telemetry.client) {
Telemetry.client = await Telemetry.getTelemetryClient();
}
}
}

View file

@ -1,11 +1,9 @@
import { getContinueRcPath, getTsConfigPath, migrate } from "core/util/paths";
import { getContinueRcPath, getTsConfigPath } from "core/util/paths";
import { Telemetry } from "core/util/posthog";
import path from "node:path";
import * as vscode from "vscode";
import { VsCodeExtension } from "../extension/VsCodeExtension";
import registerQuickFixProvider from "../lang-server/codeActions";
import { getExtensionVersion } from "../util/util";
import { getExtensionUri } from "../util/vscode";
import { VsCodeContinueApi } from "./api";
import { setupInlineTips } from "./inlineTips";

View file

@ -3,18 +3,31 @@
*/
import { setupCa } from "core/util/ca";
import { extractMinimalStackTraceInfo } from "core/util/extractMinimalStackTraceInfo";
import { Telemetry } from "core/util/posthog";
import * as vscode from "vscode";
import { getExtensionVersion } from "./util/util";
async function dynamicImportAndActivate(context: vscode.ExtensionContext) {
await setupCa();
const { activateExtension } = await import("./activation/activate");
try {
return activateExtension(context);
} catch (e) {
return await activateExtension(context);
}
export function activate(context: vscode.ExtensionContext) {
return dynamicImportAndActivate(context).catch((e) => {
console.log("Error activating extension: ", e);
Telemetry.capture(
"vscode_extension_activation_error",
{
stack: extractMinimalStackTraceInfo(e.stack),
message: e.message,
},
false,
true,
);
vscode.window
.showInformationMessage(
.showWarningMessage(
"Error activating the Continue extension.",
"View Logs",
"Retry",
@ -27,12 +40,7 @@ async function dynamicImportAndActivate(context: vscode.ExtensionContext) {
vscode.commands.executeCommand("workbench.action.reloadWindow");
}
});
}
}
export function activate(context: vscode.ExtensionContext) {
setupCa();
return dynamicImportAndActivate(context);
});
}
export function deactivate() {

View file

@ -94,31 +94,42 @@ export class WorkOsAuthProvider implements AuthenticationProvider, Disposable {
this.secretStorage = new SecretStorage(context);
}
private decodeJwt(jwt: string): any {
const decodedToken = JSON.parse(
Buffer.from(jwt.split(".")[1], "base64").toString(),
);
return decodedToken;
private decodeJwt(jwt: string): Record<string, any> | null {
try {
const decodedToken = JSON.parse(
Buffer.from(jwt.split(".")[1], "base64").toString(),
);
return decodedToken;
} catch (e: any) {
console.warn(`Error decoding JWT: ${e}`);
return null;
}
}
private getExpirationTimeMs(jwt: string): number {
const decodedToken = this.decodeJwt(jwt);
if (!decodedToken) {
return WorkOsAuthProvider.EXPIRATION_TIME_MS;
}
return decodedToken.exp && decodedToken.iat
? (decodedToken.exp - decodedToken.iat) * 1000
: WorkOsAuthProvider.EXPIRATION_TIME_MS;
}
private jwtIsExpired(jwt: string): boolean {
private jwtIsExpiredOrInvalid(jwt: string): boolean {
const decodedToken = this.decodeJwt(jwt);
if (!decodedToken) {
return true;
}
return decodedToken.exp * 1000 < Date.now();
}
private async debugAccessTokenValidity(jwt: string, refreshToken: string) {
const expired = this.jwtIsExpired(jwt);
if (expired) {
console.debug(`Invalid JWT: ${expired}`);
const expiredOrInvalid = this.jwtIsExpiredOrInvalid(jwt);
if (expiredOrInvalid) {
console.debug("Invalid JWT");
} else {
console.debug(`Valid JWT: ${expired}`);
console.debug("Valid JWT");
}
}
@ -135,8 +146,13 @@ export class WorkOsAuthProvider implements AuthenticationProvider, Disposable {
return [];
}
const value = JSON.parse(data) as ContinueAuthenticationSession[];
return value;
try {
const value = JSON.parse(data) as ContinueAuthenticationSession[];
return value;
} catch (e: any) {
console.warn(`Error parsing sessions.json: ${e}`);
return [];
}
}
get onDidChangeSessions() {