Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 45 additions & 6 deletions dapr/aio/clients/grpc/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -92,17 +93,22 @@
RegisteredComponents,
StateResponse,
TopicEventResponse,
TopicEventResponseStatus,
TryLockResponse,
UnlockResponse,
UnlockResponseStatus,
)
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.
Expand Down Expand Up @@ -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

Expand Down
27 changes: 20 additions & 7 deletions dapr/clients/grpc/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,7 @@
RegisteredComponents,
StateResponse,
TopicEventResponse,
TopicEventResponseStatus,
TryLockResponse,
UnlockResponse,
UnlockResponseStatus,
Expand Down Expand Up @@ -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:
Expand All @@ -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():
Expand Down
109 changes: 55 additions & 54 deletions tests/clients/test_dapr_grpc_client_async.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down