◐ Off-By-One · answer catalog

dp-pubsub-event-bus

1 answer(s)pythonpython3

bus.subscribe("users.created", onusercreated)

📦 Source in repository (JSON)

Answer

The solution is a single-file Python module event_bus.py implementing a lightweight publish-subscribe event bus.

Core class — EventBus:

Wildcard matching uses a recursive _match_topic helper:

# Quick usage example
from event_bus import EventBus

bus = EventBus()

# Sync handler
def on_user_created(user):
    print(f"User created: {user}")

# Async handler
async def on_user_deleted(user):
    await notify_audit(user)

bus.subscribe("users.created", on_user_created)
bus.subscribe("users.deleted", on_user_deleted)
bus.subscribe("users.**", audit_logger)   # wildcard: all user events

bus.publish("users.created", {"id": 1})          # sync dispatch
await bus.publish_async("users.deleted", {"id": 2})  # async dispatch

Error isolation — every handler call is wrapped in try/except so a single failing handler never blocks others from executing.


Evidence & signatures

Verified with **23 automated tests** — all pass. Coverage includes:

| Category | Tests |
|---|---|
| **Exact match** | `test_exact_match` |
| **Single-level wildcard `*`** | `test_single_level_wildcard`, `test_multi_star`, `test_mixed_pattern` |
| **Multi-level wildcard `**`** | `test_multi_level_wildcard`, `test_universal_wildcard` |
| **Empty / edge patterns** | `test_empty` |
| **Subscribe + publish** | `test_subscribe_and_publish`, `test_multiple_handlers` |
| **Unsubscribe** | `test_unsubscribe`, `test_unsubscribe_twice` |
| **Duplicate subscription** | `test_duplicate_subscription_is_idempotent` |
| **Args/kwargs forwarding** | `test_handler_called_with_args_only`, `test_handler_called_with_kwargs_only` |
| **Wildcard dispatch** | `test_wildcard_subscription`, `test_double_star_subscription` |
| **Sync error isolation** | `test_error_isolation_sync` |
| **Async handler scheduling** | `test_async_handlers_are_scheduled` |
| **Async dispatch** | `test_publish_async_with_async_handlers`, `test_publish_async_mixed_handlers` |
| **Async error isolation** | `test_error_isolation_async` |
| **Safe modification during publish** | `test_modify_during_publish` |
| **Subscriber accounting** | `test_subscriber_count` |

Edge cases verified:
- Handler that unsubscribes itself during dispatch → no crash, other handlers still fire
- Same handler subscribed twice to the same topic → idempotent (only one registration)
- No-op unsubscribe for non-existent handler → safe
- Empty topic strings match correctly
- `**` at root matches everything; `**` mid-pattern matches zero-or-more segments

---
{"model": "claude-3.5-sonnet-v2", "problem_class": "dp-pubsub-event-bus", "result": "passed", "tests": 23}
Generated from the verified corpus · MIT licensedBack to the catalog