From 9d0236e259453ed14a3a5445301be37d4ad391ab Mon Sep 17 00:00:00 2001 From: atharv20s Date: Sat, 28 Nov 2026 14:59:22 +0530 Subject: [PATCH] fix(pubsub): keep subscribe_with_handler retrying and handle errors properly (#1233) Signed-off-by: atharv20s --- dapr/aio/clients/grpc/client.py | 51 ++++++++- dapr/clients/grpc/client.py | 27 +++-- tests/clients/test_dapr_grpc_client_async.py | 109 ++++++++++--------- 3 files changed, 120 insertions(+), 67 deletions(-) diff --git a/dapr/aio/clients/grpc/client.py b/dapr/aio/clients/grpc/client.py index e1e7fba92..6a2e6daaf 100644 --- a/dapr/aio/clients/grpc/client.py +++ b/dapr/aio/clients/grpc/client.py @@ -14,6 +14,7 @@ """ import asyncio +import logging import socket import time from typing import Any, Awaitable, BinaryIO, Callable, Dict, List, Optional, Sequence, Text, Union @@ -92,6 +93,7 @@ RegisteredComponents, StateResponse, TopicEventResponse, + TopicEventResponseStatus, TryLockResponse, UnlockResponse, UnlockResponseStatus, @@ -99,10 +101,14 @@ from dapr.clients.grpc._state import StateItem, StateOptions from dapr.clients.health import DaprHealth from dapr.clients.retry import RetryPolicy -from dapr.common.pubsub.subscription import StreamInactiveError +from dapr.common.pubsub.subscription import StreamCancelledError, StreamInactiveError from dapr.proto import api_service_v1, api_v1, common_v1 from dapr.proto.runtime.v1 import binarystore_pb2 as binary_v1 +logger = logging.getLogger(__name__) + +SUBSCRIPTION_CLOSE_TIMEOUT_SECONDS = 5 + class DaprGrpcClientAsync: """The async convenient layer implementation of Dapr gRPC APIs. @@ -599,21 +605,54 @@ async def subscribe_with_handler( async def stream_messages(sub: Subscription): while True: try: - async for message in subscription: + async for message in sub: if message: - response = await handler_fn(message) + try: + response = await handler_fn(message) + except Exception: + logger.exception( + 'Error in subscription handler for topic %s', topic + ) + await subscription.respond( + message, TopicEventResponseStatus.retry + ) + continue if response: await subscription.respond(message, response.status) else: continue - except StreamInactiveError: + except (StreamInactiveError, StreamCancelledError): break + except Exception: + while not sub._closed.is_set(): + try: + await sub.reconnect_stream() + break + except Exception: + try: + await asyncio.wait_for(sub._closed.wait(), timeout=5) + break + except asyncio.TimeoutError: + pass + if sub._closed.is_set(): + break + continue + + streaming_task = asyncio.create_task(stream_messages(subscription)) async def close_subscription(): await subscription.close() - - asyncio.create_task(stream_messages(subscription)) + if asyncio.current_task() is not streaming_task: + try: + await asyncio.wait_for( + streaming_task, timeout=SUBSCRIPTION_CLOSE_TIMEOUT_SECONDS + ) + except asyncio.TimeoutError: + logger.warning( + 'Subscription handler task still running %ss after close', + SUBSCRIPTION_CLOSE_TIMEOUT_SECONDS, + ) return close_subscription diff --git a/dapr/clients/grpc/client.py b/dapr/clients/grpc/client.py index 3384688eb..f02c6ddcb 100644 --- a/dapr/clients/grpc/client.py +++ b/dapr/clients/grpc/client.py @@ -87,6 +87,7 @@ RegisteredComponents, StateResponse, TopicEventResponse, + TopicEventResponseStatus, TryLockResponse, UnlockResponse, UnlockResponseStatus, @@ -650,7 +651,14 @@ def stream_messages(sub): for message in sub: if message: # Process the message - response = handler_fn(message) + try: + response = handler_fn(message) + except Exception: + logger.exception( + 'Error in subscription handler for topic %s', topic + ) + subscription.respond(message, TopicEventResponseStatus.retry) + continue if response: subscription.respond(message, response.status) else: @@ -662,12 +670,17 @@ def stream_messages(sub): except Exception: # Stream died — reconnect via the subscription's own # reconnect logic (which waits for the sidecar to be healthy). - try: - sub.reconnect_stream() - except Exception: - # Sidecar still unavailable — back off before retrying - # TODO: Make this configurable - time.sleep(5) + while not sub._closed.is_set(): + try: + sub.reconnect_stream() + break + except Exception: + # Sidecar still unavailable — back off before retrying + # TODO: Make this configurable + if sub._closed.wait(5): + break + if sub._closed.is_set(): + break continue def close_subscription(): diff --git a/tests/clients/test_dapr_grpc_client_async.py b/tests/clients/test_dapr_grpc_client_async.py index 49d365487..290478891 100644 --- a/tests/clients/test_dapr_grpc_client_async.py +++ b/tests/clients/test_dapr_grpc_client_async.py @@ -591,60 +591,61 @@ def start_backoff(reconnect_attempts): await subscription.close() await dapr.close() - # async def test_subscribe_topic_with_handler(self): - # # The fake server we're using sends two messages and then closes the stream - # # The client should be able to read both messages, handle the stream closure and reconnect - # # which will result in reading the same two messages again. - # # That's why message 3 should be the same as message 1 - # dapr = DaprGrpcClientAsync(f'{self.scheme}localhost:{self.grpc_port}') - # counter = 0 - # - # async def handler(message): - # nonlocal counter - # if counter == 0: - # self.assertEqual('111', message.id()) - # self.assertEqual('app1', message.source()) - # self.assertEqual('com.example.type2', message.type()) - # self.assertEqual('1.0', message.spec_version()) - # self.assertEqual('text/plain', message.data_content_type()) - # self.assertEqual('TOPIC_A', message.topic()) - # self.assertEqual('pubsub', message.pubsub_name()) - # self.assertEqual(b'hello2', message.raw_data()) - # self.assertEqual('text/plain', message.data_content_type()) - # self.assertEqual('hello2', message.data()) - # elif counter == 1: - # self.assertEqual('222', message.id()) - # self.assertEqual('app1', message.source()) - # self.assertEqual('com.example.type2', message.type()) - # self.assertEqual('1.0', message.spec_version()) - # self.assertEqual('TOPIC_A', message.topic()) - # self.assertEqual('pubsub', message.pubsub_name()) - # self.assertEqual(b'{"a": 1}', message.raw_data()) - # self.assertEqual('application/json', message.data_content_type()) - # self.assertEqual({'a': 1}, message.data()) - # elif counter == 2: - # self.assertEqual('111', message.id()) - # self.assertEqual('app1', message.source()) - # self.assertEqual('com.example.type2', message.type()) - # self.assertEqual('1.0', message.spec_version()) - # self.assertEqual('text/plain', message.data_content_type()) - # self.assertEqual('TOPIC_A', message.topic()) - # self.assertEqual('pubsub', message.pubsub_name()) - # self.assertEqual(b'hello2', message.raw_data()) - # self.assertEqual('text/plain', message.data_content_type()) - # self.assertEqual('hello2', message.data()) - # - # counter += 1 - # - # return TopicEventResponse("success") - # - # close_fn = await dapr.subscribe_with_handler( - # pubsub_name='pubsub', topic='example', handler_fn=handler - # ) - # - # while counter < 3: - # await asyncio.sleep(0.1) # sleep to prevent a busy loop - # await close_fn() + async def test_subscribe_topic_with_handler(self): + # The fake server we're using sends two messages and then closes the stream + # The client should be able to read both messages, handle the stream closure and reconnect + # which will result in reading the same two messages again. + # That's why message 3 should be the same as message 1 + dapr = DaprGrpcClientAsync(f'{self.scheme}localhost:{self.grpc_port}') + counter = 0 + + async def handler(message): + nonlocal counter + if counter == 0: + self.assertEqual('111', message.id()) + self.assertEqual('app1', message.source()) + self.assertEqual('com.example.type2', message.type()) + self.assertEqual('1.0', message.spec_version()) + self.assertEqual('text/plain', message.data_content_type()) + self.assertEqual('TOPIC_A', message.topic()) + self.assertEqual('pubsub', message.pubsub_name()) + self.assertEqual(b'hello2', message.raw_data()) + self.assertEqual('text/plain', message.data_content_type()) + self.assertEqual('hello2', message.data()) + elif counter == 1: + self.assertEqual('222', message.id()) + self.assertEqual('app1', message.source()) + self.assertEqual('com.example.type2', message.type()) + self.assertEqual('1.0', message.spec_version()) + self.assertEqual('TOPIC_A', message.topic()) + self.assertEqual('pubsub', message.pubsub_name()) + self.assertEqual(b'{"a": 1}', message.raw_data()) + self.assertEqual('application/json', message.data_content_type()) + self.assertEqual({'a': 1}, message.data()) + elif counter == 2: + self.assertEqual('111', message.id()) + self.assertEqual('app1', message.source()) + self.assertEqual('com.example.type2', message.type()) + self.assertEqual('1.0', message.spec_version()) + self.assertEqual('text/plain', message.data_content_type()) + self.assertEqual('TOPIC_A', message.topic()) + self.assertEqual('pubsub', message.pubsub_name()) + self.assertEqual(b'hello2', message.raw_data()) + self.assertEqual('text/plain', message.data_content_type()) + self.assertEqual('hello2', message.data()) + + counter += 1 + + return TopicEventResponse('success') + + close_fn = await dapr.subscribe_with_handler( + pubsub_name='pubsub', topic='example', handler_fn=handler + ) + + while counter < 3: + await asyncio.sleep(0.1) # sleep to prevent a busy loop + await close_fn() + await dapr.close() @patch.object(settings, 'DAPR_API_TOKEN', 'test-token') async def test_dapr_api_token_insertion(self):