baseball-engine / backend /docs /CHAT_SOCKET_INTEGRATION.md
github-actions[bot]
Automated Deploy: a36ad9fbaf2a4b4a2efb7feea50aa69986cf59d3
e980186
|
Raw History Blame Contribute Delete
16.7 kB
# Chat over WebSocket: frontend integration guide
Chat (conversations between a player and their coaches) now runs over one WebSocket. This guide lists what to
change in the app.
## 0. Summary of what is new
1. **Chat socket.** One WebSocket, `wss://<api host>/v1/chat/ws`, carries every chat action (list, open, send,
mark read) and pushes new messages live. The app no longer polls. See §2 to §6.
2. **Photos and videos in chat.** Two new message kinds, `image` and `video`, can be sent and received, over the
socket and in every thread read. See §4.1.
3. **The file URL is in `media.url`.** Each `image` and `video` message has a key named **`media`**, and the link
to show or play is the **`url`** field inside it:
| Key | Meaning |
|---|---|
| `media.url` | The link to the photo or video. Display or play this. |
| `media.upload_id` | Permanent id of the file. Use it as the cache key. |
| `media.expires_at` | When `media.url` stops working (about one hour after it was issued) |
| `media.seconds` | Video length in seconds; `null` for a photo |
4. **Links are temporary, files are not.** `media.url` is a signed link that expires; the server issues a fresh
one every time a message is sent to the app. See "Why the link expires" in §4.1.
The thread object and the existing message kinds (`text`, `voice`, `session`, `review`) are unchanged: they are the
ones in `FRONTEND_INTEGRATION.md` §14.4.
## 1. What changes for the app
| Before (REST) | Now (socket command) |
|---|---|
| `GET /v1/threads` | `threads.list` |
| `GET /v1/threads/{id}` | `thread.get` |
| `GET /v1/sessions/{id}/thread` | `thread.for_session` |
| `POST /v1/threads/{id}/messages` | `message.send` |
| `POST /v1/threads/{id}/read` | `thread.read` |
| `POST /v1/coach/players/{id}/thread` | `thread.ensure` |
| Re-fetching threads to see new messages | Live events: `message.new`, `thread.read`, `thread.new` |
- **Stop polling.** Remove every timer or focus refresh that re-fetches threads. Load once over the socket, then
apply the events.
- **Files still upload over HTTP.** For a voice note, photo or video, get the presigned URL from
`POST /v1/uploads`, PUT the file, then send `message.send` with the `upload_id` (§4.1). Files never go through
the socket.
- **Older app builds will receive `image` and `video` messages** in threads once someone sends one. Make sure
every build in use renders an unknown `kind` as a placeholder instead of crashing.
- **Push notifications are unchanged.** A new message still creates an inbox notification and a push. While the
socket is open and the app is in the foreground, ignore the chat push and show the live event instead.
- **The REST endpoints still work** so released app builds keep working, and whatever they write reaches open
sockets as live events. New code should not call them.
## 2. Connecting
```
wss://<api host>/v1/chat/ws
```
1. Open the socket when the user is signed in and the app is in the foreground. One socket per app instance is
enough; it serves every thread.
2. **The first frame must be `auth`,** within 10 seconds:
```json
{"id":"1","type":"auth","token":"<access_token>"}
```
Reply: `{"id":"1","type":"auth.ok","data":{"account_id":"...","expires_at":"2026-11-17T18:30:00Z"}}`.
3. If the first frame is anything else, or the token is invalid, the server replies with an error and closes the
socket with code **4401**. Refresh the token over REST (`POST /v1/auth/refresh`) and connect again.
The token is sent in a frame, not in the URL, so it does not end up in server or proxy logs.
### When the access token expires
The socket stays open, but it stops working until you authenticate again:
- Commands get `{"type":"error","status":401,"error":{"code":"TOKEN_EXPIRED",...}}`.
- **Live events are not delivered while the token is expired.**
So refresh before `expires_at` (from `auth.ok`), then send `auth` again **on the same socket** with the new token.
After any gap (expired token or reconnect), reload the open thread and the list (§6), because events from the gap
are not replayed.
## 3. Frame format
Every frame is a JSON text frame.
**Command (app → server).** `id` is any string you choose; the reply repeats it. Parameters sit next to `type`.
```json
{"id":"42","type":"thread.get","thread_id":"6f1c...","message_limit":50}
```
**Reply (server → app).** One per command.
```json
{"id":"42","type":"thread.get.ok","data":{ ... }}
{"id":"42","type":"error","status":404,"error":{"code":"NOT_FOUND","message":"...","fields":{...}}}
```
- `error` is the same object as the REST error envelope (`FRONTEND_INTEGRATION.md` §3), and `status` is the HTTP
status the REST endpoint would have returned. Reuse your existing error handling.
- Replies can arrive in a different order from the commands, and events can arrive in between. Match replies by
`id`.
**Event (server → app).** No `id`.
```json
{"type":"message.new","data":{ ... }}
```
**Keep-alive.** `{"id":"7","type":"ping"}` → `{"id":"7","type":"pong"}`. Send one every 25 seconds or so if your
network stack drops idle sockets.
## 4. Commands
All ids are UUID strings. Unknown parameters are rejected with 400 `VALIDATION`.
### `threads.list`
| Param | Type | Notes |
|---|---|---|
| `mode` | `"h"` \| `"p"` | optional |
| `player_id` | uuid | optional; coaches filter by player |
| `unread` | bool | optional |
| `cursor` | string | optional; `next_cursor` from the previous page |
| `limit` | int | 1–200, default 50 |
`data`: `{"items":[Thread, ...],"next_cursor":"...|null"}`. Each thread carries its latest 20 messages.
### `thread.get`
| Param | Type | Notes |
|---|---|---|
| `thread_id` | uuid | required |
| `message_cursor` | string | optional; `next_message_cursor` of the thread, to load older messages |
| `message_limit` | int | 1–100, default 50 |
`data`: `{"thread": Thread}`.
### `thread.for_session`
`session_id` (uuid, required). `data`: `{"thread": Thread}`. Error 404 `THREAD_NOT_FOUND` when the session has no
conversation yet.
### `message.send`
```json
{"id":"9","type":"message.send","thread_id":"6f1c...","idempotency_key":"<uuid you generate>",
"message":{"kind":"text","text":"Thanks coach"}}
```
`message` is one of:
```json
{"kind":"text","text":"1 to 500 characters"}
{"kind":"voice","upload_id":"<audio upload>","seconds":12}
{"kind":"image","upload_id":"<image upload>"}
{"kind":"video","upload_id":"<video upload>","seconds":8.4}
{"kind":"session","session_id":"<one of the player's sessions, same mode>"}
```
`data`: `{"message": Message, "thread_status": "waiting_for_coach|reviewed", "updated_at": "..."}`.
- **Always send an `idempotency_key`** (a new UUID per message the user sends). If the connection drops before the
reply arrives, send the same frame again after reconnecting: the server returns the first result and does not
create a second message. The same key with a different message returns 409 `IDEMPOTENCY_KEY_REUSED`.
- Errors are the ones the REST endpoint had: 404 `NOT_FOUND`, 422 `MODE_MISMATCH`, 422 `INVALID_UPLOAD`,
422 `UPLOAD_ALREADY_USED`, 409 `UPLOAD_NOT_READY`, 403 `FORBIDDEN`.
- The sender also receives the `message.new` event for their own message (§5).
### 4.1 Photos and videos: the `media` key
**Sending.** Upload first, over HTTP, then send the message with the upload id.
1. `POST /v1/uploads` with one of:
| For | Body | Limits |
|---|---|---|
| Photo | `{"kind":"image","content_type":"image/jpeg","size_bytes":123456}` | `image/jpeg`, `image/png` or `image/webp`; at most 10 MB |
| Video | `{"kind":"video","content_type":"video/mp4","size_bytes":123456,"duration_sec":8.4}` | `video/mp4` or `video/quicktime`; at most 250 MB and 60 s |
The response is `{"upload_id","url","headers","expires_at"}`.
2. `PUT` the file to `url` with the returned `headers`.
3. Send `message.send` with `{"kind":"image","upload_id":...}` or `{"kind":"video","upload_id":...,"seconds":8.4}`.
Convert HEIC photos to JPEG before uploading. Each upload can be used in one message only, and only by the account
that created it.
| Error | Meaning |
|---|---|
| 409 `UPLOAD_NOT_READY` | The PUT has not finished. Retry the send. |
| 422 `UPLOAD_ALREADY_USED` | This upload is already in a message (or a session). Upload again. |
| 422 `INVALID_UPLOAD` | Not the sender's upload, or the wrong kind (an image id sent as video, and so on) |
**Receiving.** The message carries the file in `media`, in replies, in `message.new` events and in thread reads:
```json
{"id":"...","author_id":"...","from":"player","at":"2026-11-18T09:12:03Z","kind":"image",
"media":{"upload_id":"...","url":"https://...signed...","expires_at":"2026-11-18T10:12:03Z","seconds":null}}
{"id":"...","author_id":"...","from":"coach","at":"2026-11-18T09:13:40Z","kind":"video","seconds":8.4,
"media":{"upload_id":"...","url":"https://...signed...","expires_at":"2026-11-18T10:13:40Z","seconds":8.4}}
```
- **Show the photo or play the video from `media.url`.** That is the only field that holds the link.
- `media` is `null` when the file has been deleted; show a "no longer available" placeholder.
- Voice notes keep their existing `audio` key, with the same object shape (`audio.url`, `audio.upload_id`,
`audio.expires_at`, `audio.seconds`).
- There is no separate thumbnail for a chat video; show the first frame or a generic tile.
#### Why the link expires, and what the app does about it
- **Why.** The storage bucket is private, because it holds photos, videos and voice notes of players, many of
them minors. A private bucket can only give out temporary signed links. If a link leaks (a forwarded message, a
log, a screenshot) it stops working within the hour, and someone who loses access to a conversation stops
getting new links.
- **Only the link expires. The file stays.** The message and its file are kept; nothing disappears for the user.
- **The server issues a new signed URL every time it sends a message to the app:** in `threads.list`,
`thread.get` and `thread.for_session` results, in the `message.send` reply, and in every `message.new` event.
Each one is valid for about one hour from that moment. The same file therefore has a different `media.url` each
time; `media.upload_id` stays the same.
- **There is no "refresh URL" call.** To get a fresh link, read the thread again with `thread.get`.
What to implement:
1. **Never store `media.url`** in a database, local storage or app state that outlives the screen. Store
`media.upload_id`.
2. **Cache the downloaded file by `media.upload_id`.** Once a photo or video is on the device, show it from the
cache and do not download it again, whatever the current URL is.
3. **Before loading from `media.url`, check `media.expires_at`.** If it has passed, or the download returns 403,
call `thread.get` for that thread, take the new `media.url` for the same message `id`, and load again.
4. **A thread left open for more than an hour** needs this too: a video tapped after the link expired must go
through step 3 instead of showing an error.
### `thread.read`
`thread_id` (uuid, required), `last_message_id` (uuid; the newest message the user has seen). `data`: `{}`.
Send it when the thread is on screen and a new message is displayed. 422 `MESSAGE_NOT_IN_THREAD` when the message
belongs to another thread.
### `thread.ensure` (coaches)
`player_id` (uuid), `mode` (`"h"` \| `"p"`). Opens the general thread with a player, creating it if needed.
`data`: `{"thread": Thread, "created": true|false}`. 403 `FORBIDDEN` for players.
## 5. Events
Events are sent to every open socket of the thread's player and coach, and to other academy staff who have loaded
the thread on that socket (through `threads.list`, `thread.get`, `thread.for_session` or `thread.ensure`).
### `message.new`
A message was added: sent by either side from any device (socket or REST), or a coach review was posted or updated.
```json
{"type":"message.new","data":{
"thread_id":"6f1c...","message": Message,
"thread_status":"waiting_for_coach","updated_at":"...",
"unread_for_player":false,"unread_for_coach":true}}
```
- Append `message` to the thread if its `id` is not already there. **Dedupe by `message.id`**: the sender gets this
event as well as the `message.send` reply, and a re-posted review arrives with the same `id` (replace it and move
it to the end).
- Update the thread row from `thread_status`, `updated_at` and the two `unread_*` flags, and move it to the top of
the list.
- If the thread is not in your list yet, load it with `thread.get`.
### `thread.read`
One side advanced its read mark.
```json
{"type":"thread.read","data":{"thread_id":"6f1c...","thread_status":"reviewed","updated_at":"...",
"unread_for_player":false,"unread_for_coach":false}}
```
Update the unread badges. For the sender's side this is the "seen" signal: when `unread_for_coach` turns false, the
coach has read the player's messages.
### `thread.new`
A coach opened a new general thread. `data`: `{"thread": Thread}`. Add it to the list.
## 6. Reconnecting
The server does not replay events missed while the socket was closed or the token was expired.
1. On close (other than a deliberate sign-out), reconnect with backoff: 1 s, 2 s, 5 s, then every 10 s.
2. Send `auth` with a current token.
3. Run `threads.list`, and `thread.get` for the thread on screen, and replace local state with the result.
4. Re-send any `message.send` that never got a reply, with its original `idempotency_key`.
Close the socket on sign-out and when the app goes to the background; push notifications cover the background.
## 7. Minimal client (TypeScript)
```ts
type Frame = { id?: string; type: string; data?: any; status?: number; error?: { code: string; message: string } };
export class ChatSocket {
private ws?: WebSocket;
private next = 1;
private waiting = new Map<string, { resolve: (d: any) => void; reject: (e: any) => void }>();
constructor(private url: string, private getToken: () => Promise<string>,
private onEvent: (type: string, data: any) => void, private onReady: () => void) {}
async connect() {
const ws = new WebSocket(this.url);
this.ws = ws;
ws.onmessage = (e) => {
const frame: Frame = JSON.parse(e.data);
const pending = frame.id ? this.waiting.get(frame.id) : undefined;
if (pending) {
this.waiting.delete(frame.id!);
frame.type === "error" ? pending.reject(frame) : pending.resolve(frame.data);
} else if (!frame.id) {
this.onEvent(frame.type, frame.data);
}
};
ws.onclose = () => {
this.waiting.forEach((p) => p.reject({ type: "error", error: { code: "DISCONNECTED", message: "" } }));
this.waiting.clear();
setTimeout(() => this.connect(), 2000); // use backoff in production
};
ws.onopen = async () => {
await this.call("auth", { token: await this.getToken() });
this.onReady(); // reload threads.list and the open thread here
};
}
call<T = any>(type: string, params: object = {}): Promise<T> {
const id = String(this.next++);
return new Promise((resolve, reject) => {
this.waiting.set(id, { resolve, reject });
this.ws!.send(JSON.stringify({ id, type, ...params }));
});
}
}
// Usage
// const page = await chat.call("threads.list", { limit: 50 });
// await chat.call("message.send", { thread_id, idempotency_key: uuid(), message: { kind: "text", text } });
```
## 8. Checklist
- [ ] Socket opens after sign-in, sends `auth` first, and closes on sign-out and in the background.
- [ ] Token is refreshed before `expires_at` and `auth` is sent again on the same socket.
- [ ] Thread list, thread screen, send, read and "open thread with player" use socket commands.
- [ ] All polling of threads is removed.
- [ ] `message.new`, `thread.read` and `thread.new` update the list and the open thread; messages are deduped by id.
- [ ] Every `message.send` has an `idempotency_key` and is re-sent after a reconnect if it had no reply.
- [ ] After every reconnect or re-auth, the list and the open thread are reloaded.
- [ ] Voice notes, photos and videos upload through `POST /v1/uploads` first.
- [ ] `image` and `video` messages render from `media.url` and handle `media: null`.
- [ ] `media.url` is never stored; files are cached by `media.upload_id`.
- [ ] An expired link (past `media.expires_at`, or a 403) triggers `thread.get` and a retry with the new `media.url`.
- [ ] Unknown message kinds render as a placeholder.
- [ ] Chat pushes are ignored while the socket is open in the foreground.