busline 0.3.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- __init__.py +0 -0
- busline-0.3.0.dist-info/LICENSE +674 -0
- busline-0.3.0.dist-info/METADATA +104 -0
- busline-0.3.0.dist-info/RECORD +30 -0
- busline-0.3.0.dist-info/WHEEL +5 -0
- busline-0.3.0.dist-info/top_level.txt +4 -0
- event/__init__.py +0 -0
- event/event.py +25 -0
- event/event_content.py +18 -0
- event/event_metadata.py +26 -0
- eventbus/__init__.py +0 -0
- eventbus/async_local_eventbus.py +32 -0
- eventbus/eventbus.py +112 -0
- eventbus/exceptions.py +2 -0
- eventbus/queued_local_eventbus.py +50 -0
- eventbus/topic.py +35 -0
- eventbus_client/__init__.py +0 -0
- eventbus_client/eventbus_client.py +99 -0
- eventbus_client/eventbus_connector.py +37 -0
- eventbus_client/exceptions.py +4 -0
- eventbus_client/local_eventbus_client.py +25 -0
- eventbus_client/publisher/__init__.py +0 -0
- eventbus_client/publisher/local_eventbus_publisher.py +35 -0
- eventbus_client/publisher/publisher.py +59 -0
- eventbus_client/subscriber/__init__.py +0 -0
- eventbus_client/subscriber/closure_event_listener.py +19 -0
- eventbus_client/subscriber/event_listener.py +15 -0
- eventbus_client/subscriber/local_eventbus_closure_subscriber.py +17 -0
- eventbus_client/subscriber/local_eventbus_subscriber.py +40 -0
- eventbus_client/subscriber/subscriber.py +93 -0
@@ -0,0 +1,104 @@
|
|
1
|
+
Metadata-Version: 2.1
|
2
|
+
Name: busline
|
3
|
+
Version: 0.3.0
|
4
|
+
Summary: Agnostic eventbus for Python
|
5
|
+
Author-email: Nicola Ricciardi <ricciardincl@gmail.com>
|
6
|
+
Project-URL: Homepage, https://github.com/nricciardi/py-busline
|
7
|
+
Project-URL: Issues, https://github.com/nricciardi/py-busline/issues
|
8
|
+
Classifier: Programming Language :: Python :: 3
|
9
|
+
Classifier: License :: OSI Approved :: GNU General Public License v3 (GPLv3)
|
10
|
+
Classifier: Operating System :: OS Independent
|
11
|
+
Requires-Python: >=3.8
|
12
|
+
Description-Content-Type: text/markdown
|
13
|
+
License-File: LICENSE
|
14
|
+
|
15
|
+
# Busline for Python
|
16
|
+
|
17
|
+
Agnostic eventbus for Python.
|
18
|
+
|
19
|
+
Official eventbus library for [Orbitalis](https://github.com/nricciardi/orbitalis)
|
20
|
+
|
21
|
+
## Local EventBus
|
22
|
+
|
23
|
+
### Using Publisher/Subscriber
|
24
|
+
|
25
|
+
```python
|
26
|
+
from src.eventbus.async_local_eventbus import AsyncLocalEventBus
|
27
|
+
from src.eventbus_client.publisher.local_eventbus_publisher import LocalEventBusPublisher
|
28
|
+
from src.event.event import Event
|
29
|
+
from src.eventbus_client.subscriber.local_eventbus_closure_subscriber import LocalEventBusClosureSubscriber
|
30
|
+
|
31
|
+
|
32
|
+
local_eventbus_instance = AsyncLocalEventBus() # singleton
|
33
|
+
|
34
|
+
def callback(topic_name: str, event: Event):
|
35
|
+
print(event)
|
36
|
+
|
37
|
+
subscriber = LocalEventBusClosureSubscriber(local_eventbus_instance, callback)
|
38
|
+
publisher = LocalEventBusPublisher(local_eventbus_instance)
|
39
|
+
|
40
|
+
await subscriber.subscribe("test-topic")
|
41
|
+
|
42
|
+
await publisher.publish("test-topic", Event()) # publish empty event
|
43
|
+
```
|
44
|
+
|
45
|
+
### Using EventBusClient
|
46
|
+
|
47
|
+
```python
|
48
|
+
from src.event.event import Event
|
49
|
+
from src.eventbus_client.local_eventbus_client import LocalEventBusClient
|
50
|
+
|
51
|
+
def callback(topic_name: str, event: Event):
|
52
|
+
print(event)
|
53
|
+
|
54
|
+
client = LocalEventBusClient(callback)
|
55
|
+
|
56
|
+
await client.subscribe("test")
|
57
|
+
|
58
|
+
await client.publish("test", Event())
|
59
|
+
```
|
60
|
+
|
61
|
+
|
62
|
+
## Create Agnostic EventBus
|
63
|
+
|
64
|
+
Implement business logic of your `Publisher` and `Subscriber` and... done. Nothing more.
|
65
|
+
|
66
|
+
```python
|
67
|
+
from src.event.event import Event
|
68
|
+
from src.eventbus_client.publisher.publisher import Publisher
|
69
|
+
|
70
|
+
class YourEventBusPublisher(Publisher):
|
71
|
+
|
72
|
+
async def _internal_publish(self, topic_name: str, event: Event, **kwargs):
|
73
|
+
pass # send events to your eventbus (maybe in cloud?)
|
74
|
+
```
|
75
|
+
|
76
|
+
```python
|
77
|
+
from src.eventbus_client.subscriber.subscriber import Subscriber
|
78
|
+
from src.event.event import Event
|
79
|
+
|
80
|
+
class YourEventBusSubscriber(Subscriber):
|
81
|
+
|
82
|
+
async def on_event(self, topic_name: str, event: Event, **kwargs):
|
83
|
+
pass # receive your events
|
84
|
+
```
|
85
|
+
|
86
|
+
You could create a client to allow components to use it instead of become a publisher or subscriber.
|
87
|
+
|
88
|
+
```python
|
89
|
+
from src.eventbus_client.eventbus_client import EventBusClient
|
90
|
+
from src.event.event import Event
|
91
|
+
|
92
|
+
def client_callback(topic_name: str, e: Event):
|
93
|
+
print(e)
|
94
|
+
|
95
|
+
subscriber = YourEventBusSubscriber(...)
|
96
|
+
publisher = YourEventBusPublisher(...)
|
97
|
+
|
98
|
+
client = EventBusClient(publisher, subscriber, ClosureEventListener(client_callback))
|
99
|
+
```
|
100
|
+
|
101
|
+
|
102
|
+
|
103
|
+
|
104
|
+
|
@@ -0,0 +1,30 @@
|
|
1
|
+
__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
2
|
+
event/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
3
|
+
event/event.py,sha256=X5HSO6SDoxUFrxMJ9gzll2lr_M5li_09o2we5hMLbUI,587
|
4
|
+
event/event_content.py,sha256=tPvltxfs66yRmUppHvdw5ThYR_K2WitvE5sLybg6vZE,341
|
5
|
+
event/event_metadata.py,sha256=7aaSG4Z9uQzJKRe7Jz8zD6jo6WEo3PORNbJA_RElp8I,556
|
6
|
+
eventbus/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
7
|
+
eventbus/async_local_eventbus.py,sha256=cRAnUPfb22q9CzNS-48aGIdxhEgwg-nGHaAhvaeVIgI,764
|
8
|
+
eventbus/eventbus.py,sha256=INT1DYL_rlyViLTGfEpPisDFp8JUuNJ55ZOuQUjh2E4,2981
|
9
|
+
eventbus/exceptions.py,sha256=sjWa3Eyeqyci2yVWO9jSlnaZggM3SFDbTKzMtdBX1-E,40
|
10
|
+
eventbus/queued_local_eventbus.py,sha256=7Gog7Xy6ytBTkXvUKXsSqXSkarZtiCvGg-qdiQPAQDo,1368
|
11
|
+
eventbus/topic.py,sha256=rzbdYrv0YLbC6CDoFGhbc8dOVc19OHCQknkTP4fZHh4,950
|
12
|
+
eventbus_client/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
13
|
+
eventbus_client/eventbus_client.py,sha256=1n53QBf-lvoe_lJhg7gttpOWnl3db9WoKRoJj7z7dBM,3079
|
14
|
+
eventbus_client/eventbus_connector.py,sha256=zys73X8ul1UHyJHbIcmXBLucqCQhnLLVj9xDOVc1arU,702
|
15
|
+
eventbus_client/exceptions.py,sha256=gm7oZsXHlymheYDZb209T4FqeZN9Saft0Xklk4rOg54,55
|
16
|
+
eventbus_client/local_eventbus_client.py,sha256=gep5sO6Oek8y-wQEe-VMlbrboAlUI4QlrNihROY9A5E,867
|
17
|
+
eventbus_client/publisher/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
18
|
+
eventbus_client/publisher/local_eventbus_publisher.py,sha256=fizpHwZGEDuZJHMbBC76jzzcCzbvrp1oIXYKb7KsXi4,1107
|
19
|
+
eventbus_client/publisher/publisher.py,sha256=QzaXlKwlURA4UXUgbkyKwUxaKWbayt5tYNGHy5TtI_Q,1536
|
20
|
+
eventbus_client/subscriber/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
21
|
+
eventbus_client/subscriber/closure_event_listener.py,sha256=1vou3bedIIeuDzdYRJeoEvdNMZtJP_SgnxLboTgFiEg,599
|
22
|
+
eventbus_client/subscriber/event_listener.py,sha256=nBnPA-Jt5_L0qCV-IaTfmr1RTnKe_zMRF3Ce8ciX-4M,327
|
23
|
+
eventbus_client/subscriber/local_eventbus_closure_subscriber.py,sha256=7KPlkMXqwKMBgPhp4U6xkca-oGErdO8ch3W7Ab0XpbI,748
|
24
|
+
eventbus_client/subscriber/local_eventbus_subscriber.py,sha256=f7Vf4IpLeQ2IaMd9kwFUGT7hXrp1AeKHintyQONJ7YE,1331
|
25
|
+
eventbus_client/subscriber/subscriber.py,sha256=MMw_iOVEflBTLiYuEbS--hZ_fOJ3Y82wk6N0BOJXNVA,2246
|
26
|
+
busline-0.3.0.dist-info/LICENSE,sha256=OXLcl0T2SZ8Pmy2_dmlvKuetivmyPd5m1q-Gyd-zaYY,35149
|
27
|
+
busline-0.3.0.dist-info/METADATA,sha256=EzrREZWnK4NQ3ycylqWGSeNPwlRDfaOiijgm_nxiSX8,2891
|
28
|
+
busline-0.3.0.dist-info/WHEEL,sha256=PZUExdf71Ui_so67QXpySuHtCi3-J3wvF4ORK6k_S8U,91
|
29
|
+
busline-0.3.0.dist-info/top_level.txt,sha256=tVHbqJlz1BKM3vq9VKiyjRf2irKCgXPV22iae_fcMss,40
|
30
|
+
busline-0.3.0.dist-info/RECORD,,
|
event/__init__.py
ADDED
File without changes
|
event/event.py
ADDED
@@ -0,0 +1,25 @@
|
|
1
|
+
import uuid
|
2
|
+
from src.event.event_content import EventContent
|
3
|
+
from src.event.event_metadata import EventMetadata
|
4
|
+
|
5
|
+
|
6
|
+
class Event:
|
7
|
+
|
8
|
+
def __init__(self, content: EventContent = None, metadata: EventMetadata = EventMetadata()):
|
9
|
+
|
10
|
+
self._identifier = str(uuid.uuid4())
|
11
|
+
self._content = content
|
12
|
+
self._metadata = metadata
|
13
|
+
|
14
|
+
|
15
|
+
@property
|
16
|
+
def identifier(self) -> str:
|
17
|
+
return self._identifier
|
18
|
+
|
19
|
+
@property
|
20
|
+
def content(self) -> EventContent:
|
21
|
+
return self._content
|
22
|
+
|
23
|
+
@property
|
24
|
+
def metadata(self) -> EventMetadata:
|
25
|
+
return self._metadata
|
event/event_content.py
ADDED
@@ -0,0 +1,18 @@
|
|
1
|
+
from typing import Any
|
2
|
+
|
3
|
+
|
4
|
+
class EventContent:
|
5
|
+
|
6
|
+
def __init__(self, content: Any, content_type: str):
|
7
|
+
|
8
|
+
self.__content = content
|
9
|
+
self.__content_type = content_type
|
10
|
+
|
11
|
+
|
12
|
+
@property
|
13
|
+
def content(self) -> Any:
|
14
|
+
return self.__content
|
15
|
+
|
16
|
+
@property
|
17
|
+
def content_type(self) -> str:
|
18
|
+
return self.__content_type
|
event/event_metadata.py
ADDED
@@ -0,0 +1,26 @@
|
|
1
|
+
from datetime import timezone
|
2
|
+
import datetime
|
3
|
+
|
4
|
+
|
5
|
+
def utc_timestamp() -> float:
|
6
|
+
dt = datetime.datetime.now(timezone.utc)
|
7
|
+
|
8
|
+
utc_time = dt.replace(tzinfo=timezone.utc)
|
9
|
+
utc_timestamp = utc_time.timestamp()
|
10
|
+
|
11
|
+
return utc_timestamp
|
12
|
+
|
13
|
+
|
14
|
+
class EventMetadata:
|
15
|
+
|
16
|
+
def __init__(self, timestamp: float = utc_timestamp(), **extra: dict):
|
17
|
+
self.__timestamp = timestamp
|
18
|
+
self.__extra = extra
|
19
|
+
|
20
|
+
@property
|
21
|
+
def timestamp(self) -> float:
|
22
|
+
return self.__timestamp
|
23
|
+
|
24
|
+
@property
|
25
|
+
def extra(self) -> dict:
|
26
|
+
return self.__extra
|
eventbus/__init__.py
ADDED
File without changes
|
@@ -0,0 +1,32 @@
|
|
1
|
+
import logging
|
2
|
+
import asyncio
|
3
|
+
|
4
|
+
from src.event.event import Event
|
5
|
+
from src.eventbus.eventbus import EventBus
|
6
|
+
|
7
|
+
|
8
|
+
class AsyncLocalEventBus(EventBus):
|
9
|
+
"""
|
10
|
+
Async local eventbus (singleton)
|
11
|
+
|
12
|
+
Author: Nicola Ricciardi
|
13
|
+
"""
|
14
|
+
|
15
|
+
async def put_event(self, topic_name: str, event: Event):
|
16
|
+
|
17
|
+
topic_subscriptions = self.subscriptions.get(topic_name, [])
|
18
|
+
|
19
|
+
logging.debug(f"new event {event} on topic {topic_name}, notify subscribers: {topic_subscriptions}")
|
20
|
+
|
21
|
+
if len(topic_subscriptions) == 0:
|
22
|
+
return
|
23
|
+
|
24
|
+
tasks = []
|
25
|
+
|
26
|
+
for subscriber in topic_subscriptions:
|
27
|
+
task = asyncio.create_task(subscriber.on_event(topic_name, event))
|
28
|
+
tasks.append(task)
|
29
|
+
|
30
|
+
await asyncio.gather(*tasks)
|
31
|
+
|
32
|
+
|
eventbus/eventbus.py
ADDED
@@ -0,0 +1,112 @@
|
|
1
|
+
from abc import ABC, abstractmethod
|
2
|
+
from typing import Dict, List
|
3
|
+
from src.eventbus.exceptions import TopicNotFound
|
4
|
+
from src.eventbus_client.subscriber.subscriber import Subscriber
|
5
|
+
from src.eventbus.topic import Topic
|
6
|
+
from src.event.event import Event
|
7
|
+
|
8
|
+
|
9
|
+
|
10
|
+
class EventBus(ABC):
|
11
|
+
"""
|
12
|
+
Abstract class used as base for new eventbus implemented in local projects.
|
13
|
+
|
14
|
+
Eventbus are *singleton*
|
15
|
+
|
16
|
+
Author: Nicola Ricciardi
|
17
|
+
"""
|
18
|
+
|
19
|
+
# === SINGLETON pattern ===
|
20
|
+
_instance = None
|
21
|
+
|
22
|
+
def __new__(cls, *args, **kwargs):
|
23
|
+
if cls._instance is None:
|
24
|
+
cls._instance = super().__new__(cls)
|
25
|
+
|
26
|
+
return cls._instance
|
27
|
+
|
28
|
+
def __init__(self):
|
29
|
+
|
30
|
+
self.__subscriptions = None
|
31
|
+
self.__topics = None
|
32
|
+
|
33
|
+
self.reset_topics()
|
34
|
+
|
35
|
+
def reset_topics(self):
|
36
|
+
self.__topics: Dict[str, Topic] = {}
|
37
|
+
self.__subscriptions: Dict[str, List[Subscriber]] = {}
|
38
|
+
|
39
|
+
def add_topic(self, topic: Topic):
|
40
|
+
self.__topics[topic.name] = topic
|
41
|
+
self.__subscriptions[topic.name] = []
|
42
|
+
|
43
|
+
def remove_topic(self, topic_name: str):
|
44
|
+
"""
|
45
|
+
Remove topic by name
|
46
|
+
|
47
|
+
:param topic_name:
|
48
|
+
:return:
|
49
|
+
"""
|
50
|
+
|
51
|
+
del self.__topics[topic_name]
|
52
|
+
del self.__subscriptions[topic_name]
|
53
|
+
|
54
|
+
@property
|
55
|
+
def topics(self) -> Dict[str, Topic]:
|
56
|
+
return self.__topics
|
57
|
+
|
58
|
+
@property
|
59
|
+
def subscriptions(self) -> Dict[str, List[Subscriber]]:
|
60
|
+
return self.__subscriptions
|
61
|
+
|
62
|
+
def add_subscriber(self, topic_name: str, subscriber: Subscriber, raise_if_topic_missed: bool = False):
|
63
|
+
"""
|
64
|
+
Add subscriber to topic
|
65
|
+
|
66
|
+
:param raise_if_topic_missed:
|
67
|
+
:param topic_name:
|
68
|
+
:param subscriber:
|
69
|
+
:return:
|
70
|
+
"""
|
71
|
+
|
72
|
+
if topic_name not in self.__topics:
|
73
|
+
if raise_if_topic_missed:
|
74
|
+
raise TopicNotFound(f"topic '{topic_name}' not found")
|
75
|
+
|
76
|
+
else:
|
77
|
+
self.add_topic(Topic(topic_name))
|
78
|
+
|
79
|
+
self.__subscriptions[topic_name].append(subscriber)
|
80
|
+
|
81
|
+
def remove_subscriber(self, subscriber: Subscriber, topic_name: str = None, raise_if_topic_missed: bool = False):
|
82
|
+
"""
|
83
|
+
Remove subscriber from topic selected or from all if topic is None
|
84
|
+
|
85
|
+
:param raise_if_topic_missed:
|
86
|
+
:param subscriber:
|
87
|
+
:param topic_name:
|
88
|
+
:return:
|
89
|
+
"""
|
90
|
+
|
91
|
+
if raise_if_topic_missed and isinstance(topic_name, str) and topic_name not in self.__topics.keys():
|
92
|
+
raise TopicNotFound(f"topic '{topic_name}' not found")
|
93
|
+
|
94
|
+
for name in self.__topics.keys():
|
95
|
+
|
96
|
+
if topic_name is None or topic_name == name:
|
97
|
+
self.__subscriptions[name].remove(subscriber)
|
98
|
+
|
99
|
+
|
100
|
+
@abstractmethod
|
101
|
+
async def put_event(self, topic_name: str, event: Event):
|
102
|
+
"""
|
103
|
+
Put a new event in the bus and notify subscribers of corresponding
|
104
|
+
event's topic
|
105
|
+
|
106
|
+
:param topic_name:
|
107
|
+
:param event:
|
108
|
+
:return:
|
109
|
+
"""
|
110
|
+
|
111
|
+
raise NotImplemented()
|
112
|
+
|
eventbus/exceptions.py
ADDED
@@ -0,0 +1,50 @@
|
|
1
|
+
import asyncio
|
2
|
+
import logging
|
3
|
+
from queue import Queue
|
4
|
+
from concurrent.futures import ThreadPoolExecutor
|
5
|
+
from src.event.event import Event
|
6
|
+
from src.eventbus.eventbus import EventBus
|
7
|
+
|
8
|
+
|
9
|
+
MAX_WORKERS = 3
|
10
|
+
MAX_QUEUE_SIZE = 0
|
11
|
+
|
12
|
+
|
13
|
+
class QueuedLocalEventBus(EventBus):
|
14
|
+
"""
|
15
|
+
Queued local eventbus (singleton). It uses a queue to store and forward events.
|
16
|
+
|
17
|
+
Author: Nicola Ricciardi
|
18
|
+
"""
|
19
|
+
|
20
|
+
def __init__(self, max_queue_size=MAX_QUEUE_SIZE, n_workers=MAX_WORKERS):
|
21
|
+
|
22
|
+
super().__init__()
|
23
|
+
|
24
|
+
self.__queue = Queue(maxsize=max_queue_size)
|
25
|
+
self.__n_workers = n_workers
|
26
|
+
|
27
|
+
self.__tpool = ThreadPoolExecutor(max_workers=self.__n_workers)
|
28
|
+
|
29
|
+
for i in range(self.__n_workers):
|
30
|
+
self.__tpool.submit(self.__elaborate_queue)
|
31
|
+
|
32
|
+
async def put_event(self, topic_name: str, event: Event):
|
33
|
+
self.__queue.put((topic_name, event))
|
34
|
+
|
35
|
+
def __elaborate_queue(self):
|
36
|
+
|
37
|
+
while True:
|
38
|
+
|
39
|
+
topic_name, event = self.__queue.get()
|
40
|
+
|
41
|
+
topic_subscriptions = self.subscriptions.get(topic_name, [])
|
42
|
+
|
43
|
+
logging.debug(
|
44
|
+
f"new event {event} on topic {topic_name}, notify subscribers: {topic_subscriptions}")
|
45
|
+
|
46
|
+
if len(topic_subscriptions) == 0:
|
47
|
+
return
|
48
|
+
|
49
|
+
for subscriber in topic_subscriptions:
|
50
|
+
asyncio.run(subscriber.on_event(topic_name, event))
|
eventbus/topic.py
ADDED
@@ -0,0 +1,35 @@
|
|
1
|
+
|
2
|
+
|
3
|
+
class Topic:
|
4
|
+
"""
|
5
|
+
Topic of generic eventbus.
|
6
|
+
|
7
|
+
:param name: unique name of the topic
|
8
|
+
:param content_type: MIME type which describes content of the topic (e.g. "application/json")
|
9
|
+
:param description: simple topic description
|
10
|
+
:param priority: priority of message in topic related to other topics
|
11
|
+
|
12
|
+
Author: Nicola Ricciardi
|
13
|
+
"""
|
14
|
+
|
15
|
+
def __init__(self, name: str, content_type: str | None = None, description: str | None = None, priority: int = 0):
|
16
|
+
self.__name = name
|
17
|
+
self.__description = description
|
18
|
+
self.__content_type = content_type
|
19
|
+
self.__priority = priority
|
20
|
+
|
21
|
+
@property
|
22
|
+
def name(self) -> str:
|
23
|
+
return self.__name
|
24
|
+
|
25
|
+
@property
|
26
|
+
def description(self) -> str | None:
|
27
|
+
return self.__description
|
28
|
+
|
29
|
+
@property
|
30
|
+
def content_type(self) -> str | None:
|
31
|
+
return self.__content_type
|
32
|
+
|
33
|
+
@property
|
34
|
+
def priority(self) -> int:
|
35
|
+
return self.__priority
|
File without changes
|
@@ -0,0 +1,99 @@
|
|
1
|
+
from uuid import uuid4
|
2
|
+
from src.event.event import Event
|
3
|
+
from src.eventbus_client.eventbus_connector import EventBusConnector
|
4
|
+
from src.eventbus_client.publisher.publisher import Publisher
|
5
|
+
from src.eventbus_client.subscriber.event_listener import EventListener
|
6
|
+
from src.eventbus_client.subscriber.subscriber import Subscriber
|
7
|
+
|
8
|
+
|
9
|
+
class EventBusClient(EventBusConnector):
|
10
|
+
"""
|
11
|
+
Eventbus client which should used by components which wouldn't be a publisher/subscriber, but they need them
|
12
|
+
|
13
|
+
Author: Nicola Ricciardi
|
14
|
+
"""
|
15
|
+
|
16
|
+
def __init__(self, publisher: Publisher, subscriber: Subscriber, event_listener: EventListener | None = None, client_id: str = str(uuid4())):
|
17
|
+
EventBusConnector.__init__(self, client_id)
|
18
|
+
|
19
|
+
self._id = client_id
|
20
|
+
self.__publisher: Publisher = None
|
21
|
+
self.__subscriber: Subscriber = None
|
22
|
+
self.__event_listener: EventListener = None
|
23
|
+
|
24
|
+
self.publisher = publisher
|
25
|
+
self.subscriber = subscriber
|
26
|
+
self.event_listener = event_listener
|
27
|
+
|
28
|
+
@property
|
29
|
+
def publisher(self) -> Publisher:
|
30
|
+
return self.__publisher
|
31
|
+
|
32
|
+
@publisher.setter
|
33
|
+
def publisher(self, publisher: Publisher):
|
34
|
+
self.__publisher = publisher
|
35
|
+
|
36
|
+
@property
|
37
|
+
def subscriber(self) -> Subscriber:
|
38
|
+
return self.__subscriber
|
39
|
+
|
40
|
+
@subscriber.setter
|
41
|
+
def subscriber(self, subscriber: Subscriber):
|
42
|
+
|
43
|
+
original_on_event = subscriber.on_event
|
44
|
+
|
45
|
+
async def on_event_wrapper(*args, **kwargs): # wrap on_event method to call self.on_event
|
46
|
+
await original_on_event(*args, **kwargs)
|
47
|
+
await self.on_event(*args, **kwargs)
|
48
|
+
|
49
|
+
subscriber.on_event = on_event_wrapper
|
50
|
+
self.__subscriber = subscriber
|
51
|
+
|
52
|
+
@property
|
53
|
+
def event_listener(self) -> EventListener:
|
54
|
+
return self.__event_listener
|
55
|
+
|
56
|
+
@event_listener.setter
|
57
|
+
def event_listener(self, event_listener: EventListener):
|
58
|
+
self.__event_listener = event_listener
|
59
|
+
|
60
|
+
async def connect(self):
|
61
|
+
c1 = self.__publisher.connect()
|
62
|
+
c2 = self.__subscriber.connect()
|
63
|
+
|
64
|
+
await c1
|
65
|
+
await c2
|
66
|
+
|
67
|
+
async def disconnect(self):
|
68
|
+
d1 = self.__publisher.disconnect()
|
69
|
+
d2 = self.__subscriber.disconnect()
|
70
|
+
|
71
|
+
await d1
|
72
|
+
await d2
|
73
|
+
|
74
|
+
async def publish(self, topic_name: str, event: Event, **kwargs):
|
75
|
+
"""
|
76
|
+
Alias of `client.publisher.publish(...)`
|
77
|
+
"""
|
78
|
+
|
79
|
+
await self.__publisher.publish(topic_name, event, **kwargs)
|
80
|
+
|
81
|
+
async def subscribe(self, topic_name: str, **kwargs):
|
82
|
+
"""
|
83
|
+
Alias of `client.subscriber.subscribe(...)`
|
84
|
+
"""
|
85
|
+
|
86
|
+
await self.__subscriber.subscribe(topic_name, **kwargs)
|
87
|
+
|
88
|
+
async def unsubscribe(self, topic_name: str | None = None, **kwargs):
|
89
|
+
"""
|
90
|
+
Alias of `client.subscriber.unsubscribe(...)`
|
91
|
+
"""
|
92
|
+
|
93
|
+
await self.__subscriber.unsubscribe(topic_name, **kwargs)
|
94
|
+
|
95
|
+
async def on_event(self, topic_name: str, event: Event, **kwargs):
|
96
|
+
if self.__event_listener is not None:
|
97
|
+
await self.__event_listener.on_event(topic_name, event, **kwargs)
|
98
|
+
|
99
|
+
|
@@ -0,0 +1,37 @@
|
|
1
|
+
from abc import ABC, abstractmethod
|
2
|
+
from uuid import uuid4
|
3
|
+
|
4
|
+
|
5
|
+
class EventBusConnector(ABC):
|
6
|
+
"""
|
7
|
+
Abstract class which is used as base class to create a component which interacts with eventbus
|
8
|
+
|
9
|
+
Author: Nicola Ricciardi
|
10
|
+
"""
|
11
|
+
|
12
|
+
def __init__(self, connector_id: str = str(uuid4())):
|
13
|
+
self._id = connector_id
|
14
|
+
|
15
|
+
@property
|
16
|
+
def id(self) -> str:
|
17
|
+
return self._id
|
18
|
+
|
19
|
+
@id.setter
|
20
|
+
def id(self, value):
|
21
|
+
self._id = value
|
22
|
+
|
23
|
+
@abstractmethod
|
24
|
+
async def connect(self):
|
25
|
+
"""
|
26
|
+
Connect to eventbus
|
27
|
+
|
28
|
+
:return:
|
29
|
+
"""
|
30
|
+
|
31
|
+
@abstractmethod
|
32
|
+
async def disconnect(self):
|
33
|
+
"""
|
34
|
+
Disconnect to eventbus
|
35
|
+
|
36
|
+
:return:
|
37
|
+
"""
|
@@ -0,0 +1,25 @@
|
|
1
|
+
from typing import Callable
|
2
|
+
from uuid import uuid4
|
3
|
+
|
4
|
+
from src.event.event import Event
|
5
|
+
from src.eventbus.async_local_eventbus import AsyncLocalEventBus
|
6
|
+
from src.eventbus_client.eventbus_client import EventBusClient
|
7
|
+
from src.eventbus_client.publisher.local_eventbus_publisher import LocalEventBusPublisher
|
8
|
+
from src.eventbus_client.subscriber.local_eventbus_closure_subscriber import LocalEventBusClosureSubscriber
|
9
|
+
|
10
|
+
|
11
|
+
class LocalEventBusClient(EventBusClient):
|
12
|
+
|
13
|
+
def __init__(self, on_event_callback: Callable[[str, Event], None], client_id: str = str(uuid4())):
|
14
|
+
|
15
|
+
eventbus_instance = AsyncLocalEventBus()
|
16
|
+
|
17
|
+
EventBusClient.__init__(
|
18
|
+
self,
|
19
|
+
publisher=LocalEventBusPublisher(eventbus_instance),
|
20
|
+
subscriber=LocalEventBusClosureSubscriber(eventbus_instance, on_event_callback),
|
21
|
+
client_id=client_id
|
22
|
+
)
|
23
|
+
|
24
|
+
|
25
|
+
|
File without changes
|
@@ -0,0 +1,35 @@
|
|
1
|
+
from src.event.event import Event
|
2
|
+
from src.eventbus.eventbus import EventBus
|
3
|
+
from src.eventbus_client.exceptions import EventBusClientNotConnected
|
4
|
+
from src.eventbus_client.publisher.publisher import Publisher
|
5
|
+
|
6
|
+
|
7
|
+
class LocalEventBusPublisher(Publisher):
|
8
|
+
"""
|
9
|
+
Publisher which works with local eventbus, this class can be initialized and used stand-alone
|
10
|
+
|
11
|
+
Author: Nicola Ricciardi
|
12
|
+
"""
|
13
|
+
|
14
|
+
def __init__(self, eventbus_instance: EventBus):
|
15
|
+
Publisher.__init__(self)
|
16
|
+
|
17
|
+
self._eventbus = eventbus_instance
|
18
|
+
self._connected = False
|
19
|
+
|
20
|
+
async def connect(self):
|
21
|
+
self._connected = True
|
22
|
+
|
23
|
+
async def disconnect(self):
|
24
|
+
self._connected = False
|
25
|
+
|
26
|
+
async def _internal_publish(self, topic_name: str, event: Event, raise_if_not_connected: bool = False, **kwargs):
|
27
|
+
|
28
|
+
if raise_if_not_connected and not self._connected:
|
29
|
+
raise EventBusClientNotConnected()
|
30
|
+
else:
|
31
|
+
await self.connect()
|
32
|
+
|
33
|
+
self.on_publishing(topic_name, event)
|
34
|
+
await self._eventbus.put_event(topic_name, event)
|
35
|
+
self.on_published(topic_name, event)
|