Files
Schedule/server/internal/api/ws.go
T
Misaki 5be7f7f04b feat: implement AI schedule app with multi-device sync
- Qt 6 desktop client with day/month/year views, AI scheduling, and TOML settings\n- Go sync server with SQLite change stream, WebSocket notifications, and Docker deployment\n- Client outbox/LWW sync, offline retry, and dual-client integration tests\n- Linux fcitx5 setup, validation reports, and Windows MinGW preset
2026-10-26 13:58:45 +08:00

134 lines
2.9 KiB
Go

package api
import (
"log/slog"
"net/http"
"sync"
"time"
"github.com/gorilla/websocket"
)
const (
writeWait = 10 * time.Second
pongWait = 60 * time.Second
pingPeriod = 30 * time.Second
)
type wsClient struct {
conn *websocket.Conn
send chan []byte
deviceID string
}
type Hub struct {
mu sync.RWMutex
clients map[*wsClient]struct{}
logger *slog.Logger
}
func NewHub(logger *slog.Logger) *Hub {
return &Hub{clients: make(map[*wsClient]struct{}), logger: logger}
}
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
CheckOrigin: func(*http.Request) bool { return true },
}
func (h *Hub) ServeWS(w http.ResponseWriter, r *http.Request, deviceID string) {
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
h.logger.Warn("websocket upgrade failed", "error", err)
return
}
client := &wsClient{
conn: conn,
send: make(chan []byte, 16),
deviceID: deviceID,
}
h.add(client)
client.send <- []byte(`{"type":"ready"}`)
go client.writePump()
client.readPump(h)
}
func (h *Hub) add(client *wsClient) {
h.mu.Lock()
defer h.mu.Unlock()
h.clients[client] = struct{}{}
h.logger.Info("sync client connected", "device_id", client.deviceID)
}
func (h *Hub) remove(client *wsClient) {
h.mu.Lock()
defer h.mu.Unlock()
if _, ok := h.clients[client]; ok {
delete(h.clients, client)
close(client.send)
h.logger.Info("sync client disconnected", "device_id", client.deviceID)
}
}
// Broadcast notifies all connected devices that new changes are available.
// Clients still pull via REST, so a dropped notification is harmless.
func (h *Hub) Broadcast(seq int64, sourceDevice string) {
payload := []byte(`{"type":"changes","seq":` + formatInt(seq) + `}`)
h.mu.RLock()
defer h.mu.RUnlock()
for client := range h.clients {
if client.deviceID == sourceDevice {
continue
}
select {
case client.send <- payload:
default:
h.logger.Warn("sync client notification queue full", "device_id", client.deviceID)
}
}
}
func (c *wsClient) readPump(h *Hub) {
defer func() {
h.remove(c)
c.conn.Close()
}()
c.conn.SetReadLimit(4096)
_ = c.conn.SetReadDeadline(time.Now().Add(pongWait))
c.conn.SetPongHandler(func(string) error {
return c.conn.SetReadDeadline(time.Now().Add(pongWait))
})
for {
if _, _, err := c.conn.ReadMessage(); err != nil {
return
}
}
}
func (c *wsClient) writePump() {
ticker := time.NewTicker(pingPeriod)
defer func() {
ticker.Stop()
c.conn.Close()
}()
for {
select {
case message, ok := <-c.send:
_ = c.conn.SetWriteDeadline(time.Now().Add(writeWait))
if !ok {
_ = c.conn.WriteMessage(websocket.CloseMessage, []byte{})
return
}
if err := c.conn.WriteMessage(websocket.TextMessage, message); err != nil {
return
}
case <-ticker.C:
_ = c.conn.SetWriteDeadline(time.Now().Add(writeWait))
if err := c.conn.WriteMessage(websocket.PingMessage, nil); err != nil {
return
}
}
}
}