Реализовано хранилище вложений для лабораторной 4

This commit is contained in:
2026-11-02 23:40:07 +03:00
parent ec540a1a72
commit b99ad646e8
77 changed files with 2300 additions and 52 deletions
+31
View File
@@ -0,0 +1,31 @@
# Собственные проверки Lab 4
Этот каталог принадлежит студенту. Публичные contract tests в `tests/` сохранены без изменений.
Запуск после старта стенда:
```sh
make test-student BASE_URL=http://localhost:8080
```
Проверка создаёт синтетических пользователей и чат, загружает публичный PNG fixture, читает его как второй участник, проверяет ACL для постороннего, привязку вложения к чату и типовые ошибки upload. Она не печатает токены и не сохраняет пользовательские данные.
Для обязательного эксперимента чтения между API-репликами выполните после smoke:
```sh
make test-attachment-failover BASE_URL=http://localhost:8080
```
Скрипт останавливает только API-реплику, которая обслужила upload, читает оригинал через LB, затем восстанавливает две реплики. Все хранилища и volumes остаются на месте.
Проверка приватности bucket из сети API:
```sh
make test-private-bucket
```
Проверка недоступности и восстановления S3 (временно останавливает только сервис s3, затем запускает его обратно):
```sh
make test-s3-failure BASE_URL=http://localhost:8080
```
+74
View File
@@ -0,0 +1,74 @@
#!/usr/bin/env python3
"""Upload through one API instance, stop it, then download through its peer."""
import os
from pathlib import Path
import subprocess
import sys
import time
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tests'))
from client import Client, Failure, arguments, check, run
def main():
args = arguments('Lab 4 attachment cross-replica check')
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', '/api/v1/chats/' + chat['id'] + '/attachments?filename=sample.png',
201, actor=alice, raw=content, headers={'Content-Type': 'image/png'},
schema='Attachment',
)
source_instance = uploaded['headers']['X-Instance-Id']
observed = set()
for _ in range(50):
observed.add(client.call(
'GET', '/health/live', schema='Health',
)['headers']['X-Instance-Id'])
check(len(observed) >= 2, 'expected at least two API instances before stopping one')
check(source_instance in observed, 'upload instance was not observed by the load balancer')
hook = ROOT / 'scripts/stop-one.sh'
env = dict(os.environ)
env['TARGET_INSTANCE_ID'] = source_instance
subprocess_result = subprocess.run(
[str(hook)], cwd=ROOT, env=env, stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL, timeout=10, check=False,
)
check(subprocess_result.returncode == 0, 'stop-one hook could not stop the upload instance')
try:
deadline = time.monotonic() + 10
while time.monotonic() < deadline:
try:
metadata = client.call(
'GET', '/api/v1/attachments/' + uploaded['json']['id'],
actor=bob, schema='Attachment',
)
download = client.call(
'GET', '/api/v1/attachments/' + uploaded['json']['id'] + '/content',
actor=bob,
)
if (metadata['headers']['X-Instance-Id'] != source_instance
and download['headers']['X-Instance-Id'] != source_instance):
check(download['bytes'] == content, 'cross-replica bytes differ from uploaded file')
check(metadata['json']['sha256'] == uploaded['json']['sha256'],
'cross-replica metadata checksum changed')
print('PASS: upload instance stopped; metadata and original bytes read via peer')
return
except Failure:
time.sleep(0.25)
raise Failure('attachment was not readable from the other API instance within 10 seconds')
finally:
# Restore the two-replica local test stack after this explicit failure experiment.
subprocess.run(
['docker', 'compose', '--env-file', '.env', 'up', '-d', '--scale', 'api=2'],
cwd=ROOT, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
timeout=60, check=False,
)
if __name__ == '__main__':
run(main)
+79
View File
@@ -0,0 +1,79 @@
#!/usr/bin/env python3
"""Собственные интеграционные проверки вложений поверх неизменённого публичного API."""
import hashlib
from pathlib import Path
import sys
from urllib.parse import quote
import uuid
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tests'))
from client import Client, arguments, check, run
def main():
args = arguments('Lab 4 student attachment checks')
client = Client(args.base_url, args.ca_file)
alice, bob, eve, chat = client.bootstrap()
fixture = (ROOT / 'tests/fixtures/sample.png').read_bytes()
uploaded = client.call(
'POST', '/api/v1/chats/' + chat['id'] + '/attachments?filename=sample.png',
201, actor=alice, raw=fixture, headers={'Content-Type': 'image/png'},
schema='Attachment',
)['json']
check(uploaded['status'] == 'ready', 'upload was not ready')
check(uploaded['variants'] == [] and uploaded['error_code'] is None,
'Lab 4 ready metadata must have no variants or error')
check(uploaded['sha256'] == hashlib.sha256(fixture).hexdigest(),
'metadata checksum differs from fixture')
check(uploaded['size_bytes'] == len(fixture), 'metadata size differs from fixture')
metadata = client.call(
'GET', '/api/v1/attachments/' + uploaded['id'],
actor=bob, schema='Attachment',
)['json']
check(metadata == uploaded, 'another chat participant got different attachment metadata')
downloaded = client.call(
'GET', '/api/v1/attachments/' + uploaded['id'] + '/content', actor=bob,
)
check(downloaded['bytes'] == fixture, 'downloaded bytes are not identical')
check(downloaded['headers'].get_content_type() == 'image/png',
'download Content-Type is not the detected image type')
client.call('GET', '/api/v1/attachments/' + uploaded['id'], 404, actor=eve)
client.call('GET', '/api/v1/attachments/' + uploaded['id'] + '/content', 404, actor=eve)
# Нельзя привязать существующий файл чата к сообщению другого чата.
other_chat = client.call(
'POST', '/api/v1/chats', 201, actor=alice,
body={'title': 'Другой чат', 'member_ids': [alice['id'], bob['id']]},
schema='Chat',
)['json']
client.call(
'POST', '/api/v1/chats/' + other_chat['id'] + '/messages', 404,
actor=alice, body={'text': '', 'attachment_ids': [uploaded['id']]},
headers={'Idempotency-Key': uuid.uuid4().hex},
)
prefix = '/api/v1/chats/' + chat['id'] + '/attachments?filename='
client.call(
'POST', prefix + 'bad.png', 415, actor=alice, raw=b'not an image',
headers={'Content-Type': 'image/png'},
)
client.call(
'POST', prefix + 'mismatch.jpg', 415, actor=alice, raw=fixture,
headers={'Content-Type': 'image/jpeg'},
)
client.call(
'POST', prefix + quote('../sample.png', safe=''), 400, actor=alice,
raw=fixture, headers={'Content-Type': 'image/png'},
)
client.call(
'POST', prefix + 'too-large.png', 413, actor=alice,
raw=b'\x00' * (10 * 1024 * 1024 + 1),
headers={'Content-Type': 'image/png'},
)
print('PASS: upload/checksum/download, chat ACL, message binding and upload limits')
if __name__ == '__main__':
run(main)
+53
View File
@@ -0,0 +1,53 @@
#!/usr/bin/env python3
"""Проверка атомарного повтора одного сообщения через разные API-реплики."""
from concurrent.futures import ThreadPoolExecutor
import uuid
from pathlib import Path
import sys
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tests'))
from client import Client, arguments, check, run
def main():
args = arguments('Concurrent cross-replica idempotency check')
setup = Client(args.base_url, args.ca_file)
alice, _bob, _eve, chat = setup.bootstrap()
key = 'concurrent-' + uuid.uuid4().hex
text = 'Одно сообщение при конкурентном повторе ' + uuid.uuid4().hex
count = 16
def send(_):
client = Client(args.base_url, args.ca_file, timeout=10)
return client.call(
'POST', '/api/v1/chats/' + chat['id'] + '/messages', expected=201,
actor=alice, body={'text': text}, headers={'Idempotency-Key': key}, schema='Message',
)
with ThreadPoolExecutor(max_workers=count) as pool:
responses = list(pool.map(send, range(count)))
messages = [response['json'] for response in responses]
instance_ids = {response['headers'].get('X-Instance-Id') for response in responses}
check(all(message == messages[0] for message in messages), 'concurrent replay returned different Message objects')
check(len(instance_ids) >= 2, 'concurrent requests did not reach at least two observable API replicas')
replay = setup.call(
'POST', '/api/v1/chats/' + chat['id'] + '/messages', expected=201,
actor=alice, body={'text': text}, headers={'Idempotency-Key': key}, schema='Message',
)['json']
check(replay == messages[0], 'retry returned a different status payload')
setup.call(
'POST', '/api/v1/chats/' + chat['id'] + '/messages', expected=409,
actor=alice, body={'text': text + ' другой текст'}, headers={'Idempotency-Key': key},
)
history = setup.call(
'GET', '/api/v1/chats/' + chat['id'] + '/messages?limit=100',
actor=alice, schema='MessagePage',
)['json']['items']
matching = [message for message in history if message['text'] == text]
check(matching == [messages[0]], 'history contains a missing or duplicate side effect')
print('PASS: %d concurrent requests across %d API replicas returned one Message; changed body returned 409.' % (count, len(instance_ids)))
if __name__ == '__main__':
run(main)
+43
View File
@@ -0,0 +1,43 @@
#!/usr/bin/env python3
"""Отправить анонимный ListBucket из сети приложения и подтвердить private bucket."""
from pathlib import Path
import subprocess
ROOT = Path(__file__).resolve().parents[1]
def main():
env_path = ROOT / '.env'
if not env_path.is_file():
raise SystemExit('Create local .env from .env.example first')
values = {}
for line in env_path.read_text().splitlines():
if '=' in line and not line.lstrip().startswith('#'):
key, value = line.split('=', 1)
values[key.strip()] = value.strip()
bucket = values.get('S3_BUCKET', 'messenger-attachments')
url = 'http://s3:9000/' + bucket + '?list-type=2'
code = (
'import urllib.error, urllib.request\n'
'url = ' + repr(url) + '\n'
'try:\n'
' urllib.request.urlopen(url, timeout=5)\n'
'except urllib.error.HTTPError as error:\n'
' print("HTTP", error.code)\n'
' raise SystemExit(0 if error.code in (401, 403) else 1)\n'
'except Exception as error:\n'
' print(type(error).__name__)\n'
' raise SystemExit(1)\n'
'raise SystemExit("anonymous bucket listing unexpectedly succeeded")\n'
)
result = subprocess.run(
['docker', 'compose', '--env-file', '.env', 'exec', '-T', 'api', 'python', '-c', code],
cwd=ROOT, check=False,
)
if result.returncode:
raise SystemExit('FAIL: anonymous S3 bucket listing was not denied')
print('PASS: private bucket rejects unauthenticated listing')
if __name__ == '__main__':
main()
+73
View File
@@ -0,0 +1,73 @@
#!/usr/bin/env python3
"""Проверить ограниченную ошибку API при отказе S3 и восстановить его."""
from pathlib import Path
import subprocess
import sys
import time
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tests'))
from client import Client, Failure, arguments, check, run
def main():
args = arguments('Lab 4 S3 outage and recovery check')
# Дождаться ограниченных повторов boto3 при остановленном S3.
client = Client(args.base_url, args.ca_file, timeout=35)
alice, bob, eve, chat = client.bootstrap()
attachment, content = client.attachment(alice, chat)
initial = client.call(
'GET', '/api/v1/attachments/' + attachment['id'] + '/content', actor=bob,
)
check(initial['bytes'] == content, 'uploaded bytes differ before the outage')
stopped = subprocess.run(
['docker', 'compose', '--env-file', '.env', 'stop', 's3'],
cwd=ROOT, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
timeout=20, check=False,
)
check(stopped.returncode == 0, 'could not stop S3 for the outage test')
try:
ready = client.call('GET', '/health/ready', expected=503, schema='Error')
check(ready['json']['error']['code'] == 'unavailable',
'readiness did not report unavailable S3')
failed = client.call(
'GET', '/api/v1/attachments/' + attachment['id'] + '/content',
expected=503, actor=bob, schema='Error',
)
check(failed['json']['error']['code'] == 'unavailable',
'S3 failure was not translated to a bounded API error')
metadata = client.call(
'GET', '/api/v1/attachments/' + attachment['id'],
actor=bob, schema='Attachment',
)
check(metadata['json']['id'] == attachment['id'],
'PostgreSQL metadata was lost while S3 was unavailable')
print('PASS: S3 outage returned 503 for readiness/download; metadata remained available')
finally:
started = subprocess.run(
['docker', 'compose', '--env-file', '.env', 'start', 's3'],
cwd=ROOT, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
timeout=20, check=False,
)
check(started.returncode == 0, 'could not restart S3 after the outage test')
deadline = time.monotonic() + 30
while time.monotonic() < deadline:
try:
client.call('GET', '/health/ready', schema='Health')
break
except Failure:
time.sleep(0.25)
else:
raise Failure('API did not become ready after S3 restart')
recovered = client.call(
'GET', '/api/v1/attachments/' + attachment['id'] + '/content', actor=bob,
)
check(recovered['bytes'] == content, 'S3 restart changed or lost the original bytes')
print('PASS: original attachment bytes were readable after S3 recovery')
if __name__ == '__main__':
run(main)