Skip to content

Commit

Permalink
feat: add some cleanup methods to the MessageBus
Browse files Browse the repository at this point in the history
Signed-off-by: John DeAngelis <[email protected]>
  • Loading branch information
johndeange committed Dec 12, 2024
1 parent 4089a95 commit 19da16e
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 1 deletion.
1 change: 1 addition & 0 deletions backend/ops_api/ops/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,7 @@ def shutdown_session(exception=None):
def teardown_request(exception=None):
if hasattr(request, "message_bus"):
request.message_bus.handle()
request.message_bus.cleanup()

@event.listens_for(db_session, "before_commit")
def receive_before_commit(session: Session):
Expand Down
2 changes: 1 addition & 1 deletion backend/ops_api/ops/services/can_messages.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,5 @@ def can_history_trigger(
event: OpsEvent,
session: Session,
):
logger.debug(f"Handling event {event}")
logger.debug(f"Handling event {event.event_type} with details: {event.event_details}")
assert session is not None
12 changes: 12 additions & 0 deletions backend/ops_api/ops/services/message_bus.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ class MessageBus:
"""

published_events: List[OpsEvent] = []
known_callbacks = []

def handle(self):
"""
Expand All @@ -28,6 +29,7 @@ def handle(self):
ops_signal = signal(event.event_type.name)
ops_signal.send(event, session=current_app.db_session)
logger.debug(f"Handling event {event}")
self.published_events.clear()

def subscribe(self, event_type: OpsEventType, callback: callable):
"""
Expand All @@ -51,3 +53,13 @@ def publish(self, event_type: OpsEventType, event: OpsEvent):
"""
logger.debug(f"Publishing event {event_type} with details {event}")
self.published_events.append(event)

def cleanup(self):
"""
Clean up all subscriptions and published events.
"""
for callback in self.known_callbacks:
ops_signal = signal(callback)
ops_signal.disconnect(callback)
self.published_events.clear()
self.known_callbacks.clear()

0 comments on commit 19da16e

Please sign in to comment.