53 lines
1.6 KiB
Markdown
53 lines
1.6 KiB
Markdown
# WebSocket Chat - Technical Design
|
|
|
|
## Architecture
|
|
|
|
Leverages the existing `pkg/realtime` package which provides:
|
|
- `LocalHub`: In-memory connection registry with room support
|
|
- `WSClient`: WebSocket connection with heartbeat (ping/pong)
|
|
- `Handler`: HTTP upgrade and connection lifecycle management
|
|
- `RedisBroadcaster`: Cross-pod message distribution via Redis Pub/Sub
|
|
|
|
### Message Flow
|
|
|
|
```
|
|
Client → WebSocket → WSClient.readPump → Handler.OnMessage callback
|
|
→ RedisBroadcaster.Publish → Redis Pub/Sub channel
|
|
→ RedisBroadcaster.Run (subscriber) → LocalHub.Broadcast
|
|
→ WSClient.writePump → All connected WebSocket clients
|
|
```
|
|
|
|
## Changes Required
|
|
|
|
### 1. Configuration (`internal/config/config.go`)
|
|
|
|
Add `RedisURL` field to Config struct, loaded from `REDIS_URL` environment variable.
|
|
|
|
### 2. Main Entry Point (`cmd/server/main.go`)
|
|
|
|
- Create Redis client from `REDIS_URL`
|
|
- Create `LocalHub` and start its event loop
|
|
- Create `RedisBroadcaster` and start its subscriber loop
|
|
- Pass hub and broadcaster to `RegisterRoutes`
|
|
- Register shutdown hooks for hub cancellation and Redis client cleanup
|
|
|
|
### 3. Route Registration (`internal/api/routes.go`)
|
|
|
|
- Accept `realtime.Handler` as a parameter
|
|
- Mount WebSocket handler routes at `/api/chat-api/ws`
|
|
|
|
### 4. OpenAPI Spec (`internal/api/spec.go`)
|
|
|
|
- Add WebSocket tag and endpoint documentation
|
|
|
|
### 5. Tests
|
|
|
|
- Unit test for WebSocket handler wiring
|
|
- Integration test for WebSocket connection upgrade and message echo
|
|
|
|
## Dependencies
|
|
|
|
- `pkg/realtime` (already exists, no changes needed)
|
|
- `github.com/redis/go-redis/v9` (already in pkg/go.mod)
|
|
- `github.com/gorilla/websocket` (already in pkg/go.mod)
|