Documentation
¶
Overview ¶
Package server implements chalk's HTTP and WebSocket layers.
The Hub is the per-instance connection registry. It holds one *Conn per connected device, and broadcasts incoming messages to everyone except the sender. Phase 05 layers Postgres LISTEN/NOTIFY on top so messages crossing instances are delivered globally; the hub interface stays the same.
Concurrency model:
- A single sync.RWMutex protects the device-id map. Read-heavy workloads (broadcasts) take the read lock; register/unregister take the write lock.
- Each *Conn has its own bounded send channel and a dedicated writer goroutine. Broadcast does a non-blocking enqueue: if a connection's send buffer is full (slow client), the connection is closed instead of blocking the broadcaster.
- Closing happens exactly once via sync.Once on each *Conn.
Why not channels-only? A pure CSP design (one inbound channel per hub, fan out via select) is elegant but every broadcast costs N selects and the goroutine-per-connection-writer model already gives us the right backpressure semantics with less code. We can revisit if profiling shows the mutex contended.
chalk -- 85-2/85-3 operational logging: the periodic connection snapshot and the slow-request line.
Both are built around the same constraint: chalkd runs on somebody's small self-hosted box, and diagnostics that cost throughput are not diagnostics worth having. So neither of these measures anything the server was not already doing.
- The WebSocket round-trip comes from the keepalive ping, which already waits for its pong (85-2, see pingLoop).
- The pool counters are maintained by pgx whether anyone reads them or not.
- The database round-trip is one ping per snapshot interval, not per request.
- The slow-request line costs a time.Now and a comparison per request and produces no output at all on a healthy server.
The snapshot is off unless CHALK_OPLOG_SNAPSHOT_INTERVAL is set. See config.OplogConfig for why that default is about privacy rather than cost.
Index ¶
- Constants
- Variables
- type Conn
- func (c *Conn) ClaimedPresence() string
- func (c *Conn) Close(reason error)
- func (c *Conn) Closed() bool
- func (c *Conn) Enqueue(data []byte) error
- func (c *Conn) MarkDone()
- func (c *Conn) RTT() time.Duration
- func (c *Conn) SetClaimedPresence(state string)
- func (c *Conn) SetRTT(d time.Duration)
- func (c *Conn) Wait()
- type EphemeralWSConfig
- type FriendPublisher
- type Hub
- func (h *Hub) Broadcast(except string, data []byte)
- func (h *Hub) BroadcastFresh(except string, data []byte, messageTS time.Time)
- func (h *Hub) CloseAll(ctx context.Context, reason error)
- func (h *Hub) CloseConnsForUser(userID string, reason error)
- func (h *Hub) Conns() []*Conn
- func (h *Hub) ConnsForUser(userID string) []*Conn
- func (h *Hub) Count() int
- func (h *Hub) CountUsers() int
- func (h *Hub) DrainSends(ctx context.Context)
- func (h *Hub) FanOutFresh(exceptConnID string, data []byte, messageTS time.Time)
- func (h *Hub) FanOutToUser(userID, exceptConnID string, data []byte)
- func (h *Hub) FanOutToUserFresh(userID, exceptConnID string, data []byte, messageTS time.Time)
- func (h *Hub) ForEachConn(fn func(*Conn))
- func (h *Hub) Get(deviceID string) *Conn
- func (h *Hub) GetByConnID(connID string) *Conn
- func (h *Hub) HasConnForDevice(userID, deviceID, exceptConnID string) bool
- func (h *Hub) Register(c *Conn)
- func (h *Hub) Unregister(c *Conn)
- type Options
- type PrefsChangePublisher
- type Server
- type VoiceWSConfig
- type WSConfig
- type WSHandler
Constants ¶
const ErrCodeGuestForbidden = "guest_forbidden"
ErrCodeGuestForbidden is the deny answer for every frame outside the guest allowlist.
const StatusPingTimeout websocket.StatusCode = 4008
StatusPingTimeout is the close code for a connection dropped because the peer stopped answering pings. It is app-defined (4000-4999) rather than StatusPolicyViolation because clients treat 1008 as permanent and stop reconnecting; a ping timeout is transient (congested uplink during a video call, suspended laptop) and the client should retry.
Variables ¶
var ErrSendFull = errors.New("send buffer full")
ErrSendFull is returned by Enqueue when the connection's send buffer is full.
Functions ¶
This section is empty.
Types ¶
type Conn ¶
type Conn struct {
// ID is a server-generated per-connection UUID, distinct from
// DeviceID. Two browser tabs from the same device share a DeviceID
// but get separate IDs. Phase 09a uses ID as the routing key for
// fan-out (via byConnID) and echo-suppression, so multiple tabs of
// the same user coexist without one evicting the other.
ID string
DeviceID string
UserID string
// 85-2: diagnostics for the periodic connection snapshot. RemoteIP is
// the client address as auth.IPFromRequest resolved it (the real client
// behind a trusted proxy, not the proxy); Username is the handle looked
// up once at hello time, so a snapshot never costs a query. Both are
// written before Register and only read afterwards.
RemoteIP string
Username string
// DeviceType is the device class the client declared in its hello
// ("phone", "tablet", "desktop" or "browser-unknown"). Presence
// bookkeeping needs it to re-create a device_presence row that went
// missing while this connection was still live.
DeviceType string
// 80-9: guest connections. IsGuest routes every inbound frame through
// the guest dispatch (default-deny allowlist, chalk_guest data path);
// GuestChannelID is the one channel the guest exists for, taken from
// the resolved ephemeral session -- never from client input.
IsGuest bool
GuestChannelID uuid.UUID
// 80-10: when the session that authorized this connection expires.
// TURN credentials minted on voice_join are clamped to it, so a
// credential can never outlive the session that earned it. Zero when
// no session backed the conn (store-less tests).
SessionExpiresAt time.Time
// 65-4: the raw token of the login session behind this connection. Push
// subscriptions are bound to it. Empty for guests and store-less tests.
// It never leaves the process.
SessionToken []byte
// Send is the outbound queue. The writer goroutine reads from this
// channel and pushes frames over the WebSocket. Closed by Close.
Send chan []byte
// CreatedAt is set at construction; useful for logging/metrics.
CreatedAt time.Time
// contains filtered or unexported fields
}
Conn is one WebSocket connection. The websocket bits (Read/Write loops, ping/pong) are wired in ws.go; this type holds the hub-facing surface so the hub doesn't need to know about the WebSocket library.
func NewConn ¶
NewConn builds a Conn with its send buffer and lifecycle channels. closeFn is invoked exactly once when Close is called for the first time; it must be safe to call from any goroutine.
Phase 09a: id is the per-conn UUID. An empty id gets one generated: byConnID is what Count, Conns and CloseAll iterate, so an unkeyed conn would be invisible to them.
func (*Conn) ClaimedPresence ¶ added in v0.3.24
ClaimedPresence returns the last state passed to SetClaimedPresence, or "" if the client never sent a presence_update.
func (*Conn) Close ¶
Close marks the connection for teardown. Safe to call multiple times and from any goroutine. Returns immediately; callers that need to wait for goroutines to exit should call Wait afterward.
func (*Conn) Enqueue ¶
Enqueue tries to push data onto the send buffer. Returns ErrSendFull if the buffer is full (slow client), or an error if the connection is closed.
func (*Conn) MarkDone ¶
func (c *Conn) MarkDone()
MarkDone is called by the WebSocket loops when they've fully exited. The Hub's CloseAll uses Wait() to block on this.
func (*Conn) RTT ¶ added in v0.7.1
RTT returns the last measured ping round-trip, or 0 if this connection has not been pinged yet (it is younger than one ping interval).
func (*Conn) SetClaimedPresence ¶ added in v0.3.24
SetClaimedPresence records the last presence state this connection asked for. Read back when a lost device_presence row has to be re-created, so the repair doesn't resurrect a backgrounded tab as "online".
type EphemeralWSConfig ¶ added in v0.7.0
type EphemeralWSConfig struct {
Enabled bool
MaxTTL time.Duration
InviteMaxTTL time.Duration
MaxGuests int
}
EphemeralWSConfig carries the phase-80 knobs the WS handlers enforce: create clamps a requested TTL to MaxTTL (80-6); invite minting caps link life at InviteMaxTTL and the per-channel guest count at MaxGuests (80-7).
type FriendPublisher ¶
FriendPublisher publishes a Kind="friend" NOTIFY. Implemented by server.go to keep this file free of transaction plumbing.
type Hub ¶
type Hub struct {
// contains filtered or unexported fields
}
Hub registers connections and dispatches messages between them.
Phase 09a adds two indices alongside the device_id-keyed map:
- byConnID: maps Conn.ID -> *Conn for direct conn lookup
- byUser: maps userID -> *userConnSet for per-user fan-out
As of step 4, the byUser index is the primary routing structure for production fan-out. The conns (device_id) map remains as a "last writer wins" lookup for legacy callers and tests; multiple conns may share a device_id (multi-tab) without one evicting the other. byConnID and byUser see every connection regardless of deviceID collisions.
All three maps are kept consistent under the same write lock (h.mu). userConnSet has its own internal mutex so fan-out can snapshot a user's conns without holding h.mu.
func (*Hub) Broadcast ¶
Broadcast enqueues data to every connection except the one with deviceID equal to except (typically the sender, to avoid echoing). A nil except sends to all.
Broadcast does not block on slow clients: if a connection's send buffer is full, the connection is marked for close and skipped. The actual close happens out of band so the broadcast loop stays fast.
func (*Hub) BroadcastFresh ¶
BroadcastFresh is Broadcast with an additional filter: connections registered AFTER messageTS are skipped. This prevents stale messages from reaching freshly-connected clients via the live feed.
The use case: a NOTIFY for message M arrives at the listener at time T0. By the time the listener finishes processing (fetching M from storage, building the frame, calling Broadcast), additional connections may have joined the hub. Those new connections logically existed *after* M was sent and should not receive M as a live broadcast -- they should fetch history explicitly if they want past messages. Without this filter, slow listener processing produces "phantom" live deliveries of old messages to brand-new connections.
Real-app semantics: a user opening a fresh tab should not suddenly start receiving messages sent before the tab opened. The live channel represents "now and onward"; backfill is a separate concern (phase 08).
messageTS should be the wall-clock timestamp of the message being broadcast. Conn.CreatedAt is set at NewConn time.
func (*Hub) CloseAll ¶
CloseAll terminates every connection. Used during graceful shutdown. Returns when all conns have stopped, or when ctx expires.
Snapshotting byConnID rather than the device-keyed map matters: the latter holds one conn per device_id, so a second tab of the same browser would have survived the shutdown it was supposed to be closed by.
func (*Hub) CloseConnsForUser ¶
CloseConnsForUser closes every WS connection bound to userID. The reason is propagated to each Conn.Close so the websocket goodbye frame carries it. Callers should pass a descriptive error (e.g. "blocked by admin alice") so the log audit trail is informative.
Idempotent: closing an already-closed conn is a no-op at the Conn layer. Calling with an unknown userID is a no-op.
Concurrency: the snapshot is taken under the hub lock (via ConnsForUser); the close calls happen without holding the hub lock so a slow close can't stall other hub operations.
func (*Hub) Conns ¶ added in v0.3.24
Conns returns a snapshot of every active connection on this instance. Used by presence recovery, which has to re-assert a row per connected device after the instance's rows were deleted underneath it.
func (*Hub) ConnsForUser ¶
ConnsForUser returns a snapshot slice of every active connection for userID. Empty slice if no conns are registered for that user. Phase 09a step 2: production code does not yet call this; step 3 will use it to fan out per-user without holding h.mu for the duration of the enqueue loop.
The snapshot is taken under the userConnSet's own mutex, so this is cheap (no h.mu held during iteration) and does not block concurrent Register/Unregister of unrelated users.
func (*Hub) Count ¶
Count returns the number of active connections. Keyed on Conn.ID, so two tabs sharing a device_id count as the two connections they are.
func (*Hub) CountUsers ¶
CountUsers returns the number of distinct users with at least one active connection. Phase 09a step 2; mostly for tests and metrics.
func (*Hub) DrainSends ¶ added in v0.3.47
DrainSends blocks until no connection has anything left in its send buffer, or ctx expires. Shutdown uses it so a frame enqueued a moment earlier gets a chance to reach the wire: writeLoop returns on conn.closed without draining Send, so enqueue-then-CloseAll is otherwise a race the frame usually loses.
An empty buffer means the write pump picked the frame up, not that the socket write returned -- good enough for a best-effort notice, and tracking per-write completion is a lot of machinery for one caller.
func (*Hub) FanOutFresh ¶
FanOutFresh broadcasts data to every connection on this hub except the one whose Conn.ID == exceptConnID, applying the BroadcastFresh staleness filter (conns registered after messageTS are skipped).
Phase 09a step 3 introduced this with iteration over h.conns. Step 5 fix: iterate h.byConnID instead. After step 4, multiple conns can share a deviceID (multi-tab) and the conns map is a "last writer wins" lookup -- it does NOT contain every conn. byConnID does. For broadcast semantics we need every conn.
Empty exceptConnID delivers to all conns.
func (*Hub) FanOutToUser ¶
FanOutToUser enqueues data to every connection of userID, except the connection with ID equal to exceptConnID (typically the sender's conn, to suppress the echo).
Phase 09a step 3: replaces the ForEachConn-with-userID-filter pattern previously used in server.go. Empty exceptConnID delivers to all of the user's conns. Returns immediately if userID has no active conns.
func (*Hub) FanOutToUserFresh ¶
FanOutToUserFresh combines FanOutToUser with the "skip conns registered after messageTS" filter from FanOutFresh. Used for message events where stale conns should not receive the live push (they'll fetch history themselves).
func (*Hub) ForEachConn ¶
ForEachConn invokes fn for every active connection. The hub's RLock is held for the duration of the iteration; fn must not call hub methods that take the write lock (Register/Unregister) or it will deadlock. Enqueue is safe (uses its own internal locking).
func (*Hub) Get ¶
Get returns the active connection for a device_id, or nil. Mostly used by tests; production code prefers Broadcast to avoid races.
func (*Hub) GetByConnID ¶
GetByConnID returns the connection with the given per-conn UUID, or nil. Phase 09a: provides lookup by Conn.ID for the upcoming fan-out rewrite. Production code in 09a does not yet call this; it is wired up so step 2 can switch routing keys without further plumbing.
func (*Hub) HasConnForDevice ¶ added in v0.3.24
HasConnForDevice reports whether any connection other than exceptConnID is currently registered for (userID, deviceID).
Presence teardown needs this: two tabs of the same browser share one device_id and therefore one device_presence row, so only the last connection out may clear it. Passing "" as exceptConnID asks the plain "is this device connected at all" question.
func (*Hub) Register ¶
Register adds c to the hub. If a previous connection exists for the same device_id, it is asynchronously closed (last-writer-wins). This handles the common case of a browser reconnecting before the old socket has been reaped.
The prior close runs in a goroutine, not synchronously. This matters because Conn.Close ultimately invokes the WebSocket library's Close, which may need to coordinate with the connection's own writer goroutine to send a close frame. Running it inline could block the caller of Register -- which is the ServeHTTP goroutine of the *new* connection, in the middle of its own setup. Asynchronous teardown lets the new connection's setup proceed without that coupling. Register adds c to the hub. Phase 09a step 4 removed the "same-deviceID supersedes" eviction: two browser tabs that share a localStorage device_id (or any two conns with matching DeviceID for any other reason) now coexist on the hub. Each has its own unique Conn.ID, and fan-out is keyed on byUser/byConnID, not on the deviceID map.
The conns map is kept as a deviceID->Conn lookup of "the most-recently-registered conn for this device." It is no longer the primary routing index; production code uses byUser / byConnID. The map is only useful as a fallback for legacy per-device push paths (none remain in production after step 4) and for the tests that still exercise Get(deviceID). When two conns share a deviceID, conns[deviceID] always points at the latest Register; Unregister of an older conn no-ops on the map since cur != c. Unregister of the latest conn deletes the entry. This produces "last writer wins" lookup semantics without the destructive eviction.
func (*Hub) Unregister ¶
Unregister removes c from the hub if it's still the active connection for its device_id. A race-safe Unregister is a no-op if c has already been replaced by a newer connection (Register's last-writer-wins). Unregister removes c from the hub. As of phase 09a step 4 there is no eviction, so c.ID is unique in byConnID and a guaranteed member of byUser[c.UserID] (when UserID is non-empty). The deviceID-keyed conns map may have c OR may have been overwritten by a later Register of another conn sharing c.DeviceID; we only delete the entry if it still points at c (last-writer-wins).
type Options ¶
type Options struct {
Listen string
Store *store.Store
Hub *Hub
WSConfig WSConfig
InstanceID string
Logger *log.Logger
// Phase 06 dependencies. If nil, the server starts but the
// corresponding features are disabled. Production callers always
// pass both.
Presence *presence.Store
Friends *friends.Store
// PresenceLoopConfig overrides DefaultLoopConfig if non-nil; tests
// shrink these for faster sweeps.
PresenceLoopConfig *presence.LoopConfig
// 80-9: the chalk_guest pool (CHALK_DB_URL_GUEST). Nil disables guest
// WS connections entirely -- the ephemeral feature's join endpoint may
// mint sessions, but a session without this pool cannot connect.
GuestStore *store.Guest
// Phase 07: SPA hosting. If WebFS is non-nil, the server mounts
// the SPA at "/" by serving WebFS rooted at WebDir (typically
// "web", with dist/ inside). If WebFS is nil, "/" is unhandled
// (404). Tests for the WS layer pass nil; the chalkd entry point
// passes the embedded chalk.Web from the module root.
WebFS fs.FS
WebDir string
// Phase 09b sub-step 3: registration HTTP routes.
//
// If non-nil, the server mounts /api/auth/register/begin,
// /api/auth/register/finish, and /api/auth/config. The caller is
// responsible for constructing the auth.Service, the ceremony
// cache, and starting the cache's janitor goroutine (typically
// the chalkd entry point binds the cache to its lifecycle ctx).
//
// If nil, no auth routes are mounted; the existing WS handler
// still runs with its pre-09b ensureDeviceForTesting path. Sub-
// step 09b-5 cuts the WS over to session-based auth.
Auth *auth.HTTPDeps
// att-1: how long a still-'uploading' attachment row may linger before
// the orphan janitor prunes it. 0 falls back to 24h in NewServer.
AttachOrphanTTL time.Duration
// 85-2/85-3: operational logging, from config.Oplog. SnapshotInterval 0
// disables the periodic connection snapshot (the default -- see
// config.OplogConfig); SlowRequest 0 disables the slow-request line.
SnapshotInterval time.Duration
SlowRequest time.Duration
// 65-3: the Web Push sender. It is nil if push is disabled.
Push *webpush.Sender
// 136-4b: the APNs sender for the iOS app. It is nil if push is disabled
// or the CHALK_APNS_* values are not set. The server uses it only if
// Push is also set.
APNs *apns.Sender
}
Options bundles dependencies and tunables.
type PrefsChangePublisher ¶
PrefsChangePublisher is the hook called from handlePrefsSet to emit a per-user pubsub event. The Server wires this up in main.
type Server ¶
type Server struct {
// contains filtered or unexported fields
}
Server wraps the http.Server, hub, pubsub listener, presence/friends background goroutines, and lifecycle plumbing.
func (*Server) Hub ¶
Hub returns the *Hub embedded in the Server, so callers like cmd/chalkd can wire it into auth.HTTPDeps.Kicker without duplicating Server.hub via a separate option. Read-only accessor.
func (*Server) NotifyGuestJoined ¶ added in v0.7.0
NotifyGuestJoined pushes channel_event{kind:"member_added"} to a room's members after a guest's FIRST redemption (80-14 aftermath of the 80-8 join): without it, members' clients show the guest's messages under a UUID stub until their next reconnect. Wired into auth.HTTPDeps like Kicker. Best-effort: failures are logged, the redemption stands.
func (*Server) PubsubReady ¶
func (s *Server) PubsubReady() <-chan struct{}
PubsubReady returns a channel closed when the cross-instance listener has subscribed to NOTIFY at least once.
type VoiceWSConfig ¶
type VoiceWSConfig struct {
Enabled bool
MaxParticipants int
ForceRelay bool
TurnURLs []string
TurnSecret string
TurnTTL time.Duration
StunURLs []string
// 30-8: adaptive-quality policy echoed verbatim on voice_join_ack.
// Nil is legal (tests, stripped configs) -- the ack then omits the
// block and clients use their baked defaults.
Adaptive *proto.VoiceAdaptiveConfig
}
VoiceWSConfig carries the voice knobs into the WS layer. Populated in cmd/chalkd from config.VoiceConfig (the server package stays decoupled from internal/config, same as AttachMaxPerMessage).
type WSConfig ¶
type WSConfig struct {
PingInterval time.Duration
PingTimeout time.Duration
WriteTimeout time.Duration
HandshakeTimeout time.Duration
// att-1: max attachment refs one send frame may link
// (CHALK_ATTACH_MAX_PER_MESSAGE). 0 falls back to a safe default in the
// send handler.
AttachMaxPerMessage int
// 30-2: voice signaling knobs (CHALK_VOICE_* / CHALK_TURN_*), populated
// in cmd/chalkd from config.VoiceConfig. Zero-value = voice disabled.
Voice VoiceWSConfig
// 42-5: how far back a reply still counts as "active" for the thread
// inbox's discovery half (CHALK_THREAD_ACTIVE_WINDOW_HOURS). Defaulted
// here rather than left at zero, because a zero window would silently mean
// "nothing is ever active".
ThreadActiveWindow time.Duration
// 80-6: ephemeral voice channel knobs (CHALK_EPHEMERAL_*), populated in
// cmd/chalkd from config.EphemeralConfig. Zero-value = feature disabled.
Ephemeral EphemeralWSConfig
// 82-6: refuse unsigned (suite-1) wraps on publish_channel_key and tell
// clients (welcome.wrap_sig_required) to refuse them on read. Populated in
// cmd/chalkd from config.WrapSigRequired. Zero-value here is permissive,
// so a Hub built without going through cmd/chalkd (tests, embeds) accepts
// legacy wraps; the shipped default is true since 82-10 and arrives via
// config.Default(). See internal/config/config.go for why.
// accepted (the soft window).
WrapSigRequired bool
// ServerIDKey (83-6) is chalkd's long-term Ed25519 identity, from
// CHALK_SERVER_ID_KEY. Nil disables the inner sealed channel: clients
// are told inner_unavailable and run plaintext WebSocket frames (over
// TLS) as before -- acceptable for a dev stack, and the client refuses
// it the moment it holds a pin for this server.
ServerIDKey ed25519.PrivateKey
}
WSConfig tunes WebSocket behavior.
type WSHandler ¶
type WSHandler struct {
// contains filtered or unexported fields
}
WSHandler upgrades HTTP requests to chalk's WebSocket protocol and runs per-connection read/write/ping/presence loops.
Phase 06 adds presence and friends dependencies plus two publishers (for presence transitions and friend events). Both publishers are optional; nil disables the corresponding push path. Tests that don't care about cross-instance push can pass nil.
func NewWSHandler ¶
func NewWSHandler( hub *Hub, st *store.Store, cfg WSConfig, instanceID string, logger *log.Logger, presenceStore *presence.Store, friendsStore *friends.Store, pubPresence presence.Notifier, pubFriend FriendPublisher, pubPrefs PrefsChangePublisher, listener *pubsub.Listener, ) *WSHandler
NewWSHandler constructs a handler. Phase 06 adds the presence/friends stores and the two publishers. Phase 08 adds the listener so the WS layer can subscribe/unsubscribe per-channel topics.
Source Files
¶
- avatar_event.go
- avatars_ws.go
- channel_names_ws.go
- ephemeral_ws.go
- governance_dispatch.go
- governance_event.go
- governance_ws.go
- guest_ws.go
- hub.go
- hub_kick.go
- oplog.go
- push_dispatch.go
- push_ws.go
- reads_event.go
- reads_ws.go
- reminder_push.go
- reminder_ws.go
- server.go
- shutdown.go
- spa.go
- typing_event.go
- typing_ws.go
- voice_event.go
- voice_ws.go
- ws.go