Skip to content

Commit

Permalink
chore: instrument the cache layer (#942)
Browse files Browse the repository at this point in the history
  • Loading branch information
wa0x6e committed Nov 6, 2023
1 parent 26fbe60 commit b78d40d
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 0 deletions.
9 changes: 9 additions & 0 deletions src/helpers/cache.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import redis from '../redis';
import { get, set } from '../aws';
import { cacheActivitesCount } from '../metrics';

export const VP_KEY_PREFIX = 'vp';

Expand All @@ -15,6 +16,7 @@ export async function cachedVp<Type extends Promise<VpResult>>(
toCache = true
) {
if (!toCache || !redis) {
cacheActivitesCount.inc({ type: 'vp', status: 'skip' });
return { result: await callback(), cache: false };
}

Expand All @@ -24,35 +26,42 @@ export async function cachedVp<Type extends Promise<VpResult>>(
cache.vp = parseFloat(cache.vp);
cache.vp_by_strategy = JSON.parse(cache.vp_by_strategy);

cacheActivitesCount.inc({ type: 'vp', status: 'hit' });
return { result: cache as Awaited<Type>, cache: true };
}

const result = await callback();
let cacheHitStatus = 'unqualified';

if (result.vp_state === 'final') {
cacheHitStatus = 'miss';
const multi = redis.multi();
multi.hSet(`${VP_KEY_PREFIX}:${key}`, 'vp', result.vp);
multi.hSet(`${VP_KEY_PREFIX}:${key}`, 'vp_by_strategy', JSON.stringify(result.vp_by_strategy));
multi.hSet(`${VP_KEY_PREFIX}:${key}`, 'vp_state', result.vp_state);
multi.exec();
}

cacheActivitesCount.inc({ type: 'vp', status: cacheHitStatus });
return { result, cache: false };
}

export async function cachedScores<Type>(key: string, callback: () => Type, toCache = false) {
if (!toCache || !!process.env.AWS_REGION) {
cacheActivitesCount.inc({ type: 'scores', status: 'skip' });
return { scores: await callback(), cache: false };
}

const cache = await get(key);

if (cache) {
cacheActivitesCount.inc({ type: 'scores', status: 'hit' });
return { scores: cache as Awaited<Type>, cache: true };
}

const scores = await callback();
set(key, scores);

cacheActivitesCount.inc({ type: 'scores', status: 'miss' });
return { scores, cache: false };
}
6 changes: 6 additions & 0 deletions src/metrics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,3 +30,9 @@ export const requestDeduplicatorSize = new client.Gauge({
name: 'request_deduplicator_size',
help: 'Total number of items in the deduplicator queue'
});

export const cacheActivitesCount = new client.Gauge({
name: 'cache_activites_count',
help: 'Number of requests to the cache layer',
labelNames: ['type', 'status']
});

0 comments on commit b78d40d

Please sign in to comment.