import type { BrowserWindow } from 'electron'; import { Redis } from 'ioredis'; import { REDIS_CHANNELS, REDIS_CONFIG, logRedisConfig } from '../config/redis'; import { getRedisChannelHandler } from '../handlers/redis-handlers'; let redisSubscriber: Redis | null = null; /** * Initialize Redis connection */ export function connectRedis(): void { try { // Log configuration info logRedisConfig(); redisSubscriber = new Redis(REDIS_CONFIG); redisSubscriber.on('error', (error) => { console.error('[REDIS] Connection error:', error); }); console.info('[REDIS] Initialized'); } catch (error) { console.error('[REDIS] Init failed:', error); } } /** * Set up Redis pub/sub with message handlers */ export function setupRedisPubSub(mainWindow: BrowserWindow): void { if (!redisSubscriber) { console.error('[REDIS] Not initialized'); return; } try { redisSubscriber.subscribe(...REDIS_CHANNELS); // Handle incoming messages redisSubscriber.on('message', (channel: string, message: string) => { try { const data = JSON.parse(message); const handler = getRedisChannelHandler(channel); if (handler) { handler(mainWindow, data); } else { console.warn(`[REDIS] No handler for '${channel}'`); } } catch (error) { console.error(`[REDIS] Parse error on '${channel}':`, error); } }); console.info('[REDIS] PubSub ready'); } catch (error) { console.error('[REDIS] Setup error:', error); } } /** * Disconnect Redis */ export function disconnectRedis(): void { if (redisSubscriber) { redisSubscriber.disconnect(); redisSubscriber = null; console.info('[REDIS] Disconnected'); } } /** * Get Redis connection status */ export function getRedisStatus(): 'connected' | 'disconnected' | 'not_initialized' { if (!redisSubscriber) return 'not_initialized'; return redisSubscriber.status === 'ready' ? 'connected' : 'disconnected'; } /** * Test Redis connection by trying to connect */ export async function testRedisConnection(): Promise { if (!redisSubscriber) { console.error('[REDIS] Not initialized'); return false; } try { await redisSubscriber.connect(); return true; } catch (error) { console.error('[REDIS] Test failed:', error); return false; } }