Files
2026-06-11 10:52:07 -04:00

270 lines
7.9 KiB
Markdown

# VitFit V2 — Socket.io Event System
Socket.io is used exclusively for the timer engine. No other feature uses real-time events in V2.
---
## Connection and Authentication
Socket.io clients must authenticate at connection time by passing the JWT in the handshake:
```js
// Client-side (socket-client.js)
const socket = io('/', {
auth: { token: localStorage.getItem('jwt') },
reconnectionDelay: 1000,
reconnectionDelayMax: 10000,
reconnectionAttempts: Infinity
});
```
Server-side (core/socket.js):
```js
io.use((socket, next) => {
const token = socket.handshake.auth.token;
if (!token) return next(new Error('AUTH_REQUIRED'));
jwt.verify(token, process.env.JWT_SECRET, (err, user) => {
if (err) return next(new Error('AUTH_INVALID'));
socket.data.user = user;
next();
});
});
```
On auth failure the socket is disconnected immediately. The client retries with exponential backoff using the reconnect config above.
---
## Rooms
Each active timer session gets its own Socket.io room named by `sessionId`:
```
timer_<timerId>_<timestamp>
e.g. timer_3_1718273400000
```
Clients join a room to receive events for that specific timer session.
Multiple clients can join the same room (e.g., the coach's iPad + the display page both watching the same timer).
---
## Events: Client → Server
### `timer:join`
Client requests to join a timer session room.
```js
// Emit
socket.emit('timer:join', { sessionId: 'timer_3_1718273400000' });
```
Server handler (order of checks):
1. Looks up the engine by `sessionId` in the active sessions Map.
2. If not found: emits `timer:error { code: 'SESSION_NOT_FOUND' }` and returns.
3. **Verifies `engine.orgId === socket.data.user.organizationId`.**
If mismatch: emits `timer:error { code: 'SESSION_NOT_FOUND' }` — same error as missing,
so cross-org probing cannot distinguish "exists but not yours" from "doesn't exist."
4. Joins the socket to the room. Emits `timer:state` back to this socket only.
```js
socket.emit('timer:state', engine.getState());
```
This org check is required because sessionId format (`timer_<timerId>_<timestamp>`) is
guessable by anyone who knows a timerId. Without it, a user from Org B could observe
Org A's timer state.
---
### `timer:leave`
Client leaves a timer room. Server removes from room.
```js
socket.emit('timer:leave', { sessionId: 'timer_3_1718273400000' });
```
No server response.
---
## Events: Server → Client
### `timer:state`
Full state snapshot. Sent on `timer:join` to the joining socket, and when a client reconnects.
```js
{
sessionId: 'timer_3_1718273400000',
status: 'running', // 'idle' | 'running' | 'paused' | 'complete'
phase: 'set', // 'set' | 'rest' | 'move'
currentLap: 1,
currentExercise: 2,
currentSet: 1,
phaseEndTime: 1718273430000, // Unix ms — client uses Date.now() diff
sessionEndTime: 1718275200000, // Unix ms — total session end
phaseRemainingMs: 28500,
totalRemainingMs: 1725000,
config: {
lapCount: 2, exerciseCount: 5, setCount: 3,
setTime: 30, restTime: 10, moveTime: 15, totalTime: 1800
}
}
```
Client uses `phaseEndTime` (absolute timestamp) to drive local countdown. If the socket goes quiet, the client can continue using `Date.now() - phaseEndTime` without server involvement.
---
### `timer:tick`
Emitted once per second while timer is running. Lightweight — only changing fields.
```js
{
sessionId: 'timer_3_1718273400000',
phaseRemainingMs: 27500,
totalRemainingMs: 1724000
}
```
Client uses this to keep displays in sync. If ticks stop arriving (disconnect), client falls back to computing from `phaseEndTime` received in the last `timer:state`.
---
### `timer:phase-change`
Emitted when phase transitions (set→rest, rest→move, move→set).
```js
{
sessionId: 'timer_3_1718273400000',
phase: 'rest',
currentLap: 1,
currentExercise: 2,
currentSet: 1,
phaseEndTime: 1718273440000, // new phase end time
phaseRemainingMs: 10000
}
```
Client uses this to update the display color, label, and reset the phase countdown.
Phase colors are read from CSS custom properties (set by branding loader) — no color data in the event.
---
### `timer:complete`
Emitted when all laps/exercises/sets are done.
```js
{
sessionId: 'timer_3_1718273400000',
totalElapsedSeconds: 1798
}
```
Client shows completion state. No further tick events will arrive.
Timer engine is cleaned up server-side after emitting this.
---
### `timer:stopped`
Emitted when a coach or owner manually stops the timer via `DELETE /api/v1/timers/session`.
```js
{
sessionId: 'timer_3_1718273400000',
elapsedSeconds: 342,
stoppedByUserId: 2
}
```
Client shows stopped state. Distinct from `timer:complete` — the timer did not finish naturally.
---
### `timer:error`
Emitted when client attempts an invalid operation.
```js
{
code: 'SESSION_NOT_FOUND',
message: 'No active timer session with that ID.'
}
```
---
## Client-Side Event Handling (timer-display.js)
```
socket connects
→ socket.emit('timer:join', { sessionId })
→ receives timer:state → render full display state
→ store phaseEndTime for local fallback
socket receives timer:tick
→ update phaseRemainingMs display (smooth update, no flicker)
socket receives timer:phase-change
→ update phase label, color, new phaseEndTime, reset phase countdown
→ play phase-change sound (if audio unlocked by prior coach tap)
socket receives timer:complete
→ show completion state
→ stop local fallback interval if running
socket receives timer:stopped
→ show stopped state
socket disconnects
→ start localFallback(phaseEndTime):
every animationFrame: remaining = phaseEndTime - Date.now()
if remaining <= 0: show phase-change estimate (cannot know new phase without server)
show "Offline - running locally" indicator
→ Socket.io reconnects automatically (exponential backoff, infinite attempts)
socket reconnects
→ stop localFallback
→ socket.emit('timer:join', { sessionId }) again to re-sync
→ receives fresh timer:state → updates display with authoritative state
```
---
## Disconnect / Reconnect Protocol
The client's `socket-client.js` wraps the Socket.io client with:
1. On `disconnect`: call registered `onDisconnect()` callback (page shows offline indicator)
2. On `connect`: call registered `onReconnect()` callback — page re-joins its room and re-syncs
3. Socket is created once per page load, not recreated
For the display pages (timer-display.html, workout-display.html, crossfit-display.html):
- Offline indicator is a slim banner at top of screen: `⚠ Reconnecting...`
- Content remains fully visible underneath — gym display does not go dark
- Indicator disappears automatically when reconnected
---
## Active Session Registry (server-side)
Timer sessions live in a `Map<sessionId, TimerEngine>` in `modules/timers/service.js`.
This is in-process memory — sessions do not survive a server restart.
Consequence: if the server restarts while a timer is running, the session is gone.
Clients will receive a `timer:error SESSION_NOT_FOUND` when they reconnect and try to re-join.
The display page shows a "Session ended — reconnect to start a new timer" message.
The coach starts a new timer session from the timers list page.
For the current use case (single gym, single timer at a time) this is acceptable.
A persistent session store (Redis or DB-backed) is a future enhancement if needed.
---
## One Active Session Per Org
Only one timer session can be running per organization at a time.
`launchTimer()` checks for an existing active session before creating a new one.
If one exists: `AppError('CONFLICT', 'A timer is already running. Stop it before launching another.', 409)`.
The active session for an org is determined by scanning the in-memory Map for entries matching `orgId`.