import { Injectable, Logger, OnModuleInit } from '@nestjs/common'; import { ConfigService } from '@nestjs/config'; import Redis from 'ioredis'; const SESSION_TTL = 3600; // 1 hour @Injectable() export class SessionService implements OnModuleInit { private readonly logger = new Logger(SessionService.name); private redis: Redis; constructor(private config: ConfigService) {} onModuleInit() { const url = this.config.get('redis.url', 'redis://localhost:6379'); this.redis = new Redis(url); this.redis.on('connect', () => this.logger.log('Redis connected')); this.redis.on('error', (err) => this.logger.error(`Redis error: ${err.message}`)); } private key(agentId: string): string { return `agent:session:${agentId}`; } async lockSession(agentId: string, memberId: string): Promise { await this.redis.set(this.key(agentId), memberId, 'EX', SESSION_TTL); } async isSessionLocked(agentId: string): Promise { return this.redis.get(this.key(agentId)); } async refreshSession(agentId: string): Promise { await this.redis.expire(this.key(agentId), SESSION_TTL); } async unlockSession(agentId: string): Promise { await this.redis.del(this.key(agentId)); } }