import threading from app import broker, db, telemetry def _once(publish=True): 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) telemetry.sample_process() if not publish: return try: with db.connection() as conn: broker.publish_pending(conn) except Exception: telemetry.log_event("job.publish_deferred", severity="WARNING") def start(publish=True): stop = threading.Event() def loop(): while not stop.wait(2): _once(publish) _once(publish) threading.Thread(target=loop, name="poller", daemon=True).start() return stop