-
Notifications
You must be signed in to change notification settings - Fork 204
Ele 4028 messaging integ #1799
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
Merged
Merged
Ele 4028 messaging integ #1799
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
ef098ae
Refactor alert sending and grouping logic in data monitoring alerts
MikaKerman a44e9c0
Add base messaging integration classes and exceptions
MikaKerman 9cc51ce
Add Teams webhook messaging integration
MikaKerman 420f155
Add comprehensive README for Elementary Messaging Integration System
MikaKerman e197ac6
Add support for new messaging integration in data monitoring alerts
MikaKerman 0fab5f5
Rename message_body parameter to body in messaging integration methods
MikaKerman 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,58 @@ | ||
| # Elementary Messaging Integration System | ||
|
|
||
| ## Overview | ||
|
|
||
| The Elementary Messaging Integration system provides a flexible and extensible framework for sending alerts and messages to various messaging platforms (e.g., Slack, Teams). The system is designed to support a gradual migration from the legacy integration system to a more generic messaging-based approach. | ||
|
|
||
| ## Architecture | ||
|
|
||
| ### BaseMessagingIntegration | ||
|
|
||
| The core of the new messaging system is the `BaseMessagingIntegration` abstract class. This class defines the contract that all messaging integrations must follow: | ||
|
|
||
| - `send_message()`: Send a message to a specific destination | ||
| - `supports_reply()`: Check if the integration supports message threading/replies | ||
| - `reply_to_message()`: Reply to an existing message (if supported) | ||
|
|
||
| ### Key Components | ||
|
|
||
| 1. **MessageBody**: A platform-agnostic representation of a message | ||
| 2. **MessageSendResult**: Contains information about a sent message, including timestamp and platform-specific context | ||
| 3. **DestinationType**: Generic type representing the destination for a message (e.g., webhook URL, channel) | ||
| 4. **MessageContextType**: Generic type for platform-specific message context | ||
|
|
||
| ## Migration Strategy | ||
|
|
||
| The system currently supports both: | ||
|
|
||
| - Legacy `BaseIntegration` implementations (e.g., Slack) | ||
| - New `BaseMessagingIntegration` implementations (e.g., Teams) | ||
|
|
||
| This dual support allows for a gradual migration path where: | ||
|
|
||
| 1. New integrations are implemented using `BaseMessagingIntegration` | ||
| 2. Existing integrations can be migrated one at a time | ||
| 3. The legacy `BaseIntegration` will eventually be deprecated | ||
|
|
||
| ## Implementing a New Integration | ||
|
|
||
| To add a new messaging platform integration: | ||
|
|
||
| 1. Create a new class that extends `BaseMessagingIntegration` | ||
| 2. Implement the required abstract methods: | ||
| ```python | ||
| def send_message(self, destination: DestinationType, body: MessageBody) -> MessageSendResult | ||
| def supports_reply(self) -> bool | ||
| def reply_to_message(self, destination, message_context, message_body) -> MessageSendResult # if supported | ||
| ``` | ||
| 3. Update the `Integrations` factory class to support the new integration | ||
|
|
||
| ## Current Implementations | ||
|
|
||
| - **Teams**: Uses the new `BaseMessagingIntegration` system with webhook support | ||
| - **Slack**: Currently uses the legacy `BaseIntegration` system (planned for migration) | ||
|
|
||
| ## Future Improvements | ||
|
|
||
| 1. Complete migration of Slack to `BaseMessagingIntegration` | ||
| 2. Add support for more messaging platforms |
Empty file.
49 changes: 49 additions & 0 deletions
49
elementary/messages/messaging_integrations/base_messaging_integration.py
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,49 @@ | ||
| from abc import ABC, abstractmethod | ||
| from datetime import datetime | ||
| from typing import Generic, Optional, TypeVar | ||
|
|
||
| from pydantic import BaseModel | ||
|
|
||
| from elementary.messages.message_body import MessageBody | ||
| from elementary.messages.messaging_integrations.exceptions import ( | ||
| MessageIntegrationReplyNotSupportedError, | ||
| ) | ||
| from elementary.utils.log import get_logger | ||
|
|
||
| logger = get_logger(__name__) | ||
|
|
||
|
|
||
| T = TypeVar("T") | ||
|
|
||
|
|
||
| class MessageSendResult(BaseModel, Generic[T]): | ||
| timestamp: datetime | ||
| message_context: Optional[T] = None | ||
|
|
||
|
|
||
| DestinationType = TypeVar("DestinationType") | ||
| MessageContextType = TypeVar("MessageContextType") | ||
|
|
||
|
|
||
| class BaseMessagingIntegration(ABC, Generic[DestinationType, MessageContextType]): | ||
| @abstractmethod | ||
| def send_message( | ||
| self, | ||
| destination: DestinationType, | ||
| body: MessageBody, | ||
| ) -> MessageSendResult[MessageContextType]: | ||
| raise NotImplementedError | ||
|
|
||
| @abstractmethod | ||
| def supports_reply(self) -> bool: | ||
| raise NotImplementedError | ||
|
|
||
| def reply_to_message( | ||
| self, | ||
| destination: DestinationType, | ||
| message_context: MessageContextType, | ||
| body: MessageBody, | ||
| ) -> MessageSendResult[MessageContextType]: | ||
| if not self.supports_reply(): | ||
| raise MessageIntegrationReplyNotSupportedError | ||
| raise NotImplementedError |
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,6 @@ | ||
| class MessagingIntegrationError(Exception): | ||
| pass | ||
|
|
||
|
|
||
| class MessageIntegrationReplyNotSupportedError(MessagingIntegrationError): | ||
| pass |
82 changes: 82 additions & 0 deletions
82
elementary/messages/messaging_integrations/teams_webhook.py
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,82 @@ | ||
| from datetime import datetime | ||
| from typing import Optional | ||
|
|
||
| import requests | ||
| from pydantic import BaseModel | ||
|
|
||
| from elementary.messages.formats.adaptive_cards import format_adaptive_card | ||
| from elementary.messages.message_body import MessageBody | ||
| from elementary.messages.messaging_integrations.base_messaging_integration import ( | ||
| BaseMessagingIntegration, | ||
| MessageSendResult, | ||
| ) | ||
| from elementary.messages.messaging_integrations.exceptions import ( | ||
| MessageIntegrationReplyNotSupportedError, | ||
| MessagingIntegrationError, | ||
| ) | ||
| from elementary.utils.log import get_logger | ||
|
|
||
| logger = get_logger(__name__) | ||
|
|
||
|
|
||
| class ChannelWebhook(BaseModel): | ||
| webhook: str | ||
| channel: Optional[str] = None | ||
|
|
||
|
|
||
| def send_adaptive_card(webhook_url: str, card: dict) -> requests.Response: | ||
| """Sends an Adaptive Card to the specified webhook URL.""" | ||
| payload = { | ||
| "type": "message", | ||
| "attachments": [ | ||
| { | ||
| "contentType": "application/vnd.microsoft.card.adaptive", | ||
| "contentUrl": None, | ||
| "content": card, | ||
| } | ||
| ], | ||
| } | ||
|
|
||
| response = requests.post( | ||
| webhook_url, | ||
| json=payload, | ||
| headers={"Content-Type": "application/json"}, | ||
| ) | ||
| response.raise_for_status() | ||
| if response.status_code == 202: | ||
| logger.debug("Got 202 response from Teams webhook, assuming success") | ||
| return response | ||
|
|
||
|
|
||
| class TeamsWebhookMessagingIntegration( | ||
| BaseMessagingIntegration[ChannelWebhook, ChannelWebhook] | ||
| ): | ||
| def send_message( | ||
| self, | ||
| destination: ChannelWebhook, | ||
| body: MessageBody, | ||
| ) -> MessageSendResult[ChannelWebhook]: | ||
| card = format_adaptive_card(body) | ||
| try: | ||
| send_adaptive_card(destination.webhook, card) | ||
| return MessageSendResult( | ||
| message_context=destination, | ||
| timestamp=datetime.utcnow(), | ||
| ) | ||
| except requests.RequestException as e: | ||
| raise MessagingIntegrationError( | ||
| "Failed to send message to Teams webhook" | ||
| ) from e | ||
|
|
||
| def supports_reply(self) -> bool: | ||
| return False | ||
|
|
||
| def reply_to_message( | ||
| self, | ||
| destination: ChannelWebhook, | ||
| message_context: ChannelWebhook, | ||
| body: MessageBody, | ||
| ) -> MessageSendResult[ChannelWebhook]: | ||
| raise MessageIntegrationReplyNotSupportedError( | ||
| "Teams webhook message integration does not support replying to messages" | ||
| ) | ||
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.
all of the comments in this method are redundant