Реализовать observability для лабораторной 6

This commit is contained in:
2026-11-20 17:55:23 +03:00
parent 58f3d4c457
commit 9e6428de05
50 changed files with 3573 additions and 98 deletions
+54 -7
View File
@@ -8,12 +8,19 @@ import os
import socket
from datetime import datetime, timezone
from opentelemetry import trace
from opentelemetry.trace import SpanKind
from ..config import load_settings
from ..observability import get_metrics
from ..observability.logging import safe_extra
from ..observability.propagation import extract_trace_context, inject_trace_context
from ..repositories import JobRepository, OutboxRepository
from .broker import ROUTING_KEY, connect, message, topology
from .runtime import configure_logging, dependencies
logger = logging.getLogger('app.publisher')
tracer = trace.get_tracer('messenger.publisher', '1.6.0')
async def run(once: bool = False) -> None:
@@ -21,6 +28,8 @@ async def run(once: bool = False) -> None:
engine, sessions, _storage = dependencies(settings)
outbox = OutboxRepository(sessions)
jobs = JobRepository(sessions)
instruments = get_metrics()
queue_attributes = {'messaging.destination.name': 'attachments.process'}
owner = f'{socket.gethostname()}:{os.getpid()}'
connection = await connect(settings.broker_url)
try:
@@ -29,18 +38,53 @@ async def run(once: bool = False) -> None:
while True:
now = datetime.now(timezone.utc)
await jobs.recover_expired(now)
depth, oldest_age = await jobs.queue_stats(now)
instruments.queue_depth.set(depth, queue_attributes)
instruments.queue_oldest_age.set(oldest_age, queue_attributes)
events = await outbox.claim(owner, now, lease_seconds=30)
for event in events:
try:
body = json.dumps(event.payload, separators=(',', ':')).encode()
await exchange.publish(
message(body, str(event.id)), routing_key=ROUTING_KEY, mandatory=True
)
parent = extract_trace_context({
'traceparent': event.traceparent,
'tracestate': event.tracestate,
})
with tracer.start_as_current_span(
'attachments publish',
context=parent,
kind=SpanKind.PRODUCER,
attributes={
'messaging.system': 'rabbitmq',
'messaging.destination.name': 'attachments.process',
'messaging.operation.name': 'publish',
'messaging.operation.type': 'send',
'job.id': str(event.job_id),
},
):
body = json.dumps(event.payload, separators=(',', ':')).encode()
headers = inject_trace_context()
await exchange.publish(
message(body, str(event.id), headers),
routing_key=ROUTING_KEY,
mandatory=True,
)
logger.info(
'outbox event published',
extra=safe_extra(
'outbox.published', event_id=str(event.id),
job_id=str(event.job_id),
),
)
if os.getenv('FAULT_PUBLISHER_AFTER_CONFIRM') == '1':
os._exit(91)
await outbox.published(event.id, owner, datetime.now(timezone.utc))
except Exception:
logger.exception('outbox publish failed event_id=%s', event.id)
logger.exception(
'outbox publish failed',
extra=safe_extra(
'outbox.publish_failed', event_id=str(event.id),
job_id=str(event.job_id),
),
)
await outbox.failed(
event.id, owner, 'broker_unavailable', datetime.now(timezone.utc)
)
@@ -56,8 +100,11 @@ def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument('--once', action='store_true')
args = parser.parse_args()
configure_logging()
asyncio.run(run(args.once))
telemetry = configure_logging('messenger-publisher')
try:
asyncio.run(run(args.once))
finally:
telemetry.shutdown()
if __name__ == '__main__':