included rabbitmq as broker

This commit is contained in:
2026-11-10 07:01:17 +03:00
parent 0a70358829
commit 2b9fb3f375
49 changed files with 3072 additions and 287 deletions
+32 -8
View File
@@ -1,4 +1,4 @@
"""Lab4: API и транзакции с реальной БД; байты S3 подменены управляемым адаптером."""
"""Lab5: API и транзакции с реальной БД; байты S3 подменены управляемым адаптером."""
import asyncio
import hashlib
@@ -17,6 +17,10 @@ from sqlalchemy.ext.asyncio import AsyncSession
from starlette.requests import ClientDisconnect
from app.core.s3 import S3Settings
from app.core.jobs import JobSettings
from app.domain.attachment_jobs import process_attachment_job
from app.models.job import AttachmentJob
from app.schemas.job import JobMessage
from app.domain import attachments as domain
from app.errors.exceptions import unavailable
from app.models.attachment import Attachment, UploadIntent
@@ -79,14 +83,31 @@ async def upload(client, actor, chat, data=PNG, filename='фото.png', content
)
async def finish_attachment(client, storage, actor, attachment_id):
engine = client._transport.app.state.engine
async with AsyncSession(engine) as session:
job = await session.scalar(select(AttachmentJob).where(AttachmentJob.attachment_id == UUID(attachment_id)))
message = JobMessage(job_id=job.id, attachment_id=job.attachment_id,
pipeline_version=job.pipeline_version, attempt=job.attempt + 1, created_at=job.created_at)
await session.rollback()
assert await process_attachment_job(session, storage, message, JobSettings(_env_file=None))
result = await client.get(f'/api/v1/attachments/{attachment_id}', headers=bearer(actor))
assert result.json()['status'] == 'ready'
return result.json()
async def test_upload_download_and_attachment_only_message(client, context):
storage, alice, bob, eve, chat = context
response = await upload(client, alice, chat)
assert response.status_code == 201, response.text
assert response.status_code == 202, response.text
attachment = response.json()
assert attachment['status'] == 'ready'
assert attachment['status'] == 'queued'
before = await client.get(f"/api/v1/attachments/{attachment['id']}/content", headers=bearer(alice))
assert before.status_code == 409
attachment = await finish_attachment(client, storage, alice, attachment['id'])
assert attachment['sha256'] == hashlib.sha256(PNG).hexdigest()
assert attachment['variants'] == [] and attachment['error_code'] is None
assert {v['name'] for v in attachment['variants']} == {'thumbnail', 'crop', 'optimized'}
assert attachment['error_code'] is None
assert 'object_key' not in attachment
id = attachment['id']
for actor in (alice, bob):
@@ -120,13 +141,14 @@ async def test_invalid_image_and_mime_are_415(client, context, data, content_typ
async def test_jpeg_is_stored_without_reencoding(client, context):
_, alice, _, _, chat = context
storage, alice, _, _, chat = context
output = BytesIO()
Image.new('RGB', (32, 32), 'blue').save(output, format='JPEG')
original = output.getvalue()
response = await upload(client, alice, chat, original, content_type='image/jpeg')
assert response.status_code == 201, response.text
assert response.status_code == 202, response.text
id = response.json()['id']
await finish_attachment(client, storage, alice, id)
downloaded = await client.get(f'/api/v1/attachments/{id}/content', headers=bearer(alice))
assert downloaded.content == original
@@ -167,7 +189,7 @@ async def test_exact_byte_limit_accepts_valid_png(client, context):
padding = struct.pack('!I', len(payload)) + kind + payload + struct.pack('!I', zlib.crc32(kind + payload))
image = PNG[:-12] + padding + PNG[-12:]
response = await upload(client, alice, chat, image)
assert response.status_code == 201, response.text
assert response.status_code == 202, response.text
assert response.json()['size_bytes'] == maximum
assert response.json()['sha256'] == hashlib.sha256(image).hexdigest()
@@ -178,7 +200,7 @@ async def test_exact_pixel_limit_accepts_valid_png(client, context):
with Image.new('RGB', (8000, 5000), 'blue') as image:
image.save(output, format='PNG')
response = await upload(client, alice, chat, output.getvalue())
assert response.status_code == 201, response.text
assert response.status_code == 202, response.text
async def test_pixel_limit_before_decoding(client, context):
@@ -226,6 +248,7 @@ async def test_empty_ids_and_absent_ids_have_same_idempotency(client, context):
async def test_s3_outage_is_503(client, context):
storage, alice, _, _, chat = context
id = (await upload(client, alice, chat)).json()['id']
await finish_attachment(client, storage, alice, id)
storage.down = True
response = await client.get(f'/api/v1/attachments/{id}/content', headers=bearer(alice))
assert response.status_code == 503
@@ -353,6 +376,7 @@ async def test_cancelled_put_is_compensated(client, context, db_engine, monkeypa
async def test_cleanup_never_deletes_ready_attachment(client, context, db_engine):
storage, alice, _, _, chat = context
id = (await upload(client, alice, chat)).json()['id']
await finish_attachment(client, storage, alice, id)
async with AsyncSession(db_engine) as session:
attachment = await session.get(Attachment, UUID(id))
key = attachment.object_key
+71
View File
@@ -0,0 +1,71 @@
"""Реальные преобразования и OS-лимиты дочернего процесса worker."""
import asyncio
from io import BytesIO
import os
from pathlib import Path
import subprocess
import sys
from uuid import uuid4
from PIL import Image
import pytest
from app.core.image_processing import ImageSettings
from app.domain.image_pipeline import create_variants
from app.domain.job_files import render_variants
from app.storage.jobs import JobWork
from test_attachments import MemoryStorage
@pytest.mark.parametrize('size,transparent', [((1600,800),False),((24,12),True)])
async def test_variant_geometry_metadata_and_alpha(tmp_path,size,transparent):
source=tmp_path/'source.png'
with Image.new('RGBA',size,(255,0,0,0 if transparent else 255)) as image:
exif=Image.Exif();exif[270]='private description'
image.save(source,format='PNG',exif=exif)
result=create_variants(source,tmp_path,'image/png',40_000_000,ImageSettings(_env_file=None))
variants={v.name:v for v in result.variants}
assert (variants['crop'].width,variants['crop'].height)==(128,128)
assert (variants['thumbnail'].width,variants['thumbnail'].height)==((256,128) if size[0]>256 else size)
assert (variants['optimized'].width,variants['optimized'].height)==((1280,640) if size[0]>1280 else size)
for name in ('thumbnail.jpg','crop.jpg','optimized.webp'):
with Image.open(tmp_path/name) as image:
assert not image.getexif() and not image.info.get('icc_profile') and not image.info.get('xmp')
if transparent:
if name.endswith('webp'):assert image.getpixel((0,0))[3]==0
else:assert min(image.getpixel((0,0)))>=250
async def test_exif_orientation_applied(tmp_path):
source=tmp_path/'source.jpg'
with Image.new('RGB',(400,200),'blue') as image:
exif=Image.Exif();exif[274]=6
image.save(source,exif=exif)
result=create_variants(source,tmp_path,'image/jpeg',40_000_000,ImageSettings(_env_file=None))
assert (result.variants[0].width,result.variants[0].height)==(128,256)
@pytest.mark.parametrize('failure', ['memory','cpu'])
async def test_worker_os_limits(failure,tmp_path):
body='return bytearray(2 * 1024 ** 3)' if failure=='memory' else 'while True: pass'
code="from app.core import thumbnail_worker as w\ndef fail(*args):\n "+body+"\nw.create_variants=fail\nraise SystemExit(w.main())"
result=await asyncio.to_thread(subprocess.run,[sys.executable,'-c',code,'source',str(tmp_path),str(tmp_path/'metadata'),'image/png','40000000'],
env={**os.environ,'IMAGE_MEMORY_MIB':'256','IMAGE_CPU_SECONDS':'1'},capture_output=True,timeout=15)
assert result.returncode==(3 if failure=='memory' else -9)
assert not (tmp_path/'metadata').exists()
async def test_render_timeout_kills_child(monkeypatch,tmp_path):
create=asyncio.create_subprocess_exec
children=[]
async def slow_child(*args,**kwargs):
child=await create(sys.executable,'-c','import time;time.sleep(60)',**kwargs)
children.append(child)
return child
monkeypatch.setattr(asyncio,'create_subprocess_exec',slow_child)
work=JobWork(uuid4(),uuid4(),uuid4(),1,'staging/test','image/png',1,'0'*64)
with pytest.raises(TimeoutError):
async with asyncio.timeout(.2):
await render_variants(MemoryStorage(),work,tmp_path/'source',tmp_path)
assert len(children)==1 and children[0].returncode is not None
+178
View File
@@ -0,0 +1,178 @@
"""Lab5: retry/replay, fencing, cleanup, limits и транзакции реального PostgreSQL."""
import asyncio
from datetime import timedelta
import errno
from pathlib import Path
from tempfile import TemporaryDirectory
from uuid import UUID, uuid4
import pytest
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.jobs import JobSettings
from app.domain import attachment_jobs
from app.domain.attachment_jobs import claim_job, process_attachment_job, cleanup_staging, build_result
from app.domain.job_admin import replay_failed_job
from app.domain.job_retry import classify_failure, retry_delay
from app.errors.exceptions import JobOperationError, ProcessingError
from app.models.attachment import Attachment
from app.models.job import AttachmentJob
from app.models.job_replay import JobReplay
from app.schemas.job import JobMessage
from app.storage import jobs
from test_attachments import context, upload, finish_attachment
async def envelope(session, attachment_id):
job = await session.scalar(select(AttachmentJob).where(AttachmentJob.attachment_id == UUID(attachment_id)))
return JobMessage(job_id=job.id, attachment_id=job.attachment_id, pipeline_version=1,
attempt=job.attempt + 1, created_at=job.created_at)
async def test_retry_budget_backoff_replay_and_duplicate(client, context, db_engine):
storage, alice, _, _, chat = context
attachment = (await upload(client, alice, chat)).json()
settings = JobSettings(_env_file=None, job_max_attempts=3)
def fail(_):
raise TimeoutError
async with AsyncSession(db_engine, expire_on_commit=False) as session:
first = await envelope(session, attachment['id'])
for attempt in range(1, 4):
message = await envelope(session, attachment['id'])
assert await process_attachment_job(session, storage, message, settings, before_processing=fail)
job, item = await jobs.lock_job(session, first.job_id)
assert job.attempt == attempt
delay = (job.next_attempt_at - item.updated_at).total_seconds()
assert 5 * 2 ** (attempt - 1) / 2 <= delay <= 5 * 2 ** (attempt - 1)
assert item.status == ('failed' if attempt == 3 else 'queued')
assert job.last_error_permanent is False
job.next_attempt_at = await jobs.database_time(session) - timedelta(seconds=1)
await session.commit()
assert item.error_code == 'retry_exhausted'
request_id = uuid4()
result = await replay_failed_job(session, storage, settings, first.job_id, request_id=request_id,
actor='test', reason='dependency_restored')
assert result['attempt_limit'] == 6
# Old envelope cannot consume the fresh replay budget.
assert await process_attachment_job(session, storage, first, settings)
job, item = await jobs.lock_job(session, first.job_id)
assert job.attempt == 3 and item.status == 'queued'
await session.commit()
message = await envelope(session, attachment['id'])
assert await process_attachment_job(session, storage, message, settings)
before = dict(storage.objects)
assert await process_attachment_job(session, storage, message, settings)
assert storage.objects == before
repeat = await replay_failed_job(session, storage, settings, first.job_id, request_id=request_id,
actor='test', reason='dependency_restored')
assert repeat['already_applied']
with pytest.raises(JobOperationError, match='job_not_failed'):
await replay_failed_job(session, storage, settings, first.job_id, request_id=uuid4(), actor='test', reason='manual_review')
await session.rollback()
assert len((await session.scalars(select(JobReplay))).all()) == 1
async def test_permanent_failure_and_missing_source_replay(client, context, db_engine):
storage, alice, _, _, chat = context
attachment = (await upload(client, alice, chat)).json()
def fail(_):
raise ProcessingError('image_limits')
settings = JobSettings(_env_file=None)
async with AsyncSession(db_engine, expire_on_commit=False) as session:
message = await envelope(session, attachment['id'])
await process_attachment_job(session, storage, message, settings, before_processing=fail)
job, item = await jobs.lock_job(session, message.job_id)
assert item.status == 'failed' and job.attempt == 1 and job.last_error_permanent
job.staging_key = None
await session.commit()
with pytest.raises(JobOperationError, match='source_expired'):
await replay_failed_job(session, storage, settings, job.id, request_id=uuid4(), actor='test', reason='manual_review')
async def test_stale_worker_cannot_write_and_cleanup_keeps_active(client, context, db_engine):
storage, alice, _, _, chat = context
attachment = (await upload(client, alice, chat)).json()
settings = JobSettings(_env_file=None)
async with AsyncSession(db_engine, expire_on_commit=False) as session:
message = await envelope(session, attachment['id'])
claim = await claim_job(session, message, settings)
job, item = await jobs.lock_job(session, message.job_id)
job.lease_token = uuid4()
job.finished_at = await jobs.database_time(session) - timedelta(days=10)
await session.commit()
assert await cleanup_staging(session, storage, settings, apply=True) == 0
# Rendering must not be allowed to PUT on a stale lease.
before = dict(storage.objects)
assert await build_result(session, storage, claim.work)
assert storage.objects == before
async def test_cleanup_ready_preserves_final_objects(client, context, db_engine):
storage, alice, _, _, chat = context
attachment = (await upload(client, alice, chat)).json()
await finish_attachment(client, storage, alice, attachment['id'])
async with AsyncSession(db_engine, expire_on_commit=False) as session:
message = await envelope(session, attachment['id'])
job, item = await jobs.lock_job(session, message.job_id)
staging = job.staging_key
job.finished_at = await jobs.database_time(session) - timedelta(days=2)
await session.commit()
assert await cleanup_staging(session, storage, JobSettings(_env_file=None), apply=False) == 1
assert staging in storage.objects
assert await cleanup_staging(session, storage, JobSettings(_env_file=None), apply=True) == 1
assert staging not in storage.objects and len(storage.objects) == 4
assert await cleanup_staging(session, storage, JobSettings(_env_file=None), apply=True) == 0
async def test_retry_classification_and_cap():
settings = JobSettings(_env_file=None)
for attempt in (1, 2, 6, 100):
cap = min(120, 5 * 2 ** min(30, attempt - 1))
assert all(cap / 2 <= retry_delay(settings, attempt) <= cap for _ in range(100))
assert classify_failure(TimeoutError()) == ('processing_timeout', False)
assert classify_failure(OSError(errno.EACCES, 'denied'))[1]
assert not classify_failure(OSError(errno.ENOSPC, 'full'))[1]
async def test_timeout_records_retry_and_clears_lease(client, context, db_engine, monkeypatch):
storage, alice, _, _, chat = context
attachment = (await upload(client, alice, chat)).json()
async def stalled(*args, **kwargs):
await asyncio.sleep(60)
monkeypatch.setattr(attachment_jobs, 'build_result', stalled)
settings = JobSettings(_env_file=None).model_copy(update={'job_timeout_seconds': .05})
async with AsyncSession(db_engine, expire_on_commit=False) as session:
message = await envelope(session, attachment['id'])
assert await process_attachment_job(session, storage, message, settings)
job, item = await jobs.lock_job(session, message.job_id)
assert item.status == 'queued' and job.last_error_code == 'processing_timeout'
assert job.lease_token is None and job.lease_until is None
async def test_failed_retention_and_source_checksum_protect_replay(client, context, db_engine):
storage, alice, _, _, chat = context
attachment = (await upload(client, alice, chat)).json()
def fail(_):
raise ProcessingError('invalid_image')
settings = JobSettings(_env_file=None)
async with AsyncSession(db_engine, expire_on_commit=False) as session:
message = await envelope(session, attachment['id'])
await process_attachment_job(session, storage, message, settings, before_processing=fail)
job, item = await jobs.lock_job(session, message.job_id)
key = job.staging_key
job.finished_at = await jobs.database_time(session) - timedelta(days=2)
await session.commit()
assert await cleanup_staging(session, storage, settings, apply=True) == 0
data, metadata = storage.objects[key]
storage.objects[key] = (b'x' * len(data), metadata)
with pytest.raises(JobOperationError, match='source_mismatch'):
await replay_failed_job(session, storage, settings, message.job_id, request_id=uuid4(), actor='test', reason='manual_review')
await session.rollback()
assert not (await session.scalars(select(JobReplay))).all()
job, item = await jobs.lock_job(session, message.job_id)
job.finished_at = await jobs.database_time(session) - timedelta(days=8)
await session.commit()
assert await cleanup_staging(session, storage, settings, apply=True) == 1
assert key not in storage.objects
+1 -1
View File
@@ -8,7 +8,7 @@ from sqlalchemy import inspect, text
from app.models import Base
from conftest import reset_schema, upgrade_head
EXPECTED_TABLES = {"users", "chats", "chat_members", "messages", "counters", "idempotency_keys", "attachments", "message_attachments", "upload_intents"}
EXPECTED_TABLES = {"users", "chats", "chat_members", "messages", "counters", "idempotency_keys", "attachments", "message_attachments", "upload_intents", "attachment_jobs", "job_replays"}
@pytest.fixture