forked from mtusi2026/mtusi2026lab5
lab5: очередь RabbitMQ, outbox, worker, варианты, fault-injection
This commit is contained in:
Executable
+156
@@ -0,0 +1,156 @@
|
||||
"""Общие помощники собственных тестов lab4: изображения, docker compose, psql, mc.
|
||||
|
||||
Только stdlib. Секреты не печатаются: mc получает их внутри контейнера из /run/secrets.
|
||||
"""
|
||||
import struct
|
||||
import subprocess
|
||||
import sys
|
||||
import zlib
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / 'tests')) # публичный client.py
|
||||
FIXTURES = Path(__file__).resolve().parent / 'fixtures'
|
||||
BUCKET = 'messenger-attachments'
|
||||
|
||||
|
||||
def chunk(typ, data):
|
||||
return struct.pack('>I', len(data)) + typ + data + struct.pack('>I', zlib.crc32(typ + data) & 0xffffffff)
|
||||
|
||||
|
||||
def png(w, h, raw=None, color_type=2, interlace=0, level=6):
|
||||
"""PNG из сырых строк; по умолчанию RGB 8 bit, все пиксели чёрные."""
|
||||
if raw is None:
|
||||
raw = (b'\x00' + b'\x00' * (w * 3)) * h
|
||||
ihdr = struct.pack('>IIBBBBB', w, h, 8, color_type, 0, 0, interlace)
|
||||
return (b'\x89PNG\r\n\x1a\n' + chunk(b'IHDR', ihdr) + chunk(b'IDAT', zlib.compress(raw, level))
|
||||
+ chunk(b'IEND', b''))
|
||||
|
||||
|
||||
def noise_png(target_bytes):
|
||||
"""Почти несжимаемый PNG размером около target_bytes (шум из детерминированного PRNG)."""
|
||||
w = 1024
|
||||
h = max(1, target_bytes // (w * 3 + 1))
|
||||
seed = 0x2545F491
|
||||
rows = bytearray()
|
||||
for _ in range(h):
|
||||
rows.append(0)
|
||||
row = bytearray(w * 3)
|
||||
for i in range(0, w * 3, 4):
|
||||
seed = (seed * 1103515245 + 12345) & 0xffffffff
|
||||
row[i:i + 4] = seed.to_bytes(4, 'little')[:len(row) - i]
|
||||
rows += row
|
||||
return png(w, h, bytes(rows), level=1)
|
||||
|
||||
|
||||
def bomb_png(w=100_000, h=100_000):
|
||||
"""Маленький файл, огромные размеры в IHDR."""
|
||||
return png(w, h, raw=b'\x00')
|
||||
|
||||
|
||||
def raw_post(base_url, path, headers, body_iter, read_timeout=30):
|
||||
"""POST на сыром сокете: тело отправляется в фоне, ответ читается параллельно.
|
||||
|
||||
Нужен, когда сервер отвечает (413) до чтения тела и закрывает соединение:
|
||||
urllib в этом случае падает на отправке, не увидев ответа.
|
||||
Возвращает (status, body_bytes) или (None, b'') если ответа не было.
|
||||
"""
|
||||
import socket
|
||||
import threading
|
||||
from urllib.parse import urlsplit
|
||||
u = urlsplit(base_url)
|
||||
s = socket.create_connection((u.hostname, u.port or 80), timeout=read_timeout)
|
||||
head = 'POST %s HTTP/1.1\r\nHost: %s\r\nConnection: close\r\n' % (path, u.netloc)
|
||||
head += ''.join('%s: %s\r\n' % kv for kv in headers.items()) + '\r\n'
|
||||
s.sendall(head.encode())
|
||||
|
||||
def send():
|
||||
try:
|
||||
for part in body_iter:
|
||||
s.sendall(part)
|
||||
except OSError:
|
||||
pass # сервер уже ответил и закрыл соединение — ожидаемо
|
||||
t = threading.Thread(target=send, daemon=True)
|
||||
t.start()
|
||||
data = b''
|
||||
try:
|
||||
while True:
|
||||
b = s.recv(65536)
|
||||
if not b:
|
||||
break
|
||||
data += b
|
||||
if b'\r\n\r\n' in data and len(data) > 4096:
|
||||
break
|
||||
except OSError:
|
||||
pass
|
||||
finally:
|
||||
s.close()
|
||||
if not data.startswith(b'HTTP/1.'):
|
||||
return None, b''
|
||||
status = int(data.split(b' ', 2)[1])
|
||||
return status, data.split(b'\r\n\r\n', 1)[-1]
|
||||
|
||||
|
||||
def fixture(name):
|
||||
return (FIXTURES / name).read_bytes()
|
||||
|
||||
|
||||
def sh(*args, check=True, timeout=300, input=None, env=None):
|
||||
full_env = None
|
||||
if env:
|
||||
import os
|
||||
full_env = dict(os.environ, **env)
|
||||
r = subprocess.run(list(args), cwd=ROOT, capture_output=True, text=True, timeout=timeout, input=input, env=full_env)
|
||||
if check and r.returncode != 0:
|
||||
raise RuntimeError('%s failed (%d): %s' % (' '.join(args[:4]), r.returncode, (r.stderr or r.stdout)[-800:]))
|
||||
return r
|
||||
|
||||
|
||||
def compose(*args, **kw):
|
||||
return sh('docker', 'compose', *args, **kw)
|
||||
|
||||
|
||||
def psql(sql):
|
||||
"""Одно значение/таблица из PostgreSQL стенда (через docker compose exec)."""
|
||||
return compose('exec', '-T', 'postgres', 'psql', '-U', 'messenger', '-d', 'messenger',
|
||||
'-v', 'ON_ERROR_STOP=1', '-tAc', sql).stdout.strip()
|
||||
|
||||
|
||||
def mc(script, check=True, as_user='root'):
|
||||
"""Скрипт mc в одноразовом контейнере s3-init. Алиас `s3` — root или API-пользователь."""
|
||||
creds = {'root': ('s3_root_user', 's3_root_password'),
|
||||
'api': ('s3_access_key_id', 's3_secret_access_key')}[as_user]
|
||||
prelude = ('mc alias set s3 http://s3:9000 "$(cat /run/secrets/%s)" "$(cat /run/secrets/%s)" >/dev/null; '
|
||||
% creds)
|
||||
return compose('run', '--rm', '--no-deps', '-T', '--entrypoint', 'sh', 's3-init', '-c', prelude + script,
|
||||
check=check)
|
||||
|
||||
|
||||
def api_container(instance_id):
|
||||
for cid in compose('ps', '-q', 'api').stdout.split():
|
||||
if cid.startswith(instance_id):
|
||||
return cid
|
||||
raise RuntimeError('no api container for ' + instance_id)
|
||||
|
||||
|
||||
def object_key(attachment_id):
|
||||
return psql("SELECT object_key FROM attachments WHERE id = '%s'" % attachment_id)
|
||||
|
||||
|
||||
def wait_status(c, actor, att_id, statuses=('ready',), timeout=90):
|
||||
"""Опрос GET метаданных до одного из статусов; возвращает метаданные."""
|
||||
import time
|
||||
from client import Failure
|
||||
end = time.time() + timeout
|
||||
last = None
|
||||
while time.time() < end:
|
||||
last = c.call('GET', '/api/v1/attachments/' + att_id, actor=actor, schema='Attachment')['json']
|
||||
if last['status'] in statuses:
|
||||
return last
|
||||
time.sleep(0.5)
|
||||
raise Failure('attachment %s did not reach %s, last=%s' % (att_id, statuses, last and last['status']))
|
||||
|
||||
|
||||
def bucket_count(prefix):
|
||||
"""Число объектов под префиксом bucket (s/, o/, v/, a/ + chat)."""
|
||||
return int(mc('mc ls --recursive s3/%s/%s 2>/dev/null | wc -l' % (BUCKET, prefix)).stdout.strip() or 0)
|
||||
Reference in New Issue
Block a user