forked from syntaxbullet/AuroraBot-discord
50 lines
2.7 KiB
Markdown
50 lines
2.7 KiB
Markdown
# DASH-002: Real-time Live Updates via WebSockets
|
|
|
|
**Status:** Done
|
|
**Created:** 2026-01-08
|
|
**Tags:** dashboard, websocket, real-time, performance
|
|
|
|
## 1. Context & User Story
|
|
* **As a:** Bot Administrator
|
|
* **I want to:** See metrics and events update instantly on my screen without refreshing or waiting for polling intervals.
|
|
* **So that:** I can react immediately to errors or spikes in latency and have a dashboard that feels "alive."
|
|
|
|
## 2. Technical Requirements
|
|
### Data Model Changes
|
|
- [x] No database schema changes required.
|
|
- [x] Created `shared/lib/events.ts` for a global system event bus.
|
|
|
|
### API / Interface
|
|
- [x] Establish a WebSocket endpoint at `/ws`.
|
|
- [x] Define the message protocol:
|
|
- `STATS_UPDATE`: Server to client containing full `DashboardStats`.
|
|
- `NEW_EVENT`: Server to client when a specific event is recorded.
|
|
|
|
## 3. Constraints & Validations (CRITICAL)
|
|
- **Input Validation:** WS messages validated using JSON parsing and type checks.
|
|
- **System Constraints:**
|
|
- WebSocket broadcast interval set to 5s for metrics.
|
|
- Automatic reconnection logic handled in the frontend hook.
|
|
- **Business Logic Guardrails:**
|
|
- Events are pushed immediately as they occur via the system event bus.
|
|
|
|
## 4. Acceptance Criteria
|
|
1. [x] **Given** the dashboard is open, **When** a command is run in Discord (e.g. Daily), **Then** the "Recent Events" list updates instantly on the web UI.
|
|
2. [x] **Given** a changing network environment, **When** the bot's ping fluctuates, **Then** the "Avg Latency" card updates in real-time.
|
|
3. [x] **Given** a connection loss, **When** the network returns, **Then** the client automatically reconnects to the WS room.
|
|
|
|
## 5. Implementation Plan
|
|
- [x] Step 1: Integrate a WebSocket library into `web/src/server.ts` using Bun's native `websocket` support.
|
|
- [x] Step 2: Implement a broadcast system in `dashboard.service.ts` to push events to the WS handler using `systemEvents`.
|
|
- [x] Step 3: Create/Update `useDashboardStats` hook in the frontend to handle connection lifecycle and state merging.
|
|
- [x] Step 4: Refactor `Dashboard.tsx` state consumption to benefit from real-time updates.
|
|
|
|
## Implementation Notes
|
|
### Files Changed
|
|
- `shared/lib/events.ts`: New event bus for the system.
|
|
- `web/src/server.ts`: Added WebSocket handler and stats broadcast.
|
|
- `web/src/hooks/use-dashboard-stats.ts`: Replaced polling with WebSocket + HTTP initial load.
|
|
- `shared/modules/dashboard/dashboard.service.ts`: Added `recordEvent` helper to emit WS events.
|
|
- `shared/modules/economy/economy.service.ts`: Integrated `recordEvent` into daily claims and transfers.
|
|
- `shared/modules/dashboard/dashboard.service.test.ts`: Added unit tests for event emission.
|