Document codebase: comments, per-area READMEs, deployment guide
Readability pass across all four areas of the stack. Comments explain why rather than what, concentrated at the points where behaviour is non-obvious: concurrency, caching, auth, scraping and nginx templating. Backend: doc comments on every exported declaration across handlers, services, models and resolvers. Resolver commentary lives inside function bodies so gqlgen does not strip it on regeneration; schema files use # comments rather than description blocks so introspection output is unchanged. Extracted the duplicated auth-cookie blocks into helpers. Frontend: header comments on every component, store and view, including STATUS: notes marking which of the parallel/legacy views are still live. Documented the non-reactive animation-state pattern, the homeData hub and the WebSocket stale-socket guard. Removed a few dead imports and named the reconnect-backoff and poll-interval constants. Python: module and function docstrings covering the Travelodge scraping contract, the deadline threading, the two-executor concurrency and the NDJSON streaming protocol. Infra: header blocks on every compose file, nginx template, Dockerfile and entrypoint, covering the config selection, envsubst allow-lists, rate-limit semantics and volume persistence. Hoisted the duplicated envsubst variable list in nginx/entrypoint.sh. New: backend/README.md, python/README.md, DEPLOYMENT.md, .env.example, backend/graph/doc.go. Refreshed vue/README.md. Corrected CLAUDE.md, which stated a 24h access token where main.go sets 7 days. No behaviour change. go build/vet, vite build, py_compile and docker compose config all pass. Co-Authored-By: Claude Opus 5 <[email protected]>
This commit is contained in:
@@ -12,10 +12,27 @@ import (
|
||||
"github.com/gorilla/websocket"
|
||||
)
|
||||
|
||||
// This file is the chat hub behind GET /ws. It is deliberately a package-level
|
||||
// singleton (one process, one chat room) rather than an injectable type, so the
|
||||
// connection set, the database handle and the allowed origin all live in
|
||||
// package vars initialised once by InitWebSocket.
|
||||
|
||||
// maxMessages is both the size of the history replayed to a new client and the
|
||||
// number of rows kept in the database: every insert trims older messages.
|
||||
const maxMessages = 50
|
||||
|
||||
// allowedDomain is the site's domain, set by InitWebSocket and read by
|
||||
// Upgrader.CheckOrigin. It is a package var because the Upgrader is one too.
|
||||
var allowedDomain string
|
||||
|
||||
// Upgrader turns the HTTP request into a WebSocket.
|
||||
//
|
||||
// CheckOrigin is the only cross-origin defence on this endpoint: the browser
|
||||
// sends cookies with a WebSocket handshake regardless of origin and there is
|
||||
// no preflight, so without this check any site could open a socket as a
|
||||
// logged-in visitor. Default gorilla behaviour (same-host only) is too strict
|
||||
// here because the site is reached as both example.com and www.example.com,
|
||||
// and "localhost" is allowed for the Vite dev server.
|
||||
var Upgrader = websocket.Upgrader{
|
||||
ReadBufferSize: 1024,
|
||||
WriteBufferSize: 1024,
|
||||
@@ -35,12 +52,21 @@ var Upgrader = websocket.Upgrader{
|
||||
|
||||
var (
|
||||
// clients maps each open connection to whether it belongs to an admin.
|
||||
clients = make(map[*websocket.Conn]bool)
|
||||
mu sync.Mutex
|
||||
wsDB *gorm.DB
|
||||
clients = make(map[*websocket.Conn]bool)
|
||||
// mu guards clients AND serialises the write-then-broadcast sequence, so
|
||||
// that two concurrent senders cannot interleave and deliver messages to
|
||||
// different clients in different orders.
|
||||
mu sync.Mutex
|
||||
wsDB *gorm.DB
|
||||
// nextAuthorID is a per-process counter handed out on connect. It is NOT
|
||||
// a user id and has no meaning across restarts: the chat is pseudonymous,
|
||||
// and the front end only uses it to colour/group consecutive messages
|
||||
// from the same connection.
|
||||
nextAuthorID uint
|
||||
)
|
||||
|
||||
// Per-connection flood limit, separate from services.RateLimiter because it
|
||||
// counts frames on one socket rather than requests from one IP.
|
||||
const (
|
||||
rateLimitWindow = time.Second
|
||||
rateLimitMaxMsgs = 10
|
||||
@@ -70,6 +96,8 @@ type wsHistoryEvent struct {
|
||||
Messages []models.Message `json:"messages"`
|
||||
}
|
||||
|
||||
// InitWebSocket wires the package-level hub to the database and the origin
|
||||
// allow-list. Call it once, before serving.
|
||||
func InitWebSocket(database *gorm.DB, domain string) {
|
||||
wsDB = database
|
||||
allowedDomain = domain
|
||||
@@ -80,6 +108,11 @@ func InitWebSocket(database *gorm.DB, domain string) {
|
||||
func HandleWebSocket(conn *websocket.Conn, isAdmin bool) {
|
||||
defer conn.Close()
|
||||
|
||||
// Registration, history read and history send all happen under one lock.
|
||||
// That is the point: it guarantees the client is already in `clients`
|
||||
// before its snapshot is taken, so a message broadcast concurrently is
|
||||
// either in the history or delivered afterwards — never dropped in the
|
||||
// gap, and never delivered before the history that would overwrite it.
|
||||
mu.Lock()
|
||||
clients[conn] = isAdmin
|
||||
nextAuthorID++
|
||||
@@ -99,11 +132,15 @@ func HandleWebSocket(conn *websocket.Conn, isAdmin bool) {
|
||||
}
|
||||
mu.Unlock()
|
||||
|
||||
// Fixed-window flood limit. Over-limit frames are dropped silently with
|
||||
// no error to the client and without resetting the window.
|
||||
msgCount := 0
|
||||
windowStart := time.Now()
|
||||
|
||||
for {
|
||||
var incoming wsIncoming
|
||||
// Any read error — clean close, network drop or malformed JSON —
|
||||
// ends the connection; there is no attempt to resynchronise.
|
||||
if err := conn.ReadJSON(&incoming); err != nil {
|
||||
break
|
||||
}
|
||||
@@ -135,10 +172,18 @@ func HandleWebSocket(conn *websocket.Conn, isAdmin bool) {
|
||||
|
||||
mu.Lock()
|
||||
wsDB.Create(&msg)
|
||||
// Keep only the newest maxMessages rows. This is a soft delete
|
||||
// (models.Message has gorm.DeletedAt), so the rows stay in the table
|
||||
// with deleted_at set and GORM filters them out of later reads; the
|
||||
// table therefore grows forever even though the chat does not.
|
||||
// The subquery is itself soft-delete filtered, so already-trimmed
|
||||
// rows are not re-deleted.
|
||||
wsDB.Where("id NOT IN (?)",
|
||||
wsDB.Model(&models.Message{}).Select("id").Order("created_at DESC").Limit(maxMessages),
|
||||
).Delete(&models.Message{})
|
||||
|
||||
// Deleting from a map while ranging over it is explicitly allowed in
|
||||
// Go, so pruning dead clients inline here is safe.
|
||||
for client, clientAdmin := range clients {
|
||||
if msg.Private && !clientAdmin {
|
||||
continue
|
||||
|
||||
Reference in New Issue
Block a user