mirror of
https://github.com/MeshCore-Beacon/beacon-server.git
synced 2026-12-06 15:34:26 +00:00
iOS WebKit drops the socket on the first permessage-deflate message, so every iPhone and iPad browser reconnected about every 0.1 s since 2.1.0. Compress only for Chromium, Firefox and the app.
358 lines
13 KiB
Go
358 lines
13 KiB
Go
// Copyright 2026 Beacon Contributors
|
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
|
|
// Package ws handles the WebSocket endpoint at GET /ws.
|
|
//
|
|
// Protocol (from design doc):
|
|
//
|
|
// On connect: server sends hello { v:1, type:"hello", serverTime:<ms>, connectionId:"uuid" }
|
|
//
|
|
// Client → Server:
|
|
// subscribe { v, type, id, scope } → server replies subscribed { v, type, id, subscriptionId }
|
|
// unsubscribe { v, type, id, subscriptionId } → server replies unsubscribed { v, type, id, subscriptionId }
|
|
// configure { v, type, id, resolvePath, includeObserverKey, includeRepeats }
|
|
// → server replies configured { v, type, id, resolvePath, includeObserverKey, includeRepeats }
|
|
// ping { v, type, id } → server replies pong { v, type, id }
|
|
//
|
|
// configure's flags are connection-wide settings, not per-subscription.
|
|
// resolvePath adds per-hop resolvedPath data to packetObservation events,
|
|
// includeObserverKey adds observation.observerPublicKey, and includeRepeats
|
|
// also streams later hearings of an already-stored observation over a new
|
|
// path, as packetObservation events with packet.isRepeat true and
|
|
// observationCount 0. Each configure sets all three to exactly the values
|
|
// sent, so an omitted flag turns off. All default false.
|
|
//
|
|
// Server → Client events (unsolicited):
|
|
// packetObservation, observerStatus, nodeUpdate, channelMessage
|
|
// lagged { v, type, droppedCount, since }
|
|
//
|
|
// lagged also reports events dropped by the per-connection send budget,
|
|
// at most once per budgetNoticeInterval.
|
|
//
|
|
// With websocket.require_origin on, an upgrade without an Origin needs a ticket from
|
|
// GET /api/v1/ws-ticket in the X-Beacon-Ticket header, or it gets 403.
|
|
//
|
|
// Idle connections (no ping) closed after 90s.
|
|
// Client should ping every 30s.
|
|
package ws
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"fmt"
|
|
"log/slog"
|
|
"net"
|
|
"net/http"
|
|
"strconv"
|
|
"time"
|
|
|
|
"github.com/coder/websocket"
|
|
"github.com/go-chi/httprate"
|
|
"github.com/google/uuid"
|
|
|
|
"github.com/MeshCore-Beacon/beacon-server/internal/api"
|
|
"github.com/MeshCore-Beacon/beacon-server/internal/hub"
|
|
"github.com/MeshCore-Beacon/beacon-server/internal/wsticket"
|
|
)
|
|
|
|
const (
|
|
pingTimeout = 90 * time.Second // server closes connection if no message received within this window
|
|
writeTimeout = 10 * time.Second // TODO: apply per-write deadline once nhooyr supports it cleanly
|
|
)
|
|
|
|
// budgetNoticeInterval spaces out send-budget lagged notices, since each one makes the client refetch.
|
|
var budgetNoticeInterval = 30 * time.Second
|
|
|
|
// Limits bounds what one address and one connection may use. A zero send rate means no send budget.
|
|
type Limits struct {
|
|
MaxConnsPerIP int
|
|
MaxConnectsPerMinute int
|
|
SendBytesPerSecond int
|
|
SendBurstBytes int
|
|
}
|
|
|
|
// Access decides who may open /ws. A browser always sends an Origin; RequireOrigin makes every
|
|
// other client show a ticket instead.
|
|
type Access struct {
|
|
AllowedOrigins []string
|
|
RequireOrigin bool
|
|
Tickets *wsticket.Issuer
|
|
}
|
|
|
|
// Handler returns an http.HandlerFunc that requires the hub to be injected.
|
|
// Wire it via router.New(h) so the hub is available at startup.
|
|
func Handler(h *hub.Hub, reader api.Reader, limits Limits, access Access) http.HandlerFunc {
|
|
acceptOpts := &websocket.AcceptOptions{
|
|
OriginPatterns: access.AllowedOrigins,
|
|
// The live feed is repetitive JSON; a shared window cuts its bytes ~3x for ~1.2 MB per socket.
|
|
CompressionMode: websocket.CompressionContextTakeover,
|
|
}
|
|
plainOpts := &websocket.AcceptOptions{OriginPatterns: access.AllowedOrigins, CompressionMode: websocket.CompressionDisabled}
|
|
limiter := newIPLimiter(limits.MaxConnsPerIP)
|
|
attempts := httprate.NewRateLimiter(limits.MaxConnectsPerMinute, time.Minute,
|
|
httprate.WithResponseHeaders(httprate.ResponseHeaders{RetryAfter: "Retry-After"}))
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
ip := r.RemoteAddr
|
|
if host, _, err := net.SplitHostPort(ip); err == nil {
|
|
ip = host
|
|
}
|
|
// Count attempts before Accept, including failed handshakes. RemoteAddr
|
|
// was already resolved by TrustedProxyIP; never read forwarding headers here.
|
|
// Both limits share an IPv6 /64, so rotating addresses inside one doesn't add sockets.
|
|
key := wsticket.ClientKey(r)
|
|
if attempts.RespondOnLimit(w, r, key) {
|
|
return
|
|
}
|
|
if access.RequireOrigin && r.Header.Get("Origin") == "" && !access.Tickets.Valid(r.Header.Get(wsticket.Header), key) {
|
|
http.Error(w, "an Origin or a ticket is required", http.StatusForbidden)
|
|
return
|
|
}
|
|
opts := plainOpts
|
|
if compressesFor(r.UserAgent()) {
|
|
opts = acceptOpts
|
|
}
|
|
conn, err := websocket.Accept(w, r, opts)
|
|
if err != nil {
|
|
slog.Warn("ws: failed to accept connection", "component", "ws", "error", err)
|
|
return
|
|
}
|
|
defer conn.CloseNow()
|
|
if !limiter.acquire(key) {
|
|
// This attempt passed the rate budget. Give the accepted socket a
|
|
// browser-visible backoff signal before allocating a hub client.
|
|
slog.Warn("ws: connection limit reached", "component", "ws", "client_ip", ip)
|
|
_ = conn.Close(websocket.StatusTryAgainLater, "connection limit reached")
|
|
return
|
|
}
|
|
defer limiter.release(key)
|
|
|
|
connID := uuid.NewString()
|
|
client := h.NewClient()
|
|
defer h.Remove(client)
|
|
|
|
ctx, cancel := context.WithCancel(r.Context())
|
|
defer cancel()
|
|
|
|
// Send hello
|
|
hello := map[string]any{
|
|
"v": 1,
|
|
"type": "hello",
|
|
"serverTime": time.Now().UnixMilli(),
|
|
"connectionId": connID,
|
|
}
|
|
helloBytes, _ := json.Marshal(hello)
|
|
slog.Debug("connected", "component", "ws", "connection_id", connID)
|
|
err = conn.Write(ctx, websocket.MessageText, helloBytes)
|
|
if err != nil {
|
|
slog.Warn(fmt.Sprintf("ws[%s]: failed to send hello", connID), "component", "ws", "error", err)
|
|
return
|
|
}
|
|
|
|
// Write pump: forward hub events to the WS connection.
|
|
go func() {
|
|
budget := newSendBudget(limits.SendBytesPerSecond, limits.SendBurstBytes, time.Now())
|
|
budgetDropped := 0
|
|
var lastNotice time.Time
|
|
var noticeDue <-chan time.Time
|
|
writeLagged := func(dropped int) error {
|
|
lagged := map[string]any{
|
|
"v": 1,
|
|
"type": "lagged",
|
|
"droppedCount": dropped,
|
|
"since": time.Now().UnixMilli(),
|
|
}
|
|
lagBytes, _ := json.Marshal(lagged)
|
|
return conn.Write(ctx, websocket.MessageText, lagBytes)
|
|
}
|
|
for {
|
|
select {
|
|
case evt, ok := <-client.Send:
|
|
if !ok {
|
|
return
|
|
}
|
|
msg := map[string]any{
|
|
"v": 1,
|
|
"type": "event",
|
|
"event": evt.Type,
|
|
"data": json.RawMessage(evt.Payload),
|
|
}
|
|
msgBytes, _ := json.Marshal(msg)
|
|
if !budget.allow(len(msgBytes), time.Now()) {
|
|
budgetDropped++
|
|
if noticeDue == nil {
|
|
noticeDue = time.After(time.Until(lastNotice.Add(budgetNoticeInterval)))
|
|
}
|
|
continue
|
|
}
|
|
err = conn.Write(ctx, websocket.MessageText, msgBytes)
|
|
if err != nil {
|
|
slog.Warn(fmt.Sprintf("ws[%s]: failed to write hub event", connID), "component", "ws", "error", err)
|
|
cancel()
|
|
return
|
|
}
|
|
|
|
case <-noticeDue:
|
|
noticeDue = nil
|
|
slog.Warn(fmt.Sprintf("ws[%s]: send budget exceeded, dropped events", connID), "component", "ws", "client_ip", ip, "dropped", budgetDropped)
|
|
if err := writeLagged(budgetDropped); err != nil {
|
|
slog.Warn(fmt.Sprintf("ws[%s]: failed to write lagged notice", connID), "component", "ws", "error", err)
|
|
cancel()
|
|
return
|
|
}
|
|
budgetDropped = 0
|
|
lastNotice = time.Now()
|
|
|
|
case lag, ok := <-client.LaggedCH():
|
|
if !ok {
|
|
return
|
|
}
|
|
if err := writeLagged(lag.DroppedCount); err != nil {
|
|
slog.Warn(fmt.Sprintf("ws[%s]: failed to write lagged notice", connID), "component", "ws", "error", err)
|
|
cancel()
|
|
return
|
|
}
|
|
|
|
case <-ctx.Done():
|
|
return
|
|
}
|
|
}
|
|
}()
|
|
|
|
// Read pump: handle subscribe / unsubscribe / ping from the client.
|
|
// Drives the idle timeout; any message resets the deadline.
|
|
for {
|
|
readCtx, readCancel := context.WithTimeout(ctx, pingTimeout)
|
|
_, msgBytes, err := conn.Read(readCtx)
|
|
readCancel()
|
|
if err != nil {
|
|
slog.Warn(fmt.Sprintf("ws[%s]: read error", connID), "component", "ws", "error", err)
|
|
return
|
|
}
|
|
handleClientMessage(ctx, client, reader, h, conn, connID, msgBytes)
|
|
}
|
|
}
|
|
}
|
|
|
|
// clientMessage is the shape of every client → server message.
|
|
type clientMessage struct {
|
|
V int `json:"v"`
|
|
Type string `json:"type"`
|
|
ID string `json:"id"`
|
|
SubscriptionID string `json:"subscriptionId,omitempty"`
|
|
Scope *subscribeScope `json:"scope,omitempty"`
|
|
|
|
// Only read for "configure" messages. See package doc.
|
|
ResolvePath bool `json:"resolvePath,omitempty"`
|
|
IncludeObserverKey bool `json:"includeObserverKey,omitempty"`
|
|
IncludeRepeats bool `json:"includeRepeats,omitempty"`
|
|
}
|
|
|
|
// subscribeScope mirrors the scope object in the subscribe message.
|
|
type subscribeScope struct {
|
|
IATAs []string `json:"iatas"`
|
|
RegionIDs []string `json:"regionIds"`
|
|
RegionSlugs []string `json:"regionSlugs"`
|
|
PayloadTypes []uint8 `json:"payloadTypes"`
|
|
RouteTypes []uint8 `json:"routeTypes"`
|
|
ChannelHashes []string `json:"channelHashes"`
|
|
ObserverIDs []string `json:"observerIds"`
|
|
Events []hub.EventType `json:"events"`
|
|
}
|
|
|
|
// handleClientMessage dispatches a parsed client message.
|
|
func handleClientMessage(ctx context.Context, client *hub.Client, reader api.Reader, h *hub.Hub, conn *websocket.Conn, connID string, raw []byte) {
|
|
var msg clientMessage
|
|
if err := json.Unmarshal(raw, &msg); err != nil {
|
|
slog.Warn("bad message", "component", "ws", "connection_id", connID, "error", err)
|
|
return
|
|
}
|
|
|
|
switch msg.Type {
|
|
case "subscribe":
|
|
if msg.Scope == nil {
|
|
return
|
|
}
|
|
iatas := msg.Scope.IATAs
|
|
for _, ridStr := range msg.Scope.RegionIDs {
|
|
rid, err := strconv.ParseInt(ridStr, 10, 32)
|
|
if err != nil {
|
|
slog.Warn(fmt.Sprintf("ws[%s]: invalid regionId %q, skipping", connID, ridStr), "component", "ws")
|
|
continue
|
|
}
|
|
region, err := reader.GetRegion(ctx, int32(rid))
|
|
if err != nil {
|
|
slog.Warn(fmt.Sprintf("ws[%s]: region %d not found, skipping", connID, rid), "component", "ws", "error", err)
|
|
continue
|
|
}
|
|
iatas = append(iatas, region.IATAs...)
|
|
}
|
|
for _, slug := range msg.Scope.RegionSlugs {
|
|
region, err := reader.GetRegionBySlug(ctx, slug)
|
|
if err != nil {
|
|
slog.Warn(fmt.Sprintf("ws[%s]: region slug %q not found, skipping", connID, slug), "component", "ws", "error", err)
|
|
continue
|
|
}
|
|
iatas = append(iatas, region.IATAs...)
|
|
}
|
|
scope := hub.Scope{
|
|
IATAs: iatas,
|
|
PayloadTypes: msg.Scope.PayloadTypes,
|
|
RouteTypes: msg.Scope.RouteTypes,
|
|
ChannelHashes: msg.Scope.ChannelHashes,
|
|
ObserverIDs: msg.Scope.ObserverIDs,
|
|
Events: msg.Scope.Events,
|
|
}
|
|
subID := uuid.NewString()
|
|
h.AddScope(client, subID, scope)
|
|
reply, _ := json.Marshal(map[string]any{
|
|
"v": 1, "type": "subscribed", "id": msg.ID, "subscriptionId": subID,
|
|
})
|
|
if slog.Default().Enabled(context.Background(), slog.LevelDebug) {
|
|
// Debug lines log only server-made IDs; client-sent values stay out of the logs.
|
|
slog.Debug(fmt.Sprintf("ws[%s]: subscribed %s", connID, subID), "component", "ws")
|
|
}
|
|
err := conn.Write(ctx, websocket.MessageText, reply)
|
|
if err != nil {
|
|
slog.Warn("failed to send subscribed reply", "component", "ws", "connection_id", connID, "error", err)
|
|
}
|
|
|
|
case "unsubscribe":
|
|
if msg.SubscriptionID == "" {
|
|
return
|
|
}
|
|
h.RemoveScope(client, msg.SubscriptionID)
|
|
reply, _ := json.Marshal(map[string]any{
|
|
"v": 1, "type": "unsubscribed", "id": msg.ID, "subscriptionId": msg.SubscriptionID,
|
|
})
|
|
if slog.Default().Enabled(context.Background(), slog.LevelDebug) {
|
|
slog.Debug(fmt.Sprintf("ws[%s]: unsubscribed", connID), "component", "ws")
|
|
}
|
|
if err := conn.Write(ctx, websocket.MessageText, reply); err != nil {
|
|
slog.Warn("failed to send unsubscribed reply", "component", "ws", "connection_id", connID, "error", err)
|
|
}
|
|
|
|
case "configure":
|
|
h.Configure(client, hub.ClientOptions{ResolvePath: msg.ResolvePath, IncludeObserverKey: msg.IncludeObserverKey, IncludeRepeats: msg.IncludeRepeats})
|
|
reply, _ := json.Marshal(map[string]any{
|
|
"v": 1, "type": "configured", "id": msg.ID,
|
|
"resolvePath": msg.ResolvePath, "includeObserverKey": msg.IncludeObserverKey, "includeRepeats": msg.IncludeRepeats,
|
|
})
|
|
if slog.Default().Enabled(context.Background(), slog.LevelDebug) {
|
|
slog.Debug(fmt.Sprintf("ws[%s]: configured", connID), "component", "ws")
|
|
}
|
|
if err := conn.Write(ctx, websocket.MessageText, reply); err != nil {
|
|
slog.Warn(fmt.Sprintf("ws[%s]: failed to send configured reply", connID), "component", "ws", "error", err)
|
|
}
|
|
|
|
case "ping":
|
|
reply, _ := json.Marshal(map[string]any{"v": 1, "type": "pong", "id": msg.ID})
|
|
err := conn.Write(ctx, websocket.MessageText, reply)
|
|
if err != nil {
|
|
slog.Warn(fmt.Sprintf("ws[%s]: failed to send pong", connID), "component", "ws", "error", err)
|
|
}
|
|
|
|
default:
|
|
slog.Warn("unknown message type", "component", "ws", "connection_id", connID)
|
|
}
|
|
}
|