Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

🔨 chore: support to have Redis and providers (#10391)

Neko36750adc3a8b
diff --git a/.env.example b/.env.example
index 46260b964cb..d7eb934f0f3 100644
--- a/.env.example
+++ b/.env.example
@@ -24,9 +24,29 @@
# Example: Allow specific internal servers while keeping SSRF protection
# SSRF_ALLOW_IP_ADDRESS_LIST=192.168.1.100,10.0.0.50
-# #######################################
-# ######### AI Provider Service #########
-# #######################################
+########################################
+############ Redis Settings ############
+########################################
+
+# Connection string for self-hosted Redis (Docker/K8s/managed). Use container hostname when running via docker-compose.
+# REDIS_URL=redis://localhost:6379
+
+# Optional database index.
+# REDIS_DATABASE=0
+
+# Optional authentication for managed Redis.
+# REDIS_USERNAME=default
+# REDIS_PASSWORD=yourpassword
+
+# Set to '1' to enforce TLS when connecting to managed Redis or rediss:// endpoints.
+# REDIS_TLS=0
+
+# Namespace prefix for cache/queue keys.
+# REDIS_PREFIX=lobechat
+
+########################################
+########## AI Provider Service #########
+########################################
# ## OpenAI ###
diff --git a/.env.example.development b/.env.example.development
index 6471d676105..fef1c3a386a 100644
--- a/.env.example.development
+++ b/.env.example.development
@@ -31,6 +31,11 @@ DATABASE_URL=postgresql://postgres:${POSTGRES_PASSWORD}@localhost:5432/${LOBE_DB
# Database driver type
DATABASE_DRIVER=node
+# Redis Cache/Queue Configuration
+REDIS_URL=redis://localhost:6379
+REDIS_PREFIX=lobechat
+REDIS_TLS=0
+
# Authentication Configuration
# Enable Better Auth authentication
NEXT_PUBLIC_ENABLE_BETTER_AUTH=1
diff --git a/docker-compose.development.yml b/docker-compose.development.yml
index e7c081d8182..91dbe54fca2 100644
--- a/docker-compose.development.yml
+++ b/docker-compose.development.yml
@@ -19,6 +19,10 @@ services:
extends:
file: docker-compose/local/docker-compose.yml
service: postgresql
+ redis:
+ extends:
+ file: docker-compose/local/docker-compose.yml
+ service: redis
minio:
extends:
file: docker-compose/local/docker-compose.yml
@@ -78,6 +82,8 @@ volumes:
driver: local
prometheus_data:
driver: local
+ redis_data:
+ driver: local
networks:
lobe-network:
diff --git a/docker-compose/local/docker-compose.yml b/docker-compose/local/docker-compose.yml
index 4b7f27f7c59..c7561806b43 100644
--- a/docker-compose/local/docker-compose.yml
+++ b/docker-compose/local/docker-compose.yml
@@ -35,6 +35,23 @@ services:
networks:
- lobe-network
+ redis:
+ image: redis:7-alpine
+ container_name: lobe-redis
+ ports:
+ - '6379:6379'
+ command: redis-server --save 60 1000 --appendonly yes
+ volumes:
+ - 'redis_data:/data'
+ healthcheck:
+ test: ['CMD', 'redis-cli', 'ping']
+ interval: 5s
+ timeout: 3s
+ retries: 5
+ restart: always
+ networks:
+ - lobe-network
+
minio:
image: minio/minio:RELEASE.2025-04-22T22-12-26Z
container_name: lobe-minio
@@ -107,6 +124,8 @@ services:
condition: service_started
casdoor:
condition: service_started
+ redis:
+ condition: service_healthy
environment:
- 'NEXT_AUTH_SSO_PROVIDERS=casdoor'
@@ -121,6 +140,9 @@ services:
- 'LLM_VISION_IMAGE_USE_BASE64=1'
- 'S3_SET_ACL=0'
- 'SEARXNG_URL=http://searxng:8080'
+ - 'REDIS_URL=redis://redis:6379'
+ - 'REDIS_PREFIX=lobechat'
+ - 'REDIS_TLS=0'
env_file:
- .env
restart: always
@@ -248,7 +270,8 @@ volumes:
driver: local
prometheus_data:
driver: local
-
+ redis_data:
+ driver: local
networks:
lobe-network:
diff --git a/docker-compose/local/logto/docker-compose.yml b/docker-compose/local/logto/docker-compose.yml
index 2e6df0397e4..2c8f8b0db5a 100644
--- a/docker-compose/local/logto/docker-compose.yml
+++ b/docker-compose/local/logto/docker-compose.yml
@@ -32,10 +32,27 @@ services:
networks:
- lobe-network
+ redis:
+ image: redis:7-alpine
+ container_name: lobe-redis
+ ports:
+ - '6379:6379'
+ command: redis-server --save 60 1000 --appendonly yes
+ volumes:
+ - 'redis_data:/data'
+ healthcheck:
+ test: ['CMD', 'redis-cli', 'ping']
+ interval: 5s
+ timeout: 3s
+ retries: 5
+ restart: always
+ networks:
+ - lobe-network
+
minio:
image: minio/minio:RELEASE.2025-04-22T22-12-26Z
container_name: lobe-minio
- network_mode: 'service:network-service'
+ network_mode: "service:network-service"
volumes:
- './s3_data:/etc/minio/data'
environment:
@@ -46,7 +63,6 @@ services:
command: >
server /etc/minio/data --address ":${MINIO_PORT}" --console-address ":9001"
-
logto:
image: svhd/logto
container_name: lobe-logto
@@ -75,6 +91,8 @@ services:
condition: service_started
logto:
condition: service_started
+ redis:
+ condition: service_healthy
environment:
- 'APP_URL=http://localhost:3210'
@@ -88,6 +106,9 @@ services:
- 'S3_BUCKET=${MINIO_LOBE_BUCKET}'
- 'S3_PUBLIC_DOMAIN=http://localhost:${MINIO_PORT}'
- 'S3_ENABLE_PATH_STYLE=1'
+ - 'REDIS_URL=redis://redis:6379'
+ - 'REDIS_PREFIX=lobechat'
+ - 'REDIS_TLS=0'
env_file:
- .env
restart: always
@@ -97,6 +118,8 @@ volumes:
driver: local
s3_data:
driver: local
+ redis_data:
+ driver: local
networks:
lobe-network:
diff --git a/package.json b/package.json
index 0b809c25eaf..096238807eb 100644
--- a/package.json
+++ b/package.json
@@ -189,6 +189,7 @@
"@trpc/next": "^11.7.1",
"@trpc/react-query": "^11.7.1",
"@trpc/server": "^11.7.1",
+ "@upstash/redis": "^1.35.7",
"@vercel/analytics": "^1.5.0",
"@vercel/edge-config": "^1.4.3",
"@vercel/functions": "^3.3.2",
@@ -222,6 +223,7 @@
"i18next-browser-languagedetector": "^8.2.0",
"i18next-resources-to-backend": "^1.2.1",
"immer": "^10.2.0",
+ "ioredis": "^5.4.1",
"jose": "^5.10.0",
"js-sha256": "^0.11.1",
"jsonl-parse-stringify": "^1.0.3",
@@ -331,6 +333,7 @@
"@types/crypto-js": "^4.2.2",
"@types/debug": "^4.1.12",
"@types/fs-extra": "^11.0.4",
+ "@types/ioredis": "^5.0.0",
"@types/ip": "^1.1.3",
"@types/json-schema": "^7.0.15",
"@types/lodash": "^4.17.20",
diff --git a/src/envs/redis.ts b/src/envs/redis.ts
new file mode 100644
index 00000000000..f7b7a7be812
--- /dev/null
+++ b/src/envs/redis.ts
@@ -0,0 +1,106 @@
+/* eslint-disable sort-keys-fix/sort-keys-fix */
+import { createEnv } from '@t3-oss/env-nextjs';
+import { z } from 'zod';
+
+import type { RedisConfig } from '@/libs/redis';
+
+type UpstashRedisConfig = { token: string; url: string };
+
+const parseNumber = (value?: string) => {
+ const parsed = Number.parseInt(value ?? '', 10);
+
+ return Number.isInteger(parsed) ? parsed : undefined;
+};
+
+const parseRedisTls = (value?: string) => {
+ if (!value) {
+ return false
+ }
+
+ const normalized = value.trim().toLowerCase();
+ return normalized === 'true' || normalized === '1';
+};
+
+export const getRedisEnv = () => {
+ return createEnv({
+ runtimeEnv: {
+ REDIS_DATABASE: parseNumber(process.env.REDIS_DATABASE),
+ REDIS_PASSWORD: process.env.REDIS_PASSWORD,
+ REDIS_PREFIX: process.env.REDIS_PREFIX || 'lobechat',
+ REDIS_TLS: parseRedisTls(process.env.REDIS_TLS),
+ REDIS_URL: process.env.REDIS_URL,
+ REDIS_USERNAME: process.env.REDIS_USERNAME,
+ UPSTASH_REDIS_REST_TOKEN: process.env.UPSTASH_REDIS_REST_TOKEN,
+ UPSTASH_REDIS_REST_URL: process.env.UPSTASH_REDIS_REST_URL,
+ },
+ server: {
+ REDIS_DATABASE: z.number().int().optional(),
+ REDIS_PASSWORD: z.string().optional(),
+ REDIS_PREFIX: z.string(),
+ REDIS_TLS: z.boolean().default(false),
+ REDIS_URL: z.string().url().optional(),
+ REDIS_USERNAME: z.string().optional(),
+ UPSTASH_REDIS_REST_TOKEN: z.string().optional(),
+ UPSTASH_REDIS_REST_URL: z.string().url().optional(),
+ },
+ });
+};
+
+export const redisEnv = getRedisEnv();
+
+export const getUpstashRedisConfig = (): UpstashRedisConfig | null => {
+ const upstashConfigSchema = z.union([
+ z.object({
+ token: z.string(),
+ url: z.string().url(),
+ }),
+ z.object({
+ token: z.undefined().optional(),
+ url: z.undefined().optional(),
+ }),
+ ]);
+
+ const parsed = upstashConfigSchema.safeParse({
+ token: redisEnv.UPSTASH_REDIS_REST_TOKEN,
+ url: redisEnv.UPSTASH_REDIS_REST_URL,
+ });
+
+ if (!parsed.success) throw parsed.error;
+ if (!parsed.data.token || !parsed.data.url) return null;
+
+ return parsed.data;
+};
+
+export const getRedisConfig = (): RedisConfig => {
+ const prefix = redisEnv.REDIS_PREFIX;
+
+ if (redisEnv.REDIS_URL) {
+ return {
+ database: redisEnv.REDIS_DATABASE,
+ enabled: true,
+ password: redisEnv.REDIS_PASSWORD,
+ prefix,
+ provider: 'redis',
+ tls: redisEnv.REDIS_TLS,
+ url: redisEnv.REDIS_URL,
+ username: redisEnv.REDIS_USERNAME,
+ };
+ }
+
+ const upstashConfig = getUpstashRedisConfig();
+ if (upstashConfig) {
+ return {
+ enabled: true,
+ prefix,
+ provider: 'upstash',
+ token: upstashConfig.token,
+ url: upstashConfig.url,
+ };
+ }
+
+ return {
+ enabled: false,
+ prefix,
+ provider: false,
+ };
+};
diff --git a/src/libs/redis/index.ts b/src/libs/redis/index.ts
new file mode 100644
index 00000000000..f2a17986546
--- /dev/null
+++ b/src/libs/redis/index.ts
@@ -0,0 +1,5 @@
+export * from './manager';
+export * from './redis';
+export * from './types';
+export * from './upstash';
+export * from './utils';
diff --git a/src/libs/redis/manager.test.ts b/src/libs/redis/manager.test.ts
new file mode 100644
index 00000000000..7cad711c1dd
--- /dev/null
+++ b/src/libs/redis/manager.test.ts
@@ -0,0 +1,107 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { RedisManager, initializeRedis, resetRedisClient } from './manager';
+import { DisabledRedisConfig } from './types';
+
+const {
+ mockIoRedisInitialize,
+ mockIoRedisDisconnect,
+ mockUpstashInitialize,
+ mockUpstashDisconnect,
+} = vi.hoisted(() => ({
+ mockIoRedisInitialize: vi.fn().mockResolvedValue(undefined),
+ mockIoRedisDisconnect: vi.fn().mockResolvedValue(undefined),
+ mockUpstashInitialize: vi.fn().mockResolvedValue(undefined),
+ mockUpstashDisconnect: vi.fn().mockResolvedValue(undefined),
+}));
+
+vi.mock('./redis', () => {
+ const IoRedisRedisProvider = vi.fn().mockImplementation((config) => ({
+ provider: 'redis' as const,
+ config,
+ initialize: mockIoRedisInitialize,
+ disconnect: mockIoRedisDisconnect,
+ }));
+
+ return { IoRedisRedisProvider };
+});
+
+vi.mock('./upstash', () => {
+ const UpstashRedisProvider = vi.fn().mockImplementation((config) => ({
+ provider: 'upstash' as const,
+ config,
+ initialize: mockUpstashInitialize,
+ disconnect: mockUpstashDisconnect,
+ }));
+
+ return { UpstashRedisProvider };
+});
+
+afterEach(async () => {
+ vi.clearAllMocks();
+ await RedisManager.reset();
+});
+
+describe('RedisManager', () => {
+ it('returns null when redis is disabled', async () => {
+ const config = {
+ enabled: false,
+ prefix: 'test',
+ provider: false,
+ } satisfies DisabledRedisConfig;
+
+ const instance = await initializeRedis(config);
+
+ expect(instance).toBeNull();
+ expect(mockIoRedisInitialize).not.toHaveBeenCalled();
+ expect(mockUpstashInitialize).not.toHaveBeenCalled();
+ });
+
+ it('initializes ioredis provider once and memoizes the instance', async () => {
+ const config = {
+ database: 0,
+ enabled: true,
+ password: 'pwd',
+ prefix: 'test',
+ provider: 'redis' as const,
+ tls: false,
+ url: 'redis://localhost:6379',
+ username: 'user',
+ };
+ const [first, second] = await Promise.all([initializeRedis(config), initializeRedis(config)]);
+
+ expect(first).toBe(second);
+ expect(mockIoRedisInitialize).toHaveBeenCalledTimes(1);
+ expect(mockUpstashInitialize).not.toHaveBeenCalled();
+ });
+
+ it('initializes upstash provider when configured', async () => {
+ const config = {
+ enabled: true,
+ prefix: 'test',
+ provider: 'upstash' as const,
+ token: 'token',
+ url: 'https://example.upstash.io',
+ };
+ const instance = await initializeRedis(config);
+
+ expect(instance?.provider).toBe('upstash');
+ expect(mockUpstashInitialize).toHaveBeenCalledTimes(1);
+ expect(mockIoRedisInitialize).not.toHaveBeenCalled();
+ });
+
+ it('disconnects existing provider on reset', async () => {
+ const config = {
+ enabled: true,
+ prefix: 'test',
+ provider: 'redis' as const,
+ tls: false,
+ url: 'redis://localhost:6379',
+ };
+
+ await initializeRedis(config);
+ await resetRedisClient();
+
+ expect(mockIoRedisDisconnect).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/src/libs/redis/manager.ts b/src/libs/redis/manager.ts
new file mode 100644
index 00000000000..a0ec9d6d43d
--- /dev/null
+++ b/src/libs/redis/manager.ts
@@ -0,0 +1,56 @@
+import { IoRedisRedisProvider } from './redis';
+import { BaseRedisProvider, RedisConfig } from './types';
+import { UpstashRedisProvider } from './upstash';
+
+class RedisManager {
+ private static instance: BaseRedisProvider | null = null;
+ // NOTICE: initPromise keeps concurrent initialize() calls sharing the same in-flight setup,
+ // preventing multiple connections from being created in parallel.
+ private static initPromise: Promise<BaseRedisProvider | null> | null = null;
+
+ static async initialize(config: RedisConfig): Promise<BaseRedisProvider | null> {
+ if (RedisManager.instance) return RedisManager.instance;
+ if (RedisManager.initPromise) return RedisManager.initPromise;
+
+ RedisManager.initPromise = (async () => {
+ if (!config.enabled) {
+ RedisManager.instance = null;
+ return null;
+ }
+
+ let provider: BaseRedisProvider;
+
+ if (config.provider === 'redis') {
+ provider = new IoRedisRedisProvider(config);
+ } else if (config.provider === 'upstash') {
+ provider = new UpstashRedisProvider({ token: config.token, url: config.url });
+ } else {
+ throw new Error(`Unsupported redis provider: ${String((config as any).provider)}`);
+ }
+
+ await provider.initialize();
+ RedisManager.instance = provider;
+
+ return provider;
+ })().catch((error) => {
+ RedisManager.initPromise = null;
+ throw error;
+ });
+
+ return RedisManager.initPromise;
+ }
+
+ static async reset() {
+ if (RedisManager.instance) {
+ await RedisManager.instance.disconnect();
+ }
+
+ RedisManager.instance = null;
+ RedisManager.initPromise = null;
+ }
+}
+
+export const initializeRedis = (config: RedisConfig) => RedisManager.initialize(config);
+export const resetRedisClient = () => RedisManager.reset();
+export const isRedisEnabled = (config: RedisConfig) => config.enabled;
+export { RedisManager };
diff --git a/src/libs/redis/redis.test.ts b/src/libs/redis/redis.test.ts
new file mode 100644
index 00000000000..c16454ac36a
--- /dev/null
+++ b/src/libs/redis/redis.test.ts
@@ -0,0 +1,158 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import { IoRedisConfig } from './types';
+
+const buildRedisConfig = (): IoRedisConfig | null => {
+ const url = process.env.REDIS_URL;
+
+ if (!url) return null;
+
+ const database = Number.parseInt(process.env.REDIS_DATABASE ?? '', 10);
+
+ return {
+ database: Number.isNaN(database) ? undefined : database,
+ enabled: true,
+ password: process.env.REDIS_PASSWORD,
+ prefix: process.env.REDIS_PREFIX ?? 'lobe-chat-test',
+ provider: 'redis',
+ tls: process.env.REDIS_TLS === 'true',
+ url,
+ username: process.env.REDIS_USERNAME,
+ };
+};
+
+const loadRedisProvider = async () => (await import('./redis')).IoRedisRedisProvider;
+
+const createMockedProvider = async () => {
+ const mocks = {
+ connect: vi.fn().mockResolvedValue(undefined),
+ ping: vi.fn().mockResolvedValue('PONG'),
+ quit: vi.fn().mockResolvedValue(undefined),
+ get: vi.fn().mockResolvedValue('mock-value'),
+ set: vi.fn().mockResolvedValue('OK'),
+ setex: vi.fn().mockResolvedValue('OK'),
+ del: vi.fn().mockResolvedValue(1),
+ exists: vi.fn().mockResolvedValue(1),
+ expire: vi.fn().mockResolvedValue(1),
+ ttl: vi.fn().mockResolvedValue(50),
+ incr: vi.fn().mockResolvedValue(2),
+ decr: vi.fn().mockResolvedValue(0),
+ mget: vi.fn().mockResolvedValue(['a', 'b']),
+ mset: vi.fn().mockResolvedValue('OK'),
+ hget: vi.fn().mockResolvedValue('field'),
+ hset: vi.fn().mockResolvedValue(1),
+ hdel: vi.fn().mockResolvedValue(1),
+ hgetall: vi.fn().mockResolvedValue({ a: '1' }),
+ };
+
+ vi.resetModules();
+ vi.doMock('ioredis', () => {
+ class FakeRedis {
+ constructor(
+ public url: string,
+ public options: any,
+ ) {}
+ connect = mocks.connect;
+ ping = mocks.ping;
+ quit = mocks.quit;
+ get = mocks.get;
+ set = mocks.set;
+ setex = mocks.setex;
+ del = mocks.del;
+ exists = mocks.exists;
+ expire = mocks.expire;
+ ttl = mocks.ttl;
+ incr = mocks.incr;
+ decr = mocks.decr;
+ mget = mocks.mget;
+ mset = mocks.mset;
+ hget = mocks.hget;
+ hset = mocks.hset;
+ hdel = mocks.hdel;
+ hgetall = mocks.hgetall;
+ }
+
+ return { default: FakeRedis };
+ });
+
+ const IoRedisRedisProvider = await loadRedisProvider();
+ const provider = new IoRedisRedisProvider({
+ enabled: true,
+ prefix: 'mock',
+ provider: 'redis',
+ tls: false,
+ url: 'redis://localhost:6379',
+ });
+
+ await provider.initialize();
+
+ return { mocks, provider };
+};
+
+const shouldSkipIntegration = (error: unknown) =>
+ error instanceof Error &&
+ ['ENOTFOUND', 'ECONNREFUSED', 'EAI_AGAIN', 'Connection is closed'].some((msg) =>
+ error.message.includes(msg),
+ );
+
+afterEach(() => {
+ vi.clearAllMocks();
+ vi.resetModules();
+ vi.unmock('ioredis');
+});
+
+describe('integrated', (test) => {
+ const config = buildRedisConfig();
+ if (!config) {
+ test.skip('REDIS_URL not provided; skip integrated ioredis tests');
+ return;
+ }
+
+ it('set -> get -> del roundtrip', async () => {
+ vi.unmock('ioredis');
+ vi.resetModules();
+
+ const IoRedisRedisProvider = await loadRedisProvider();
+ const provider = new IoRedisRedisProvider(config);
+ try {
+ await provider.initialize();
+
+ const key = `redis:test:${Date.now()}`;
+ await provider.set(key, 'value', { ex: 60 });
+ expect(await provider.get(key)).toBe('value');
+ expect(await provider.del(key)).toBe(1);
+ } catch (error) {
+ if (shouldSkipIntegration(error)) {
+ // Remote Redis unavailable in current environment; treat as skipped.
+ return;
+ }
+
+ throw error;
+ } finally {
+ await provider.disconnect();
+ }
+ });
+});
+
+describe('mocked', () => {
+ it('normalizes set options into ioredis arguments', async () => {
+ const { mocks, provider } = await createMockedProvider();
+ await provider.set('key', 'value', { ex: 10, nx: true, get: true });
+
+ expect(mocks.set).toHaveBeenCalledWith('key', 'value', 'EX', 10, 'NX', 'GET');
+ await provider.disconnect();
+ });
+
+ it('supports buffer keys for hashes and strings', async () => {
+ const { mocks, provider } = await createMockedProvider();
+
+ const bufKey = Buffer.from('buffer-key');
+ await provider.hset(bufKey, 'field', 'value');
+ await provider.get(bufKey);
+
+ expect(mocks.hset).toHaveBeenCalledWith(bufKey, 'field', 'value');
+ expect(mocks.get).toHaveBeenCalledWith(bufKey);
+
+ await provider.disconnect();
+ });
+});
diff --git a/src/libs/redis/redis.ts b/src/libs/redis/redis.ts
new file mode 100644
index 00000000000..5858d0918f9
--- /dev/null
+++ b/src/libs/redis/redis.ts
@@ -0,0 +1,117 @@
+import debug from 'debug';
+import type { Redis } from 'ioredis';
+
+import {
+ BaseRedisProvider,
+ IoRedisConfig,
+ RedisKey,
+ RedisMSetArgument,
+ RedisProviderName,
+ RedisSetResult,
+ RedisValue,
+ SetOptions,
+} from './types';
+import { buildIORedisSetArgs, normalizeMsetValues } from './utils';
+
+const log = debug('lobe:redis');
+
+export class IoRedisRedisProvider implements BaseRedisProvider {
+ provider: RedisProviderName = 'redis';
+ private client: Redis | null = null;
+
+ constructor(private config: IoRedisConfig) {}
+
+ async initialize() {
+ const IORedis = await import('ioredis');
+
+ this.client = new IORedis.default(this.config.url, {
+ db: this.config.database,
+ keyPrefix: this.config.prefix ? `${this.config.prefix}:` : undefined,
+ lazyConnect: true,
+ maxRetriesPerRequest: 2,
+ password: this.config.password,
+ tls: this.config.tls ? {} : undefined,
+ username: this.config.username,
+ });
+
+ await this.client.connect();
+ await this.client.ping();
+
+ log('Connected to Redis provider with prefix "%s"', this.config.prefix);
+ }
+
+ async disconnect() {
+ await this.client?.quit();
+ }
+
+ private ensureClient(): Redis {
+ if (!this.client) {
+ throw new Error('Redis client is not initialized');
+ }
+
+ return this.client;
+ }
+
+ async get(key: RedisKey): Promise<string | null> {
+ return this.ensureClient().get(key);
+ }
+
+ async set(key: RedisKey, value: RedisValue, options?: SetOptions): Promise<RedisSetResult> {
+ const args = buildIORedisSetArgs(options);
+
+ // ioredis has many overloads for SET; use a cast to keep async-only usage ergonomic
+ return (this.ensureClient().set as any)(key, value, ...args);
+ }
+
+ async setex(key: RedisKey, seconds: number, value: RedisValue): Promise<'OK'> {
+ return this.ensureClient().setex(key, seconds, value);
+ }
+
+ async del(...keys: RedisKey[]): Promise<number> {
+ return this.ensureClient().del(...keys);
+ }
+
+ async exists(...keys: RedisKey[]): Promise<number> {
+ return this.ensureClient().exists(...keys);
+ }
+
+ async expire(key: RedisKey, seconds: number): Promise<number> {
+ return this.ensureClient().expire(key, seconds);
+ }
+
+ async ttl(key: RedisKey): Promise<number> {
+ return this.ensureClient().ttl(key);
+ }
+
+ async incr(key: RedisKey): Promise<number> {
+ return this.ensureClient().incr(key);
+ }
+
+ async decr(key: RedisKey): Promise<number> {
+ return this.ensureClient().decr(key);
+ }
+
+ async mget(...keys: RedisKey[]): Promise<(string | null)[]> {
+ return this.ensureClient().mget(...keys);
+ }
+
+ async mset(values: RedisMSetArgument): Promise<'OK'> {
+ return this.ensureClient().mset(normalizeMsetValues(values));
+ }
+
+ async hget(key: RedisKey, field: RedisKey): Promise<string | null> {
+ return this.ensureClient().hget(key, field);
+ }
+
+ async hset(key: RedisKey, field: RedisKey, value: RedisValue): Promise<number> {
+ return this.ensureClient().hset(key, field, value);
+ }
+
+ async hdel(key: RedisKey, ...fields: RedisKey[]): Promise<number> {
+ return this.ensureClient().hdel(key, ...fields);
+ }
+
+ async hgetall(key: RedisKey): Promise<Record<string, string>> {
+ return this.ensureClient().hgetall(key);
+ }
+}
diff --git a/src/libs/redis/types.ts b/src/libs/redis/types.ts
new file mode 100644
index 00000000000..1e94a89fc9f
--- /dev/null
+++ b/src/libs/redis/types.ts
@@ -0,0 +1,71 @@
+export type RedisKey = string | Buffer;
+export type RedisValue = string | Buffer | number;
+export type RedisProvider = false | 'redis' | 'upstash';
+export type RedisProviderName = Exclude<RedisProvider, false>;
+
+export type IoRedisConfig = {
+ database?: number;
+ enabled: boolean;
+ password?: string;
+ prefix: string;
+ provider: 'redis';
+ tls: boolean;
+ url: string;
+ username?: string;
+};
+
+export type UpstashConfig = {
+ enabled: boolean;
+ prefix: string;
+ provider: 'upstash';
+ token: string;
+ url: string;
+};
+
+export type DisabledRedisConfig = {
+ enabled: false;
+ prefix: string;
+ provider: false;
+};
+
+export type RedisConfig = IoRedisConfig | UpstashConfig | DisabledRedisConfig;
+
+export interface SetOptions {
+ ex?: number;
+ exat?: number;
+ get?: boolean;
+ keepTtl?: boolean;
+ nx?: boolean;
+ px?: number;
+ pxat?: number;
+ xx?: boolean;
+}
+
+// NOTICE: number comes from upstash
+export type RedisSetResult = 'OK' | null | string | number;
+export type RedisMSetArgument = Record<string, RedisValue> | Map<RedisKey, RedisValue>;
+
+export interface RedisClient {
+ decr(key: RedisKey): Promise<number>;
+ del(...keys: RedisKey[]): Promise<number>;
+ exists(...keys: RedisKey[]): Promise<number>;
+ expire(key: RedisKey, seconds: number): Promise<number>;
+ get(key: RedisKey): Promise<string | null>;
+ hdel(key: RedisKey, ...fields: RedisKey[]): Promise<number>;
+ hget(key: RedisKey, field: RedisKey): Promise<string | null>;
+ hgetall(key: RedisKey): Promise<Record<string, string>>;
+ hset(key: RedisKey, field: RedisKey, value: RedisValue): Promise<number>;
+ incr(key: RedisKey): Promise<number>;
+ mget(...keys: RedisKey[]): Promise<(string | null)[]>;
+ mset(values: RedisMSetArgument): Promise<'OK'>;
+ set(key: RedisKey, value: RedisValue, options?: SetOptions): Promise<RedisSetResult>;
+ setex(key: RedisKey, seconds: number, value: RedisValue): Promise<'OK'>;
+ ttl(key: RedisKey): Promise<number>;
+}
+
+export interface BaseRedisProvider extends RedisClient {
+ disconnect(): Promise<void>;
+
+ initialize(): Promise<void>;
+ provider: RedisProviderName;
+}
diff --git a/src/libs/redis/upstash.test.ts b/src/libs/redis/upstash.test.ts
new file mode 100644
index 00000000000..09e6d7de4c9
--- /dev/null
+++ b/src/libs/redis/upstash.test.ts
@@ -0,0 +1,154 @@
+// @vitest-environment node
+// NOTICE: here due to the reason we are using [`happy-dom`](https://github.com/lobehub/lobe-chat/blob/13753145557a9dede98b1f5489f93ac570ef2956/vitest.config.mts#L45)
+// for Vitest environment, and in fact that this is a known bug for happy-dom not including
+// Authorization header in fetch requests.
+//
+// Read more here: https://github.com/capricorn86/happy-dom/issues/1042#issuecomment-3585851354
+import { Buffer } from 'node:buffer';
+import { describe, expect, it, vi } from 'vitest';
+
+import { UpstashConfig } from './types';
+
+const buildUpstashConfig = (): UpstashConfig | null => {
+ const url = process.env.UPSTASH_REDIS_REST_URL;
+ const token = process.env.UPSTASH_REDIS_REST_TOKEN;
+
+ if (!url || !token) return null;
+
+ return {
+ enabled: true,
+ prefix: process.env.REDIS_PREFIX ?? 'lobe-chat-test',
+ provider: 'upstash',
+ token,
+ url,
+ };
+};
+
+const loadUpstashProvider = async () => (await import('./upstash')).UpstashRedisProvider;
+
+const createMockedProvider = async () => {
+ const mocks = {
+ mockSet: vi.fn().mockResolvedValue('OK'),
+ mockGet: vi.fn().mockResolvedValue('mock-value'),
+ mockDel: vi.fn().mockResolvedValue(1),
+ mockSetex: vi.fn().mockResolvedValue('OK'),
+ mockMset: vi.fn().mockResolvedValue('OK'),
+ mockHset: vi.fn().mockResolvedValue(1),
+ mockHdel: vi.fn().mockResolvedValue(1),
+ mockHgetall: vi.fn().mockResolvedValue({ a: '1' }),
+ mockPing: vi.fn().mockResolvedValue('PONG'),
+ mockExists: vi.fn().mockResolvedValue(1),
+ mockExpire: vi.fn().mockResolvedValue(1),
+ mockTtl: vi.fn().mockResolvedValue(50),
+ mockIncr: vi.fn().mockResolvedValue(2),
+ mockDecr: vi.fn().mockResolvedValue(0),
+ mockMget: vi.fn().mockResolvedValue(['a', 'b']),
+ mockHget: vi.fn().mockResolvedValue('field'),
+ };
+
+ vi.resetModules();
+ vi.doMock('@upstash/redis', () => {
+ class FakeRedis {
+ constructor(public config: any) {}
+ ping = mocks.mockPing;
+ set = mocks.mockSet;
+ get = mocks.mockGet;
+ del = mocks.mockDel;
+ setex = mocks.mockSetex;
+ exists = mocks.mockExists;
+ expire = mocks.mockExpire;
+ ttl = mocks.mockTtl;
+ incr = mocks.mockIncr;
+ decr = mocks.mockDecr;
+ mget = mocks.mockMget;
+ mset = mocks.mockMset;
+ hget = mocks.mockHget;
+ hset = mocks.mockHset;
+ hdel = mocks.mockHdel;
+ hgetall = mocks.mockHgetall;
+ }
+
+ return { Redis: FakeRedis };
+ });
+
+ const UpstashRedisProvider = await loadUpstashProvider();
+ const provider = new UpstashRedisProvider({
+ enabled: true,
+ prefix: 'mock',
+ provider: 'upstash',
+ token: 'token',
+ url: 'https://example.upstash.io',
+ });
+
+ await provider.initialize();
+
+ return { mocks, provider };
+};
+
+const shouldSkipIntegration = (error: unknown) =>
+ error instanceof Error &&
+ ['ENOTFOUND', 'ECONNREFUSED', 'EAI_AGAIN', 'Connection is closed'].some((msg) =>
+ error.message.includes(msg),
+ );
+
+afterEach(() => {
+ vi.clearAllMocks();
+ vi.resetModules();
+ vi.unmock('@upstash/redis');
+});
+
+describe('integrated', (test) => {
+ const config = buildUpstashConfig();
+ if (!config) {
+ test.skip('UPSTASH_REDIS_REST_URL/TOKEN not provided; skip integrated upstash tests');
+ return;
+ }
+
+ it('set -> get -> del roundtrip', async () => {
+ vi.unmock('@upstash/redis');
+ vi.resetModules();
+
+ const UpstashRedisProvider = await loadUpstashProvider();
+ const provider = new UpstashRedisProvider(config);
+ try {
+ await provider.initialize();
+
+ const key = `upstash:test:${Date.now()}`;
+ await provider.set(key, 'value', { ex: 60 });
+ expect(await provider.get(key)).toBe('value');
+ expect(await provider.del(key)).toBe(1);
+ } catch (error) {
+ if (shouldSkipIntegration(error)) {
+ // Remote Upstash Redis unavailable in current environment; treat as skipped.
+ return;
+ }
+
+ throw error;
+ } finally {
+ await provider.disconnect();
+ }
+ });
+});
+
+describe('mocked', () => {
+ it('normalizes buffer keys to strings', async () => {
+ const { mocks, provider } = await createMockedProvider();
+
+ const bufKey = Buffer.from('buffer-key');
+ await provider.set(bufKey, 'value');
+ await provider.hset(bufKey, 'field', 'value');
+ await provider.del(bufKey);
+
+ expect(mocks.mockSet).toHaveBeenCalledWith('buffer-key', 'value', undefined);
+ expect(mocks.mockHset).toHaveBeenCalledWith('buffer-key', { field: 'value' });
+ expect(mocks.mockDel).toHaveBeenCalledWith('buffer-key');
+ });
+
+ it('passes set options through to upstash client', async () => {
+ const { mocks, provider } = await createMockedProvider();
+
+ await provider.set('key', 'value', { ex: 10, nx: true, get: true });
+
+ expect(mocks.mockSet).toHaveBeenCalledWith('key', 'value', { ex: 10, nx: true, get: true });
+ });
+});
diff --git a/src/libs/redis/upstash.ts b/src/libs/redis/upstash.ts
new file mode 100644
index 00000000000..c0c263d4fa5
--- /dev/null
+++ b/src/libs/redis/upstash.ts
@@ -0,0 +1,109 @@
+import { Redis, RedisConfigNodejs } from '@upstash/redis';
+import { Buffer } from 'node:buffer';
+
+import {
+ BaseRedisProvider,
+ RedisKey,
+ RedisMSetArgument,
+ RedisSetResult,
+ RedisValue,
+ SetOptions,
+ UpstashConfig,
+} from './types';
+import {
+ buildUpstashSetOptions,
+ normalizeMsetValues,
+ normalizeRedisKey,
+ normalizeRedisKeys,
+} from './utils';
+
+export class UpstashRedisProvider implements BaseRedisProvider {
+ provider: 'upstash' = 'upstash';
+ private client: Redis;
+
+ constructor(options: UpstashConfig | RedisConfigNodejs) {
+ this.client = new Redis(options as RedisConfigNodejs);
+ }
+
+ async initialize(): Promise<void> {
+ await this.client.ping();
+ }
+
+ async disconnect() {
+ // upstash client is stateless http, nothing to disconnect
+ }
+
+ async get(key: RedisKey): Promise<string | null> {
+ return this.client.get(normalizeRedisKey(key));
+ }
+
+ async set(key: RedisKey, value: RedisValue, options?: SetOptions): Promise<RedisSetResult> {
+ const res = await this.client.set(
+ normalizeRedisKey(key),
+ value,
+ buildUpstashSetOptions(options),
+ );
+ if (Buffer.isBuffer(res)) {
+ return res.toString();
+ }
+
+ return res;
+ }
+
+ async setex(key: RedisKey, seconds: number, value: RedisValue): Promise<'OK'> {
+ return this.client.setex(normalizeRedisKey(key), seconds, value);
+ }
+
+ async del(...keys: RedisKey[]): Promise<number> {
+ return this.client.del(...normalizeRedisKeys(keys));
+ }
+
+ async exists(...keys: RedisKey[]): Promise<number> {
+ return this.client.exists(...normalizeRedisKeys(keys));
+ }
+
+ async expire(key: RedisKey, seconds: number): Promise<number> {
+ return this.client.expire(normalizeRedisKey(key), seconds);
+ }
+
+ async ttl(key: RedisKey): Promise<number> {
+ return this.client.ttl(normalizeRedisKey(key));
+ }
+
+ async incr(key: RedisKey): Promise<number> {
+ return this.client.incr(normalizeRedisKey(key));
+ }
+
+ async decr(key: RedisKey): Promise<number> {
+ return this.client.decr(normalizeRedisKey(key));
+ }
+
+ async mget(...keys: RedisKey[]): Promise<(string | null)[]> {
+ return this.client.mget(...normalizeRedisKeys(keys));
+ }
+
+ async mset(values: RedisMSetArgument): Promise<'OK'> {
+ return this.client.mset(normalizeMsetValues(values));
+ }
+
+ async hget(key: RedisKey, field: RedisKey): Promise<string | null> {
+ return this.client.hget(normalizeRedisKey(key), normalizeRedisKey(field));
+ }
+
+ async hset(key: RedisKey, field: RedisKey, value: RedisValue): Promise<number> {
+ return this.client.hset(normalizeRedisKey(key), { [normalizeRedisKey(field)]: value });
+ }
+
+ async hdel(key: RedisKey, ...fields: RedisKey[]): Promise<number> {
+ return this.client.hdel(normalizeRedisKey(key), ...normalizeRedisKeys(fields));
+ }
+
+ async hgetall(key: RedisKey): Promise<Record<string, string>> {
+ const res = await this.client.hgetall(normalizeRedisKey(key));
+ if (!res) {
+ return {};
+ }
+
+ return res as Record<string, string>;
+ }
+}
diff --git a/src/libs/redis/utils.test.ts b/src/libs/redis/utils.test.ts
new file mode 100644
index 00000000000..23b9c757923
--- /dev/null
+++ b/src/libs/redis/utils.test.ts
@@ -0,0 +1,46 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ buildIORedisSetArgs,
+ buildUpstashSetOptions,
+ normalizeMsetValues,
+ normalizeRedisKey,
+ normalizeRedisKeys,
+} from './utils';
+
+describe('redis utils', () => {
+ it('normalizes single redis key to string', () => {
+ expect(normalizeRedisKey('foo')).toBe('foo');
+ expect(normalizeRedisKey(Buffer.from('bar'))).toBe('bar');
+ });
+
+ it('normalizes an array of redis keys', () => {
+ expect(normalizeRedisKeys(['foo', Buffer.from('bar')])).toEqual(['foo', 'bar']);
+ });
+
+ it('normalizes mset values from Map', () => {
+ const payload = normalizeMsetValues(
+ new Map<Buffer | string, number>([
+ [Buffer.from('a'), 1],
+ ['b', 2],
+ ]),
+ );
+
+ expect(payload).toEqual({ a: 1, b: 2 });
+ });
+
+ it('builds ioredis set arguments', () => {
+ const args = buildIORedisSetArgs({ ex: 1, nx: true, get: true });
+
+ expect(args).toEqual(['EX', 1, 'NX', 'GET']);
+ });
+
+ it('builds upstash set options', () => {
+ expect(buildUpstashSetOptions()).toBeUndefined();
+ expect(buildUpstashSetOptions({ ex: 10, nx: true, get: true })).toEqual({
+ ex: 10,
+ nx: true,
+ get: true,
+ });
+ });
+});
diff --git a/src/libs/redis/utils.ts b/src/libs/redis/utils.ts
new file mode 100644
index 00000000000..cb4724b2259
--- /dev/null
+++ b/src/libs/redis/utils.ts
@@ -0,0 +1,53 @@
+import type { SetCommandOptions } from '@upstash/redis';
+
+import { RedisKey, RedisMSetArgument, RedisValue, SetOptions } from './types';
+
+export const normalizeRedisKey = (key: RedisKey) =>
+ typeof key === 'string' ? key : key.toString();
+
+export const normalizeRedisKeys = (keys: RedisKey[]) => keys.map(normalizeRedisKey);
+
+export const normalizeMsetValues = (values: RedisMSetArgument): Record<string, RedisValue> => {
+ if (values instanceof Map) {
+ return Array.from(values.entries()).reduce<Record<string, RedisValue>>((acc, [key, value]) => {
+ acc[normalizeRedisKey(key)] = value;
+ return acc;
+ }, {});
+ }
+
+ return values;
+};
+
+export const buildIORedisSetArgs = (options?: SetOptions): Array<string | number> => {
+ if (!options) return [];
+
+ const args: Array<string | number> = [];
+
+ if (options.ex !== undefined) args.push('EX', options.ex);
+ if (options.px !== undefined) args.push('PX', options.px);
+ if (options.exat !== undefined) args.push('EXAT', options.exat);
+ if (options.pxat !== undefined) args.push('PXAT', options.pxat);
+ if (options.keepTtl) args.push('KEEPTTL');
+ if (options.nx) args.push('NX');
+ if (options.xx) args.push('XX');
+ if (options.get) args.push('GET');
+
+ return args;
+};
+
+export const buildUpstashSetOptions = (options?: SetOptions): SetCommandOptions | undefined => {
+ if (!options) return undefined;
+
+ const mapped: Partial<SetCommandOptions> = {};
+
+ if (options.ex !== undefined) mapped.ex = options.ex;
+ if (options.px !== undefined) mapped.px = options.px;
+ if (options.exat !== undefined) mapped.exat = options.exat;
+ if (options.pxat !== undefined) mapped.pxat = options.pxat;
+ if (options.keepTtl) mapped.keepTtl = true;
+ if (options.nx) mapped.nx = true;
+ if (options.xx) mapped.xx = true;
+ if (options.get) mapped.get = true;
+
+ return Object.keys(mapped).length ? (mapped as SetCommandOptions) : undefined;
+};