forked from mtusi2026/mtusi2026lab2
ЛР 2 — БВТ2301 — Майорова — на 5
This commit is contained in:
@@ -0,0 +1,92 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Destructive only to this repository's disposable lab services; volumes preserved."""
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import uuid
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
os.chdir(ROOT)
|
||||
sys.path.insert(0, str(ROOT / 'tests'))
|
||||
from client import Client, Failure
|
||||
|
||||
|
||||
def compose(*args):
|
||||
return subprocess.check_output(['docker', 'compose', *args], text=True).strip()
|
||||
|
||||
|
||||
def wait_ready(client):
|
||||
deadline = time.monotonic() + 45
|
||||
while True:
|
||||
try:
|
||||
client.call('GET', '/health/ready', schema='Health')
|
||||
return
|
||||
except Failure:
|
||||
if time.monotonic() > deadline:
|
||||
raise
|
||||
time.sleep(0.3)
|
||||
|
||||
|
||||
def main():
|
||||
c = Client(timeout=5)
|
||||
alice, bob, eve, chat = c.bootstrap()
|
||||
result = {}
|
||||
query = "SELECT count(*) FROM chats;"
|
||||
before = compose('exec', '-T', 'postgres', 'psql', '-U', 'messenger', '-d', 'messenger', '-Atc', query)
|
||||
c.call('POST', '/api/v1/chats', 400, actor=alice, body={'title': 'must rollback', 'member_ids': [alice['id'], str(uuid.uuid4())]})
|
||||
after = compose('exec', '-T', 'postgres', 'psql', '-U', 'messenger', '-d', 'messenger', '-Atc', query)
|
||||
assert before == after, 'failed chat left an orphan'
|
||||
result['composite_operation_rollback'] = True
|
||||
# Force a miss and observe the actual user cache and TTL, without printing its values.
|
||||
compose('exec', '-T', 'redis', 'redis-cli', 'DEL', 'user:' + alice['id'])
|
||||
c.call('GET', '/api/v1/users/me', actor=alice)
|
||||
ttl = int(compose('exec', '-T', 'redis', 'redis-cli', 'TTL', 'user:' + alice['id']))
|
||||
assert 0 < ttl <= 60
|
||||
result['redis_user_cache_ttl_seconds'] = ttl
|
||||
compose('stop', 'redis')
|
||||
try:
|
||||
started = time.monotonic()
|
||||
c.call('GET', '/api/v1/users/me', actor=alice)
|
||||
c.message(alice, chat, 'Redis unavailable; PostgreSQL remains authoritative')
|
||||
c.call('GET', '/api/v1/users/me', 401, headers={'Authorization': 'Bearer ' + 'x' * 43})
|
||||
c.call('GET', '/health/ready', schema='Health')
|
||||
result['redis_outage_seconds'] = time.monotonic() - started
|
||||
finally:
|
||||
compose('up', '-d', '--wait', 'redis')
|
||||
c.call('GET', '/api/v1/users/me', actor=alice)
|
||||
result['redis_recovered_without_relogin'] = True
|
||||
compose('stop', 'postgres')
|
||||
try:
|
||||
started = time.monotonic()
|
||||
c.call('GET', '/api/v1/users/me', 503, actor=alice)
|
||||
result['postgres_outage_response_seconds'] = time.monotonic() - started
|
||||
assert result['postgres_outage_response_seconds'] < 4
|
||||
c.call('GET', '/health/ready', 503)
|
||||
c.call('GET', '/health/live', schema='Health')
|
||||
finally:
|
||||
compose('up', '-d', '--wait', 'postgres')
|
||||
wait_ready(c)
|
||||
c.call('GET', '/api/v1/users/me', actor=alice)
|
||||
result['postgres_recovered_without_relogin'] = True
|
||||
# A separate short-TTL API uses the same authoritative PostgreSQL without changing the main API.
|
||||
name = 'mtusi-lab2-expiry-' + uuid.uuid4().hex[:8]
|
||||
compose('run', '-d', '--no-deps', '--name', name, '-e', 'SESSION_TTL_SECONDS=2', '-p', '127.0.0.1:18083:8080', 'api')
|
||||
try:
|
||||
short = Client('http://127.0.0.1:18083')
|
||||
wait_ready(short)
|
||||
actor = short.user('expiry')
|
||||
short.call('GET', '/api/v1/users/me', actor=actor)
|
||||
time.sleep(2.2)
|
||||
short.call('GET', '/api/v1/users/me', 401, actor=actor)
|
||||
result['short_ttl_expired'] = True
|
||||
finally:
|
||||
subprocess.run(['docker', 'rm', '-f', name], check=True, stdout=subprocess.DEVNULL)
|
||||
(ROOT / 'evidence/dependencies.json').write_text(json.dumps(result, indent=2))
|
||||
print('PASS: rollback, real Redis TTL/cache, Redis outage, PostgreSQL outage/recovery and session expiry.')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,113 @@
|
||||
"""Runs inside the API image, against a separate synthetic research database."""
|
||||
import datetime as dt
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import statistics
|
||||
import sys
|
||||
import time
|
||||
import uuid
|
||||
|
||||
import psycopg
|
||||
from psycopg import sql
|
||||
from psycopg.conninfo import make_conninfo
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / 'src'))
|
||||
from postgres import setting
|
||||
|
||||
|
||||
def snapshot(conn):
|
||||
counts = {}
|
||||
for table in ('users', 'chats', 'chat_members', 'messages', 'sessions'):
|
||||
counts[table] = conn.execute(sql.SQL('SELECT count(*) FROM {}').format(sql.Identifier(table))).fetchone()[0]
|
||||
digest = hashlib.sha256()
|
||||
selected = []
|
||||
with conn.cursor(name='checksum') as cur:
|
||||
cur.execute('SELECT row_to_json(m)::text FROM messages m ORDER BY id')
|
||||
for i, (row,) in enumerate(cur):
|
||||
digest.update(row.encode() + b'\n')
|
||||
if i in (0, 1, 50000, 99998, 99999):
|
||||
selected.append(json.loads(row))
|
||||
return dict(counts=counts, messages_sha256=digest.hexdigest(), selected_messages=selected)
|
||||
|
||||
|
||||
def main():
|
||||
url = setting('DATABASE_URL')
|
||||
if '--verify' in sys.argv:
|
||||
with psycopg.connect(make_conninfo(url, dbname=os.environ['RESEARCH_DATABASE'], host=os.environ['RESEARCH_HOST'])) as conn:
|
||||
print(json.dumps(snapshot(conn)))
|
||||
return
|
||||
database = 'research_' + uuid.uuid4().hex[:12]
|
||||
with psycopg.connect(url, autocommit=True) as admin:
|
||||
admin.execute(sql.SQL('CREATE DATABASE {}').format(sql.Identifier(database)))
|
||||
conn = psycopg.connect(make_conninfo(url, dbname=database))
|
||||
conn.execute((ROOT / 'migrations/001_initial.sql').read_text())
|
||||
user = uuid.uuid4()
|
||||
conn.execute('INSERT INTO users (id, username, display_name, password_hash) VALUES (%s, %s, %s, %s)', (user, 'research_user', 'Synthetic', 'not-an-authenticatable-password'))
|
||||
sizes = [70000, 20000, 5000, 2000, 1000, 800, 500, 300, 200, 200]
|
||||
chats = [uuid.uuid4() for _ in sizes]
|
||||
base = dt.datetime(2026, 1, 1, tzinfo=dt.timezone.utc)
|
||||
for chat in chats:
|
||||
conn.execute('INSERT INTO chats (id, title) VALUES (%s, %s)', (chat, 'Synthetic'))
|
||||
conn.execute('INSERT INTO chat_members (chat_id, user_id) VALUES (%s, %s)', (chat, user))
|
||||
with conn.cursor().copy('COPY messages (id, chat_id, sender_id, text, created_at) FROM STDIN') as copy:
|
||||
for chat, count in zip(chats, sizes):
|
||||
for i in range(count):
|
||||
copy.write_row((uuid.uuid4(), chat, user, 'x' * 64, base + dt.timedelta(microseconds=i)))
|
||||
conn.commit()
|
||||
results = []
|
||||
query = '''
|
||||
SELECT
|
||||
id
|
||||
, chat_id
|
||||
, sender_id
|
||||
, text
|
||||
, created_at
|
||||
FROM messages
|
||||
WHERE 1=1
|
||||
AND chat_id = %s
|
||||
AND (created_at, id) > (%s, %s)
|
||||
ORDER BY created_at, id
|
||||
LIMIT 51
|
||||
'''
|
||||
for variant, columns in (('chat_only', 'chat_id'), ('composite', 'chat_id, created_at, id')):
|
||||
conn.execute('DROP INDEX messages_history')
|
||||
# The two SQL fragments are constants, never request input.
|
||||
conn.execute('CREATE INDEX messages_history ON messages (' + columns + ')')
|
||||
conn.execute('ANALYZE messages')
|
||||
conn.commit()
|
||||
reads = []
|
||||
for position in (0, 1, 9):
|
||||
params = (chats[position], base + dt.timedelta(microseconds=sizes[position] * 4 // 5), uuid.UUID(int=0))
|
||||
conn.execute(query, params).fetchall() # Warm the same page before both variants.
|
||||
plans = [conn.execute('EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON) ' + query, params).fetchone()[0][0] for _ in range(5)]
|
||||
reads.append(dict(chat_messages=sizes[position], median_execution_ms=statistics.median(v['Execution Time'] for v in plans), plans=plans))
|
||||
conn.commit()
|
||||
writes = []
|
||||
for repeat in range(3):
|
||||
ids = [uuid.uuid4() for _ in range(1000)]
|
||||
before = conn.execute('SELECT pg_current_wal_insert_lsn()').fetchone()[0]
|
||||
conn.commit()
|
||||
started = time.perf_counter()
|
||||
with conn.cursor().copy('COPY messages (id, chat_id, sender_id, text, created_at) FROM STDIN') as copy:
|
||||
for i, mid in enumerate(ids):
|
||||
copy.write_row((mid, chats[0], user, 'write-cost', base + dt.timedelta(seconds=1, microseconds=i)))
|
||||
conn.commit()
|
||||
elapsed = (time.perf_counter() - started) * 1000
|
||||
wal = conn.execute('SELECT pg_wal_lsn_diff(pg_current_wal_insert_lsn(), %s::pg_lsn)', (before,)).fetchone()[0]
|
||||
writes.append(dict(rows=1000, commit_ms=elapsed, wal_bytes=int(wal)))
|
||||
conn.execute('DELETE FROM messages WHERE 1=1 AND id = ANY(%s::uuid[])', (ids,))
|
||||
conn.commit()
|
||||
index_size = conn.execute("SELECT pg_relation_size('messages_history')").fetchone()[0]
|
||||
results.append(dict(variant=variant, index_bytes=index_size, reads=reads, writes=writes))
|
||||
captured = snapshot(conn)
|
||||
assert captured['counts']['messages'] == 100000
|
||||
version = conn.execute('SELECT version()').fetchone()[0]
|
||||
conn.close()
|
||||
print(json.dumps(dict(database=database, postgresql=version, sizes=sizes, query=query, repeats=5, results=results, snapshot=captured)))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,52 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Index study, pg_dump, restore into a new database, full message checksum."""
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import time
|
||||
import uuid
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
os.chdir(ROOT)
|
||||
COMPOSE = ['docker', 'compose']
|
||||
RUN = COMPOSE + ['run', '--rm', '--no-deps', '-T', '-v', str(ROOT / 'student-tests') + ':/app/student-tests:ro']
|
||||
|
||||
result = json.loads(subprocess.check_output(RUN + ['api', 'python', 'student-tests/index_study.py'], text=True))
|
||||
source = result['database']
|
||||
restore = 'restore_' + uuid.uuid4().hex[:12]
|
||||
restore_container = 'mtusi-lab2-' + restore
|
||||
restore_volume = restore_container + '-data'
|
||||
directory = ROOT / 'backups'
|
||||
directory.mkdir(exist_ok=True, mode=0o700)
|
||||
backup = directory / (source + '.dump')
|
||||
started = time.perf_counter()
|
||||
with backup.open('wb') as output:
|
||||
subprocess.run(COMPOSE + ['exec', '-T', 'postgres', 'pg_dump', '-U', 'messenger', '-Fc', source], stdout=output, check=True)
|
||||
backup.chmod(0o600)
|
||||
dump_seconds = time.perf_counter() - started
|
||||
source_id = subprocess.check_output(COMPOSE + ['ps', '-q', 'postgres'], text=True).strip()
|
||||
source_info = json.loads(subprocess.check_output(['docker', 'inspect', source_id], text=True))[0]
|
||||
network = next(iter(source_info['NetworkSettings']['Networks']))
|
||||
image = source_info['Config']['Image']
|
||||
subprocess.run(['docker', 'volume', 'create', restore_volume], check=True, stdout=subprocess.DEVNULL)
|
||||
started_bootstrap = time.perf_counter()
|
||||
restore_id = subprocess.check_output(['docker', 'run', '-d', '--name', restore_container, '--network', network, '--cpus=1', '--memory=512m', '-e', 'POSTGRES_USER=messenger', '-e', 'POSTGRES_DB=' + restore, '-e', 'POSTGRES_PASSWORD_FILE=/run/secrets/postgres_password', '--mount', 'type=volume,src=' + restore_volume + ',dst=/var/lib/postgresql/data', '--mount', 'type=bind,src=' + str(ROOT / 'secrets/postgres_password') + ',dst=/run/secrets/postgres_password,readonly', image], text=True).strip()
|
||||
try:
|
||||
deadline = time.monotonic() + 45
|
||||
while subprocess.run(['docker', 'exec', restore_container, 'pg_isready', '-U', 'messenger', '-d', restore], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL).returncode:
|
||||
assert time.monotonic() < deadline, 'new PostgreSQL did not become ready'
|
||||
time.sleep(0.3)
|
||||
bootstrap_seconds = time.perf_counter() - started_bootstrap
|
||||
started = time.perf_counter()
|
||||
with backup.open('rb') as data:
|
||||
subprocess.run(['docker', 'exec', '-i', restore_container, 'pg_restore', '-U', 'messenger', '--no-owner', '--exit-on-error', '-d', restore], stdin=data, check=True)
|
||||
restore_seconds = time.perf_counter() - started
|
||||
verified = json.loads(subprocess.check_output(RUN + ['-e', 'RESEARCH_DATABASE=' + restore, '-e', 'RESEARCH_HOST=' + restore_container, 'api', 'python', 'student-tests/index_study.py', '--verify'], text=True))
|
||||
finally:
|
||||
subprocess.run(['docker', 'stop', '-t', '10', restore_container], check=True, stdout=subprocess.DEVNULL)
|
||||
assert result['snapshot'] == verified, 'restored contents differ'
|
||||
result['backup'] = dict(format='pg_dump custom', bytes=backup.stat().st_size, dump_seconds=dump_seconds, bootstrap_seconds=bootstrap_seconds, restore_seconds=restore_seconds, restored_database=restore, source_container_id=source_id[:12], restore_container_id=restore_id[:12], fresh_restore_volume=restore_volume, source_volume=[m['Name'] for m in source_info['Mounts'] if m['Type'] == 'volume'], matching_counts=True, matching_all_messages_sha256=True, matching_selected_messages=True, restored_snapshot=verified)
|
||||
(ROOT / 'evidence/index-study.json').write_text(json.dumps(result, indent=2))
|
||||
print('PASS: 100000 messages; two indexes; write costs; backup/restore counts, samples and full checksum match.')
|
||||
print('Backup seconds:', round(dump_seconds, 3), 'Restore seconds:', round(restore_seconds, 3))
|
||||
@@ -0,0 +1,98 @@
|
||||
"""Extra black-box tests, without changing the course's public tests."""
|
||||
import concurrent.futures
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import unittest
|
||||
from urllib.parse import quote
|
||||
import uuid
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests'))
|
||||
from client import Client, LAB
|
||||
|
||||
|
||||
class APIContract(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.client = Client()
|
||||
self.alice, self.bob, self.eve, self.chat = self.client.bootstrap()
|
||||
self.path = '/api/v1/chats/' + self.chat['id']
|
||||
|
||||
def test_malformed_json_and_extra_fields(self):
|
||||
for raw in (b'{', b'[]', b'{"text":"x","text":"y"}', b'{"text":NaN}', b'{"text":"\\ud800"}'):
|
||||
self.client.call('POST', self.path + '/messages', 400, actor=self.alice, raw=raw, headers={'Content-Type': 'application/json'})
|
||||
for body in ({'text': 'ok', 'sender_id': self.eve['id']}, {'text': True}, {'text': ' '}, {'text': ''}, {'text': None}):
|
||||
self.client.call('POST', self.path + '/messages', 400, actor=self.alice, body=body)
|
||||
deep = b'{"text":' + b'[' * 1200 + b'0' + b']' * 1200 + b'}'
|
||||
self.client.call('POST', self.path + '/messages', 400, actor=self.alice, raw=deep, headers={'Content-Type': 'application/json'})
|
||||
|
||||
def test_unicode_limits(self):
|
||||
result = self.client.message(self.alice, self.chat, '👩' * 4000)['json']
|
||||
self.assertEqual(result['text'], '👩' * 4000)
|
||||
self.client.call('POST', self.path + '/messages', 400, actor=self.alice, body={'text': '👩' * 4001})
|
||||
|
||||
def test_foreign_chat(self):
|
||||
for suffix in ('', '/messages'):
|
||||
self.client.call('GET', self.path + suffix, 404, actor=self.eve)
|
||||
self.client.call('POST', self.path + '/messages', 404, actor=self.eve, body={'text': 'hidden'})
|
||||
self.client.call('GET', '/api/v1/chats/' + str(uuid.uuid4()), 404, actor=self.alice)
|
||||
|
||||
def test_registration_race(self):
|
||||
body = dict(self.alice['registration'], username='race_' + uuid.uuid4().hex[:20])
|
||||
def register(_):
|
||||
return Client().call('POST', '/api/v1/users', [201, 409], body=body)['status']
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=10) as executor:
|
||||
statuses = list(executor.map(register, range(10)))
|
||||
self.assertEqual(statuses.count(201), 1)
|
||||
self.assertEqual(statuses.count(409), 9)
|
||||
|
||||
def test_invalid_chat_creation(self):
|
||||
members = ([self.alice['id'], self.alice['id']], [self.bob['id']], [self.alice['id'], str(uuid.uuid4())], [], [True])
|
||||
for member_ids in members:
|
||||
self.client.call('POST', '/api/v1/chats', 400, actor=self.alice, body={'title': 'rollback', 'member_ids': member_ids})
|
||||
|
||||
def test_cursor_scope_and_validation(self):
|
||||
for i in range(3):
|
||||
self.client.message(self.alice, self.chat, str(i))
|
||||
cursor = self.client.call('GET', self.path + '/messages?limit=1', actor=self.alice, schema='MessagePage')['json']['next_cursor']
|
||||
other = self.client.call('POST', '/api/v1/chats', 201, actor=self.alice, body={'title': 'other', 'member_ids': [self.alice['id']]}, schema='Chat')['json']
|
||||
self.client.call('GET', '/api/v1/chats/' + other['id'] + '/messages?cursor=' + quote(cursor), 400, actor=self.alice)
|
||||
for query in ('limit=0', 'limit=101', 'limit=' + '9' * 5000, 'limit=true', 'limit=1&limit=2', 'cursor=', 'cursor=bad', 'cursor=e30=', 'offset=1'):
|
||||
self.client.call('GET', self.path + '/messages?' + query, 400, actor=self.alice)
|
||||
|
||||
def test_concurrent_messages_and_pagination(self):
|
||||
def send(i):
|
||||
return Client().message(self.alice if i % 2 else self.bob, self.chat, 'parallel-' + str(i))['json']
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=10) as executor:
|
||||
sent = list(executor.map(send, range(100)))
|
||||
found = []
|
||||
cursor = None
|
||||
while True:
|
||||
url = self.path + '/messages?limit=7' + ('&cursor=' + quote(cursor) if cursor else '')
|
||||
page = self.client.call('GET', url, actor=self.alice, schema='MessagePage')['json']
|
||||
found.extend(page['items'])
|
||||
cursor = page['next_cursor']
|
||||
if cursor is None:
|
||||
break
|
||||
self.assertEqual(len(found), 100)
|
||||
self.assertEqual(len({v['id'] for v in found}), 100)
|
||||
self.assertEqual({v['id'] for v in found}, {v['id'] for v in sent})
|
||||
self.assertEqual(found, sorted(found, key=lambda v: (v['created_at'], v['id'])))
|
||||
|
||||
@unittest.skipUnless(LAB >= 2, 'sessions start in lab2')
|
||||
def test_unicode_password_basic_and_logout(self):
|
||||
import base64
|
||||
registration = {'username': 'unicode_' + uuid.uuid4().hex[:16], 'display_name': 'Софья', 'password': '🔐' * 127 + ':'}
|
||||
self.client.call('POST', '/api/v1/users', 201, body=registration)
|
||||
encoded = base64.b64encode((registration['username'] + ':' + registration['password']).encode()).decode()
|
||||
headers = {'Authorization': 'Basic ' + encoded}
|
||||
session = self.client.call('POST', '/api/v1/auth/sessions', 201, headers=headers, schema='Session')['json']
|
||||
actor = {'id': session['user']['id'], 'token': session['token']}
|
||||
self.client.call('GET', '/api/v1/users/me', actor=actor)
|
||||
self.client.call('GET', '/api/v1/users/me', 401, headers=headers)
|
||||
for authorization in ('Basic !!!', 'Bearer wrong', '', 'Basic Zm9v'):
|
||||
self.client.call('POST', '/api/v1/auth/sessions', 401, headers={'Authorization': authorization})
|
||||
self.client.call('DELETE', '/api/v1/auth/sessions/current', 204, actor=actor)
|
||||
self.client.call('GET', '/api/v1/users/me', 401, actor=actor)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main(verbosity=2)
|
||||
Reference in New Issue
Block a user