forked from mtusi2026/mtusi2026lab7
Перенос решения ЛР 6 без изменений (src, migrations, student-tests, bench, infra, scripts, compose, Dockerfile, docs)
This commit is contained in:
@@ -0,0 +1,403 @@
|
||||
"""Image worker: `python -m messenger.worker` (compose service `worker`, separate from the API).
|
||||
|
||||
One delivery of a job message:
|
||||
|
||||
decode + validate (schema v1; invalid -> reject -> dead-letter queue)
|
||||
-> CLAIM in PostgreSQL (jobs.claim): finished/leased/not due/stale -> no-op, ack
|
||||
-> lease heartbeat every JOB_LEASE_SECONDS/3 while the attempt runs
|
||||
-> read the source (staging copy or published original), check size + SHA-256 against the DB
|
||||
-> variants in a child process (imaging.py: pixel, memory and time limits)
|
||||
-> PUT the original (first publication) and the variants under keys of THIS attempt
|
||||
-> ONE transaction: variants + attachment ready, fenced by the lease token (jobs.complete)
|
||||
-> ack -> delete the staging copy (marked in the DB first, then S3).
|
||||
|
||||
The ack comes only after the durable effect (the COMMIT). A crash anywhere before it makes
|
||||
RabbitMQ deliver the message again; the job row then says what is left to do. Failures: a
|
||||
permanent one (invalid_image, image_too_large, source_missing/corrupt) fails the job at once, a
|
||||
transient one (S3 down, timeout, killed decoder) is retried with backoff via the outbox, at most
|
||||
JOB_MAX_ATTEMPTS claims in total.
|
||||
|
||||
Concurrency: RabbitMQ prefetch = WORKER_CONCURRENCY unacked messages per worker, and at most
|
||||
WORKER_CONCURRENCY image child processes. Graceful stop (SIGTERM): stop consuming, let running
|
||||
attempts finish for WORKER_SHUTDOWN_SECONDS, give the rest back (jobs.release).
|
||||
|
||||
The worker also runs the cleanup of the pipeline objects (staging copies that are no longer
|
||||
needed, objects of attempts that never published) - always decided under a row lock.
|
||||
|
||||
Lab 6: one delivery = one CONSUMER span `messenger.attachment-jobs process`, child of the relay's
|
||||
PRODUCER span (context from the message's `traceparent`), so the upload, its publish, every
|
||||
attempt and its DB/S3 steps are one trace. Metrics: messenger.jobs.processed (by outcome),
|
||||
messenger.job.duration, messenger.attachment.time_to_ready (uploads: 202 -> ready COMMIT),
|
||||
messenger.worker.busy / messenger.worker.capacity, db.client.connection.* of the worker pool.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import hashlib
|
||||
import logging
|
||||
import sys
|
||||
import time
|
||||
|
||||
import aio_pika
|
||||
from aio_pika.abc import AbstractChannel, AbstractConnection, AbstractIncomingMessage, AbstractQueue
|
||||
|
||||
from . import __version__, broker, imaging, jobs, logging_setup, service, telemetry
|
||||
from .config import ConfigError, Settings
|
||||
from .db import Database
|
||||
from .errors import Unavailable
|
||||
from .imaging import ProcessingError
|
||||
from .storage import ObjectMissing, Storage
|
||||
|
||||
log = logging.getLogger("messenger.worker")
|
||||
|
||||
|
||||
class Worker:
|
||||
def __init__(self, settings: Settings):
|
||||
self.settings = settings
|
||||
self.name = settings.instance_id
|
||||
self.actor = "worker:" + self.name
|
||||
self.db = Database(settings, name="messenger-worker")
|
||||
self.staging = Storage(settings, bucket=settings.s3_staging_bucket)
|
||||
self.final = Storage(settings)
|
||||
self.slots = asyncio.Semaphore(settings.worker_concurrency)
|
||||
self.tasks: set[asyncio.Task] = set()
|
||||
self.connection: AbstractConnection | None = None
|
||||
self.channel: AbstractChannel | None = None
|
||||
self.queue: AbstractQueue | None = None
|
||||
self.consumer_tag: str | None = None
|
||||
self.lost: asyncio.Event | None = None
|
||||
|
||||
def connected(self) -> bool:
|
||||
return (self.connection is not None and self.lost is not None and not self.lost.is_set()
|
||||
and self.channel is not None and not self.channel.is_closed)
|
||||
|
||||
# ---------------------------------------------------------------- broker
|
||||
async def connect(self) -> None:
|
||||
self.connection = await aio_pika.connect(
|
||||
self.settings.broker_url, timeout=5,
|
||||
client_properties={"connection_name": "worker@" + self.name})
|
||||
self.lost = service.watch_connection(self.connection)
|
||||
self.channel = await self.connection.channel()
|
||||
# Prefetch: the broker keeps at most this many unacked messages in flight to this worker.
|
||||
await self.channel.set_qos(prefetch_count=self.settings.worker_concurrency)
|
||||
self.queue = await self.channel.get_queue(broker.QUEUE, ensure=False)
|
||||
self.consumer_tag = await self.queue.consume(self.on_message, no_ack=False)
|
||||
log.info("consuming", extra={"fields": {"queue": broker.QUEUE, "prefetch": self.settings.worker_concurrency}})
|
||||
|
||||
async def disconnect(self) -> None:
|
||||
if self.connection is not None:
|
||||
try:
|
||||
await self.connection.close()
|
||||
except Exception: # noqa: BLE001 - already broken
|
||||
pass
|
||||
self.connection = self.channel = self.queue = self.lost = None
|
||||
self.consumer_tag = None
|
||||
|
||||
async def on_message(self, message: AbstractIncomingMessage) -> None:
|
||||
task = asyncio.create_task(self.deliver(message))
|
||||
self.tasks.add(task)
|
||||
task.add_done_callback(self.tasks.discard)
|
||||
|
||||
@staticmethod
|
||||
async def settle(action) -> None:
|
||||
"""ack/nack/reject; the channel may be gone (broker restart): then the broker requeues the
|
||||
message by itself and the redelivery is a no-op."""
|
||||
try:
|
||||
await action
|
||||
except Exception as exc: # noqa: BLE001
|
||||
log.warning("settle_failed", extra={"fields": {"error": type(exc).__name__}})
|
||||
|
||||
async def deliver(self, message: AbstractIncomingMessage) -> None:
|
||||
begin = time.perf_counter()
|
||||
try:
|
||||
body = broker.decode(message.body)
|
||||
except broker.BadMessage as exc:
|
||||
log.error("bad_message", extra={"fields": {"reason": str(exc), "message_id": message.message_id}})
|
||||
self.count("rejected", begin)
|
||||
await self.settle(message.reject(requeue=False)) # -> messenger.attachment-jobs.dlq
|
||||
return
|
||||
with telemetry.TRACER.start_as_current_span(
|
||||
f"{broker.QUEUE} process", kind=telemetry.SpanKind.CONSUMER,
|
||||
context=telemetry.extract(body.get("traceparent"), body.get("tracestate")),
|
||||
record_exception=False, set_status_on_exception=False,
|
||||
attributes={"messaging.system": "rabbitmq", "messaging.operation.type": "process",
|
||||
"messaging.destination.name": broker.QUEUE,
|
||||
"messaging.message.id": message.message_id or "",
|
||||
"messaging.rabbitmq.message.redelivered": bool(message.redelivered),
|
||||
"messenger.job.id": body["job_id"], "messenger.job.message_attempt": body["attempt"],
|
||||
"messenger.attachment.id": body["attachment_id"],
|
||||
"messenger.pipeline.version": body["pipeline_version"],
|
||||
"service.instance.id": self.name}) as span:
|
||||
try:
|
||||
async with self.slots:
|
||||
telemetry.worker_busy.add(1)
|
||||
try:
|
||||
outcome = await self.process(body["job_id"])
|
||||
finally:
|
||||
telemetry.worker_busy.add(-1)
|
||||
except Unavailable:
|
||||
# PostgreSQL (or S3 during a DB step) unavailable: nothing decided. Back to the queue
|
||||
# after a pause; a claim that did happen is protected by its lease.
|
||||
log.warning("job_deferred", extra={"fields": {"job_id": body["job_id"]}})
|
||||
telemetry.mark_error(span, "deferred")
|
||||
span.set_attribute("messenger.job.outcome", "deferred")
|
||||
self.count("deferred", begin)
|
||||
await asyncio.sleep(2)
|
||||
await self.settle(message.nack(requeue=True))
|
||||
return
|
||||
except asyncio.CancelledError:
|
||||
# Shutdown: back to the queue. If the job was claimed it has been released (new outbox
|
||||
# row), and one of the two deliveries becomes a no-op.
|
||||
span.set_attribute("messenger.job.outcome", "cancelled")
|
||||
self.count("cancelled", begin)
|
||||
await self.settle(asyncio.shield(message.nack(requeue=True)))
|
||||
raise
|
||||
span.set_attribute("messenger.job.outcome", outcome)
|
||||
if outcome in ("failed", "retry", "fenced"):
|
||||
telemetry.mark_error(span, outcome)
|
||||
self.count(outcome, begin)
|
||||
log.info("job_done", extra={"fields": {"job_id": body["job_id"], "outcome": outcome,
|
||||
"message_attempt": body["attempt"],
|
||||
"redelivered": message.redelivered}})
|
||||
await self.settle(message.ack())
|
||||
|
||||
@staticmethod
|
||||
def count(outcome: str, begin: float) -> None:
|
||||
"""messenger.jobs.processed + messenger.job.duration of one delivery (outcome: a fixed set:
|
||||
succeeded, retry, failed, fenced, superseded, released, deferred, cancelled, rejected, noop_*)."""
|
||||
attributes = {"messenger.job.type": broker.JOB_TYPE, "outcome": outcome}
|
||||
telemetry.jobs_processed.add(1, attributes)
|
||||
telemetry.job_duration.record(time.perf_counter() - begin, attributes)
|
||||
|
||||
# ---------------------------------------------------------------- one attempt
|
||||
async def process(self, job_id: str) -> str:
|
||||
settings = self.settings
|
||||
claim = await self.db.run(lambda c: jobs.claim(c, job_id, self.name, settings.job_lease_seconds),
|
||||
op="jobs.claim")
|
||||
if isinstance(claim, jobs.Noop):
|
||||
return "noop_" + claim.reason
|
||||
span = telemetry.trace.get_current_span()
|
||||
span.set_attribute("messenger.job.attempt", claim.attempt)
|
||||
span.set_attribute("messenger.job.kind", claim.kind)
|
||||
span.set_attribute("messenger.job.source", claim.source)
|
||||
await service.crash_once(settings, self.db, "crash_after_claim", job_id, self.actor)
|
||||
lost = asyncio.Event()
|
||||
work = asyncio.create_task(self.attempt(claim))
|
||||
beat = asyncio.create_task(self.heartbeat(claim, work, lost))
|
||||
try:
|
||||
variants = await work
|
||||
except asyncio.CancelledError:
|
||||
if lost.is_set() and not asyncio.current_task().cancelling():
|
||||
return "fenced" # lease taken over: this attempt may write nothing more
|
||||
outcome = await asyncio.shield(self.db.run(lambda c: jobs.release(c, claim, self.name), op="jobs.release"))
|
||||
log.info("job_released", extra={"fields": {"job_id": job_id, "outcome": outcome}})
|
||||
raise
|
||||
except ProcessingError as exc:
|
||||
return await self.failed(claim, exc.code, exc.permanent)
|
||||
except Unavailable:
|
||||
return await self.failed(claim, "storage_unavailable", False)
|
||||
finally:
|
||||
beat.cancel()
|
||||
await service.crash_once(settings, self.db, "crash_after_s3_write", job_id, self.actor)
|
||||
outcome = await self.db.run(lambda c: jobs.complete(c, claim, variants, self.name), op="jobs.complete")
|
||||
if outcome == "succeeded" and claim.kind == "upload" and claim.accepted_at is not None:
|
||||
# Lab 6 SLI "time to ready": durable acceptance (job COMMIT before the 202) -> ready COMMIT.
|
||||
telemetry.time_to_ready.record(max(0.0, time.time() - claim.accepted_at.timestamp()),
|
||||
{"messenger.job.kind": claim.kind})
|
||||
await service.crash_once(settings, self.db, "crash_after_commit", job_id, self.actor)
|
||||
if outcome == "succeeded":
|
||||
await self.delete_staging(claim.attachment_id)
|
||||
return outcome
|
||||
|
||||
async def failed(self, claim: jobs.Claim, code: str, permanent: bool) -> str:
|
||||
s = self.settings
|
||||
outcome, delay = await self.db.run(
|
||||
lambda c: jobs.retry_or_fail(c, claim, code, permanent, self.name, s.job_retry_base_seconds,
|
||||
s.job_retry_max_seconds), op="jobs.retry_or_fail")
|
||||
telemetry.trace.get_current_span().set_attribute("messenger.job.error_code", code)
|
||||
log.info("attempt_failed", extra={"fields": {"job_id": claim.job_id, "attempt": claim.attempt, "code": code,
|
||||
"permanent": permanent, "outcome": outcome,
|
||||
"delay_s": round(delay, 3)}})
|
||||
return outcome
|
||||
|
||||
async def heartbeat(self, claim: jobs.Claim, work: asyncio.Task, lost: asyncio.Event) -> None:
|
||||
"""Renew the lease while the attempt is alive and within JOB_TIMEOUT_SECONDS. A hung attempt
|
||||
stops being renewed, so the reaper can hand the job to another worker; if the lease turns out
|
||||
to be lost, the attempt is cancelled (its result would be fenced anyway)."""
|
||||
s = self.settings
|
||||
if "hang" in s.fault_points:
|
||||
return # experiment: a hung worker that no longer heartbeats
|
||||
started = time.monotonic()
|
||||
while True:
|
||||
await asyncio.sleep(s.job_lease_seconds / 3)
|
||||
if time.monotonic() - started > s.job_timeout_seconds:
|
||||
return
|
||||
try:
|
||||
alive = await self.db.run(lambda c: jobs.heartbeat(c, claim, s.job_lease_seconds), op="jobs.heartbeat")
|
||||
except Unavailable:
|
||||
continue # the lease may expire meanwhile; the fence protects the result
|
||||
if not alive:
|
||||
log.warning("lease_lost", extra={"fields": {"job_id": claim.job_id, "attempt": claim.attempt}})
|
||||
lost.set()
|
||||
work.cancel()
|
||||
return
|
||||
|
||||
async def attempt(self, claim: jobs.Claim) -> list[imaging.Rendered]:
|
||||
s = self.settings
|
||||
if "hang" in s.fault_points:
|
||||
await asyncio.sleep(s.fault_value("hang", 3600)) # stuck outside of the time limit
|
||||
try:
|
||||
return await asyncio.wait_for(self.build(claim), s.job_timeout_seconds)
|
||||
except asyncio.TimeoutError:
|
||||
raise ProcessingError("processing_timeout", permanent=False) from None
|
||||
|
||||
async def build(self, claim: jobs.Claim) -> list[imaging.Rendered]:
|
||||
s = self.settings
|
||||
started = time.monotonic()
|
||||
if claim.size_bytes > s.max_upload_bytes:
|
||||
raise ProcessingError("image_too_large", permanent=True)
|
||||
source = self.staging if claim.source == "staging" else self.final
|
||||
try:
|
||||
data = await source.read_all(claim.source_key, limit=s.max_upload_bytes)
|
||||
except ObjectMissing:
|
||||
raise ProcessingError("source_missing", permanent=True) from None
|
||||
if len(data) != claim.size_bytes or hashlib.sha256(data).digest() != claim.sha256:
|
||||
raise ProcessingError("source_corrupt", permanent=True)
|
||||
self.injected(claim)
|
||||
if "slow" in s.fault_points and s.fault_value("slow_pipeline", claim.pipeline_version) == claim.pipeline_version:
|
||||
await asyncio.sleep(s.fault_value("slow", 10))
|
||||
remaining = max(1.0, s.job_timeout_seconds - (time.monotonic() - started))
|
||||
with telemetry.child_span("image render", {"messenger.image.content_type": claim.content_type,
|
||||
"messenger.image.size_bytes": claim.size_bytes}) as span:
|
||||
variants = await imaging.render(data, claim.content_type, claim.pipeline_version,
|
||||
max_pixels=s.max_image_pixels, timeout=remaining,
|
||||
memory_mb=s.image_max_memory_mb)
|
||||
if span is not None:
|
||||
span.set_attribute("messenger.image.variants", [v.name for v in variants])
|
||||
meta = {"attachment-id": claim.attachment_id, "pipeline-version": str(claim.pipeline_version)}
|
||||
puts = [self.final.put(claim.key(v.name), v.data, v.content_type, meta) for v in variants]
|
||||
if claim.write_original:
|
||||
puts.append(self.final.put(claim.key("original"), data, claim.content_type,
|
||||
{**meta, "sha256": claim.sha256.hex()}))
|
||||
await asyncio.gather(*puts)
|
||||
return variants
|
||||
|
||||
def injected(self, claim: jobs.Claim) -> None:
|
||||
s = self.settings
|
||||
if "permanent_error" in s.fault_points:
|
||||
raise ProcessingError("invalid_image", permanent=True)
|
||||
if "transient_error" in s.fault_points and claim.attempt <= s.fault_value("transient_error", 1000):
|
||||
raise ProcessingError("injected_transient", permanent=False)
|
||||
|
||||
# ---------------------------------------------------------------- cleanup
|
||||
async def delete_staging(self, attachment_id: str) -> None:
|
||||
"""Mark `deleting` under the row lock (re-checked there), then S3 DELETE, then `deleted`."""
|
||||
try:
|
||||
key = await self.db.run(
|
||||
lambda c: jobs.mark_staging_deleting(c, attachment_id, self.settings.staging_retention_seconds))
|
||||
if key is None:
|
||||
return
|
||||
await self.staging.delete(key)
|
||||
await self.db.run(lambda c: jobs.mark_staging_deleted(c, attachment_id))
|
||||
log.info("staging_deleted", extra={"fields": {"attachment_id": attachment_id}})
|
||||
except Unavailable:
|
||||
pass # stays present/deleting; the next cleanup pass repeats (DELETE is idempotent)
|
||||
|
||||
async def cleanup(self) -> None:
|
||||
s = self.settings
|
||||
ids = await self.db.run(lambda c: jobs.staging_to_delete(c, s.staging_retention_seconds))
|
||||
tokens = await self.db.run(lambda c: jobs.attempts_to_clean(c, s.orphan_grace_seconds))
|
||||
if "pause_cleanup" in s.fault_points and (ids or tokens):
|
||||
# Experiment: the race "cleanup read its candidates -> replay commits -> cleanup goes on".
|
||||
log.warning("cleanup_paused", extra={"fields": {"attachments": ids, "attempts": tokens}})
|
||||
await asyncio.sleep(s.fault_value("pause_cleanup", 10))
|
||||
for attachment_id in ids:
|
||||
await self.delete_staging(attachment_id)
|
||||
for token in tokens:
|
||||
keys = await self.db.run(lambda c: jobs.lock_attempt_for_cleanup(c, token))
|
||||
if keys is None:
|
||||
continue
|
||||
await asyncio.gather(*(self.final.delete(k) for k in keys))
|
||||
await self.db.run(lambda c: jobs.mark_attempt_cleaned(c, token))
|
||||
log.info("attempt_objects_deleted", extra={"fields": {"token": token, "objects": len(keys)}})
|
||||
|
||||
async def cleanup_loop(self, stop: asyncio.Event) -> None:
|
||||
while not stop.is_set() and self.settings.cleanup_interval_seconds > 0:
|
||||
await service.sleep_or_stop(stop, self.settings.cleanup_interval_seconds)
|
||||
try:
|
||||
await self.cleanup()
|
||||
except Unavailable:
|
||||
pass
|
||||
|
||||
# ---------------------------------------------------------------- lifecycle
|
||||
async def run(self) -> int:
|
||||
stop = service.stop_event()
|
||||
telemetry.observe("messenger.worker.capacity", "{job}", "WORKER_CONCURRENCY: attempts one worker runs at once",
|
||||
lambda: [(self.settings.worker_concurrency, {})])
|
||||
telemetry.observe_pool(self.db.pool, self.db.name)
|
||||
await self.db.open()
|
||||
await self.staging.open()
|
||||
await self.final.open()
|
||||
cleaner = asyncio.create_task(self.cleanup_loop(stop))
|
||||
try:
|
||||
while not stop.is_set():
|
||||
if not self.connected():
|
||||
await self.disconnect()
|
||||
try:
|
||||
await self.connect()
|
||||
except Exception as exc: # noqa: BLE001 - broker down: retry in 2 s, never crash
|
||||
log.warning("broker_unavailable", extra={"fields": {"error": type(exc).__name__}})
|
||||
await self.disconnect()
|
||||
if self.connected():
|
||||
service.beat() # healthy only while a consumer is really attached
|
||||
await service.sleep_or_stop(stop, 2.0)
|
||||
await self.shutdown()
|
||||
finally:
|
||||
cleaner.cancel()
|
||||
await self.disconnect()
|
||||
await self.final.close()
|
||||
await self.staging.close()
|
||||
await self.db.close()
|
||||
log.info("worker_stopped")
|
||||
return 0
|
||||
|
||||
async def shutdown(self) -> None:
|
||||
"""Stop consuming; running attempts get WORKER_SHUTDOWN_SECONDS, the rest is released."""
|
||||
if self.queue is not None and self.consumer_tag is not None:
|
||||
try:
|
||||
await self.queue.cancel(self.consumer_tag)
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
pending = set(self.tasks)
|
||||
log.info("worker_draining", extra={"fields": {"in_flight": len(pending)}})
|
||||
if pending:
|
||||
_, pending = await asyncio.wait(pending, timeout=self.settings.worker_shutdown_seconds)
|
||||
for task in pending:
|
||||
task.cancel()
|
||||
if pending:
|
||||
await asyncio.wait(pending, timeout=10)
|
||||
|
||||
|
||||
def main() -> int:
|
||||
try:
|
||||
settings = Settings.from_env()
|
||||
if not settings.broker_url:
|
||||
raise ConfigError("BROKER_URL_FILE (or BROKER_URL) must be set")
|
||||
except ConfigError as exc:
|
||||
print(f"configuration error: {exc}", file=sys.stderr)
|
||||
return 2
|
||||
logging_setup.configure(settings.log_level)
|
||||
telemetry.setup("messenger-worker", settings.instance_id, __version__)
|
||||
log.info("worker_starting", extra={"fields": {
|
||||
"instance_id": settings.instance_id, "concurrency": settings.worker_concurrency,
|
||||
"max_attempts": settings.job_max_attempts, "timeout_s": settings.job_timeout_seconds,
|
||||
"lease_s": settings.job_lease_seconds, "memory_mb": settings.image_max_memory_mb,
|
||||
"fault_points": sorted(settings.fault_points)}})
|
||||
try:
|
||||
return asyncio.run(Worker(settings).run())
|
||||
finally:
|
||||
telemetry.shutdown()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Reference in New Issue
Block a user