add level 3 and 4

This commit is contained in:
Матвей
2026-11-05 22:23:52 +03:00
parent 66026d3ec9
commit 45c7aa0085
30 changed files with 1370 additions and 68 deletions
+35 -8
View File
@@ -20,6 +20,8 @@ from .broker import QUEUE, _connection, publish_dlq
from .config import load_settings
from .storage.postgres import PostgresStore
from .storage.s3 import S3Settings, S3Store
from . import telemetry as tel
from datetime import datetime, timezone
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s worker %(message)s")
@@ -131,6 +133,8 @@ async def process_locked(store: PostgresStore, s3: S3Store, payload: dict, lease
os._exit(70)
committed = await store.complete_attachment_job(attachment_id, original_key, metadata, attachment['claim_time'])
if committed:
if attachment.get('created_at') is not None:
tel.ready_duration.record(max(0, (datetime.now(timezone.utc) - attachment['created_at']).total_seconds()), {"job_type": "attachment"})
try:
await s3.delete(attachment["staging_key"])
except Exception:
@@ -151,10 +155,12 @@ def settle_delivery(channel, delivery_tag, future):
def main() -> None:
tel.setup("messenger-worker")
settings = load_settings()
connection = _connection()
channel = connection.channel()
workers = max(1, int(os.environ.get("WORKER_CONCURRENCY", "2")))
tel.capacity.add(workers)
channel.basic_qos(prefetch_count=max(1, int(os.environ.get("WORKER_PREFETCH", str(workers)))))
async def handle_async(payload):
@@ -178,7 +184,7 @@ def main() -> None:
finally:
await retry_store.close()
def handle(body):
def handle_job(body):
payload = None
try:
payload = json.loads(body)
@@ -188,18 +194,19 @@ def main() -> None:
raise ValueError("unexpected broker payload")
UUID(payload['attachment_id'])
UUID(payload['job_id'])
tel.trace.get_current_span().set_attribute("messaging.retry.attempt", int(payload.get('attempt', 1)))
except (ValueError, KeyError, TypeError):
try:
asyncio.run(publish_dlq({'failure': 'invalid_job'}))
return True
return True, False
except Exception:
return False
return False, False
try:
asyncio.run(handle_async(payload))
except Exception as error:
logging.warning("job failed attachment_id=%s", payload['attachment_id'])
if '_claim_time' not in payload:
return False
return False, False
try:
attachment_id = UUID(payload["attachment_id"])
attempt = int(payload.get("attempt", 1))
@@ -207,12 +214,32 @@ def main() -> None:
asyncio.run(schedule_retry(attachment_id, delay, payload['_claim_time'],
str(error) if isinstance(error, PermanentFailure) else None))
except Exception:
return False
return True
return False, False
return True, False
return True, True
def handle(body, headers):
started = time.monotonic()
tel.busy.add(1)
with tel.tracer.start_as_current_span("attachment.consume", context=tel.extract(headers), kind=tel.SpanKind.CONSUMER, record_exception=False, set_status_on_exception=False) as span:
try:
acknowledged, succeeded = handle_job(body)
outcome = "success" if succeeded else "failed"
return acknowledged
except Exception:
outcome = "failed"
raise
finally:
if 'outcome' not in locals(): outcome = "failed"
if outcome == "failed": span.set_status(tel.Status(tel.StatusCode.ERROR))
attrs = {"job_type": "attachment", "outcome": outcome}
tel.jobs.add(1, attrs)
tel.job_duration.record(time.monotonic() - started, attrs)
tel.log.info("job.processed", extra={"outcome": outcome})
tel.busy.add(-1)
def consume(ch, method, properties, body):
del properties
future = executor.submit(handle, body)
future = executor.submit(handle, body, properties.headers or {})
def acknowledged(_future):
if connection.is_open:
connection.add_callback_threadsafe(lambda: settle_delivery(ch, method.delivery_tag, _future))