#Redis reconnect with Microsoft Entra ID Error (I'm sorry for huge block of code)

3 messages · Page 1 of 1 (latest)

ashen frigate
#

In this service i make reconnection to redis ```ts
@Injectable()
export class RedisService {
constructor(
@Inject(AZURE_CREDENTIALS)
private readonly azureCredentials: DefaultAzureCredential,
@Inject(REDIS_CLIENT)
private readonly redisClient: RedisClientType,
private readonly configService: ConfigService,
) {}
private accessTokenCache: AccessToken | undefined = undefined;
private expireInMinutes: number = 0;
private readonly logger = new Logger(RedisService.name);

@Cron(CronExpression.EVERY_MINUTE)
private async updateToken() {
//Cannot have negative expire in
if (this.expireInMinutes < 0) {
throw new Error('Failed to update redis token');
}

// You can get new token when current one expire time is less than 10 minutes, in other case you get the same token
if (this.expireInMinutes >= 10) {
  --this.expireInMinutes;

  return void 0;
}

const accessToken = await getRedisAccessToken(this.azureCredentials);
// Return if get same token
if (this.accessTokenCache?.token === accessToken.token) {
  --this.expireInMinutes;

  return void 0;
}

await this.redisClient
  .auth({
    username: extractUsernameFromToken(accessToken),
    password: accessToken.token,
  })
  .catch((error) => {
    this.logger.error(error, error.stack);
    throw new InternalServerErrorException();
  });

this.accessTokenCache = accessToken;
this.expireInMinutes = this.calculateTokenExpiryMinutes(accessToken);


return void 0;

}
//Method that calculate the approximate token expiration in minutes
private calculateTokenExpiryMinutes(accessToken: AccessToken): number {
const now = Date.now();
const expiresTimestamp = accessToken.expiresOnTimestamp;

const timeRemainingMs = expiresTimestamp - now;
const minutesRemaining = Math.floor(timeRemainingMs / (1000 * 60));

return minutesRemaining > 0 ? minutesRemaining : 0;

}
}

#

Redis reconnect with Microsoft Entra ID Error (I'm sorry for huge block of code)

#

But after a while from setting new token I get these errors [Nest] 43010 - 02/17/2025, 2:11:11 PM LOG [RedisService] [Success::updateToken]=> {"expireInMinutes":56} SocketClosedUnexpectedlyError: Socket closed unexpectedly at TLSSocket.<anonymous> (/media/vasile/tt/tech-titans/chat-backend/node_modules/@redis/client/dist/lib/client/socket.js:194:118) at Object.onceWrapper (node:events:633:26) at TLSSocket.emit (node:events:530:35) at node:net:343:12 at TCP.done (node:_tls_wrap:650:7) [Nest] 43010 - 02/17/2025, 2:11:21 PM LOG [RedisService] [Success::updateToken]=> {"expireInMinutes":56} ClientClosedError: The client is closed at Commander._RedisClient_sendCommand (/media/vasile/tt/tech-titans/chat-backend/node_modules/@redis/client/dist/lib/client/index.js:520:31) at Timeout._onTimeout (/media/vasile/tt/tech-titans/chat-backend/node_modules/@redis/client/dist/lib/client/index.js:513:93) at listOnTimeout (node:internal/timers:594:17) at process.processTimers (node:internal/timers:529:7) [Nest] 43010 - 02/17/2025, 2:11:31 PM LOG [RedisService] [Success::updateToken]=> {"expireInMinutes":56} ClientClosedError: The client is closed at Commander._RedisClient_sendCommand (/media/vasile/tt/tech-titans/chat-backend/node_modules/@redis/client/dist/lib/client/index.js:520:31) at Timeout._onTimeout (/media/vasile/tt/tech-titans/chat-backend/node_modules/@redis/client/dist/lib/client/index.js:513:93) at listOnTimeout (node:internal/timers:594:17) at process.processTimers (node:internal/timers:529:7)