Coverage for dao/notification_threads_dao.py: 33.33%

44 statements  

« prev     ^ index     » next       coverage.py v7.10.6, created at 2026-11-30 14:44 +0000

1"""Which platform thread holds a match on a channel (SB-1606). 

2 

3One row per (channel, match). The unique constraint is the lock: whoever 

4inserts the row creates the thread; anyone else reads the row and posts into 

5`thread_ref` once it is set. A claim whose creator died (no ref after 

6STALE_SECONDS) or failed (released) can be taken over, atomically. 

7 

8Holds no destination. Errors are logged by type only. 

9""" 

10 

11from __future__ import annotations 

12 

13from datetime import UTC, datetime, timedelta 

14 

15import structlog 

16 

17from dao.base_dao import BaseDAO 

18 

19logger = structlog.get_logger() 

20 

21TABLE = "notification_threads" 

22_UNIQUE_VIOLATION = "23505" 

23STALE_SECONDS = 120 

24# A released claim is backdated so it is stale at once. 

25_RELEASED_AT = "1970-01-01T00:00:00+00:00" 

26 

27 

28class ThreadStoreError(Exception): 

29 """The thread table could not be read or written. Safe to log.""" 

30 

31 

32class NotificationThreadsDAO(BaseDAO): 

33 """Data access for match threads.""" 

34 

35 def claim(self, channel_id: int, match_id: int, thread_name: str) -> tuple[bool, dict]: 

36 """(True, row) when this caller must create the thread; (False, row) when it exists. 

37 

38 Raises ThreadStoreError when the table cannot answer. 

39 """ 

40 row = {"channel_id": channel_id, "match_id": match_id, "thread_name": thread_name} 

41 try: 

42 return True, self.client.table(TABLE).insert(row).execute().data[0] 

43 except Exception as exc: 

44 if _UNIQUE_VIOLATION not in str(exc): 

45 logger.error("dao_notification_threads_claim_failed", error_type=type(exc).__name__) 

46 raise ThreadStoreError("Could not claim the match thread") from None 

47 try: 

48 existing = ( 

49 self.client.table(TABLE) 

50 .select("*") 

51 .eq("channel_id", channel_id) 

52 .eq("match_id", match_id) 

53 .limit(1) 

54 .execute() 

55 .data 

56 ) 

57 except Exception as exc: 

58 logger.error("dao_notification_threads_read_failed", error_type=type(exc).__name__) 

59 raise ThreadStoreError("Could not read the match thread") from None 

60 if not existing: 

61 raise ThreadStoreError("Match thread vanished") 

62 return False, existing[0] 

63 

64 def take_over(self, thread_id: int, now: datetime | None = None) -> dict | None: 

65 """Claim a thread row whose creator died or gave up. None if someone else holds it.""" 

66 cutoff = ((now or datetime.now(UTC)) - timedelta(seconds=STALE_SECONDS)).isoformat() 

67 try: 

68 rows = ( 

69 self.client.table(TABLE) 

70 .update({"created_at": (now or datetime.now(UTC)).isoformat()}) 

71 .eq("id", thread_id) 

72 .is_("thread_ref", "null") 

73 .lt("created_at", cutoff) 

74 .execute() 

75 .data 

76 ) 

77 except Exception as exc: 

78 logger.error("dao_notification_threads_takeover_failed", error_type=type(exc).__name__) 

79 raise ThreadStoreError("Could not take over the match thread") from None 

80 return rows[0] if rows else None 

81 

82 def set_ref(self, thread_id: int, thread_ref: str) -> None: 

83 self._update(thread_id, {"thread_ref": thread_ref}) 

84 

85 def release(self, thread_id: int) -> None: 

86 """Give up creating the thread so the next sender can, straight away.""" 

87 self._update(thread_id, {"created_at": _RELEASED_AT}) 

88 

89 def _update(self, thread_id: int, fields: dict) -> None: 

90 try: 

91 self.client.table(TABLE).update(fields).eq("id", thread_id).execute() 

92 except Exception as exc: 

93 logger.error("dao_notification_threads_update_failed", error_type=type(exc).__name__)