nomadro/apps/api/services/social_svc/im.py
Eric ffa456afdf Ship social join profile + SeaweedFS avatars, notify/coffee, and .com audience stack.
Pay-then-profile join desk with live card, S3 upload fallback, hydration-safe drafts; document on test9 README.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-04 02:25:05 +08:00

46 lines
1.3 KiB
Python

"""Tinode-inspired IM primitives on Nomadro social stack.
Borrowed ideas (not code) from tinode/chat:
- per-topic monotonic ``seq`` for sync / unread / pagination
- clientId idempotent publish
- note.recv / note.read watermarks
- lightweight rate limit before fan-out
Transport stays Centrifugo; persistence stays SQLite (isolated social.db).
"""
from __future__ import annotations
import time
from collections import defaultdict, deque
from threading import Lock
from typing import Any
# guest -> timestamps of recent posts (process-local; fine for single social worker)
_RATE: dict[str, deque[float]] = defaultdict(deque)
_RATE_LOCK = Lock()
_RATE_WINDOW_SEC = 60.0
_RATE_MAX = 30 # msgs / window / guest
def check_rate(guest_id: str) -> None:
"""Raise ValueError if guest exceeds send rate."""
now = time.time()
key = (guest_id or "").strip() or "_"
with _RATE_LOCK:
q = _RATE[key]
while q and now - q[0] > _RATE_WINDOW_SEC:
q.popleft()
if len(q) >= _RATE_MAX:
raise ValueError("发送过快,请稍后再试")
q.append(now)
def note_event(what: str, seq: int, guest_id: str) -> dict[str, Any]:
return {
"type": "chat.note",
"what": what, # recv | read | kp
"seq": int(seq),
"guestId": guest_id,
"at": time.strftime("%Y-%m-%dT%H:%M:%S.000Z", time.gmtime()),
}