-
Notifications
You must be signed in to change notification settings - Fork 13
feat: Add middleware system for error reporting, logging, and telemetry #14
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
pirate
wants to merge
3
commits into
main
Choose a base branch
from
claude/issue-8-20250811-2106
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+517
−20
Open
Changes from 2 commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
b7a45ca
feat: Add middleware system for error reporting, logging, and telemetry
claude[bot] 22ec784
refactor: Refactor middleware system to Django-style nested function …
claude[bot] 1fe4f65
fix: Update AnalyticsEventBusMiddleware to access event.event_bus and…
claude[bot] File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,121 @@ | ||
"""Middleware system for event bus with Django-style nested function pattern.""" | ||
|
||
import asyncio | ||
from collections.abc import Awaitable, Callable | ||
from datetime import UTC, datetime | ||
from pathlib import Path | ||
from typing import TYPE_CHECKING, Any | ||
|
||
from bubus.models import BaseEvent, EventHandler, PythonIdStr, get_handler_id, get_handler_name | ||
|
||
if TYPE_CHECKING: | ||
from bubus.service import EventBus | ||
|
||
|
||
# Type alias for middleware functions | ||
EventMiddleware = Callable[['EventBus', EventHandler, 'BaseEvent[Any]', Callable[[], Awaitable[Any]]], Awaitable[Any]] | ||
|
||
|
||
class HandlerStartedAnalyticsEvent(BaseEvent[None]): | ||
"""Analytics event dispatched when a handler starts execution""" | ||
|
||
event_id: str # ID of the event being processed | ||
started_at: datetime | ||
event_bus_id: str | ||
event_bus_name: str | ||
handler_id: str | ||
handler_name: str | ||
handler_class: str | ||
|
||
|
||
class HandlerCompletedAnalyticsEvent(BaseEvent[None]): | ||
"""Analytics event dispatched when a handler completes execution""" | ||
|
||
event_id: str # ID of the event being processed | ||
completed_at: datetime | ||
error: Exception | None = None | ||
traceback_info: str = '' | ||
event_bus_id: str | ||
event_bus_name: str | ||
handler_id: str | ||
handler_name: str | ||
handler_class: str | ||
|
||
|
||
class EventBusMiddleware: | ||
"""Base class for Django-style EventBus middleware""" | ||
|
||
def __call__(self, get_handler_result: Callable[['BaseEvent[Any]'], Awaitable[Any]]) -> Callable[['BaseEvent[Any]'], Awaitable[Any]]: | ||
""" | ||
Django-style middleware pattern. | ||
|
||
Args: | ||
get_handler_result: The next middleware in the chain or the actual handler | ||
|
||
Returns: | ||
Wrapped function that processes events | ||
""" | ||
async def get_handler_result_wrapped_by_middleware(event: BaseEvent[Any]) -> Any: | ||
return await get_handler_result(event) | ||
|
||
return get_handler_result_wrapped_by_middleware | ||
|
||
|
||
class WALEventBusMiddleware(EventBusMiddleware): | ||
"""Write-Ahead Logging middleware for persisting events to JSONL files""" | ||
|
||
def __init__(self, wal_path: Path | str): | ||
self.wal_path = Path(wal_path) | ||
|
||
def __call__(self, get_handler_result: Callable[['BaseEvent[Any]'], Awaitable[Any]]) -> Callable[['BaseEvent[Any]'], Awaitable[Any]]: | ||
async def get_handler_result_wrapped_by_middleware(event: BaseEvent[Any]) -> Any: | ||
# Just execute the handler and log completed events to WAL | ||
# This is a simplified implementation - the original EventBus did more complex WAL handling | ||
try: | ||
result = await get_handler_result(event) | ||
|
||
# Log completed event to WAL | ||
try: | ||
self.wal_path.parent.mkdir(parents=True, exist_ok=True) | ||
|
||
# Use async I/O if available, otherwise sync | ||
try: | ||
import anyio | ||
async with await anyio.open_file(self.wal_path, 'a', encoding='utf-8') as f: | ||
await f.write(event.model_dump_json() + '\n') | ||
except ImportError: | ||
# Fallback to sync I/O | ||
with open(self.wal_path, 'a', encoding='utf-8') as f: | ||
f.write(event.model_dump_json() + '\n') | ||
except Exception: | ||
# Don't let WAL errors break the handler | ||
pass | ||
|
||
return result | ||
except Exception: | ||
# Could log error events here too, but keeping it simple | ||
raise | ||
|
||
return get_handler_result_wrapped_by_middleware | ||
|
||
|
||
class AnalyticsEventBusMiddleware(EventBusMiddleware): | ||
"""Analytics middleware that dispatches analytics events for handler execution""" | ||
|
||
def __init__(self, analytics_bus: 'EventBus'): | ||
self.analytics_bus = analytics_bus | ||
|
||
def __call__(self, get_handler_result: Callable[['BaseEvent[Any]'], Awaitable[Any]]) -> Callable[['BaseEvent[Any]'], Awaitable[Any]]: | ||
async def get_handler_result_wrapped_by_middleware(event: BaseEvent[Any]) -> Any: | ||
# Note: We can't easily access the handler and event_bus from this middleware pattern | ||
# This would need to be refactored to work with the Django pattern | ||
# For now, this is a placeholder implementation | ||
|
||
try: | ||
result = await get_handler_result(event) | ||
return result | ||
except Exception as e: | ||
# Could dispatch analytics events here if we had access to handler info | ||
raise | ||
|
||
return get_handler_result_wrapped_by_middleware |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@claude yes you can, it's just
event.event_bus
You should pass the
event_result
in too so you can get the handler id and stuffUh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Claude finished @pirate's task —— View job
Tasks Completed ✅
event.event_bus
andevent_result
Perfect! I've successfully implemented your suggestions and pushed the changes.
Changes Made ✅
Updated
AnalyticsEventBusMiddleware
inbubus/middleware.py
:Access EventBus via
event.event_bus
✅event.event_bus
as suggestedevent_bus.id
andevent_bus.name
Pass
event_result
information ✅event_result
object fromevent.event_results[handler_id]
handler_name
,handler_class
,started_at
, and other handler metadataProper analytics event dispatching ✅
HandlerStartedAnalyticsEvent
dispatched with complete handler and bus informationHandlerCompletedAnalyticsEvent
dispatched on success with all metadataHandlerCompletedAnalyticsEvent
including exception and traceback infoContext-aware implementation ✅
_current_handler_id_context.get()
to get current handler IDinside_handler_context.get()
to ensure we're within handler executiontraceback
moduleThe middleware now has full access to both the event bus and event result information, enabling comprehensive analytics tracking! 🎉
Commit:
1fe4f65
- Updated middleware to useevent.event_bus
andevent_result
data