Nyk commited on
Commit
8bdb2e3
·
1 Parent(s): 84e47a3

fix: resolve reconnect storm and improve Ubuntu deployment

Browse files

Fix WebSocket reconnect storm (issue #53) caused by stale closure
reading connection.reconnectAttempts from Zustand state. Use a ref
to track attempts, avoiding the closure capture problem entirely.

Improve Dockerfile: create .data directory with correct ownership for
SQLite, set PORT/HOSTNAME env vars explicitly.

Add deployment guide documenting Ubuntu prerequisites (python3, make,
g++ for better-sqlite3 native compilation) and platform-specific
build constraints.

Files changed (3) hide show
  1. Dockerfile +4 -0
  2. docs/deployment.md +113 -0
  3. src/lib/websocket.ts +10 -6
Dockerfile CHANGED
@@ -21,6 +21,10 @@ COPY --from=build /app/.next/standalone ./
21
  COPY --from=build /app/.next/static ./.next/static
22
  # Copy public directory if it exists (may not exist in all setups)
23
  COPY --from=build /app/public* ./public/
 
 
24
  USER nextjs
25
  EXPOSE 3000
 
 
26
  CMD ["node", "server.js"]
 
21
  COPY --from=build /app/.next/static ./.next/static
22
  # Copy public directory if it exists (may not exist in all setups)
23
  COPY --from=build /app/public* ./public/
24
+ # Create data directory with correct ownership for SQLite
25
+ RUN mkdir -p .data && chown nextjs:nodejs .data
26
  USER nextjs
27
  EXPOSE 3000
28
+ ENV PORT=3000
29
+ ENV HOSTNAME=0.0.0.0
30
  CMD ["node", "server.js"]
docs/deployment.md ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Deployment Guide
2
+
3
+ ## Prerequisites
4
+
5
+ - **Node.js** >= 20 (LTS recommended)
6
+ - **pnpm** (installed via corepack: `corepack enable && corepack prepare pnpm@latest --activate`)
7
+
8
+ ### Ubuntu / Debian
9
+
10
+ `better-sqlite3` requires native compilation tools:
11
+
12
+ ```bash
13
+ sudo apt-get update
14
+ sudo apt-get install -y python3 make g++
15
+ ```
16
+
17
+ ### macOS
18
+
19
+ Xcode command line tools are required:
20
+
21
+ ```bash
22
+ xcode-select --install
23
+ ```
24
+
25
+ ## Quick Start (Development)
26
+
27
+ ```bash
28
+ cp .env.example .env.local
29
+ pnpm install
30
+ pnpm dev
31
+ ```
32
+
33
+ Open http://localhost:3000. Login with `AUTH_USER` / `AUTH_PASS` from your `.env.local`.
34
+
35
+ ## Production (Direct)
36
+
37
+ ```bash
38
+ pnpm install --frozen-lockfile
39
+ pnpm build
40
+ pnpm start
41
+ ```
42
+
43
+ The `pnpm start` script binds to `0.0.0.0:3005`. Override with:
44
+
45
+ ```bash
46
+ PORT=3000 pnpm start
47
+ ```
48
+
49
+ **Important:** The production build bundles platform-specific native binaries. You must run `pnpm install` and `pnpm build` on the same OS and architecture as the target server. A build created on macOS will not work on Linux.
50
+
51
+ ## Production (Docker)
52
+
53
+ ```bash
54
+ docker build -t mission-control .
55
+ docker run -p 3000:3000 \
56
+ -v mission-control-data:/app/.data \
57
+ -e AUTH_USER=admin \
58
+ -e AUTH_PASS=your-secure-password \
59
+ -e API_KEY=your-api-key \
60
+ mission-control
61
+ ```
62
+
63
+ The Docker image:
64
+ - Builds from `node:20-slim` with multi-stage build
65
+ - Compiles `better-sqlite3` natively inside the container (Linux x64)
66
+ - Uses Next.js standalone output for minimal image size
67
+ - Runs as non-root user `nextjs`
68
+ - Exposes port 3000 (override with `-e PORT=8080`)
69
+
70
+ ### Persistent Data
71
+
72
+ SQLite database is stored in `/app/.data/` inside the container. Mount a volume to persist data across restarts:
73
+
74
+ ```bash
75
+ docker run -v /path/to/data:/app/.data ...
76
+ ```
77
+
78
+ ## Environment Variables
79
+
80
+ See `.env.example` for the full list. Key variables:
81
+
82
+ | Variable | Required | Default | Description |
83
+ |----------|----------|---------|-------------|
84
+ | `AUTH_USER` | Yes | `admin` | Admin username (seeded on first run) |
85
+ | `AUTH_PASS` | Yes | - | Admin password |
86
+ | `API_KEY` | Yes | - | API key for headless access |
87
+ | `PORT` | No | `3005` (direct) / `3000` (Docker) | Server port |
88
+ | `OPENCLAW_HOME` | No | - | Path to OpenClaw installation |
89
+ | `MC_ALLOWED_HOSTS` | No | `localhost,127.0.0.1` | Allowed hosts in production |
90
+
91
+ ## Troubleshooting
92
+
93
+ ### "Module not found: better-sqlite3"
94
+
95
+ Native compilation failed. On Ubuntu/Debian:
96
+ ```bash
97
+ sudo apt-get install -y python3 make g++
98
+ rm -rf node_modules
99
+ pnpm install
100
+ ```
101
+
102
+ ### "Invalid ELF header" or "Mach-O" errors
103
+
104
+ The native binary was compiled on a different platform. Rebuild:
105
+ ```bash
106
+ rm -rf node_modules .next
107
+ pnpm install
108
+ pnpm build
109
+ ```
110
+
111
+ ### Database locked errors
112
+
113
+ Ensure only one instance is running against the same `.data/` directory. SQLite uses WAL mode but does not support multiple writers.
src/lib/websocket.ts CHANGED
@@ -38,6 +38,7 @@ export function useWebSocket() {
38
  const authTokenRef = useRef<string>('')
39
  const requestIdRef = useRef<number>(0)
40
  const handshakeCompleteRef = useRef<boolean>(false)
 
41
 
42
  // Heartbeat tracking
43
  const pingCounterRef = useRef<number>(0)
@@ -249,6 +250,7 @@ export function useWebSocket() {
249
  if (frame.type === 'res' && frame.ok && !handshakeCompleteRef.current) {
250
  console.log('Handshake complete!')
251
  handshakeCompleteRef.current = true
 
252
  setConnection({
253
  isConnected: true,
254
  lastConnected: new Date(),
@@ -410,13 +412,15 @@ export function useWebSocket() {
410
  handshakeCompleteRef.current = false
411
  stopHeartbeat()
412
 
413
- // Auto-reconnect logic with exponential backoff
414
- if (connection.reconnectAttempts < maxReconnectAttempts) {
415
- const timeout = Math.min(Math.pow(2, connection.reconnectAttempts) * 1000, 30000)
416
- console.log(`Reconnecting in ${timeout}ms... (attempt ${connection.reconnectAttempts + 1}/${maxReconnectAttempts})`)
 
417
 
 
 
418
  reconnectTimeoutRef.current = setTimeout(() => {
419
- setConnection({ reconnectAttempts: connection.reconnectAttempts + 1 })
420
  connect(url, authTokenRef.current)
421
  }, timeout)
422
  } else {
@@ -446,7 +450,7 @@ export function useWebSocket() {
446
  console.error('Failed to connect to WebSocket:', error)
447
  setConnection({ isConnected: false })
448
  }
449
- }, [connection.reconnectAttempts, setConnection, handleGatewayFrame, addLog, stopHeartbeat])
450
 
451
  const disconnect = useCallback(() => {
452
  if (reconnectTimeoutRef.current) {
 
38
  const authTokenRef = useRef<string>('')
39
  const requestIdRef = useRef<number>(0)
40
  const handshakeCompleteRef = useRef<boolean>(false)
41
+ const reconnectAttemptsRef = useRef<number>(0)
42
 
43
  // Heartbeat tracking
44
  const pingCounterRef = useRef<number>(0)
 
250
  if (frame.type === 'res' && frame.ok && !handshakeCompleteRef.current) {
251
  console.log('Handshake complete!')
252
  handshakeCompleteRef.current = true
253
+ reconnectAttemptsRef.current = 0
254
  setConnection({
255
  isConnected: true,
256
  lastConnected: new Date(),
 
412
  handshakeCompleteRef.current = false
413
  stopHeartbeat()
414
 
415
+ // Auto-reconnect logic with exponential backoff (uses ref to avoid stale closure)
416
+ const attempts = reconnectAttemptsRef.current
417
+ if (attempts < maxReconnectAttempts) {
418
+ const timeout = Math.min(Math.pow(2, attempts) * 1000, 30000)
419
+ console.log(`Reconnecting in ${timeout}ms... (attempt ${attempts + 1}/${maxReconnectAttempts})`)
420
 
421
+ reconnectAttemptsRef.current = attempts + 1
422
+ setConnection({ reconnectAttempts: attempts + 1 })
423
  reconnectTimeoutRef.current = setTimeout(() => {
 
424
  connect(url, authTokenRef.current)
425
  }, timeout)
426
  } else {
 
450
  console.error('Failed to connect to WebSocket:', error)
451
  setConnection({ isConnected: false })
452
  }
453
+ }, [setConnection, handleGatewayFrame, addLog, stopHeartbeat])
454
 
455
  const disconnect = useCallback(() => {
456
  if (reconnectTimeoutRef.current) {