This commit is contained in:
2026-11-22 17:59:11 +03:00
parent 7e1780be67
commit 813fc03da5
18 changed files with 1859 additions and 265 deletions
+446 -169
View File
@@ -1,46 +1,59 @@
"""Separate process: copy the staged original and write one thumbnail.
"""Separate process: publish the staged original and the level-4 variants.
Ack happens only after that result is committed. A kill before ack redelivers the same
job id; the variant primary key keeps the second run from creating a second thumbnail.
Staging is left in place. Removing it is a later step, after the result is known to be safe.
Ack happens only after the ready row is committed. A kill after the object put and
before ack redelivers the same job id; variant primary keys keep a single set.
Staging is removed only after that commit. Failed staging stays until retention so
an operator can still replay.
"""
import asyncio
import hashlib
import logging
import os
import signal
import uuid
from datetime import datetime, timezone
from datetime import datetime, timedelta, timezone
from pathlib import Path
import asyncpg
from .broker import Broker, BrokerDown
from .config import job_max_attempts, job_timeout_seconds, load_broker_url, load_object_settings, load_settings, worker_concurrency
from .db import open_pool
from .jobs import PIPELINE_VERSION, QUEUE, QUEUE_ARGUMENTS, PermanentJobError, TransientJobError, dump_job, load_job, variant_key
from .config import (
effective_lease_seconds,
job_max_attempts,
job_timeout_seconds,
load_broker_url,
load_object_settings,
load_settings,
retry_base_seconds,
retry_cap_seconds,
staging_retention_seconds,
worker_concurrency,
)
from .fault import consume_fault
from .jobs import (
DLQ,
PIPELINE_VERSION,
REQUIRED_VARIANTS,
PermanentJobError,
TransientJobError,
backoff_seconds,
load_job,
lock_key,
variant_key,
)
from .objects import MissingObject, ObjectStore, StorageError
from .thumbnail import ImageRejected, make_thumbnail
from .outbox import due_at, publish_pending, reclaim_expired
from .thumbnail import ImageRejected, render_variants
logger = logging.getLogger('messenger')
_HEARTBEAT = Path('/tmp/worker-alive')
_inflight = 0
_ACK_LOCK = asyncio.Lock()
def _lock_key(attachment_id: uuid.UUID) -> int:
return attachment_id.int & ((1 << 63) - 1)
def _prepare(
objects: ObjectStore,
attachment_id: str,
staging: str,
final: str,
size: int,
digest: str,
content_type: str,
) -> dict:
"""Copy the original unchanged and build the thumbnail. Runs off the event loop."""
def _prepare(objects: ObjectStore, attachment_id: str, staging: str, final: str, size: int, digest: str, content_type: str) -> list:
"""Copy the original unchanged and write every required variant. Runs off the event loop."""
try:
data = objects.get(staging)
except MissingObject:
@@ -55,119 +68,228 @@ def _prepare(
except StorageError:
raise TransientJobError() from None
try:
jpeg, width, height = make_thumbnail(data)
rendered = render_variants(data)
except ImageRejected:
raise PermanentJobError('invalid_image') from None
thumb_key = variant_key(attachment_id, 'thumbnail')
try:
objects.put(thumb_key, jpeg, 'image/jpeg')
except StorageError:
raise TransientJobError() from None
return {
'object_key': thumb_key,
'size_bytes': len(jpeg),
'width': width,
'height': height,
'sha256': hashlib.sha256(jpeg).hexdigest(),
}
except MemoryError:
raise PermanentJobError('invalid_image') from None
if set(rendered) != set(REQUIRED_VARIANTS):
raise PermanentJobError('processing_failed')
stored = []
for name in REQUIRED_VARIANTS:
item = rendered[name]
key = variant_key(attachment_id, name)
blob = item['data']
try:
objects.put(key, blob, str(item['content_type']))
except StorageError:
raise TransientJobError() from None
stored.append({
'name': name,
'content_type': item['content_type'],
'object_key': key,
'size_bytes': len(blob),
'width': int(item['width']),
'height': int(item['height']),
'sha256': hashlib.sha256(blob).hexdigest(),
})
return stored
async def _mark_failed(conn: asyncpg.Connection, attachment_id: uuid.UUID, code: str) -> None:
now = datetime.now(timezone.utc)
async def _record_failure(conn: asyncpg.Connection, job: dict, code: str, permanent: bool) -> None:
await conn.execute(
'''
INSERT INTO attachment_job_failures (job_id, attempt, error_code, permanent, created_at)
VALUES ($1, $2, $3, $4, clock_timestamp())
ON CONFLICT (job_id, attempt, error_code) DO NOTHING
''',
uuid.UUID(job['job_id']),
job['attempt'],
code,
permanent,
)
async def _fail(conn: asyncpg.Connection, broker: Broker, job: dict, attachment_id: uuid.UUID, code: str, permanent: bool) -> None:
"""Terminal state plus the failure registry. The DLQ copy is best-effort after the commit."""
async with conn.transaction():
await conn.execute(
'''
UPDATE attachments
SET status = 'failed', error_code = $2, updated_at = $3
WHERE id = $1 AND status IN ('queued', 'processing')
''',
status = await conn.fetchval(
'SELECT status FROM attachments WHERE id = $1 FOR UPDATE',
attachment_id,
code,
now,
)
async def _schedule_retry(
conn: asyncpg.Connection,
broker: Broker,
job: dict,
attachment_id: uuid.UUID,
limit: int,
) -> None:
"""Advance attempt and publish the next message before the caller acks this one."""
nxt = job['attempt'] + 1
now = datetime.now(timezone.utc)
if nxt > limit:
await _mark_failed(conn, attachment_id, 'retry_exhausted')
return
async with conn.transaction():
moved = await conn.fetchval(
'''
UPDATE attachment_jobs
SET attempt = $2, updated_at = $3
WHERE id = $1 AND attempt = $4
RETURNING attempt
''',
uuid.UUID(job['job_id']),
nxt,
now,
job['attempt'],
)
if moved is None:
if status == 'ready':
return
await conn.execute(
'''
UPDATE attachments
SET status = 'queued', error_code = NULL, updated_at = $2
WHERE id = $1 AND status IN ('queued', 'processing')
SET status = 'failed', error_code = $2, updated_at = clock_timestamp()
WHERE id = $1 AND status = 'processing'
''',
attachment_id,
now,
code,
)
await broker.publish(dump_job(job['job_id'], job['attachment_id'], nxt, job['created_at']))
async def _finish(conn: asyncpg.Connection, attachment_id: uuid.UUID, thumb: dict) -> None:
now = datetime.now(timezone.utc)
async with conn.transaction():
await _record_failure(conn, job, code, permanent)
await conn.execute(
'''
INSERT INTO attachment_variants (
attachment_id, pipeline_version, name, content_type, size_bytes,
width, height, sha256, object_key
)
VALUES ($1, $2, 'thumbnail', 'image/jpeg', $3, $4, $5, $6, $7)
ON CONFLICT (attachment_id, pipeline_version, name) DO UPDATE
SET content_type = EXCLUDED.content_type,
size_bytes = EXCLUDED.size_bytes,
width = EXCLUDED.width,
height = EXCLUDED.height,
sha256 = EXCLUDED.sha256,
object_key = EXCLUDED.object_key
UPDATE attachment_jobs
SET lease_until = NULL, last_error = $2, updated_at = clock_timestamp()
WHERE id = $1
''',
attachment_id,
PIPELINE_VERSION,
thumb['size_bytes'],
thumb['width'],
thumb['height'],
thumb['sha256'],
thumb['object_key'],
uuid.UUID(job['job_id']),
code,
)
try:
await broker.publish(dump_current(job), DLQ, {'x-error-code': code})
except BrokerDown:
logger.warning('job %s recorded as %s; DLQ did not confirm', job['job_id'], code)
def dump_current(job: dict) -> bytes:
from .jobs import dump_job
return dump_job(job['job_id'], job['attachment_id'], job['attempt'], job['created_at'])
async def _schedule_retry(conn: asyncpg.Connection, job: dict, attachment_id: uuid.UUID, limit: int, code: str) -> None:
"""Park the next attempt in the outbox. The current delivery is acked by the caller."""
nxt = job['attempt'] + 1
if nxt > limit:
return False
delay = backoff_seconds(job['attempt'], retry_base_seconds(), retry_cap_seconds())
async with conn.transaction():
moved = await conn.fetchval(
'''
UPDATE attachment_jobs
SET attempt = $2,
runs = 0,
available_at = $3,
published_at = NULL,
lease_until = NULL,
last_error = $4,
updated_at = clock_timestamp()
WHERE id = $1 AND attempt = $5
RETURNING attempt
''',
uuid.UUID(job['job_id']),
nxt,
due_at(delay),
code,
job['attempt'],
)
if moved is None:
return True
await conn.execute(
'''
UPDATE attachments
SET status = 'ready', error_code = NULL, updated_at = $2
WHERE id = $1 AND status IN ('queued', 'processing')
SET status = 'queued', error_code = NULL, updated_at = clock_timestamp()
WHERE id = $1 AND status = 'processing'
''',
attachment_id,
now,
)
logger.info('attachment %s attempt %s will retry in %.3fs (%s)', job['attachment_id'], job['attempt'], delay, code)
return True
async def _process(pool: asyncpg.Pool, objects: ObjectStore, broker: Broker, job: dict, limit: int, timeout: int) -> None:
async def _finish(conn: asyncpg.Connection, attachment_id: uuid.UUID, job_id: uuid.UUID, variants: list) -> bool:
async with conn.transaction():
status = await conn.fetchval(
'SELECT status FROM attachments WHERE id = $1 FOR UPDATE',
attachment_id,
)
if status != 'processing':
return False
for item in variants:
await conn.execute(
'''
INSERT INTO attachment_variants (
attachment_id, pipeline_version, name, content_type, size_bytes,
width, height, sha256, object_key
)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)
ON CONFLICT (attachment_id, pipeline_version, name) DO UPDATE
SET content_type = EXCLUDED.content_type,
size_bytes = EXCLUDED.size_bytes,
width = EXCLUDED.width,
height = EXCLUDED.height,
sha256 = EXCLUDED.sha256,
object_key = EXCLUDED.object_key
''',
attachment_id,
PIPELINE_VERSION,
item['name'],
item['content_type'],
item['size_bytes'],
item['width'],
item['height'],
item['sha256'],
item['object_key'],
)
await conn.execute(
'''
UPDATE attachments
SET status = 'ready', error_code = NULL, updated_at = clock_timestamp()
WHERE id = $1 AND status = 'processing'
''',
attachment_id,
)
await conn.execute(
'''
UPDATE attachment_jobs
SET lease_until = NULL, last_error = NULL, updated_at = clock_timestamp()
WHERE id = $1
''',
job_id,
)
return True
async def _drop_staging(conn: asyncpg.Connection, objects: ObjectStore, attachment_id: uuid.UUID, staging: str, final: str) -> None:
"""Remove staging only after ready is committed and the final object is the copy."""
if not staging or staging == final:
return
try:
await asyncio.to_thread(objects.delete, staging)
except StorageError:
logger.warning('staging left in place for %s', attachment_id)
return
await conn.execute(
'''
UPDATE attachments
SET staging_key = object_key
WHERE id = $1 AND status = 'ready' AND staging_key = $2
''',
attachment_id,
staging,
)
async def _beat_lease(pool: asyncpg.Pool, job_id: uuid.UUID, stop: asyncio.Event, lease_seconds: int) -> None:
interval = max(1.0, lease_seconds / 3)
while not stop.is_set():
try:
async with pool.acquire() as conn:
await conn.execute(
'''
UPDATE attachment_jobs
SET lease_until = $2
WHERE id = $1
''',
job_id,
datetime.now(timezone.utc) + timedelta(seconds=lease_seconds),
)
except Exception:
logger.warning('lease refresh failed')
try:
await asyncio.wait_for(stop.wait(), timeout=interval)
except asyncio.TimeoutError:
pass
async def _process(pool: asyncpg.Pool, objects: ObjectStore, broker: Broker, job: dict, lease_seconds: int, timeout: int) -> None:
attachment_id = uuid.UUID(job['attachment_id'])
job_id = uuid.UUID(job['job_id'])
async with pool.acquire() as conn:
await conn.execute('SELECT pg_advisory_lock($1)', _lock_key(attachment_id))
await conn.execute('SELECT pg_advisory_lock($1)', lock_key(attachment_id))
try:
row = await conn.fetchrow(
'''
@@ -177,66 +299,129 @@ async def _process(pool: asyncpg.Pool, objects: ObjectStore, broker: Broker, job
JOIN attachments a ON a.id = j.attachment_id
WHERE j.id = $1
''',
uuid.UUID(job['job_id']),
job_id,
)
if row is None or row['status'] in ('ready', 'failed'):
return
if job['attempt'] < row['attempt']:
# The previous attempt crashed after the counter moved and before its ack.
await broker.publish(dump_job(job['job_id'], job['attachment_id'], row['attempt'], job['created_at']))
if job['attempt'] != row['attempt']:
# A newer attempt is already in the outbox, or this delivery is stale.
return
if job['attempt'] > row['max_attempts']:
await _mark_failed(conn, attachment_id, 'retry_exhausted')
return
now = datetime.now(timezone.utc)
await conn.execute(
'''
UPDATE attachments
SET status = 'processing', error_code = NULL, updated_at = $2
WHERE id = $1 AND status IN ('queued', 'processing')
''',
attachment_id,
now,
)
try:
thumb = await asyncio.wait_for(
asyncio.to_thread(
_prepare,
objects,
job['attachment_id'],
row['staging_key'],
row['object_key'],
row['size_bytes'],
row['sha256'],
row['content_type'],
),
timeout=timeout,
lease_until = datetime.now(timezone.utc) + timedelta(seconds=lease_seconds)
async with conn.transaction():
runs = await conn.fetchval(
'''
UPDATE attachment_jobs
SET runs = runs + 1, lease_until = $2, updated_at = clock_timestamp()
WHERE id = $1 AND attempt = $3
RETURNING runs
''',
job_id,
lease_until,
job['attempt'],
)
except PermanentJobError as exc:
await _mark_failed(conn, attachment_id, exc.code)
if runs is None:
return
if runs > row['max_attempts']:
await conn.execute(
'''
UPDATE attachments
SET status = 'failed', error_code = 'retry_exhausted', updated_at = clock_timestamp()
WHERE id = $1 AND status IN ('queued', 'processing')
''',
attachment_id,
)
await _record_failure(conn, job, 'retry_exhausted', True)
await conn.execute(
'''
UPDATE attachment_jobs
SET lease_until = NULL, last_error = 'retry_exhausted', updated_at = clock_timestamp()
WHERE id = $1
''',
job_id,
)
exhausted = True
else:
await conn.execute(
'''
UPDATE attachments
SET status = 'processing', error_code = NULL, updated_at = clock_timestamp()
WHERE id = $1 AND status IN ('queued', 'processing')
''',
attachment_id,
)
exhausted = False
if exhausted:
try:
await broker.publish(dump_current(job), DLQ, {'x-error-code': 'retry_exhausted'})
except BrokerDown:
logger.warning('job %s exhausted; DLQ did not confirm', job['job_id'])
return
except (TransientJobError, asyncio.TimeoutError):
await _schedule_retry(conn, broker, job, attachment_id, row['max_attempts'])
return
except Exception:
logger.exception('attachment %s attempt %s failed', job['attachment_id'], job['attempt'])
await _schedule_retry(conn, broker, job, attachment_id, row['max_attempts'])
return
await _finish(conn, attachment_id, thumb)
logger.info('attachment %s ready on attempt %s', job['attachment_id'], job['attempt'])
stop_lease = asyncio.Event()
beat = asyncio.create_task(_beat_lease(pool, job_id, stop_lease, lease_seconds))
try:
try:
if await consume_fault(pool, 'transient-once'):
raise TransientJobError()
if await consume_fault(pool, 'permanent-once'):
raise PermanentJobError('invalid_image')
variants = await asyncio.wait_for(
asyncio.to_thread(
_prepare,
objects,
job['attachment_id'],
row['staging_key'],
row['object_key'],
row['size_bytes'],
row['sha256'],
row['content_type'],
),
timeout=timeout,
)
except PermanentJobError as exc:
await _fail(conn, broker, job, attachment_id, exc.code, True)
return
except TransientJobError:
if not await _schedule_retry(conn, job, attachment_id, row['max_attempts'], 'storage'):
await _fail(conn, broker, job, attachment_id, 'retry_exhausted', True)
return
except asyncio.TimeoutError:
if not await _schedule_retry(conn, job, attachment_id, row['max_attempts'], 'timeout'):
await _fail(conn, broker, job, attachment_id, 'retry_exhausted', True)
return
except Exception as exc:
logger.warning(
'attachment %s attempt %s failed (%s)',
job['attachment_id'],
job['attempt'],
type(exc).__name__,
)
if not await _schedule_retry(conn, job, attachment_id, row['max_attempts'], 'processing_failed'):
await _fail(conn, broker, job, attachment_id, 'retry_exhausted', True)
return
if await consume_fault(pool, 'exit-after-put'):
logger.warning('fault exit-after-put: leaving %s unacked after object put', job['attachment_id'])
logging.shutdown()
os._exit(75)
finished = await _finish(conn, attachment_id, job_id, variants)
if finished:
await _drop_staging(conn, objects, attachment_id, row['staging_key'], row['object_key'])
logger.info('attachment %s ready on attempt %s', job['attachment_id'], job['attempt'])
finally:
stop_lease.set()
beat.cancel()
finally:
await conn.execute('SELECT pg_advisory_unlock($1)', _lock_key(attachment_id))
await conn.execute('SELECT pg_advisory_unlock($1)', lock_key(attachment_id))
async def _handle(pool, objects, broker, body: bytes, limit: int, timeout: int) -> None:
async def _handle(pool, objects, broker, body: bytes, lease_seconds: int, timeout: int) -> None:
job = load_job(body)
if job is None:
logger.warning('dropped a job message that does not match the contract')
return
await _process(pool, objects, broker, job, limit, timeout)
await _process(pool, objects, broker, job, lease_seconds, timeout)
async def _beat(stop: asyncio.Event) -> None:
async def _alive(stop: asyncio.Event) -> None:
while not stop.is_set():
_HEARTBEAT.write_text('ok', encoding='ascii')
try:
@@ -245,9 +430,81 @@ async def _beat(stop: asyncio.Event) -> None:
pass
async def _cleanup_staging(pool: asyncpg.Pool, objects: ObjectStore, retention: int) -> None:
cutoff = datetime.now(timezone.utc) - timedelta(seconds=retention)
async with pool.acquire() as conn:
ready = await conn.fetch(
'''
SELECT id, staging_key, object_key
FROM attachments
WHERE status = 'ready' AND staging_key <> object_key
LIMIT 20
'''
)
failed = await conn.fetch(
'''
SELECT id, staging_key
FROM attachments
WHERE status = 'failed' AND staging_key <> object_key AND updated_at <= $1
LIMIT 20
''',
cutoff,
)
for row in ready:
try:
await asyncio.to_thread(objects.delete, row['staging_key'])
except StorageError:
continue
async with pool.acquire() as conn:
await conn.execute(
'''
UPDATE attachments
SET staging_key = object_key
WHERE id = $1 AND status = 'ready' AND staging_key = $2
''',
row['id'],
row['staging_key'],
)
for row in failed:
async with pool.acquire() as conn:
claimed = await conn.fetchval(
'''
UPDATE attachments
SET staging_key = object_key
WHERE id = $1 AND status = 'failed' AND staging_key = $2 AND updated_at <= $3
RETURNING id
''',
row['id'],
row['staging_key'],
cutoff,
)
if claimed is None:
continue
try:
await asyncio.to_thread(objects.delete, row['staging_key'])
except StorageError:
logger.warning('failed staging %s was unlinked in metadata and is still in the bucket', row['id'])
async def _maintain(pool, broker, objects, stop: asyncio.Event, retention: int) -> None:
ticks = 0
while not stop.is_set():
try:
await publish_pending(pool, broker)
await reclaim_expired(pool)
ticks += 1
if ticks % 30 == 0:
await _cleanup_staging(pool, objects, retention)
except Exception:
logger.exception('worker maintenance failed')
try:
await asyncio.wait_for(stop.wait(), timeout=1)
except asyncio.TimeoutError:
pass
async def _run() -> None:
logging.basicConfig(level=logging.INFO, format='%(levelname)s %(message)s')
# Library logs can include the AMQP URL. Keep them quiet.
logging.getLogger('aio_pika').setLevel(logging.ERROR)
logging.getLogger('aiormq').setLevel(logging.ERROR)
stop = asyncio.Event()
@@ -255,40 +512,52 @@ async def _run() -> None:
for sig in (signal.SIGTERM, signal.SIGINT):
loop.add_signal_handler(sig, stop.set)
settings = load_settings()
limit = job_max_attempts()
# Imported for the side effect of validating the pool settings the API also uses.
load_settings()
job_max_attempts()
timeout = job_timeout_seconds()
pool = await open_pool(settings.database_url)
lease_seconds = effective_lease_seconds()
retention = staging_retention_seconds()
prefetch = worker_concurrency()
pool = await open_pool_from_settings()
objects = ObjectStore(load_object_settings())
broker = Broker(load_broker_url())
beat = asyncio.create_task(_beat(stop))
alive = asyncio.create_task(_alive(stop))
maintain = None
try:
await broker.connect()
channel = broker.channel
if channel is None:
raise RuntimeError('broker did not become reachable')
await channel.set_qos(prefetch_count=worker_concurrency())
queue = await channel.declare_queue(QUEUE, durable=True, arguments=QUEUE_ARGUMENTS)
# consumer_channel stays referenced until this function returns, so it is not closed early.
consumer_channel, queue = await broker.open_consumer(prefetch)
maintain = asyncio.create_task(_maintain(pool, broker, objects, stop, retention))
async def on_message(message) -> None:
global _inflight
_inflight += 1
try:
await _handle(pool, objects, broker, message.body, limit, timeout)
await _handle(pool, objects, broker, message.body, lease_seconds, timeout)
except BrokerDown:
await message.nack(requeue=True)
async with _ACK_LOCK:
await message.nack(requeue=True)
return
except Exception:
logger.exception('job was not finished')
await message.nack(requeue=True)
async with _ACK_LOCK:
await message.nack(requeue=True)
return
else:
await message.ack()
async with _ACK_LOCK:
await message.ack()
finally:
_inflight -= 1
consumer = await queue.consume(on_message)
logger.info('worker consuming %s', queue.name)
logger.info(
'worker consuming %s prefetch %s lease %ss channel %s',
queue.name,
prefetch,
lease_seconds,
id(consumer_channel),
)
await stop.wait()
logger.info('worker draining')
await queue.cancel(consumer)
@@ -297,11 +566,19 @@ async def _run() -> None:
break
await asyncio.sleep(0.05)
finally:
beat.cancel()
alive.cancel()
if maintain is not None:
maintain.cancel()
await broker.close()
await pool.close()
async def open_pool_from_settings():
from .db import open_pool
return await open_pool(load_settings().database_url)
def main() -> None:
asyncio.run(_run())