diff --git a/scripts/explain.sql b/scripts/explain.sql new file mode 100644 index 0000000..3dcaee2 --- /dev/null +++ b/scripts/explain.sql @@ -0,0 +1,54 @@ +\set ON_ERROR_STOP on +\pset pager off +\set owner '''00000000-0000-4000-8000-000000000001''' +\set target '''00000000-0000-4000-8000-0000000000c0''' + +BEGIN; + +INSERT INTO users (id, username, display_name, password_hash) +VALUES (:owner, 'explain_owner', 'Explain', 'not-a-real-hash'); + +INSERT INTO chats (id, title) VALUES (:target, 'explain target'); +INSERT INTO chats (id, title) SELECT gen_random_uuid(), 'explain other ' || g FROM generate_series(1, 20) g; +INSERT INTO chat_members (chat_id, user_id) SELECT id, :owner FROM chats WHERE title LIKE 'explain %'; + +INSERT INTO messages (id, chat_id, sender_id, text, created_at) +SELECT gen_random_uuid(), c.id, :owner, 'synthetic message ' || g, + timestamptz '2026-01-01 00:00:00Z' + g * interval '1 millisecond' +FROM chats c +CROSS JOIN LATERAL generate_series(1, CASE WHEN c.id = :target THEN 10000 ELSE 2000 END) g +WHERE c.title LIKE 'explain %'; + +ANALYZE messages; + +SELECT count(*) FILTER (WHERE chat_id = :target) AS target_chat_messages, count(*) AS total_messages FROM messages; + +SELECT created_at AS anchor_ts, id AS anchor_id FROM messages WHERE chat_id = :target +ORDER BY created_at, id OFFSET 8999 LIMIT 1 \gset + +\echo '=== 1. Keyset, first page (index messages_chat_id_created_at_id_idx)' +EXPLAIN (ANALYZE, BUFFERS) +SELECT id, chat_id, sender_id, text, created_at FROM messages +WHERE chat_id = :target +ORDER BY created_at, id LIMIT 51; + +\echo '=== 2. Keyset, page after message #9000' +EXPLAIN (ANALYZE, BUFFERS) +SELECT id, chat_id, sender_id, text, created_at FROM messages +WHERE chat_id = :target AND (created_at, id) > (:'anchor_ts'::timestamptz, :'anchor_id'::uuid) +ORDER BY created_at, id LIMIT 51; + +\echo '=== 3. For comparison: OFFSET 9000 reads and discards all previous rows' +EXPLAIN (ANALYZE, BUFFERS) +SELECT id, chat_id, sender_id, text, created_at FROM messages +WHERE chat_id = :target +ORDER BY created_at, id OFFSET 9000 LIMIT 51; + +\echo '=== 4. For comparison: keyset page #9000 without the index' +DROP INDEX messages_chat_id_created_at_id_idx; +EXPLAIN (ANALYZE, BUFFERS) +SELECT id, chat_id, sender_id, text, created_at FROM messages +WHERE chat_id = :target AND (created_at, id) > (:'anchor_ts'::timestamptz, :'anchor_id'::uuid) +ORDER BY created_at, id LIMIT 51; + +ROLLBACK; diff --git a/test/failures.e2e-spec.ts b/test/failures.e2e-spec.ts new file mode 100644 index 0000000..6fdf894 --- /dev/null +++ b/test/failures.e2e-spec.ts @@ -0,0 +1,113 @@ +import { INestApplication } from '@nestjs/common'; +import request from 'supertest'; +import { randomUUID } from 'crypto'; +import { PrismaService } from '../src/db/prisma.service'; +import { bearer, createTestApp, registerUser } from './helpers'; + +const UNREACHABLE_REDIS = 'redis://127.0.0.1:1/0'; +const UNREACHABLE_DB = 'postgresql://test:test@127.0.0.1:1/none?connect_timeout=1'; + +function sleep(ms: number): Promise { + return new Promise((resolve) => setTimeout(resolve, ms)); +} + +describe('Уровень 4: expiry, отказы зависимостей, rollback (e2e)', () => { + const apps: INestApplication[] = []; + + async function start(env: Record = {}) { + const started = await createTestApp(env); + apps.push(started.app); + return started; + } + + afterAll(async () => { + await Promise.all(apps.map((app) => app.close())); + }); + + it('сессия истекает при коротком SESSION_TTL_SECONDS, в том числе из кэша', async () => { + const { server } = await start({ SESSION_TTL_SECONDS: '2' }); + const user = await registerUser(server, 'ttl'); + await request(server) + .get('/api/v1/users/me') + .set('Authorization', bearer(user)) + .expect(200); + await sleep(2500); + const res = await request(server) + .get('/api/v1/users/me') + .set('Authorization', bearer(user)) + .expect(401); + expect(res.headers['www-authenticate']).toBe('Bearer realm="messenger"'); + }); + + it('без Redis вход, проверка сессии и logout работают через PostgreSQL', async () => { + const { server } = await start({ CACHE_URL: UNREACHABLE_REDIS }); + const user = await registerUser(server, 'noredis'); + await request(server) + .get('/api/v1/users/me') + .set('Authorization', bearer(user)) + .expect(200); + await request(server) + .delete('/api/v1/auth/sessions/current') + .set('Authorization', bearer(user)) + .expect(204); + await request(server) + .get('/api/v1/users/me') + .set('Authorization', bearer(user)) + .expect(401); + await request(server).get('/api/v1/users/me').expect(401); + }); + + it('без PostgreSQL отвечает ограниченным 503 и не пускает анонима', async () => { + const healthy = await start(); + const user = await registerUser(healthy.server, 'nodb'); + await request(healthy.server) + .get('/api/v1/users/me') + .set('Authorization', bearer(user)) + .expect(200); + + const { server } = await start({ DATABASE_URL: UNREACHABLE_DB }); + const ready = await request(server).get('/health/ready').expect(503); + expect(ready.body.error.code).toBe('unavailable'); + expect(JSON.stringify(ready.body)).not.toMatch(/127\.0\.0\.1|postgresql:|prisma/i); + + await request(server).get('/api/v1/chats').expect(401); + await request(server) + .get('/api/v1/chats') + .set('X-User-Id', user.id) + .expect(401); + await request(server) + .get('/api/v1/chats') + .set('Authorization', 'Bearer unknown-token-value') + .expect(503); + const res = await request(server) + .get('/api/v1/chats') + .set('Authorization', bearer(user)) + .expect(503); + expect(res.body.error.code).toBe('unavailable'); + await request(server) + .post('/api/v1/users') + .send({ + username: `nodb_${randomUUID().slice(0, 8)}`, + display_name: 'X', + password: 'Long-enough-pass-1', + }) + .expect(503); + }); + + it('откатывает создание чата целиком, если один из участников не существует', async () => { + const { app, server } = await start(); + const alice = await registerUser(server, 'rollback'); + const title = `rollback ${randomUUID()}`; + const res = await request(server) + .post('/api/v1/chats') + .set('Authorization', bearer(alice)) + .send({ title, member_ids: [alice.id, randomUUID()] }) + .expect(400); + expect(res.body.error.code).toBe('invalid_request'); + const prisma = app.get(PrismaService); + expect(await prisma.chat.count({ where: { title } })).toBe(0); + expect( + await prisma.chatMember.count({ where: { userId: alice.id } }), + ).toBe(0); + }); +}); diff --git a/test/helpers.ts b/test/helpers.ts index a0c1e39..676d6be 100644 --- a/test/helpers.ts +++ b/test/helpers.ts @@ -17,16 +17,23 @@ export interface TestUser { token: string; } -export async function createTestApp(): Promise<{ +export async function createTestApp(env: Record = {}): Promise<{ app: INestApplication; server: any; }> { - const moduleRef = await Test.createTestingModule({ - imports: [AppModule], - }).compile(); - const app = moduleRef.createNestApplication( - new FastifyAdapter(), - ); + const saved = { ...process.env }; + Object.assign(process.env, env); + let app: NestFastifyApplication; + try { + const moduleRef = await Test.createTestingModule({ + imports: [AppModule], + }).compile(); + app = moduleRef.createNestApplication( + new FastifyAdapter(), + ); + } finally { + process.env = saved; + } configureApp(app); await app.listen(0, '127.0.0.1'); return { app, server: app.getHttpServer() };