1 import { Model } from 'sequelize-typescript'
2 import * as Bluebird from 'bluebird'
3 import { logger } from '@server/helpers/logger'
16 private static instance: ModelCache
18 private readonly localCache: { [id in ModelCacheType]: Map<string, any> } = {
19 'local-account-name': new Map(),
20 'local-actor-name': new Map(),
21 'local-actor-url': new Map(),
22 'video-immutable': new Map()
25 private readonly deleteIds: {
26 [deleteKey in DeleteKey]: Map<number, { cacheType: ModelCacheType, key: string }[]>
31 private constructor () {
34 static get Instance () {
35 return this.instance || (this.instance = new this())
38 doCache<T extends Model> (options: {
39 cacheType: ModelCacheType
41 fun: () => Bluebird<T>
42 whitelist?: () => boolean
45 const { cacheType, key, fun, whitelist, deleteKey } = options
47 if (whitelist && whitelist() !== true) return fun()
49 const cache = this.localCache[cacheType]
52 logger.debug('Model cache hit for %s -> %s.', cacheType, key)
53 return Bluebird.resolve<T>(cache.get(key))
56 return fun().then(m => {
59 if (!whitelist || whitelist()) cache.set(key, m)
62 const map = this.deleteIds[deleteKey]
63 if (!map.has(m.id)) map.set(m.id, [])
65 const a = map.get(m.id)
66 a.push({ cacheType, key })
73 invalidateCache (deleteKey: DeleteKey, modelId: number) {
74 const map = this.deleteIds[deleteKey]
76 if (!map.has(modelId)) return
78 for (const toDelete of map.get(modelId)) {
79 logger.debug('Removing %s -> %d of model cache %s -> %s.', deleteKey, modelId, toDelete.cacheType, toDelete.key)
80 this.localCache[toDelete.cacheType].delete(toDelete.key)