File size: 9,214 Bytes
e980186
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
"""The chat socket: WS /v1/chat/ws. Every chat read and write as a command, plus live events (live.py).

Frames are JSON text. The client sends {"id", "type", ...params}; the reply repeats the id:
{"id", "type": "<type>.ok", "data"} or {"id", "type": "error", "status", "error": {code, message, fields}}.
Events arrive without an id: {"type": "message.new" | "thread.read" | "thread.new", "data"}.

The first frame must be {"type": "auth", "token": <access token>}. Each command runs in its own short database
transaction through ThreadService, so the rules and shapes are the ones the REST endpoints have.
"""

import asyncio
import json
import logging
from collections.abc import Awaitable, Callable
from datetime import UTC, datetime
from typing import Any, Literal
from uuid import UUID

import jwt
from fastapi import APIRouter, WebSocket, WebSocketDisconnect
from pydantic import Field, TypeAdapter, ValidationError
from sqlalchemy.ext.asyncio import AsyncSession

from app.common.academy_access import staff_context
from app.common.schemas import RequestModel
from app.core.database import get_autocommit_engine, get_session_factory
from app.core.errors import AppError, Forbidden, Unauthenticated, ValidationFailed, _field_path
from app.core.pagination import PageParams, decode_cursor
from app.core.security import decode_access_token
from app.integrations.push import get_push_client
from app.integrations.storage import get_storage
from app.modules.accounts.models import Account
from app.modules.idempotency.service import run_idempotent
from app.modules.threads import live
from app.modules.threads.schemas import EnsureThreadIn, MessageIn
from app.modules.threads.service import ThreadService

log = logging.getLogger(__name__)
router = APIRouter()

AUTH_TIMEOUT_S = 10.0
CLOSE_UNAUTHENTICATED = 4401


class ListIn(RequestModel):
    mode: Literal["h", "p"] | None = None
    player_id: UUID | None = None
    unread: bool | None = None
    cursor: str | None = None
    limit: int = Field(50, ge=1, le=200)


class GetIn(RequestModel):
    thread_id: UUID
    message_cursor: str | None = None
    message_limit: int = Field(50, ge=1, le=100)


class ForSessionIn(RequestModel):
    session_id: UUID


class ReadIn(RequestModel):
    thread_id: UUID
    last_message_id: UUID | None = None


class SendIn(RequestModel):
    thread_id: UUID
    message: MessageIn
    idempotency_key: str | None = Field(None, min_length=1, max_length=200)


class EnsureIn(EnsureThreadIn):
    player_id: UUID


Context = tuple[ThreadService, Account, AsyncSession, live.Connection]


async def _list(ctx: Context, p: ListIn) -> Any:
    service, account, _, connection = ctx
    page = await service.list_threads(account, PageParams(p.limit, decode_cursor(p.cursor) if p.cursor else None),
                                      mode=p.mode, player_id=p.player_id, unread=p.unread)
    connection.watched.update(t.id for t in page.items)
    return page


async def _get(ctx: Context, p: GetIn) -> Any:
    service, account, _, connection = ctx
    thread = await service.get(account, p.thread_id, p.message_cursor, p.message_limit)
    connection.watched.add(thread.id)
    return {"thread": thread}


async def _for_session(ctx: Context, p: ForSessionIn) -> Any:
    service, account, _, connection = ctx
    thread = await service.for_session(account, p.session_id)
    connection.watched.add(thread.id)
    return {"thread": thread}


async def _read(ctx: Context, p: ReadIn) -> Any:
    service, account, _, _ = ctx
    await service.mark_read(account, p.thread_id, p.last_message_id)
    return {}


async def _send(ctx: Context, p: SendIn) -> Any:
    service, account, db, _ = ctx
    # A resend after a dropped connection carries the same key and gets the first result back.
    response = await run_idempotent(db, account.id, p.idempotency_key, p.message,
                                    lambda: service.send(account, p.thread_id, p.message),
                                    status_code=201, scope=p.thread_id)
    return json.loads(response.body)


async def _ensure(ctx: Context, p: EnsureIn) -> Any:
    service, account, db, connection = ctx
    staff = await staff_context(db, account)
    if staff is None:
        raise Forbidden("Only coaches can do this.")
    thread, created = await service.ensure_general(staff, p.player_id, EnsureThreadIn(mode=p.mode))
    connection.watched.add(thread.id)
    return {"thread": thread, "created": created}


# type -> (params model, handler, read-only)
COMMANDS: dict[str, tuple[type[RequestModel], Callable[[Context, Any], Awaitable[Any]], bool]] = {
    "threads.list": (ListIn, _list, True),
    "thread.get": (GetIn, _get, True),
    "thread.for_session": (ForSessionIn, _for_session, True),
    "thread.read": (ReadIn, _read, False),
    "message.send": (SendIn, _send, False),
    "thread.ensure": (EnsureIn, _ensure, False),
}
_FRAME = TypeAdapter(dict[str, Any])


def _error(exc: Exception) -> dict:
    if isinstance(exc, ValidationError):
        fields: dict[str, str] = {}
        for err in exc.errors():
            fields.setdefault(_field_path(tuple(err.get("loc", ()))), err.get("msg", "Invalid value."))
        exc = ValidationFailed(fields=fields)
    if not isinstance(exc, AppError):
        log.exception("chat socket command failed", exc_info=exc)
        exc = AppError()
    error: dict = {"code": exc.code, "message": exc.message}
    if exc.fields:
        error["fields"] = exc.fields
    return {"type": "error", "status": exc.status_code, "error": error}


def _authenticate(token: Any) -> tuple[UUID, datetime]:
    if not isinstance(token, str):
        raise Unauthenticated()
    account_id = decode_access_token(token)  # verifies signature, type and expiry
    expires = jwt.decode(token, options={"verify_signature": False})["exp"]
    return account_id, datetime.fromtimestamp(expires, UTC)


async def _run(connection: live.Connection, kind: str, params: dict) -> Any:
    if kind not in COMMANDS:
        raise ValidationFailed(fields={"type": "Unknown command."})
    model, handler, read_only = COMMANDS[kind]
    parsed = model.model_validate(params)
    # Reads skip BEGIN/COMMIT like GET requests do; the connection goes back to the pool after every command.
    async with get_session_factory()(**({"bind": get_autocommit_engine()} if read_only else {})) as db:
        account = await db.get(Account, connection.account_id)
        if account is None:
            raise Unauthenticated()
        service = ThreadService(db, get_storage(), get_push_client())
        result = await handler((service, account, db, connection), parsed)
        await db.commit()
        return result


async def serve(socket) -> None:
    """One connection, start to finish. `socket` needs accept, receive_text, send_text and close."""
    await socket.accept()
    connection: live.Connection | None = None
    try:
        while True:
            # An unauthenticated socket may not sit open: the first frame has to arrive promptly.
            raw = await asyncio.wait_for(socket.receive_text(), None if connection else AUTH_TIMEOUT_S)
            reply: dict = {}
            try:
                frame = _FRAME.validate_json(raw)
                kind, request_id = frame.pop("type", None), frame.pop("id", None)
                if request_id is not None:
                    reply["id"] = request_id
                if kind == "ping":
                    reply["type"] = "pong"
                elif kind == "auth":
                    account_id, expires_at = _authenticate(frame.get("token"))
                    if connection is None:
                        connection = live.Connection(socket, account_id, expires_at)
                        live.CONNECTIONS.add(connection)
                    elif connection.account_id != account_id:
                        raise Unauthenticated("This connection belongs to another account.")
                    connection.expires_at = expires_at
                    reply.update(type="auth.ok", data={"account_id": account_id, "expires_at": expires_at})
                elif connection is None:
                    raise Unauthenticated()
                elif connection.expires_at <= datetime.now(UTC):
                    raise Unauthenticated("Your sign-in has expired. Send auth again with a new token.",
                                          code="TOKEN_EXPIRED")
                else:
                    reply.update(type=f"{kind}.ok", data=await _run(connection, kind, frame))
            except Exception as exc:
                reply.update(_error(exc))
            if connection is not None:
                await connection.send(reply)
            else:
                await socket.send_text(json.dumps(reply))
                await socket.close(CLOSE_UNAUTHENTICATED)  # no valid auth as the first frame
                return
    except TimeoutError:
        await socket.close(CLOSE_UNAUTHENTICATED)
    except WebSocketDisconnect:
        pass
    finally:
        if connection is not None:
            live.CONNECTIONS.discard(connection)


@router.websocket("/v1/chat/ws")
async def chat_socket(socket: WebSocket) -> None:
    await serve(socket)