forked from mtusi2026/mtusi2026lab7
123 lines
5.0 KiB
Python
123 lines
5.0 KiB
Python
"""Bounded consumers, one unacknowledged message per consumer, hard process timeout."""
|
|
import json
|
|
import logging
|
|
import os
|
|
import subprocess
|
|
import sys
|
|
import time
|
|
from concurrent.futures import ThreadPoolExecutor
|
|
from uuid import uuid4
|
|
|
|
from sqlalchemy.orm import sessionmaker
|
|
|
|
from .database import create_db_engine
|
|
from .jobs import GROUP, STREAM, LEASE_SECONDS, TIMEOUT, broker, claim, ensure_group, record_failure
|
|
from .models import Attachment, AttachmentJob
|
|
from . import telemetry as otel
|
|
|
|
|
|
def handle(sessions, client, message_id, fields):
|
|
try:
|
|
message = json.loads(fields['job'])
|
|
if not isinstance(message, dict):
|
|
raise ValueError('invalid envelope')
|
|
except (ValueError, KeyError, TypeError):
|
|
otel.event('invalid_job')
|
|
acknowledge(client, message_id)
|
|
return
|
|
with otel.span('attachment-jobs process', kind=otel.SpanKind.CONSUMER,
|
|
context=otel.extract(message), attributes={
|
|
'messaging.system': 'redis', 'messaging.destination.name': STREAM,
|
|
'messaging.operation.type': 'process', 'job.attempt': message.get('attempt', 0)}):
|
|
process_message(sessions, client, message_id, message)
|
|
|
|
|
|
def process_message(sessions, client, message_id, message):
|
|
try:
|
|
claimed = claim(sessions, message)
|
|
except (ValueError, KeyError, TypeError):
|
|
otel.event('invalid_job')
|
|
claimed = None
|
|
if claimed:
|
|
job_id, token = claimed
|
|
started = time.monotonic()
|
|
outcome = 'failed'
|
|
otel.worker_busy.add(1)
|
|
try:
|
|
environment = {**os.environ, 'OTEL_CHILD_PROCESS': 'true'}
|
|
environment.update({key.upper(): value for key, value in otel.carrier().items()})
|
|
try:
|
|
result = subprocess.run([sys.executable, '-m', 'src.image_processor', job_id, token],
|
|
timeout=TIMEOUT, check=False, env=environment)
|
|
code = result.returncode
|
|
except subprocess.TimeoutExpired:
|
|
code = 23
|
|
if code in (91, 92):
|
|
# Simulate a lost worker before ack: leave the pending entry and lease.
|
|
return
|
|
if code:
|
|
record_failure(sessions, job_id, token,
|
|
{20: 'invalid_image', 21: 'resource_limit', 23: 'processing_timeout'}
|
|
.get(code, 'processing_failed'), permanent=code in (20, 21))
|
|
otel.trace.get_current_span().set_status(otel.Status(otel.StatusCode.ERROR))
|
|
else:
|
|
with sessions() as session:
|
|
job = session.get(AttachmentJob, job_id)
|
|
attachment = session.get(Attachment, job.attachment_id)
|
|
outcome = 'ready' if attachment.status == 'ready' else 'skipped'
|
|
if outcome == 'ready':
|
|
otel.time_to_ready.record((attachment.updated_at - attachment.created_at).total_seconds(),
|
|
{'job_type': 'attachment.process.v1'})
|
|
finally:
|
|
otel.worker_busy.add(-1)
|
|
labels = {'job_type': 'attachment.process.v1', 'outcome': outcome}
|
|
elapsed = time.monotonic() - started
|
|
otel.jobs_processed.add(1, labels)
|
|
otel.job_duration.record(elapsed, labels)
|
|
otel.event('job_processed', severity=logging.ERROR if outcome == 'failed' else logging.INFO,
|
|
**labels, duration_seconds=elapsed)
|
|
# Only after a durable ready/failed/retry (or an existing durable lease).
|
|
acknowledge(client, message_id)
|
|
|
|
|
|
def acknowledge(client, message_id):
|
|
with client.pipeline(transaction=True) as pipe:
|
|
pipe.xack(STREAM, GROUP, message_id)
|
|
pipe.xdel(STREAM, message_id)
|
|
pipe.execute()
|
|
|
|
|
|
def consume(sessions):
|
|
client = broker()
|
|
consumer = str(uuid4())
|
|
cursor = '0-0'
|
|
while True:
|
|
try:
|
|
ensure_group(client)
|
|
pending = client.xautoclaim(STREAM, GROUP, consumer, LEASE_SECONDS * 1000,
|
|
start_id=cursor, count=1)
|
|
cursor, messages = pending[0], pending[1]
|
|
if not messages:
|
|
batches = client.xreadgroup(GROUP, consumer, {STREAM: '>'}, count=1, block=1000)
|
|
messages = batches[0][1] if batches else []
|
|
for message_id, fields in messages:
|
|
handle(sessions, client, message_id, fields)
|
|
except Exception as exc:
|
|
otel.event('worker_deferred', error_type=type(exc).__name__)
|
|
time.sleep(1)
|
|
|
|
|
|
def main():
|
|
logging.basicConfig(level=logging.INFO)
|
|
otel.setup()
|
|
engine = create_db_engine()
|
|
sessions = sessionmaker(engine, expire_on_commit=False)
|
|
concurrency = min(4, max(1, int(os.getenv('WORKER_CONCURRENCY', '2'))))
|
|
with ThreadPoolExecutor(max_workers=concurrency) as pool:
|
|
for task in [pool.submit(consume, sessions) for _ in range(concurrency)]:
|
|
task.result()
|
|
|
|
|
|
if __name__ == '__main__':
|
|
main()
|