Реализовать лабораторную 3 на основе lab2: балансировка и идемпотентность

This commit is contained in:
Владислав Гавриленко
2026-11-13 01:30:14 +03:00
parent 0ab3a341aa
commit 4322edcbec
21 changed files with 870 additions and 31 deletions
+49
View File
@@ -0,0 +1,49 @@
"""Additional checks against a running lab3 server."""
import sys
import uuid
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests'))
from client import Client, arguments
args = arguments('Additional validation checks')
c = Client(args.base_url, args.ca_file)
a, b, eve, chat = c.bootstrap()
path = '/api/v1/chats/' + chat['id'] + '/messages'
c.call('POST', '/api/v1/users', 400, body={'username': 'BAD', 'display_name': 'X'})
c.call('POST', '/api/v1/users', 400, body={'username': 'valid_name', 'display_name': ' '})
c.call('POST', '/api/v1/users', 400, body=dict(a['registration'], extra=True))
c.call('POST', path, 400, actor=a, body={'text': ' '}, headers={'Idempotency-Key': uuid.uuid4().hex})
c.call('POST', path, 400, actor=a, body={'text': 'ok', 'sender_id': b['id']}, headers={'Idempotency-Key': uuid.uuid4().hex})
c.call('GET', path, 404, actor=eve)
c.call('GET', path + '?cursor=bad', 400, actor=a)
c.call('GET', path + '?limit=1.5', 400, actor=a)
c.call('GET', '/api/v1/users/me', 401, headers={'X-User-Id': str(uuid.uuid4())})
for i in range(5):
c.message(a, chat, 'Юникод 👋 ' + str(i))
p = c.call('GET', path + '?limit=2', actor=b, schema='MessagePage')['json']
other = c.call('POST', '/api/v1/chats', 201, actor=a, body={'title': 'other', 'member_ids': [a['id']]}, schema='Chat')['json']
c.call('GET', '/api/v1/chats/' + other['id'] + '/messages?cursor=' + p['next_cursor'], 400, actor=a)
items = p['items']
while p['next_cursor']:
p = c.call('GET', path + '?limit=2&cursor=' + p['next_cursor'], actor=b, schema='MessagePage')['json']
items += p['items']
assert len(items) == len({x['id'] for x in items}) == 5
print('PASS: validation, access, Unicode, pagination and cursor scope')
c.call('POST', '/api/v1/users', 400, raw=b'{', headers={'Content-Type': 'application/json'})
c.call('POST', '/api/v1/users', 409, body=a['registration'])
print('PASS: malformed JSON and duplicate username')
import base64
# All 128 Unicode code points, including colon, must survive KDF without truncation.
registration = {'username': 'unicode_' + uuid.uuid4().hex[:12], 'display_name': 'Unicode', 'password': ':' + '🔐' * 127}
u = c.call('POST', '/api/v1/users', 201, body=registration, schema='User')['json']
credential = base64.b64encode((u['username'] + ':' + registration['password']).encode()).decode()
session = c.call('POST', '/api/v1/auth/sessions', 201, headers={'Authorization': 'Basic ' + credential}, schema='Session')['json']
assert session['user'] == u
c.call('POST', '/api/v1/users', 400, body=dict(registration, password='a' * 11))
c.call('POST', '/api/v1/users', 400, body=dict(registration, password='a' * 129))
# Creating a chat with a missing participant must leave no visible chat behind.
before = c.call('GET', '/api/v1/chats?limit=100', actor=a, schema='ChatPage')['json']
for members in ([a['id'], str(uuid.uuid4())], [a['id'], a['id']], [b['id']]):
c.call('POST', '/api/v1/chats', 400, actor=a, body={'title': 'invalid', 'member_ids': members})
assert c.call('GET', '/api/v1/chats?limit=100', actor=a, schema='ChatPage')['json'] == before
print('PASS: Unicode/colon passwords, length boundaries, invalid chat creation')
+35
View File
@@ -0,0 +1,35 @@
"""Run inside API container: migrations, constraints, rollback and password storage."""
import sys
import uuid
sys.path.insert(0, '/app/src')
import psycopg
from db import connect, migrate
def counts():
with connect() as db:
return {name: db.execute('SELECT count(*) AS n FROM ' + name).fetchone()['n']
for name in ('users', 'chats', 'chat_members', 'messages', 'sessions', 'message_keys', 'schema_migrations')}
before = counts()
migrate()
migrate()
assert counts() == before
with connect() as db:
assert db.execute('SELECT count(*) AS n FROM users').fetchone()['n'] > 0
assert db.execute('SELECT 1 FROM users WHERE octet_length(password_salt) != 16 OR octet_length(password_hash) != 64').fetchone() is None
assert db.execute('SELECT 1 FROM sessions WHERE octet_length(token_hash) != 32').fetchone() is None
chat_id = uuid.uuid4()
try:
with connect() as db:
db.execute('INSERT INTO chats (id,title) VALUES (%s,%s)', (chat_id, 'rollback check'))
db.execute('INSERT INTO chat_members VALUES (%s,%s)', (chat_id, uuid.uuid4()))
except psycopg.errors.ForeignKeyViolation:
pass
else:
raise AssertionError('Foreign key did not reject missing member')
with connect() as db:
assert db.execute('SELECT 1 FROM chats WHERE id=%s', (chat_id,)).fetchone() is None
assert counts() == before
print('PASS: repeated migrations preserve row counts; scrypt/token digests; FK and transaction rollback')
+15
View File
@@ -0,0 +1,15 @@
"""Run against an API started with SESSION_TTL_SECONDS=2; tokens never printed."""
import sys
import time
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests'))
from client import Client, arguments
args = arguments('Short-TTL session expiry')
c = Client(args.base_url, args.ca_file)
a = c.user('expiry')
c.call('GET', '/api/v1/users/me', actor=a, schema='User')
time.sleep(3)
c.call('GET', '/api/v1/users/me', 401, actor=a)
c.call('DELETE', '/api/v1/auth/sessions/current', 401, actor=a)
print('PASS: session expires with TTL=2; expired token cannot read or logout')
+41
View File
@@ -0,0 +1,41 @@
"""Concurrent retries through the LB must reach different real API processes."""
import sys
import uuid
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests'))
from client import Client, arguments
args = arguments('Shared idempotency across replicas')
c = Client(args.base_url, args.ca_file)
a, b, eve, chat = c.bootstrap()
path = '/api/v1/chats/' + chat['id'] + '/messages'
key = uuid.uuid4().hex
def send(i):
client = Client(args.base_url, args.ca_file)
body = {'text': 'Один результат 👋'}
if i % 2:
body['attachment_ids'] = []
return client.call('POST', path, 201, actor=a, body=body,
headers={'Idempotency-Key': key}, schema='Message')
with ThreadPoolExecutor(max_workers=16) as pool:
responses = list(pool.map(send, range(32)))
assert len({r['headers']['X-Instance-Id'] for r in responses}) >= 2
assert all(r['json'] == responses[0]['json'] for r in responses)
page = c.call('GET', path, actor=b, schema='MessagePage')['json']
assert page['items'] == [responses[0]['json']]
c.call('POST', path, 409, actor=a, body={'text': 'Другой текст'}, headers={'Idempotency-Key': key})
c.call('POST', path, 404, actor=eve, body={'text': 'Один результат 👋'}, headers={'Idempotency-Key': key})
other = c.message(b, chat, 'Другой пользователь', key=key)['json']
assert other['id'] != responses[0]['json']['id']
second_chat = c.call('POST', '/api/v1/chats', 201, actor=a,
body={'title': 'Другой чат', 'member_ids': [a['id']]}, schema='Chat')['json']
assert c.message(a, second_chat, 'Другой чат', key=key)['json']['id'] != other['id']
for bad_key in ('', 'has spaces', 'x' * 129):
c.call('POST', path, 400, actor=a, body={'text': 'Invalid key'}, headers={'Idempotency-Key': bad_key})
print('PASS: 32 concurrent retries across >=2 replicas: one message; conflict, access, key scope and validation')