From 552b74eb955ceda1796fd78fd4c8fd93ae056a65 Mon Sep 17 00:00:00 2001 From: aegor Date: Wed, 21 Oct 2026 11:01:29 +0300 Subject: [PATCH] feat: add redis --- .env.example | 7 +-- compose.test.yaml | 7 +++ compose.yaml | 26 ++++++++++- package-lock.json | 88 ++++++++++++++++++++++++++++++++++++++ package.json | 1 + scripts/restart.sh | 4 +- src/app.module.ts | 2 + src/auth/auth.service.ts | 47 ++++++++++++++++++-- src/cache/cache.module.ts | 9 ++++ src/cache/cache.service.ts | 58 +++++++++++++++++++++++++ 10 files changed, 240 insertions(+), 9 deletions(-) create mode 100644 src/cache/cache.module.ts create mode 100644 src/cache/cache.service.ts diff --git a/.env.example b/.env.example index 714c807..acba506 100644 --- a/.env.example +++ b/.env.example @@ -1,11 +1,12 @@ # Copy to .env for your LOCAL synthetic test environment; never commit .env. -# These are logical interface suggestions; map actual framework names in REPORT.md. +# .env is optional: compose.yaml has the same defaults. +# APP_PORT is the published host port (127.0.0.1); inside the container API listens on 8080. APP_HOST=0.0.0.0 APP_PORT=8080 APP_ENV=lab SESSION_TTL_SECONDS=3600 -# Choose credentials locally. File paths contain no secret values. +# Generated by the secrets-init service into the "secrets" volume; fixed paths in compose.yaml. DATABASE_URL_FILE=/run/secrets/database_url -# Optional on 3, required use on 4 in lab2; Redis OR Valkey: +# Sessions: PostgreSQL is the source of truth, Redis is a read-through cache (no persistence). SESSION_STORE=postgres CACHE_URL_FILE=/run/secrets/cache_url diff --git a/compose.test.yaml b/compose.test.yaml index f80f98c..a30cee9 100644 --- a/compose.test.yaml +++ b/compose.test.yaml @@ -15,6 +15,10 @@ services: timeout: 3s retries: 15 + redis: + image: redis:7.4.1-alpine + command: ["redis-server", "--save", "", "--appendonly", "no"] + tests: build: context: . @@ -22,6 +26,9 @@ services: image: mtusi-messenger-lab2-test:dev environment: DATABASE_URL: postgresql://test:test@postgres:5432/messenger_test?connection_limit=20 + CACHE_URL: redis://redis:6379/0 depends_on: postgres: condition: service_healthy + redis: + condition: service_started diff --git a/compose.yaml b/compose.yaml index 3457a59..4801d50 100644 --- a/compose.yaml +++ b/compose.yaml @@ -12,7 +12,9 @@ services: cd /secrets [ -s pg_password ] || head -c 24 /dev/urandom | od -An -tx1 | tr -d ' \n' > pg_password printf 'postgresql://messenger:%s@postgres:5432/messenger?connection_limit=10&pool_timeout=5&connect_timeout=5&socket_timeout=10&application_name=api&options=-c%%20statement_timeout%%3D5000' "$$(cat pg_password)" > database_url - chmod 0444 pg_password database_url + [ -s redis_password ] || head -c 24 /dev/urandom | od -An -tx1 | tr -d ' \n' > redis_password + printf 'redis://:%s@redis:6379/0' "$$(cat redis_password)" > cache_url + chmod 0444 pg_password database_url redis_password cache_url postgres: image: postgres:17.2-alpine @@ -33,6 +35,25 @@ services: condition: service_completed_successfully restart: unless-stopped + redis: + image: redis:7.4.1-alpine + user: redis + command: + - sh + - -c + - exec redis-server --save '' --appendonly no --maxmemory 64mb --maxmemory-policy allkeys-lru --requirepass "$$(cat /run/secrets/redis_password)" + volumes: + - secrets:/run/secrets:ro + healthcheck: + test: ["CMD-SHELL", "redis-cli --no-auth-warning -a \"$$(cat /run/secrets/redis_password)\" ping | grep -q PONG"] + interval: 5s + timeout: 3s + retries: 10 + depends_on: + secrets-init: + condition: service_completed_successfully + restart: unless-stopped + migrate: build: context: . @@ -57,6 +78,7 @@ services: APP_ENV: ${APP_ENV:-lab} SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600} DATABASE_URL_FILE: /run/secrets/database_url + CACHE_URL_FILE: /run/secrets/cache_url ports: - "127.0.0.1:${APP_PORT:-8080}:8080" volumes: @@ -64,6 +86,8 @@ services: depends_on: migrate: condition: service_completed_successfully + redis: + condition: service_started restart: unless-stopped tools: diff --git a/package-lock.json b/package-lock.json index 1d1cad3..48ce183 100644 --- a/package-lock.json +++ b/package-lock.json @@ -16,6 +16,7 @@ "argon2": "0.41.1", "class-transformer": "^0.5.1", "class-validator": "^0.14.1", + "ioredis": "5.4.1", "reflect-metadata": "^0.2.2", "rxjs": "^7.8.1" }, @@ -1031,6 +1032,12 @@ "dev": true, "license": "BSD-3-Clause" }, + "node_modules/@ioredis/commands": { + "version": "1.11.0", + "resolved": "https://registry.npmjs.org/@ioredis/commands/-/commands-1.11.0.tgz", + "integrity": "sha512-tuMmOu6dtyGFv/fzCjtapCJj/zgoHaFsqs3wKsroJSRXtlLmyL/t+B7uaQiavGk1F3WWFQcUqZwk92bpp9jKcA==", + "license": "MIT" + }, "node_modules/@isaacs/cliui": { "version": "8.0.2", "resolved": "https://registry.npmjs.org/@isaacs/cliui/-/cliui-8.0.2.tgz", @@ -3696,6 +3703,15 @@ "node": ">=0.8" } }, + "node_modules/cluster-key-slot": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/cluster-key-slot/-/cluster-key-slot-1.1.2.tgz", + "integrity": "sha512-RMr0FhtfXemyinomL4hrWcYJxmX6deFdCxpJzhDttxgO1+bcCnkk+9drydLVDmAMG7NE6aN/fl4F7ucU/90gAA==", + "license": "Apache-2.0", + "engines": { + "node": ">=0.10.0" + } + }, "node_modules/co": { "version": "4.6.0", "resolved": "https://registry.npmjs.org/co/-/co-4.6.0.tgz", @@ -4000,6 +4016,15 @@ "node": ">=0.4.0" } }, + "node_modules/denque": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/denque/-/denque-2.1.0.tgz", + "integrity": "sha512-HVQE3AAb/pxF8fQAoiqpvg9i3evqug3hoiwakOyZAwJm+6vZehbkYXZ0l4JxS+I3QxM97v5aaRNhj8v5oBhekw==", + "license": "Apache-2.0", + "engines": { + "node": ">=0.10" + } + }, "node_modules/detect-newline": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/detect-newline/-/detect-newline-3.1.0.tgz", @@ -5477,6 +5502,30 @@ "node": ">=12.0.0" } }, + "node_modules/ioredis": { + "version": "5.4.1", + "resolved": "https://registry.npmjs.org/ioredis/-/ioredis-5.4.1.tgz", + "integrity": "sha512-2YZsvl7jopIa1gaePkeMtd9rAcSjOOjPtpcLlOeusyO+XH2SK5ZcT+UCrElPP+WVIInh2TzeI4XW9ENaSLVVHA==", + "license": "MIT", + "dependencies": { + "@ioredis/commands": "^1.1.1", + "cluster-key-slot": "^1.1.0", + "debug": "^4.3.4", + "denque": "^2.1.0", + "lodash.defaults": "^4.2.0", + "lodash.isarguments": "^3.1.0", + "redis-errors": "^1.2.0", + "redis-parser": "^3.0.0", + "standard-as-callback": "^2.1.0" + }, + "engines": { + "node": ">=12.22.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/ioredis" + } + }, "node_modules/ipaddr.js": { "version": "1.9.1", "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz", @@ -6690,6 +6739,18 @@ "dev": true, "license": "MIT" }, + "node_modules/lodash.defaults": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/lodash.defaults/-/lodash.defaults-4.2.0.tgz", + "integrity": "sha512-qjxPLHd3r5DnsdGacqOMU6pb/avJzdh9tFX2ymgoZE27BmjXrNy/y4LoaiTeAb+O3gL8AfpJGtqfX/ae2leYYQ==", + "license": "MIT" + }, + "node_modules/lodash.isarguments": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/lodash.isarguments/-/lodash.isarguments-3.1.0.tgz", + "integrity": "sha512-chi4NHZlZqZD18a0imDHnZPrDeBbTtVN7GXMwuGdRH9qotxAjYs3aVLKc7zNOG9eddR5Ksd8rvFEBc9SsggPpg==", + "license": "MIT" + }, "node_modules/lodash.memoize": { "version": "4.1.2", "resolved": "https://registry.npmjs.org/lodash.memoize/-/lodash.memoize-4.1.2.tgz", @@ -7890,6 +7951,27 @@ "node": ">= 12.13.0" } }, + "node_modules/redis-errors": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/redis-errors/-/redis-errors-1.2.0.tgz", + "integrity": "sha512-1qny3OExCf0UvUV/5wpYKf2YwPcOqXzkwKKSmKHiE6ZMQs5heeE/c8eXK+PNllPvmjgAbfnsbpkGZWy8cBpn9w==", + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/redis-parser": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/redis-parser/-/redis-parser-3.0.0.tgz", + "integrity": "sha512-DJnGAeenTdpMEH6uAJRK/uiyEIH9WVsUmoLwzudwGJUwZPp80PDBWPHXSAGNPwNvIXAbe7MSUB1zQFugFml66A==", + "license": "MIT", + "dependencies": { + "redis-errors": "^1.0.0" + }, + "engines": { + "node": ">=4" + } + }, "node_modules/reflect-metadata": { "version": "0.2.2", "resolved": "https://registry.npmjs.org/reflect-metadata/-/reflect-metadata-0.2.2.tgz", @@ -8498,6 +8580,12 @@ "node": ">=8" } }, + "node_modules/standard-as-callback": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/standard-as-callback/-/standard-as-callback-2.1.0.tgz", + "integrity": "sha512-qoRRSyROncaz1z0mvYqIE4lCd9p2R90i6GxW3uZv5ucSu8tU7B5HXUP1gG8pVZsYNVaXjk8ClXHPttLyxAL48A==", + "license": "MIT" + }, "node_modules/string_decoder": { "version": "1.3.0", "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz", diff --git a/package.json b/package.json index 7e05012..f1c0aad 100644 --- a/package.json +++ b/package.json @@ -20,6 +20,7 @@ "argon2": "0.41.1", "class-transformer": "^0.5.1", "class-validator": "^0.14.1", + "ioredis": "5.4.1", "reflect-metadata": "^0.2.2", "rxjs": "^7.8.1" }, diff --git a/scripts/restart.sh b/scripts/restart.sh index 7e2fc28..7ff5ed9 100755 --- a/scripts/restart.sh +++ b/scripts/restart.sh @@ -2,8 +2,8 @@ set -eu cd "$(dirname "$0")/.." started() { - docker inspect -f '{{.Name}} {{.State.Status}} started={{.State.StartedAt}}' $(docker compose ps -q postgres api) + docker inspect -f '{{.Name}} {{.State.Status}} started={{.State.StartedAt}}' $(docker compose ps -q postgres redis api) } started -docker compose restart postgres api +docker compose restart postgres redis api started diff --git a/src/app.module.ts b/src/app.module.ts index f4728bb..e19cc32 100644 --- a/src/app.module.ts +++ b/src/app.module.ts @@ -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, diff --git a/src/auth/auth.service.ts b/src/auth/auth.service.ts index 12e35de..245c90e 100644 --- a/src/auth/auth.service.ts +++ b/src/auth/auth.service.ts @@ -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 { const credentials = parseBasic(authorization); @@ -52,21 +63,51 @@ export class AuthService { async resolve(token: string): Promise { 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 { 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 { diff --git a/src/cache/cache.module.ts b/src/cache/cache.module.ts new file mode 100644 index 0000000..e67c549 --- /dev/null +++ b/src/cache/cache.module.ts @@ -0,0 +1,9 @@ +import { Global, Module } from '@nestjs/common'; +import { CacheService } from './cache.service'; + +@Global() +@Module({ + providers: [CacheService], + exports: [CacheService], +}) +export class CacheModule {} diff --git a/src/cache/cache.service.ts b/src/cache/cache.service.ts new file mode 100644 index 0000000..190be6b --- /dev/null +++ b/src/cache/cache.service.ts @@ -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 { + try { + return (await this.client?.get(key)) ?? null; + } catch { + return null; + } + } + + async set( + key: string, + value: string, + ttlMs: number, + onlyIfAbsent = false, + ): Promise { + 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; +}