UNPKG

@thermopylae/lib.cache

Version:
72 lines (71 loc) 2.58 kB
import { DependencyGraph } from "../../data-structures/dependency-graph.js"; import { createException } from "../../error.js"; class KeysDependenciesEvictionPolicy { dependencyGraph; readonlyCacheBackend; visitedEntriesOnDeletion; deleteFromCache; constructor(readonlyCacheBackend) { this.dependencyGraph = new DependencyGraph(); this.readonlyCacheBackend = readonlyCacheBackend; this.visitedEntriesOnDeletion = new Set(); } onHit() { return 1 ; } onMiss() { return undefined; } onSet(entry, options) { if (options == null) { return; } let dependencyEntry; if (options.dependencies) { for (const dependencyKey of options.dependencies) { dependencyEntry = this.readonlyCacheBackend.get(dependencyKey); if (dependencyEntry == null) { if (options.throwOnDependencyNotFound) { throw createException("DEPENDENCY_KEY_NOT_FOUND" , `Dependency '${dependencyKey}' of the '${entry.key}' wasn't found.`); } continue; } this.dependencyGraph.addDependency(entry, dependencyEntry); } } if (options.dependents) { for (const dependentKey of options.dependents) { dependencyEntry = this.readonlyCacheBackend.get(dependentKey); if (dependencyEntry == null) { if (options.throwOnDependencyNotFound) { throw createException("DEPENDENT_KEY_NOT_FOUND" , `Dependent '${dependentKey}' of the '${entry.key}' wasn't found.`); } continue; } this.dependencyGraph.addDependency(dependencyEntry, entry); } } } onUpdate() { return undefined; } onDelete(entry) { this.visitedEntriesOnDeletion.add(entry); const dependencies = this.dependencyGraph.directDependenciesOf(entry); let i = dependencies.length; while (i-- && dependencies.length) { if (this.visitedEntriesOnDeletion.has(dependencies[i])) { continue; } this.deleteFromCache(dependencies[i]); } this.visitedEntriesOnDeletion.delete(entry); this.dependencyGraph.removeNode(entry); } onClear() { } setDeleter(deleter) { this.deleteFromCache = deleter; } } export { KeysDependenciesEvictionPolicy };