|
12 | 12 | from datetime import datetime, timedelta |
13 | 13 | from threading import Event, Thread |
14 | 14 | from types import GeneratorType |
15 | | -from typing import Any, Generator, Optional, Sequence, TypeVar, Union |
| 15 | +from typing import Any, Generator, Iterator, Optional, Sequence, TypeVar, Union |
16 | 16 |
|
17 | 17 | import grpc |
18 | 18 | from google.protobuf import empty_pb2 |
@@ -282,7 +282,7 @@ class TaskHubGrpcWorker: |
282 | 282 | activity function. |
283 | 283 | """ |
284 | 284 |
|
285 | | - _response_stream: Optional[grpc.Future] = None |
| 285 | + _response_stream: Optional[Union[Iterator[grpc.Future], grpc.Future]] = None |
286 | 286 | _interceptors: Optional[list[shared.ClientInterceptor]] = None |
287 | 287 |
|
288 | 288 | def __init__( |
@@ -420,9 +420,12 @@ def invalidate_connection(): |
420 | 420 | # Cancel the response stream first to signal the reader thread to stop |
421 | 421 | if self._response_stream is not None: |
422 | 422 | try: |
423 | | - self._response_stream.cancel() |
424 | | - except Exception: |
425 | | - pass |
| 423 | + if hasattr(self._response_stream, "call"): |
| 424 | + self._response_stream.call.cancel() # type: ignore |
| 425 | + else: |
| 426 | + self._response_stream.cancel() # type: ignore |
| 427 | + except Exception as e: |
| 428 | + self._logger.warning(f"Error cancelling response stream: {e}") |
426 | 429 | self._response_stream = None |
427 | 430 |
|
428 | 431 | # Wait for the reader thread to finish |
@@ -739,13 +742,13 @@ def stop(self): |
739 | 742 |
|
740 | 743 | self._logger.info("Stopping gRPC worker...") |
741 | 744 | if self._response_stream is not None: |
742 | | - if isinstance(self._response_stream, grpc.Future): |
743 | | - self._response_stream.cancel() |
744 | | - elif hasattr(self._response_stream, "call"): |
745 | | - # This is a generator returned by the gRPC stub |
746 | | - self._response_stream.call.cancel() |
747 | | - else: |
748 | | - self._logger.warning("Unknown response stream type, cannot cancel directly") |
| 745 | + try: |
| 746 | + if hasattr(self._response_stream, "call"): |
| 747 | + self._response_stream.call.cancel() # type: ignore |
| 748 | + else: |
| 749 | + self._response_stream.cancel() # type: ignore |
| 750 | + except Exception as e: |
| 751 | + self._logger.warning(f"Error cancelling response stream: {e}") |
749 | 752 | self._shutdown.set() |
750 | 753 | # Explicitly close the gRPC channel to ensure OTel interceptors and other resources are cleaned up |
751 | 754 | if self._current_channel is not None: |
|
0 commit comments