levelcache/ts/levelcache.classes.cacherouter.ts

69 lines
2.4 KiB
TypeScript
Raw Normal View History

2020-02-14 18:10:10 +00:00
import * as plugins from './levelcache.plugins';
2020-02-15 22:38:28 +00:00
import { LevelCache } from './levelcache.classes.levelcache';
2021-04-23 18:40:57 +00:00
import { AbstractCache } from './levelcache.abstract.classes.cache';
import { CacheEntry } from './levelcache.classes.cacheentry';
2020-02-14 18:10:10 +00:00
export class CacheRouter {
2020-02-15 22:38:28 +00:00
public levelCacheRef: LevelCache;
2021-04-23 18:40:57 +00:00
public cacheKeyMap = new plugins.lik.FastMap<AbstractCache>();
2020-02-15 22:38:28 +00:00
constructor(levelCacheRef: LevelCache) {
this.levelCacheRef = levelCacheRef;
}
/**
* gets the relevant cache to perform a store action on
*/
2021-04-23 18:40:57 +00:00
async getCacheForStoreAction(keyArg: string, cacheEntry: CacheEntry): Promise<AbstractCache> {
let returnCache: AbstractCache;
switch (true) {
case cacheEntry.contents.byteLength <= 500:
returnCache = this.levelCacheRef.cacheMemoryManager;
break;
case this.levelCacheRef.cacheDiskManager.status === 'active' &&
cacheEntry.contents.byteLength >= 500 &&
(cacheEntry.contents.byteLength < 10000 ||
this.levelCacheRef.cacheS3Manager.status === 'inactive'):
returnCache = this.levelCacheRef.cacheDiskManager;
break;
case cacheEntry.contents.byteLength >= 10000 &&
this.levelCacheRef.cacheS3Manager.status === 'active':
returnCache = this.levelCacheRef.cacheS3Manager;
break;
default:
returnCache = this.levelCacheRef.cacheMemoryManager;
}
this.cacheKeyMap.addToMap(keyArg, returnCache);
return returnCache;
}
2020-02-15 22:38:28 +00:00
/**
* gets the relevant cache to perform a retrieval action on
*/
2021-04-23 18:40:57 +00:00
async getCacheForRetrieveAction(keyArg: string): Promise<AbstractCache> {
const done = plugins.smartpromise.defer<AbstractCache>();
const returnCache = this.cacheKeyMap.getByKey(keyArg);
if (!returnCache && this.levelCacheRef.options.persistentCache) {
const checkCache = (cacheArg: AbstractCache) => {
const resultPromise = cacheArg.checkKeyPresence(keyArg);
2021-04-23 18:41:30 +00:00
resultPromise.then((hasKeyArg) => {
2021-04-23 18:40:57 +00:00
if (hasKeyArg) {
done.resolve(cacheArg);
}
});
return resultPromise;
};
Promise.all([
checkCache(this.levelCacheRef.cacheMemoryManager),
checkCache(this.levelCacheRef.cacheDiskManager),
2021-04-23 18:41:30 +00:00
checkCache(this.levelCacheRef.cacheMemoryManager),
2021-04-23 18:40:57 +00:00
]).then(() => {
done.resolve(returnCache);
});
} else {
done.resolve(returnCache);
}
return done.promise;
}
2020-02-15 22:38:28 +00:00
}