forked from mtusi2026/mtusi2026lab7
238 lines
12 KiB
Python
238 lines
12 KiB
Python
"""Outbox relay: `python -m messenger.relay` (compose service `relay`, one process).
|
|
|
|
loop: SELECT due outbox rows FOR UPDATE SKIP LOCKED
|
|
-> publish each job message to RabbitMQ, wait for the publisher CONFIRM
|
|
-> UPDATE outbox SET published_at -> COMMIT
|
|
every few seconds: reaper (expired leases -> queued/failed), lost-message guard.
|
|
|
|
Why an outbox: the API commits the job and the outbox row in ONE PostgreSQL transaction and never
|
|
talks to the broker. A crash between COMMIT and publish leaves the row unpublished; the relay
|
|
publishes it when it (or the broker) is back - nobody re-creates a job by hand. While the broker
|
|
is down, uploads still get 202 and the rows wait in the outbox.
|
|
|
|
A crash after the confirm but before the COMMIT of published_at publishes the row once more after
|
|
the restart: the queue then holds a duplicate. That is at-least-once delivery; the worker turns
|
|
the duplicate into a no-op (jobs.claim). The relay never deletes or rewrites jobs.
|
|
|
|
Lab 6: every publish is a PRODUCER span `messenger.jobs publish` (publish + wait for the confirm),
|
|
child of the trace context stored with the job (the upload request). The producer's context goes
|
|
into the message body (`traceparent`/`tracestate`, contracts/jobs.schema.json) and the AMQP
|
|
headers. The relay is also the source of the queue gauges: every MAINTENANCE_SECONDS it counts
|
|
unfinished jobs and due outbox rows in PostgreSQL (the source of truth of the backlog, including
|
|
jobs waiting for a retry, which the broker queue does not hold).
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import asyncio
|
|
import logging
|
|
import sys
|
|
import time
|
|
|
|
import aio_pika
|
|
from aio_pika.abc import AbstractChannel, AbstractConnection, AbstractExchange
|
|
|
|
from . import __version__, broker, jobs, logging_setup, service, telemetry
|
|
from .config import ConfigError, Settings, publish_instance_id
|
|
from .db import Database
|
|
from .errors import Unavailable
|
|
|
|
log = logging.getLogger("messenger.relay")
|
|
ACTOR = "relay"
|
|
MAINTENANCE_SECONDS = 5.0
|
|
PURGE_SECONDS = 600.0
|
|
|
|
|
|
class Relay:
|
|
def __init__(self, settings: Settings):
|
|
self.settings = settings
|
|
self.db = Database(settings, name="messenger-relay")
|
|
self.connection: AbstractConnection | None = None
|
|
self.channel: AbstractChannel | None = None
|
|
self.exchange: AbstractExchange | None = None
|
|
self.lost: asyncio.Event | None = None
|
|
self.queue_stats: dict | None = None # last jobs.queue_stats (None: unknown -> no data points)
|
|
|
|
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)
|
|
|
|
async def connect(self) -> None:
|
|
self.connection = await aio_pika.connect(
|
|
self.settings.broker_url, timeout=5, ssl_context=broker.ssl_context(self.settings),
|
|
client_properties={"connection_name": "relay@" + self.settings.instance_id})
|
|
self.lost = service.watch_connection(self.connection)
|
|
# Confirm mode: every publish() waits for basic.ack of the broker (message in the quorum log).
|
|
self.channel = await self.connection.channel(publisher_confirms=True, on_return_raises=True)
|
|
# No declare: the topology belongs to the broker definitions; the relay may only write.
|
|
self.exchange = await self.channel.get_exchange(broker.EXCHANGE, ensure=False)
|
|
log.info("broker_connected", extra={"fields": {"exchange": broker.EXCHANGE}})
|
|
|
|
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.exchange = self.lost = None
|
|
|
|
async def publish_due(self) -> int:
|
|
settings = self.settings
|
|
exchange = self.exchange
|
|
|
|
async def work(conn) -> list[jobs.Due]:
|
|
rows = await jobs.due_outbox(conn, settings.relay_batch)
|
|
if "reverse_order" in settings.fault_points:
|
|
rows.reverse()
|
|
# Rows of jobs that are no longer queued (finished meanwhile) need no message.
|
|
sendable = [r for r in rows if r.job_state == "queued"]
|
|
copies = 2 if "duplicate_publish" in settings.fault_points else 1
|
|
for row in sendable:
|
|
with telemetry.TRACER.start_as_current_span(
|
|
f"{broker.EXCHANGE} publish", kind=telemetry.SpanKind.PRODUCER,
|
|
context=telemetry.extract(row.traceparent, row.tracestate),
|
|
record_exception=False, set_status_on_exception=False,
|
|
attributes={"messaging.system": "rabbitmq", "messaging.operation.type": "send",
|
|
"messaging.operation.name": "publish",
|
|
"messaging.destination.name": broker.EXCHANGE,
|
|
"messaging.rabbitmq.destination.routing_key": broker.ROUTING_KEY,
|
|
"messaging.message.id": f"{row.job_id}:{row.outbox_id}",
|
|
"messenger.job.id": row.job_id, "messenger.job.attempt": row.attempt,
|
|
"messenger.job.kind": row.kind}) as span:
|
|
carrier = telemetry.inject() # = this producer span
|
|
message = aio_pika.Message(
|
|
broker.encode(row.job_id, row.attachment_id, row.pipeline_version, row.attempt,
|
|
row.created_at, carrier),
|
|
delivery_mode=aio_pika.DeliveryMode.PERSISTENT, content_type="application/json",
|
|
message_id=f"{row.job_id}:{row.outbox_id}", type=broker.JOB_TYPE, headers=dict(carrier))
|
|
try:
|
|
for _ in range(copies):
|
|
await exchange.publish(message, routing_key=broker.ROUTING_KEY, mandatory=True, timeout=5)
|
|
except BaseException as exc:
|
|
telemetry.mark_error(span, type(exc).__name__)
|
|
raise
|
|
for row in sendable:
|
|
# Confirmed by the broker, outbox not marked yet: the window "after publish, before
|
|
# the confirm is recorded". The crash rolls this transaction back.
|
|
await service.crash_once(settings, self.db, "crash_after_publish", row.job_id, ACTOR,
|
|
outbox_id=row.outbox_id)
|
|
await jobs.mark_published(conn, [r.outbox_id for r in rows])
|
|
return sendable
|
|
|
|
sent = await self.db.run(work, deadline=10 + 5 * settings.relay_batch)
|
|
for row in sent:
|
|
log.info("job_published", extra={"fields": {"job_id": row.job_id, "attempt": row.attempt,
|
|
"outbox_id": row.outbox_id}})
|
|
return len(sent)
|
|
|
|
async def maintenance(self) -> None:
|
|
try:
|
|
self.queue_stats = await self.db.run(jobs.queue_stats, op="queue_stats")
|
|
except Unavailable:
|
|
self.queue_stats = None # unknown backlog: the gauges report nothing (not a stale value)
|
|
raise
|
|
expired = await self.db.run(lambda c: jobs.expire_leases(c, ACTOR))
|
|
republished = await self.db.run(lambda c: jobs.republish_stale(c, self.settings.queued_republish_seconds, ACTOR))
|
|
if expired or republished:
|
|
log.info("maintenance", extra={"fields": {"leases_expired": expired, "republished": republished}})
|
|
|
|
def register_metrics(self) -> None:
|
|
queue = {"messaging.destination.name": broker.QUEUE}
|
|
|
|
def depth():
|
|
st = self.queue_stats
|
|
return [] if st is None else [(st["queued"], {**queue, "state": "queued"}),
|
|
(st["processing"], {**queue, "state": "processing"})]
|
|
|
|
def oldest():
|
|
st = self.queue_stats
|
|
return [] if st is None else [(st["oldest_age"], queue)]
|
|
|
|
def outbox():
|
|
st = self.queue_stats
|
|
return [] if st is None else [(st["outbox_due"], {"state": "due"}),
|
|
(st["outbox_delayed"], {"state": "delayed"})]
|
|
|
|
def outbox_age():
|
|
st = self.queue_stats
|
|
return [] if st is None else [(st["outbox_oldest_due_age"], {})]
|
|
|
|
telemetry.observe("messenger.queue.depth", "{job}",
|
|
"Unfinished jobs (PostgreSQL) by state: queued (incl. waiting for a retry) / processing", depth)
|
|
telemetry.observe("messenger.queue.oldest_age", "s",
|
|
"Age of the oldest unfinished job: now - its durable acceptance (jobs.created_at)", oldest)
|
|
telemetry.observe("messenger.outbox.pending", "{message}",
|
|
"Unpublished outbox rows: due now / delayed (retry backoff)", outbox)
|
|
telemetry.observe("messenger.outbox.oldest_age", "s",
|
|
"How long the oldest DUE outbox row waits for its publish (broker down -> grows)", outbox_age)
|
|
telemetry.observe_pool(self.db.pool, self.db.name)
|
|
|
|
async def run(self) -> int:
|
|
stop = service.stop_event()
|
|
self.register_metrics()
|
|
await self.db.open()
|
|
next_maintenance = next_purge = 0.0
|
|
failures = 0
|
|
try:
|
|
while not stop.is_set():
|
|
healthy = True
|
|
now = time.monotonic()
|
|
try:
|
|
if now >= next_maintenance:
|
|
await self.maintenance()
|
|
next_maintenance = now + MAINTENANCE_SECONDS
|
|
if now >= next_purge:
|
|
purged = await self.db.run(jobs.purge_outbox)
|
|
next_purge = now + PURGE_SECONDS
|
|
if purged:
|
|
log.info("outbox_purged", extra={"fields": {"rows": purged}})
|
|
except Unavailable:
|
|
healthy = False
|
|
try:
|
|
if not self.connected():
|
|
await self.disconnect()
|
|
await self.connect()
|
|
sent = await self.publish_due()
|
|
failures = 0
|
|
except Unavailable:
|
|
healthy, sent = False, 0
|
|
except Exception as exc: # noqa: BLE001 - every broker/channel error, never a crash
|
|
# Broker down/unreachable, channel closed, message returned/nacked: nothing marked,
|
|
# the rows stay in the outbox (transaction rolled back) and are published later.
|
|
failures += 1
|
|
healthy, sent = False, 0
|
|
log.warning("publish_failed", extra={"fields": {"error": type(exc).__name__, "failures": failures}})
|
|
await self.disconnect()
|
|
if healthy:
|
|
service.beat()
|
|
if not sent:
|
|
await service.sleep_or_stop(stop, min(5.0, self.settings.relay_poll_seconds * (2 ** min(failures, 3))))
|
|
finally:
|
|
await self.disconnect()
|
|
await self.db.close()
|
|
log.info("relay_stopped")
|
|
return 0
|
|
|
|
|
|
def main() -> int:
|
|
logging_setup.configure_early()
|
|
try:
|
|
settings = Settings.from_env(s3_credentials=False)
|
|
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)
|
|
publish_instance_id(settings.instance_id)
|
|
telemetry.setup("messenger-relay", settings.instance_id, __version__)
|
|
log.info("relay_starting", extra={"fields": {"instance_id": settings.instance_id,
|
|
"fault_points": sorted(settings.fault_points)}})
|
|
try:
|
|
return asyncio.run(Relay(settings).run())
|
|
finally:
|
|
telemetry.shutdown()
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|