From b804e32fad6094aa495a88741442fd9fb3cc4460 Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Wed, 17 Jun 2026 14:27:03 +0200 Subject: [PATCH 1/8] Retry logic for event connections --- docs/concepts/event-processing.md | 51 +++++++ docs/guides/deployment.md | 2 + docs/reference/configuration-keys.md | 4 + pyproject.toml | 2 +- src/blueprint/agents/io/api/eventing/dapr.py | 5 +- .../io/api/eventing/event_handling_base.py | 69 ++++++++- src/blueprint/agents/io/api/eventing/nats.py | 25 +--- .../api/eventing/test_event_handling_base.py | 137 +++++++++++++++++- .../unit/agents/io/api/eventing/test_nats.py | 14 +- 9 files changed, 271 insertions(+), 38 deletions(-) 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 8e896380..48b88bca 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -6,7 +6,7 @@ build-backend = "setuptools.build_meta" [project] name = "avs-blueprint-agents" -version = "0.6.1" +version = "0.6.2" description = "Microservice blueprint for creating agents" authors = [ { name = "Blueprint Team", email = "patrick.maue@bechtle.com" }, diff --git a/src/blueprint/agents/io/api/eventing/dapr.py b/src/blueprint/agents/io/api/eventing/dapr.py index d7511b98..57f36a8f 100644 --- a/src/blueprint/agents/io/api/eventing/dapr.py +++ b/src/blueprint/agents/io/api/eventing/dapr.py @@ -22,13 +22,10 @@ def __init__(self) -> None: super().__init__(should_register=False) self._client: DaprClient | None = None - async def on_startup(self) -> None: + async def _connect_and_subscribe(self) -> None: """Fetch the registered DaprClient from the registry.""" self._client = self.registry.get_component(DaprClient) - async def on_shutdown(self) -> None: - """No shutdown actions required — DaprClient lifecycle is managed separately.""" - @RestApiBase.get("/dapr/subscribe", tags=["dapr"]) async def subscribe(self, topic: str, queue_group: str | None = None) -> dict[str, Any]: """ 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..af9f7e10 100644 --- a/src/blueprint/agents/io/api/eventing/event_handling_base.py +++ b/src/blueprint/agents/io/api/eventing/event_handling_base.py @@ -2,8 +2,10 @@ from __future__ import annotations +import asyncio import logging from abc import ABC, abstractmethod +from contextlib import suppress from typing import Any from ....component.component import traced @@ -22,8 +24,73 @@ 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. + + Subclasses implement ``_connect_and_subscribe`` to perform the actual + broker connection and topic subscription. ``on_startup`` launches this + in a background task with configurable retry logic so the service enters + a live state immediately even when the broker is temporarily unavailable. + + Config keys: + event_client_max_retries (int, default -1): Number of retries after + the first failure. ``-1`` retries indefinitely. ``0`` makes a + single attempt and raises on failure. + event_client_retry_delay (float, default 5.0): Seconds between retries. """ + def __init__(self, **kwargs: Any) -> None: + super().__init__(**kwargs) + self._retry_task: asyncio.Task | None = None + + async def on_startup(self) -> None: + self._retry_task = asyncio.ensure_future(self._start_with_retry()) + + async def on_shutdown(self) -> None: + if self._retry_task and not self._retry_task.done(): + self._retry_task.cancel() + with suppress(asyncio.CancelledError): + await self._retry_task + + @abstractmethod + async def _connect_and_subscribe(self) -> None: + """Perform the broker connection and topic subscriptions. + + Called by the retry loop. Raise any exception to trigger a retry. + Must be idempotent — it may be called more than once if earlier + attempts fail. + """ + raise NotImplementedError() + + 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 + last_exc: Exception | None = None + while True: + try: + await self._connect_and_subscribe() + logger.info("%s connected successfully", type(self).__name__) + return + except Exception as e: + last_exc = e + attempt += 1 + if max_retries != -1 and attempt > max_retries: + logger.error( + "%s permanently failed to connect after %d attempt(s): %s", + type(self).__name__, + attempt, + last_exc, + exc_info=last_exc, + ) + raise last_exc + logger.warning( + "%s connect attempt %d failed, retrying in %.1fs: %s", + type(self).__name__, + attempt, + delay, + e, + ) + await asyncio.sleep(delay) + @traced("topic", "cloud_event") async def handle_event(self, topic: str, cloud_event: CloudEvent[Any]) -> dict[str, Any]: processing_result = await self._process_cloud_event(cloud_event, {"topic": topic}) @@ -78,4 +145,4 @@ async def _process_cloud_event( raise except Exception as exc: logger.error("Processing service failed: %s", str(exc), exc_info=True) - raise + raise \ No newline at end of file diff --git a/src/blueprint/agents/io/api/eventing/nats.py b/src/blueprint/agents/io/api/eventing/nats.py index 319f0700..77913dd4 100644 --- a/src/blueprint/agents/io/api/eventing/nats.py +++ b/src/blueprint/agents/io/api/eventing/nats.py @@ -19,7 +19,7 @@ def __init__(self) -> None: super().__init__(should_register=False) self._client: NATSClient | None = None - async def on_startup(self) -> None: + async def _connect_and_subscribe(self) -> None: """Fetch the registered NATSClient and auto-subscribe to declared topics. Topics are collected from two sources (handler-declared topics first, @@ -69,9 +69,6 @@ async def _process_event(event: CloudEvent[Any]) -> None: 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.""" - @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. @@ -83,25 +80,7 @@ async def subscribe(self, topic: str, queue_group: str | None = None) -> dict[st Returns: Success message """ - if not self._client: - raise RuntimeError("NATS client not initialized") - - # Callback to process incoming events - 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) - # NATS handles retries/acks via client - - await self._client.subscribe(topic, _process_event) + await self._subscribe_to_topic(topic) return {"message": f"Subscribed to topic {topic}"} @RestApiBase.post("/events/{topic}", tags=["nats"]) 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..469c1821 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 @@ -1,13 +1,49 @@ -"""Unit tests for EventHandlingBase._unwrap_nested_cloud_event and handle_event.""" +"""Unit tests for EventHandlingBase._unwrap_nested_cloud_event, handle_event, and retry logic.""" +import asyncio import json -from unittest.mock import AsyncMock, MagicMock +from typing import Any +from unittest.mock import AsyncMock, MagicMock, patch +import pytest from blueprint.agents.io.api.eventing.dapr import DaprEventing +from blueprint.agents.io.api.eventing.event_handling_base import EventHandlingBase from blueprint.agents.models.events import CloudEvent from blueprint.agents.models.result import ProcessingResult + +# --------------------------------------------------------------------------- +# Minimal concrete subclass used for retry tests +# --------------------------------------------------------------------------- + + +class _RetryEventing(EventHandlingBase): + """Concrete EventHandlingBase with a controllable _connect_and_subscribe.""" + + def __init__(self) -> None: + super().__init__(should_register=False) + self.connect_mock = AsyncMock() + + async def _connect_and_subscribe(self) -> None: + await self.connect_mock() + + async def publish(self, topic: str, event: CloudEvent) -> dict[str, Any]: + return {} + + async def subscribe(self, topic: str, queue_group: str | None = None) -> dict[str, Any]: + return {} + + +@pytest.fixture +def eventing(mock_registry: MagicMock, mock_config: MagicMock) -> _RetryEventing: + """_RetryEventing with infinite retries and zero delay by default.""" + mock_config.get.side_effect = lambda key, default=None: { + "event_client_max_retries": -1, + "event_client_retry_delay": 0.0, + }.get(key, default) + return _RetryEventing() + # --------------------------------------------------------------------------- # _unwrap_nested_cloud_event # --------------------------------------------------------------------------- @@ -129,3 +165,100 @@ async def test_retry_result_includes_reason( result = await dapr_eventing.handle_event("topic", cloud_event) assert "reason" in result + + +# --------------------------------------------------------------------------- +# EventHandlingBase retry logic (on_startup / _start_with_retry / on_shutdown) +# --------------------------------------------------------------------------- + +_SLEEP_PATH = "blueprint.agents.io.api.eventing.event_handling_base.asyncio.sleep" + + +class TestStartWithRetry: + async def test_on_startup_returns_immediately_without_raising(self, eventing: _RetryEventing) -> None: + eventing.connect_mock.side_effect = Exception("broker down") + await eventing.on_startup() # must not raise even though connect will fail + + async def test_on_startup_creates_a_background_task(self, eventing: _RetryEventing) -> None: + await eventing.on_startup() + assert isinstance(eventing._retry_task, asyncio.Task) + + async def test_successful_first_attempt_calls_connect_once(self, eventing: _RetryEventing) -> None: + await eventing.on_startup() + await eventing._retry_task + eventing.connect_mock.assert_awaited_once() + + async def test_retries_on_transient_failure_then_succeeds(self, eventing: _RetryEventing) -> None: + eventing.connect_mock.side_effect = [Exception("transient"), None] + with patch(_SLEEP_PATH, new_callable=AsyncMock): + await eventing.on_startup() + await eventing._retry_task + assert eventing.connect_mock.await_count == 2 + + async def test_max_retries_zero_raises_after_single_attempt( + self, eventing: _RetryEventing, mock_config: MagicMock + ) -> None: + mock_config.get.side_effect = lambda key, default=None: { + "event_client_max_retries": 0, + "event_client_retry_delay": 0.0, + }.get(key, default) + eventing.connect_mock.side_effect = ConnectionError("broker down") + + await eventing.on_startup() + with pytest.raises(ConnectionError): + await eventing._retry_task + eventing.connect_mock.assert_awaited_once() + + async def test_max_retries_exhausted_calls_connect_n_plus_one_times( + self, eventing: _RetryEventing, mock_config: MagicMock + ) -> None: + mock_config.get.side_effect = lambda key, default=None: { + "event_client_max_retries": 2, + "event_client_retry_delay": 0.0, + }.get(key, default) + eventing.connect_mock.side_effect = ConnectionError("broker down") + + with patch(_SLEEP_PATH, new_callable=AsyncMock): + await eventing.on_startup() + with pytest.raises(ConnectionError): + await eventing._retry_task + assert eventing.connect_mock.await_count == 3 # 1 initial + 2 retries + + async def test_succeeds_on_last_allowed_retry( + self, eventing: _RetryEventing, mock_config: MagicMock + ) -> None: + mock_config.get.side_effect = lambda key, default=None: { + "event_client_max_retries": 2, + "event_client_retry_delay": 0.0, + }.get(key, default) + eventing.connect_mock.side_effect = [Exception("fail"), Exception("fail"), None] + + with patch(_SLEEP_PATH, new_callable=AsyncMock): + await eventing.on_startup() + await eventing._retry_task # must not raise + assert eventing.connect_mock.await_count == 3 + + async def test_on_shutdown_cancels_in_progress_retry_task(self, eventing: _RetryEventing) -> None: + task_reached_sleep = asyncio.Event() + never_resolves = asyncio.Event() + + async def hang(*args: Any, **kwargs: Any) -> None: + task_reached_sleep.set() + await never_resolves.wait() + + eventing.connect_mock.side_effect = Exception("fail") + with patch(_SLEEP_PATH, side_effect=hang): + await eventing.on_startup() + await task_reached_sleep.wait() # asyncio.Event.wait() doesn't use asyncio.sleep + await eventing.on_shutdown() + + assert eventing._retry_task.done() + assert eventing._retry_task.cancelled() + + async def test_on_shutdown_before_startup_is_noop(self, eventing: _RetryEventing) -> None: + await eventing.on_shutdown() # _retry_task is None — must not raise + + async def test_on_shutdown_after_completed_task_is_noop(self, eventing: _RetryEventing) -> None: + await eventing.on_startup() + await eventing._retry_task # let connect succeed + await eventing.on_shutdown() # task already done — must not raise diff --git a/tests/unit/agents/io/api/eventing/test_nats.py b/tests/unit/agents/io/api/eventing/test_nats.py index b3a37195..c38df736 100644 --- a/tests/unit/agents/io/api/eventing/test_nats.py +++ b/tests/unit/agents/io/api/eventing/test_nats.py @@ -68,7 +68,7 @@ async def test_publish_raises_when_client_none( # --------------------------------------------------------------------------- -class TestNatsEventingOnStartup: +class TestNatsEventingConnectAndSubscribe: async def test_fetches_nats_client_from_registry( self, nats_eventing: NatsEventing, mock_registry: MagicMock, mock_config: MagicMock ) -> None: @@ -77,7 +77,7 @@ async def test_fetches_nats_client_from_registry( mock_registry.get_event_handler.return_value = [] mock_config.get_nats_subscription_config.return_value = [] - await nats_eventing.on_startup() + await nats_eventing._connect_and_subscribe() assert nats_eventing._client is mock_client @@ -87,7 +87,7 @@ async def test_no_topics_skips_subscribing(self, nats_eventing: NatsEventing, mo 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() + await nats_eventing._connect_and_subscribe() mock_sub.assert_not_called() @@ -101,7 +101,7 @@ async def test_handler_declared_topics_are_subscribed( 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() + await nats_eventing._connect_and_subscribe() mock_sub.assert_awaited_once_with("events.created") @@ -113,7 +113,7 @@ async def test_config_declared_topics_are_subscribed( 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() + await nats_eventing._connect_and_subscribe() assert mock_sub.await_count == 2 @@ -127,7 +127,7 @@ async def test_duplicate_topic_subscribed_only_once( 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() + await nats_eventing._connect_and_subscribe() subscribed = [c.args[0] for c in mock_sub.call_args_list] assert subscribed.count("shared.topic") == 1 @@ -143,7 +143,7 @@ async def test_handler_topics_precede_config_topics( 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() + await nats_eventing._connect_and_subscribe() subscribed = [c.args[0] for c in mock_sub.call_args_list] assert subscribed == ["handler.topic", "config.topic"] From d26c5e46858e5a92c511c0c9c3a40e2f2582d153 Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Wed, 17 Jun 2026 14:36:14 +0200 Subject: [PATCH 2/8] Ruff check --- .../agents/io/api/eventing/event_handling_base.py | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) 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 af9f7e10..cf56f08b 100644 --- a/src/blueprint/agents/io/api/eventing/event_handling_base.py +++ b/src/blueprint/agents/io/api/eventing/event_handling_base.py @@ -64,24 +64,22 @@ 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 - last_exc: Exception | None = None while True: try: await self._connect_and_subscribe() logger.info("%s connected successfully", type(self).__name__) return except Exception as e: - last_exc = e attempt += 1 if max_retries != -1 and attempt > max_retries: logger.error( "%s permanently failed to connect after %d attempt(s): %s", type(self).__name__, attempt, - last_exc, - exc_info=last_exc, + e, + exc_info=e, ) - raise last_exc + raise logger.warning( "%s connect attempt %d failed, retrying in %.1fs: %s", type(self).__name__, @@ -145,4 +143,4 @@ async def _process_cloud_event( raise except Exception as exc: logger.error("Processing service failed: %s", str(exc), exc_info=True) - raise \ No newline at end of file + raise From 9508de5e7d4e9f6d2a693b21c4c5aa1f6e14920e Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Wed, 17 Jun 2026 15:49:33 +0200 Subject: [PATCH 3/8] Ruff format and mypy check --- .../agents/io/api/eventing/event_handling_base.py | 2 +- .../io/api/eventing/test_event_handling_base.py | 13 ++++--------- 2 files changed, 5 insertions(+), 10 deletions(-) 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 cf56f08b..6b632753 100644 --- a/src/blueprint/agents/io/api/eventing/event_handling_base.py +++ b/src/blueprint/agents/io/api/eventing/event_handling_base.py @@ -39,7 +39,7 @@ class EventHandlingBase(RestApiBase, CloudEventProcessorMixin, ABC): def __init__(self, **kwargs: Any) -> None: super().__init__(**kwargs) - self._retry_task: asyncio.Task | None = None + self._retry_task: asyncio.Task[None] | None = None async def on_startup(self) -> None: self._retry_task = asyncio.ensure_future(self._start_with_retry()) 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 469c1821..74e188aa 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 @@ -44,6 +44,7 @@ def eventing(mock_registry: MagicMock, mock_config: MagicMock) -> _RetryEventing }.get(key, default) return _RetryEventing() + # --------------------------------------------------------------------------- # _unwrap_nested_cloud_event # --------------------------------------------------------------------------- @@ -195,9 +196,7 @@ async def test_retries_on_transient_failure_then_succeeds(self, eventing: _Retry await eventing._retry_task assert eventing.connect_mock.await_count == 2 - async def test_max_retries_zero_raises_after_single_attempt( - self, eventing: _RetryEventing, mock_config: MagicMock - ) -> None: + async def test_max_retries_zero_raises_after_single_attempt(self, eventing: _RetryEventing, mock_config: MagicMock) -> None: mock_config.get.side_effect = lambda key, default=None: { "event_client_max_retries": 0, "event_client_retry_delay": 0.0, @@ -209,9 +208,7 @@ async def test_max_retries_zero_raises_after_single_attempt( await eventing._retry_task eventing.connect_mock.assert_awaited_once() - async def test_max_retries_exhausted_calls_connect_n_plus_one_times( - self, eventing: _RetryEventing, mock_config: MagicMock - ) -> None: + async def test_max_retries_exhausted_calls_connect_n_plus_one_times(self, eventing: _RetryEventing, mock_config: MagicMock) -> None: mock_config.get.side_effect = lambda key, default=None: { "event_client_max_retries": 2, "event_client_retry_delay": 0.0, @@ -224,9 +221,7 @@ async def test_max_retries_exhausted_calls_connect_n_plus_one_times( await eventing._retry_task assert eventing.connect_mock.await_count == 3 # 1 initial + 2 retries - async def test_succeeds_on_last_allowed_retry( - self, eventing: _RetryEventing, mock_config: MagicMock - ) -> None: + async def test_succeeds_on_last_allowed_retry(self, eventing: _RetryEventing, mock_config: MagicMock) -> None: mock_config.get.side_effect = lambda key, default=None: { "event_client_max_retries": 2, "event_client_retry_delay": 0.0, From 0856424d0de54b5652d9e11b313d5ce8623f43a9 Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Wed, 17 Jun 2026 16:03:15 +0200 Subject: [PATCH 4/8] MyPy check --- src/blueprint/agents/io/api/utilities/root.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/blueprint/agents/io/api/utilities/root.py b/src/blueprint/agents/io/api/utilities/root.py index 9dc15750..04748e21 100644 --- a/src/blueprint/agents/io/api/utilities/root.py +++ b/src/blueprint/agents/io/api/utilities/root.py @@ -45,9 +45,9 @@ async def root(self) -> Any: for route in self._app.routes: if not isinstance(route, APIRoute): continue - methods = ", ".join(sorted(route.methods)) + methods = ", ".join(sorted(route.methods or set())) summary = route.summary or "" - if "GET" in route.methods: + if "GET" in (route.methods or set()): path_cell = f'{route.path}' else: anchor = route.path.replace("/", "-").strip("-") From e93484d98dece0daf3682286444be7c526fefa4b Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Thu, 18 Jun 2026 14:21:02 +0200 Subject: [PATCH 5/8] Improved retry logic, health check and improved some separation of concerns aspects --- .../agents/clients/ai/openai_client.py | 2 +- .../agents/clients/ai/vllm_client.py | 2 +- src/blueprint/agents/clients/client_base.py | 9 +- .../agents/clients/io/dapr_client.py | 125 ++++++++++- .../agents/clients/io/nats_client.py | 211 +++++++++++++++--- src/blueprint/agents/io/api/eventing/dapr.py | 91 ++++---- .../io/api/eventing/event_handling_base.py | 97 +------- src/blueprint/agents/io/api/eventing/nats.py | 68 ++---- .../agents/clients/ai/test_openai_client.py | 2 +- .../agents/clients/ai/test_vllm_client.py | 2 +- .../agents/clients/io/test_dapr_client.py | 123 +++++++++- .../agents/clients/io/test_nats_client.py | 175 ++++++++++++++- tests/unit/agents/config/test_agent_scope.py | 24 +- .../unit/agents/io/api/eventing/test_dapr.py | 48 ++++ .../api/eventing/test_event_handling_base.py | 133 +---------- .../unit/agents/io/api/eventing/test_nats.py | 130 +++++------ 16 files changed, 793 insertions(+), 449 deletions(-) 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 57f36a8f..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,41 +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 _connect_and_subscribe(self) -> None: - """Fetch the registered DaprClient from the registry.""" + async def on_startup(self) -> None: 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: + 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 = { @@ -59,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"} @@ -72,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 6b632753..4c3c6b91 100644 --- a/src/blueprint/agents/io/api/eventing/event_handling_base.py +++ b/src/blueprint/agents/io/api/eventing/event_handling_base.py @@ -2,10 +2,8 @@ from __future__ import annotations -import asyncio import logging from abc import ABC, abstractmethod -from contextlib import suppress from typing import Any from ....component.component import traced @@ -25,87 +23,23 @@ class EventHandlingBase(RestApiBase, CloudEventProcessorMixin, ABC): (CloudEventProcessorMixin) and adds structured error-handling and logging around the dispatch pipeline. - Subclasses implement ``_connect_and_subscribe`` to perform the actual - broker connection and topic subscription. ``on_startup`` launches this - in a background task with configurable retry logic so the service enters - a live state immediately even when the broker is temporarily unavailable. - - Config keys: - event_client_max_retries (int, default -1): Number of retries after - the first failure. ``-1`` retries indefinitely. ``0`` makes a - single attempt and raises on failure. - event_client_retry_delay (float, default 5.0): Seconds between retries. + 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. """ - def __init__(self, **kwargs: Any) -> None: - super().__init__(**kwargs) - self._retry_task: asyncio.Task[None] | None = None - - async def on_startup(self) -> None: - self._retry_task = asyncio.ensure_future(self._start_with_retry()) - - async def on_shutdown(self) -> None: - if self._retry_task and not self._retry_task.done(): - self._retry_task.cancel() - with suppress(asyncio.CancelledError): - await self._retry_task - - @abstractmethod - async def _connect_and_subscribe(self) -> None: - """Perform the broker connection and topic subscriptions. - - Called by the retry loop. Raise any exception to trigger a retry. - Must be idempotent — it may be called more than once if earlier - attempts fail. - """ - raise NotImplementedError() - - 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() - logger.info("%s connected successfully", type(self).__name__) - return - except Exception as e: - attempt += 1 - if max_retries != -1 and attempt > max_retries: - logger.error( - "%s permanently failed to connect after %d attempt(s): %s", - type(self).__name__, - attempt, - e, - exc_info=e, - ) - raise - logger.warning( - "%s connect attempt %d failed, retrying in %.1fs: %s", - type(self).__name__, - attempt, - delay, - e, - ) - await asyncio.sleep(delay) - @traced("topic", "cloud_event") async def handle_event(self, topic: str, cloud_event: CloudEvent[Any]) -> dict[str, Any]: 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( @@ -113,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 77913dd4..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,45 +14,39 @@ 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 _connect_and_subscribe(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. - """ + async def on_startup(self) -> None: 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. + async def on_shutdown(self) -> None: + pass - 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") + 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.""" async def _process_event(event: CloudEvent[Any]) -> None: try: @@ -66,33 +61,18 @@ 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) - await self._client.subscribe(topic, _process_event) - logger.info("NatsEventing: auto-subscribed to topic '%s'", topic) - - @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 - """ - await self._subscribe_to_topic(topic) - 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/config/test_agent_scope.py b/tests/unit/agents/config/test_agent_scope.py index c8538da6..f3971b54 100644 --- a/tests/unit/agents/config/test_agent_scope.py +++ b/tests/unit/agents/config/test_agent_scope.py @@ -50,8 +50,7 @@ def test_unscoped_get_returns_root_value(self, base_config: Config) -> None: assert base_config.get("app_port") == 8000 def test_unscoped_get_runtime_config_uses_legacy_block(self, write_settings: WriteSettings) -> None: - settings_file = write_settings( - """ + settings_file = write_settings(""" [development] app_name = "legacy" app_port = 8000 @@ -62,8 +61,7 @@ def test_unscoped_get_runtime_config_uses_legacy_block(self, write_settings: Wri [development.runtimes.my_agent] model_name = "legacy-model" - """ - ) + """) config = Config(settings_files=[str(settings_file)], root_path=str(settings_file.parent)) runtime_cfg = config.get_runtime_config("my_agent") assert runtime_cfg["model_name"] == "legacy-model" @@ -110,16 +108,14 @@ def test_resolves_scoped_model_settings(self, scoped_config_foo: Config) -> None class TestValidators: def test_missing_scoped_app_name_raises(self, write_settings: WriteSettings) -> None: - settings_file = write_settings( - """ + settings_file = write_settings(""" [development] app_environment = "development" [development.foo] app_port = 8101 # app_name intentionally missing - """ - ) + """) with pytest.raises(ConfigError): Config( settings_files=[str(settings_file)], @@ -128,16 +124,14 @@ def test_missing_scoped_app_name_raises(self, write_settings: WriteSettings) -> ) def test_missing_scoped_app_port_raises(self, write_settings: WriteSettings) -> None: - settings_file = write_settings( - """ + settings_file = write_settings(""" [development] app_environment = "development" [development.foo] app_name = "foo-app" # app_port intentionally missing - """ - ) + """) with pytest.raises(ConfigError): Config( settings_files=[str(settings_file)], @@ -147,16 +141,14 @@ def test_missing_scoped_app_port_raises(self, write_settings: WriteSettings) -> def test_root_keys_not_required_when_scoped(self, write_settings: WriteSettings) -> None: # No root app_name / app_port; only scoped versions exist. - settings_file = write_settings( - """ + settings_file = write_settings(""" [development] app_environment = "development" [development.foo] app_name = "foo-app" app_port = 8101 - """ - ) + """) # Must not raise. config = Config( settings_files=[str(settings_file)], 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 74e188aa..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 @@ -1,50 +1,12 @@ -"""Unit tests for EventHandlingBase._unwrap_nested_cloud_event, handle_event, and retry logic.""" +"""Unit tests for EventHandlingBase._unwrap_nested_cloud_event and handle_event.""" -import asyncio import json -from typing import Any -from unittest.mock import AsyncMock, MagicMock, patch - -import pytest +from unittest.mock import AsyncMock, MagicMock from blueprint.agents.io.api.eventing.dapr import DaprEventing -from blueprint.agents.io.api.eventing.event_handling_base import EventHandlingBase from blueprint.agents.models.events import CloudEvent from blueprint.agents.models.result import ProcessingResult - -# --------------------------------------------------------------------------- -# Minimal concrete subclass used for retry tests -# --------------------------------------------------------------------------- - - -class _RetryEventing(EventHandlingBase): - """Concrete EventHandlingBase with a controllable _connect_and_subscribe.""" - - def __init__(self) -> None: - super().__init__(should_register=False) - self.connect_mock = AsyncMock() - - async def _connect_and_subscribe(self) -> None: - await self.connect_mock() - - async def publish(self, topic: str, event: CloudEvent) -> dict[str, Any]: - return {} - - async def subscribe(self, topic: str, queue_group: str | None = None) -> dict[str, Any]: - return {} - - -@pytest.fixture -def eventing(mock_registry: MagicMock, mock_config: MagicMock) -> _RetryEventing: - """_RetryEventing with infinite retries and zero delay by default.""" - mock_config.get.side_effect = lambda key, default=None: { - "event_client_max_retries": -1, - "event_client_retry_delay": 0.0, - }.get(key, default) - return _RetryEventing() - - # --------------------------------------------------------------------------- # _unwrap_nested_cloud_event # --------------------------------------------------------------------------- @@ -166,94 +128,3 @@ async def test_retry_result_includes_reason( result = await dapr_eventing.handle_event("topic", cloud_event) assert "reason" in result - - -# --------------------------------------------------------------------------- -# EventHandlingBase retry logic (on_startup / _start_with_retry / on_shutdown) -# --------------------------------------------------------------------------- - -_SLEEP_PATH = "blueprint.agents.io.api.eventing.event_handling_base.asyncio.sleep" - - -class TestStartWithRetry: - async def test_on_startup_returns_immediately_without_raising(self, eventing: _RetryEventing) -> None: - eventing.connect_mock.side_effect = Exception("broker down") - await eventing.on_startup() # must not raise even though connect will fail - - async def test_on_startup_creates_a_background_task(self, eventing: _RetryEventing) -> None: - await eventing.on_startup() - assert isinstance(eventing._retry_task, asyncio.Task) - - async def test_successful_first_attempt_calls_connect_once(self, eventing: _RetryEventing) -> None: - await eventing.on_startup() - await eventing._retry_task - eventing.connect_mock.assert_awaited_once() - - async def test_retries_on_transient_failure_then_succeeds(self, eventing: _RetryEventing) -> None: - eventing.connect_mock.side_effect = [Exception("transient"), None] - with patch(_SLEEP_PATH, new_callable=AsyncMock): - await eventing.on_startup() - await eventing._retry_task - assert eventing.connect_mock.await_count == 2 - - async def test_max_retries_zero_raises_after_single_attempt(self, eventing: _RetryEventing, mock_config: MagicMock) -> None: - mock_config.get.side_effect = lambda key, default=None: { - "event_client_max_retries": 0, - "event_client_retry_delay": 0.0, - }.get(key, default) - eventing.connect_mock.side_effect = ConnectionError("broker down") - - await eventing.on_startup() - with pytest.raises(ConnectionError): - await eventing._retry_task - eventing.connect_mock.assert_awaited_once() - - async def test_max_retries_exhausted_calls_connect_n_plus_one_times(self, eventing: _RetryEventing, mock_config: MagicMock) -> None: - mock_config.get.side_effect = lambda key, default=None: { - "event_client_max_retries": 2, - "event_client_retry_delay": 0.0, - }.get(key, default) - eventing.connect_mock.side_effect = ConnectionError("broker down") - - with patch(_SLEEP_PATH, new_callable=AsyncMock): - await eventing.on_startup() - with pytest.raises(ConnectionError): - await eventing._retry_task - assert eventing.connect_mock.await_count == 3 # 1 initial + 2 retries - - async def test_succeeds_on_last_allowed_retry(self, eventing: _RetryEventing, mock_config: MagicMock) -> None: - mock_config.get.side_effect = lambda key, default=None: { - "event_client_max_retries": 2, - "event_client_retry_delay": 0.0, - }.get(key, default) - eventing.connect_mock.side_effect = [Exception("fail"), Exception("fail"), None] - - with patch(_SLEEP_PATH, new_callable=AsyncMock): - await eventing.on_startup() - await eventing._retry_task # must not raise - assert eventing.connect_mock.await_count == 3 - - async def test_on_shutdown_cancels_in_progress_retry_task(self, eventing: _RetryEventing) -> None: - task_reached_sleep = asyncio.Event() - never_resolves = asyncio.Event() - - async def hang(*args: Any, **kwargs: Any) -> None: - task_reached_sleep.set() - await never_resolves.wait() - - eventing.connect_mock.side_effect = Exception("fail") - with patch(_SLEEP_PATH, side_effect=hang): - await eventing.on_startup() - await task_reached_sleep.wait() # asyncio.Event.wait() doesn't use asyncio.sleep - await eventing.on_shutdown() - - assert eventing._retry_task.done() - assert eventing._retry_task.cancelled() - - async def test_on_shutdown_before_startup_is_noop(self, eventing: _RetryEventing) -> None: - await eventing.on_shutdown() # _retry_task is None — must not raise - - async def test_on_shutdown_after_completed_task_is_noop(self, eventing: _RetryEventing) -> None: - await eventing.on_startup() - await eventing._retry_task # let connect succeed - await eventing.on_shutdown() # task already done — must not raise diff --git a/tests/unit/agents/io/api/eventing/test_nats.py b/tests/unit/agents/io/api/eventing/test_nats.py index c38df736..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,105 +45,112 @@ async def test_publish_raises_when_client_none( # --------------------------------------------------------------------------- -# on_startup — auto-subscription logic +# on_startup — topic collection and client.subscribe() delegation # --------------------------------------------------------------------------- -class TestNatsEventingConnectAndSubscribe: +class TestNatsEventingOnStartup: 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 = [] - await nats_eventing._connect_and_subscribe() + await nats_eventing.on_startup() 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._connect_and_subscribe() - 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._connect_and_subscribe() - 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._connect_and_subscribe() - assert mock_sub.await_count == 2 + await nats_eventing.on_startup() - async def test_duplicate_topic_subscribed_only_once( + mapping = mock_client.subscribe.call_args[0][0] + assert set(mapping.keys()) == {"orders.created", "orders.updated"} + + 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._connect_and_subscribe() - 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._connect_and_subscribe() - subscribed = [c.args[0] for c in mock_sub.call_args_list] - assert subscribed == ["handler.topic", "config.topic"] + await nats_eventing.on_startup() + mapping = mock_client.subscribe.call_args[0][0] + assert list(mapping.keys()) == ["handler.topic", "config.topic"] -# --------------------------------------------------------------------------- -# _subscribe_to_topic — client guard and delegation -# --------------------------------------------------------------------------- - - -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") - - 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 From ae7b01a26c90c47216e3e63d90b922c0f4866f8d Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Wed, 24 Jun 2026 15:48:19 +0200 Subject: [PATCH 6/8] Updated CI to use uv --- .github/workflows/ci.yml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ba7708eb..56ec0e77 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -21,13 +21,13 @@ jobs: - uses: ./.github/actions/setup-python-env - name: ruff check - run: ruff check src tests + run: uv run ruff check src tests - name: ruff format check - run: ruff format --check src tests + run: uv run ruff format --check src tests - name: mypy - run: mypy src + run: uv run mypy src - name: Run unit tests - run: python -m pytest tests/unit -v --tb=short + run: uv run pytest tests/unit -v --tb=short From 3af41ba13540eb1887c3252c597732445a0cf345 Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Wed, 24 Jun 2026 15:56:20 +0200 Subject: [PATCH 7/8] Changed install, using uv is not required anymore --- .github/actions/setup-python-env/action.yml | 10 ++++++---- .github/workflows/ci.yml | 8 ++++---- 2 files changed, 10 insertions(+), 8 deletions(-) diff --git a/.github/actions/setup-python-env/action.yml b/.github/actions/setup-python-env/action.yml index 4a394981..66c225e1 100644 --- a/.github/actions/setup-python-env/action.yml +++ b/.github/actions/setup-python-env/action.yml @@ -29,12 +29,14 @@ runs: path: .venv key: venv-${{ runner.os }}-py${{ inputs.python-version }}-${{ hashFiles('pyproject.toml') }} - - name: Create venv and install dependencies + - name: Create venv if: steps.cache-venv.outputs.cache-hit != 'true' shell: bash - run: | - uv venv .venv - uv pip install -e ".[${{ inputs.install-extras }}]" + run: uv venv .venv + + - name: Install dependencies + shell: bash + run: uv pip install -e ".[${{ inputs.install-extras }}]" - name: Add venv to PATH shell: bash diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 56ec0e77..ba7708eb 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -21,13 +21,13 @@ jobs: - uses: ./.github/actions/setup-python-env - name: ruff check - run: uv run ruff check src tests + run: ruff check src tests - name: ruff format check - run: uv run ruff format --check src tests + run: ruff format --check src tests - name: mypy - run: uv run mypy src + run: mypy src - name: Run unit tests - run: uv run pytest tests/unit -v --tb=short + run: python -m pytest tests/unit -v --tb=short From 79f252c22d5485987d52ca190d0e466c665fba60 Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Wed, 24 Jun 2026 16:00:19 +0200 Subject: [PATCH 8/8] Since astral-sh/setup-uv already caches the downloaded packages (the 15 MB uv cache), the venv can be recreated quickly from that. The venv cache (113 MB) is not worth the trouble. --- .github/actions/setup-python-env/action.yml | 18 ++++-------------- 1 file changed, 4 insertions(+), 14 deletions(-) diff --git a/.github/actions/setup-python-env/action.yml b/.github/actions/setup-python-env/action.yml index 66c225e1..7932cc78 100644 --- a/.github/actions/setup-python-env/action.yml +++ b/.github/actions/setup-python-env/action.yml @@ -22,21 +22,11 @@ runs: with: python-version: ${{ inputs.python-version }} - - name: Cache virtual environment - uses: actions/cache@v4 - id: cache-venv - with: - path: .venv - key: venv-${{ runner.os }}-py${{ inputs.python-version }}-${{ hashFiles('pyproject.toml') }} - - - name: Create venv - if: steps.cache-venv.outputs.cache-hit != 'true' - shell: bash - run: uv venv .venv - - - name: Install dependencies + - name: Create venv and install dependencies shell: bash - run: uv pip install -e ".[${{ inputs.install-extras }}]" + run: | + uv venv .venv + uv pip install -e ".[${{ inputs.install-extras }}]" - name: Add venv to PATH shell: bash