Skip to content

Commit

Permalink
chore: Use ttl for lru cache as well
Browse files Browse the repository at this point in the history
  • Loading branch information
CCristi committed Jun 24, 2024
1 parent 29e2e41 commit 62f4e56
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 8 deletions.
4 changes: 2 additions & 2 deletions packages/explorerkit-server/src/components/idls.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ export async function loadAllIdls(programIds: string[]): Promise<IdlsMap> {
}

const cache = getSharedDep("cache");
const cachedIdls = await cache.multiGet(programIds);
const cachedIdls = await cache.multiGet(programIds, IDL_CACHE_TTL);

await Promise.allSettled(
cachedIdls.map(async (res, i) => {
Expand All @@ -28,7 +28,7 @@ export async function loadAllIdls(programIds: string[]): Promise<IdlsMap> {
}

const idl = await getProgramIdl(programId);
void cache.set(programId, serializeIdl(idl), { EX: IDL_CACHE_TTL });
void cache.set(programId, serializeIdl(idl), IDL_CACHE_TTL);
idls.set(programId, idl && new SolanaFMParser(idl, programId));
})
);
Expand Down
20 changes: 14 additions & 6 deletions packages/explorerkit-server/src/core/cache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { register } from "@/components/metrics";
import { config } from "@/core/config";
import { onTeardown } from "@/utils/teardown";

const LRU_CACHE_MAX_ITEMS_COUNT = 100;
const LRU_CACHE_MAX_ITEMS_COUNT = 1000;

type CacheMetricGauges = {
redisHits: Gauge<string>;
Expand All @@ -21,7 +21,7 @@ class MultiCache {
private guages: CacheMetricGauges
) {}

async multiGet(keys: string[]): Promise<(string | null)[]> {
async multiGet(keys: string[], ttlInS: number = 0): Promise<(string | null)[]> {
const items: Record<string, string | null> = {};
const missingLruKeys: string[] = [];

Expand All @@ -44,7 +44,9 @@ class MultiCache {
items[key] = maybeIdl;
if (maybeIdl) {
this.guages.redisHits.inc();
this.lruCache.set(key, maybeIdl);
this.lruCache.set(key, maybeIdl, {
ttl: ttlInS * 1000,
});
} else {
this.guages.misses.inc();
}
Expand All @@ -54,9 +56,14 @@ class MultiCache {
return keys.map((key) => items[key] ?? null);
}

async set(key: string, value: string, options: { EX: number }): Promise<void> {
this.lruCache.set(key, value);
await this.redis.set(key, value, options);
async set(key: string, value: string, ttlInS: number = 0): Promise<void> {
this.lruCache.set(key, value, {
ttl: ttlInS * 1000,
});

await this.redis.set(key, value, {
EX: ttlInS,
});
}

async teardown() {
Expand All @@ -72,6 +79,7 @@ export async function createCache(): Promise<MultiCache> {

const lruCache = new LRUCache<string, string>({
max: LRU_CACHE_MAX_ITEMS_COUNT,
updateAgeOnGet: true,
});

const multiCache = new MultiCache(redisClient as RedisClientType, lruCache, {
Expand Down

0 comments on commit 62f4e56

Please sign in to comment.