-
Notifications
You must be signed in to change notification settings - Fork 158
Expand file tree
/
Copy pathcontextCache.ts
More file actions
428 lines (378 loc) · 14.5 KB
/
contextCache.ts
File metadata and controls
428 lines (378 loc) · 14.5 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
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as vscode from 'vscode';
import * as crypto from 'crypto';
import { INodeImportClass } from './copilotHelper';
import { logger } from "../utils";
/**
* Cache entry interface for storing import data with enhanced metadata
*/
interface CacheEntry {
/** Unique cache entry ID for tracking */
id: string;
/** Cached import data */
value: INodeImportClass[];
/** Creation timestamp */
timestamp: number;
/** Document version when cached */
documentVersion?: number;
/** Last access timestamp */
lastAccess: number;
/** File content hash for change detection */
contentHash?: string;
/** Caret offset when cached (for position-sensitive invalidation) */
caretOffset?: number;
}
/**
* Configuration options for the context cache
*/
interface ContextCacheOptions {
/** Cache expiry time in milliseconds. Default: 10 minutes */
expiryTime?: number;
/** Enable automatic cleanup interval. Default: true */
enableAutoCleanup?: boolean;
/** Enable file watching for cache invalidation. Default: true */
enableFileWatching?: boolean;
/** Maximum cache size (number of entries). Default: 100 */
maxCacheSize?: number;
/** Enable content-based invalidation. Default: true */
enableContentHashing?: boolean;
/** Cleanup interval in milliseconds. Default: 2 minutes */
cleanupInterval?: number;
/** Maximum distance from cached caret position before cache becomes stale. Default: 8192 */
maxCaretDistance?: number;
/** Enable position-sensitive cache invalidation. Default: false */
enablePositionSensitive?: boolean;
}
/**
* Context cache manager for storing and managing Java import contexts
*/
export class ContextCache {
private readonly cache = new Map<string, CacheEntry>();
private readonly expiryTime: number;
private readonly enableAutoCleanup: boolean;
private readonly enableFileWatching: boolean;
private readonly maxCacheSize: number;
private readonly enableContentHashing: boolean;
private readonly cleanupIntervalMs: number;
private readonly maxCaretDistance: number;
private readonly enablePositionSensitive: boolean;
private cleanupTimer?: NodeJS.Timeout;
private fileWatcher?: vscode.FileSystemWatcher;
private accessCount = 0; // For statistics tracking
constructor(options: ContextCacheOptions = {}) {
this.expiryTime = options.expiryTime ?? 10 * 60 * 1000; // 10 minutes default
this.enableAutoCleanup = options.enableAutoCleanup ?? true;
this.enableFileWatching = options.enableFileWatching ?? true;
this.maxCacheSize = options.maxCacheSize ?? 100;
this.enableContentHashing = options.enableContentHashing ?? true;
this.cleanupIntervalMs = options.cleanupInterval ?? 2 * 60 * 1000; // 2 minutes
this.maxCaretDistance = options.maxCaretDistance ?? 8192; // Same as CopilotCompletionContextProvider
this.enablePositionSensitive = options.enablePositionSensitive ?? false;
}
/**
* Initialize the cache with VS Code extension context
* @param context VS Code extension context for managing disposables
*/
public initialize(context: vscode.ExtensionContext): void {
if (this.enableAutoCleanup) {
this.startPeriodicCleanup();
}
if (this.enableFileWatching) {
this.setupFileWatcher();
}
// Register cleanup on extension disposal
context.subscriptions.push(
new vscode.Disposable(() => {
this.dispose();
})
);
if (this.fileWatcher) {
context.subscriptions.push(this.fileWatcher);
}
}
/**
* Generate a hash for the document URI to use as cache key
* @param uri Document URI
* @returns Hashed URI string
*/
private generateCacheKey(uri: vscode.Uri): string {
return crypto.createHash('md5').update(uri.toString()).digest('hex');
}
/**
* Get cached imports for a document URI with enhanced validation
* @param uri Document URI
* @param currentCaretOffset Optional current caret offset for position-sensitive validation
* @returns Cached imports or null if not found/expired/stale
*/
public async get(uri: vscode.Uri, currentCaretOffset?: number): Promise<INodeImportClass[] | null> {
const key = this.generateCacheKey(uri);
const cached = this.cache.get(key);
if (!cached) {
return null;
}
// Check if cache is expired or stale
if (await this.isExpiredOrStale(uri, cached, currentCaretOffset)) {
this.cache.delete(key);
return null;
}
// Update last access time and increment access count
cached.lastAccess = Date.now();
this.accessCount++;
return cached.value;
}
/**
* Get cached imports synchronously (fallback method for compatibility)
* @param uri Document URI
* @param currentCaretOffset Optional current caret offset for position-sensitive validation
* @returns Cached imports or null if not found/expired
*/
public getSync(uri: vscode.Uri, currentCaretOffset?: number): INodeImportClass[] | null {
const key = this.generateCacheKey(uri);
const cached = this.cache.get(key);
if (!cached) {
return null;
}
// Check time-based expiry
if (this.isExpired(cached)) {
this.cache.delete(key);
return null;
}
// Check position-sensitive expiry if enabled and caret offsets available
if (this.enablePositionSensitive &&
cached.caretOffset !== undefined &&
currentCaretOffset !== undefined) {
if (this.isStaleCacheHit(currentCaretOffset, cached.caretOffset)) {
this.cache.delete(key);
return null;
}
}
// Update last access time and increment access count
cached.lastAccess = Date.now();
this.accessCount++;
return cached.value;
}
/**
* Set cached imports for a document URI
* @param uri Document URI
* @param imports Import class array to cache
* @param documentVersion Optional document version
* @param caretOffset Optional caret offset for position-sensitive caching
*/
public async set(uri: vscode.Uri, imports: INodeImportClass[], documentVersion?: number, caretOffset?: number): Promise<void> {
const key = this.generateCacheKey(uri);
const now = Date.now();
// Check cache size limit and evict if necessary
if (this.cache.size >= this.maxCacheSize) {
this.evictLeastRecentlyUsed();
}
// Generate lightweight content hash if enabled
let contentHash: string | undefined;
if (this.enableContentHashing) {
try {
const document = await vscode.workspace.openTextDocument(uri);
// Use document version and file stats for efficient change detection
const stats = await vscode.workspace.fs.stat(uri);
const hashInput = `${document.version}-${stats.mtime}-${stats.size}`;
contentHash = crypto.createHash('md5').update(hashInput).digest('hex');
} catch (error) {
logger.error('Failed to generate content hash:', error);
}
}
this.cache.set(key, {
id: crypto.randomUUID(),
value: imports,
timestamp: now,
lastAccess: now,
documentVersion,
contentHash,
caretOffset
});
}
/**
* Check if a cache entry is expired
* @param entry Cache entry to check
* @returns True if expired, false otherwise
*/
private isExpired(entry: CacheEntry): boolean {
return Date.now() - entry.timestamp > this.expiryTime;
}
/**
* Check if cache is stale based on caret position (similar to CopilotCompletionContextProvider)
* @param currentCaretOffset Current caret offset
* @param cachedCaretOffset Cached caret offset
* @returns True if stale, false otherwise
*/
private isStaleCacheHit(currentCaretOffset: number, cachedCaretOffset: number): boolean {
return Math.abs(currentCaretOffset - cachedCaretOffset) > this.maxCaretDistance;
}
/**
* Enhanced expiry check including content changes and position sensitivity
* @param uri Document URI
* @param entry Cache entry to check
* @param currentCaretOffset Optional current caret offset
* @returns True if expired or stale
*/
private async isExpiredOrStale(uri: vscode.Uri, entry: CacheEntry, currentCaretOffset?: number): Promise<boolean> {
// Check time-based expiry
if (this.isExpired(entry)) {
return true;
}
// Check position-sensitive expiry if enabled and caret offsets available
if (this.enablePositionSensitive &&
entry.caretOffset !== undefined &&
currentCaretOffset !== undefined) {
if (this.isStaleCacheHit(currentCaretOffset, entry.caretOffset)) {
return true;
}
}
// Check content-based changes
if (await this.hasContentChanged(uri, entry)) {
return true;
}
return false;
}
/**
* Evict least recently used cache entries when cache is full
*/
private evictLeastRecentlyUsed(): void {
if (this.cache.size === 0) return;
let oldestTime = Date.now();
let oldestKey = '';
for (const [key, entry] of this.cache.entries()) {
if (entry.lastAccess < oldestTime) {
oldestTime = entry.lastAccess;
oldestKey = key;
}
}
if (oldestKey) {
this.cache.delete(oldestKey);
logger.trace('Evicted LRU cache entry:', oldestKey);
}
}
/**
* Check if content has changed by comparing lightweight hash
* @param uri Document URI
* @param entry Cache entry to check
* @returns True if content has changed
*/
private async hasContentChanged(uri: vscode.Uri, entry: CacheEntry): Promise<boolean> {
if (!this.enableContentHashing || !entry.contentHash) {
return false;
}
try {
// Fast check using document version first
const document = await vscode.workspace.openTextDocument(uri);
if (entry.documentVersion !== undefined && document.version !== entry.documentVersion) {
return true;
}
// If document version is the same or not available, check file stats
const stats = await vscode.workspace.fs.stat(uri);
const hashInput = `${document.version}-${stats.mtime}-${stats.size}`;
const currentHash = crypto.createHash('md5').update(hashInput).digest('hex');
return currentHash !== entry.contentHash;
} catch (error) {
logger.error('Failed to check content change:', error);
return false;
}
}
/**
* Clear expired cache entries
*/
public clearExpired(): void {
const now = Date.now();
for (const [key, entry] of this.cache.entries()) {
if (now - entry.timestamp > this.expiryTime) {
this.cache.delete(key);
}
}
}
/**
* Clear all cache entries
*/
public clear(): void {
this.cache.clear();
}
/**
* Invalidate cache for specific URI
* @param uri URI to invalidate
*/
public invalidate(uri: vscode.Uri): void {
const key = this.generateCacheKey(uri);
if (this.cache.has(key)) {
this.cache.delete(key);
logger.trace('Cache invalidated for:', uri.toString());
}
}
/**
* Get cache statistics
* @returns Object containing cache size and other statistics
*/
public getStats(): {
size: number;
expiryTime: number;
accessCount: number;
maxSize: number;
hitRate?: number;
positionSensitive: boolean;
} {
return {
size: this.cache.size,
expiryTime: this.expiryTime,
accessCount: this.accessCount,
maxSize: this.maxCacheSize,
positionSensitive: this.enablePositionSensitive
};
}
/**
* Start periodic cleanup of expired cache entries
*/
private startPeriodicCleanup(): void {
this.cleanupTimer = setInterval(() => {
this.clearExpired();
}, this.cleanupIntervalMs);
}
/**
* Setup file system watcher for Java files to invalidate cache on changes
*/
private setupFileWatcher(): void {
this.fileWatcher = vscode.workspace.createFileSystemWatcher('**/*.java');
const invalidateHandler = (uri: vscode.Uri) => {
this.invalidate(uri);
};
this.fileWatcher.onDidChange(invalidateHandler);
this.fileWatcher.onDidDelete(invalidateHandler);
}
/**
* Dispose of all resources (intervals, watchers, etc.)
*/
public dispose(): void {
if (this.cleanupTimer) {
clearInterval(this.cleanupTimer);
this.cleanupTimer = undefined;
}
if (this.fileWatcher) {
this.fileWatcher.dispose();
this.fileWatcher = undefined;
}
this.clear();
}
}
/**
* Default context cache instance
*/
export const contextCache = new ContextCache();
/**
* Enhanced context cache instance with position-sensitive features enabled
* for more precise code completion context
*/
export const enhancedContextCache = new ContextCache({
expiryTime: 10 * 60 * 1000, // 10 minutes
enablePositionSensitive: true,
maxCaretDistance: 8192, // Same as CopilotCompletionContextProvider
enableContentHashing: true,
maxCacheSize: 100,
cleanupInterval: 2 * 60 * 1000 // 2 minutes
});