[json] add 'Clear schema cache' command. Fixes #138524

This commit is contained in:
Martin Aeschlimann
2021-12-06 16:56:12 +01:00
parent 1d4b413018
commit 95a9378519
6 changed files with 72 additions and 12 deletions

View File

@@ -101,14 +101,23 @@ const retryTimeoutInHours = 2 * 24; // 2 days
async function getSchemaRequestService(context: ExtensionContext, log: Log): Promise<SchemaRequestService> {
let cache: JSONSchemaCache | undefined = undefined;
const globalStorage = context.globalStorageUri;
let clearCache: (() => Promise<string[]>) | undefined;
if (globalStorage.scheme === 'file') {
const schemaCacheLocation = path.join(globalStorage.fsPath, 'json-schema-cache');
await fs.mkdir(schemaCacheLocation, { recursive: true });
cache = new JSONSchemaCache(schemaCacheLocation, context.globalState);
log.trace(`[json schema cache] initial state: ${JSON.stringify(cache.getCacheInfo(), null, ' ')}`);
const schemaCache = new JSONSchemaCache(schemaCacheLocation, context.globalState);
log.trace(`[json schema cache] initial state: ${JSON.stringify(schemaCache.getCacheInfo(), null, ' ')}`);
cache = schemaCache;
clearCache = async () => {
const cachedSchemas = await schemaCache.clearCache();
log.trace(`[json schema cache] cache cleared. Previously cached schemas: ${cachedSchemas.join(', ')}`);
return cachedSchemas;
};
}
const isXHRResponse = (error: any): error is XHRResponse => typeof error?.status === 'number';
const request = async (uri: string, etag?: string): Promise<string> => {
@@ -172,6 +181,7 @@ async function getSchemaRequestService(context: ExtensionContext, log: Log): Pro
}
}
return request(uri, cache?.getETag(uri));
}
},
clearCache
};
}

View File

@@ -21,7 +21,7 @@ interface CacheInfo {
const MEMENTO_KEY = 'json-schema-cache';
export class JSONSchemaCache {
private readonly cacheInfo: CacheInfo;
private cacheInfo: CacheInfo;
constructor(private readonly schemaCacheLocation: string, private readonly globalState: Memento) {
const infos = globalState.get<CacheInfo>(MEMENTO_KEY, {}) as CacheInfo;
@@ -120,6 +120,27 @@ export class JSONSchemaCache {
// ignore
}
}
public async clearCache(): Promise<string[]> {
const uris = Object.keys(this.cacheInfo);
try {
const files = await fs.readdir(this.schemaCacheLocation);
for (const file of files) {
try {
await fs.unlink(path.join(this.schemaCacheLocation, file));
} catch (_e) {
// ignore
}
}
} catch (e) {
// ignore
} finally {
this.cacheInfo = {};
await this.updateMemento();
}
return uris;
}
}
function getCacheFileName(uri: string): string {
return `${createHash('MD5').update(uri).digest('hex')}.schema.json`;