157 lines
8.8 KiB
Python
157 lines
8.8 KiB
Python
"""Usage (стенд запущен через docker compose up -d):
|
||
python student-tests/consistency_check.py
|
||
|
||
Проверяет, что сбои при загрузке не оставляют вечных неучтённых данных:
|
||
1) клиент обрывает загрузку посреди тела → ни строки, ни объекта;
|
||
2) S3 остановлен → upload/download 503, ни строки, ни объекта; метаданные, текст и ready работают;
|
||
3) процесс «падает» после S3 PUT до COMMIT ready (FAULTS=after_s3_put, только в этом тесте) →
|
||
остаётся строка uploading + объект; сверщик не трогает их в пределах grace и убирает после;
|
||
4) объект без строки в БД (orphan) → свежий не трогается, старый удаляется; повторный запуск ничего не делает;
|
||
5) периодический сервис reconciler сам удаляет заготовку старше grace (без ручного запуска).
|
||
"""
|
||
import json
|
||
import os
|
||
import socket
|
||
import time
|
||
import urllib.parse
|
||
import uuid
|
||
|
||
from helpers import BASE_URL, call, compose, new_chat, new_user, sql, wait_ready
|
||
from imagegen import SAMPLE_PNG
|
||
from test_attachments import download, upload
|
||
|
||
failures = []
|
||
|
||
|
||
def check(title, ok, detail=''):
|
||
print(' %-62s %s %s' % (title, 'OK' if ok else 'FAIL', detail))
|
||
if not ok:
|
||
failures.append(title)
|
||
|
||
|
||
def reconcile(*args):
|
||
return json.loads(compose('run', '--rm', 'reconcile', *args))
|
||
|
||
|
||
def s3_python(code):
|
||
return compose('run', '--rm', '--entrypoint', 'python', 'reconcile', '-c',
|
||
'import sys; sys.path.insert(0, "src")\n' + code)
|
||
|
||
|
||
def counts():
|
||
return sql("SELECT count(*) FILTER (WHERE status = 'ready') || '/' || count(*) FILTER (WHERE status = 'uploading') "
|
||
"FROM attachments")
|
||
|
||
|
||
def object_exists(key):
|
||
return s3_python('from config import setting, settings\nfrom s3 import make_client\n'
|
||
'c = make_client(setting("S3_RECONCILER_ACCESS_KEY_ID"), setting("S3_RECONCILER_SECRET_ACCESS_KEY"))\n'
|
||
'keys = [o["Key"] for o in c.list_objects_v2(Bucket=settings.s3_bucket, Prefix=%r).get("Contents", [])]\n'
|
||
'print(len(keys))' % key).strip() == '1'
|
||
|
||
|
||
def restart_api(faults=None):
|
||
env = dict(os.environ)
|
||
env['FAULTS'] = faults or ''
|
||
compose('up', '-d', '--no-deps', '--no-build', 'api', env=env)
|
||
time.sleep(3)
|
||
wait_ready()
|
||
time.sleep(3)
|
||
|
||
|
||
def interrupted_upload(alice, chat):
|
||
target = urllib.parse.urlsplit(BASE_URL)
|
||
with socket.create_connection((target.hostname, target.port), timeout=10) as sock:
|
||
head = ('POST /api/v1/chats/%s/attachments?filename=cut.png HTTP/1.1\r\nHost: x\r\n'
|
||
'Authorization: Bearer %s\r\nContent-Type: image/png\r\nContent-Length: %d\r\n\r\n'
|
||
% (chat['id'], alice['token'], 5 * 1024 * 1024))
|
||
sock.sendall(head.encode() + SAMPLE_PNG + bytes(512 * 1024))
|
||
time.sleep(2)
|
||
|
||
|
||
def main():
|
||
alice = new_user('consistency')
|
||
chat = new_chat(alice)
|
||
|
||
print('1. Обрыв загрузки посреди тела')
|
||
before = counts()
|
||
interrupted_upload(alice, chat)
|
||
check('строк не прибавилось (ready/uploading)', counts() == before, '%s -> %s' % (before, counts()))
|
||
|
||
print('2. S3 остановлен: загрузка, скачивание, остальной API')
|
||
stored = upload(alice, chat, SAMPLE_PNG)[2]
|
||
before = counts()
|
||
compose('stop', 's3')
|
||
try:
|
||
started = time.monotonic()
|
||
status = upload(alice, chat, SAMPLE_PNG)[0]
|
||
check('upload при остановленном S3 → 503', status == 503, '%s за %.1f с' % (status, time.monotonic() - started))
|
||
check('заготовка удалена компенсацией', counts() == before, '%s -> %s' % (before, counts()))
|
||
started = time.monotonic()
|
||
status = download(alice, stored['id'])[0]
|
||
check('download при остановленном S3 → 503', status == 503, '%s за %.1f с' % (status, time.monotonic() - started))
|
||
check('метаданные вложения доступны (они в PostgreSQL)',
|
||
call('GET', '/api/v1/attachments/' + stored['id'], token=alice['token'])[0] == 200)
|
||
check('текстовое сообщение → 201', call('POST', '/api/v1/chats/%s/messages' % chat['id'],
|
||
{'text': 'без S3'}, alice['token'])[0] == 201)
|
||
check('/health/ready → 200 (S3 не критичен для текстового API)', call('GET', '/health/ready')[0] == 200)
|
||
finally:
|
||
compose('up', '-d', '--wait', 's3')
|
||
check('после старта S3 upload снова 201', upload(alice, chat, SAMPLE_PNG)[0] == 201)
|
||
|
||
print('3. Сбой после S3 PUT до фиксации ready (FAULTS=after_s3_put)')
|
||
restart_api('after_s3_put')
|
||
try:
|
||
status = upload(alice, chat, SAMPLE_PNG, filename='fault-%s.png' % uuid.uuid4().hex[:6])[0]
|
||
row = sql("SELECT id || ' ' || object_key FROM attachments WHERE status = 'uploading' "
|
||
"AND filename LIKE 'fault-%%' ORDER BY created_at DESC LIMIT 1").split()
|
||
check('клиент получил ошибку (не 201)', status != 201, str(status))
|
||
check('осталась строка uploading и объект в S3', bool(row) and object_exists(row[1]), ' '.join(row))
|
||
finally:
|
||
restart_api()
|
||
fresh = reconcile('--grace-seconds', '900')
|
||
check('dry-run, grace 900 с: заготовка свежая, не трогается', fresh['counts']['fresh_upload'] >= 1
|
||
and fresh['counts']['stale_upload'] == 0, str(fresh['counts']))
|
||
applied = reconcile('--apply', '--grace-seconds', '0')
|
||
check('apply, grace 0: строка и объект удалены', applied['actions']['stale_rows_deleted'] >= 1
|
||
and applied['actions']['stale_objects_deleted'] >= 1, str(applied['actions']))
|
||
check('объекта больше нет', not object_exists(row[1]))
|
||
|
||
print('4. Объект без строки в БД (orphan)')
|
||
key = 'attachments/%s' % uuid.uuid4()
|
||
s3_python('from config import setting, settings\nfrom s3 import make_client\n'
|
||
'c = make_client(setting("S3_RECONCILER_ACCESS_KEY_ID"), setting("S3_RECONCILER_SECRET_ACCESS_KEY"))\n'
|
||
'c.put_object(Bucket=settings.s3_bucket, Key=%r, Body=b"orphan")' % key)
|
||
fresh = reconcile('--grace-seconds', '900')
|
||
check('dry-run, grace 900 с: свежая сирота не трогается', fresh['counts']['fresh_orphan'] >= 1
|
||
and fresh['counts']['orphan'] == 0, str(fresh['counts']))
|
||
applied = reconcile('--apply', '--grace-seconds', '0')
|
||
check('apply, grace 0: сирота удалена', applied['actions']['orphan_objects_deleted'] >= 1, str(applied['actions']))
|
||
again = reconcile('--apply', '--grace-seconds', '0')
|
||
check('повторный запуск ничего не делает', not any(again['actions'][k] for k in
|
||
('orphan_objects_deleted', 'stale_rows_deleted', 'stale_objects_deleted')), str(again['actions']))
|
||
check('рабочие вложения не пострадали (missing = 0)', again['counts']['missing'] == 0, str(again['counts']))
|
||
|
||
print('5. Периодический сервис reconciler убирает зависшую заготовку сам')
|
||
stale = str(uuid.uuid4())
|
||
sql("INSERT INTO attachments (id, chat_id, owner_id, filename, content_type, size_bytes, sha256, object_key, "
|
||
"status, created_at, updated_at) VALUES ('%s', '%s', '%s', 'stale.png', 'image/png', 1, "
|
||
"decode(repeat('00', 32), 'hex'), 'attachments/%s', 'uploading', now() - interval '1 hour', "
|
||
"now() - interval '1 hour')" % (stale, chat['id'], alice['id'], stale))
|
||
running = 'reconciler' in compose('ps', '--status', 'running', '--services')
|
||
check('сервис reconciler запущен (docker compose ps)', running)
|
||
if running:
|
||
compose('restart', 'reconciler') # проход выполняется сразу после старта, дальше — раз в интервал
|
||
deadline = time.monotonic() + 60
|
||
while time.monotonic() < deadline and sql("SELECT count(*) FROM attachments WHERE id = '%s'" % stale) != '0':
|
||
time.sleep(1)
|
||
check('заготовка старше grace удалена без ручного запуска',
|
||
sql("SELECT count(*) FROM attachments WHERE id = '%s'" % stale) == '0')
|
||
|
||
print('FAIL: ' + ', '.join(failures) if failures else 'PASS: сбои загрузки не оставляют неучтённых данных')
|
||
raise SystemExit(1 if failures else 0)
|
||
|
||
|
||
if __name__ == '__main__':
|
||
main()
|