Skip to content

Allow the dispatcher to call handlers synchronously #68

Description

@djalexd

The current implementation will either store the dispatched event in event_store or create an asyncio.Task that is never awaited.

https://github.com/melvinkcx/fastapi-events/blob/dev/fastapi_events/dispatcher.py#L81

There are 2 situations where I believe synchronous handling is useful:

  1. unit-testing. My current approach involves a somewhat complicated setup with a fixture:
@pytest.fixture(autouse=True)
def register_local_handlers():
    _id = 0
    token_middleware_id = middleware_identifier.set(_id)
    try:
        handler_store.update({_id: [local_handler]})
        yield
    finally:
        del handler_store[_id]
        middleware_identifier.reset(token_middleware_id)

this allows the registered local handlers to be invoked whenever I do a dispatch from tests

@pytest.mark.asyncio
async def test_save_success():
    with patch.object(DB, "save", new_callable=AsyncMock) as mock_save:
      dispatch("test-event", "test-payload")
     # here I cannot directly assert that handler performed something.
    
     # this is needed:
     await asyncio.gather(*asyncio.all_tasks())
  1. having a handler that in turn forwards the event to some topic (i.e. SQS, SNS, Kinesis, Kafka), because this operation is very fast anyway. For example a retry policy would be hard to implement because there is no way I can await just for this dispatch task.

Any advice is welcome! I was also considering simply duplicating the dispatcher.py code as an alternative

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions