diff --git a/.github/actions/setup-python-env/action.yml b/.github/actions/setup-python-env/action.yml index f27ad235..7932cc78 100644 --- a/.github/actions/setup-python-env/action.yml +++ b/.github/actions/setup-python-env/action.yml @@ -18,25 +18,11 @@ runs: uses: astral-sh/setup-uv@v6 - name: Set up Python ${{ inputs.python-version }} - id: setup-python uses: actions/setup-python@v5 with: python-version: ${{ inputs.python-version }} - - name: Cache virtual environment - uses: actions/cache@v4 - id: cache-venv - with: - path: .venv - # Key on the resolved patch version (e.g. 3.13.14), not just "3.13". - # A venv's bin/ scripts hard-code the interpreter path; when the runner - # bumps its 3.13.x patch the old cached interpreter disappears and the - # restored scripts fail with "cannot execute: required file not found". - key: venv-${{ runner.os }}-py${{ steps.setup-python.outputs.python-version }}-${{ hashFiles('pyproject.toml') }} - - name: Create venv and install dependencies - # Always run: idempotent with uv, and it repairs a restored venv whose - # interpreter path drifted. On a clean cache hit this is a fast no-op. shell: bash run: | uv venv .venv diff --git a/docs/concepts/event-processing.md b/docs/concepts/event-processing.md index efe70816..de836731 100644 --- a/docs/concepts/event-processing.md +++ b/docs/concepts/event-processing.md @@ -234,6 +234,57 @@ default_pubsub_name = "default" "document.summarized" = "documents.processed" ``` +## Broker Startup Resilience + +By default the framework does not require the broker to be reachable when the service starts. The broker connection and topic subscriptions are established in a background task so the application enters a live state immediately, even if the NATS server or Dapr sidecar is temporarily unavailable. + +### Startup sequence + +1. `AppBuilder.build()` completes and the FastAPI application starts. +2. `/health/live` returns `200` immediately — the process is alive. +3. The eventing component attempts to connect and subscribe in the background. +4. Until the connection succeeds, `/health/ready` returns `503` because the underlying client health check reports `unhealthy`. +5. Once the broker is reachable and all subscriptions are established, `/health/ready` returns `200`. + +This behaviour is particularly useful in Kubernetes where Dapr sidecars or NATS may become available a few seconds after the application container starts. + +### Configuration + +```toml +# Retry indefinitely (default) — suitable for Kubernetes where the broker +# eventually becomes available. +event_client_max_retries = -1 +event_client_retry_delay = 5.0 + +# Fail fast after 3 attempts — useful for local development to surface +# misconfiguration quickly. +event_client_max_retries = 3 +event_client_retry_delay = 2.0 +``` + +| Key | Default | Behaviour | +|-----|---------|-----------| +| `event_client_max_retries` | `-1` | `-1` = retry indefinitely. `0` = single attempt. `N` = N retries after the first failure. | +| `event_client_retry_delay` | `5.0` | Seconds between attempts. | + +When all retries are exhausted (i.e. `event_client_max_retries >= 0` and the limit is reached), the error is logged at `ERROR` level with a full traceback. The application remains live but permanently not-ready. + +### Kubernetes probe recommendations + +Because the broker connection is asynchronous, tune the readiness probe to allow enough time for the broker to start: + +```yaml +readinessProbe: + httpGet: + path: /health/ready + port: 8000 + initialDelaySeconds: 10 + periodSeconds: 10 + failureThreshold: 12 # tolerate up to ~2 minutes of broker unavailability +``` + +--- + ## Sessions Transport When `event_bus = "sessions"`, `AppBuilder.build()` wires three components automatically: diff --git a/docs/guides/deployment.md b/docs/guides/deployment.md index 622d3851..d7ec6931 100644 --- a/docs/guides/deployment.md +++ b/docs/guides/deployment.md @@ -297,6 +297,8 @@ Returns a readiness check indicating the application and its dependencies are re Use this for the Kubernetes readiness probe. If this endpoint fails, the pod is removed from the service load balancer until it recovers. +> **Event broker startup**: the broker connection (NATS / Dapr) is established asynchronously after startup. `/health/ready` returns `503` until the broker is reachable and all topic subscriptions are active. Set `failureThreshold` high enough to tolerate the broker's own startup time — see [Broker Startup Resilience](../concepts/event-processing.md#broker-startup-resilience). + ### /health/detailed Returns component-level health status for debugging and monitoring. diff --git a/docs/reference/configuration-keys.md b/docs/reference/configuration-keys.md index 38841476..82d697e6 100644 --- a/docs/reference/configuration-keys.md +++ b/docs/reference/configuration-keys.md @@ -28,6 +28,8 @@ Settings for the event bus transport layer. |-----|------|---------|-------------| | `event_bus` | `str` | `""` | Event bus implementation. Set to `"dapr"` for Dapr pub/sub or `"nats"` for NATS. Empty string disables the event bus. | | `nats_url` | `str` | `"nats://localhost:4222"` | NATS server URL. Only used when `event_bus = "nats"`. | +| `event_client_max_retries` | `int` | `-1` | Number of reconnection attempts if the broker is unavailable at startup. `-1` retries indefinitely until the broker becomes reachable. `0` makes a single attempt and logs a permanent error on failure. | +| `event_client_retry_delay` | `float` | `5.0` | Seconds to wait between reconnection attempts. | --- @@ -125,6 +127,8 @@ log_format = "text" # Event Bus event_bus = "nats" nats_url = "nats://localhost:4222" +event_client_max_retries = -1 # retry indefinitely +event_client_retry_delay = 5.0 # seconds between attempts # Prompts prompt_directory = "prompts" diff --git a/pyproject.toml b/pyproject.toml index 83804938..2a487dc3 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -6,7 +6,7 @@ build-backend = "setuptools.build_meta" [project] name = "avs-blueprint-agents" -version = "0.6.3" +version = "0.6.4" description = "Microservice blueprint for creating agents" authors = [ { name = "Blueprint Team", email = "patrick.maue@bechtle.com" }, diff --git a/src/blueprint/agents/clients/ai/openai_client.py b/src/blueprint/agents/clients/ai/openai_client.py index ce124c3d..944f197c 100644 --- a/src/blueprint/agents/clients/ai/openai_client.py +++ b/src/blueprint/agents/clients/ai/openai_client.py @@ -30,7 +30,7 @@ async def close(self) -> None: await self._client.close() self._client = None - async def subscribe(self, topic: str, callback: Callable[[CloudEvent[Any]], Awaitable[None]]) -> None: + async def subscribe(self, topic_callbacks: dict[str, Callable[[CloudEvent[Any]], Awaitable[None]]]) -> None: logger.warning("OpenAI client does not support subscriptions") async def publish(self, topic: str, event: CloudEvent[Any], routing_key: str | None = None) -> None: diff --git a/src/blueprint/agents/clients/ai/vllm_client.py b/src/blueprint/agents/clients/ai/vllm_client.py index 5048648e..ce8d5d5a 100644 --- a/src/blueprint/agents/clients/ai/vllm_client.py +++ b/src/blueprint/agents/clients/ai/vllm_client.py @@ -38,7 +38,7 @@ async def close(self) -> None: await self._client.close() self._client = None - async def subscribe(self, topic: str, callback: Callable[[CloudEvent[Any]], Awaitable[None]]) -> None: + async def subscribe(self, topic_callbacks: dict[str, Callable[[CloudEvent[Any]], Awaitable[None]]]) -> None: logger.warning("VLLM client does not support subscriptions") async def publish(self, topic: str, event: CloudEvent[Any], routing_key: str | None = None) -> None: diff --git a/src/blueprint/agents/clients/client_base.py b/src/blueprint/agents/clients/client_base.py index c6507dda..6b2720ff 100644 --- a/src/blueprint/agents/clients/client_base.py +++ b/src/blueprint/agents/clients/client_base.py @@ -68,8 +68,13 @@ async def close(self) -> None: raise NotImplementedError @abstractmethod - async def subscribe(self, topic: str, callback: Callable[[CloudEvent[Any]], Awaitable[None]]) -> None: - """Subscribe to a topic with a callback for incoming events.""" + async def subscribe(self, topic_callbacks: dict[str, Callable[[CloudEvent[Any]], Awaitable[None]]]) -> None: + """Register all topic→callback mappings and begin the managed connection + subscription cycle. + + Implementations must be non-blocking: store the mapping and start a + background retry task, then return immediately. The ``subscriptions_ready`` + property reports whether the cycle has completed successfully. + """ raise NotImplementedError @abstractmethod diff --git a/src/blueprint/agents/clients/io/dapr_client.py b/src/blueprint/agents/clients/io/dapr_client.py index 5ae75c69..1ee16dc4 100644 --- a/src/blueprint/agents/clients/io/dapr_client.py +++ b/src/blueprint/agents/clients/io/dapr_client.py @@ -1,5 +1,7 @@ """Dapr client implementation for eventing.""" +import asyncio +import contextlib import json import logging from collections.abc import Awaitable, Callable @@ -19,7 +21,63 @@ class DaprClient(IOClientBase): - """Dapr client for publishing CloudEvents via Dapr pub/sub.""" + """Dapr client for publishing CloudEvents via Dapr pub/sub. + + Managed subscription lifecycle + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + Dapr subscriptions are declarative: the Dapr sidecar calls + ``GET /dapr/subscribe`` to discover topics and then pushes matching + events to ``POST /events/{topic}``. No programmatic subscribe call to + the broker is required. + + ``subscribe(topic_callbacks)`` stores the callback mapping for use by + ``DaprEventing.publish()`` and starts a background retry task that + pings the sidecar until it responds. ``subscriptions_ready`` becomes + ``True`` once the sidecar is confirmed reachable; ``health_check()`` + additionally pings the sidecar on every call so runtime availability is + always reflected. + + Config keys + ~~~~~~~~~~~ + ``event_client_max_retries`` (int, default -1): retries after first + failure; ``-1`` = indefinite, ``0`` = single attempt. + ``event_client_retry_delay`` (float, default 5.0): seconds between retries. + """ + + def __init__(self) -> None: + super().__init__() + self._topic_callbacks: dict[str, Callable[[CloudEvent[Any]], Awaitable[None]]] = {} + self._subscriptions_ready: bool = False + self._subscriptions_managed: bool = False + self._retry_task: asyncio.Task[None] | None = None + + # ------------------------------------------------------------------ + # Public state + # ------------------------------------------------------------------ + + @property + def subscriptions_ready(self) -> bool: + """``True`` once the sidecar was confirmed reachable at startup.""" + return self._subscriptions_ready + + # ------------------------------------------------------------------ + # Managed subscription API + # ------------------------------------------------------------------ + + async def subscribe(self, topic_callbacks: dict[str, Callable[[CloudEvent[Any]], Awaitable[None]]]) -> None: + """Store topic→callback mappings and start the background sidecar-ping retry task. + + Returns immediately; sidecar reachability check happens in the background. + """ + self._topic_callbacks = topic_callbacks + self._subscriptions_managed = True + self._subscriptions_ready = False + self._retry_task = asyncio.ensure_future(self._start_with_retry()) + self._retry_task.add_done_callback(self._on_retry_done) + + # ------------------------------------------------------------------ + # Connection + # ------------------------------------------------------------------ def _is_connected(self) -> bool: return self._client is not None @@ -28,23 +86,23 @@ async def connect(self) -> None: """Initialize the HTTP client for Dapr communication.""" if self._client is not None: return - self._client = httpx.AsyncClient() logger.info("Initialized Dapr client at %s", self.config.get("dapr_url", "http://localhost:3500")) async def close(self) -> None: - """Close the HTTP client.""" + """Cancel the retry task and close the HTTP client.""" + if self._retry_task and not self._retry_task.done(): + self._retry_task.cancel() + with contextlib.suppress(asyncio.CancelledError): + await self._retry_task + if self._client is not None: await self._client.aclose() self._client = None - async def subscribe(self, topic: str, callback: Callable[[CloudEvent[Any]], Awaitable[None]]) -> None: - """Subscribe to a topic. - - Note: Dapr subscriptions are typically configured declaratively, - not programmatically. This method is a no-op. - """ - logger.warning("Dapr subscriptions should be configured declaratively, not via client") + # ------------------------------------------------------------------ + # Publish + # ------------------------------------------------------------------ async def publish( self, @@ -72,12 +130,19 @@ async def publish( logger.error("Failed to publish event to Dapr topic '%s': %s", topic, str(e)) raise + # ------------------------------------------------------------------ + # Health + # ------------------------------------------------------------------ + async def health_check(self) -> ComponentHealth: - """Check Dapr sidecar availability.""" + """Return healthy only when subscriptions are established and sidecar is reachable.""" if not self.config.get("health_check_dapr", True): logger.debug("Dapr health check is disabled") return ComponentHealth(status="healthy", message="Dapr health check disabled") + if self._subscriptions_managed and not self._subscriptions_ready: + return ComponentHealth(status="unhealthy", message="subscriptions not yet established") + dapr_url = self.config.get("dapr_url", "http://localhost:3500") try: client = await self.client @@ -93,3 +158,41 @@ async def health_check(self) -> ComponentHealth: except Exception as e: logger.error("Unexpected error during Dapr health check: %s", e, exc_info=True) return ComponentHealth(status="unhealthy", message=f"Health check error: {e}") + + # ------------------------------------------------------------------ + # Internal — retry loop + # ------------------------------------------------------------------ + + async def _start_with_retry(self) -> None: + max_retries: int = self.config.get("event_client_max_retries", -1) + delay: float = float(self.config.get("event_client_retry_delay", 5.0)) + attempt = 0 + while True: + try: + await self._connect_and_subscribe() + self._subscriptions_ready = True + logger.info("DaprClient connected and sidecar reachable") + return + except Exception as e: + attempt += 1 + self._subscriptions_ready = False + if max_retries != -1 and attempt > max_retries: + raise + logger.warning("DaprClient attempt %d failed, retrying in %.1fs: %s", attempt, delay, e) + await asyncio.sleep(delay) + + def _on_retry_done(self, task: asyncio.Task[None]) -> None: + if task.cancelled(): + return + exc = task.exception() + if exc is not None: + logger.error("DaprClient permanently failed after exhausting retries: %s", exc, exc_info=exc) + + async def _connect_and_subscribe(self) -> None: + """Connect the HTTP client and verify the Dapr sidecar is reachable.""" + await self.connect() + if self.config.get("health_check_dapr", True): + dapr_url = self.config.get("dapr_url", "http://localhost:3500") + client = await self.client + response = await client.get(f"{dapr_url}/v1.0/healthz") + response.raise_for_status() diff --git a/src/blueprint/agents/clients/io/nats_client.py b/src/blueprint/agents/clients/io/nats_client.py index 0c15680c..33f088b0 100644 --- a/src/blueprint/agents/clients/io/nats_client.py +++ b/src/blueprint/agents/clients/io/nats_client.py @@ -1,9 +1,11 @@ """NATS client implementation for eventing.""" +import asyncio +import contextlib import json import logging -from typing import Any from collections.abc import Awaitable, Callable +from typing import Any import nats from nats.aio.client import Client as NatsClient @@ -17,7 +19,27 @@ class NATSClient(IOClientBase): - """NATS client for subscribing to and publishing CloudEvents.""" + """NATS client for subscribing to and publishing CloudEvents. + + Managed subscription lifecycle + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + Call ``subscribe(topic_callbacks)`` once at startup with the full + ``{topic: callback}`` mapping. The client fires a background retry + task that connects to the broker and subscribes to every topic. + ``subscriptions_ready`` becomes ``True`` once all subscriptions are + active; ``health_check()`` reflects this state so the readiness probe + keeps the pod out of service rotation until then. + + On disconnect the NATS library fires ``_on_disconnected``, which clears + the ready flag. On reconnect ``_on_reconnected`` re-subscribes (JetStream + only — Core NATS re-subscribes automatically) and restores the flag. + + Config keys + ~~~~~~~~~~~ + ``event_client_max_retries`` (int, default -1): retries after first failure; + ``-1`` = indefinite, ``0`` = single attempt. + ``event_client_retry_delay`` (float, default 5.0): seconds between retries. + """ def __init__(self) -> None: super().__init__() @@ -25,12 +47,44 @@ def __init__(self) -> None: self._js: JetStreamContext | None = None self._use_jetstream: bool = False self._subscriptions: list[Any] = [] + self._topic_callbacks: dict[str, Callable[[CloudEvent[Any]], Awaitable[None]]] = {} + self._subscriptions_ready: bool = False + self._subscriptions_managed: bool = False + self._retry_task: asyncio.Task[None] | None = None + + # ------------------------------------------------------------------ + # Public state + # ------------------------------------------------------------------ + + @property + def subscriptions_ready(self) -> bool: + """``True`` once all managed subscriptions are active.""" + return self._subscriptions_ready + + # ------------------------------------------------------------------ + # Managed subscription API + # ------------------------------------------------------------------ + + async def subscribe(self, topic_callbacks: dict[str, Callable[[CloudEvent[Any]], Awaitable[None]]]) -> None: + """Register all topic→callback mappings and start the background retry task. + + Returns immediately; connection and subscription happen in the background. + """ + self._topic_callbacks = topic_callbacks + self._subscriptions_managed = True + self._subscriptions_ready = False + self._retry_task = asyncio.ensure_future(self._start_with_retry()) + self._retry_task.add_done_callback(self._on_retry_done) + + # ------------------------------------------------------------------ + # Connection + # ------------------------------------------------------------------ def _is_connected(self) -> bool: return self._nats_client is not None and not self._nats_client.is_closed and self._nats_client.is_connected async def connect(self) -> None: - """Connect to NATS server.""" + """Connect to the NATS server, registering disconnect/reconnect callbacks.""" if self._nats_client is not None and not self._nats_client.is_closed: return @@ -41,6 +95,8 @@ async def connect(self) -> None: max_reconnect_attempts=self.config.get("nats_max_reconnect_attempts", 5), reconnect_time_wait=self.config.get("nats_reconnect_time_wait", 2), connect_timeout=10, + disconnected_cb=self._on_disconnected, + reconnected_cb=self._on_reconnected, ) self._client = self._nats_client self._use_jetstream = self.config.get("nats_use_jetstream", False) @@ -59,10 +115,16 @@ async def connect(self) -> None: raise async def close(self) -> None: - """Close NATS connection and clean up resources.""" + """Cancel the retry task, unsubscribe all topics, and close the connection.""" + if self._retry_task and not self._retry_task.done(): + self._retry_task.cancel() + with contextlib.suppress(asyncio.CancelledError): + await self._retry_task + if self._nats_client is not None: for sub in self._subscriptions: - await sub.unsubscribe() + with contextlib.suppress(Exception): + await sub.unsubscribe() self._subscriptions.clear() await self._nats_client.close() @@ -70,8 +132,92 @@ async def close(self) -> None: self._js = None self._client = None - async def subscribe(self, topic: str, callback: Callable[[CloudEvent[Any]], Awaitable[None]]) -> None: - """Subscribe to a topic and call callback with parsed CloudEvents.""" + # ------------------------------------------------------------------ + # Publish + # ------------------------------------------------------------------ + + async def publish(self, topic: str, event: CloudEvent[Any], routing_key: str | None = None) -> None: + """Publish a CloudEvent to a topic. + + Args: + topic: The topic, used for event routing. + event: The CloudEvent to publish. + routing_key: Ignored — NATS does not use routing keys. + """ + client = await self.client + + try: + event_data = json.dumps(dict(event)).encode() + + if self._use_jetstream and client.jetstream(): + ack = await client.jetstream().publish(topic, event_data) + logger.debug("Published event to JetStream topic '%s' (seq: %d): %s", topic, ack.seq, event.id) + else: + await client.publish(topic, event_data) + logger.debug("Published event to Core NATS topic '%s': %s", topic, event.id) + + except Exception as e: + logger.error("Failed to publish event to topic '%s': %s", topic, str(e)) + raise + + # ------------------------------------------------------------------ + # Health + # ------------------------------------------------------------------ + + async def health_check(self) -> ComponentHealth: + """Return healthy only when connected and all managed subscriptions are active.""" + if not self._is_connected(): + return ComponentHealth(status="unhealthy", message="NATS client not connected") + if self._subscriptions_managed and not self._subscriptions_ready: + return ComponentHealth(status="unhealthy", message="connected but subscriptions not yet established") + server_info = self._nats_client.connected_url # type: ignore[union-attr] + sub_info = f" ({len(self._subscriptions)} subscriptions active)" if self._subscriptions else "" + return ComponentHealth(status="healthy", message=f"Connected to NATS server at {server_info}{sub_info}") + + # ------------------------------------------------------------------ + # Internal — retry loop + # ------------------------------------------------------------------ + + async def _start_with_retry(self) -> None: + max_retries: int = self.config.get("event_client_max_retries", -1) + delay: float = float(self.config.get("event_client_retry_delay", 5.0)) + attempt = 0 + while True: + try: + await self._connect_and_subscribe() + self._subscriptions_ready = True + logger.info("NATSClient connected and subscribed successfully") + return + except Exception as e: + attempt += 1 + self._subscriptions_ready = False + if max_retries != -1 and attempt > max_retries: + raise + logger.warning("NATSClient attempt %d failed, retrying in %.1fs: %s", attempt, delay, e) + await asyncio.sleep(delay) + + def _on_retry_done(self, task: asyncio.Task[None]) -> None: + if task.cancelled(): + return + exc = task.exception() + if exc is not None: + logger.error("NATSClient permanently failed to connect after exhausting retries: %s", exc, exc_info=exc) + + async def _connect_and_subscribe(self) -> None: + await self.connect() + # Clean up any partial subscriptions from a previous failed attempt + for sub in self._subscriptions: + with contextlib.suppress(Exception): + await sub.unsubscribe() + self._subscriptions.clear() + for topic, callback in self._topic_callbacks.items(): + await self._subscribe_one(topic, callback) + + # ------------------------------------------------------------------ + # Internal — per-topic subscription + # ------------------------------------------------------------------ + + async def _subscribe_one(self, topic: str, callback: Callable[[CloudEvent[Any]], Awaitable[None]]) -> None: client = await self.client async def message_handler(msg: Any) -> None: @@ -110,34 +256,27 @@ async def message_handler(msg: Any) -> None: logger.error("Failed to subscribe to topic '%s': %s", topic, str(e)) raise - async def publish(self, topic: str, event: CloudEvent[Any], routing_key: str | None = None) -> None: - """Publish a CloudEvent to a topic. - - Args: - topic: The topic, used for event routing. - event: The CloudEvent to publish. - routing_key: Ignored — NATS does not use routing keys - """ - client = await self.client - - try: - event_data = json.dumps(dict(event)).encode() + # ------------------------------------------------------------------ + # Internal — reconnect callbacks + # ------------------------------------------------------------------ - if self._use_jetstream and client.jetstream(): - ack = await client.jetstream().publish(topic, event_data) - logger.debug("Published event to JetStream topic '%s' (seq: %d): %s", topic, ack.seq, event.id) - else: - await client.publish(topic, event_data) - logger.debug("Published event to Core NATS topic '%s': %s", topic, event.id) + async def _on_disconnected(self) -> None: + self._subscriptions_ready = False + logger.warning("NATSClient disconnected") - except Exception as e: - logger.error("Failed to publish event to topic '%s': %s", topic, str(e)) - raise - - async def health_check(self) -> ComponentHealth: - """Check the health of the NATS connection.""" - if self._nats_client and not self._nats_client.is_closed and self._nats_client.is_connected: - server_info = self._nats_client.connected_url - return ComponentHealth(status="healthy", message=f"Connected to NATS server at {server_info}") - else: - return ComponentHealth(status="unhealthy", message="NATS client not connected") + async def _on_reconnected(self) -> None: + logger.info("NATSClient reconnected") + if not self._subscriptions_managed: + return + if self._use_jetstream and self._topic_callbacks: + # JetStream durable consumers do not survive reconnects; re-subscribe manually. + # Core NATS re-subscribes automatically via the client library. + self._subscriptions.clear() + try: + for topic, callback in self._topic_callbacks.items(): + await self._subscribe_one(topic, callback) + except Exception as e: + logger.error("NATSClient failed to re-establish JetStream subscriptions after reconnect: %s", e) + return + self._subscriptions_ready = True + logger.info("NATSClient subscriptions ready after reconnect") diff --git a/src/blueprint/agents/io/api/eventing/dapr.py b/src/blueprint/agents/io/api/eventing/dapr.py index d7511b98..80567c8d 100644 --- a/src/blueprint/agents/io/api/eventing/dapr.py +++ b/src/blueprint/agents/io/api/eventing/dapr.py @@ -1,6 +1,7 @@ """Generic Dapr pub/sub endpoints for the agent service (framework-level).""" import logging +from collections.abc import Awaitable, Callable from typing import Any from fastapi import HTTPException, status @@ -16,44 +17,64 @@ class DaprEventing(EventHandlingBase): - """Encapsulates all Dapr-related endpoints and logic.""" + """Implements event handling using Dapr pub/sub. + + Dapr subscriptions are declarative: the sidecar discovers topics via + ``GET /dapr/subscribe`` and pushes events to ``POST /events/{topic}``. + + ``on_startup`` stores the topic→callback mapping in ``DaprClient`` and + starts a background retry task that pings the sidecar until it responds. + The client tracks ``subscriptions_ready`` and exposes it via + ``health_check()`` so the readiness probe reflects sidecar availability. + """ def __init__(self) -> None: super().__init__(should_register=False) self._client: DaprClient | None = None async def on_startup(self) -> None: - """Fetch the registered DaprClient from the registry.""" self._client = self.registry.get_component(DaprClient) + topic_callbacks: dict[str, Callable[[CloudEvent[Any]], Awaitable[None]]] = {} + for handler in self.registry.get_event_handler(): + for topic in handler.get_subscribed_topics(): + if topic and topic not in topic_callbacks: + topic_callbacks[topic] = self._make_event_callback(topic) + + if topic_callbacks: + await self._client.subscribe(topic_callbacks) + else: + logger.info("DaprEventing: no subscriptions configured") + async def on_shutdown(self) -> None: - """No shutdown actions required — DaprClient lifecycle is managed separately.""" + pass + + def _make_event_callback(self, topic: str) -> Callable[[CloudEvent[Any]], Awaitable[None]]: + """Return an async callback that routes an incoming Dapr event through the handler chain.""" + + async def _process_event(event: CloudEvent[Any]) -> None: + try: + context = {"dapr_topic": topic} + await self._process_cloud_event(event, context) + except Exception as exc: + logger.error("Event processing failed on topic %s: %s", topic, str(exc), exc_info=True) + + return _process_event @RestApiBase.get("/dapr/subscribe", tags=["dapr"]) async def subscribe(self, topic: str, queue_group: str | None = None) -> dict[str, Any]: - """ - Dapr subscription discovery endpoint. + """Dapr subscription discovery endpoint. - Implementations can override this by adding their own router with the same - path to provide real topics and routes. - - Note: this complements subscription resources defined in kubernetes - (you can choose your approach) + The Dapr sidecar calls this at startup to learn which topics to route + to this service. Override in user code to declare real subscriptions. + Note: subscriptions can also be defined via Kubernetes resources. """ - - # Framework default: no subscriptions declared. - # Example structure: - # return [ - # {"pubsubname": "pubsub", "topic": "events.topic1", "route": "/events/topic1"} - # ] return {} @RestApiBase.post("/events/{topic}", tags=["dapr"]) async def publish(self, topic: str, cloud_event: CloudEvent[Any]) -> dict[str, Any]: - """ - Generic Dapr event handler that processes events through the unified service. - """ + """Generic Dapr event handler that processes events through the unified service.""" try: context = { @@ -62,7 +83,6 @@ async def publish(self, topic: str, cloud_event: CloudEvent[Any]) -> dict[str, A processing_result = await self._process_cloud_event(cloud_event, context) - # Return Dapr-compatible response based on result status if processing_result.status == ProcessingStatus.PROCESSED: return {"status": "SUCCESS"} @@ -75,39 +95,19 @@ async def publish(self, topic: str, cloud_event: CloudEvent[Any]) -> dict[str, A return {"status": "RETRY", "reason": failure_reason} except RetryableHandlerError as exc: - logger.error( - "Retrying message for topic %s: %s", - topic, - str(exc), - exc_info=True, - ) + logger.error("Retrying message for topic %s: %s", topic, str(exc), exc_info=True) return {"status": "RETRY", "reason": exc.reason} except InvalidEventError as exc: - logger.error( - "Dropping message for topic %s: %s", - topic, - str(exc), - exc_info=True, - ) + logger.error("Dropping message for topic %s: %s", topic, str(exc), exc_info=True) return {"status": "DROP", "reason": exc.reason} except CriticalHandlerError as exc: - logger.error( - "Critical error for topic %s: %s", - topic, - str(exc), - exc_info=True, - ) + logger.error("Critical error for topic %s: %s", topic, str(exc), exc_info=True) return {"status": "RETRY", "reason": exc.reason} except Exception as exc: # pragma: no cover - integration behaviour - logger.error( - "Processing service failed for Dapr topic %s: %s", - topic, - str(exc), - exc_info=True, - ) + logger.error("Processing service failed for Dapr topic %s: %s", topic, str(exc), exc_info=True) raise HTTPException( status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail="Dapr event handling failed", diff --git a/src/blueprint/agents/io/api/eventing/event_handling_base.py b/src/blueprint/agents/io/api/eventing/event_handling_base.py index 18c159c2..4c3c6b91 100644 --- a/src/blueprint/agents/io/api/eventing/event_handling_base.py +++ b/src/blueprint/agents/io/api/eventing/event_handling_base.py @@ -22,6 +22,11 @@ class EventHandlingBase(RestApiBase, CloudEventProcessorMixin, ABC): Combines REST API routing (RestApiBase) with CloudEvent processing (CloudEventProcessorMixin) and adds structured error-handling and logging around the dispatch pipeline. + + Transport connection, topic subscriptions, and retry logic live entirely + in the transport client (NATSClient, DaprClient). Subclasses implement + ``on_startup`` to wire the client's managed subscription flow and declare + their own REST endpoints via concrete ``publish`` implementations. """ @traced("topic", "cloud_event") @@ -29,18 +34,12 @@ async def handle_event(self, topic: str, cloud_event: CloudEvent[Any]) -> dict[s processing_result = await self._process_cloud_event(cloud_event, {"topic": topic}) if processing_result.status == ProcessingStatus.PROCESSED: return {"status": "SUCCESS"} - else: - failure_reason = processing_result.message or processing_result.status.value or "unknown_status" - return {"status": "RETRY", "reason": failure_reason} + failure_reason = processing_result.message or processing_result.status.value or "unknown_status" + return {"status": "RETRY", "reason": failure_reason} @abstractmethod async def publish(self, topic: str, event: CloudEvent[Any]) -> dict[str, Any]: - """Abstract method for publishing events (output)""" - raise NotImplementedError() - - @abstractmethod - async def subscribe(self, topic: str, queue_group: str | None = None) -> dict[str, Any]: - """Abstract method for subscribing for events (input)""" + """Publish a CloudEvent to the broker (output path).""" raise NotImplementedError() async def _process_cloud_event( @@ -48,21 +47,10 @@ async def _process_cloud_event( cloud_event: CloudEvent[Any], context: dict[str, Any], ) -> ProcessingResult: - """Process a CloudEvent with error handling and logging. - - Wraps ``_dispatch_cloud_event`` with structured logging and exception - handling for the four known error types. All exceptions are re-raised - after logging. - - Args: - cloud_event: The CloudEvent to process - context: Additional context for processing - - Returns: - The processing result + """Dispatch a CloudEvent with structured error-handling and logging. - Raises: - Exception: Re-raises all exceptions after logging + Wraps ``_dispatch_cloud_event`` and re-raises all exceptions after + logging them at the appropriate level. """ try: logger.debug("Processing CloudEvent: %s", cloud_event.id) diff --git a/src/blueprint/agents/io/api/eventing/nats.py b/src/blueprint/agents/io/api/eventing/nats.py index 319f0700..4b86bc0c 100644 --- a/src/blueprint/agents/io/api/eventing/nats.py +++ b/src/blueprint/agents/io/api/eventing/nats.py @@ -1,6 +1,7 @@ """NATS eventing implementation using NATSClient.""" import logging +from collections.abc import Awaitable, Callable from typing import Any from ....clients.io.nats_client import NATSClient @@ -13,80 +14,40 @@ class NatsEventing(EventHandlingBase): - """Implements event handling using NATS via NATSClient.""" + """Implements event handling using NATS via NATSClient. + + ``on_startup`` collects the full topic→callback mapping from all registered + handlers and config, then hands it to ``NATSClient.subscribe()``. The client + owns connection, retry, reconnect, and subscription-readiness tracking. + """ def __init__(self) -> None: super().__init__(should_register=False) self._client: NATSClient | None = None async def on_startup(self) -> None: - """Fetch the registered NATSClient and auto-subscribe to declared topics. - - Topics are collected from two sources (handler-declared topics first, - then config-declared topics). Duplicates are silently dropped — the - first occurrence wins, so handler declarations take priority. - """ self._client = self.registry.get_component(NATSClient) - seen: dict[str, None] = {} + topic_callbacks: dict[str, Callable[[CloudEvent[Any]], Awaitable[None]]] = {} for handler in self.registry.get_event_handler(): for topic in handler.get_subscribed_topics(): - if topic and topic not in seen: - seen[topic] = None + if topic and topic not in topic_callbacks: + topic_callbacks[topic] = self._make_event_callback(topic) for topic in self.config.get_nats_subscription_config(): - if topic and topic not in seen: - seen[topic] = None + if topic and topic not in topic_callbacks: + topic_callbacks[topic] = self._make_event_callback(topic) - if not seen: + if topic_callbacks: + await self._client.subscribe(topic_callbacks) + else: logger.info("NatsEventing: no auto-subscriptions configured") - return - - for topic in seen: - await self._subscribe_to_topic(topic) - - async def _subscribe_to_topic(self, topic: str) -> None: - """Subscribe to a single NATS topic using the standard processing callback. - - Extracted as a method so the closure correctly captures ``topic`` by - value at call time, avoiding the loop late-binding pitfall. - """ - if not self._client: - raise RuntimeError("NATS client not initialized") - - async def _process_event(event: CloudEvent[Any]) -> None: - try: - context = {"nats_topic": topic} - processing_result = await self._process_cloud_event(event, context) - logger.debug( - "Processed CloudEvent %s on topic %s with status %s", - event.id, - topic, - processing_result.status.value, - ) - except (RetryableHandlerError, InvalidEventError, CriticalHandlerError) as exc: - logger.error("Event processing failed: %s", str(exc), exc_info=True) - - await self._client.subscribe(topic, _process_event) - logger.info("NatsEventing: auto-subscribed to topic '%s'", topic) async def on_shutdown(self) -> None: - """No shutdown actions required — NATSClient lifecycle is managed separately.""" + pass - @RestApiBase.post("/nats/subscribe/{topic}", tags=["nats"]) - async def subscribe(self, topic: str, queue_group: str | None = None) -> dict[str, Any]: - """Subscribe to a NATS topic. - - Args: - topic: The topic to subscribe to - queue_group: Optional queue group - - Returns: - Success message - """ - if not self._client: - raise RuntimeError("NATS client not initialized") + def _make_event_callback(self, topic: str) -> Callable[[CloudEvent[Any]], Awaitable[None]]: + """Return an async callback that routes an incoming event through the handler chain.""" - # Callback to process incoming events async def _process_event(event: CloudEvent[Any]) -> None: try: context = {"nats_topic": topic} @@ -99,21 +60,19 @@ async def _process_event(event: CloudEvent[Any]) -> None: ) except (RetryableHandlerError, InvalidEventError, CriticalHandlerError) as exc: logger.error("Event processing failed: %s", str(exc), exc_info=True) - # NATS handles retries/acks via client - await self._client.subscribe(topic, _process_event) - return {"message": f"Subscribed to topic {topic}"} + return _process_event @RestApiBase.post("/events/{topic}", tags=["nats"]) async def publish(self, topic: str, event: CloudEvent[Any]) -> dict[str, Any]: """Publish a CloudEvent to a NATS topic. Args: - topic: The topic to publish to - event: The CloudEvent to publish + topic: The topic to publish to. + event: The CloudEvent to publish. Returns: - Success message + Success message. """ if not self._client: raise RuntimeError("NATS client not initialized") diff --git a/tests/unit/agents/clients/ai/test_openai_client.py b/tests/unit/agents/clients/ai/test_openai_client.py index bb961076..e8e999b8 100644 --- a/tests/unit/agents/clients/ai/test_openai_client.py +++ b/tests/unit/agents/clients/ai/test_openai_client.py @@ -36,7 +36,7 @@ async def test_close_is_safe_when_client_already_none(self, openai_client: OpenA class TestOpenAIClientPubSub: async def test_subscribe_is_noop(self, openai_client: OpenAIClient) -> None: - await openai_client.subscribe("topic", AsyncMock()) # must not raise + await openai_client.subscribe({"topic": AsyncMock()}) # must not raise async def test_publish_is_noop(self, openai_client: OpenAIClient) -> None: await openai_client.publish("topic", MagicMock()) # must not raise diff --git a/tests/unit/agents/clients/ai/test_vllm_client.py b/tests/unit/agents/clients/ai/test_vllm_client.py index 25c73575..a4515534 100644 --- a/tests/unit/agents/clients/ai/test_vllm_client.py +++ b/tests/unit/agents/clients/ai/test_vllm_client.py @@ -36,7 +36,7 @@ async def test_close_is_safe_when_client_already_none(self, vllm_client: VLLMCli class TestVLLMClientPubSub: async def test_subscribe_is_noop(self, vllm_client: VLLMClient) -> None: - await vllm_client.subscribe("topic", AsyncMock()) + await vllm_client.subscribe({"topic": AsyncMock()}) async def test_publish_is_noop(self, vllm_client: VLLMClient) -> None: await vllm_client.publish("topic", MagicMock()) diff --git a/tests/unit/agents/clients/io/test_dapr_client.py b/tests/unit/agents/clients/io/test_dapr_client.py index bf8f95e1..0fc58ee9 100644 --- a/tests/unit/agents/clients/io/test_dapr_client.py +++ b/tests/unit/agents/clients/io/test_dapr_client.py @@ -1,6 +1,7 @@ """Unit tests for DaprClient.""" import json +import logging from unittest.mock import AsyncMock, MagicMock, patch import httpx @@ -38,10 +39,35 @@ async def test_close_calls_aclose_and_clears_client(self, connected_dapr_client: async def test_close_is_safe_when_client_none(self, dapr_client: DaprClient) -> None: await dapr_client.close() # must not raise + async def test_close_cancels_retry_task(self, dapr_client: DaprClient) -> None: + import asyncio + + async def _never() -> None: + await asyncio.sleep(9999) + + task = asyncio.create_task(_never()) + dapr_client._retry_task = task + await dapr_client.close() + assert task.cancelled() + class TestDaprClientSubscribe: - async def test_subscribe_logs_warning_and_does_not_raise(self, connected_dapr_client: DaprClient) -> None: - await connected_dapr_client.subscribe("topic", AsyncMock()) + async def test_subscribe_stores_mapping_and_starts_task(self, dapr_client: DaprClient) -> None: + callback = AsyncMock() + with patch.object(dapr_client, "_start_with_retry", new_callable=AsyncMock) as mock_retry: + await dapr_client.subscribe({"topic.a": callback}) + assert dapr_client._topic_callbacks == {"topic.a": callback} + assert dapr_client._subscriptions_managed is True + mock_retry.assert_called_once() # coroutine was created and scheduled, not directly awaited + + async def test_subscribe_returns_immediately(self, dapr_client: DaprClient) -> None: + with patch.object(dapr_client, "_start_with_retry", new_callable=AsyncMock): + await dapr_client.subscribe({"t": AsyncMock()}) + + async def test_subscriptions_ready_false_before_retry_completes(self, dapr_client: DaprClient) -> None: + with patch.object(dapr_client, "_start_with_retry", new_callable=AsyncMock): + await dapr_client.subscribe({"t": AsyncMock()}) + assert dapr_client.subscriptions_ready is False class TestDaprClientPublish: @@ -140,3 +166,96 @@ async def test_healthy_when_health_check_disabled(self, dapr_client: DaprClient, result = await dapr_client.health_check() assert result.status == "healthy" assert "disabled" in result.message + + async def test_unhealthy_when_subscriptions_managed_but_not_ready(self, connected_dapr_client: DaprClient) -> None: + connected_dapr_client._subscriptions_managed = True + connected_dapr_client._subscriptions_ready = False + result = await connected_dapr_client.health_check() + assert result.status == "unhealthy" + assert "subscriptions" in result.message + + async def test_healthy_when_subscriptions_ready_and_sidecar_up( + self, connected_dapr_client: DaprClient, mock_httpx_client: MagicMock + ) -> None: + connected_dapr_client._subscriptions_managed = True + connected_dapr_client._subscriptions_ready = True + result = await connected_dapr_client.health_check() + assert result.status == "healthy" + + +class TestDaprClientRetryLoop: + async def test_success_on_first_attempt_sets_ready(self, dapr_client: DaprClient) -> None: + dapr_client._subscriptions_managed = True + with patch.object(dapr_client, "_connect_and_subscribe", new_callable=AsyncMock): + await dapr_client._start_with_retry() + assert dapr_client.subscriptions_ready is True + + async def test_max_retries_zero_raises_immediately_on_failure(self, dapr_client: DaprClient, mock_config: MagicMock) -> None: + mock_config.get.side_effect = lambda k, d=None: {"event_client_max_retries": 0, "event_client_retry_delay": 0.0}.get(k, d) + dapr_client._subscriptions_managed = True + with patch.object(dapr_client, "_connect_and_subscribe", new_callable=AsyncMock, side_effect=OSError("refused")): + with pytest.raises(OSError): + await dapr_client._start_with_retry() + assert dapr_client.subscriptions_ready is False + + async def test_max_retries_2_calls_connect_three_times_then_raises(self, dapr_client: DaprClient, mock_config: MagicMock) -> None: + mock_config.get.side_effect = lambda k, d=None: {"event_client_max_retries": 2, "event_client_retry_delay": 0.0}.get(k, d) + dapr_client._subscriptions_managed = True + mock_connect = AsyncMock(side_effect=OSError("refused")) + with patch.object(dapr_client, "_connect_and_subscribe", mock_connect): + with pytest.raises(OSError): + await dapr_client._start_with_retry() + assert mock_connect.await_count == 3 + + async def test_max_retries_2_succeeds_on_third_attempt(self, dapr_client: DaprClient, mock_config: MagicMock) -> None: + mock_config.get.side_effect = lambda k, d=None: {"event_client_max_retries": 2, "event_client_retry_delay": 0.0}.get(k, d) + dapr_client._subscriptions_managed = True + mock_connect = AsyncMock(side_effect=[OSError("fail"), OSError("fail"), None]) + with patch.object(dapr_client, "_connect_and_subscribe", mock_connect): + await dapr_client._start_with_retry() + assert mock_connect.await_count == 3 + assert dapr_client.subscriptions_ready is True + + async def test_done_callback_logs_error_on_permanent_failure(self, dapr_client: DaprClient) -> None: + task = MagicMock() + task.cancelled.return_value = False + task.exception.return_value = OSError("final failure") + with patch.object(logging.getLogger("blueprint.agents.clients.io.dapr_client"), "error") as mock_log: + dapr_client._on_retry_done(task) + mock_log.assert_called_once() + + async def test_done_callback_silent_on_cancellation(self, dapr_client: DaprClient) -> None: + task = MagicMock() + task.cancelled.return_value = True + with patch.object(logging.getLogger("blueprint.agents.clients.io.dapr_client"), "error") as mock_log: + dapr_client._on_retry_done(task) + mock_log.assert_not_called() + + async def test_connect_and_subscribe_pings_sidecar( + self, dapr_client: DaprClient, mock_config: MagicMock, mock_httpx_client: MagicMock + ) -> None: + mock_config.get.side_effect = lambda k, d=None: { + "health_check_dapr": True, + "dapr_url": "http://localhost:3500", + }.get(k, d) + dapr_client._client = mock_httpx_client + await dapr_client._connect_and_subscribe() + mock_httpx_client.get.assert_awaited_once_with("http://localhost:3500/v1.0/healthz") + + async def test_sidecar_unreachable_leaves_ready_false( + self, dapr_client: DaprClient, mock_config: MagicMock, mock_httpx_client: MagicMock + ) -> None: + """Sidecar ping fails → _connect_and_subscribe raises → subscriptions_ready stays False.""" + mock_config.get.side_effect = lambda k, d=None: { + "event_client_max_retries": 0, + "event_client_retry_delay": 0.0, + "health_check_dapr": True, + "dapr_url": "http://localhost:3500", + }.get(k, d) + mock_httpx_client.get.return_value.raise_for_status.side_effect = Exception("503") + dapr_client._client = mock_httpx_client + dapr_client._subscriptions_managed = True + with patch.object(dapr_client, "_connect_and_subscribe", side_effect=OSError("sidecar down")): + with pytest.raises(OSError): + await dapr_client._start_with_retry() + assert dapr_client.subscriptions_ready is False diff --git a/tests/unit/agents/clients/io/test_nats_client.py b/tests/unit/agents/clients/io/test_nats_client.py index cffb2037..bbe6bf53 100644 --- a/tests/unit/agents/clients/io/test_nats_client.py +++ b/tests/unit/agents/clients/io/test_nats_client.py @@ -1,5 +1,6 @@ """Unit tests for NATSClient.""" +import asyncio import json from unittest.mock import AsyncMock, MagicMock, patch @@ -22,6 +23,12 @@ def test_use_jetstream_initialises_as_false(self, nats_client: NATSClient) -> No def test_subscriptions_initialises_as_empty_list(self, nats_client: NATSClient) -> None: assert nats_client._subscriptions == [] + def test_subscriptions_ready_initialises_as_false(self, nats_client: NATSClient) -> None: + assert nats_client.subscriptions_ready is False + + def test_subscriptions_managed_initialises_as_false(self, nats_client: NATSClient) -> None: + assert nats_client._subscriptions_managed is False + class TestNATSClientIsConnected: def test_false_when_nats_client_none(self, nats_client: NATSClient) -> None: @@ -59,6 +66,18 @@ async def test_connect_calls_nats_connect_with_url(self, nats_client: NATSClient mock_connect.assert_awaited_once() assert mock_connect.call_args[0][0] == "nats://localhost:4222" + async def test_connect_passes_disconnect_and_reconnect_callbacks(self, nats_client: NATSClient) -> None: + mock_nc = MagicMock(is_closed=False, is_connected=True) + mock_nc.jetstream = MagicMock(return_value=None) + with patch("blueprint.agents.clients.io.nats_client.nats.connect", new_callable=AsyncMock) as mock_connect: + mock_connect.return_value = mock_nc + await nats_client.connect() + kwargs = mock_connect.call_args[1] + assert callable(kwargs["disconnected_cb"]) + assert kwargs["disconnected_cb"].__func__.__name__ == "_on_disconnected" + assert callable(kwargs["reconnected_cb"]) + assert kwargs["reconnected_cb"].__func__.__name__ == "_on_reconnected" + async def test_connect_sets_nats_client_and_client(self, nats_client: NATSClient) -> None: mock_nc = MagicMock(is_closed=False, is_connected=True) mock_nc.jetstream = MagicMock(return_value=None) @@ -125,6 +144,17 @@ async def test_close_clears_client_references(self, connected_nats_client: NATSC assert connected_nats_client._client is None assert connected_nats_client._js is None + async def test_close_cancels_retry_task(self, nats_client: NATSClient) -> None: + + async def _never() -> None: + await asyncio.sleep(9999) + + task = asyncio.create_task(_never()) + nats_client._retry_task = task + nats_client._nats_client = None + await nats_client.close() + assert task.cancelled() + class TestNATSClientPublish: async def test_publish_sends_json_encoded_event_via_core_nats( @@ -170,7 +200,7 @@ async def test_publish_raises_on_nats_error( class TestNATSClientHealthCheck: - async def test_healthy_when_connected(self, connected_nats_client: NATSClient) -> None: + async def test_healthy_when_connected_without_managed_subscriptions(self, connected_nats_client: NATSClient) -> None: result = await connected_nats_client.health_check() assert result.status == "healthy" @@ -187,3 +217,146 @@ async def test_unhealthy_when_client_closed(self, nats_client: NATSClient) -> No nats_client._nats_client = mock_nc result = await nats_client.health_check() assert result.status == "unhealthy" + + async def test_unhealthy_when_connected_but_subscriptions_not_ready(self, connected_nats_client: NATSClient) -> None: + connected_nats_client._subscriptions_managed = True + connected_nats_client._subscriptions_ready = False + result = await connected_nats_client.health_check() + assert result.status == "unhealthy" + assert "subscriptions" in result.message + + async def test_healthy_when_connected_and_subscriptions_ready(self, connected_nats_client: NATSClient) -> None: + connected_nats_client._subscriptions_managed = True + connected_nats_client._subscriptions_ready = True + result = await connected_nats_client.health_check() + assert result.status == "healthy" + + +class TestNATSClientManagedSubscriptions: + async def test_subscribe_stores_mapping_and_starts_task(self, nats_client: NATSClient) -> None: + callback = AsyncMock() + with patch.object(nats_client, "_start_with_retry", new_callable=AsyncMock) as mock_retry: + await nats_client.subscribe({"topic.a": callback}) + assert nats_client._topic_callbacks == {"topic.a": callback} + assert nats_client._subscriptions_managed is True + mock_retry.assert_called_once() # coroutine was created and scheduled, not directly awaited + + async def test_subscribe_returns_immediately(self, nats_client: NATSClient) -> None: + """subscribe() must be non-blocking — the retry runs as a background task.""" + with patch.object(nats_client, "_start_with_retry", new_callable=AsyncMock): + await nats_client.subscribe({"t": AsyncMock()}) + # reaching here means subscribe() returned without awaiting the retry + + async def test_subscriptions_ready_false_before_retry_completes(self, nats_client: NATSClient) -> None: + with patch.object(nats_client, "_start_with_retry", new_callable=AsyncMock): + await nats_client.subscribe({"t": AsyncMock()}) + assert nats_client.subscriptions_ready is False + + +class TestNATSClientRetryLoop: + async def test_success_on_first_attempt_sets_ready(self, nats_client: NATSClient) -> None: + nats_client._subscriptions_managed = True + with patch.object(nats_client, "_connect_and_subscribe", new_callable=AsyncMock): + await nats_client._start_with_retry() + assert nats_client.subscriptions_ready is True + + async def test_max_retries_zero_raises_immediately_on_failure(self, nats_client: NATSClient, mock_config: MagicMock) -> None: + mock_config.get.side_effect = lambda k, d=None: {"event_client_max_retries": 0, "event_client_retry_delay": 0.0}.get(k, d) + nats_client._subscriptions_managed = True + with patch.object(nats_client, "_connect_and_subscribe", new_callable=AsyncMock, side_effect=OSError("refused")): + with pytest.raises(OSError, match="refused"): + await nats_client._start_with_retry() + assert nats_client.subscriptions_ready is False + + async def test_max_retries_2_calls_connect_three_times_then_raises(self, nats_client: NATSClient, mock_config: MagicMock) -> None: + mock_config.get.side_effect = lambda k, d=None: {"event_client_max_retries": 2, "event_client_retry_delay": 0.0}.get(k, d) + nats_client._subscriptions_managed = True + mock_connect = AsyncMock(side_effect=OSError("refused")) + with patch.object(nats_client, "_connect_and_subscribe", mock_connect): + with pytest.raises(OSError): + await nats_client._start_with_retry() + assert mock_connect.await_count == 3 + + async def test_max_retries_2_succeeds_on_third_attempt(self, nats_client: NATSClient, mock_config: MagicMock) -> None: + mock_config.get.side_effect = lambda k, d=None: {"event_client_max_retries": 2, "event_client_retry_delay": 0.0}.get(k, d) + nats_client._subscriptions_managed = True + mock_connect = AsyncMock(side_effect=[OSError("fail"), OSError("fail"), None]) + with patch.object(nats_client, "_connect_and_subscribe", mock_connect): + await nats_client._start_with_retry() + assert mock_connect.await_count == 3 + assert nats_client.subscriptions_ready is True + + async def test_done_callback_logs_error_on_permanent_failure(self, nats_client: NATSClient) -> None: + task = MagicMock() + task.cancelled.return_value = False + task.exception.return_value = OSError("final failure") + import logging + + with patch.object(logging.getLogger("blueprint.agents.clients.io.nats_client"), "error") as mock_log: + nats_client._on_retry_done(task) + mock_log.assert_called_once() + + async def test_done_callback_silent_on_cancellation(self, nats_client: NATSClient) -> None: + task = MagicMock() + task.cancelled.return_value = True + import logging + + with patch.object(logging.getLogger("blueprint.agents.clients.io.nats_client"), "error") as mock_log: + nats_client._on_retry_done(task) + mock_log.assert_not_called() + + async def test_broker_connects_but_subscription_fails_leaves_ready_false(self, nats_client: NATSClient, mock_config: MagicMock) -> None: + """Connect succeeds; subscribe raises — readiness must stay False.""" + mock_config.get.side_effect = lambda k, d=None: {"event_client_max_retries": 0, "event_client_retry_delay": 0.0}.get(k, d) + nats_client._subscriptions_managed = True + + async def connect_ok_subscribe_fails() -> None: + # Simulate a successful broker connect without a real network call + nats_client._nats_client = MagicMock(is_closed=False, is_connected=True) + nats_client._client = nats_client._nats_client + raise OSError("subscription failed") + + with patch.object(nats_client, "_connect_and_subscribe", side_effect=connect_ok_subscribe_fails): + with pytest.raises(OSError): + await nats_client._start_with_retry() + assert nats_client.subscriptions_ready is False + + +class TestNATSClientReconnect: + async def test_disconnected_callback_clears_ready_flag(self, connected_nats_client: NATSClient) -> None: + connected_nats_client._subscriptions_ready = True + await connected_nats_client._on_disconnected() + assert connected_nats_client.subscriptions_ready is False + + async def test_reconnected_callback_restores_ready_flag_for_core_nats(self, connected_nats_client: NATSClient) -> None: + connected_nats_client._subscriptions_managed = True + connected_nats_client._subscriptions_ready = False + connected_nats_client._use_jetstream = False + await connected_nats_client._on_reconnected() + assert connected_nats_client.subscriptions_ready is True + + async def test_reconnected_callback_no_op_without_managed_subscriptions(self, connected_nats_client: NATSClient) -> None: + connected_nats_client._subscriptions_managed = False + connected_nats_client._subscriptions_ready = False + await connected_nats_client._on_reconnected() + assert connected_nats_client.subscriptions_ready is False + + async def test_reconnected_resubscribes_jetstream_topics(self, connected_nats_client: NATSClient, mock_nats_jetstream: tuple) -> None: + mock_nc, mock_js = mock_nats_jetstream + connected_nats_client._nats_client = mock_nc + connected_nats_client._client = mock_nc + connected_nats_client._use_jetstream = True + connected_nats_client._subscriptions_managed = True + connected_nats_client._subscriptions_ready = False + connected_nats_client._topic_callbacks = {"topic.a": AsyncMock(), "topic.b": AsyncMock()} + + with patch.object(connected_nats_client, "_subscribe_one", new_callable=AsyncMock) as mock_sub: + await connected_nats_client._on_reconnected() + + assert mock_sub.await_count == 2 + assert connected_nats_client.subscriptions_ready is True + + +# --------------------------------------------------------------------------- +# asyncio import needed by the non-blocking subscribe test +# --------------------------------------------------------------------------- diff --git a/tests/unit/agents/io/api/eventing/test_dapr.py b/tests/unit/agents/io/api/eventing/test_dapr.py index 15d3d9ca..e122744f 100644 --- a/tests/unit/agents/io/api/eventing/test_dapr.py +++ b/tests/unit/agents/io/api/eventing/test_dapr.py @@ -94,3 +94,51 @@ class TestDaprEventingSubscribe: async def test_subscribe_returns_empty_dict(self, dapr_eventing: DaprEventing) -> None: result = await dapr_eventing.subscribe("some-topic") assert result == {} + + +class TestDaprEventingOnStartup: + async def test_fetches_dapr_client_from_registry(self, dapr_eventing: DaprEventing, mock_registry: MagicMock) -> None: + mock_client = MagicMock() + mock_client.subscribe = AsyncMock() + mock_registry.get_component.return_value = mock_client + mock_registry.get_event_handler.return_value = [] + + await dapr_eventing.on_startup() + + assert dapr_eventing._client is mock_client + + async def test_no_handlers_skips_client_subscribe(self, dapr_eventing: DaprEventing, mock_registry: MagicMock) -> None: + mock_client = MagicMock() + mock_client.subscribe = AsyncMock() + mock_registry.get_component.return_value = mock_client + mock_registry.get_event_handler.return_value = [] + + await dapr_eventing.on_startup() + + mock_client.subscribe.assert_not_called() + + async def test_handler_topics_passed_to_client_subscribe(self, dapr_eventing: DaprEventing, mock_registry: MagicMock) -> None: + handler = MagicMock() + handler.get_subscribed_topics.return_value = ["orders.created"] + mock_client = MagicMock() + mock_client.subscribe = AsyncMock() + mock_registry.get_component.return_value = mock_client + mock_registry.get_event_handler.return_value = [handler] + + await dapr_eventing.on_startup() + + mock_client.subscribe.assert_awaited_once() + mapping = mock_client.subscribe.call_args[0][0] + assert "orders.created" in mapping + assert callable(mapping["orders.created"]) + + async def test_on_startup_returns_without_raising(self, dapr_eventing: DaprEventing, mock_registry: MagicMock) -> None: + """on_startup must return immediately; subscribe() starts a background task.""" + handler = MagicMock() + handler.get_subscribed_topics.return_value = ["t"] + mock_client = MagicMock() + mock_client.subscribe = AsyncMock() + mock_registry.get_component.return_value = mock_client + mock_registry.get_event_handler.return_value = [handler] + + await dapr_eventing.on_startup() # must not raise or hang diff --git a/tests/unit/agents/io/api/eventing/test_event_handling_base.py b/tests/unit/agents/io/api/eventing/test_event_handling_base.py index 1529cdf8..2bae4fc5 100644 --- a/tests/unit/agents/io/api/eventing/test_event_handling_base.py +++ b/tests/unit/agents/io/api/eventing/test_event_handling_base.py @@ -3,7 +3,6 @@ import json from unittest.mock import AsyncMock, MagicMock - from blueprint.agents.io.api.eventing.dapr import DaprEventing from blueprint.agents.models.events import CloudEvent from blueprint.agents.models.result import ProcessingResult diff --git a/tests/unit/agents/io/api/eventing/test_nats.py b/tests/unit/agents/io/api/eventing/test_nats.py index b3a37195..76866c91 100644 --- a/tests/unit/agents/io/api/eventing/test_nats.py +++ b/tests/unit/agents/io/api/eventing/test_nats.py @@ -1,6 +1,6 @@ """Unit tests for NatsEventing.""" -from unittest.mock import AsyncMock, MagicMock, patch +from unittest.mock import AsyncMock, MagicMock import pytest @@ -8,25 +8,6 @@ from blueprint.agents.models.events import CloudEvent -class TestNatsEventingSubscribe: - async def test_subscribe_delegates_to_client(self, connected_nats_eventing: NatsEventing) -> None: - await connected_nats_eventing.subscribe("events.topic") - connected_nats_eventing._client.subscribe.assert_awaited_once() - - async def test_subscribe_passes_correct_topic(self, connected_nats_eventing: NatsEventing) -> None: - await connected_nats_eventing.subscribe("my.topic") - topic_arg = connected_nats_eventing._client.subscribe.call_args[0][0] - assert topic_arg == "my.topic" - - async def test_subscribe_returns_success_message(self, connected_nats_eventing: NatsEventing) -> None: - result = await connected_nats_eventing.subscribe("topic") - assert "Subscribed" in result["message"] or "topic" in result["message"] - - async def test_subscribe_raises_when_client_none(self, nats_eventing: NatsEventing) -> None: - with pytest.raises(RuntimeError, match="NATS client not initialized"): - await nats_eventing.subscribe("topic") - - class TestNatsEventingPublish: async def test_publish_delegates_to_client( self, @@ -64,7 +45,7 @@ async def test_publish_raises_when_client_none( # --------------------------------------------------------------------------- -# on_startup — auto-subscription logic +# on_startup — topic collection and client.subscribe() delegation # --------------------------------------------------------------------------- @@ -73,6 +54,7 @@ async def test_fetches_nats_client_from_registry( self, nats_eventing: NatsEventing, mock_registry: MagicMock, mock_config: MagicMock ) -> None: mock_client = MagicMock() + mock_client.subscribe = AsyncMock() mock_registry.get_component.return_value = mock_client mock_registry.get_event_handler.return_value = [] mock_config.get_nats_subscription_config.return_value = [] @@ -81,88 +63,94 @@ async def test_fetches_nats_client_from_registry( assert nats_eventing._client is mock_client - async def test_no_topics_skips_subscribing(self, nats_eventing: NatsEventing, mock_registry: MagicMock, mock_config: MagicMock) -> None: - mock_registry.get_component.return_value = MagicMock() + async def test_no_topics_skips_client_subscribe( + self, nats_eventing: NatsEventing, mock_registry: MagicMock, mock_config: MagicMock + ) -> None: + mock_client = MagicMock() + mock_client.subscribe = AsyncMock() + mock_registry.get_component.return_value = mock_client mock_registry.get_event_handler.return_value = [] mock_config.get_nats_subscription_config.return_value = [] - mock_sub = AsyncMock() - with patch.object(nats_eventing, "_subscribe_to_topic", mock_sub): - await nats_eventing.on_startup() - mock_sub.assert_not_called() + await nats_eventing.on_startup() + + mock_client.subscribe.assert_not_called() - async def test_handler_declared_topics_are_subscribed( + async def test_handler_declared_topics_passed_to_client_subscribe( self, nats_eventing: NatsEventing, mock_registry: MagicMock, mock_config: MagicMock ) -> None: handler = MagicMock() handler.get_subscribed_topics.return_value = ["events.created"] - mock_registry.get_component.return_value = MagicMock() + mock_client = MagicMock() + mock_client.subscribe = AsyncMock() + mock_registry.get_component.return_value = mock_client mock_registry.get_event_handler.return_value = [handler] mock_config.get_nats_subscription_config.return_value = [] - mock_sub = AsyncMock() - with patch.object(nats_eventing, "_subscribe_to_topic", mock_sub): - await nats_eventing.on_startup() - mock_sub.assert_awaited_once_with("events.created") + await nats_eventing.on_startup() + + mock_client.subscribe.assert_awaited_once() + mapping = mock_client.subscribe.call_args[0][0] + assert "events.created" in mapping + assert callable(mapping["events.created"]) - async def test_config_declared_topics_are_subscribed( + async def test_config_declared_topics_passed_to_client_subscribe( self, nats_eventing: NatsEventing, mock_registry: MagicMock, mock_config: MagicMock ) -> None: - mock_registry.get_component.return_value = MagicMock() + mock_client = MagicMock() + mock_client.subscribe = AsyncMock() + mock_registry.get_component.return_value = mock_client mock_registry.get_event_handler.return_value = [] mock_config.get_nats_subscription_config.return_value = ["orders.created", "orders.updated"] - mock_sub = AsyncMock() - with patch.object(nats_eventing, "_subscribe_to_topic", mock_sub): - await nats_eventing.on_startup() - assert mock_sub.await_count == 2 + await nats_eventing.on_startup() + + mapping = mock_client.subscribe.call_args[0][0] + assert set(mapping.keys()) == {"orders.created", "orders.updated"} - async def test_duplicate_topic_subscribed_only_once( + async def test_duplicate_topic_appears_once_in_mapping( self, nats_eventing: NatsEventing, mock_registry: MagicMock, mock_config: MagicMock ) -> None: handler = MagicMock() handler.get_subscribed_topics.return_value = ["shared.topic"] - mock_registry.get_component.return_value = MagicMock() + mock_client = MagicMock() + mock_client.subscribe = AsyncMock() + mock_registry.get_component.return_value = mock_client mock_registry.get_event_handler.return_value = [handler] mock_config.get_nats_subscription_config.return_value = ["shared.topic", "other.topic"] - mock_sub = AsyncMock() - with patch.object(nats_eventing, "_subscribe_to_topic", mock_sub): - await nats_eventing.on_startup() - subscribed = [c.args[0] for c in mock_sub.call_args_list] - assert subscribed.count("shared.topic") == 1 - assert "other.topic" in subscribed + await nats_eventing.on_startup() + + mapping = mock_client.subscribe.call_args[0][0] + assert list(mapping.keys()).count("shared.topic") == 1 + assert "other.topic" in mapping async def test_handler_topics_precede_config_topics( self, nats_eventing: NatsEventing, mock_registry: MagicMock, mock_config: MagicMock ) -> None: handler = MagicMock() handler.get_subscribed_topics.return_value = ["handler.topic"] - mock_registry.get_component.return_value = MagicMock() + mock_client = MagicMock() + mock_client.subscribe = AsyncMock() + mock_registry.get_component.return_value = mock_client mock_registry.get_event_handler.return_value = [handler] mock_config.get_nats_subscription_config.return_value = ["config.topic"] - mock_sub = AsyncMock() - with patch.object(nats_eventing, "_subscribe_to_topic", mock_sub): - await nats_eventing.on_startup() - - subscribed = [c.args[0] for c in mock_sub.call_args_list] - assert subscribed == ["handler.topic", "config.topic"] - - -# --------------------------------------------------------------------------- -# _subscribe_to_topic — client guard and delegation -# --------------------------------------------------------------------------- + await nats_eventing.on_startup() -class TestSubscribeToTopic: - async def test_raises_when_client_is_none(self, nats_eventing: NatsEventing) -> None: - with pytest.raises(RuntimeError, match="NATS client not initialized"): - await nats_eventing._subscribe_to_topic("events.topic") + mapping = mock_client.subscribe.call_args[0][0] + assert list(mapping.keys()) == ["handler.topic", "config.topic"] - async def test_calls_client_subscribe_with_topic_and_callback(self, connected_nats_eventing: NatsEventing) -> None: - await connected_nats_eventing._subscribe_to_topic("test.topic") + async def test_on_startup_returns_without_raising_when_client_subscribe_is_non_blocking( + self, nats_eventing: NatsEventing, mock_registry: MagicMock, mock_config: MagicMock + ) -> None: + """on_startup must return immediately; subscribe() starts a background task.""" + handler = MagicMock() + handler.get_subscribed_topics.return_value = ["t"] + mock_client = MagicMock() + mock_client.subscribe = AsyncMock() + mock_registry.get_component.return_value = mock_client + mock_registry.get_event_handler.return_value = [handler] + mock_config.get_nats_subscription_config.return_value = [] - connected_nats_eventing._client.subscribe.assert_awaited_once() - call_args = connected_nats_eventing._client.subscribe.call_args[0] - assert call_args[0] == "test.topic" - assert callable(call_args[1]) + await nats_eventing.on_startup() # must not raise or hang