Elffuss BraidHub

kikocis/continue public

deff15df45d1 · 7.4 KiBRawPermalink
1import fs from "fs";
2import path from "path";
3
4import {
5 allDevEventNames,
6 DataLogLevel,
7 DevDataLogEvent,
8 devDataVersionedSchemas,
9} from "@continuedev/config-yaml";
10import { fetchwithRequestOptions } from "@continuedev/fetch";
11import * as URI from "uri-js";
12import { fileURLToPath } from "url";
13import { AnyZodObject } from "zod";
14import { Core } from "../core.js";
15import { IdeInfo, IdeSettings } from "../index.js";
16import { getDevDataFilePath } from "../util/paths.js";
17import { joinPathsToUri } from "../util/uri.js";
18
19const DEFAULT_DEV_DATA_LEVEL: DataLogLevel = "all";
20export const LOCAL_DEV_DATA_VERSION = "0.2.0";
21export 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 logDevData(event: DevDataLogEvent) {
72 // Local logs (always on for all levels)
73 try {
74 const filepath: string = getDevDataFilePath(
75 event.name,
76 LOCAL_DEV_DATA_VERSION,
77 );
78 const localSchema =
79 devDataVersionedSchemas[LOCAL_DEV_DATA_VERSION]["all"][event.name];
80
81 if (!localSchema) {
82 throw new Error(
83 `Schema ${LOCAL_DEV_DATA_VERSION} doesn't exist at level "all"`,
84 );
85 }
86
87 const eventDataWithBaseValues = await this.addBaseValues(
88 event.data,
89 event.name,
90 LOCAL_DEV_DATA_VERSION,
91 localSchema,
92 );
93
94 const parsed = localSchema?.safeParse(eventDataWithBaseValues);
95 if (parsed?.success) {
96 fs.writeFileSync(filepath, `${JSON.stringify(parsed.data)}\n`, {
97 flag: "a",
98 });
99 }
100 } catch (error) {
101 console.error("Error logging local dev data:", error);
102 }
103
104 // Remote logs
105 const config = (await this.core?.configHandler.loadConfig())?.config;
106 if (config?.data?.length) {
107 await Promise.allSettled(
108 config.data.map(async (dataConfig) => {
109 try {
110 // First extract the data schema based on the version and level
111 const { schema } = dataConfig;
112
113 const level = dataConfig.level ?? DEFAULT_DEV_DATA_LEVEL;
114
115 // Skip event if `events` is specified and does not include the event
116 const events = dataConfig.events ?? allDevEventNames;
117 if (!events.includes(event.name)) {
118 return;
119 }
120
121 const versionSchemas = devDataVersionedSchemas[schema];
122 if (!versionSchemas) {
123 throw new Error(
124 `Attempting to log dev data to non-existent version ${schema}`,
125 );
126 }
127
128 const levelSchemas = versionSchemas[level];
129 if (!levelSchemas) {
130 throw new Error(
131 `Attempting to log dev data at level ${level} for version ${schema} which does not exist`,
132 );
133 }
134
135 const zodSchema = levelSchemas[event.name];
136 if (!zodSchema) {
137 throw new Error(
138 `Attempting to log dev data for event ${event.name} at level ${level} for version ${schema}: no schema found`,
139 );
140 }
141
142 const eventDataWithBaseValues = await this.addBaseValues(
143 event.data,
144 event.name,
145 schema,
146 zodSchema,
147 );
148
149 const parsed = zodSchema.safeParse(eventDataWithBaseValues);
150 if (!parsed.success) {
151 throw new Error(
152 `Failed to parse event data for event ${event.name} and schema ${schema}\n:${parsed.error.toString()}`,
153 );
154 }
155
156 const uriComponents = URI.parse(dataConfig.destination);
157
158 // Send to remote server
159 if (
160 uriComponents.scheme === "https" ||
161 uriComponents.scheme === "http"
162 ) {
163 const headers: Record<string, string> = {
164 "Content-Type": "application/json",
165 };
166 if (dataConfig.apiKey) {
167 headers["Authorization"] = `Bearer ${dataConfig.apiKey}`;
168 }
169
170 // For events going to Continue, overwrite the access token
171 if (
172 uriComponents.host?.endsWith(".continue.dev") ||
173 uriComponents.host === "continue.dev"
174 ) {
175 //
176 const accessToken =
177 await this.core?.configHandler.controlPlaneClient.getAccessToken();
178 headers["Authorization"] = `Bearer ${accessToken}`;
179 }
180 const profileId =
181 this.core?.configHandler.currentProfile?.profileDescription
182 .id ?? "";
183 const response = await fetchwithRequestOptions(
184 dataConfig.destination,
185 {
186 method: "POST",
187 headers,
188 body: JSON.stringify({
189 name: event.name,
190 data: parsed.data,
191 schema,
192 level,
193 profileId,
194 }),
195 },
196 dataConfig.requestOptions,
197 );
198 if (!response.ok) {
199 throw new Error(
200 `Post request failed. ${response.status}: ${response.statusText}`,
201 );
202 }
203 } else if (uriComponents.scheme === "file") {
204 // Write to jsonc file for local file URIs
205 const dirUri = joinPathsToUri(dataConfig.destination, schema);
206 const dirPath = fileURLToPath(dirUri);
207
208 if (!fs.existsSync(dirPath)) {
209 fs.mkdirSync(dirPath, { recursive: true });
210 }
211 const filepath = path.join(dirPath, `${event.name}.jsonl`);
212 const jsonLine = JSON.stringify(event.data);
213 fs.writeFileSync(filepath, `${jsonLine}\n`, { flag: "a" });
214 } else {
215 throw new Error(`Unsupported URI scheme ${uriComponents.scheme}`);
216 }
217 } catch (error) {
218 console.error(
219 `Error logging data to ${dataConfig.destination}: ${error instanceof Error ? error.message : error}`,
220 );
221 }
222 }),
223 );
224 }
225 }
226}