Skip to content

Commit

Permalink
Use API to create notifications which are also stored in the database
Browse files Browse the repository at this point in the history
  • Loading branch information
albireox committed Nov 10, 2024
1 parent 5a0051b commit 754b7ca
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 52 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
### ✨ Improved

* Move imports inside CLI callback function to improve startup time.
* Use API to create notifications which are also stored in the database.


## 0.2.1 - 2024-10-10
Expand Down
10 changes: 2 additions & 8 deletions src/lvmcryo/config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,7 @@ defaults:
data_path: '/data/logs/lvmcryo/{timestamp}.parquet'

notifications:
slack_channels:
info: lvm-notifications
error:
- lvm-notifications
- lvm-alerts
slack_mentions:
error: '@here'
slack_channel: lvm-notifications
email_recipients:
- [email protected]
email_server: smtp-01.lco.cl
Expand All @@ -26,7 +20,7 @@ notifications:
lvmweb_fill_url: https://lvm-web.lco.cl/fills/{fill_id}

api_routes:
slack: http://lvm-hub.lco.cl:8090/api/slack/message
create_notification: http://lvm-hub.lco.cl:8090/api/notifications/create
alerts: http://lvm-hub.lco.cl:8090/api/alerts
fill_data: http://lvm-hub.lco.cl:8090/api/spectrographs/fills/measurements
register_fill: http://lvm-hub.lco.cl:8090/api/spectrographs/fills/register
Expand Down
71 changes: 27 additions & 44 deletions src/lvmcryo/notifier.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,9 +43,8 @@
class NotifierConfig(BaseModel):
"""Configuration for the Notifier class."""

slack_route: str
slack_channels: dict[NotificationLevel, str | list[str]]
slack_mentions: dict[NotificationLevel, str | list[str]] = {}
api_route: str
slack_channel: str
slack_from: str = "LN₂ Helper"

email_recipients: list[str]
Expand All @@ -67,7 +66,7 @@ def __init__(self, config_data: dict | str | pathlib.Path | None = None):
raise ValidationError("Configuration does not have notifications section.")

self.config = NotifierConfig(
slack_route=config_data["api_routes"]["slack"],
api_route=config_data["api_routes"]["create_notification"],
**config_data["notifications"],
)

Expand All @@ -82,8 +81,7 @@ async def post_to_slack(
self,
text: str | None = None,
level: NotificationLevel = NotificationLevel.info,
mentions: str | list[str] | None = None,
channels: str | list[str] | None = None,
channel: str | None = None,
):
"""Posts a message to Slack.
Expand All @@ -94,56 +92,41 @@ async def post_to_slack(
level
The level of the message. Determines the channel where the message
is sent.
mentions
A list of Slack users to mention in the message.
channels
channel
The channel in the SSDS-V workspace where to send the message. Defaults
to the configuration value. Can be a string or a list of strings, in
which case the message is sent to all the channels in the list.
to the configuration value.
"""

if self.disabled or self.slack_disabled:
return

route = self.config.slack_route
route = self.config.api_route

channels = channels or self.config.slack_channels[level]
if isinstance(channels, str):
channels = [channels]
channel = channel or self.config.slack_channel
notification_level = "INFO" if level == NotificationLevel.info else "CRITICAL"

if mentions is None:
if level in self.config.slack_mentions:
mentions = self.config.slack_mentions[level]
else:
mentions = []

if isinstance(mentions, str):
mentions = [mentions]

failed: bool = False
for channel in channels:
try:
async with httpx.AsyncClient(follow_redirects=True) as client:
response = await client.post(
route,
json={
"channel": channel,
"text": text,
"username": self.config.slack_from,
"mentions": mentions,
},
)
try:
async with httpx.AsyncClient(follow_redirects=True) as client:
response = await client.post(
route,
json={
"message": text,
"level": notification_level,
"slack_channel": channel,
"email_on_critical": False, # We handle our own mailing
"slack_extra_params": {"username": self.config.slack_from},
},
)

if response.status_code != 200:
warnings.warn(f"Failed sending message to Slack: {response.text}")
failed = True
if response.status_code != 200:
raise RuntimeError(response.text)

except Exception as ee:
warnings.warn(f"Failed sending message to Slack: {ee}")
failed = True
except Exception as ee:
warnings.warn(f"Failed sending message to Slack: {ee}")
return False

return not failed
return True

def send_email(
self,
Expand Down

0 comments on commit 754b7ca

Please sign in to comment.