| 1 | import fs from "fs"; |
| 2 | import path from "path"; |
| 3 | |
| 4 | import { |
| 5 | allDevEventNames, |
| 6 | DataLogLevel, |
| 7 | DevDataLogEvent, |
| 8 | devDataVersionedSchemas, |
| 9 | } from "@continuedev/config-yaml"; |
| 10 | import { fetchwithRequestOptions } from "@continuedev/fetch"; |
| 11 | import * as URI from "uri-js"; |
| 12 | import { fileURLToPath } from "url"; |
| 13 | import { AnyZodObject } from "zod"; |
| 14 | import { Core } from "../core.js"; |
| 15 | import { ContinueConfig, IdeInfo, IdeSettings } from "../index.js"; |
| 16 | import { getDevDataFilePath } from "../util/paths.js"; |
| 17 | import { joinPathsToUri } from "../util/uri.js"; |
| 18 | |
| 19 | const DEFAULT_DEV_DATA_LEVEL: DataLogLevel = "all"; |
| 20 | export const LOCAL_DEV_DATA_VERSION = "0.2.0"; |
| 21 | export class DataLogger { |
| 22 | private static instance: DataLogger | null = null; |
| 23 | core?: Core; |
| 24 | ideSettingsPromise?: Promise<IdeSettings>; |
| 25 | ideInfoPromise?: Promise<IdeInfo>; |
| 26 | |
| 27 | private constructor() {} |
| 28 | |
| 29 | public static getInstance(): DataLogger { |
| 30 | if (DataLogger.instance === null) { |
| 31 | DataLogger.instance = new DataLogger(); |
| 32 | } |
| 33 | return DataLogger.instance; |
| 34 | } |
| 35 | |
| 36 | async addBaseValues( |
| 37 | body: Record<string, any>, |
| 38 | eventName: string, |
| 39 | schema: string, |
| 40 | zodSchema: AnyZodObject, |
| 41 | ): Promise<Record<string, any>> { |
| 42 | const newBody = { ...body }; |
| 43 | const ideSettings = await this.ideSettingsPromise; |
| 44 | const ideInfo = await this.ideInfoPromise; |
| 45 | |
| 46 | if ("eventName" in zodSchema.shape) { |
| 47 | newBody.eventName = eventName; |
| 48 | } |
| 49 | if (!newBody.timestamp && "timestamp" in zodSchema.shape) { |
| 50 | newBody.timestamp = new Date().toISOString(); |
| 51 | } |
| 52 | if ("schema" in zodSchema.shape) { |
| 53 | newBody.schema = schema; |
| 54 | } |
| 55 | if ("userAgent" in zodSchema.shape) { |
| 56 | newBody.userAgent = ideInfo |
| 57 | ? `${ideInfo.name}/${ideInfo.version} (Continue/${ideInfo.extensionVersion})` |
| 58 | : "Unknown/Unknown (Continue/Unknown)"; |
| 59 | } |
| 60 | if ("selectedProfileId" in zodSchema.shape) { |
| 61 | newBody.selectedProfileId = |
| 62 | this.core?.configHandler.currentProfile?.profileDescription.id ?? ""; |
| 63 | } |
| 64 | if ("userId" in zodSchema.shape) { |
| 65 | newBody.userId = ideSettings?.userToken ?? ""; |
| 66 | } |
| 67 | |
| 68 | return newBody; |
| 69 | } |
| 70 | |
| 71 | async logLocalData(event: DevDataLogEvent) { |
| 72 | try { |
| 73 | const filepath: string = getDevDataFilePath( |
| 74 | event.name, |
| 75 | LOCAL_DEV_DATA_VERSION, |
| 76 | ); |
| 77 | const localSchema = |
| 78 | devDataVersionedSchemas[LOCAL_DEV_DATA_VERSION]["all"][event.name]; |
| 79 | |
| 80 | if (!localSchema) { |
| 81 | throw new Error( |
| 82 | `Schema ${LOCAL_DEV_DATA_VERSION} doesn't exist at level "all"`, |
| 83 | ); |
| 84 | } |
| 85 | |
| 86 | const eventDataWithBaseValues = await this.addBaseValues( |
| 87 | event.data, |
| 88 | event.name, |
| 89 | LOCAL_DEV_DATA_VERSION, |
| 90 | localSchema, |
| 91 | ); |
| 92 | |
| 93 | const parsed = localSchema?.safeParse(eventDataWithBaseValues); |
| 94 | if (parsed?.success) { |
| 95 | fs.writeFileSync(filepath, `${JSON.stringify(parsed.data)}\n`, { |
| 96 | flag: "a", |
| 97 | }); |
| 98 | } |
| 99 | } catch (error) { |
| 100 | console.error("Error logging local dev data:", error); |
| 101 | } |
| 102 | } |
| 103 | |
| 104 | async logDevData(event: DevDataLogEvent) { |
| 105 | // Local logs (always on for all levels) |
| 106 | await this.logLocalData(event); |
| 107 | |
| 108 | // Remote logs |
| 109 | const config = (await this.core?.configHandler.loadConfig())?.config; |
| 110 | if (config?.data?.length) { |
| 111 | await Promise.allSettled( |
| 112 | config.data.map((dataConfig) => |
| 113 | this.logToOneDestination(dataConfig, event), |
| 114 | ), |
| 115 | ); |
| 116 | } |
| 117 | } |
| 118 | |
| 119 | async parseEventData( |
| 120 | event: DevDataLogEvent, |
| 121 | schema: string, |
| 122 | level: "all" | "noCode", |
| 123 | ) { |
| 124 | const versionSchemas = devDataVersionedSchemas[schema]; |
| 125 | if (!versionSchemas) { |
| 126 | throw new Error( |
| 127 | `Attempting to log dev data to non-existent version ${schema}`, |
| 128 | ); |
| 129 | } |
| 130 | |
| 131 | const levelSchemas = versionSchemas[level]; |
| 132 | if (!levelSchemas) { |
| 133 | throw new Error( |
| 134 | `Attempting to log dev data at level ${level} for version ${schema} which does not exist`, |
| 135 | ); |
| 136 | } |
| 137 | |
| 138 | const zodSchema = levelSchemas[event.name]; |
| 139 | if (!zodSchema) { |
| 140 | throw new Error( |
| 141 | `Attempting to log dev data for event ${event.name} at level ${level} for version ${schema}: no schema found`, |
| 142 | ); |
| 143 | } |
| 144 | |
| 145 | const eventDataWithBaseValues = await this.addBaseValues( |
| 146 | event.data, |
| 147 | event.name, |
| 148 | schema, |
| 149 | zodSchema, |
| 150 | ); |
| 151 | |
| 152 | const parsed = zodSchema.safeParse(eventDataWithBaseValues); |
| 153 | if (!parsed.success) { |
| 154 | throw new Error( |
| 155 | `Failed to parse event data for event ${event.name} and schema ${schema}\n:${parsed.error.toString()}`, |
| 156 | ); |
| 157 | } |
| 158 | |
| 159 | return parsed.data; |
| 160 | } |
| 161 | |
| 162 | async logToOneDestination( |
| 163 | dataConfig: NonNullable<ContinueConfig["data"]>[number], |
| 164 | event: DevDataLogEvent, |
| 165 | ) { |
| 166 | try { |
| 167 | if (!dataConfig) { |
| 168 | return; |
| 169 | } |
| 170 | |
| 171 | // First extract the data schema based on the version and level |
| 172 | const { schema } = dataConfig; |
| 173 | const level = dataConfig.level ?? DEFAULT_DEV_DATA_LEVEL; |
| 174 | |
| 175 | // Skip event if `events` is specified and does not include the event |
| 176 | const events = dataConfig.events ?? allDevEventNames; |
| 177 | if (!events.includes(event.name)) { |
| 178 | return; |
| 179 | } |
| 180 | |
| 181 | // Parse the event data, throwing if it fails |
| 182 | const parsed = await this.parseEventData(event, schema, level); |
| 183 | |
| 184 | const uriComponents = URI.parse(dataConfig.destination); |
| 185 | |
| 186 | // Send to remote server |
| 187 | if (uriComponents.scheme === "https" || uriComponents.scheme === "http") { |
| 188 | const headers: Record<string, string> = { |
| 189 | "Content-Type": "application/json", |
| 190 | }; |
| 191 | |
| 192 | // If an API key is provided, use it, otherwise use the Continue access token |
| 193 | if (dataConfig.apiKey) { |
| 194 | headers["Authorization"] = `Bearer ${dataConfig.apiKey}`; |
| 195 | } else { |
| 196 | const accessToken = |
| 197 | await this.core?.configHandler.controlPlaneClient.getAccessToken(); |
| 198 | headers["Authorization"] = `Bearer ${accessToken}`; |
| 199 | } |
| 200 | |
| 201 | const profileId = |
| 202 | this.core?.configHandler.currentProfile?.profileDescription.id ?? ""; |
| 203 | const response = await fetchwithRequestOptions( |
| 204 | dataConfig.destination, |
| 205 | { |
| 206 | method: "POST", |
| 207 | headers, |
| 208 | body: JSON.stringify({ |
| 209 | name: event.name, |
| 210 | data: parsed, |
| 211 | schema, |
| 212 | level, |
| 213 | profileId, |
| 214 | }), |
| 215 | }, |
| 216 | dataConfig.requestOptions, |
| 217 | ); |
| 218 | if (!response.ok) { |
| 219 | throw new Error( |
| 220 | `Post request failed. ${response.status}: ${response.statusText}`, |
| 221 | ); |
| 222 | } |
| 223 | } else if (uriComponents.scheme === "file") { |
| 224 | // Write to jsonc file for local file URIs |
| 225 | const dirUri = joinPathsToUri(dataConfig.destination, schema); |
| 226 | const dirPath = fileURLToPath(dirUri); |
| 227 | |
| 228 | if (!fs.existsSync(dirPath)) { |
| 229 | fs.mkdirSync(dirPath, { recursive: true }); |
| 230 | } |
| 231 | const filepath = path.join(dirPath, `${event.name}.jsonl`); |
| 232 | const jsonLine = JSON.stringify(event.data); |
| 233 | fs.writeFileSync(filepath, `${jsonLine}\n`, { flag: "a" }); |
| 234 | } else { |
| 235 | throw new Error(`Unsupported URI scheme ${uriComponents.scheme}`); |
| 236 | } |
| 237 | } catch (error) { |
| 238 | console.error( |
| 239 | `Error logging data to ${dataConfig.destination}: ${error instanceof Error ? error.message : error}`, |
| 240 | ); |
| 241 | } |
| 242 | } |
| 243 | } |