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

This commit is contained in:
2026-11-17 18:21:09 +03:00
parent 4d54ba3848
commit e8becaf761
51 changed files with 2234 additions and 58 deletions
+3 -2
View File
@@ -22,12 +22,13 @@ def main():
uploaded = client.call(
'POST',
f'/api/v1/chats/{chat["id"]}/attachments?filename=failover.png',
201,
202,
actor=alice,
raw=content,
headers={'Content-Type': 'image/png'},
schema='Attachment',
)
ready = client.wait_ready(bob, uploaded['json'])
target = uploaded['headers']['X-Instance-Id']
env = dict(os.environ)
env['TARGET_INSTANCE_ID'] = target
@@ -40,7 +41,7 @@ def main():
try:
downloaded = client.call(
'GET',
f'/api/v1/attachments/{uploaded["json"]["id"]}/content',
f'/api/v1/attachments/{ready["id"]}/content',
actor=bob,
)
if downloaded['headers']['X-Instance-Id'] != target:
+47
View File
@@ -0,0 +1,47 @@
#!/usr/bin/env python3
"""A persistent broker volume keeps a confirmed job across broker restart."""
import os
from pathlib import Path
import subprocess
import time
from client import Client, arguments, check, run
def executable(value):
path = Path(value).resolve()
check(path.is_file() and os.access(path, os.X_OK), str(path) + ': not executable')
return path
def main():
def configure(parser):
parser.add_argument('--stop-worker-script', required=True)
parser.add_argument('--restart-broker-script', required=True)
parser.add_argument('--start-worker-script', required=True)
args = arguments('RabbitMQ persistent delivery after restart', configure)
stop_worker = executable(args.stop_worker_script)
restart_broker = executable(args.restart_broker_script)
start_worker = executable(args.start_worker_script)
client = Client(args.base_url, args.ca_file)
alice, bob, _eve, chat = client.bootstrap()
subprocess.run([str(stop_worker)], check=True)
attachment, original = client.attachment(alice, chat)
time.sleep(2)
queued = client.call(
'GET', f'/api/v1/attachments/{attachment["id"]}', actor=bob, schema='Attachment'
)['json']
check(queued['status'] == 'queued', 'worker processed job while expected stopped')
subprocess.run([str(restart_broker)], check=True)
subprocess.run([str(start_worker)], check=True)
client.wait_ready(bob, attachment)
downloaded = client.call(
'GET', f'/api/v1/attachments/{attachment["id"]}/content', actor=bob
)['bytes']
check(downloaded == original, 'job/original lost across broker restart')
print('PASS: confirmed durable message survived broker restart with its volume')
if __name__ == '__main__':
run(main)
+58
View File
@@ -0,0 +1,58 @@
#!/usr/bin/env python3
"""Prove permanent failure, DLQ routing and guarded operator replay."""
import os
from pathlib import Path
import subprocess
import time
from client import Client, arguments, check, run
def executable(value):
path = Path(value).resolve()
check(path.is_file() and os.access(path, os.X_OK), str(path) + ': not executable')
return path
def main():
def configure(parser):
parser.add_argument('--stop-worker-script', required=True)
parser.add_argument('--crash-worker-script', required=True)
parser.add_argument('--replay-script', required=True)
args = arguments('Failed registry, DLQ and guarded replay', configure)
stop = executable(args.stop_worker_script)
crash = executable(args.crash_worker_script)
replay = executable(args.replay_script)
client = Client(args.base_url, args.ca_file)
alice, bob, _eve, chat = client.bootstrap()
subprocess.run([str(stop)], check=True)
attachment, original = client.attachment(alice, chat)
subprocess.run([str(crash), 'permanent'], check=True)
deadline = time.monotonic() + 20
while True:
failed = client.call(
'GET', f'/api/v1/attachments/{attachment["id"]}', actor=bob,
schema='Attachment',
)['json']
if failed['status'] == 'failed':
break
check(time.monotonic() < deadline, 'attachment did not reach failed')
time.sleep(0.2)
check(failed['error_code'] == 'fault_injected', 'unsafe or unexpected error code')
subprocess.run([str(replay), attachment['id']], check=True)
ready = client.wait_ready(bob, attachment)
check(len(ready['variants']) == 3, 'replay produced incomplete variants')
content = client.call(
'GET', f'/api/v1/attachments/{attachment["id"]}/content', actor=bob
)['bytes']
check(content == original, 'replay changed original')
duplicate = subprocess.run([str(replay), attachment['id']], check=False)
check(duplicate.returncode != 0, 'ready job was replayed again')
print('PASS: permanent failure reached failed/DLQ and guarded replay reached ready')
if __name__ == '__main__':
run(main)
+36
View File
@@ -0,0 +1,36 @@
#!/usr/bin/env python3
"""Prove that a committed outbox survives publisher downtime."""
import os
from pathlib import Path
import subprocess
import time
from client import Client, arguments, check, run
def main():
def configure(parser):
parser.add_argument('--stop-publisher-script', required=True)
parser.add_argument('--start-publisher-script', required=True)
args = arguments('Transactional outbox recovery', configure)
stop = Path(args.stop_publisher_script).resolve()
start = Path(args.start_publisher_script).resolve()
check(all(path.is_file() and os.access(path, os.X_OK) for path in (stop, start)), 'scripts must be executable')
client = Client(args.base_url, args.ca_file)
alice, bob, _eve, chat = client.bootstrap()
subprocess.run([str(stop)], check=True)
attachment, _content = client.attachment(alice, chat)
time.sleep(1)
queued = client.call(
'GET', f'/api/v1/attachments/{attachment["id"]}', actor=bob, schema='Attachment'
)['json']
check(queued['status'] == 'queued', 'job escaped outbox while publisher was stopped')
subprocess.run([str(start)], check=True)
ready = client.wait_ready(bob, attachment)
check(ready['status'] == 'ready', 'outbox did not recover committed job')
print('PASS: COMMIT-before-publish recovered without a new upload')
if __name__ == '__main__':
run(main)
+45
View File
@@ -0,0 +1,45 @@
#!/usr/bin/env python3
"""Grade-4 black-box check for every promised image variant."""
import hashlib
from client import Client, arguments, check, run
from image_probe import jpeg_size
def main():
args = arguments('Verify thumbnail, crop and optimized variants')
client = Client(args.base_url, args.ca_file)
alice, bob, _eve, chat = client.bootstrap()
attachment, original = client.attachment(alice, chat)
ready = client.wait_ready(bob, attachment)
variants = {item['name']: item for item in ready['variants']}
check(set(variants) == {'thumbnail', 'crop', 'optimized'}, 'grade-4 variants missing')
expected = {
'thumbnail': ('image/jpeg', (256, 160)),
'crop': ('image/jpeg', (128, 128)),
'optimized': ('image/webp', (320, 200)),
}
for name, (content_type, dimensions) in expected.items():
response = client.call(
'GET',
f'/api/v1/attachments/{ready["id"]}/content?variant={name}',
actor=bob,
)
metadata = variants[name]
check(response['headers'].get_content_type() == content_type, name + ': MIME mismatch')
check((metadata['width'], metadata['height']) == dimensions, name + ': metadata dimensions')
check(len(response['bytes']) == metadata['size_bytes'], name + ': size mismatch')
check(hashlib.sha256(response['bytes']).hexdigest() == metadata['sha256'], name + ': hash mismatch')
if content_type == 'image/jpeg':
check(jpeg_size(response['bytes']) == dimensions, name + ': actual dimensions')
else:
check(response['bytes'][:4] == b'RIFF' and response['bytes'][8:12] == b'WEBP', 'optimized is not WebP')
downloaded = client.call(
'GET', f'/api/v1/attachments/{ready["id"]}/content', actor=bob
)['bytes']
check(downloaded == original, 'original bytes changed')
print('PASS: original plus thumbnail/crop/optimized variants are valid')
if __name__ == '__main__':
run(main)
+36
View File
@@ -0,0 +1,36 @@
#!/usr/bin/env python3
"""Crash after publisher confirm creates a harmless duplicate delivery."""
import os
from pathlib import Path
import subprocess
from client import Client, arguments, check, run
def executable(value):
path = Path(value).resolve()
check(path.is_file() and os.access(path, os.X_OK), str(path) + ': not executable')
return path
def main():
def configure(parser):
parser.add_argument('--stop-publisher-script', required=True)
parser.add_argument('--crash-publisher-script', required=True)
args = arguments('Crash after publisher confirm', configure)
stop = executable(args.stop_publisher_script)
crash = executable(args.crash_publisher_script)
client = Client(args.base_url, args.ca_file)
alice, bob, _eve, chat = client.bootstrap()
subprocess.run([str(stop)], check=True)
attachment, _original = client.attachment(alice, chat)
subprocess.run([str(crash)], check=True)
ready = client.wait_ready(bob, attachment)
names = [item['name'] for item in ready['variants']]
check(sorted(names) == ['crop', 'optimized', 'thumbnail'], 'duplicate or missing variants')
print('PASS: confirm-before-outbox-mark duplicate produced one logical result')
if __name__ == '__main__':
run(main)
+2 -2
View File
@@ -16,7 +16,7 @@ def scenario():
return client, alice, bob, eve, chat
def upload(client, actor, chat, content, *, filename='sample.png', content_type='image/png', expected=201):
def upload(client, actor, chat, content, *, filename='sample.png', content_type='image/png', expected=202):
return client.call(
'POST',
f'/api/v1/chats/{chat["id"]}/attachments?filename={quote(filename, safe="")}',
@@ -24,7 +24,7 @@ def upload(client, actor, chat, content, *, filename='sample.png', content_type=
actor=actor,
raw=content,
headers={'Content-Type': content_type},
schema='Attachment' if expected == 201 else None,
schema='Attachment' if expected == 202 else None,
)
+89
View File
@@ -0,0 +1,89 @@
from __future__ import annotations
import hashlib
from io import BytesIO
import pytest
from PIL import Image
from app.jobs.pipeline import PermanentImageError, process_image
def encoded(width: int, height: int, mode: str = 'RGBA') -> bytes:
image = Image.new(mode, (width, height), (20, 80, 160, 128) if mode == 'RGBA' else 'navy')
output = BytesIO()
image.save(output, 'PNG', pnginfo=None)
return output.getvalue()
def run(source: bytes):
return process_image(
source,
'image/png',
hashlib.sha256(source).hexdigest(),
40_000_000,
85,
85,
82,
)
def test_pipeline_creates_all_grade4_variants() -> None:
"""Create every grade-4 variant with the required format, size and checksum."""
variants = {item.name: item for item in run(encoded(320, 200))}
assert set(variants) == {'thumbnail', 'crop', 'optimized'}
assert (variants['thumbnail'].width, variants['thumbnail'].height) == (256, 160)
assert variants['thumbnail'].content_type == 'image/jpeg'
assert (variants['crop'].width, variants['crop'].height) == (128, 128)
assert variants['crop'].content_type == 'image/jpeg'
assert (variants['optimized'].width, variants['optimized'].height) == (320, 200)
assert variants['optimized'].content_type == 'image/webp'
for item in variants.values():
assert hashlib.sha256(item.content).hexdigest() == item.sha256
def test_thumbnail_and_optimized_do_not_upscale_small_image() -> None:
"""Keep small images at source size except for the required 128x128 crop."""
variants = {item.name: item for item in run(encoded(40, 20, 'RGB'))}
assert (variants['thumbnail'].width, variants['thumbnail'].height) == (40, 20)
assert (variants['optimized'].width, variants['optimized'].height) == (40, 20)
assert (variants['crop'].width, variants['crop'].height) == (128, 128)
def test_jpeg_variants_composite_alpha_on_white() -> None:
"""Flatten transparent input before encoding JPEG variants without an alpha channel."""
variants = {item.name: item for item in run(encoded(2, 2))}
with Image.open(BytesIO(variants['thumbnail'].content)) as image:
assert image.mode == 'RGB'
def test_checksum_mismatch_is_permanent() -> None:
"""Reject changed staging bytes as a permanent checksum error."""
source = encoded(20, 20)
with pytest.raises(PermanentImageError, match='checksum_mismatch'):
process_image(source, 'image/png', '0' * 64, 40_000_000, 85, 85, 82)
def test_exif_orientation_is_applied_and_removed() -> None:
"""Apply EXIF orientation before resizing and omit metadata from generated output."""
image = Image.new('RGB', (320, 200), 'red')
exif = Image.Exif()
exif[274] = 6
output = BytesIO()
image.save(output, 'JPEG', exif=exif)
source = output.getvalue()
variants = {
item.name: item
for item in process_image(
source,
'image/jpeg',
hashlib.sha256(source).hexdigest(),
40_000_000,
85,
85,
82,
)
}
assert (variants['thumbnail'].width, variants['thumbnail'].height) == (160, 256)
with Image.open(BytesIO(variants['thumbnail'].content)) as transformed:
assert not transformed.getexif()
+41
View File
@@ -0,0 +1,41 @@
#!/usr/bin/env python3
"""Fault injection around S3 effects, DB commit and broker ack."""
import os
from pathlib import Path
import subprocess
from client import Client, arguments, check, run
def executable(value):
path = Path(value).resolve()
check(path.is_file() and os.access(path, os.X_OK), str(path) + ': not executable')
return path
def main():
def configure(parser):
parser.add_argument('--stop-worker-script', required=True)
parser.add_argument('--crash-worker-script', required=True)
parser.add_argument('--mode', choices=('objects', 'commit'), required=True)
args = arguments('Worker crash around durable effects', configure)
stop = executable(args.stop_worker_script)
crash = executable(args.crash_worker_script)
client = Client(args.base_url, args.ca_file)
alice, bob, _eve, chat = client.bootstrap()
subprocess.run([str(stop)], check=True)
attachment, original = client.attachment(alice, chat)
subprocess.run([str(crash), args.mode], check=True)
ready = client.wait_ready(bob, attachment)
names = sorted(item['name'] for item in ready['variants'])
check(names == ['crop', 'optimized', 'thumbnail'], 'duplicate or missing variants')
downloaded = client.call(
'GET', f'/api/v1/attachments/{attachment["id"]}/content', actor=bob
)['bytes']
check(downloaded == original, 'original changed after crash recovery')
print('PASS: worker crash mode=%s recovered one logical result' % args.mode)
if __name__ == '__main__':
run(main)
+61
View File
@@ -0,0 +1,61 @@
#!/usr/bin/env python3
"""Required scenario: accepted work survives worker and API downtime."""
import os
from pathlib import Path
import subprocess
import time
from client import Client, arguments, check, run
def executable(value):
path = Path(value).expanduser().resolve()
check(path.is_file() and os.access(path, os.X_OK), str(path) + ': not executable')
return path
def main():
def configure(parser):
parser.add_argument('--stop-worker-script', required=True)
parser.add_argument('--restart-api-script', required=True)
parser.add_argument('--start-worker-script', required=True)
args = arguments('Worker outage and durable accepted job', configure)
stop_worker = executable(args.stop_worker_script)
restart_api = executable(args.restart_api_script)
start_worker = executable(args.start_worker_script)
client = Client(args.base_url, args.ca_file)
alice, bob, _eve, chat = client.bootstrap()
subprocess.run([str(stop_worker)], check=True)
attachment, original = client.attachment(alice, chat)
message = client.message(alice, chat, '', attachments=[attachment['id']])['json']
check(message['attachment_ids'] == [attachment['id']], 'queued attachment was not linkable')
time.sleep(1)
client.call(
'GET', f'/api/v1/attachments/{attachment["id"]}/content', 409, actor=bob
)
subprocess.run([str(restart_api)], check=True)
deadline = time.monotonic() + 60
while True:
try:
client.call('GET', '/health/ready', schema='Health')
break
except Exception:
check(time.monotonic() < deadline, 'API did not recover after restart')
time.sleep(0.3)
persisted = client.call(
'GET', f'/api/v1/attachments/{attachment["id"]}', actor=bob, schema='Attachment'
)['json']
check(persisted['status'] in {'queued', 'processing'}, 'accepted job disappeared after API restart')
subprocess.run([str(start_worker)], check=True)
ready = client.wait_ready(bob, attachment)
downloaded = client.call(
'GET', f'/api/v1/attachments/{attachment["id"]}/content', actor=bob
)['bytes']
check(downloaded == original, 'original changed after worker recovery')
check(ready['status'] == 'ready', 'job did not become ready')
print('PASS: worker stopped -> 202 -> message -> API restart -> worker -> ready')
if __name__ == '__main__':
run(main)