76 lines
2.8 KiB
TypeScript
76 lines
2.8 KiB
TypeScript
import * as plugins from './levelcache.plugins.js';
|
|
import { LevelCache } from './levelcache.classes.levelcache.js';
|
|
import { AbstractCache } from './levelcache.abstract.classes.cache.js';
|
|
import { CacheEntry } from './levelcache.classes.cacheentry.js';
|
|
|
|
export class CacheRouter {
|
|
public levelCacheRef: LevelCache;
|
|
public cacheKeyMap = new plugins.lik.FastMap<AbstractCache>();
|
|
|
|
constructor(levelCacheRef: LevelCache) {
|
|
this.levelCacheRef = levelCacheRef;
|
|
}
|
|
|
|
/**
|
|
* gets the relevant cache to perform a store action on
|
|
*/
|
|
async getCacheForStoreAction (keyArg: string, cacheEntry: CacheEntry): Promise<AbstractCache> {
|
|
let returnCache: AbstractCache;
|
|
const mbToBytesMultiplier = 1000 * 1000;
|
|
const maxMemoryBytes = this.levelCacheRef.options.maxMemoryStorageInMB * mbToBytesMultiplier;
|
|
const maxDiskBytes = this.levelCacheRef.options.maxDiskStorageInMB * mbToBytesMultiplier;
|
|
const maxS3Bytes = this.levelCacheRef.options.maxS3StorageInMB * mbToBytesMultiplier;
|
|
|
|
switch (true) {
|
|
case cacheEntry.contents.byteLength <= maxMemoryBytes &&
|
|
this.levelCacheRef.cacheMemoryManager.status === 'active':
|
|
returnCache = this.levelCacheRef.cacheMemoryManager;
|
|
break;
|
|
case this.levelCacheRef.cacheDiskManager.status === 'active' &&
|
|
cacheEntry.contents.byteLength > maxMemoryBytes &&
|
|
cacheEntry.contents.byteLength <= maxDiskBytes &&
|
|
this.levelCacheRef.cacheDiskManager.status === 'active':
|
|
returnCache = this.levelCacheRef.cacheDiskManager;
|
|
break;
|
|
case cacheEntry.contents.byteLength > maxDiskBytes &&
|
|
cacheEntry.contents.byteLength < maxS3Bytes &&
|
|
this.levelCacheRef.cacheS3Manager.status === 'active':
|
|
returnCache = this.levelCacheRef.cacheS3Manager;
|
|
break;
|
|
default:
|
|
returnCache = null;
|
|
}
|
|
this.cacheKeyMap.addToMap(keyArg, returnCache);
|
|
return returnCache;
|
|
}
|
|
|
|
/**
|
|
* gets the relevant cache to perform a retrieval action on
|
|
*/
|
|
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);
|
|
resultPromise.then((hasKeyArg) => {
|
|
if (hasKeyArg) {
|
|
done.resolve(cacheArg);
|
|
}
|
|
});
|
|
return resultPromise;
|
|
};
|
|
Promise.all([
|
|
checkCache(this.levelCacheRef.cacheMemoryManager),
|
|
checkCache(this.levelCacheRef.cacheDiskManager),
|
|
checkCache(this.levelCacheRef.cacheMemoryManager),
|
|
]).then(() => {
|
|
done.resolve(returnCache);
|
|
});
|
|
} else {
|
|
done.resolve(returnCache);
|
|
}
|
|
return done.promise;
|
|
}
|
|
}
|