Исправить скачивание JPEG и добавить таймаут и DLQ

This commit is contained in:
Nik
2026-11-25 16:39:03 +03:00
parent d193e6c857
commit 0bb5c18d4b
10 changed files with 368 additions and 147 deletions
+31
View File
@@ -0,0 +1,31 @@
"""A valid JPEG must survive upload and download without any byte changes."""
import hashlib
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).parents[1] / 'tests'))
from client import Client, check
def main():
client = Client()
alice, bob, _, chat = client.bootstrap()
original = Path(__file__).with_name('sample.jpg').read_bytes()
attachment = client.call(
'POST', '/api/v1/chats/' + chat['id'] + '/attachments?filename=sample.jpg',
202, actor=alice, raw=original, headers={'Content-Type': 'image/jpeg'},
schema='Attachment',
)['json']
check(attachment['status'] == 'queued', 'JPEG upload must start queued')
ready = client.wait_ready(bob, attachment)
result = client.call(
'GET', '/api/v1/attachments/' + ready['id'] + '/content', 200, actor=bob,
)
check(result['headers'].get_content_type() == 'image/jpeg', 'JPEG content type changed')
check(result['bytes'] == original, 'JPEG original bytes changed')
check(ready['sha256'] == hashlib.sha256(original).hexdigest(), 'JPEG checksum mismatch')
print('PASS: JPEG upload 202 -> ready -> original 200, bytes and SHA-256 match')
if __name__ == '__main__':
main()
Binary file not shown.

After

Width:  |  Height:  |  Size: 644 B

+103
View File
@@ -0,0 +1,103 @@
"""Force two timeouts, verify durable DLQ delivery, then replay the attachment."""
import json
import subprocess
import sys
import time
from pathlib import Path
from uuid import uuid4
sys.path.insert(0, str(Path(__file__).parents[1] / 'tests'))
from client import Client, check
def compose(*args):
result = subprocess.run(
['docker', 'compose', *args], check=True, text=True, stdout=subprocess.PIPE,
)
return result.stdout.strip()
def dead_letters(attachment_id):
records = json.loads(compose(
'exec', '-T', 'broker', 'redis-cli', '--json', 'XRANGE', 'attachment-jobs-dlq', '-', '+',
))
events = [dict(zip(fields[::2], fields[1::2])) for _, fields in records]
return [event for event in events if event.get('attachment_id') == attachment_id]
def wait_for(check_state, seconds=25):
deadline = time.monotonic() + seconds
while time.monotonic() < deadline:
result = check_state()
if result:
return result
time.sleep(0.2)
raise AssertionError('timed out waiting for the expected state')
def main():
client = Client()
alice, bob, _, chat = client.bootstrap()
container = 'lab5-timeout-' + uuid4().hex[:8]
compose('stop', 'worker')
try:
compose(
'run', '--no-deps', '--rm', '-d', '--name', container,
'-e', 'JOB_TIMEOUT_SECONDS=2', '-e', 'MAX_JOB_ATTEMPTS=2',
'-e', 'LAB5_TEST_PROCESS_DELAY_SECONDS=60', 'worker',
)
started = time.monotonic()
attachment, original = client.attachment(alice, chat)
other, _ = client.attachment(alice, chat)
attachment_id = attachment['id']
path = '/api/v1/attachments/' + attachment_id
events = wait_for(lambda: dead_letters(attachment_id))
check(len(events) == 1, 'expected exactly one event in the DLQ')
event = events[0]
check(event['attempt'] == '2', 'timeout did not retry before the final failure')
check(event['error_code'] == 'retry_exhausted', 'unexpected terminal error')
check(event['last_error'] == 'processing_timeout', 'deadline did not stop processing')
other_events = wait_for(lambda: dead_letters(other['id']))
check(len(other_events) == 1, 'each failed job needs its own DLQ entry')
check(other_events[0]['event_id'] != event['event_id'], 'DLQ event ID was reused')
state = client.call('GET', path, actor=bob, schema='Attachment')['json']
check(state['status'] == 'failed', 'terminal error did not reach the API')
client.call('GET', path + '/content', 409, actor=bob)
alive = subprocess.check_output(
['docker', 'inspect', '--format', '{{.State.Running}} {{.RestartCount}}', container],
text=True,
).strip()
check(alive == 'true 0', 'worker restarted instead of handling the timeout')
print(f'PASS: two attempts per job, two failed jobs, two DLQ events in {time.monotonic() - started:.1f}s')
finally:
subprocess.run(['docker', 'stop', '--time', '1', container], check=False, capture_output=True)
compose('up', '-d', '--no-deps', 'worker')
compose('restart', 'broker')
compose('up', '-d', '--wait', '--no-deps', 'broker')
check(dead_letters(attachment_id) == events, 'DLQ did not survive broker restart')
# Repeat the PostgreSQL outbox delivery as if Redis accepted XADD before
# the publisher recorded its success in PostgreSQL.
compose('exec', '-T', 'worker', 'python', '-c', """
import sys
sys.path.insert(0, 'scripts')
from worker import connect, publish_outbox
with connect() as connection:
connection.execute(
'UPDATE attachment_jobs SET published_at=NULL WHERE attachment_id=%s',
(sys.argv[1],),
)
publish_outbox(sys.argv[1])
""", attachment_id)
check(dead_letters(attachment_id) == events, 'outbox redelivery duplicated a DLQ event')
replay = json.loads(compose('exec', '-T', 'worker', 'python', 'scripts/replay_failed.py', attachment_id))
check(replay['job_id'] == event['job_id'], 'replay replaced the logical job')
client.wait_ready(bob, attachment)
downloaded = client.call('GET', path + '/content', actor=bob)
check(downloaded['bytes'] == original, 'replayed original changed')
check(dead_letters(attachment_id) == events, 'replay changed the original DLQ event')
print('PASS: DLQ survived broker restart and explicit replay reached ready')
if __name__ == '__main__':
main()