Coverage for notifications/threads.py: 100.00%
40 statements
« prev ^ index » next coverage.py v7.10.6, created at 2026-11-30 20:17 +0000
« prev ^ index » next coverage.py v7.10.6, created at 2026-11-30 20:17 +0000
1"""Post a match's updates into one thread per channel (SB-1606).
3Used by the live path (Notifier._post_to_channel) and the retry worker, so a
4thread is created once whoever gets there first:
6- The first post for a match claims its notification_threads row (the unique
7 (channel_id, match_id) is the lock), creates the thread named after the
8 match, and stores the thread id.
9- Later posts go into that thread.
10- A post that arrives while another is still creating the thread fails
11 retryably (a few seconds) and the retry worker posts it into the thread.
12- A creator that died or failed leaves a claim the next sender takes over.
14A channel not marked post_as_threads, a platform without threads, or a post
15with no match goes out flat, as before.
16"""
18from __future__ import annotations
20from typing import TYPE_CHECKING
22import structlog
24from dao.notification_threads_dao import ThreadStoreError
25from notifications.adapters.base import Capability, DeliveryError, DeliveryResult
26from notifications.registry import get_adapter
28if TYPE_CHECKING:
29 from collections.abc import Callable
31logger = structlog.get_logger(__name__)
33# How long a post waits for a thread another sender is still creating.
34WAIT_FOR_THREAD_SECONDS = 5
37def threads_apply(platform: str, post_as_threads: bool, match_id: int | None) -> bool:
38 if not post_as_threads or match_id is None:
39 return False
40 return Capability.THREADS in get_adapter(platform).capabilities
43def deliver_to_thread(
44 platform: str,
45 destination: str,
46 content: str,
47 channel_id: int,
48 match_id: int,
49 thread_name: str,
50 threads,
51) -> DeliveryResult:
52 """Post into the match's thread on this channel, creating it if this caller won the claim."""
53 adapter = get_adapter(platform)
54 try:
55 mine, row = threads.claim(channel_id, match_id, thread_name)
56 except ThreadStoreError:
57 # Without the table, posting a fresh thread beats losing the update.
58 logger.warning("notifications.thread_store_unavailable", channel_id=channel_id, match_id=match_id)
59 return adapter.send_in_thread(destination, content, None, thread_name)
61 if not mine:
62 if row.get("thread_ref"):
63 return adapter.send_in_thread(destination, content, row["thread_ref"], None)
64 taken = threads.take_over(row["id"])
65 if taken is None:
66 raise DeliveryError(
67 f"{platform} send failed: match thread is being created",
68 retryable=True,
69 retry_after=WAIT_FOR_THREAD_SECONDS,
70 )
71 row = taken
73 try:
74 result = adapter.send_in_thread(destination, content, None, row.get("thread_name") or thread_name)
75 except Exception:
76 threads.release(row["id"])
77 raise
78 if result.thread_ref:
79 threads.set_ref(row["id"], result.thread_ref)
80 else:
81 # Posted, but follow-ups could not find it: let the next post start one.
82 threads.release(row["id"])
83 logger.warning("notifications.thread_ref_missing", channel_id=channel_id, match_id=match_id)
84 return result
87def send(
88 send_fn: Callable,
89 platform: str,
90 destination: str,
91 content: str,
92 *,
93 post_as_threads: bool,
94 channel_id: int,
95 match_id: int | None,
96 thread_name: str | None,
97 threads,
98):
99 """Flat post through `send_fn`, or a match-thread post when the channel asks for one."""
100 if threads is None or match_id is None or not threads_apply(platform, post_as_threads, match_id):
101 return send_fn(platform, destination, content)
102 return deliver_to_thread(
103 platform, destination, content, channel_id, match_id, thread_name or f"Match {match_id}", threads
104 )