Swadhin Biswas feat(api): add runner, analytics, packages, and security services · 3/6/2026
28f7954
100 lines · 2.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
import Redis from "ioredis";
import { logger } from "@/lib/logger";

// Create a Redis client
// Uses REDIS_URL environment variable by default
const redisUrl = import.meta.env?.REDIS_URL || process.env.REDIS_URL || "redis://localhost:6379";
const safeRedisUrl = redisUrl.replace(/:\/\/([^:@]+)(:[^@]+)?@/, "://$1:***@");
logger.info({ redisUrl: safeRedisUrl }, "Redis configured");

export const redis = new Redis(redisUrl, {
    // Some managed Redis providers restrict INFO; avoid noisy ready-check failures.
    enableReadyCheck: false,
    maxRetriesPerRequest: 3,
    retryStrategy: (times) => {
        const delay = Math.min(times * 50, 2000);
        return delay;
    },
});

redis.on("error", (error) => {
    logger.warn({ error }, "Redis connection error");
});

redis.on("connect", () => {
    logger.info("Redis connected");
});

export async function waitForRedisReady(timeoutMs = 5000): Promise<boolean> {
    if (redis.status === "ready") return true;

    return await new Promise((resolve) => {
        const timeout = setTimeout(() => {
            cleanup();
            resolve(false);
        }, timeoutMs);

        const onReady = () => {
            cleanup();
            resolve(true);
        };

        const onError = () => {
            // Keep waiting until timeout; transient errors are common during startup.
        };

        const cleanup = () => {
            clearTimeout(timeout);
            redis.off("ready", onReady);
            redis.off("error", onError);
        };

        redis.on("ready", onReady);
        redis.on("error", onError);
    });
}

/**
 * Set a user session
 * @param sessionId Session ID
 * @param data Session data
 * @param ttl Time to live in seconds (default 1 week)
 */
export async function setSession(sessionId: string, data: any, ttl = 7 * 24 * 60 * 60) {
    if (redis.status !== "ready") return;
    try {
        await redis.setex(sessionId, ttl, JSON.stringify(data));
    } catch (e) {
        logger.error({ error: e }, "Failed to set session in Redis");
    }
}

/**
 * Get a user session
 * @param sessionId Session ID
 * @returns Session data or null
 */
export async function getSession(sessionId: string) {
    if (redis.status !== "ready") return null;
    try {
        const data = await redis.get(sessionId);
        return data ? JSON.parse(data) : null;
    } catch (e) {
        logger.error({ error: e }, "Failed to get session from Redis");
        return null;
    }
}

/**
 * Delete a user session
 * @param sessionId Session ID
 */
export async function deleteSession(sessionId: string) {
    if (redis.status !== "ready") return;
    try {
        await redis.del(sessionId);
    } catch (e) {
        logger.error({ error: e }, "Failed to delete session from Redis");
    }
}