Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions src/config/redis.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@ import { createClient } from 'redis';

const redisClient = createClient({
url: process.env.REDIS_URL,
socket: {
connectTimeout: 3000,
reconnectStrategy: (retries) => Math.min(retries * 200, 5000),
},
});

redisClient.on('connect', () => {
Expand Down
22 changes: 18 additions & 4 deletions src/stats/repositories/admin-visitor-stats.repository.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,38 @@
import redisClient from '../../config/redis';
import { buildHllKey } from '../../utils/visitor-tracking';

const REDIS_TIMEOUT_MS = 2000;

// ponytail: Redis μž₯μ•  μ‹œ 응닡이 hang λ˜μ§€ μ•Šλ„λ‘ 짧은 νƒ€μž„μ•„μ›ƒ + 폴백. κ·Όλ³Έ λ³΅κ΅¬λŠ” 인프라 λͺ«.
const withTimeout = <T>(op: Promise<T>, fallback: T): Promise<T> =>
Promise.race([
op,
new Promise<T>((resolve) => setTimeout(() => resolve(fallback), REDIS_TIMEOUT_MS)),
]);

export const AdminVisitorStatsRepository = {
countUniqueOnDate: async (kstDate: string): Promise<number> => {
return Number(await redisClient.pfCount(buildHllKey(kstDate)));
return withTimeout(
redisClient.pfCount(buildHllKey(kstDate)).then(Number),
0,
);
},

countUniqueOverRange: async (kstDates: string[]): Promise<number> => {
if (kstDates.length === 0) return 0;
const keys = kstDates.map(buildHllKey);
return Number(await redisClient.pfCount(keys));
return withTimeout(redisClient.pfCount(keys).then(Number), 0);
},

countUniquePerDay: async (
kstDates: string[],
): Promise<{ date: string; count: number }[]> => {
if (kstDates.length === 0) return [];
const counts = await Promise.all(
kstDates.map((d) => redisClient.pfCount(buildHllKey(d))),
kstDates.map((d) =>
withTimeout(redisClient.pfCount(buildHllKey(d)).then(Number), 0),
),
);
return kstDates.map((date, i) => ({ date, count: Number(counts[i]) }));
return kstDates.map((date, i) => ({ date, count: counts[i] }));
},
};
Loading