This commit is contained in:
2026-11-30 15:50:51 +03:00
parent aef85e362a
commit d4ca44b300
20 changed files with 641 additions and 335 deletions
+95 -48
View File
@@ -5,6 +5,11 @@ import logging
import os
import time
import uuid
from telemetry import configure, JsonLogFormatter
from opentelemetry import trace
from opentelemetry.propagate import extract, inject
from opentelemetry.trace import Status, StatusCode
import logging
from datetime import datetime, timedelta, timezone
from PIL import Image, ImageOps
@@ -20,6 +25,9 @@ MAX_ATTEMPTS = int(os.environ.get("JOB_MAX_ATTEMPTS", "5"))
LEASE_SECONDS = int(os.environ.get("JOB_TIMEOUT_SECONDS", "60"))
PREFETCH = max(1, min(10, int(os.environ.get("BROKER_PREFETCH", "1"))))
FAULT = os.environ.get("FAULT_INJECTION", "").strip()
TRACER = None
JOB_PROCESSED = None
JOB_DURATION = None
def inject_crash(point):
@@ -118,6 +126,12 @@ class Worker:
"attempt": 1,
"created_at": iso(now()),
}
with TRACER.start_as_current_span(
"publish attachment job",
kind=trace.SpanKind.PRODUCER,
attributes={"messaging.system": "redis", "messaging.destination.name": STREAM},
):
inject(fields)
message_id = self.redis.xadd(STREAM, fields, maxlen=10000, approximate=True)
self.store.mark_outbox_published(row["id"], iso(now()))
LOG.info("published job=%s message=%s", fields["job_id"], message_id)
@@ -128,56 +142,82 @@ class Worker:
if not job_id or not attachment_id:
self.redis.xack(STREAM, GROUP, message_id)
return
claim = self.store.claim_job(
job_id, iso(now() + timedelta(seconds=LEASE_SECONDS)), iso(now())
)
if claim is None:
self.redis.xack(STREAM, GROUP, message_id)
return
inject_crash("before-side-effect")
attachment = self.store.get_attachment_for_job(attachment_id)
if not attachment:
self.redis.xack(STREAM, GROUP, message_id)
return
if int(fields.get("pipeline_version", 1)) < int(attachment.get("pipeline_version", 1)):
self.redis.xack(STREAM, GROUP, message_id)
return
try:
staged = self.objects.get_object(attachment["staging_key"])
if staged is None:
raise ValueError("staging_missing")
raw = staged["Body"].read()
staged["Body"].close()
self.objects.put_file(
attachment["object_key"], io.BytesIO(raw), len(raw), attachment["content_type"]
)
inject_crash("after-original")
rendered = prepare_variants(raw, attachment_id)
for item in rendered:
self.objects.put_file(
item["_key"], io.BytesIO(item["_data"]), item["size_bytes"], item["content_type"]
)
inject_crash("after-side-effect")
self.store.set_attachment_variants(attachment_id, public_variants(rendered), iso(now()))
carrier = {key: value for key, value in fields.items() if key in ("traceparent", "tracestate")}
context = extract(carrier)
started = time.perf_counter()
with TRACER.start_as_current_span(
"process attachment job",
context=context,
kind=trace.SpanKind.CONSUMER,
attributes={"messaging.system": "redis", "messaging.destination.name": STREAM, "messaging.operation.name": "process"},
) as span:
outcome = "failed"
try:
self.objects.delete_object(attachment["staging_key"])
except S3Unavailable:
LOG.warning("staging cleanup deferred attachment=%s", attachment_id)
self.redis.xack(STREAM, GROUP, message_id)
except (S3Unavailable, OSError, ValueError, RuntimeError) as error:
attempt = claim["attempts"]
code = "processing_failed" if not isinstance(error, ValueError) else str(error)
if attempt >= MAX_ATTEMPTS:
self.store.fail_job(job_id, attachment_id, "retry_exhausted", iso(now()))
self.redis.xack(STREAM, GROUP, message_id)
else:
delay = min(300, 2 ** (attempt - 1)) + (hash(job_id) % 1000) / 1000
self.store.retry_job(
job_id, attachment_id, iso(now() + timedelta(seconds=delay)), code, iso(now())
claim = self.store.claim_job(
job_id, iso(now() + timedelta(seconds=LEASE_SECONDS)), iso(now())
)
if claim is None:
self.redis.xack(STREAM, GROUP, message_id)
outcome = "ignored"
return
inject_crash("before-side-effect")
attachment = self.store.get_attachment_for_job(attachment_id)
if not attachment:
self.redis.xack(STREAM, GROUP, message_id)
outcome = "ignored"
return
if int(fields.get("pipeline_version", 1)) < int(attachment.get("pipeline_version", 1)):
self.redis.xack(STREAM, GROUP, message_id)
outcome = "ignored"
return
staged = self.objects.get_object(attachment["staging_key"])
if staged is None:
raise ValueError("staging_missing")
raw = staged["Body"].read()
staged["Body"].close()
self.objects.put_file(
attachment["object_key"], io.BytesIO(raw), len(raw), attachment["content_type"]
)
inject_crash("after-original")
rendered = prepare_variants(raw, attachment_id)
for item in rendered:
self.objects.put_file(
item["_key"], io.BytesIO(item["_data"]), item["size_bytes"], item["content_type"]
)
inject_crash("after-side-effect")
self.store.set_attachment_variants(attachment_id, public_variants(rendered), iso(now()))
try:
self.objects.delete_object(attachment["staging_key"])
except S3Unavailable:
LOG.warning("staging cleanup deferred attachment=%s", attachment_id)
self.redis.xack(STREAM, GROUP, message_id)
time.sleep(delay)
self.redis.xadd(STREAM, fields, maxlen=10000, approximate=True)
outcome = "success"
LOG.info(
"job completed outcome=%s",
outcome,
extra={"job_id": job_id},
)
span.set_status(Status(StatusCode.OK))
except (S3Unavailable, OSError, ValueError, RuntimeError) as error:
attempt = claim["attempts"]
code = "processing_failed" if not isinstance(error, ValueError) else str(error)
if attempt >= MAX_ATTEMPTS:
self.store.fail_job(job_id, attachment_id, "retry_exhausted", iso(now()))
self.redis.xack(STREAM, GROUP, message_id)
else:
delay = min(300, 2 ** (attempt - 1)) + (hash(job_id) % 1000) / 1000
self.store.retry_job(
job_id, attachment_id, iso(now() + timedelta(seconds=delay)), code, iso(now())
)
self.redis.xack(STREAM, GROUP, message_id)
time.sleep(delay)
self.redis.xadd(STREAM, fields, maxlen=10000, approximate=True)
span.record_exception(error)
span.set_status(Status(StatusCode.ERROR))
finally:
attributes = {"job.type": "attachment.process.v1", "outcome": outcome}
JOB_PROCESSED.add(1, attributes)
JOB_DURATION.record(time.perf_counter() - started, attributes)
def run(self):
while True:
@@ -197,7 +237,14 @@ class Worker:
def main():
logging.basicConfig(level=os.environ.get("LOG_LEVEL", "INFO"), format="%(asctime)s %(levelname)s %(message)s")
global TRACER, JOB_PROCESSED, JOB_DURATION
TRACER, meter, otel_handler = configure("messenger-worker")
JOB_PROCESSED = meter.create_counter("messenger.jobs.processed", description="Worker jobs")
JOB_DURATION = meter.create_histogram("messenger.jobs.duration", unit="s", description="Worker job duration")
logging.basicConfig(level=os.environ.get("LOG_LEVEL", "INFO"), format="%(message)s")
for handler in logging.getLogger().handlers:
handler.setFormatter(JsonLogFormatter("messenger-worker"))
logging.getLogger().addHandler(otel_handler)
worker = Worker()
try:
worker.run()