xonecas.io
8058
Ir

irvc / commit 4937fd2

fix: presence issues accross the stack

Add a docker file to run with docker or Podman on local for
dev/debugging

xonecas2026-10-14 4937fd269b4164f31c6ac3783dd7099e214838d5 parent eb359d8

12 files changed

.dockerignore+8−0
@@ -0,0 +1,8 @@
1+.git
2+irvc
3+*.db
4+*.db-shm
5+*.db-wal
6+media
7+web/node_modules
8+web/dist
AGENTS.md+8−0
@@ -13,3 +13,11 @@ This is ours.
1313 - `README.md` — build, configuration, invites, run.
1414 - `irvc.md` — design.
1515 - `DEPLOY.md` — runbook for the VPS deployment.
16+- `deploy/dev/README.md` — local dev stack (Podman).
17+
18+## Dev
19+
20+`deploy/dev/` runs the whole thing locally in containers: `podman-compose up
21+-d --build`, then <http://localhost:8080>. The container serves the built
22+frontend; run `npm run dev` in `web/` for HMR. Details in
23+`deploy/dev/README.md`. The bare-metal path in `DEPLOY.md` is unaffected.
README.md+14−1
@@ -13,9 +13,22 @@ Three processes on one host:
1313 media uploads, SQLite.
1414 - **Caddy** — TLS + reverse proxy for the frontend, API, and LiveKit signal.
1515
16+## Local dev (Podman)
17+
18+An alternate, disposable dev path that does not touch the bare-metal setup:
19+`deploy/dev/` builds irvc + the frontend into one image and runs it with
20+LiveKit under Podman.
21+
22+ cd deploy/dev
23+ podman-compose up -d --build
24+
25+Serves <http://localhost:8080>. The container serves the built frontend; run
26+`cd web && npm run dev` for HMR (Vite proxies `/api` to `:8080`). See
27+`deploy/dev/README.md` for invites, state, and reset.
28+
1629 ## System dependencies
1730
18-Bare Linux, no Docker. On Arch:
31+The deployment path below is bare Linux, no Docker. On Arch:
1932
2033 sudo pacman -S go nodejs npm caddy
2134
deploy/dev/Containerfile+28−0
@@ -0,0 +1,28 @@
1+# syntax=docker/dockerfile:1
2+# Dev image: builds irvc and the frontend, serves both from one process.
3+
4+FROM docker.io/library/golang:1.27-alpine AS server
5+WORKDIR /src
6+COPY go.mod go.sum ./
7+RUN go mod download
8+COPY *.go ./
9+RUN CGO_ENABLED=0 go build -trimpath -o /out/irvc .
10+
11+FROM docker.io/library/node:26-alpine AS web
12+WORKDIR /src
13+COPY web/package.json web/package-lock.json ./
14+RUN npm ci
15+COPY web/ ./
16+RUN npm run build
17+
18+FROM docker.io/library/alpine:3.21
19+RUN apk add --no-cache ca-certificates && adduser -D -u 1000 irvc
20+WORKDIR /app
21+COPY --from=server /out/irvc /app/irvc
22+COPY --from=web /src/dist /app/web/dist
23+RUN mkdir -p /data && chown irvc /data
24+ENV IRVC_DB_PATH=/data/irvc.db \
25+ IRVC_MEDIA_DIR=/data/media
26+USER irvc
27+EXPOSE 8080
28+ENTRYPOINT ["/app/irvc"]
deploy/dev/README.md+37−0
@@ -0,0 +1,37 @@
1+# IRVC dev stack (Podman)
2+
3+Local dev instance. Two containers, host networking, no TLS:
4+
5+- `irvc` — built from `Containerfile` (Go server + built frontend), `:8080`.
6+- `livekit-server` — `:7880`, media `7881/tcp`, `7882/udp`.
7+
8+Host networking is used so LiveKit can advertise reachable ICE ports.
9+
10+## Run
11+
12+ cd deploy/dev
13+ podman-compose up -d --build
14+
15+Open <http://localhost:8080>. Use `localhost`, not a LAN IP: session cookies
16+are `Secure`, and browsers only accept those on `https` or `localhost`.
17+
18+State lives in the `irvc-dev_irvc-data` volume (`/data`: `irvc.db`, `media`).
19+Reset it with `podman-compose down -v`.
20+
21+## Invite
22+
23+The DB starts empty. Create an invite, then open its `/join?token=...` URL:
24+
25+ podman exec irvc-dev_irvc_1 /app/irvc invite
26+
27+## Frontend dev (HMR)
28+
29+The container serves the built frontend. For hot reload, run Vite on the host
30+instead; `vite.config.ts` already proxies `/api` (and the websocket) to `:8080`:
31+
32+ cd web && npm install && npm run dev # http://localhost:5173
33+
34+## Logs and stop
35+
36+ podman-compose logs -f
37+ podman-compose down
deploy/dev/compose.yaml+31−0
@@ -0,0 +1,31 @@
1+name: irvc-dev
2+
3+services:
4+ irvc:
5+ build:
6+ context: ../..
7+ dockerfile: deploy/dev/Containerfile
8+ image: localhost/irvc:dev
9+ network_mode: host
10+ environment:
11+ IRVC_LISTEN_ADDR: ":8080"
12+ IRVC_SESSION_SECRET: ${IRVC_SESSION_SECRET:-dev-session-secret-change-me}
13+ IRVC_LIVEKIT_URL: ${IRVC_LIVEKIT_URL:-ws://localhost:7880}
14+ IRVC_LIVEKIT_API_KEY: irvc
15+ IRVC_LIVEKIT_SECRET: ${IRVC_LIVEKIT_SECRET:-irvc-dev-livekit-secret-000000000000}
16+ volumes:
17+ - irvc-data:/data
18+ depends_on:
19+ - livekit
20+ restart: unless-stopped
21+
22+ livekit:
23+ image: docker.io/livekit/livekit-server:latest
24+ network_mode: host
25+ command: --config /etc/livekit.yaml
26+ volumes:
27+ - ./livekit.yaml:/etc/livekit.yaml:ro
28+ restart: unless-stopped
29+
30+volumes:
31+ irvc-data:
deploy/dev/livekit.yaml+7−0
@@ -0,0 +1,7 @@
1+port: 7880
2+rtc:
3+ tcp_port: 7881
4+ udp_port: 7882
5+ use_external_ip: false
6+keys:
7+ irvc: irvc-dev-livekit-secret-000000000000
irvc.md+0−1
@@ -22,7 +22,6 @@ Small, private chat + voice for 4–6 people on one VPS. No data gathering, full
2222 - Recording, screen share, video, DMs.
2323 - Message editing/deletion/search, channel CRUD.
2424 - Email, OAuth, passkeys.
25-- Docker.
2625 - Backups.
2726 - Password reset via email (admin resets manually).
2827
web/src/lib/presence.ts+121−0
@@ -0,0 +1,121 @@
1+import { useCallback, useEffect, useRef, useState } from "react";
2+import type { WSEvent } from "./types";
3+
4+const PING = 10_000; // heartbeat interval
5+const SILENCE = 20_000; // no reply for this long means the socket is a zombie
6+const CONNECTING = 15_000; // a handshake that never completes is a dead end
7+const MAX_BACKOFF = 15_000;
8+const WAKE_HIDDEN = 5_000; // ignore quick tab switches
9+
10+// usePresence owns the presence socket and keeps it up. The server sends a full
11+// snapshot on every connect, so a reconnect doubles as a resync. `onOpen` fires
12+// after each (re)connect so the caller can replay state the server forgot.
13+export function usePresence(onEvent: (ev: WSEvent) => void, onOpen: () => void) {
14+ const [connected, setConnected] = useState(false);
15+ const socket = useRef<WebSocket | null>(null);
16+ const event = useRef(onEvent);
17+ const opened = useRef(onOpen);
18+ event.current = onEvent;
19+ opened.current = onOpen;
20+
21+ useEffect(() => {
22+ let reconnecting = 0;
23+ let retry = 0;
24+ let pong = 0;
25+ let connecting = 0;
26+ let hidden = Date.now();
27+ let closed = false;
28+
29+ const proto = location.protocol === "https:" ? "wss" : "ws";
30+ const url = `${proto}://${location.host}/api/ws`;
31+
32+ // Jitter keeps every client from retrying in lockstep after a restart.
33+ const schedule = () => {
34+ const wait = Math.min(1000 * 2 ** retry++, MAX_BACKOFF) * (0.5 + Math.random());
35+ reconnecting = window.setTimeout(open, wait);
36+ };
37+
38+ const open = () => {
39+ if (closed) return;
40+ const ws = new WebSocket(url);
41+ socket.current = ws;
42+ pong = connecting = Date.now();
43+ ws.onopen = () => {
44+ retry = 0;
45+ setConnected(true);
46+ opened.current();
47+ };
48+ ws.onmessage = (e) => {
49+ const ev = JSON.parse(e.data as string) as WSEvent;
50+ if (ev.type === "pong") pong = Date.now();
51+ else event.current(ev);
52+ };
53+ // onerror always precedes onclose, so close alone is worth reacting to.
54+ ws.onclose = () => {
55+ if (socket.current !== ws) return; // already dropped or replaced
56+ socket.current = null;
57+ setConnected(false);
58+ if (!closed) schedule();
59+ };
60+ };
61+
62+ // drop abandons a socket instead of closing it. close() runs a closing
63+ // handshake, and a half-open peer never answers one, so the browser sits on
64+ // the dead socket; detaching it loses nothing and reconnects immediately.
65+ const drop = () => {
66+ const ws = socket.current;
67+ if (!ws) return;
68+ socket.current = null;
69+ ws.onopen = ws.onmessage = ws.onerror = ws.onclose = null;
70+ setConnected(false);
71+ ws.close();
72+ if (!closed) schedule();
73+ };
74+
75+ // A sleeping laptop keeps the socket OPEN while nothing flows, so trust
76+ // heartbeats rather than readyState: silence means reconnect.
77+ const beat = window.setInterval(() => {
78+ const ws = socket.current;
79+ if (!ws) return;
80+ if (ws.readyState === WebSocket.CONNECTING) {
81+ if (Date.now() - connecting > CONNECTING) drop();
82+ } else if (ws.readyState === WebSocket.OPEN) {
83+ if (Date.now() - pong > SILENCE) drop();
84+ else ws.send('{"type":"ping"}');
85+ }
86+ }, PING);
87+
88+ const wake = () => {
89+ if (closed) return;
90+ window.clearTimeout(reconnecting);
91+ retry = 0;
92+ if (socket.current) drop();
93+ else open();
94+ };
95+
96+ const onVisibility = () => {
97+ if (document.visibilityState === "hidden") hidden = Date.now();
98+ else if (Date.now() - hidden > WAKE_HIDDEN) wake();
99+ };
100+
101+ open();
102+ document.addEventListener("visibilitychange", onVisibility);
103+ window.addEventListener("online", wake);
104+ return () => {
105+ closed = true;
106+ window.clearTimeout(reconnecting);
107+ window.clearInterval(beat);
108+ document.removeEventListener("visibilitychange", onVisibility);
109+ window.removeEventListener("online", wake);
110+ socket.current?.close();
111+ socket.current = null;
112+ };
113+ }, []);
114+
115+ const send = useCallback((data: string) => {
116+ const ws = socket.current;
117+ if (ws?.readyState === WebSocket.OPEN) ws.send(data);
118+ }, []);
119+
120+ return { connected, send };
121+}
web/src/lib/types.ts+1−1
@@ -26,7 +26,7 @@ export interface Message {
2626 }
2727
2828 export interface WSEvent {
29- type: "message" | "presence";
29+ type: "message" | "presence" | "pong";
3030 message?: Message;
3131 users?: string[];
3232 roster?: UserSummary[];
web/src/views/Chat.tsx+28−27
@@ -2,14 +2,17 @@ import { useEffect, useRef, useState } from "react";
22 import { Hash, Menu, Settings } from "lucide-react";
33 import { Button } from "@/components/ui/button";
44 import { api } from "../lib/api";
5+import { usePresence } from "../lib/presence";
56 import { useSettings } from "../lib/settings";
67 import { useTheme } from "../lib/theme";
78 import { useVoice } from "../lib/voice";
8-import type { Channel, Message, User, UserSummary, WSEvent } from "../lib/types";
9+import type { Channel, Message, User, UserSummary } from "../lib/types";
910 import ChatPane from "../components/ChatPane";
1011 import SettingsPanel from "../components/SettingsPanel";
1112 import Sidebar from "../components/Sidebar";
1213
14+const voiceMessage = (channelId: number) => JSON.stringify({ type: "voice", channelId });
15+
1316 export default function Chat({ user, onLogout }: { user: User; onLogout: () => void }) {
1417 const [channels, setChannels] = useState<Channel[]>([]);
1518 const [selected, setSelected] = useState<Channel | null>(null);
@@ -20,15 +23,28 @@ export default function Chat({ user, onLogout }: { user: User; onLogout: () => v
2023 const desktop = useRef(window.matchMedia("(min-width: 768px)").matches);
2124 const [sidebarOpen, setSidebarOpen] = useState(desktop.current);
2225 const selectedId = useRef<number | null>(null);
23- const wsRef = useRef<WebSocket | null>(null);
26+ const [voiceRooms, setVoiceRooms] = useState<Record<string, string[]>>({});
27+ const voiceChannel = useRef(0);
2428 const { settings, update } = useSettings();
29+ // Presence arrives as a snapshot on every connect, so a reconnect resyncs the
30+ // roster and voice occupancy. Replay our own voice channel on connect, since
31+ // the server drops occupancy when the socket dies.
32+ const { connected, send } = usePresence(
33+ (ev) => {
34+ if (ev.type === "presence") {
35+ setOnline(new Set(ev.users ?? []));
36+ if (ev.roster) setUsers(ev.roster);
37+ setVoiceRooms(ev.voice ?? {});
38+ } else if (ev.message && ev.message.channelId === selectedId.current) {
39+ setMessages((prev) => [...prev, ev.message!]);
40+ }
41+ },
42+ () => send(voiceMessage(voiceChannel.current)),
43+ );
2544 const voice = useVoice(settings, (channelId) => {
26- const ws = wsRef.current;
27- if (ws?.readyState === WebSocket.OPEN) {
28- ws.send(JSON.stringify({ type: "voice", channelId: channelId ?? 0 }));
29- }
45+ voiceChannel.current = channelId ?? 0;
46+ send(voiceMessage(voiceChannel.current));
3047 });
31- const [voiceRooms, setVoiceRooms] = useState<Record<string, string[]>>({});
3248 const { mode, toggleMode, theme, setTheme } = useTheme();
3349
3450 useEffect(() => {
@@ -52,26 +68,6 @@ export default function Chat({ user, onLogout }: { user: User; onLogout: () => v
5268 .catch(() => {});
5369 }, []);
5470
55- useEffect(() => {
56- const proto = window.location.protocol === "https:" ? "wss" : "ws";
57- const ws = new WebSocket(`${proto}://${window.location.host}/api/ws`);
58- wsRef.current = ws;
59- ws.onmessage = (e) => {
60- const ev = JSON.parse(e.data as string) as WSEvent;
61- if (ev.type === "presence") {
62- setOnline(new Set(ev.users ?? []));
63- if (ev.roster) setUsers(ev.roster);
64- setVoiceRooms(ev.voice ?? {});
65- } else if (ev.message && ev.message.channelId === selectedId.current) {
66- setMessages((prev) => [...prev, ev.message!]);
67- }
68- };
69- return () => {
70- wsRef.current = null;
71- ws.close();
72- };
73- }, []);
74-
7571 useEffect(() => {
7672 if (selected?.type !== "text") {
7773 setMessages([]);
@@ -146,6 +142,11 @@ export default function Chat({ user, onLogout }: { user: User; onLogout: () => v
146142 </>
147143 )}
148144 </span>
145+ {!connected && (
146+ // Presence is stale until the socket is back, so say so instead of
147+ // showing a silently wrong roster.
148+ <span className="ml-auto text-xs text-sepia/50">reconnecting…</span>
149+ )}
149150 </header>
150151 {settingsOpen ? (
151152 <SettingsPanel
ws.go+43−24
@@ -41,12 +41,12 @@ type client struct {
4141 type hub struct {
4242 mu sync.Mutex
4343 clients map[int64]map[*client]bool
44- voice map[int64]map[int64]string
44+ voice map[int64]map[*client]bool
4545 db *sql.DB
4646 }
4747
4848 func newHub(db *sql.DB) *hub {
49- return &hub{clients: map[int64]map[*client]bool{}, voice: map[int64]map[int64]string{}, db: db}
49+ return &hub{clients: map[int64]map[*client]bool{}, voice: map[int64]map[*client]bool{}, db: db}
5050 }
5151
5252 func (h *hub) register(c *client) {
@@ -79,7 +79,7 @@ func (h *hub) clearVoiceLocked(c *client) {
7979 return
8080 }
8181 if set := h.voice[c.voiceID]; set != nil {
82- delete(set, c.userID)
82+ delete(set, c)
8383 if len(set) == 0 {
8484 delete(h.voice, c.voiceID)
8585 }
@@ -88,15 +88,17 @@ func (h *hub) clearVoiceLocked(c *client) {
8888 }
8989
9090 // setVoice moves a client into a voice channel (0 for none) and rebroadcasts.
91+// Occupancy is keyed by connection, not user, so one tab leaving a channel
92+// does not evict another tab that is still in it.
9193 func (h *hub) setVoice(c *client, channelID int64) {
9294 h.mu.Lock()
9395 h.clearVoiceLocked(c)
9496 c.voiceID = channelID
9597 if channelID != 0 {
9698 if h.voice[channelID] == nil {
97- h.voice[channelID] = map[int64]string{}
99+ h.voice[channelID] = map[*client]bool{}
98100 }
99- h.voice[channelID][c.userID] = c.username
101+ h.voice[channelID][c] = true
100102 }
101103 h.mu.Unlock()
102104 h.broadcastPresence()
@@ -158,9 +160,13 @@ func (h *hub) voiceUsers() map[string][]string {
158160 defer h.mu.Unlock()
159161 out := map[string][]string{}
160162 for channelID, set := range h.voice {
163+ seen := map[string]bool{}
161164 names := make([]string, 0, len(set))
162- for _, name := range set {
163- names = append(names, name)
165+ for c := range set {
166+ if !seen[c.username] {
167+ seen[c.username] = true
168+ names = append(names, c.username)
169+ }
164170 }
165171 sort.Strings(names)
166172 out[strconv.FormatInt(channelID, 10)] = names
@@ -177,28 +183,32 @@ func (h *hub) broadcastPresence() {
177183 })
178184 }
179185
186+// checkOrigin allows same-host origins. It lives on the (shared) upgrader, so
187+// it must not be reassigned per request: concurrent upgrades would race.
188+func checkOrigin(r *http.Request) bool {
189+ origin := r.Header.Get("Origin")
190+ if origin == "" {
191+ return true
192+ }
193+ u, err := url.Parse(origin)
194+ if err != nil {
195+ return false
196+ }
197+ host := r.Host
198+ if h, _, err := net.SplitHostPort(host); err == nil {
199+ host = h
200+ }
201+ return u.Hostname() == host
202+}
203+
180204 var upgrader = websocket.Upgrader{
181205 ReadBufferSize: 1024,
182206 WriteBufferSize: 1024,
207+ CheckOrigin: checkOrigin,
183208 }
184209
185210 func (s *Server) handleWS(c *gin.Context) {
186211 user := c.MustGet("user").(User)
187- upgrader.CheckOrigin = func(r *http.Request) bool {
188- origin := r.Header.Get("Origin")
189- if origin == "" {
190- return true
191- }
192- u, err := url.Parse(origin)
193- if err != nil {
194- return false
195- }
196- host := r.Host
197- if h, _, err := net.SplitHostPort(host); err == nil {
198- host = h
199- }
200- return u.Hostname() == host
201- }
202212 conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
203213 if err != nil {
204214 return
@@ -211,7 +221,7 @@ func (s *Server) handleWS(c *gin.Context) {
211221
212222 const (
213223 writeWait = 10 * time.Second
214- pongWait = 60 * time.Second
224+ pongWait = 30 * time.Second
215225 pingPeriod = (pongWait * 9) / 10
216226 )
217227
@@ -235,8 +245,17 @@ func (c *client) readPump() {
235245 if json.Unmarshal(msg, &in) != nil {
236246 continue
237247 }
238- if in.Type == "voice" {
248+ switch in.Type {
249+ case "voice":
239250 c.hub.setVoice(c, in.ChannelID)
251+ case "ping":
252+ // Application-level heartbeat: the browser answers protocol pings
253+ // itself, so a client cannot see them. This lets it detect a
254+ // half-open socket (sleep, dead network) instead of trusting it.
255+ select {
256+ case c.send <- []byte(`{"type":"pong"}`):
257+ default:
258+ }
240259 }
241260 }
242261 }