Files
unshackle/unshackle/core/api/events.py
T

123 lines
4.6 KiB
Python

"""Server-wide event broadcaster feeding the dashboard SSE event stream."""
from __future__ import annotations
import asyncio
import threading
from collections import deque
from contextlib import suppress
from typing import Any
class EventBus:
"""Fan events out to every subscriber queue; drop when a subscriber falls behind."""
def __init__(self, history: int = 20000) -> None:
self._subs: list[asyncio.Queue] = []
self.seq = 0
self.history: deque[dict[str, Any]] = deque(maxlen=history)
self._loop: asyncio.AbstractEventLoop | None = None
self._loop_thread: threading.Thread | None = None
self._lock = threading.RLock()
def subscribe(self) -> asyncio.Queue:
self._loop = asyncio.get_running_loop()
self._loop_thread = threading.current_thread()
queue: asyncio.Queue = asyncio.Queue(maxsize=200)
self._subs.append(queue)
return queue
def unsubscribe(self, queue: asyncio.Queue) -> None:
with suppress(ValueError):
self._subs.remove(queue)
def close(self) -> None:
"""End every subscriber's stream with a None item."""
for queue in list(self._subs):
put_latest(queue, None)
def since(self, seq: int) -> list[dict[str, Any]]:
"""Return the history after ``seq``.
``deque.copy()`` is one C call, so it is atomic against an append from another thread.
Do not take the lock here: a finalizer that logs on the loop can then wait for the log
handler's lock while a worker that holds it waits for this lock, and the server stops.
"""
return [item for item in self.history.copy() if item["seq"] > seq]
def publish(self, event: str, data: dict[str, Any]) -> None:
"""Record and fan out one event; safe to call from any thread.
The lock is re-entrant because a log call inside it publishes again. ``seq``
moves only after the append, so a reader that sees it also finds the event in history.
"""
with self._lock:
seq = self.seq + 1
item = {"seq": seq, "event": event, "data": data}
self.history.append(item)
self.seq = seq
if not self._subs:
return
on_loop = self._loop is None or threading.current_thread() is self._loop_thread
for queue in list(self._subs):
if on_loop:
_put_drop(queue, item)
else:
assert self._loop is not None
self._loop.call_soon_threadsafe(_put_drop, queue, item)
def _put_drop(queue: asyncio.Queue, item: dict[str, Any]) -> None:
with suppress(asyncio.QueueFull):
queue.put_nowait(item)
def put_latest(queue: asyncio.Queue, item: dict[str, Any] | None) -> None:
"""Enqueue an item, discarding the oldest when a slow listener has filled the queue."""
try:
queue.put_nowait(item)
except asyncio.QueueFull:
with suppress(asyncio.QueueEmpty):
queue.get_nowait()
with suppress(asyncio.QueueFull):
queue.put_nowait(item)
bus = EventBus()
async def close_event_streams(_app: object) -> None:
"""End the dashboard event streams at serve shutdown, so none holds the exit for the shutdown timeout."""
bus.close()
def publish_service_event(action: str, tags: list[str], errors: list[str] | None = None) -> None:
"""Tell dashboard listeners that services were staged, applied, or failed to reload.
Lives here rather than in ``core.services`` so the service loader never imports the API layer.
"""
data: dict[str, Any] = {"action": action, "tags": list(tags)}
if errors:
data["errors"] = list(errors)
bus.publish("service", data)
def publish_refresh_events(repos: list[dict[str, Any]]) -> None:
"""Publish the ``service`` events one ``refresh_and_reload`` result implies.
A tag counts as applied only when it changed, was not deferred, and did not fail to
import - a failed re-import keeps the old module, so calling it applied would be a lie.
"""
from unshackle.core.services import failed_tags
for repo in repos:
failed = failed_tags(repo["load_errors"])
changed = {line[1:] for line in repo["changes"] if line and line[0] in "+~-!"}
applied = sorted(changed - set(repo["deferred"]) - failed)
if applied:
publish_service_event("applied", applied)
if repo["deferred"]:
publish_service_event("staged", repo["deferred"])
if repo["load_errors"]:
publish_service_event("failed", [], errors=repo["load_errors"])