Skip to content

Commit

Permalink
refresh commit ttl on load
Browse files Browse the repository at this point in the history
  • Loading branch information
m0ar committed Sep 17, 2024
1 parent 52da0e6 commit 7dc3cf1
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 3 deletions.
2 changes: 1 addition & 1 deletion .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ SUPABASE_KEY=
# REDIS_PORT=6379
# Short TTL's for tinkering with history loading
# CACHE_TTL_ANCHORED=60
# CACHE_TTL_PENDING=5
# CACHE_TTL_PENDING=10

# If set to 1, the `/*` route will use the legacy handler
FALLBACK_RESOLVER=0
Expand Down
6 changes: 4 additions & 2 deletions src/api/v2/queries/history.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import parentLogger from "../../../logger.js";
import { resolveDpid } from "../resolvers/dpid.js";
import { isDpid } from "../../../util/validation.js";
import { CommitID, StreamID } from "@desci-labs/desci-codex-lib/dist/streams.js";
import { getFromCache, setToCache } from "../../../redis.js";
import { getFromCache, keyBump, setToCache } from "../../../redis.js";
import { cleanupEip155Address } from "../../../util/conversions.js";

const logger = parentLogger.child({
Expand Down Expand Up @@ -119,11 +119,13 @@ export const getCodexHistory = async (streamId: string) => {
const key = getKeyForCommit(commit);
const cached = await getFromCache<HistoryVersion>(key);
if (cached !== null) {
// Only refresh TTL if entry is anchored, otherwise we'll postpone refreshes
if (cached.time) keyBump(key, CACHE_TTL_ANCHORED);
return cached;
}
const fresh = await getFreshVersionInfo(ceramic, commit);
const cacheTtl = fresh.time ? CACHE_TTL_ANCHORED : CACHE_TTL_PENDING;
await setToCache(key, fresh, cacheTtl);
setToCache(key, fresh, cacheTtl);
return fresh;
});

Expand Down
9 changes: 9 additions & 0 deletions src/redis.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,15 @@ redisClient.on("error", (err) => {
logger.error({ err }, "Client error");
});

export async function keyBump(key: string, ttl: number): Promise<void> {
if (!redisClient.isReady) {
logger.error({ fn: "keyBump", key, op: "bump" }, "client not connected");
return;
}
logger.info({ fn: "keyBump", key, op: "bump" }, "refreshing cache ttl");
await redisClient.expire(key, ttl);
}

export async function getFromCache<T>(key: string): Promise<T | null> {
if (!redisClient.isReady) {
logger.error({ fn: "getFromCache", key, op: "get" }, "client not connected");
Expand Down

0 comments on commit 7dc3cf1

Please sign in to comment.