Skip to content
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

Improve callback handlers #134

Merged
merged 7 commits into from
Oct 11, 2023
Merged
Show file tree
Hide file tree
Changes from 2 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
32 changes: 29 additions & 3 deletions rstream/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
import time
from collections import defaultdict
from contextlib import suppress
from dataclasses import dataclass
from typing import (
Annotated,
Any,
Expand Down Expand Up @@ -57,6 +58,12 @@ class Addr(NamedTuple):
port: int


@dataclass
class FrameEntry:
handler: HT[Any]
frame: schema.Frame


class BaseClient:
def __init__(
self,
Expand Down Expand Up @@ -95,6 +102,7 @@ def __init__(

self._last_heartbeat: float = 0
self._connection_closed_handler = connection_closed_handler
self._frames: asyncio.Queue = asyncio.Queue()

def start_task(self, name: str, coro: Awaitable[None]) -> None:
assert name not in self._tasks
Expand Down Expand Up @@ -172,9 +180,22 @@ async def start(self) -> None:
self._conn = Connection(self.host, self.port, self._ssl_context)
await self._conn.open()
self.start_task("listener", self._listener())
self.start_task("run_delivery_handlers", self._run_delivery_handlers())
self.add_handler(schema.Heartbeat, self._on_heartbeat)
self.add_handler(schema.Close, self._on_close)

async def _run_delivery_handlers(self):

while True:
try:
frame_entry = await self._frames.get()
maybe_coro = await frame_entry.handler(frame_entry.frame)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There's an extra await here

This thing with if maybe_coro is not None was introduced to allow to have both sync and async handlers. The equivalent code would be

if asyncio.iscoroutinefunction(handler):
    await handler(frame)
else:
    handler(frame)

(but if the handler is sync, there's no point in moving it to another asyncio.Task)

if maybe_coro is not None:
await maybe_coro
except Exception as e:
logger.debug("Error reading item from _run_delivery_handlers: " + str(e))
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That seems to be a critical error, probably shouldn't be debug level. Also, currently we're just silently stopping _run_delivery_handlers task without raising any error, it's unclear what the user should do about it.

This try/except wraps both library code and user-provided callback, which is why it's difficult to handle errors carefully. But I think at least we should log an error message (so the user can get a monitoring alert) and if we choose to suppress such kind of errors, the loop shouldn't be stopped:

while True:
    try:
        ...
    except Exception:
        logger.exception("Error while handlilng %s frame", frame.__class__)
        # no break

break

async def _listener(self) -> None:
assert self._conn
while True:
Expand Down Expand Up @@ -206,9 +227,12 @@ async def _listener(self) -> None:

for _, handler in self._handlers.get(frame.__class__, {}).items():
try:
maybe_coro = handler(frame)
if maybe_coro is not None:
await maybe_coro
if frame.__class__ == schema.Deliver:
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This special handling of Deliver frame feels kinda hacky, maybe move this to Consumer._on_deliver?

await self._frames.put(FrameEntry(handler, frame))
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We can get a corresponding handler for a frame when receiving it from self_frames queue, it seems a bit redundant to put handler along with each frame

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

HI @qweeze do you mean to get it from self._handlers in _run_delivery_handlers?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh never mind I think I've understood now!

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

do you mean to get it from self._handlers in _run_delivery_handlers?

Yes, exactly

else:
maybe_coro = handler(frame)
if maybe_coro is not None:
await maybe_coro
except Exception:
logger.exception("Error while running handler %s of frame %s", handler, frame)

Expand Down Expand Up @@ -243,6 +267,7 @@ def is_started(self) -> bool:

async def close(self) -> None:
logger.info("Stopping client %s:%s", self.host, self.port)

if self._conn is None:
return

Expand All @@ -256,6 +281,7 @@ async def close(self) -> None:
resp_schema=schema.CloseResponse,
)

await self.stop_task("run_delivery_handlers")
await self.stop_task("listener")

await self._conn.close()
Expand Down
18 changes: 18 additions & 0 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,24 @@ async def consumer(pytestconfig, ssl_context):
await consumer.close()


@pytest.fixture()
async def test_consumer_close(pytestconfig, ssl_context):
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This fixture fully duplicates the previous one, do we need it?

consumer = Consumer(
host=pytestconfig.getoption("rmq_host"),
port=pytestconfig.getoption("rmq_port"),
ssl_context=ssl_context,
username=pytestconfig.getoption("rmq_username"),
password=pytestconfig.getoption("rmq_password"),
frame_max=1024 * 1024,
heartbeat=60,
)
await consumer.start()
try:
yield consumer
finally:
await consumer.close()


@pytest.fixture()
async def producer(pytestconfig, ssl_context):
producer = Producer(
Expand Down
14 changes: 14 additions & 0 deletions tests/test_consumer.py
Original file line number Diff line number Diff line change
Expand Up @@ -502,3 +502,17 @@ async def test_consume_superstream_with_callback_offset(
consumers_set = consumers_set.union(consumer_stream_list3)

assert len(consumers_set) == 3


async def test_callback_sync_request(stream: str, test_consumer_close: Consumer, producer: Producer) -> None:
captured: list[bytes] = []

async def on_message_first(msg: AMQPMessage, message_context: MessageContext):
captured.append(bytes(msg))
await test_consumer_close.close()

await test_consumer_close.subscribe(stream, callback=on_message_first)
messages = [str(i).encode() for i in range(0, 1)]
await producer.send_batch(stream, messages)

await wait_for(lambda: len(captured) >= 1)