|
| 1 | +""" |
| 2 | +Emote broadcast service (PR-07). |
| 3 | +
|
| 4 | +Responsibilities |
| 5 | +---------------- |
| 6 | +* Validate that an emote_id belongs to the fixed permitted catalog. |
| 7 | +* Enforce per-connection rate limits (all values from settings): |
| 8 | + - Cooldown: EMOTE_COOLDOWN_SECONDS (1.5 s) between any two emotes. |
| 9 | + - Burst cap: at most EMOTE_BURST_CAP (3) emotes within |
| 10 | + EMOTE_BURST_WINDOW_SECONDS (10 s) sliding window. |
| 11 | + - Same-emote soft block: more than EMOTE_SAME_REPEAT_CAP (2) consecutive |
| 12 | + sends of the identical slug are denied until a different emote is sent. |
| 13 | +* Provide reset() for test isolation. |
| 14 | +
|
| 15 | +No broadcast or session logic lives here — the WS handler is responsible |
| 16 | +for fanout and mute filtering. |
| 17 | +
|
| 18 | +Emote catalog |
| 19 | +------------- |
| 20 | +Emotes are identified by a short ASCII slug. The client maps these to |
| 21 | +emoji / images. The server only validates the slug — it never stores or |
| 22 | +renders it. |
| 23 | +
|
| 24 | +Permitted slugs: |
| 25 | + thumbsup 👍 좋아요 |
| 26 | + thumbsdown 👎 별로 |
| 27 | + smile 😄 웃음 |
| 28 | + sweat 😅 땀 |
| 29 | + thinking 🤔 생각 |
| 30 | + fire 🔥 열정 |
| 31 | + cry 😭 눈물 |
| 32 | + clap 👏 박수 |
| 33 | +""" |
| 34 | + |
| 35 | +from __future__ import annotations |
| 36 | + |
| 37 | +import time |
| 38 | + |
| 39 | +from app.config import settings |
| 40 | + |
| 41 | +# --------------------------------------------------------------------------- |
| 42 | +# Catalog |
| 43 | +# --------------------------------------------------------------------------- |
| 44 | + |
| 45 | +VALID_EMOTE_IDS: frozenset[str] = frozenset( |
| 46 | + { |
| 47 | + "thumbsup", |
| 48 | + "thumbsdown", |
| 49 | + "smile", |
| 50 | + "sweat", |
| 51 | + "thinking", |
| 52 | + "fire", |
| 53 | + "cry", |
| 54 | + "clap", |
| 55 | + } |
| 56 | +) |
| 57 | + |
| 58 | + |
| 59 | +# --------------------------------------------------------------------------- |
| 60 | +# Service |
| 61 | +# --------------------------------------------------------------------------- |
| 62 | + |
| 63 | + |
| 64 | +class EmoteService: |
| 65 | + """ |
| 66 | + Stateful rate-limit tracker for emote broadcasts. |
| 67 | +
|
| 68 | + One instance is shared for the entire server process. All state is |
| 69 | + keyed by connection_id so there is no per-user persistence. |
| 70 | + State is cleared between tests via reset(). |
| 71 | + """ |
| 72 | + |
| 73 | + def __init__(self) -> None: |
| 74 | + # connection_id -> timestamp of the most recent allowed emote |
| 75 | + self._last_sent: dict[str, float] = {} |
| 76 | + # connection_id -> list of timestamps within the current burst window |
| 77 | + self._window_history: dict[str, list[float]] = {} |
| 78 | + # connection_id -> (last_emote_id, consecutive_count) |
| 79 | + # Tracks same-emote repetitions for soft-block enforcement. |
| 80 | + self._same_emote: dict[str, tuple[str, int]] = {} |
| 81 | + # connection_id -> reason string for the most recent denial |
| 82 | + # One of: "cooldown", "burst", "same_emote" |
| 83 | + self._last_deny_reason: dict[str, str] = {} |
| 84 | + |
| 85 | + # ------------------------------------------------------------------ |
| 86 | + # Validation |
| 87 | + # ------------------------------------------------------------------ |
| 88 | + |
| 89 | + def is_valid_emote(self, emote_id: str) -> bool: |
| 90 | + """Return True if emote_id is in the permitted catalog.""" |
| 91 | + return emote_id in VALID_EMOTE_IDS |
| 92 | + |
| 93 | + # ------------------------------------------------------------------ |
| 94 | + # Rate limiting |
| 95 | + # ------------------------------------------------------------------ |
| 96 | + |
| 97 | + def check_and_record(self, conn_id: str, emote_id: str) -> bool: |
| 98 | + """ |
| 99 | + Check whether conn_id may send *emote_id* right now. |
| 100 | +
|
| 101 | + Returns True and records the emission if allowed. |
| 102 | + Returns False (without recording) if any limit would be violated. |
| 103 | +
|
| 104 | + Rules applied in order: |
| 105 | + 1. Cooldown: now − last_sent < EMOTE_COOLDOWN_SECONDS → deny. |
| 106 | + 2. Burst cap: entries_in_window >= EMOTE_BURST_CAP → deny. |
| 107 | + 3. Same-emote soft block: consecutive_same > EMOTE_SAME_REPEAT_CAP |
| 108 | + → deny until a different emote is used. |
| 109 | + """ |
| 110 | + now = time.time() |
| 111 | + |
| 112 | + # 1. Cooldown check |
| 113 | + last = self._last_sent.get(conn_id, 0.0) |
| 114 | + if now - last < settings.EMOTE_COOLDOWN_SECONDS: |
| 115 | + self._last_deny_reason[conn_id] = "cooldown" |
| 116 | + return False |
| 117 | + |
| 118 | + # 2. Burst window — prune expired entries then count |
| 119 | + window = self._window_history.get(conn_id, []) |
| 120 | + window = [t for t in window if now - t < settings.EMOTE_BURST_WINDOW_SECONDS] |
| 121 | + if len(window) >= settings.EMOTE_BURST_CAP: |
| 122 | + self._last_deny_reason[conn_id] = "burst" |
| 123 | + return False |
| 124 | + |
| 125 | + # 3. Same-emote soft block |
| 126 | + prev_id, streak = self._same_emote.get(conn_id, ("", 0)) |
| 127 | + if emote_id == prev_id and streak >= settings.EMOTE_SAME_REPEAT_CAP: |
| 128 | + self._last_deny_reason[conn_id] = "same_emote" |
| 129 | + return False |
| 130 | + |
| 131 | + # Allowed — record |
| 132 | + window.append(now) |
| 133 | + self._last_sent[conn_id] = now |
| 134 | + self._window_history[conn_id] = window |
| 135 | + |
| 136 | + # Update same-emote streak counter |
| 137 | + if emote_id == prev_id: |
| 138 | + self._same_emote[conn_id] = (emote_id, streak + 1) |
| 139 | + else: |
| 140 | + self._same_emote[conn_id] = (emote_id, 1) |
| 141 | + |
| 142 | + return True |
| 143 | + |
| 144 | + def last_deny_reason(self, conn_id: str) -> str: |
| 145 | + """ |
| 146 | + Return the reason for the most recent rate-limit denial for conn_id. |
| 147 | +
|
| 148 | + Returns one of: ``"cooldown"``, ``"burst"``, ``"same_emote"``. |
| 149 | + Returns ``""`` if conn_id has never been denied. |
| 150 | + """ |
| 151 | + return self._last_deny_reason.get(conn_id, "") |
| 152 | + |
| 153 | + def remaining_cooldown(self, conn_id: str) -> float: |
| 154 | + """ |
| 155 | + Return seconds until the cooldown expires for conn_id. |
| 156 | +
|
| 157 | + Returns 0.0 if the connection is not rate-limited. |
| 158 | + Useful for generating informative error messages. |
| 159 | + """ |
| 160 | + last = self._last_sent.get(conn_id, 0.0) |
| 161 | + remaining = settings.EMOTE_COOLDOWN_SECONDS - (time.time() - last) |
| 162 | + return max(0.0, remaining) |
| 163 | + |
| 164 | + # ------------------------------------------------------------------ |
| 165 | + # Lifecycle |
| 166 | + # ------------------------------------------------------------------ |
| 167 | + |
| 168 | + def reset(self) -> None: |
| 169 | + """Clear all rate-limit state. Called between tests.""" |
| 170 | + self._last_sent.clear() |
| 171 | + self._window_history.clear() |
| 172 | + self._same_emote.clear() |
| 173 | + self._last_deny_reason.clear() |
| 174 | + |
| 175 | + |
| 176 | +# --------------------------------------------------------------------------- |
| 177 | +# Module-level singleton |
| 178 | +# --------------------------------------------------------------------------- |
| 179 | + |
| 180 | +emote_service = EmoteService() |
0 commit comments