Лабораторная 4 — вложения и приватное S3

This commit is contained in:
2026-11-13 10:39:20 +03:00
parent ec540a1a72
commit 4cd025e477
62 changed files with 3545 additions and 22 deletions
+106
View File
@@ -0,0 +1,106 @@
"""Run cleanup scenarios against a disposable PostgreSQL database."""
import os
import sys
from pathlib import Path
from uuid import uuid4
import psycopg2
from psycopg2 import sql
from psycopg2.extensions import make_dsn
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'src'))
from messenger.config import Config
from messenger.db import Database
from messenger.errors import Unavailable
from messenger.store import Store
GRACE_SECONDS = 900
def unavailable(_key):
raise Unavailable('synthetic S3 failure')
def expect_unavailable(operation):
try:
operation()
except Unavailable:
return
raise AssertionError('Expected Unavailable')
def exercise(database):
store = Store(None, database, None)
user, chat = str(uuid4()), str(uuid4())
with database.cursor() as cur:
cur.execute("INSERT INTO users VALUES (%s,'cleanup','unused','Cleanup')", (user,))
cur.execute("INSERT INTO chats VALUES (%s,'Cleanup')", (chat,))
def reserve(expired=False):
aid = str(uuid4())
key = 'attachments/' + aid
store.reserve_attachment(aid, chat, user, 'x.png', 'image/png', 1, 'a' * 64, key)
if expired:
with database.cursor() as cur:
cur.execute("UPDATE attachments SET updated_at=now()-interval '16 minutes' WHERE id=%s", (aid,))
return aid, key
objects = set()
fresh, fresh_key = reserve()
objects.add(fresh_key)
ready, ready_key = reserve(expired=True)
store.finish_attachment(ready, objects.add)
with database.cursor() as cur:
cur.execute("UPDATE attachments SET updated_at=now()-interval '16 minutes' WHERE id=%s", (ready,))
active, active_key = reserve(expired=True)
def active_put(key):
objects.add(key)
assert not store.clean_pending_attachment(GRACE_SECONDS, objects.discard)
store.finish_attachment(active, active_put)
failed, failed_key = reserve(expired=True)
def put_then_fail(key):
objects.add(key)
# Inject a failure after the object exists and before the ready update.
raise Unavailable('synthetic failure after PUT')
expect_unavailable(lambda: store.finish_attachment(failed, put_then_fail))
assert failed_key in objects
expect_unavailable(lambda: store.clean_pending_attachment(GRACE_SECONDS, unavailable))
with database.cursor() as cur:
cur.execute('SELECT status FROM attachments WHERE id=%s', (failed,))
assert cur.fetchone()['status'] == 'pending'
assert store.clean_pending_attachment(GRACE_SECONDS, objects.discard)
assert objects == {fresh_key, ready_key, active_key}
reserve(expired=True) # Reservation whose PUT never created an object.
assert store.clean_pending_attachment(GRACE_SECONDS, objects.discard)
assert not store.clean_pending_attachment(GRACE_SECONDS, objects.discard)
with database.cursor() as cur:
cur.execute('SELECT id::text AS id, status FROM attachments')
assert {row['id']: row['status'] for row in cur.fetchall()} == {
fresh: 'pending', ready: 'ready', active: 'ready',
}
print('PASS: PostgreSQL row lock protects active PUT; fresh and ready attachments preserved')
print('PASS: interrupted PUT and failure after PUT cleaned; S3 failure retries safely')
def main():
dsn = os.environ['LAB4_TEST_DATABASE_URL']
schema = 'cleanup_' + uuid4().hex
with psycopg2.connect(dsn) as conn, conn.cursor() as cur:
cur.execute(sql.SQL('CREATE SCHEMA {}').format(sql.Identifier(schema)))
config = Config.from_env({'DATABASE_URL': make_dsn(dsn, options='-csearch_path=' + schema)})
database = Database(config)
try:
database.open()
database.run_migrations()
exercise(database)
finally:
database.close()
with psycopg2.connect(dsn) as conn, conn.cursor() as cur:
cur.execute(sql.SQL('DROP SCHEMA {} CASCADE').format(sql.Identifier(schema)))
if __name__ == '__main__':
main()
+68
View File
@@ -0,0 +1,68 @@
"""Check upload errors through Nginx and exercise an actual S3 outage."""
from io import BytesIO
from pathlib import Path
import subprocess
import sys
import time
from PIL import Image
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(__doc__)
client = Client(args.base_url, args.ca_file, timeout=45)
alice, _, eve, chat = client.bootstrap()
data = (ROOT / 'tests/fixtures/sample.png').read_bytes()
path = f"/api/v1/chats/{chat['id']}/attachments"
good = path + '?filename=sample.png'
item, _ = client.attachment(alice, chat)
content = f"/api/v1/attachments/{item['id']}/content"
def upload(url, payload, expected, mime='image/png', actor=alice):
return client.call('POST', url, expected, actor=actor, raw=payload,
headers={'Content-Type': mime})
huge = BytesIO()
Image.new('1', (8001, 5000)).save(huge, 'PNG')
for payload, expected, mime in [
(b'x' * (10 * 1024 * 1024 + 1), 413, 'image/png'),
(huge.getvalue(), 413, 'image/png'),
(data[:30], 415, 'image/png'),
(data, 415, 'image/jpeg'),
]:
upload(good, payload, expected, mime)
upload(path + '?filename=a%2Fb.png', data, 400)
upload(good, data, 404, actor=eve)
client.call('GET', content, 404, actor=eve)
print('PASS: size, pixel count, corruption, MIME, filename and chat ACL over Nginx')
def s3_command(action):
subprocess.run(['docker', 'compose', action, 's3'], cwd=ROOT, check=True, timeout=30)
try:
s3_command('stop')
upload(good, data, 503)
client.call('GET', content, 503, actor=alice)
client.message(alice, chat, 'Текст при недоступном S3')
finally:
s3_command('start')
started = time.monotonic()
for _ in range(40):
try:
downloaded = client.call('GET', content, actor=alice)
break
except Failure:
time.sleep(.25)
else:
raise Failure('S3 download did not recover after restart')
check(downloaded['bytes'] == data, 'original changed after S3 restart')
print(f'PASS: S3 outage returned 503, text remained available, original recovered in {time.monotonic()-started:.2f}s')
if __name__ == '__main__':
run(main)
+54
View File
@@ -0,0 +1,54 @@
"""Stop the actual upload replica and check original bytes after failover and restart."""
from hashlib import sha256
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, arguments, check, run
def main():
args = arguments(__doc__)
client = Client(args.base_url, args.ca_file, timeout=55)
alice, bob, _, chat = client.bootstrap()
path = f"/api/v1/chats/{chat['id']}/attachments?filename=sample.png"
original = (ROOT / 'tests/fixtures/sample.png').read_bytes()
reply = client.call('POST', path, 201, actor=alice, raw=original,
headers={'Content-Type': 'image/png'}, schema='Attachment')
aid = reply['json']['id']
upload_instance = reply['headers']['X-Instance-Id']
digest = sha256(original).hexdigest()
content = '/api/v1/attachments/' + aid + '/content'
text = client.message(alice, chat, '', attachments=[aid])['json']
def verify():
received = client.call('GET', content, actor=bob)
check(received['bytes'] == original and sha256(received['bytes']).hexdigest() == digest,
'original changed')
history = client.call('GET', f"/api/v1/chats/{chat['id']}/messages",
actor=bob, schema='MessagePage')['json']
check(text in history['items'], 'message attachment link lost')
return received['headers']['X-Instance-Id']
start = time.monotonic()
try:
subprocess.run(['scripts/stop-one.sh'], cwd=ROOT, check=True, timeout=30,
env={**os.environ, 'TARGET_INSTANCE_ID': upload_instance})
instance = verify()
check(instance != upload_instance, 'download was served by the stopped uploader')
print(f'PASS: {upload_instance} -> {instance}, SHA-256 {digest}, {time.monotonic()-start:.2f}s')
finally:
subprocess.run([sys.executable, 'scripts/manage.py', 'restore'], cwd=ROOT, check=True, timeout=100)
start = time.monotonic()
subprocess.run(['scripts/restart.sh'], cwd=ROOT, check=True, timeout=100)
instance = verify()
print(f'PASS: after full restart via {instance}, SHA-256 {digest}, {time.monotonic()-start:.2f}s')
if __name__ == '__main__':
run(main)
+141
View File
@@ -0,0 +1,141 @@
from datetime import datetime, timezone
from hashlib import sha256
from io import BytesIO
import logging
import os
import http.client
import socket
from pathlib import Path
import threading
from urllib.error import HTTPError
from urllib.request import Request, urlopen
from uuid import uuid4
import json
import sys
from botocore.response import StreamingBody
from PIL import Image
root = Path(__file__).resolve().parents[1]
os.environ['S3_BUCKET'] = 'test'
sys.path.insert(0, str(root / 'src'))
from messenger.api import Api
from messenger.config import Config
from messenger.security import hash_token
from messenger.server import build_server
from messenger.store import Store
chat, member, outsider = [str(uuid4()) for _ in range(3)]
class Metadata:
rows = {}
def get_session(self, token):
return {hash_token('member'): member, hash_token('outsider'): outsider}.get(token)
def user(self, uid):
return {'id': uid}
def chat(self, cid):
return {'id': cid} if cid == chat else None
def is_member(self, _chat, uid):
return uid == member
def reserve_attachment(self, aid, cid, uid, filename, mime, size, digest, key):
now = datetime.now(timezone.utc)
self.rows[aid] = dict(id=aid, chat_id=cid, owner_id=uid, filename=filename,
content_type=mime, size_bytes=size, sha256=digest,
object_key=key, status='pending', error_code=None,
created_at=now, updated_at=now)
def finish_attachment(self, aid, put_object):
put_object(self.rows[aid]['object_key'])
self.rows[aid]['status'] = 'ready'
return self.rows[aid]
def visible_attachment(self, aid, uid):
row = self.rows.get(aid)
if uid == member and row and row['status'] == 'ready':
return row
return None
public_attachment = staticmethod(Store.public_attachment)
class S3:
def __init__(self):
self.objects = {}
self.fail = False
def put_object(self, **kw):
if self.fail:
from botocore.exceptions import EndpointConnectionError
raise EndpointConnectionError(endpoint_url='http://s3.invalid')
data = kw['Body'].read()
assert len(data) == kw['ContentLength']
self.objects[kw['Key']] = data
def get_object(self, **kw):
data = self.objects[kw['Key']]
return {'ContentLength': len(data), 'Body': StreamingBody(BytesIO(data), len(data))}
config = Config.from_env({'APP_HOST':'127.0.0.1','APP_PORT':'8080'})
config.port = 0
api = Api(config, Metadata(), None)
s3 = S3()
api.attachments.client = s3
server = build_server(config, logging.getLogger('lab4-check'), api, None)
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread.start()
base = 'http://127.0.0.1:' + str(server.server_address[1])
upload = f'/api/v1/chats/{chat}/attachments?filename=x.png'
def call(path, method='GET', data=None, mime='image/png', token='member'):
headers = {'Authorization': 'Bearer ' + token, 'Content-Type': mime}
try:
response = urlopen(Request(base + path, data=data, headers=headers, method=method), timeout=12)
except HTTPError as exc:
response = exc
with response:
return response.code, response.headers, response.read()
try:
for image_format, mime in [('PNG', 'image/png'), ('JPEG', 'image/jpeg')]:
buf = BytesIO()
Image.new('RGB', (10, 10), 'green').save(buf, format=image_format)
data = buf.getvalue()
status, _, raw = call(upload, 'POST', data, mime)
assert status == 201, (status, raw)
item = json.loads(raw)
assert item['status'] == 'ready' and item['sha256'] == sha256(data).hexdigest()
assert item['size_bytes'] == len(data) and 'object_key' not in item
path = '/api/v1/attachments/' + item['id']
assert json.loads(call(path)[2]) == item
status, headers, actual = call(path + '/content')
assert (status, headers['Content-Type'], actual) == (200, mime, data)
assert call(path, token='outsider')[0] == 404
assert call(path + '/content', token='outsider')[0] == 404
assert call(path + '/content?variant=thumbnail')[0] == 404
png = (root / 'tests/fixtures/sample.png').read_bytes()
assert call(upload, 'POST', png)[0] == 201
assert call(upload, 'POST', png, 'image/jpeg')[0] == 415
assert call(upload, 'POST', png[:30])[0] == 415
assert call(upload.replace('x.png','a%2Fb.png'), 'POST', png)[0] == 400
before = len(api.store.rows)
for length, partial, expected in [(10 * 1024 * 1024 + 1, b'', 413), (64, b'abc', 400)]:
conn = http.client.HTTPConnection(*server.server_address, timeout=5)
try:
conn.request('POST', upload, body=partial, headers={
'Authorization': 'Bearer member', 'Content-Type': 'image/png',
'Content-Length': str(length)})
if partial:
conn.sock.shutdown(socket.SHUT_WR)
with conn.getresponse() as response:
assert response.status == expected, response.status
response.read()
finally:
conn.close()
assert len(api.store.rows) == before
buf = BytesIO()
Image.new('1', (8001, 5000)).save(buf, 'PNG')
assert call(upload, 'POST', buf.getvalue())[0] == 413
s3.fail = True
assert call(upload, 'POST', png)[0] == 503
assert list(api.store.rows.values())[-1]['status'] == 'pending'
print('PASS: local HTTP PNG/JPEG round trip, checksum, metadata, ACL and missing variant')
print('PASS: malformed image, mismatched MIME, unsafe filename, byte/pixel limits and S3 error mapping')
print('NOTE: metadata and S3 are test substitutes; real Compose integration not exercised')
finally:
server.shutdown()
server.server_close()
thread.join()
+53
View File
@@ -0,0 +1,53 @@
"""Exercise attachment links and message replay over the running lab4 API."""
import sys
import uuid
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests'))
from client import Client, arguments, check, run
def main():
args = arguments('Message attachment links and replay')
client = Client(args.base_url, args.ca_file)
alice, bob, eve, chat = client.bootstrap()
first, _ = client.attachment(alice, chat)
second, _ = client.attachment(bob, chat)
ids = [second['id'], first['id']]
key = uuid.uuid4().hex
sent = client.message(bob, chat, '', key=key, attachments=ids)['json']
replay = client.message(bob, chat, '', key=key, attachments=ids)['json']
check(sent == replay and sent['attachment_ids'] == ids, 'ordered attachment replay mismatch')
path = f"/api/v1/chats/{chat['id']}/messages"
client.call('POST', path, 409, actor=bob, body={'text': '', 'attachment_ids': ids[::-1]},
headers={'Idempotency-Key': key})
for invalid in [[ids[0]] * 2, [str(uuid.uuid4()) for _ in range(11)], ['bad UUID'], None]:
client.call('POST', path, 400, actor=bob, body={'text': '', 'attachment_ids': invalid},
headers={'Idempotency-Key': uuid.uuid4().hex})
client.call('POST', path, 400, actor=bob, body={'text': ''},
headers={'Idempotency-Key': uuid.uuid4().hex})
client.call('POST', path, 404, actor=bob,
body={'text': '', 'attachment_ids': [str(uuid.uuid4())]},
headers={'Idempotency-Key': uuid.uuid4().hex})
other = client.call('POST', '/api/v1/chats', 201, actor=alice,
body={'title': 'Другой чат', 'member_ids': [alice['id'], eve['id']]},
schema='Chat')['json']
foreign, _ = client.attachment(alice, other)
client.call('POST', path, 404, actor=alice,
body={'text': '', 'attachment_ids': [foreign['id']]},
headers={'Idempotency-Key': uuid.uuid4().hex})
plain_key = uuid.uuid4().hex
plain = client.message(alice, chat, 'Обычный текст', key=plain_key)['json']
check(client.message(alice, chat, 'Обычный текст', key=plain_key, attachments=[])['json'] == plain,
'omitted and empty attachment_ids must replay identically')
page = client.call('GET', path, actor=alice, schema='MessagePage')['json']
check([item for item in page['items'] if item['id'] == sent['id']] == [sent],
'ordered attachment IDs missing or duplicated in history')
print('PASS: ordered attachments, replay, invalid input, cross-chat rejection and history')
if __name__ == '__main__':
run(main)
+72
View File
@@ -0,0 +1,72 @@
"""Run via docker compose exec -T api-a python - with this file on stdin."""
from hashlib import sha256
from io import BytesIO
from uuid import uuid4
from botocore.exceptions import ClientError
from PIL import Image
from messenger.attachments import AttachmentStorage
from messenger.clean_attachments import GRACE_SECONDS, clean_batch
from messenger.config import Config
from messenger.db import Database
from messenger.errors import Unavailable
from messenger.store import Store
def main():
config = Config.from_env()
db = Database(config)
db.open()
store = Store(config, db, None)
s3 = AttachmentStorage()
user, chat, aid = [str(uuid4()) for _ in range(3)]
key = 'attachments/' + aid
payload = BytesIO()
Image.new('RGB', (2, 2), 'green').save(payload, format='PNG')
data = payload.getvalue()
try:
with db.cursor() as cur:
cur.execute('INSERT INTO users (id,username,password_hash,display_name) VALUES (%s,%s,%s,%s)',
(user, 'gc_' + user[:8], 'unused', 'Cleanup check'))
cur.execute("INSERT INTO chats (id,title) VALUES (%s,'Cleanup check')", (chat,))
store.reserve_attachment(aid, chat, user, 'probe.png', 'image/png',
len(data), sha256(data).hexdigest(), key)
def put_then_fail(object_key):
s3.put(object_key, BytesIO(data), len(data), 'image/png')
raise Unavailable('synthetic failure after successful PUT')
try:
store.finish_attachment(aid, put_then_fail)
except Unavailable as exc:
assert str(exc) == 'synthetic failure after successful PUT'
else:
raise AssertionError('fault did not run')
obj = s3.client.get_object(Bucket=s3.bucket, Key=key)
with obj['Body'] as body:
assert body.read() == data
with db.cursor() as cur:
cur.execute('SELECT status FROM attachments WHERE id=%s', (aid,))
assert cur.fetchone()['status'] == 'pending'
cur.execute("UPDATE attachments SET updated_at=now()-make_interval(secs => %s) WHERE id=%s",
(GRACE_SECONDS + 1, aid))
clean_batch(store, s3)
with db.cursor() as cur:
cur.execute('SELECT 1 FROM attachments WHERE id=%s', (aid,))
assert cur.fetchone() is None
try:
obj = s3.client.get_object(Bucket=s3.bucket, Key=key)
except ClientError as exc:
assert exc.response['ResponseMetadata']['HTTPStatusCode'] == 404, exc
else:
obj['Body'].close()
raise AssertionError('orphan object still exists')
print('PASS: actual MinIO object existed after failed commit and was removed by cleanup')
finally:
db.close()
if __name__ == '__main__':
main()
+104
View File
@@ -0,0 +1,104 @@
"""Measure sampled cgroup memory during ten simultaneous HTTP uploads."""
from concurrent.futures import ThreadPoolExecutor
import hashlib
from io import BytesIO
import json
import math
from pathlib import Path
import random
import subprocess
import sys
from threading import Barrier
import time
from PIL import Image
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tests'))
from client import Client, Failure, arguments, check, run
COUNT = 10
SAMPLER = """
import select, sys, time
from pathlib import Path
usage = Path('/sys/fs/cgroup/memory.current')
limit = Path('/sys/fs/cgroup/memory.max')
cpu = Path('/sys/fs/cgroup/cpu.stat')
print(limit.read_text().strip(), flush=True)
while True:
stats = dict(line.split() for line in cpu.read_text().splitlines())
print(usage.read_text().strip(), stats['usage_usec'], flush=True)
if select.select([sys.stdin], [], [], .05)[0]:
break
"""
def main():
args = arguments(__doc__)
client = Client(args.base_url, args.ca_file, timeout=60)
alice, _, _, chat = client.bootstrap()
width = 1700
source = Image.frombytes('RGB', (width, width), random.Random(2026).randbytes(width * width * 3))
buffer = BytesIO()
source.save(buffer, format='PNG', compress_level=0)
payload = buffer.getvalue()
digest = hashlib.sha256(payload).hexdigest()
check(len(payload) <= 10 * 1024 * 1024, 'fixture exceeds upload size limit')
path = f"/api/v1/chats/{chat['id']}/attachments?filename=load.png"
barrier = Barrier(COUNT + 1)
samplers = {}
def upload():
local = Client(args.base_url, args.ca_file, timeout=60)
barrier.wait(timeout=30)
start = time.monotonic()
try:
reply = local.call('POST', path, 201, actor=alice, raw=payload,
headers={'Content-Type': 'image/png'}, schema='Attachment')
check(reply['json']['sha256'] == digest, 'upload hash mismatch')
return {'instance': reply['headers']['X-Instance-Id'], 'id': reply['json']['id'],
'seconds': time.monotonic() - start}
except Failure as exc:
return {'error': str(exc), 'seconds': time.monotonic() - start}
try:
for service in ('api-a', 'api-b'):
proc = subprocess.Popen(
['docker', 'compose', 'exec', '-T', service, 'python', '-u', '-c', SAMPLER],
cwd=ROOT, stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True)
samplers[service] = proc
with ThreadPoolExecutor(max_workers=COUNT) as pool:
futures = [pool.submit(upload) for _ in range(COUNT)]
limits = {service: int(proc.stdout.readline()) for service, proc in samplers.items()}
initial = {service: tuple(map(int, proc.stdout.readline().split()))
for service, proc in samplers.items()}
start = time.monotonic()
barrier.wait(timeout=30)
requests = [future.result() for future in futures]
elapsed = time.monotonic() - start
finally:
for proc in samplers.values():
if proc.poll() is None:
proc.stdin.close()
resources = {}
for service, proc in samplers.items():
samples = [initial[service]] + [tuple(map(int, line.split())) for line in proc.stdout]
check(proc.wait(timeout=10) == 0 and len(samples) > 1, 'memory sampler failed')
resources[service] = {
'baseline_bytes': samples[0][0], 'peak_sample_bytes': max(row[0] for row in samples),
'limit_bytes': limits[service], 'samples': len(samples),
'cpu_seconds': (samples[-1][1] - samples[0][1]) / 1e6,
}
successes = [row for row in requests if 'id' in row]
durations = sorted(row['seconds'] for row in successes)
percentiles = {f'p{p}': durations[math.ceil(p / 100 * len(durations)) - 1]
for p in (50, 95, 99)} if durations else {}
print(json.dumps({'concurrency': COUNT, 'payload_bytes': len(payload), 'sha256': digest,
'elapsed_seconds': elapsed, 'successful_rps': len(successes) / elapsed,
'latency_seconds': percentiles, 'requests': requests,
'memory_sample_interval_seconds': .05, 'resources': resources}, indent=2))
check(len({row['id'] for row in successes}) == COUNT, 'not all uploads succeeded uniquely')
if __name__ == '__main__':
run(main)