forked from mtusi2026/mtusi2026lab3
lab3
This commit is contained in:
@@ -0,0 +1,55 @@
|
||||
"""Каждая реплика отдельно и поочерёдная замена под одним профилем нагрузки."""
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import time
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
from scripts.benchmark import context, measure, verify_confirmations
|
||||
from scripts.stack import containers, stop, wait, command, rolling, save
|
||||
from scripts.monitor import Monitor
|
||||
|
||||
|
||||
def main():
|
||||
base = os.getenv('BASE_URL', 'http://localhost:8080')
|
||||
aliases = wait(2, base)
|
||||
results = []
|
||||
for target in aliases:
|
||||
ctx = context(base)
|
||||
# Сохраняем подтверждённую запись до отказа вместе с подтверждениями нагрузки.
|
||||
from scripts.benchmark import Client
|
||||
original = Client(base).message(ctx['actor'], ctx['chat'], 'До отказа')['json']
|
||||
try:
|
||||
with Monitor() as monitor:
|
||||
report, confirmations = measure(base, ctx, 16, 4,
|
||||
action=lambda: stop(target), retry_writes=True)
|
||||
event = report['action_events'][0]
|
||||
successful_times = sorted(int(x) for x, count in report['successful_per_second'].items() if count)
|
||||
first = next((x for x in successful_times if x > event['end_seconds']), None)
|
||||
if first is None or first+1-event['start_seconds'] > 10:
|
||||
raise AssertionError('Recovery exceeded 10 seconds')
|
||||
stopped_host = target.split(':')[0]
|
||||
if any(r['running'] for r in containers('api') if r['hostname'] == stopped_host):
|
||||
raise AssertionError('Target is still running')
|
||||
report['first_successful_bucket_after_stop_seconds'] = first
|
||||
report['recovery_upper_bound_seconds'] = round(first+1-event['start_seconds'], 3)
|
||||
report['verification'] = verify_confirmations(base, ctx, [original, *confirmations])
|
||||
report['monitor'] = monitor.samples
|
||||
report['target'] = target
|
||||
results.append(report)
|
||||
save('failures.json', results)
|
||||
finally:
|
||||
command(['docker', 'compose', 'start', 'api'])
|
||||
wait(2, base)
|
||||
ctx = context(base)
|
||||
with Monitor() as monitor:
|
||||
report, confirmations = measure(base, ctx, 35, 4, action=rolling, retry_writes=True)
|
||||
report['verification'] = verify_confirmations(base, ctx, confirmations)
|
||||
report['monitor'] = monitor.samples
|
||||
save('rolling.json', report)
|
||||
print('PASS: both API failures and rolling replacement, confirmations preserved')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,64 @@
|
||||
"""Дополнения к публичному smoke. Не печатает и не сохраняет tokens."""
|
||||
import concurrent.futures
|
||||
import json
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
from uuid import uuid4
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests'))
|
||||
from client import Client, arguments, check, run
|
||||
|
||||
|
||||
def main():
|
||||
def configure(p):
|
||||
p.add_argument('--expiry', action='store_true', help='API must run with TTL=2')
|
||||
args = arguments('Student API checks', configure)
|
||||
c = Client(args.base_url)
|
||||
alice, bob, eve, chat = c.bootstrap()
|
||||
if args.expiry:
|
||||
time.sleep(2.2)
|
||||
c.call('GET', '/api/v1/users/me', 401, actor=alice)
|
||||
print('PASS: short TTL expiry')
|
||||
return
|
||||
registration = {'username': 'race_' + uuid4().hex[:12], 'display_name': 'Гонка',
|
||||
'password': 'Synthetic-password-42'}
|
||||
# Для гонки регистрируем оба допустимых исхода через urllib.
|
||||
import urllib.request
|
||||
import urllib.error
|
||||
def register(_):
|
||||
req = urllib.request.Request(c.base + '/api/v1/users',
|
||||
data=json.dumps(registration).encode(),
|
||||
headers={'Content-Type': 'application/json'})
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=10) as response:
|
||||
return response.status
|
||||
except urllib.error.HTTPError as error:
|
||||
return error.code
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=8) as executor:
|
||||
codes = list(executor.map(register, range(8)))
|
||||
check(codes.count(201) == 1 and codes.count(409) == 7, 'username race failed')
|
||||
path = '/api/v1/chats/' + chat['id']
|
||||
c.call('POST', '/api/v1/chats', 400, actor=alice,
|
||||
body={'title': 'unknown member', 'member_ids': [alice['id'], str(uuid4())]})
|
||||
for body in [{'text': 'x', 'sender_id': eve['id']}, {'text': 4}, {'text': ' '}]:
|
||||
c.call('POST', path + '/messages', 400, actor=alice, body=body)
|
||||
c.call('GET', path + '/messages?limit=true', 400, actor=alice)
|
||||
c.call('GET', path + '/messages?cursor=not-a-cursor', 400, actor=alice)
|
||||
for n in range(3):
|
||||
c.message(alice, chat, 'read-after-write ' + str(n))
|
||||
page = c.call('GET', path + '/messages?limit=1', actor=alice, schema='MessagePage')['json']
|
||||
other = c.call('POST', '/api/v1/chats', 201, actor=alice,
|
||||
body={'title': 'other', 'member_ids': [alice['id']]}, schema='Chat')['json']
|
||||
from urllib.parse import quote
|
||||
c.call('GET', '/api/v1/chats/' + other['id'] + '/messages?cursor=' +
|
||||
quote(page['next_cursor'], safe=''), 400, actor=alice)
|
||||
history = c.call('GET', path + '/messages', actor=bob, schema='MessagePage')['json']['items']
|
||||
check(len(history) == 3 and history[-1]['text'] == 'read-after-write 2', 'read-after-write failed')
|
||||
c.call('DELETE', '/api/v1/auth/sessions/current', 204, actor=alice)
|
||||
c.call('GET', '/api/v1/users/me', 401, actor=alice)
|
||||
print('PASS: registration race, invalid input, cursor scope, read-after-write, logout')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run(main)
|
||||
@@ -0,0 +1,61 @@
|
||||
"""Проверка реального rollback после вставки чата и первого участника."""
|
||||
import sys
|
||||
from pathlib import Path
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
from uuid import uuid4
|
||||
import psycopg
|
||||
import os
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests'))
|
||||
from client import Client
|
||||
from src.config import DATABASE_URL
|
||||
from src.migrate import migrate
|
||||
|
||||
migrate()
|
||||
migrate() # Повтор миграции не создаёт дубликаты.
|
||||
with psycopg.connect(DATABASE_URL) as db:
|
||||
user = db.execute('SELECT id FROM users LIMIT 1').fetchone()
|
||||
assert user, 'Сначала выполните smoke, чтобы создать синтетического пользователя'
|
||||
chat = uuid4()
|
||||
try:
|
||||
with db.transaction():
|
||||
db.execute('INSERT INTO chats(id,title) VALUES (%s,%s)', (chat, 'rollback test'))
|
||||
db.execute('INSERT INTO chat_members VALUES (%s,%s)', (chat, user[0]))
|
||||
# FK прерывает составную операцию ПОСЛЕ двух успешных INSERT.
|
||||
db.execute('INSERT INTO chat_members VALUES (%s,%s)', (chat, uuid4()))
|
||||
except psycopg.errors.ForeignKeyViolation:
|
||||
pass
|
||||
else:
|
||||
raise AssertionError('Expected foreign-key failure')
|
||||
assert db.execute('SELECT count(*) FROM chats WHERE id=%s', (chat,)).fetchone()[0] == 0
|
||||
assert db.execute('SELECT count(*) FROM chat_members WHERE chat_id=%s', (chat,)).fetchone()[0] == 0
|
||||
assert db.execute('SELECT count(*) FROM schema_migrations').fetchone()[0] == 2
|
||||
print('PASS: rollback of chat + members; migration reapplied twice')
|
||||
|
||||
c = Client(os.getenv('BASE_URL', 'http://localhost:8080'))
|
||||
alice, bob, _, chat = c.bootstrap()
|
||||
key = uuid4().hex
|
||||
original = c.message(alice, chat, 'До истечения ключа', key=key)['json']
|
||||
with psycopg.connect(DATABASE_URL) as db:
|
||||
# Без ожидания суток: сдвигаем именно persisted expiry, а не clock приложения.
|
||||
db.execute("UPDATE message_requests SET expires_at=now()-interval '1 second' "
|
||||
"WHERE chat_id=%s AND request_key=%s", (chat['id'], key))
|
||||
renewed = c.message(alice, chat, 'После истечения ключа', key=key)['json']
|
||||
assert renewed['id'] != original['id']
|
||||
with psycopg.connect(DATABASE_URL) as db:
|
||||
assert db.execute('SELECT count(*) FROM message_requests WHERE chat_id=%s AND request_key=%s',
|
||||
(chat['id'], key)).fetchone()[0] == 1
|
||||
with psycopg.connect(DATABASE_URL) as db:
|
||||
message = uuid4()
|
||||
try:
|
||||
with db.transaction():
|
||||
db.execute('INSERT INTO messages(id,chat_id,sender_id,text) VALUES (%s,%s,%s,%s)',
|
||||
(message, chat['id'], bob['id'], 'atomic rollback'))
|
||||
# Ошибка сохранения результата должна откатить и сообщение.
|
||||
db.execute("INSERT INTO message_requests VALUES (%s,%s,%s,%s,%s,now())",
|
||||
(uuid4(), chat['id'], 'rollback', '0'*64, psycopg.types.json.Jsonb({})))
|
||||
except psycopg.errors.ForeignKeyViolation:
|
||||
pass
|
||||
else:
|
||||
raise AssertionError('Expected result-store failure')
|
||||
assert db.execute('SELECT count(*) FROM messages WHERE id=%s', (message,)).fetchone()[0] == 0
|
||||
print('PASS: persisted key expiry, atomic message/result rollback')
|
||||
@@ -0,0 +1,48 @@
|
||||
"""Redis необязателен для корректности; без PostgreSQL готовность снимается."""
|
||||
import os
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import time
|
||||
import urllib.request
|
||||
import urllib.error
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
from scripts.benchmark import context, Client
|
||||
from scripts.stack import command, wait, save
|
||||
|
||||
base = os.getenv('BASE_URL', 'http://localhost:8080')
|
||||
c = Client(base)
|
||||
ctx = context(base)
|
||||
original = c.message(ctx['actor'], ctx['chat'], 'До отказов')['json']
|
||||
results = {}
|
||||
try:
|
||||
command(['docker', 'compose', 'stop', 'cache'])
|
||||
started = time.monotonic()
|
||||
for _ in range(6):
|
||||
c.call('GET', '/api/v1/users/me', actor=ctx['actor'], schema='User')
|
||||
c.message(ctx['actor'], ctx['chat'], 'Без Redis')
|
||||
results['redis'] = dict(status='PASS', elapsed_seconds=time.monotonic()-started)
|
||||
finally:
|
||||
command(['docker', 'compose', 'up', '-d', '--wait', 'cache'])
|
||||
try:
|
||||
command(['docker', 'compose', 'stop', 'db'])
|
||||
# Даём LB время исключить все неготовые API. Его собственный 503 может быть HTML.
|
||||
time.sleep(4)
|
||||
codes = []
|
||||
for path in ['/health/ready', '/api/v1/users/me']:
|
||||
request = urllib.request.Request(base+path, headers={'Authorization': 'Bearer '+ctx['actor']['token']})
|
||||
try:
|
||||
with urllib.request.urlopen(request, timeout=8) as response:
|
||||
codes.append(response.status)
|
||||
except urllib.error.HTTPError as exc:
|
||||
codes.append(exc.code)
|
||||
assert codes == [503, 503], codes
|
||||
results['postgres'] = dict(status='PASS', readiness_and_request_status=codes)
|
||||
finally:
|
||||
command(['docker', 'compose', 'up', '-d', '--wait', 'db'])
|
||||
wait(2, base)
|
||||
page = c.call('GET', '/api/v1/chats/'+ctx['chat']['id']+'/messages', actor=ctx['reader'], schema='MessagePage')['json']
|
||||
assert original in page['items']
|
||||
c.call('GET', '/api/v1/users/me', actor=ctx['actor'], schema='User')
|
||||
results['recovery'] = 'old session and confirmed message preserved'
|
||||
save('dependencies.json', results)
|
||||
print('PASS: Redis fallback, PostgreSQL unready, recovery without new login')
|
||||
@@ -0,0 +1,58 @@
|
||||
"""Проверки общего результата повтора через LB и несколько API."""
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import json
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import uuid
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests'))
|
||||
from client import Client, arguments, check, run
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments('Shared idempotency through LB')
|
||||
c = Client(args.base_url, args.ca_file)
|
||||
alice, bob, eve, chat = c.bootstrap()
|
||||
key = uuid.uuid4().hex
|
||||
text = 'Один результат для конкурентных повторов'
|
||||
|
||||
def send(_):
|
||||
return Client(args.base_url, args.ca_file).message(alice, chat, text, key=key)
|
||||
|
||||
with ThreadPoolExecutor(max_workers=16) as pool:
|
||||
responses = list(pool.map(send, range(32)))
|
||||
first = responses[0]['json']
|
||||
check(all(r['json'] == first and r['status'] == 201 for r in responses), 'replay differs')
|
||||
instances = {r['headers']['X-Instance-Id'] for r in responses}
|
||||
check(len(instances) >= 2, 'race did not cross API replicas')
|
||||
path = '/api/v1/chats/' + chat['id'] + '/messages'
|
||||
history = c.call('GET', path, actor=bob, schema='MessagePage')['json']['items']
|
||||
check(len(history) == 1 and history[0] == first, 'concurrent replay created duplicates')
|
||||
c.call('POST', path, 409, body={'text': 'Другой текст'}, actor=alice,
|
||||
headers={'Idempotency-Key': key})
|
||||
for invalid in ['', 'bad key', 'a' * 129]:
|
||||
c.call('POST', path, 400, body={'text': text}, actor=alice,
|
||||
headers={'Idempotency-Key': invalid})
|
||||
c.call('POST', path, 400, body={'text': text}, actor=alice)
|
||||
# Тот же ключ независим для другого пользователя и другого чата.
|
||||
other = c.message(bob, chat, text, key=key)['json']
|
||||
check(other['id'] != first['id'], 'key scope must include user')
|
||||
chat2 = c.call('POST', '/api/v1/chats', 201, actor=alice,
|
||||
body={'title': 'Second', 'member_ids': [alice['id']]}, schema='Chat')['json']
|
||||
check(c.message(alice, chat2, text, key=key)['json']['id'] != first['id'], 'key scope must include chat')
|
||||
# Пробелы JSON не изменяют смысл текста и не должны менять результат.
|
||||
replay = c.call('POST', path, 201, actor=alice, raw=json.dumps({'text': text}, indent=2).encode(),
|
||||
headers={'Content-Type': 'application/json', 'Idempotency-Key': key}, schema='Message')
|
||||
check(replay['json'] == first, 'JSON formatting changed idempotency')
|
||||
c.call('POST', path, 404, actor=eve, body={'text': text}, headers={'Idempotency-Key': key})
|
||||
c.call('DELETE', '/api/v1/auth/sessions/current', 204, actor=alice)
|
||||
c.call('POST', path, 401, actor=alice, body={'text': text}, headers={'Idempotency-Key': key})
|
||||
result = dict(status='PASS', concurrent_requests=32, observed_instances=len(instances),
|
||||
messages_after_race=len(history), conflict=409, invalid_key=400, logout=401)
|
||||
Path('evidence').mkdir(exist_ok=True)
|
||||
Path('evidence/idempotency.json').write_text(json.dumps(result, indent=2))
|
||||
print('PASS: shared idempotency, scope, conflict and auth on replay')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run(main)
|
||||
@@ -0,0 +1,87 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Black-box grading evidence beyond the public smoke test."""
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import json
|
||||
import sys
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
from urllib.parse import quote
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import Client, arguments, check, run # noqa: E402
|
||||
|
||||
|
||||
def collect_messages(client, actor, chat, page_size=17):
|
||||
items = []
|
||||
cursor = None
|
||||
while True:
|
||||
path = f"/api/v1/chats/{chat['id']}/messages?limit={page_size}"
|
||||
if cursor:
|
||||
path += "&cursor=" + quote(cursor, safe="")
|
||||
page = client.call("GET", path, actor=actor, schema="MessagePage")["json"]
|
||||
items.extend(page["items"])
|
||||
cursor = page["next_cursor"]
|
||||
if cursor is None:
|
||||
return items
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments("Student negative, pagination and concurrency tests")
|
||||
client = Client(args.base_url, args.ca_file)
|
||||
alice, bob, outsider, chat = client.bootstrap()
|
||||
|
||||
client.call(
|
||||
"POST",
|
||||
"/api/v1/users",
|
||||
400,
|
||||
raw=b'{"username":',
|
||||
headers={"Content-Type": "application/json"},
|
||||
)
|
||||
client.call(
|
||||
"POST",
|
||||
"/api/v1/users",
|
||||
415,
|
||||
raw=b'{"username":"wrong_media","display_name":"Wrong"}',
|
||||
headers={"Content-Type": "text/plain"},
|
||||
)
|
||||
client.call("POST", "/api/v1/users", 409, body=alice["registration"])
|
||||
client.call(
|
||||
"POST",
|
||||
f"/api/v1/chats/{chat['id']}/messages",
|
||||
400,
|
||||
actor=alice,
|
||||
body={"text": " \t"},
|
||||
)
|
||||
client.call("GET", f"/api/v1/chats/{chat['id']}", 404, actor=outsider)
|
||||
|
||||
prefix = "race-" + uuid.uuid4().hex + "-"
|
||||
|
||||
def send(worker_id):
|
||||
local = Client(args.base_url, args.ca_file)
|
||||
return [
|
||||
local.message(alice, chat, f"{prefix}{worker_id}-{index}")["json"]
|
||||
for index in range(10)
|
||||
]
|
||||
|
||||
with ThreadPoolExecutor(max_workers=10) as pool:
|
||||
created = [message for batch in pool.map(send, range(10)) for message in batch]
|
||||
|
||||
check(len(created) == 100, "not all concurrent requests succeeded")
|
||||
check(len({message["id"] for message in created}) == 100, "duplicate message ids returned")
|
||||
|
||||
history = collect_messages(client, bob, chat)
|
||||
concurrent_history = [message for message in history if message["text"].startswith(prefix)]
|
||||
check(len(concurrent_history) == 100, "history does not contain exactly 100 concurrent messages")
|
||||
check(len({message["id"] for message in concurrent_history}) == 100, "history contains duplicates")
|
||||
check(
|
||||
history == sorted(history, key=lambda message: (message["created_at"], uuid.UUID(message["id"]).int)),
|
||||
"multi-page history is out of order",
|
||||
)
|
||||
|
||||
print("PASS: malformed JSON/media type, duplicate username, blank message, outsider access, pagination")
|
||||
print("PASS: 10 clients created exactly 100 unique messages")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
Reference in New Issue
Block a user