| 19 | * discarded automatically on the next startup. |
| 20 | */ |
| 21 | export default class VsCodeBasedParserCache implements ParserCache { |
| 22 | static CACHE_NAME = 'foam-cache'; |
| 23 | static CACHE_VERSION = 5; |
| 24 | static CACHE_VERSION_KEY = 'foam-cache-version'; |
| 25 | private _cache: LRUCache<string, ParserCacheEntry>; |
| 26 | |
| 27 | constructor(private context: ExtensionContext, size = 10000) { |
| 28 | this._cache = new LRUCache({ |
| 29 | max: size, |
| 30 | updateAgeOnGet: true, |
| 31 | updateAgeOnHas: false, |
| 32 | }); |
| 33 | |
| 34 | const storedVersion = context.workspaceState.get<number>( |
| 35 | VsCodeBasedParserCache.CACHE_VERSION_KEY, |
| 36 | 0 |
| 37 | ); |
| 38 | if (storedVersion !== VsCodeBasedParserCache.CACHE_VERSION) { |
| 39 | Logger.debug( |
| 40 | `Cache version mismatch (stored: ${storedVersion}, current: ${VsCodeBasedParserCache.CACHE_VERSION}) — clearing cache` |
| 41 | ); |
| 42 | this.clear(); |
| 43 | context.workspaceState.update( |
| 44 | VsCodeBasedParserCache.CACHE_VERSION_KEY, |
| 45 | VsCodeBasedParserCache.CACHE_VERSION |
| 46 | ); |
| 47 | } else { |
| 48 | const source = context.workspaceState.get( |
| 49 | VsCodeBasedParserCache.CACHE_NAME, |
| 50 | [] |
| 51 | ); |
| 52 | try { |
| 53 | this._cache.load(source); |
| 54 | } catch (e) { |
| 55 | Logger.warn(`Failed to load cache: ${e}`); |
| 56 | this.clear(); |
| 57 | } |
| 58 | } |
| 59 | Logger.debug('Cache size: ' + this._cache.size); |
| 60 | } |
| 61 | |
| 62 | clear(): void { |
| 63 | this._cache.clear(); |
| 64 | this.context.workspaceState.update(VsCodeBasedParserCache.CACHE_NAME, []); |
| 65 | } |
| 66 | |
| 67 | get(uri: URI): ParserCacheEntry { |
| 68 | const result = this._cache.get(uri.toString()); |
| 69 | if (result) { |
| 70 | // The cache returns a plain object, but we need an actual |
| 71 | // instance of URI in the resource (we check instanceof in the code), |
| 72 | // so to be sure we convert it here. |
| 73 | const { checksum, resource } = result; |
| 74 | const rehydrated = { |
| 75 | ...resource, |
| 76 | uri: new URI(resource.uri), |
| 77 | }; |
| 78 | return { |
nothing calls this directly
no outgoing calls
no test coverage detected