-
Notifications
You must be signed in to change notification settings - Fork 97
Expand file tree
/
Copy pathutils.ts
More file actions
331 lines (296 loc) · 9.94 KB
/
utils.ts
File metadata and controls
331 lines (296 loc) · 9.94 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
import * as vscode from 'vscode';
import {
ContextProviderApiV1,
ResolveRequest,
SupportedContextItem,
type ContextProvider,
} from '@github/copilot-language-server';
import { sendInfo } from "vscode-extension-telemetry-wrapper";
/**
* TelemetryQueue - Asynchronous telemetry queue to avoid blocking main thread
* Based on the PromiseQueue pattern from copilot-client
*/
class TelemetryQueue {
private promises = new Set<Promise<unknown>>();
register(promise: Promise<unknown>): void {
this.promises.add(promise);
// Use void to avoid blocking - the key pattern from PromiseQueue
void promise.finally(() => this.promises.delete(promise));
}
async flush(): Promise<void> {
await Promise.allSettled(this.promises);
}
get size(): number {
return this.promises.size;
}
}
// Global telemetry queue instance
const globalTelemetryQueue = new TelemetryQueue();
/**
* Error classes for Copilot context provider cancellation handling
*/
export class CancellationError extends Error {
static readonly CANCELED = "Canceled";
constructor() {
super(CancellationError.CANCELED);
this.name = this.message;
}
}
export class InternalCancellationError extends CancellationError {
}
export class CopilotCancellationError extends CancellationError {
}
/**
* Type definitions for common patterns
*/
export type ContextResolverFunction = (request: ResolveRequest, token: vscode.CancellationToken) => Promise<SupportedContextItem[]>;
export interface CopilotApiWrapper {
clientApi?: CopilotApi;
chatApi?: CopilotApi;
}
export interface CopilotApi {
getContextProviderAPI(version: string): Promise<ContextProviderApiV1 | undefined>;
}
/**
* Utility class for handling common operations in Java Context Provider
*/
export class JavaContextProviderUtils {
/**
* Check if operation should be cancelled and throw appropriate error
*/
static checkCancellation(token: vscode.CancellationToken): void {
if (token.isCancellationRequested) {
throw new CopilotCancellationError();
}
}
static createContextItemsFromProjectDependencies(projectDepsResults: { key: string; value: string }[]): SupportedContextItem[] {
return projectDepsResults.map(dep => ({
name: dep.key,
value: dep.value,
importance: 70
}));
}
/**
* Create context items from import classes
*/
static createContextItemsFromImports(importClasses: any[]): SupportedContextItem[] {
return importClasses.map((cls: any) => ({
uri: cls.uri,
value: cls.value,
importance: 80,
origin: 'request' as const
}));
}
/**
* Get and validate Copilot APIs
*/
static async getCopilotApis(): Promise<CopilotApiWrapper> {
const copilotClientApi = await getCopilotClientApi();
const copilotChatApi = await getCopilotChatApi();
return { clientApi: copilotClientApi, chatApi: copilotChatApi };
}
/**
* Install context provider on available APIs
*/
static async installContextProviderOnApis(
apis: CopilotApiWrapper,
provider: ContextProvider<SupportedContextItem>,
context: vscode.ExtensionContext,
installFn: (api: CopilotApi, provider: ContextProvider<SupportedContextItem>) => Promise<vscode.Disposable | undefined>
): Promise<number> {
let installCount = 0;
if (apis.clientApi) {
const disposable = await installFn(apis.clientApi, provider);
if (disposable) {
context.subscriptions.push(disposable);
installCount++;
}
}
if (apis.chatApi) {
const disposable = await installFn(apis.chatApi, provider);
if (disposable) {
context.subscriptions.push(disposable);
installCount++;
}
}
return installCount;
}
/**
* Calculate approximate token count for context items
* Using a simple heuristic: ~4 characters per token
* Optimized for performance by using reduce and direct property access
*/
static calculateTokenCount(items: SupportedContextItem[]): number {
// Fast path: if no items, return 0
if (items.length === 0) {
return 0;
}
// Use reduce for better performance
const totalChars = items.reduce((sum, item) => {
let itemChars = 0;
// Direct property access is faster than 'in' operator
const value = (item as any).value;
const name = (item as any).name;
if (value && typeof value === 'string') {
itemChars += value.length;
}
if (name && typeof name === 'string') {
itemChars += name.length;
}
return sum + itemChars;
}, 0);
// Approximate: 1 token ≈ 4 characters
// Use bitwise shift for faster division by 4
return Math.ceil(totalChars / 4);
}
}
/**
* Get Copilot client API
*/
export async function getCopilotClientApi(): Promise<CopilotApi | undefined> {
const extension = vscode.extensions.getExtension<CopilotApi>('github.copilot');
if (!extension) {
return undefined;
}
try {
return await extension.activate();
} catch {
return undefined;
}
}
/**
* Get Copilot chat API
*/
export async function getCopilotChatApi(): Promise<CopilotApi | undefined> {
type CopilotChatApi = { getAPI?(version: number): CopilotApi | undefined };
const extension = vscode.extensions.getExtension<CopilotChatApi>('github.copilot-chat');
if (!extension) {
return undefined;
}
let exports: CopilotChatApi | undefined;
try {
exports = await extension.activate();
} catch {
return undefined;
}
if (!exports || typeof exports.getAPI !== 'function') {
return undefined;
}
return exports.getAPI(1);
}
export class ContextProviderRegistrationError extends Error {
constructor(message: string) {
super(message);
this.name = 'ContextProviderRegistrationError';
}
}
export class GetImportClassContentError extends Error {
constructor(message: string) {
super(message);
this.name = 'GetImportClassContentError';
}
}
export class GetProjectDependenciesError extends Error {
constructor(message: string) {
super(message);
this.name = 'GetProjectDependenciesError';
}
}
export class ContextProviderResolverError extends Error {
constructor(message: string) {
super(message);
this.name = 'ContextProviderResolverError';
}
}
/**
* Asynchronously send telemetry data preparation and sending
* This function prepares telemetry data and handles the actual sending asynchronously
*/
async function _sendContextResolutionTelemetry(
request: ResolveRequest,
duration: number,
items: SupportedContextItem[],
status: string,
error?: string,
dependenciesEmptyReason?: string,
importsEmptyReason?: string,
dependenciesCount?: number,
importsCount?: number
): Promise<void> {
try {
const tokenCount = JavaContextProviderUtils.calculateTokenCount(items);
const telemetryData: any = {
"action": "resolveJavaContext",
"completionId": request.completionId,
"duration": duration,
"itemCount": items.length,
"tokenCount": tokenCount,
"status": status,
"dependenciesCount": dependenciesCount ?? 0,
"importsCount": importsCount ?? 0
};
// Add empty reasons if present
if (dependenciesEmptyReason) {
telemetryData.dependenciesEmptyReason = dependenciesEmptyReason;
}
if (importsEmptyReason) {
telemetryData.importsEmptyReason = importsEmptyReason;
}
if (error) {
telemetryData.error = error;
}
// Actual telemetry sending - this is synchronous but network is async
sendInfo("", telemetryData);
} catch (telemetryError) {
// Silently ignore telemetry errors to not affect main functionality
}
}
/**
* Send consolidated telemetry data for Java context resolution asynchronously
* This function immediately returns and sends telemetry in the background without blocking
*
* @param request The resolve request from Copilot
* @param duration Duration of the resolution in milliseconds
* @param items The resolved context items
* @param status Status of the resolution ("succeeded", "cancelled_by_copilot", "cancelled_internally", "error_partial_results")
* @param error Optional error message
* @param dependenciesEmptyReason Optional reason why dependencies were empty
* @param importsEmptyReason Optional reason why imports were empty
* @param dependenciesCount Number of dependency items resolved
* @param importsCount Number of import items resolved
*/
export function sendContextResolutionTelemetry(
request: ResolveRequest,
duration: number,
items: SupportedContextItem[],
status: string,
error?: string,
dependenciesEmptyReason?: string,
importsEmptyReason?: string,
dependenciesCount?: number,
importsCount?: number
): void {
// Register the telemetry promise for non-blocking execution
// This follows the PromiseQueue pattern from copilot-client
globalTelemetryQueue.register(
_sendContextResolutionTelemetry(
request,
duration,
items,
status,
error,
dependenciesEmptyReason,
importsEmptyReason,
dependenciesCount,
importsCount
)
);
}
/**
* Get the global telemetry queue instance (useful for testing and monitoring)
*/
export function getTelemetryQueue(): TelemetryQueue {
return globalTelemetryQueue;
}