Adds schema caching capabilities (5s by default) (#2286)

* Adds schema caching capabilities (off by default)

* Use InMemoryCacheAdapter

* Uses proper adapter to generate a cache

* Fix bugs when running disabled cache

* nits

* nits

* Use options object instead of boolean

* Imrpove concurrency of loadSchema

* Adds testing with SCHEMA_CACHE_ON

* Use CacheController instead of generator

- Makes caching SchemaCache use a generated prefix
- Makes clearing the SchemaCache clear only the cached schema keys
- Enable cache by default (ttl 5s)
This commit is contained in:
Florent Vilmart
2016-07-23 06:23:59 +02:00
committed by Drew
parent 66c4b98b55
commit 09bd9e3b2c
14 changed files with 205 additions and 47 deletions

View File

@@ -0,0 +1,68 @@
const MAIN_SCHEMA = "__MAIN_SCHEMA";
const SCHEMA_CACHE_PREFIX = "__SCHEMA";
const ALL_KEYS = "__ALL_KEYS";
import { randomString } from '../cryptoUtils';
export default class SchemaCache {
cache: Object;
constructor(cacheController, ttl = 30) {
this.ttl = ttl;
if (typeof ttl == 'string') {
this.ttl = parseInt(ttl);
}
this.cache = cacheController;
this.prefix = SCHEMA_CACHE_PREFIX+randomString(20);
}
put(key, value) {
return this.cache.get(this.prefix+ALL_KEYS).then((allKeys) => {
allKeys = allKeys || {};
allKeys[key] = true;
return Promise.all([this.cache.put(this.prefix+ALL_KEYS, allKeys, this.ttl), this.cache.put(key, value, this.ttl)]);
});
}
getAllClasses() {
if (!this.ttl) {
return Promise.resolve(null);
}
return this.cache.get(this.prefix+MAIN_SCHEMA);
}
setAllClasses(schema) {
if (!this.ttl) {
return Promise.resolve(null);
}
return this.put(this.prefix+MAIN_SCHEMA, schema);
}
setOneSchema(className, schema) {
if (!this.ttl) {
return Promise.resolve(null);
}
return this.put(this.prefix+className, schema);
}
getOneSchema(className) {
if (!this.ttl) {
return Promise.resolve(null);
}
return this.cache.get(this.prefix+className);
}
clear() {
// That clears all caches...
let promise = Promise.resolve();
return this.cache.get(this.prefix+ALL_KEYS).then((allKeys) => {
if (!allKeys) {
return;
}
let promises = Object.keys(allKeys).map((key) => {
return this.cache.del(key);
});
return Promise.all(promises);
});
}
}