forked from mtusi2026/mtusi2026lab4
feat: ЛР 4 с хранением вложений в MinIO
This commit is contained in:
@@ -0,0 +1,67 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Stop the API replica that accepted upload and download through another replica."""
|
||||
import hashlib
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import time
|
||||
|
||||
from client import Client, ROOT, arguments, check, run
|
||||
|
||||
|
||||
def main():
|
||||
def configure(parser):
|
||||
parser.add_argument('--action-script', required=True)
|
||||
|
||||
args = arguments('Attachment API-replica failover', configure)
|
||||
script = Path(args.action_script).expanduser().resolve()
|
||||
check(script.is_file() and os.access(script, os.X_OK), 'action script must be executable')
|
||||
client = Client(args.base_url, args.ca_file, timeout=3)
|
||||
alice, bob, _eve, chat = client.bootstrap()
|
||||
content = (ROOT / 'tests/fixtures/sample.png').read_bytes()
|
||||
uploaded = client.call(
|
||||
'POST',
|
||||
f'/api/v1/chats/{chat["id"]}/attachments?filename=failover.png',
|
||||
201,
|
||||
actor=alice,
|
||||
raw=content,
|
||||
headers={'Content-Type': 'image/png'},
|
||||
schema='Attachment',
|
||||
)
|
||||
target = uploaded['headers']['X-Instance-Id']
|
||||
env = dict(os.environ)
|
||||
env['TARGET_INSTANCE_ID'] = target
|
||||
started = time.monotonic()
|
||||
subprocess.run([str(script)], env=env, check=True)
|
||||
|
||||
deadline = time.monotonic() + 15
|
||||
failures = 0
|
||||
while True:
|
||||
try:
|
||||
downloaded = client.call(
|
||||
'GET',
|
||||
f'/api/v1/attachments/{uploaded["json"]["id"]}/content',
|
||||
actor=bob,
|
||||
)
|
||||
if downloaded['headers']['X-Instance-Id'] != target:
|
||||
break
|
||||
except Exception:
|
||||
failures += 1
|
||||
check(time.monotonic() < deadline, 'download did not recover through another replica')
|
||||
time.sleep(0.2)
|
||||
|
||||
check(downloaded['bytes'] == content, 'downloaded file differs after replica failure')
|
||||
print(
|
||||
'PASS: upload_instance=%s download_instance=%s recovery_seconds=%.3f failures=%d sha256=%s'
|
||||
% (
|
||||
target,
|
||||
downloaded['headers']['X-Instance-Id'],
|
||||
time.monotonic() - started,
|
||||
failures,
|
||||
hashlib.sha256(content).hexdigest(),
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run(main)
|
||||
@@ -0,0 +1,54 @@
|
||||
"""Проверка компенсации объекта при ошибке commit метаданных."""
|
||||
import asyncio
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
from uuid import uuid4
|
||||
|
||||
import pytest
|
||||
|
||||
from app.domain.models import User
|
||||
from app.services.attachments import AttachmentService
|
||||
|
||||
|
||||
class FailingRepository:
|
||||
async def chat_exists_for_member(self, chat_id, user_id):
|
||||
return True
|
||||
|
||||
async def create(self, **kwargs):
|
||||
raise RuntimeError('injected database commit failure')
|
||||
|
||||
|
||||
class RecordingStorage:
|
||||
def __init__(self):
|
||||
self.put_key = None
|
||||
self.removed_key = None
|
||||
|
||||
async def put(self, key, source, length, content_type):
|
||||
self.put_key = key
|
||||
|
||||
async def remove(self, key):
|
||||
self.removed_key = key
|
||||
|
||||
|
||||
def test_uploaded_object_is_removed_when_metadata_commit_fails():
|
||||
storage = RecordingStorage()
|
||||
service = AttachmentService(FailingRepository(), storage, 10 * 1024 * 1024, 40_000_000)
|
||||
actor = User(uuid4(), 'tester', 'Tester', datetime.now(timezone.utc))
|
||||
content = (Path(__file__).parent / 'fixtures/sample.png').read_bytes()
|
||||
|
||||
async def chunks():
|
||||
yield content
|
||||
|
||||
with pytest.raises(RuntimeError, match='injected database commit failure'):
|
||||
asyncio.run(
|
||||
service.upload(
|
||||
actor,
|
||||
uuid4(),
|
||||
'sample.png',
|
||||
'image/png',
|
||||
chunks(),
|
||||
)
|
||||
)
|
||||
|
||||
assert storage.put_key is not None
|
||||
assert storage.removed_key == storage.put_key
|
||||
@@ -0,0 +1,144 @@
|
||||
"""Негативные интеграционные проверки вложений для уровня 4."""
|
||||
import struct
|
||||
from urllib.parse import quote
|
||||
import uuid
|
||||
import zlib
|
||||
|
||||
import pytest
|
||||
|
||||
from tests.client import Client, ROOT
|
||||
|
||||
|
||||
@pytest.fixture(scope='module')
|
||||
def scenario():
|
||||
client = Client()
|
||||
alice, bob, eve, chat = client.bootstrap()
|
||||
return client, alice, bob, eve, chat
|
||||
|
||||
|
||||
def upload(client, actor, chat, content, *, filename='sample.png', content_type='image/png', expected=201):
|
||||
return client.call(
|
||||
'POST',
|
||||
f'/api/v1/chats/{chat["id"]}/attachments?filename={quote(filename, safe="")}',
|
||||
expected,
|
||||
actor=actor,
|
||||
raw=content,
|
||||
headers={'Content-Type': content_type},
|
||||
schema='Attachment' if expected == 201 else None,
|
||||
)
|
||||
|
||||
|
||||
def oversized_dimensions_png(content: bytes) -> bytes:
|
||||
data = bytearray(content)
|
||||
data[16:20] = struct.pack('>I', 10_000)
|
||||
data[20:24] = struct.pack('>I', 5_000)
|
||||
data[29:33] = struct.pack('>I', zlib.crc32(data[12:29]) & 0xFFFFFFFF)
|
||||
return bytes(data)
|
||||
|
||||
|
||||
def test_file_larger_than_10_mib_is_rejected(scenario):
|
||||
client, alice, _bob, _eve, chat = scenario
|
||||
upload(client, alice, chat, b'x' * (10 * 1024 * 1024 + 1), expected=413)
|
||||
|
||||
|
||||
def test_corrupted_image_is_rejected(scenario):
|
||||
client, alice, _bob, _eve, chat = scenario
|
||||
upload(client, alice, chat, b'not-a-png', expected=415)
|
||||
|
||||
|
||||
def test_mime_mismatch_is_rejected(scenario):
|
||||
client, alice, _bob, _eve, chat = scenario
|
||||
content = (ROOT / 'tests/fixtures/sample.png').read_bytes()
|
||||
upload(client, alice, chat, content, content_type='image/jpeg', expected=415)
|
||||
|
||||
|
||||
def test_pixel_limit_is_checked_before_decode(scenario):
|
||||
client, alice, _bob, _eve, chat = scenario
|
||||
content = oversized_dimensions_png((ROOT / 'tests/fixtures/sample.png').read_bytes())
|
||||
upload(client, alice, chat, content, expected=413)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
'filename',
|
||||
['../escape.png', 'folder\\escape.png', 'bad\x00name.png', 'bad\x85name.png'],
|
||||
)
|
||||
def test_dangerous_filename_is_rejected(scenario, filename):
|
||||
client, alice, _bob, _eve, chat = scenario
|
||||
content = (ROOT / 'tests/fixtures/sample.png').read_bytes()
|
||||
upload(client, alice, chat, content, filename=filename, expected=400)
|
||||
|
||||
|
||||
def test_outsider_cannot_read_attachment(scenario):
|
||||
client, alice, _bob, eve, chat = scenario
|
||||
content = (ROOT / 'tests/fixtures/sample.png').read_bytes()
|
||||
attachment = upload(client, alice, chat, content)['json']
|
||||
client.call('GET', f'/api/v1/attachments/{attachment["id"]}', 404, actor=eve)
|
||||
client.call('GET', f'/api/v1/attachments/{attachment["id"]}/content', 404, actor=eve)
|
||||
|
||||
|
||||
def test_attachment_from_another_chat_cannot_be_linked(scenario):
|
||||
client, alice, bob, _eve, chat = scenario
|
||||
other_chat = client.call(
|
||||
'POST',
|
||||
'/api/v1/chats',
|
||||
201,
|
||||
actor=alice,
|
||||
body={'title': 'Другой чат', 'member_ids': [alice['id'], bob['id']]},
|
||||
schema='Chat',
|
||||
)['json']
|
||||
content = (ROOT / 'tests/fixtures/sample.png').read_bytes()
|
||||
attachment = upload(client, alice, other_chat, content)['json']
|
||||
client.call(
|
||||
'POST',
|
||||
f'/api/v1/chats/{chat["id"]}/messages',
|
||||
404,
|
||||
actor=alice,
|
||||
body={'text': 'чужое вложение', 'attachment_ids': [attachment['id']]},
|
||||
headers={'Idempotency-Key': uuid.uuid4().hex},
|
||||
)
|
||||
|
||||
|
||||
def test_idempotency_distinguishes_attachment_list(scenario):
|
||||
client, alice, _bob, _eve, chat = scenario
|
||||
content = (ROOT / 'tests/fixtures/sample.png').read_bytes()
|
||||
attachment = upload(client, alice, chat, content)['json']
|
||||
key = uuid.uuid4().hex
|
||||
first = client.message(
|
||||
alice,
|
||||
chat,
|
||||
'идемпотентное вложение',
|
||||
key=key,
|
||||
attachments=[attachment['id']],
|
||||
)['json']
|
||||
replay = client.message(
|
||||
alice,
|
||||
chat,
|
||||
'идемпотентное вложение',
|
||||
key=key,
|
||||
attachments=[attachment['id']],
|
||||
)['json']
|
||||
assert replay == first
|
||||
client.call(
|
||||
'POST',
|
||||
f'/api/v1/chats/{chat["id"]}/messages',
|
||||
409,
|
||||
actor=alice,
|
||||
body={'text': 'идемпотентное вложение', 'attachment_ids': []},
|
||||
headers={'Idempotency-Key': key},
|
||||
)
|
||||
|
||||
|
||||
def test_missing_attachment_ids_equals_empty_list_for_idempotency(scenario):
|
||||
client, alice, _bob, _eve, chat = scenario
|
||||
key = uuid.uuid4().hex
|
||||
first = client.message(alice, chat, 'обычный текст', key=key)['json']
|
||||
replay = client.call(
|
||||
'POST',
|
||||
f'/api/v1/chats/{chat["id"]}/messages',
|
||||
201,
|
||||
actor=alice,
|
||||
body={'text': 'обычный текст', 'attachment_ids': []},
|
||||
headers={'Idempotency-Key': key},
|
||||
schema='Message',
|
||||
)['json']
|
||||
assert replay == first
|
||||
@@ -0,0 +1,63 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Простой профиль параллельных загрузок для измерения RAM контейнеров API."""
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import json
|
||||
import time
|
||||
import uuid
|
||||
|
||||
from client import Client, ROOT, arguments, run
|
||||
|
||||
|
||||
def main():
|
||||
def configure(parser):
|
||||
parser.add_argument('--concurrency', type=int, default=10)
|
||||
parser.add_argument('--uploads', type=int, default=30)
|
||||
|
||||
args = arguments(
|
||||
'Parallel attachment uploads',
|
||||
configure,
|
||||
)
|
||||
if args.concurrency < 10:
|
||||
raise ValueError('concurrency must be at least 10 for lab4 evidence')
|
||||
if args.uploads < args.concurrency:
|
||||
raise ValueError('uploads must be greater than or equal to concurrency')
|
||||
client = Client(args.base_url, args.ca_file, timeout=30)
|
||||
alice, _bob, _eve, chat = client.bootstrap()
|
||||
content = (ROOT / 'tests/fixtures/sample.png').read_bytes()
|
||||
|
||||
def upload(index):
|
||||
local = Client(args.base_url, args.ca_file, timeout=30)
|
||||
started = time.monotonic()
|
||||
response = local.call(
|
||||
'POST',
|
||||
f'/api/v1/chats/{chat["id"]}/attachments?filename=load-{index}-{uuid.uuid4().hex}.png',
|
||||
201,
|
||||
actor=alice,
|
||||
raw=content,
|
||||
headers={'Content-Type': 'image/png'},
|
||||
schema='Attachment',
|
||||
)
|
||||
return response['headers']['X-Instance-Id'], time.monotonic() - started
|
||||
|
||||
started = time.monotonic()
|
||||
with ThreadPoolExecutor(max_workers=args.concurrency) as pool:
|
||||
results = list(pool.map(upload, range(args.uploads)))
|
||||
duration = time.monotonic() - started
|
||||
latencies = sorted(item[1] for item in results)
|
||||
print(
|
||||
json.dumps(
|
||||
{
|
||||
'concurrency': args.concurrency,
|
||||
'file_size_bytes': len(content),
|
||||
'successful_uploads': len(results),
|
||||
'instances': len({item[0] for item in results}),
|
||||
'duration_seconds': round(duration, 3),
|
||||
'max_latency_seconds': round(latencies[-1], 3),
|
||||
},
|
||||
ensure_ascii=False,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run(main)
|
||||
Reference in New Issue
Block a user