New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
feat: Implement CPS non-asyncio subscriber #25
Merged
Merged
Changes from 2 commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
18 changes: 18 additions & 0 deletions
18
google/cloud/pubsublite/cloudpubsub/internal/streaming_pull_manager.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,18 @@ | ||
from abc import ABC, abstractmethod | ||
from typing import Optional, Callable | ||
|
||
from google.api_core.exceptions import GoogleAPICallError | ||
|
||
|
||
CloseCallback = Callable[["StreamingPullManager", Optional[GoogleAPICallError]], None] | ||
|
||
|
||
class StreamingPullManager(ABC): | ||
"""The API expected by StreamingPullFuture.""" | ||
@abstractmethod | ||
def add_close_callback(self, close_callback: CloseCallback): | ||
pass | ||
|
||
@abstractmethod | ||
def close(self): | ||
pass |
75 changes: 75 additions & 0 deletions
75
google/cloud/pubsublite/cloudpubsub/internal/subscriber_impl.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,75 @@ | ||
import concurrent.futures | ||
import threading | ||
from asyncio import CancelledError | ||
from concurrent.futures.thread import ThreadPoolExecutor | ||
from typing import ContextManager, Optional | ||
from google.api_core.exceptions import GoogleAPICallError | ||
from google.cloud.pubsublite.cloudpubsub.internal.managed_event_loop import ManagedEventLoop | ||
from google.cloud.pubsublite.cloudpubsub.internal.streaming_pull_manager import StreamingPullManager, CloseCallback | ||
from google.cloud.pubsublite.cloudpubsub.subscriber import AsyncSubscriber, MessageCallback | ||
|
||
|
||
class SubscriberImpl(ContextManager, StreamingPullManager): | ||
_underlying: AsyncSubscriber | ||
_callback: MessageCallback | ||
_executor: ThreadPoolExecutor | ||
|
||
_event_loop: ManagedEventLoop | ||
|
||
_poller_future: concurrent.futures.Future | ||
_close_lock: threading.Lock | ||
_failure: Optional[GoogleAPICallError] | ||
_close_callback: Optional[CloseCallback] | ||
_closed: bool | ||
|
||
def __init__(self, underlying: AsyncSubscriber, callback: MessageCallback, executor: ThreadPoolExecutor): | ||
self._underlying = underlying | ||
self._callback = callback | ||
self._executor = executor | ||
self._event_loop = ManagedEventLoop() | ||
self._close_lock = threading.Lock() | ||
self._failure = None | ||
self._close_callback = None | ||
self._closed = False | ||
|
||
def add_close_callback(self, close_callback: CloseCallback): | ||
with self._close_lock: | ||
assert self._close_callback is None | ||
self._close_callback = close_callback | ||
|
||
def close(self): | ||
with self._close_lock: | ||
if not self._closed: | ||
self._closed = True | ||
self.__exit__(None, None, None) | ||
|
||
def _fail(self, error: GoogleAPICallError): | ||
self._failure = error | ||
self.close() | ||
|
||
async def _poller(self): | ||
try: | ||
while True: | ||
message = await self._underlying.read() | ||
self._executor.submit(self._callback, message) | ||
except GoogleAPICallError as e: | ||
self._executor.submit(lambda: self._fail(e)) | ||
|
||
def __enter__(self): | ||
assert self._close_callback is not None | ||
self._event_loop.__enter__() | ||
self._event_loop.submit(self._underlying.__aenter__()).result() | ||
self._poller_future = self._event_loop.submit(self._poller()) | ||
return self | ||
|
||
def __exit__(self, exc_type, exc_value, traceback): | ||
try: | ||
self._poller_future.cancel() | ||
self._poller_future.result() | ||
except CancelledError: | ||
pass | ||
self._event_loop.submit(self._underlying.__aexit__(exc_type, exc_value, traceback)).result() | ||
self._event_loop.__exit__(exc_type, exc_value, traceback) | ||
assert self._close_callback is not None | ||
self._executor.shutdown(wait=False) # __exit__ may be called from the executor. | ||
self._close_callback(self, self._failure) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
3 changes: 1 addition & 2 deletions
3
tests/unit/pubsublite/cloudpubsub/internal/assigning_subscriber_test.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
93 changes: 93 additions & 0 deletions
93
tests/unit/pubsublite/cloudpubsub/internal/subscriber_impl_test.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,93 @@ | ||
import asyncio | ||
import concurrent | ||
from concurrent.futures.thread import ThreadPoolExecutor | ||
from queue import Queue | ||
|
||
from asynctest.mock import MagicMock | ||
import pytest | ||
from google.api_core.exceptions import FailedPrecondition | ||
from google.cloud.pubsub_v1.subscriber.message import Message | ||
from google.pubsub_v1 import PubsubMessage | ||
|
||
from google.cloud.pubsublite.cloudpubsub.internal.streaming_pull_manager import CloseCallback | ||
from google.cloud.pubsublite.cloudpubsub.internal.subscriber_impl import SubscriberImpl | ||
from google.cloud.pubsublite.cloudpubsub.subscriber import AsyncSubscriber, MessageCallback | ||
from google.cloud.pubsublite.testing.test_utils import Box | ||
|
||
|
||
@pytest.fixture() | ||
def async_subscriber(): | ||
subscriber = MagicMock(spec=AsyncSubscriber) | ||
subscriber.__aenter__.return_value = subscriber | ||
return subscriber | ||
|
||
|
||
@pytest.fixture() | ||
def message_callback(): | ||
return MagicMock(spec=MessageCallback) | ||
|
||
|
||
@pytest.fixture() | ||
def close_callback(): | ||
return MagicMock(spec=CloseCallback) | ||
|
||
|
||
@pytest.fixture() | ||
def subscriber(async_subscriber, message_callback, close_callback): | ||
return SubscriberImpl(async_subscriber, message_callback, ThreadPoolExecutor(max_workers=1)) | ||
|
||
|
||
async def sleep_forever(*args, **kwargs): | ||
await asyncio.sleep(float("inf")) | ||
|
||
|
||
def test_init(subscriber: SubscriberImpl, async_subscriber, close_callback): | ||
async_subscriber.read.side_effect = sleep_forever | ||
subscriber.add_close_callback(close_callback) | ||
subscriber.__enter__() | ||
async_subscriber.__aenter__.assert_called_once() | ||
subscriber.close() | ||
async_subscriber.__aexit__.assert_called_once() | ||
close_callback.assert_called_once_with(subscriber, None) | ||
|
||
|
||
def test_failed(subscriber: SubscriberImpl, async_subscriber, close_callback): | ||
error = FailedPrecondition("bad read") | ||
async_subscriber.read.side_effect = error | ||
|
||
close_called = concurrent.futures.Future() | ||
close_callback.side_effect = lambda manager, err: close_called.set_result(None) | ||
|
||
subscriber.add_close_callback(close_callback) | ||
subscriber.__enter__() | ||
async_subscriber.__aenter__.assert_called_once() | ||
close_called.result() | ||
async_subscriber.__aexit__.assert_called_once() | ||
close_callback.assert_called_once_with(subscriber, error) | ||
|
||
|
||
def test_messages_received(subscriber: SubscriberImpl, async_subscriber, message_callback, close_callback): | ||
message1 = Message(PubsubMessage(message_id="1")._pb, "", 0, None) | ||
message2 = Message(PubsubMessage(message_id="2")._pb, "", 0, None) | ||
|
||
counter = Box[int]() | ||
counter.val = 0 | ||
|
||
async def on_read() -> Message: | ||
counter.val += 1 | ||
if counter.val == 1: | ||
return message1 | ||
if counter.val == 2: | ||
return message2 | ||
await sleep_forever() | ||
|
||
async_subscriber.read.side_effect = on_read | ||
|
||
results = Queue() | ||
message_callback.side_effect = lambda m: results.put(m.message_id) | ||
|
||
subscriber.add_close_callback(close_callback) | ||
subscriber.__enter__() | ||
assert results.get() == "1" | ||
assert results.get() == "2" | ||
subscriber.close() |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
IIUC, we will fail if close_callback is None. I'd personally make this optional, but if you choose not to do this, can you document this?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Done.