-
Notifications
You must be signed in to change notification settings - Fork 282
Expand file tree
/
Copy pathsla_service.py
More file actions
283 lines (231 loc) · 9.24 KB
/
Copy pathsla_service.py
File metadata and controls
283 lines (231 loc) · 9.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
"""
SLA escalation service.
Scans unresolved tickets with expired SLA deadlines, marks them breached,
increments escalation level, emits sanitized system notifications, and writes
audit records for admin review.
"""
from __future__ import annotations
import asyncio
import logging
import os
from datetime import datetime, timedelta, timezone
from typing import Any, Callable, Optional
try:
from dotenv import load_dotenv
except ImportError:
def load_dotenv(*_args, **_kwargs):
return False
load_dotenv()
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
if not logger.handlers:
handler = logging.StreamHandler()
formatter = logging.Formatter("[SlaEscalationService] %(asctime)s - %(levelname)s - %(message)s")
handler.setFormatter(formatter)
logger.addHandler(handler)
RESPONSE_DEADLINES_HOURS = {
"critical": 1,
"high": 4,
"medium": 8,
"low": 24,
}
RESOLUTION_DEADLINES_HOURS = {
"critical": 4,
"high": 12,
"medium": 24,
"low": 72,
}
TERMINAL_STATUSES = {"resolved", "closed", "auto-resolved", "auto resolved"}
WARNING_WINDOW = timedelta(hours=1)
def _utc_now() -> datetime:
return datetime.now(timezone.utc)
def normalize_priority(priority: str | None) -> str:
value = str(priority or "low").strip().lower()
return value if value in RESOLUTION_DEADLINES_HOURS else "low"
def calculate_sla_response_at(priority: str | None, now: datetime | None = None) -> datetime:
base = now or _utc_now()
priority_key = normalize_priority(priority)
return base + timedelta(hours=RESPONSE_DEADLINES_HOURS[priority_key])
def calculate_sla_breach_at(priority: str | None, now: datetime | None = None) -> datetime:
base = now or _utc_now()
priority_key = normalize_priority(priority)
return base + timedelta(hours=RESOLUTION_DEADLINES_HOURS[priority_key])
def parse_sla_datetime(value: str | None) -> datetime | None:
if not value:
return None
try:
parsed = datetime.fromisoformat(str(value).replace("Z", "+00:00"))
except ValueError:
return None
if parsed.tzinfo is None:
return parsed.replace(tzinfo=timezone.utc)
return parsed.astimezone(timezone.utc)
def classify_sla_status(sla_breach_at: str | None, now: datetime | None = None) -> str:
deadline = parse_sla_datetime(sla_breach_at)
if deadline is None:
return "ACTIVE"
current = now or _utc_now()
if deadline <= current:
return "BREACHED"
if deadline - current <= WARNING_WINDOW:
return "WARNING"
return "ACTIVE"
def is_terminal_status(status: str | None) -> bool:
return str(status or "").strip().lower() in TERMINAL_STATUSES
class SlaEscalationService:
"""Background service for enforcing ticket SLA breach state."""
def __init__(
self,
supabase_client: Any,
*,
now_fn: Callable[[], datetime] = _utc_now,
notification_router: Any = None,
):
self.supabase = supabase_client
self.now_fn = now_fn
self.notification_router = notification_router
def run_once(self) -> dict[str, int | str]:
stats: dict[str, int | str] = {
"processed_count": 0,
"breached_count": 0,
"skipped_count": 0,
"error_count": 0,
}
now = self.now_fn().astimezone(timezone.utc)
try:
tickets = self._fetch_candidate_tickets()
stats["processed_count"] = len(tickets)
except Exception as exc:
logger.error("Failed to fetch SLA candidates: %s", exc)
stats["error_count"] = int(stats["error_count"]) + 1
return stats
for ticket in tickets:
try:
if not self._should_breach(ticket, now):
stats["skipped_count"] = int(stats["skipped_count"]) + 1
continue
self._breach_ticket(ticket, now)
stats["breached_count"] = int(stats["breached_count"]) + 1
except Exception as exc:
stats["error_count"] = int(stats["error_count"]) + 1
logger.error("Failed to process SLA ticket %s: %s", ticket.get("id"), exc)
logger.info(
"SLA sweep complete. processed=%s breached=%s skipped=%s errors=%s",
stats["processed_count"],
stats["breached_count"],
stats["skipped_count"],
stats["error_count"],
)
return stats
def _fetch_candidate_tickets(self) -> list[dict[str, Any]]:
response = (
self.supabase.table("tickets")
.select(
"id, company_id, company, status, priority, subject, assigned_team, "
"sla_breach_at, sla_status, escalation_level"
)
.execute()
)
return list(response.data or [])
def _should_breach(self, ticket: dict[str, Any], now: datetime) -> bool:
if is_terminal_status(ticket.get("status")):
return False
if str(ticket.get("sla_status") or "").upper() == "BREACHED":
return False
return classify_sla_status(ticket.get("sla_breach_at"), now) == "BREACHED"
def _breach_ticket(self, ticket: dict[str, Any], now: datetime) -> None:
ticket_id = str(ticket.get("id"))
company_id = ticket.get("company_id")
escalation_level = int(ticket.get("escalation_level") or 0) + 1
timestamp = now.isoformat().replace("+00:00", "Z")
self.supabase.table("tickets").update(
{
"sla_status": "BREACHED",
"escalation_level": escalation_level,
"updated_at": timestamp,
}
).eq("id", ticket_id).execute()
self._insert_audit_log(ticket, escalation_level, timestamp)
self._emit_system_message(ticket, escalation_level, timestamp)
logger.warning(
"SLA breached | ticket_id=%s | company_id=%s | priority=%s | level=%s",
ticket_id,
company_id or "unknown",
ticket.get("priority") or "unknown",
escalation_level,
)
def _insert_audit_log(self, ticket: dict[str, Any], escalation_level: int, timestamp: str) -> None:
ticket_id = str(ticket.get("id"))
self.supabase.table("audit_logs").insert(
{
"event_type": "sla_breached",
"ticket_id": ticket_id,
"company_id": ticket.get("company_id"),
"actor_type": "system",
"message": "SLA breached and escalation triggered.",
"metadata": {
"priority": ticket.get("priority"),
"assigned_team": ticket.get("assigned_team"),
"escalation_level": escalation_level,
"channels": self._notification_channels(ticket),
},
"created_at": timestamp,
}
).execute()
def _emit_system_message(self, ticket: dict[str, Any], escalation_level: int, timestamp: str) -> None:
if not self._should_send_admin_alert(ticket):
logger.info("Admin alert skipped by notification settings for ticket %s", ticket.get("id"))
return
subject = ticket.get("subject") or "Untitled ticket"
message = (
f"SLA breached for '{subject}'. Escalation level {escalation_level} "
"has been triggered for admin review."
)
self.supabase.table("ticket_messages").insert(
{
"ticket_id": str(ticket.get("id")),
"sender_id": "00000000-0000-0000-0000-000000000000",
"sender_name": "SLA Escalation Engine",
"sender_role": "admin",
"message": message,
}
).execute()
def _notification_channels(self, ticket: dict[str, Any]) -> list[str]:
channels = ["incident_log", "admin_alert"]
if self._should_send_admin_alert(ticket):
channels.append("ticket_timeline")
return channels
def _should_send_admin_alert(self, ticket: dict[str, Any]) -> bool:
if not self.notification_router:
return True
company_id = ticket.get("company_id")
if not company_id:
return True
try:
return bool(self.notification_router.should_send_admin_alert(str(company_id)))
except Exception as exc:
logger.warning("Notification router failed open for company %s: %s", company_id, exc)
return True
async def run_sla_escalation_loop(
service: SlaEscalationService,
*,
interval_seconds: int = 300,
) -> None:
while True:
service.run_once()
await asyncio.sleep(interval_seconds)
_instance: Optional[SlaEscalationService] = None
def load(supabase_client: Any = None, notification_router: Any = None) -> SlaEscalationService:
global _instance
if _instance is None:
if supabase_client is None:
from backend.supabase_client import get_admin_client
supabase_client = get_admin_client()
_instance = SlaEscalationService(
supabase_client,
notification_router=notification_router,
)
logger.info("SlaEscalationService loaded")
return _instance
def get_instance() -> Optional[SlaEscalationService]:
return _instance