swadhinbiswas feat: OpenCodeHub v1.1.0 - Enterprise Features & Storage Adapters · 2/15/2026
719a1cb
69 lines · 1.8 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
import Redis from "ioredis";
import { logger } from "@/lib/logger";

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

export const redis = new Redis(redisUrl, {
    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");
});

/**
 * 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");
    }
}