Skip to content

Commit

Permalink
Add event_id field to Event base class (#5)
Browse files Browse the repository at this point in the history
* Add `event_id` field to `Event` base class

* Add IDE files to gitignore
  • Loading branch information
GauthamGoli authored May 6, 2022
1 parent 07b1aa4 commit 53919e2
Show file tree
Hide file tree
Showing 4 changed files with 46 additions and 7 deletions.
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,9 @@ share/python-wheels/
*.egg
MANIFEST

#IDE
.idea*

# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
Expand Down
32 changes: 28 additions & 4 deletions eventbusk/bus.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,9 @@
import json
import logging
import time
import uuid
from abc import ABC
from dataclasses import asdict, dataclass
from dataclasses import asdict, dataclass, field
from functools import wraps
from typing import Callable, Type, Union

Expand All @@ -31,6 +32,14 @@ class MyEvent(Event):
foo: int
bar: str
"""
event_id: uuid.UUID = field(default_factory=uuid.uuid4, init=False)


class EventJsonEncoder(json.JSONEncoder):
def default(self, o):
if isinstance(o, uuid.UUID):
return str(o)
return json.JSONEncoder.default(self, o)


EventT = Type[Event]
Expand Down Expand Up @@ -120,8 +129,7 @@ def send(
event_fqn = self.to_fqn(event.__class__)
# TODO: Ensure unknown event throws a error.
topic = self._event_to_topic[event_fqn]

data = json.dumps(asdict(event)).encode("utf-8")
data = json.dumps(asdict(event), cls=EventJsonEncoder).encode("utf-8")
try:
self.producer.produce(
topic=topic, value=data, flush=flush, on_delivery=on_delivery
Expand All @@ -131,7 +139,7 @@ def send(
if fail_silently:
logger.warning(
"Error producing event.",
extra={"event": event_fqn, "topic": topic},
extra={"event": event_fqn, "topic": topic, "event_id": event.event_id},
exc_info=True,
)
else:
Expand Down Expand Up @@ -216,9 +224,25 @@ def wrapper() -> None:
msg_value = message.value().decode("utf-8") # type: ignore
event_data = json.loads(msg_value)

if "event_id" in event_data:
try:
event_id = uuid.UUID(event_data.pop('event_id'))
except ValueError:
logger.exception(
(
"Error while converting str -> UUID "
),
extra={**log_context, **{"data": event_data}},
exc_info=True,
)
pass
else:
event_id = None

# TODO: Fix following
# Too many arguments for "Event" [call-arg]
event = event_type(**event_data) # type: ignore
setattr(event, 'event_id', event_id)

try:
func(event)
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[tool.poetry]
name = "eventbusk"
version = "0.1.0"
version = "0.1.1"
description = "Event bus with Kafka"
authors = ["Airbase Inc <[email protected]>"]

Expand Down
16 changes: 14 additions & 2 deletions tests/test_bus.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
from __future__ import annotations

import logging
import uuid
from dataclasses import dataclass

from pytest_mock import MockerFixture
Expand Down Expand Up @@ -43,8 +44,13 @@ def test_bus_send(mocker: MockerFixture) -> None:
# Given events registered to certain topics
bus.register_event(topic="first_topic", event_type=Foo)
bus.register_event(topic="second_topic", event_type=Bar)

foo_event_uuid = uuid.uuid4()
bar_event_uuid = uuid.uuid4()
foo_event = Foo(first=1)
foo_event.event_id = foo_event_uuid
bar_event = Bar(second=1)
bar_event.event_id = bar_event_uuid

# When we send events of a different types
def on_delivery(error: str, event: Event) -> None:
Expand All @@ -62,13 +68,19 @@ def on_delivery(error: str, event: Event) -> None:
[
mocker.call(
topic="first_topic",
value=b'{"first": 1}',
value=bytes(
'{{"event_id": "{foo_event_uuid}", "first": 1}}'.format(foo_event_uuid=str(foo_event_uuid)),
"utf-8"
),
flush=True,
on_delivery=on_delivery,
),
mocker.call(
topic="second_topic",
value=b'{"second": 1}',
value=bytes(
'{{"event_id": "{bar_event_uuid}", "second": 1}}'.format(bar_event_uuid=str(bar_event_uuid)),
"utf-8"
),
flush=True,
on_delivery=on_delivery,
),
Expand Down

0 comments on commit 53919e2

Please sign in to comment.