mirror of
https://github.com/directus/directus.git
synced 2026-04-25 03:00:53 -04:00
Add lock for system cache (#12017)
* Add lock for system cache * Add lock when forcing a flush * Simplify code Co-authored-by: rijkvanzanten <rijkvanzanten@me.com>
This commit is contained in:
@@ -7,8 +7,9 @@ import { validateEnv } from './utils/validate-env';
|
||||
|
||||
let cache: Keyv | null = null;
|
||||
let systemCache: Keyv | null = null;
|
||||
let lockCache: Keyv | null = null;
|
||||
|
||||
export function getCache(): { cache: Keyv | null; systemCache: Keyv } {
|
||||
export function getCache(): { cache: Keyv | null; systemCache: Keyv; lockCache: Keyv } {
|
||||
if (env.CACHE_ENABLED === true && cache === null) {
|
||||
validateEnv(['CACHE_NAMESPACE', 'CACHE_TTL', 'CACHE_STORE']);
|
||||
cache = getKeyvInstance(ms(env.CACHE_TTL as string));
|
||||
@@ -20,15 +21,39 @@ export function getCache(): { cache: Keyv | null; systemCache: Keyv } {
|
||||
systemCache.on('error', (err) => logger.warn(err, `[cache] ${err}`));
|
||||
}
|
||||
|
||||
return { cache, systemCache };
|
||||
if (lockCache === null) {
|
||||
lockCache = getKeyvInstance(undefined, '_lock');
|
||||
lockCache.on('error', (err) => logger.warn(err, `[cache] ${err}`));
|
||||
}
|
||||
|
||||
return { cache, systemCache, lockCache };
|
||||
}
|
||||
|
||||
export async function flushCaches(): Promise<void> {
|
||||
const { systemCache, cache } = getCache();
|
||||
await systemCache?.clear();
|
||||
export async function flushCaches(forced?: boolean): Promise<void> {
|
||||
const { cache } = getCache();
|
||||
await clearSystemCache(forced);
|
||||
await cache?.clear();
|
||||
}
|
||||
|
||||
export async function clearSystemCache(forced?: boolean): Promise<void> {
|
||||
const { systemCache, lockCache } = getCache();
|
||||
|
||||
// Flush system cache when forced or when system cache lock not set
|
||||
if (forced || !(await lockCache.get('system-cache-lock'))) {
|
||||
await lockCache.set('system-cache-lock', true, 10000);
|
||||
await systemCache.clear();
|
||||
await lockCache.delete('system-cache-lock');
|
||||
}
|
||||
}
|
||||
|
||||
export async function setSystemCache(key: string, value: any, ttl?: number): Promise<void> {
|
||||
const { systemCache, lockCache } = getCache();
|
||||
|
||||
if (!(await lockCache.get('system-cache-lock'))) {
|
||||
await systemCache.set(key, value, ttl);
|
||||
}
|
||||
}
|
||||
|
||||
function getKeyvInstance(ttl: number | undefined, namespaceSuffix?: string): Keyv {
|
||||
switch (env.CACHE_STORE) {
|
||||
case 'redis':
|
||||
|
||||
Reference in New Issue
Block a user