Реализовать асинхронную обработку изображений

This commit is contained in:
Nik
2026-11-05 20:34:10 +03:00
parent 276dbdad8a
commit 35371114cd
28 changed files with 1968 additions and 45 deletions
+51
View File
@@ -0,0 +1,51 @@
"""Negative checks for upload validation and chat-scoped access."""
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('http://localhost:8080')
alice, bob, eve, chat = client.bootstrap()
sample = (Path(__file__).parents[1] / 'tests/fixtures/sample.png').read_bytes()
attachment = client.call(
'POST', '/api/v1/chats/' + chat['id'] + '/attachments?filename=sample.png',
202, actor=alice, raw=sample,
headers={'Content-Type': 'image/png'}, schema='Attachment',
)['json']
attachment_id = attachment['id']
client.call(
'POST', '/api/v1/chats/' + chat['id'] + '/attachments?filename=broken.png',
415, actor=alice, raw=b'not an image',
headers={'Content-Type': 'image/png'},
)
client.call(
'POST', '/api/v1/chats/' + chat['id'] + '/attachments?filename=wrong.jpg',
415, actor=alice, raw=sample,
headers={'Content-Type': 'image/jpeg'},
)
client.call(
'POST', '/api/v1/chats/' + chat['id'] + '/attachments?filename=large.png',
413, actor=alice, raw=b'0' * (10 * 1024 * 1024 + 1),
headers={'Content-Type': 'image/png'},
)
client.call('GET', '/api/v1/attachments/' + attachment_id, 404, actor=eve)
client.call('GET', '/api/v1/attachments/' + attachment_id + '/content', 404, actor=eve)
other_chat = client.call(
'POST', '/api/v1/chats', 201, actor=alice,
body={'title': 'Другой чат', 'member_ids': [alice['id'], eve['id']]}, schema='Chat',
)['json']
client.message(alice, other_chat, 'без чужого вложения')
response = client.call(
'POST', '/api/v1/chats/' + other_chat['id'] + '/messages', 404, actor=alice,
body={'text': '', 'attachment_ids': [attachment_id]},
headers={'Idempotency-Key': 'foreign-attachment-check'},
)
check(response['status'] == 404, 'foreign attachment was accepted')
print('PASS: attachment validation and chat-scoped access')
if __name__ == '__main__':
main()
+37
View File
@@ -0,0 +1,37 @@
#!/usr/bin/env python3
"""Проверка общего Idempotency-Key через обе API-реплики."""
import sys
import uuid
from concurrent.futures import ThreadPoolExecutor
sys.path.insert(0, 'tests')
from client import Client, check
def main():
client = Client('http://localhost:8080')
alice, _, _, chat = client.bootstrap()
key = 'student-' + uuid.uuid4().hex
body = {'text': 'одно сообщение при восьми повторах'}
def send(_):
return client.call(
'POST', '/api/v1/chats/' + chat['id'] + '/messages', 201,
actor=alice, body=body,
headers={'Idempotency-Key': key}, schema='Message',
)
with ThreadPoolExecutor(max_workers=8) as pool:
responses = list(pool.map(send, range(8)))
ids = {item['json']['id'] for item in responses}
check(len(ids) == 1, 'concurrent retries created more than one message')
client.call(
'POST', '/api/v1/chats/' + chat['id'] + '/messages', 409,
actor=alice, body={'text': 'другой текст'},
headers={'Idempotency-Key': key},
)
print('PASS: concurrent idempotency, one message id:', next(iter(ids)))
if __name__ == '__main__':
main()
+44
View File
@@ -0,0 +1,44 @@
"""Show that a committed job survives while the worker/broker publisher is stopped."""
import subprocess
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).parents[1] / 'tests'))
from client import Client, check
def compose(*args):
subprocess.run(['docker', 'compose', *args], check=True, stdout=subprocess.DEVNULL)
def outbox_is_pending(attachment_id):
code = """import os,sys,psycopg
with psycopg.connect(os.environ['DATABASE_URL']) as c:
print(c.execute("SELECT count(*) FROM attachment_jobs j JOIN attachments a ON a.id=j.attachment_id WHERE a.id=%s AND j.published_at IS NULL", (sys.argv[1],)).fetchone()[0])"""
result = subprocess.run(
['docker', 'compose', 'exec', '-T', 'api-1', 'python', '-c', code, str(attachment_id)],
check=True, text=True, capture_output=True,
)
return result.stdout.strip().endswith('1')
def main():
client = Client('http://localhost:8080')
alice, bob, _, chat = client.bootstrap()
data = (Path(__file__).parents[1] / 'tests/fixtures/sample.png').read_bytes()
compose('stop', 'worker')
try:
attachment = client.call(
'POST', '/api/v1/chats/' + chat['id'] + '/attachments?filename=outbox.png',
202, actor=alice, raw=data, headers={'Content-Type': 'image/png'}, schema='Attachment',
)['json']
check(outbox_is_pending(attachment['id']), 'outbox intent was not durable')
finally:
compose('up', '-d', 'worker')
ready = client.wait_ready(bob, attachment)
check(ready['status'] == 'ready', 'outbox job was not published after worker restart')
print('PASS: committed outbox intent survived worker stop and reached ready')
if __name__ == '__main__':
main()
+30
View File
@@ -0,0 +1,30 @@
"""Ten concurrent bounded uploads for a small local memory check."""
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
import sys
import uuid
sys.path.insert(0, str(Path(__file__).parents[1] / 'tests'))
from client import Client, check
def main():
client = Client('http://localhost:8080')
alice, _, _, chat = client.bootstrap()
data = (Path(__file__).parents[1] / 'tests/fixtures/sample.png').read_bytes()
def upload(number):
return client.call(
'POST', '/api/v1/chats/' + chat['id'] + '/attachments?filename=load-' + str(number) + '.png',
202, actor=alice, raw=data,
headers={'Content-Type': 'image/png'}, schema='Attachment',
)
with ThreadPoolExecutor(max_workers=10) as pool:
results = list(pool.map(upload, range(10)))
check(len(results) == 10, 'not all uploads completed')
print('PASS: 10 concurrent uploads, bytes per upload:', len(data))
if __name__ == '__main__':
main()
+36
View File
@@ -0,0 +1,36 @@
"""Check all level-4 image variants and their metadata."""
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('http://localhost:8080')
alice, bob, _, chat = client.bootstrap()
data = (Path(__file__).parents[1] / 'tests/fixtures/sample.png').read_bytes()
attachment = client.call(
'POST', '/api/v1/chats/' + chat['id'] + '/attachments?filename=variants.png',
202, actor=alice, raw=data, headers={'Content-Type': 'image/png'}, schema='Attachment',
)['json']
ready = client.wait_ready(bob, attachment)
variants = {item['name']: item for item in ready['variants']}
check(set(variants) == {'thumbnail', 'crop', 'optimized'}, 'not all variants are ready')
check((variants['thumbnail']['width'], variants['thumbnail']['height']) == (256, 160), 'thumbnail size')
check((variants['crop']['width'], variants['crop']['height']) == (128, 128), 'crop size')
check(variants['optimized']['content_type'] == 'image/webp', 'optimized format')
for name, meta in variants.items():
response = client.call(
'GET', '/api/v1/attachments/' + attachment['id'] + '/content?variant=' + name,
200, actor=bob,
)
check(response['headers'].get_content_type() == meta['content_type'], name + ' content type')
check(len(response['bytes']) == meta['size_bytes'], name + ' size')
check(hashlib.sha256(response['bytes']).hexdigest() == meta['sha256'], name + ' checksum')
print('PASS: thumbnail, crop and optimized variants')
if __name__ == '__main__':
main()
+55
View File
@@ -0,0 +1,55 @@
"""Inject a pause after DB ready and before broker ack, then restart the worker."""
import subprocess
import sys
import time
from pathlib import Path
sys.path.insert(0, str(Path(__file__).parents[1] / 'tests'))
from client import Client, check
TEST_CONTAINER = 'mtusi2026lab5-ack-test'
def run(*args, capture=False):
return subprocess.run(['docker', 'compose', *args], check=True, text=True,
capture_output=capture)
def cleanup_test_container():
subprocess.run(['docker', 'rm', '-f', TEST_CONTAINER], check=False,
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
def main():
client = Client('http://localhost:8080')
alice, bob, _, chat = client.bootstrap()
data = (Path(__file__).parents[1] / 'tests/fixtures/sample.png').read_bytes()
run('stop', 'worker')
cleanup_test_container()
run('run', '--no-deps', '-d', '--name', TEST_CONTAINER, '-e', 'ACK_DELAY_SECONDS=60', 'worker')
try:
attachment = client.call(
'POST', '/api/v1/chats/' + chat['id'] + '/attachments?filename=ack-window.png',
202, actor=alice, raw=data, headers={'Content-Type': 'image/png'}, schema='Attachment',
)['json']
deadline = time.monotonic() + 60
while time.monotonic() < deadline:
state = client.call('GET', '/api/v1/attachments/' + attachment['id'], actor=bob, schema='Attachment')['json']
if state['status'] == 'ready':
break
time.sleep(0.2)
else:
raise AssertionError('attachment did not reach ready during ack pause')
time.sleep(2)
subprocess.run(['docker', 'stop', TEST_CONTAINER], check=True, stdout=subprocess.DEVNULL)
finally:
cleanup_test_container()
run('up', '-d', 'worker')
ready = client.wait_ready(bob, attachment)
check(len(ready['variants']) == 3, 'redelivery changed the variant set')
print('PASS: redelivery after ready-before-ack kept one result set')
if __name__ == '__main__':
main()
+44
View File
@@ -0,0 +1,44 @@
"""Worker stop/start scenario for the durable staging and broker path."""
import subprocess
import sys
import time
import uuid
from pathlib import Path
sys.path.insert(0, str(Path(__file__).parents[1] / 'tests'))
from client import Client, check
def compose(*args):
subprocess.run(['docker', 'compose', *args], check=True, stdout=subprocess.DEVNULL)
def main():
client = Client('http://localhost:8080')
alice, bob, _, chat = client.bootstrap()
data = (Path(__file__).parents[1] / 'tests/fixtures/sample.png').read_bytes()
compose('stop', 'worker')
try:
attachment = client.call(
'POST', '/api/v1/chats/' + chat['id'] + '/attachments?filename=stopped.png',
202, actor=alice, raw=data, headers={'Content-Type': 'image/png'}, schema='Attachment',
)['json']
client.message(alice, chat, '', attachments=[attachment['id']])
client.call(
'GET', '/api/v1/attachments/' + attachment['id'] + '/content',
409, actor=bob,
)
finally:
compose('up', '-d', 'worker')
ready = client.wait_ready(bob, attachment)
check(ready['status'] == 'ready', 'worker did not finish queued job')
content = client.call(
'GET', '/api/v1/attachments/' + attachment['id'] + '/content?variant=thumbnail',
200, actor=bob,
)
check(content['headers'].get_content_type() == 'image/jpeg', 'thumbnail is not JPEG')
print('PASS: upload survived stopped worker and reached ready after restart')
if __name__ == '__main__':
main()