Files
thor/thor/outbox.py
T

66 lines
2.8 KiB
Python
Raw Normal View History

"""Sends live ticket actions to Tinker, with retries. Shadow actions never get here.
No check is live before tinker_tickets#123 ships (thor#1), so in phase 1 this mostly waits.
An action that can't be sent stays pending and is retried with backoff; Tinker being down
(it lives on CT 132 and the same MariaDB) never loses an action.
"""
import logging
from typing import Optional
from .clients.tinker import TinkerClient, backoff_s
from .db import DatabaseError
logger = logging.getLogger('thor.outbox')
MAX_ATTEMPTS = 30
CREATE_KINDS = ('open', 'escalate', 'refresh')
COMMENT_KINDS = ('also_seen', 'cleared', 'root_cause')
class Outbox:
def __init__(self, store, tinker: TinkerClient):
self.store = store
self.tinker = tinker
def flush(self, now: float) -> int:
"""Send what's due. Returns how many actions were sent."""
if not self.tinker.configured:
return 0
try:
due = self.store.due_actions(now)
except DatabaseError:
return 0
sent = 0
for a in due:
ok, ticket_id, error = self._send(a)
try:
if ok:
self.store.mark_action_sent(a['id'], ticket_id, now)
sent += 1
else:
attempts = int(a['attempts']) + 1
retry_at: Optional[float] = now + backoff_s(attempts) if attempts < MAX_ATTEMPTS else None
self.store.mark_action_failed(a['id'], error, attempts, retry_at)
logger.warning('Action %s (%s %s) not sent: %s', a['id'], a['kind'], a['incident_key'], error)
except DatabaseError:
break
return sent
def _send(self, a):
p = a['payload']
if a['kind'] in CREATE_KINDS:
r = self.tinker.create(title=p['title'], description=p['description'], priority=p['priority'],
category=p['category'], ticket_type=p.get('type', 'Issue'),
dedup_key=p['dedup_key'])
if r.ok and a['kind'] == 'escalate' and p.get('comment'):
self.tinker.comment(r.ticket_id, p['comment'])
return r.ok, r.ticket_id, r.error
if a['kind'] in ('known_note', 'attach'):
ok = self.tinker.comment(p['ticket_id'], p['comment'])
return ok, p['ticket_id'], '' if ok else 'comment failed'
if a['kind'] in COMMENT_KINDS:
ticket_id = self.store.incident_ticket(a['incident_key'])
if not ticket_id:
return False, None, 'no ticket yet for this incident (its open action is not sent)'
ok = self.tinker.comment(ticket_id, p['comment'])
return ok, ticket_id, '' if ok else 'comment failed'
return False, None, f'unknown action kind {a["kind"]}'