Files
mtusi2026lab6/app/poller.py
T

45 lines
1.3 KiB
Python

import threading
from app import broker, db, telemetry
def _once():
try:
with db.connection() as conn:
row = conn.execute(
"""
SELECT COUNT(*) AS depth,
EXTRACT(EPOCH FROM (NOW() - MIN(created_at))) AS age
FROM attachments
WHERE status IN ('queued', 'processing')
"""
).fetchone()
depth = int(row["depth"] or 0)
age = float(row["age"] or 0) if depth else 0.0
used, waiting = db.stats()
telemetry.update_runtime(queue_depth=depth, queue_age=age, db_up=1, pool_used=used, pool_waiting=waiting)
except Exception:
telemetry.update_runtime(db_up=0)
try:
telemetry.update_runtime(worker_consumers=broker.consumer_count())
except Exception:
telemetry.log_event("broker.stats_unavailable", severity="WARNING")
telemetry.sample_process()
try:
with db.connection() as conn:
broker.publish_pending(conn)
except Exception:
telemetry.log_event("job.publish_deferred", severity="WARNING")
def start():
stop = threading.Event()
def loop():
while not stop.wait(2):
_once()
_once()
threading.Thread(target=loop, name="poller", daemon=True).start()
return stop