|
1 | 1 | import json |
2 | 2 | import logging |
3 | 3 | import os |
| 4 | +import time |
4 | 5 | from typing import Optional, Sequence, Type |
5 | 6 |
|
6 | 7 | import requests |
|
13 | 14 | SLACK_ADMIN_NOTIFICATIONS_WEBHOOK_URL = os.environ.get("SLACK_ADMIN_NOTIFICATIONS_WEBHOOK_URL") |
14 | 15 | SITE_BASE_URL = os.environ.get("SITE_BASE_URL") |
15 | 16 |
|
| 17 | +SLACK_ADMIN_NOTIFICATIONS_RETRY_COUNT = int(os.environ.get("SLACK_ADMIN_NOTIFICATIONS_RETRY_COUNT", 3)) |
| 18 | + |
16 | 19 |
|
17 | 20 | def escape_slack_text(text: str) -> str: |
18 | 21 | return text.replace("↔", "<->").replace("&", "&").replace("<", "<").replace(">", ">") |
@@ -69,13 +72,21 @@ def notify_admins( |
69 | 72 | ) |
70 | 73 | return |
71 | 74 |
|
72 | | - response = requests.post(SLACK_ADMIN_NOTIFICATIONS_WEBHOOK_URL, json=slack_message) |
73 | | - |
74 | | - if raise_exception_on_failure: |
75 | | - response.raise_for_status() |
76 | | - elif response.status_code != 200: |
77 | | - logging.error( |
78 | | - f"Got HTTP {response.status_code} while sending slack notification to slack admin. " |
79 | | - f"HTTP response was {response.text}. Unable to notify admins of " |
80 | | - f"the following message: {slack_message}" |
81 | | - ) |
| 75 | + for i in range(0, SLACK_ADMIN_NOTIFICATIONS_RETRY_COUNT + 1): |
| 76 | + response = requests.post(SLACK_ADMIN_NOTIFICATIONS_WEBHOOK_URL, json=slack_message) |
| 77 | + try: |
| 78 | + response.raise_for_status() |
| 79 | + return |
| 80 | + except requests.exceptions.RequestException as e: |
| 81 | + if i == SLACK_ADMIN_NOTIFICATIONS_RETRY_COUNT: |
| 82 | + if raise_exception_on_failure: |
| 83 | + raise e |
| 84 | + else: |
| 85 | + logging.error( |
| 86 | + f"Got HTTP {response.status_code} while sending slack notification to slack admin. " |
| 87 | + f"HTTP response was {response.text}. Unable to notify admins of " |
| 88 | + f"the following message: {slack_message}" |
| 89 | + ) |
| 90 | + else: |
| 91 | + # Exponential backoff to try to avoid triggering Slack's rate limiting logic |
| 92 | + time.sleep(2**i) |
0 commit comments