Реализовать лабораторную 4: вложения в S3 и согласованность с БД

- приватный bucket SeaweedFS за S3-шлюзом, отдельные identities
  admin/api/reconciler, анонимный доступ запрещён
- потоковый upload с проверкой PNG/JPEG (CRC, распаковка со сверкой
  объёма, лимит пикселей до распаковки) без буферизации тела
- скачивание через авторизованный API; компенсация неудачной загрузки:
  сначала pending-строка, затем объект
- reconciler БД ↔ S3 с grace period: stale_pending, orphan_object,
  missing_object, size/checksum mismatch, обратимый карантин lost
- сценарии отказов S3, замер памяти загрузок, трек 2, evidence и REPORT.md
This commit is contained in:
celis
2026-10-31 00:31:54 +03:00
parent ec540a1a72
commit 04458025fb
58 changed files with 4549 additions and 17 deletions
+130
View File
@@ -0,0 +1,130 @@
#!/usr/bin/env python3
"""Трек 2: reconciler --apply с grace 1 с работает каждую секунду параллельно с потоком загрузок через API.
Гипотеза: правила (pending старше grace, объект без строки старше grace, проверка только settled-строк) не трогают
загрузки в процессе и подтверждённые (201) вложения. Проверка: каждое вложение, получившее 201, после теста ready
и скачивается с тем же SHA-256; итоговая сверка без расхождений. Отдельно — заведомо медленная загрузка (дольше grace):
reconciler убирает её pending-строку, клиент получает 503, но ни строки, ни объекта не остаётся.
Запуск: python3 research/reconcile_concurrency.py --base-url http://localhost:8080 [--seconds 25]"""
import collections
import hashlib
import http.client
import json
from pathlib import Path
import subprocess
import sys
import threading
import time
import urllib.parse
import uuid
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tests'))
from client import Client, arguments, check, run # noqa: E402
PNG = (ROOT / 'tests/fixtures/sample.png').read_bytes()
SHA = hashlib.sha256(PNG).hexdigest()
NAME = 'lab4-reconcile-race'
def compose(*args):
r = subprocess.run(['docker', 'compose', *args], cwd=ROOT, text=True, capture_output=True)
check(r.returncode == 0, 'docker compose %s: %s' % (args[0], r.stderr.strip().splitlines()[-1:]))
return r.stdout
def slow_upload(base, token, chat, pieces=10, pause=0.4):
"""Тело отправляется частями ~4 с — заведомо дольше grace (1 с)."""
url = urllib.parse.urlsplit(base)
conn = http.client.HTTPConnection(url.hostname, url.port, timeout=30)
conn.putrequest('POST', '/api/v1/chats/' + chat + '/attachments?filename=slow.png')
conn.putheader('Authorization', 'Bearer ' + token)
conn.putheader('Content-Type', 'image/png')
conn.putheader('Content-Length', str(len(PNG)))
conn.endheaders()
step = len(PNG) // pieces + 1
for i in range(0, len(PNG), step):
conn.send(PNG[i:i + step])
time.sleep(pause)
r = conn.getresponse()
return r.status, json.loads(r.read() or b'{}')
def main():
args = arguments('Reconciler vs concurrent uploads', lambda p: p.add_argument('--seconds', type=int, default=25))
c = Client(args.base_url, args.ca_file, timeout=30)
alice, bob, _, chat = c.bootstrap()
path = '/api/v1/chats/' + chat['id'] + '/attachments?filename=race.png'
send = '/api/v1/chats/' + chat['id'] + '/messages'
compose('stop', 'reconciler')
# Чистая база: остатки прошлых тестов не должны попасть в находки гонки.
compose('run', '--rm', '--no-deps', '-T', 'reconciler', 'node', 'src/main.ts', 'reconcile', '--apply', '--grace=0')
runs = []
proc = subprocess.Popen(['docker', 'compose', 'run', '--rm', '--no-deps', '-T', '--name', NAME, 'reconciler',
'node', 'src/main.ts', 'reconcile', '--apply', '--grace=1', '--every=1'],
cwd=ROOT, text=True, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
reader = threading.Thread(target=lambda: [runs.append(json.loads(x)) for x in proc.stdout if x.startswith('{"mode"')], daemon=True)
reader.start()
try:
deadline = time.monotonic() + 60
while not runs:
check(time.monotonic() < deadline, 'reconciler did not start')
time.sleep(0.2)
created, statuses, stop = [], collections.Counter(), time.monotonic() + args.seconds
lock = threading.Lock()
def worker(n):
local = Client(args.base_url, args.ca_file, timeout=30)
i = 0
while time.monotonic() < stop:
r = local.call('POST', path, [201, 503], actor=alice, raw=PNG, headers={'Content-Type': 'image/png'}, schema='Attachment')
with lock:
statuses[r['status']] += 1
if r['status'] == 201:
att = r['json']
if i % 5 == 0: # часть вложений сразу используется сообщением
local.call('POST', send, 201, actor=alice, body={'text': '', 'attachment_ids': [att['id']]},
headers={'Idempotency-Key': uuid.uuid4().hex})
with lock:
created.append(att)
i += 1
slow = []
threads = [threading.Thread(target=worker, args=(n,)) for n in range(4)]
threads.append(threading.Thread(target=lambda: slow.append(slow_upload(c.base, alice['token'], chat['id']))))
for t in threads:
t.start()
for t in threads:
t.join()
finally:
subprocess.run(['docker', 'stop', NAME], capture_output=True)
proc.wait(timeout=30)
compose('start', 'reconciler')
# Каждое подтверждённое вложение на месте и не изменилось.
for att in created:
meta = c.call('GET', '/api/v1/attachments/' + att['id'], 200, actor=bob, schema='Attachment')['json']
body = c.call('GET', '/api/v1/attachments/' + att['id'] + '/content', 200, actor=bob)['bytes']
check(meta['sha256'] == SHA and hashlib.sha256(body).hexdigest() == SHA, 'confirmed attachment changed')
slow_status, slow_body = slow[0]
left = compose('exec', '-T', 'postgres', 'psql', '-U', 'messenger', '-d', 'messenger', '-tAc',
"SELECT count(*) FROM attachments WHERE chat_id = '%s' AND filename = 'slow.png'" % chat['id']).strip()
final = json.loads(compose('run', '--rm', '--no-deps', '-T', 'reconciler', 'node', 'src/main.ts', 'reconcile', '--grace=0').splitlines()[-1])
findings = collections.Counter()
for r in runs:
findings.update(r.get('findings', {}))
print(json.dumps({
'seconds': args.seconds, 'upload_threads': 4, 'uploads': dict(statuses), 'confirmed_and_verified': len(created),
'reconciler_runs': len(runs), 'run_ms_max': max(r['duration_ms'] for r in runs), 'findings_during_race': dict(findings),
'slow_upload': {'status': slow_status, 'code': slow_body.get('error', {}).get('code'), 'rows_left': int(left)},
'final_check_grace0': final['findings'],
}, ensure_ascii=False))
check(statuses[503] == 0 and len(created) > 100 and len(runs) >= 5, 'too few uploads or reconciler runs')
check(set(findings) <= {'stale_pending', 'orphan_object'} and findings['stale_pending'] <= 1, 'reconciler touched regular uploads')
check(slow_status == 503 and left == '0', 'slow upload must fail cleanly')
check(not final['findings'], 'stores inconsistent after race')
print('PASS: %d confirmed uploads intact after %d reconciler --apply runs (grace 1 s); slow upload > grace failed cleanly'
% (len(created), len(runs)))
if __name__ == '__main__':
run(main)