feat: add redis

This commit is contained in:
2026-10-21 11:01:29 +03:00
parent ab2bbeef83
commit 552b74eb95
10 changed files with 240 additions and 9 deletions
+2
View File
@@ -1,5 +1,6 @@
import { Module } from '@nestjs/common';
import { AuthModule } from './auth/auth.module';
import { CacheModule } from './cache/cache.module';
import { ChatsModule } from './chats/chats.module';
import { DbModule } from './db/db.module';
import { HealthModule } from './health/health.module';
@@ -9,6 +10,7 @@ import { UsersModule } from './users/users.module';
@Module({
imports: [
DbModule,
CacheModule,
AuthModule,
HealthModule,
UsersModule,
+44 -3
View File
@@ -1,5 +1,6 @@
import { Injectable } from '@nestjs/common';
import { createHash, randomBytes } from 'crypto';
import { CacheService } from '../cache/cache.service';
import { codePointLength } from '../common/dto/code-point-length.validator';
import { User } from '../common/domain';
import { ApiError } from '../common/filters/api-error';
@@ -9,6 +10,13 @@ import { verifyPassword } from './password';
const BASIC_CHALLENGE = 'Basic realm="messenger", charset="UTF-8"';
const USERNAME_PATTERN = /^[a-z0-9_]{3,32}$/;
const CACHE_TTL_MS = 60_000;
const REVOKED = 'revoked';
interface CachedSession {
user: User;
expiresAt: number;
}
export interface CreatedSession {
token: string;
@@ -25,7 +33,10 @@ export interface ResolvedSession {
export class AuthService {
private readonly ttlSeconds = readSessionTtl();
constructor(private readonly prisma: PrismaService) {}
constructor(
private readonly prisma: PrismaService,
private readonly cache: CacheService,
) {}
async login(authorization: string | undefined): Promise<CreatedSession> {
const credentials = parseBasic(authorization);
@@ -52,21 +63,51 @@ export class AuthService {
async resolve(token: string): Promise<ResolvedSession | null> {
const tokenHash = hashToken(token);
const key = cacheKey(tokenHash);
const cached = await this.cache.get(key);
if (cached === REVOKED) {
return null;
}
if (cached) {
const entry = JSON.parse(cached) as CachedSession;
if (entry.expiresAt > Date.now()) {
return { tokenHash, user: entry.user };
}
}
const session = await this.prisma.session.findUnique({
where: { tokenHash },
include: { user: true },
});
if (!session || session.expiresAt.getTime() <= Date.now()) {
const remainingMs = session
? session.expiresAt.getTime() - Date.now()
: 0;
if (!session || remainingMs <= 0) {
return null;
}
return { tokenHash, user: toUser(session.user) };
const user = toUser(session.user);
const entry: CachedSession = {
user,
expiresAt: session.expiresAt.getTime(),
};
await this.cache.set(
key,
JSON.stringify(entry),
Math.min(remainingMs, CACHE_TTL_MS),
true,
);
return { tokenHash, user };
}
async revoke(tokenHash: string): Promise<void> {
await this.prisma.session.deleteMany({ where: { tokenHash } });
await this.cache.set(cacheKey(tokenHash), REVOKED, CACHE_TTL_MS);
}
}
function cacheKey(tokenHash: string): string {
return `session:v1:${tokenHash}`;
}
function parseBasic(
header: string | undefined,
): { username: string; password: string } | null {
+9
View File
@@ -0,0 +1,9 @@
import { Global, Module } from '@nestjs/common';
import { CacheService } from './cache.service';
@Global()
@Module({
providers: [CacheService],
exports: [CacheService],
})
export class CacheModule {}
+58
View File
@@ -0,0 +1,58 @@
import { Injectable, Logger, OnModuleDestroy } from '@nestjs/common';
import { readFileSync } from 'fs';
import Redis from 'ioredis';
@Injectable()
export class CacheService implements OnModuleDestroy {
private readonly logger = new Logger('CacheService');
private readonly client: Redis | null;
constructor() {
const url = readCacheUrl();
this.client = url
? new Redis(url, {
enableOfflineQueue: false,
maxRetriesPerRequest: 0,
connectTimeout: 1000,
commandTimeout: 200,
})
: null;
this.client?.on('error', (error) =>
this.logger.warn(`redis unavailable: ${error.message}`),
);
}
async get(key: string): Promise<string | null> {
try {
return (await this.client?.get(key)) ?? null;
} catch {
return null;
}
}
async set(
key: string,
value: string,
ttlMs: number,
onlyIfAbsent = false,
): Promise<void> {
try {
if (onlyIfAbsent) {
await this.client?.set(key, value, 'PX', ttlMs, 'NX');
} else {
await this.client?.set(key, value, 'PX', ttlMs);
}
} catch {
return;
}
}
onModuleDestroy(): void {
this.client?.disconnect();
}
}
function readCacheUrl(): string | undefined {
const file = process.env.CACHE_URL_FILE;
return file ? readFileSync(file, 'utf8').trim() : process.env.CACHE_URL;
}