server

package
v1.54.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 25, 2026 License: MIT Imports: 31 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package server implements a WebSocket sync server for ygo documents that speaks the y-websocket and Hocuspocus protocols.

The server exposes an http.Handler that adopters mount on their own http.ServeMux at any path prefix. Per port-note §"Go translation choices" — every adopter already has an HTTP server, so we layer on top rather than impose our own runtime. cmd/yserve wraps this for stand-alone use.

Wire format: y-websocket frames, a message type followed by its payload (0=Sync, 1=Awareness, 3=QueryAwareness). The server also handles Hocuspocus's message types (Auth, Stateless, BroadcastStateless, Close, SyncStatus). HocuspocusHandler serves document-prefixed frames and multiple documents on one socket. Handler also serves Hocuspocus when DocNameFn returns an empty name.

Per-document state lives in a map keyed by docName (by default the URL path below the mux pattern the handler is mounted on; see Options.DocNameFn). Documents are loaded lazily on the first connection and evicted after the last connection closes (or, with Options.DocIdleTimeout, after the idle window lapses); if a persist.Store is configured, every applied update is persisted and a final snapshot is written at eviction time.

Index

Constants

View Source
const StateVectorHeader = "Ygo-State-Vector"

StateVectorHeader is the response header that carries the server's state vector (base64) at the moment of the response's snapshot. A client that applied the response can POST its own changes as a diff against it.

Variables

View Source
var (
	// ErrDocumentNotFound is returned by CloseDocument for a document the
	// server does not hold.
	ErrDocumentNotFound = errors.New("server: document not resident")
	// ErrDocumentHasConnections is returned by CloseDocument without force
	// for a document that still has connections.
	ErrDocumentHasConnections = errors.New("server: document has connections")
	// ErrWriteRefused wraps the error Options.OnServerWrite refused a
	// server write with.
	ErrWriteRefused = errors.New("server: write refused by OnServerWrite")
	// ErrNotStored wraps the Store's error for a server write that was
	// applied and sent but not stored.
	ErrNotStored = errors.New("server: write applied and sent but not stored")
	// ErrTooManyDocuments is returned when loading the document would pass
	// Options.MaxDocs.
	ErrTooManyDocuments = errServerDocsFull
	// ErrDocumentClosed is returned by a Document after its Close.
	ErrDocumentClosed = errors.New("server: Document is closed")
	// ErrInvalidUpdate wraps the decoding error of an update ApplyUpdate
	// was given, or reports bytes after one complete update.
	ErrInvalidUpdate = errors.New("server: invalid V1 update")
)
View Source
var ErrServerClosed = errors.New("server: closed")

ErrServerClosed is returned by the server's document API (OpenDocument, Apply, ApplyUpdate, CloseDocument) after Close.

Functions

This section is empty.

Types

type DocStat added in v1.14.0

type DocStat struct {
	// Name is the docName of a resident document.
	Name string
	// Connections is the number of live document connections on it.
	// Each Hocuspocus routing key counts separately, even on a shared socket.
	Connections int
	// QueuedMessages and QueuedBytes sum what is queued on the document's
	// connections and not yet taken by their writers, replies included. A
	// value that stays high points at a client that cannot keep up.
	QueuedMessages int
	QueuedBytes    int64
}

DocStat is the per-document line of a Stats snapshot.

type Document added in v1.52.0

type Document struct {
	// contains filtered or unexported fields
}

Document is a server document held open by OpenDocument: it stays resident until Close, whether or not clients are connected. Its methods are safe for concurrent use.

func (*Document) Apply added in v1.52.0

func (d *Document) Apply(ctx context.Context, fn func(txn *doc.TransactionMut) error) ([]byte, error)

Apply runs fn in one write transaction on the server's copy of the document and sends what it changed as a client's update is sent: queued to every connection, stored, published, reported to OnChange. It returns that update, or nil when fn changed nothing (nothing is then sent).

The transaction's origin is a new *ServerOrigin. fn runs under the document's write lock: take roots with the *In accessors (ygo.TextIn(txn, "t")), and do not call the server for the same document or wait on its clients. Whatever fn changed is committed and sent even when it returns an error or panics (CRDT edits are not rolled back, and the clients must see what the server holds); the error is returned after that, a panic goes on after that. Updates of follow-up transactions the server's own observers open during the commit (TextEvent.ReadDelta) are not sent, as for a client's update.

A Store error is returned wrapped in ErrNotStored, after the update was applied and sent.

func (*Document) ApplyUpdate added in v1.52.0

func (d *Document) ApplyUpdate(ctx context.Context, update []byte) error

ApplyUpdate applies a V1 update to the server's copy of the document and sends it, as given, as a client's update is sent: queued to every connection, stored, published, reported to OnChange. The update is checked first: it must decode, and nothing may follow it (ErrInvalidUpdate); nothing is applied otherwise. Unlike a fan-out that does not apply, the server's state then holds the update, so a client that connects later gets it in its sync.

A Store error is returned wrapped in ErrNotStored, after the update was applied and sent.

func (*Document) Close added in v1.52.0

func (d *Document) Close()

Close lets the document go: with no connection and no other open Document left it is parked (DocIdleTimeout) or evicted with a final flush, as after its last disconnect. On a server without a Store, a document a server write changed stays resident instead (until CloseDocument or the server's Close), so the write is not lost. Close is idempotent.

func (*Document) Name added in v1.52.0

func (d *Document) Name() string

Name is the document's name.

func (*Document) State added in v1.52.0

func (d *Document) State() ([]byte, error)

State is the server's copy of the document as one V1 update (EncodeStateAsUpdate), the pending buffer included.

type HTTPError added in v1.54.0

type HTTPError struct {
	Status  int
	Message string
}

HTTPError is an error Options.OnHTTPRequest returns to choose the response's status (and message) of a refused request.

func (*HTTPError) Error added in v1.54.0

func (e *HTTPError) Error() string

type HTTPOrigin added in v1.54.0

type HTTPOrigin struct {
	DocName string
	Request *http.Request
}

HTTPOrigin is the origin of the transaction an HTTP POST's update is applied in.

type Options

type Options struct {
	// Store optionally persists every applied update keyed by
	// docName. When set, new documents load their history on first
	// connect (drain through the pending buffer if necessary).
	// When nil, documents are in-memory only and lost on the last
	// disconnect.
	Store persist.Store

	// DocNameFn extracts the docName from the WS upgrade request. The
	// default is the whole URL path below the ServeMux pattern the
	// handler is mounted on, slashes included: mounted at "/collab/",
	// "/collab/team-a/doc" is "team-a/doc". Without a pattern it is the
	// whole path without its leading slash, as y-websocket's reference
	// server takes req.url.slice(1). Only net/http's ServeMux records the
	// pattern (r.Pattern, not under GODEBUG=httpmuxgo121=1). Behind
	// another router or a proxy that keeps a prefix, mount on a ServeMux
	// at that prefix or strip it here, e.g.
	//
	//	DocNameFn: func(r *http.Request) string {
	//		return strings.TrimPrefix(r.URL.Path, "/collab/")
	//	},
	DocNameFn func(r *http.Request) string

	// OriginPatterns lists the allowed Origin headers for CORS-
	// style WS upgrade rejection. Defaults to an empty list which
	// rejects all browser cross-origin connections; pass "*" to
	// allow any origin (development only — relaxes browser
	// same-origin protection). Forwarded verbatim to coder/websocket
	// AcceptOptions.
	OriginPatterns []string

	// OnAuthenticate checks a Hocuspocus key's token before loading its
	// document or admitting it to the room. A denial sends PermissionDenied
	// and keeps the socket open for a retry. OnAuthenticateRequest takes
	// precedence when set. Legacy Auth envelopes on y-websocket connections
	// still use this hook; stock y-websocket clients must use OnConnect.
	OnAuthenticate syncpkg.AuthHandler

	// OnAuthenticateRequest checks a new Hocuspocus key's token with the
	// upgrade request and returns its read-only permission. ReadOnly can
	// additionally restrict it. Established keys keep their permission until
	// closed; token refresh requires closing and re-opening the key.
	// Like OnConnect, hooks run on the socket's read goroutine; keep them fast.
	OnAuthenticateRequest func(r *http.Request, docName, token string) (readOnly bool, err error)

	// IdleTimeout closes a Hocuspocus socket after this long without an
	// inbound message. Zero or negative selects 60 seconds. It does not
	// change y-websocket connections.
	IdleTimeout time.Duration

	// AuthTimeout is the absolute deadline for establishing the first
	// Hocuspocus key, unaffected by incoming traffic. Zero or negative
	// selects 60 seconds. After the first admission only IdleTimeout applies.
	AuthTimeout time.Duration

	// OnStateless handles Hocuspocus's Stateless and BroadcastStateless
	// message types, on the same frames as OnAuthenticate.
	// Receives docName + payload string for both MessageStateless
	// and MessageBroadcastStateless envelopes. Long-running work
	// should be dispatched off-thread — this runs on the conn's
	// read goroutine.
	//
	// MessageBroadcastStateless also fans out to other conns on
	// the doc's Hocuspocus keys regardless of whether the callback is set.
	OnStateless syncpkg.StatelessHandler

	// OnConnect, when set, is called once a connection has been admitted
	// to its room (past the per-doc and global caps) but before the
	// initial sync is sent. It receives a stable per-connection id
	// (unique for the server's lifetime), the docName, and the original
	// upgrade *http.Request, so an adopter can gate on headers, cookies,
	// TLS state, or remote address — request context that the token-only
	// OnAuthenticate does not see. Returning a non-nil error rejects the
	// connection: it is torn down and the WS is closed with
	// StatusPolicyViolation on y-websocket. Hocuspocus sends PermissionDenied
	// for that key and keeps the socket. OnDisconnect does NOT fire for it. A
	// panic inside OnConnect is also torn down cleanly (the room slot is
	// released, no leak) and likewise does not fire OnDisconnect. This
	// runs on the connection's serve goroutine (so it runs concurrently
	// across connections); keep it fast. On Hocuspocus sessions it runs
	// once per document key.
	OnConnect func(connID, docName string, r *http.Request) error

	// OnDisconnect, when set, is called when a connection that OnConnect
	// accepted (or any admitted connection, if OnConnect is nil) is
	// released, with the same connID and docName passed to OnConnect.
	// It pairs one-to-one with a successful admission, so an adopter can
	// keep a balanced per-connection ledger. It runs on the connection's
	// serve goroutine after the room teardown; keep it fast.
	OnDisconnect func(connID, docName string)

	// ReadOnly, when set and it returns true for a connection, marks
	// that connection read-only: the server drops any document update it
	// sends (the update reaches neither the document nor other peers),
	// while still delivering updates to it and accepting its awareness
	// (presence). Decide from the request the way OnConnect gates
	// admission (a JWT claim, header, or path). A read-only client
	// should also disable editing in its UI; the server enforcement is
	// the backstop. Nil means every connection is read-write.
	ReadOnly func(docName string, r *http.Request) bool

	// OnChange, when set, is called after a document update is applied
	// and queued to every connection of the room (it does not wait for them
	// to receive it), with the docName and the V1 update bytes that were
	// applied. Use it for side effects on edits (search indexing,
	// webhooks, audit, external persistence). It fires for every accepted
	// document mutation whether or not a Store is configured, and NOT for
	// an update a read-only connection sent (that is dropped before
	// broadcast) nor for awareness or handshake frames. It runs
	// synchronously on the originating connection's read goroutine, so
	// keep it fast and dispatch long-running work elsewhere; a panic
	// tears down that connection. When a Store is also configured,
	// OnChange runs after the StoreUpdate attempt and fires even if that
	// StoreUpdate failed (the document already changed in memory and on
	// peers; the failure is logged), so do not treat an OnChange call as
	// confirmation of durable persistence. Treat the update slice as
	// valid only for the duration of the call; copy it if you retain it.
	OnChange func(docName string, update []byte)

	// OnLoadDocument, when set, is called the first time a document is
	// loaded into memory (a cache miss), after any Store history has been
	// applied, with the docName. It lets an adopter seed or load initial
	// content from a source other than the Store. A returned V1 update is
	// applied to the fresh document; a returned error aborts the load and
	// the connection is closed with StatusInternalError, leaving no
	// document registered.
	//
	// The returned update is applied in memory and is not itself
	// persisted, so it re-applies on every first load (including after an
	// eviction). For that to be safe the seed MUST be deterministic with
	// STABLE item IDs across calls — build it from a fixed reserved
	// ClientID with fixed clocks, or return the same bytes each time. A
	// seed built from a fresh/random ClientID each call (the default of
	// doc.NewDoc) will, together with a Store, both duplicate its content
	// on every reload and strand persisted client edits that referenced
	// the seed (their origin never reappears). Prefer the Store for
	// durable content; use this hook for stable, regenerable seeds.
	//
	// It runs synchronously under the internal document-registry lock, so
	// it must be fast and MUST NOT call back into the Server (Stats,
	// Close, or opening another connection) or it will deadlock. While it
	// runs, all connection admission and document eviction across the
	// server are stalled, not just this document's creation.
	OnLoadDocument func(docName string) ([]byte, error)

	// OnServerWrite, if non-nil, is called before each server write
	// (Apply, ApplyUpdate, on the Server or a Document) with what it is
	// about to write; a non-nil error refuses the write (ErrWriteRefused
	// wraps it) before anything changes. It cannot refuse a write already
	// committed. It runs on the caller's goroutine, without server locks.
	OnServerWrite func(ctx context.Context, w ServerWrite) error

	// OnHTTPRequest decides who may use HTTPSyncHandler: it runs for every
	// request, before its body is read or its document loaded, with the
	// document's name and whether the request writes (POST). A nil error
	// lets the request through; an *HTTPError chooses the response's
	// status, any other error is 403. The WebSocket hooks (OnConnect,
	// OnAuthenticate) do not cover HTTP requests, so without this hook
	// HTTPSyncHandler refuses every request (403); an open server passes a
	// function that returns nil. ReadOnly also applies: a request it marks
	// read-only may not POST.
	OnHTTPRequest func(r *http.Request, docName string, write bool) error

	// VersionInterval enables periodic auto-versioning: every
	// interval, each document that received updates since the last
	// sweep is captured as a named version ("auto") via
	// persist.SaveVersion. Requires Store to also implement
	// persist.VersionStore (the sqlite backend does); ignored with a
	// logged notice otherwise. Zero disables auto-versioning.
	VersionInterval time.Duration

	// KeepVersions prunes each auto-versioned document to its newest
	// N versions after every capture. Zero keeps every version
	// (history grows unbounded; prune externally).
	KeepVersions int

	// AwarenessTimeout bounds how long a silent presence entry
	// survives before the server sweeps it: any non-local awareness
	// client whose last update is older than this is marked offline
	// and the removal is broadcast to the room. The sweep also
	// garbage-collects tombstones older than twice this value,
	// reclaiming memory from churned clients. Zero selects the
	// y-protocols default (30s). Healthy clients heartbeat well
	// inside the window (y-websocket every 15s), so the sweep only
	// evicts the wedged.
	AwarenessTimeout time.Duration

	// MaxAwarenessClients bounds the distinct presence clientIDs a
	// single room tracks, capping the memory one peer can force by
	// flooding fabricated clientIDs. Zero selects a safe default
	// (4096); a negative value disables the cap. New clients beyond
	// the cap are dropped; already-tracked clients keep updating.
	MaxAwarenessClients int

	// MaxForeignAwarenessClients partitions the MaxAwarenessClients budget
	// by origin: it bounds how many of a room's presence slots relayed
	// presence (cursors of clients on OTHER instances, carried over the
	// Backplane) may occupy, reserving the remainder for this instance's
	// local clients. Once relayed presence fills this many slots, further
	// brand-new foreign clientIDs are dropped while local clients keep
	// being admitted up to MaxAwarenessClients, so a presence flood arriving
	// over the Backplane cannot starve new local clients of a slot. The
	// local floor is MaxAwarenessClients minus this value (it is zero only
	// when this value is set at or above MaxAwarenessClients, see below).
	//
	// Zero selects a default that reserves about 1/8 of the (bounded) cap for
	// local clients (foreign may use the rest), always leaving at least one
	// local slot when the cap has room for one. A negative value disables the
	// partition, so relayed presence again shares the full cap with local
	// clients. A value at or above MaxAwarenessClients is clamped to it, which
	// leaves no local reservation. A positive value is still honored when
	// MaxAwarenessClients is unlimited (it bounds relayed presence while local
	// presence stays unbounded); the zero default imposes no sub-cap in that
	// case. Ignored without a Backplane (there is no relayed presence).
	MaxForeignAwarenessClients int

	// ReadLimit sets the maximum WebSocket message size in bytes that
	// the server will read from a single client frame. Zero selects
	// 4 MiB. A larger message closes the connection with 1009, and a
	// client that resends it on reconnect never gets through, so raise
	// this above the largest document a client may send in one sync
	// (e.g. 128 << 20 for 128 MiB). Set to -1 for unlimited.
	ReadLimit int64

	// WriteTimeout bounds how long one frame of a write to one peer may
	// take, done by that connection's own writer goroutine: a peer that has
	// stopped reading (full TCP send buffer, half-open) is closed once a
	// frame to it has not gone out for this long (after the socket buffers
	// fill), and nobody else waits meanwhile. A large message goes out in
	// 32 KiB fragments, each of which restarts the clock, so a client is not
	// cut however long the whole message takes as long as each fragment
	// goes out in time (3.2 KiB/s at the default). It also bounds how long
	// a message may wait in a connection's send queue before the writer
	// takes it, counted from when it was queued or, if later, from the end
	// of the last reply written to that connection (its initial sync, a
	// presence snapshot, a Hocuspocus SyncStatus): one that has waited
	// longer means the client has fallen behind its room, and the
	// connection is closed with websocket.StatusTryAgainLater (1013, reason
	// "send queue stalled") so the client reconnects and resyncs. A
	// broadcast can so wait up to about twice WriteTimeout plus the write
	// of the reply before it. The close frame a connection closed for
	// falling behind gets is a write too: one that cannot go out within
	// WriteTimeout ends the close (the client's reply to a frame it took
	// keeps its usual time). Zero selects a safe default (10s).
	WriteTimeout time.Duration

	// MaxSendQueue bounds the messages queued to one connection on behalf of
	// its room (updates, presence and stateless broadcasts from other
	// connections, sweep and disconnect tombstones, backplane re-broadcasts)
	// that its writer has not yet taken. Every connection has its own queue
	// and writer goroutine, so a slow or stuck client never delays the
	// others; one whose queue already holds this many messages when another
	// arrives has fallen behind and is closed: with
	// websocket.StatusTryAgainLater (1013, reason "send queue full") once the
	// message being written to it completes, or, if it does not read at all,
	// by that write's WriteTimeout, which drops the connection without a close
	// code. Its queued messages are dropped: a reconnecting client resyncs the document
	// and presence through the ordinary handshake, but stateless messages it
	// missed are not resent. The connection's own replies (the initial sync,
	// SyncStep2, auth and ping replies) are not counted: its read loop waits
	// for each to be written, so it has at most one queued. Zero selects a
	// safe default (4096); a negative value disables the bound. Stats reports
	// the queued messages per document and SlowClientsClosed.
	MaxSendQueue int

	// MaxSendQueueBytes bounds, like MaxSendQueue, the bytes of the messages
	// queued to one connection on behalf of its room and not yet taken by
	// its writer. It is a backlog threshold checked before each message is
	// queued, not a message size limit: one message is never refused for its
	// size, but a connection whose queue already holds this many bytes when
	// another message arrives is closed as for MaxSendQueue, so a
	// large message followed by another before the writer takes the first
	// can trip it. Size it above the bursts a room may send, including
	// messages relayed over the Backplane. Zero selects 16 MiB, or four times
	// ReadLimit when that is larger; a negative value disables the bound. Per
	// connection the queue holds at most this plus one message beyond it,
	// besides the message being written and one reply: these are
	// per-connection limits, not a server memory bound (size the server with
	// MaxConns and MaxConnsPerDoc).
	MaxSendQueueBytes int64

	// MaxConnsPerDoc bounds the number of simultaneous WebSocket
	// connections to a single document, capping the goroutines and
	// memory one peer can pin by opening many sockets to the same room.
	// Zero selects a safe default (4096); a negative value disables the
	// cap. A connection beyond the cap is rejected at the upgrade with
	// websocket.StatusPolicyViolation; connections already in the room
	// keep working. A connection already admitted is never displaced by a
	// flood; between two still being admitted, the one admitted second is
	// refused, whichever handshake finished first (the room is decided
	// after the handshake, unlike MaxConns). Hocuspocus counts each key
	// separately; a refused key closes its socket with 1013.
	MaxConnsPerDoc int

	// MaxDocs bounds the number of distinct documents the server holds
	// in memory at once, capping the docStates (and Store loads) a peer
	// can force by connecting to many fabricated docNames. Unlike the
	// per-room caps above, this defaults to UNLIMITED (zero or negative):
	// a global document count scales with deployment size, so a default
	// cap would silently break a large multi-tenant server. Operators
	// fronting untrusted clients should set a positive bound. Documents
	// evict when their last connection departs (or, with DocIdleTimeout,
	// when the idle window lapses), so the cap tracks concurrently
	// resident rooms - active plus idle-warm - not lifetime document
	// count. A
	// connection that would create a document past the cap is refused at
	// the upgrade with websocket.StatusTryAgainLater (1013); an already
	// resident room is always admitted. The cap is decided after the
	// handshake: between two connections each creating a room, the one
	// admitted second is refused, whichever handshake finished first.
	MaxDocs int

	// MaxConns bounds the total number of simultaneous WebSocket
	// connections the server holds across all documents at once: a
	// server-wide ceiling that complements the per-room MaxConnsPerDoc.
	// Like MaxDocs, it defaults to UNLIMITED (zero or negative), because a
	// total-connection count scales with deployment size and a default cap
	// would silently break a large server. Operators fronting untrusted
	// clients should set a positive bound sized to their memory and
	// file-descriptor budget. A connection that would exceed the cap is
	// refused at the upgrade with websocket.StatusTryAgainLater (1013)
	// before its room is created or loaded, so a rejected connection
	// neither orphans a fresh document nor forces a Store load; connections
	// already established keep working and the newest socket is the one
	// refused. A connection counts from the moment its upgrade request
	// reaches the handler, before its handshake completes, so a client whose
	// handshake completed is never refused in favour of one that arrived
	// later; it stops counting when it departs or is refused, so the cap
	// tracks live load, not lifetime connections. A Hocuspocus socket counts
	// once, including before its first key is authenticated; its document
	// keys do not consume additional slots.
	MaxConns int

	// DocIdleTimeout keeps a document resident in memory for this long after
	// its last connection departs, instead of evicting it immediately. A
	// reconnect inside the window reuses the live document — no Store reload,
	// no backplane resubscribe — which turns the page-refresh reconnect from a
	// full load into a map lookup. The document is flushed to the Store at the
	// moment it goes idle, so durability is the same as eviction; with a
	// Backplane, foreign updates keep applying while it is idle, so it stays
	// warm AND current. Zero (the default) preserves the existing behaviour:
	// evict as soon as the last connection leaves.
	DocIdleTimeout time.Duration

	// MaxIdleDocs bounds how many idle documents (kept resident by
	// DocIdleTimeout) stay in memory at once. When a document goes idle past
	// the bound, the least-recently-idle one is evicted immediately. Zero
	// means unbounded (within DocIdleTimeout); ignored when DocIdleTimeout is
	// zero. Note that idle documents still count toward MaxDocs — size the two
	// caps together, or a burst of idle rooms can hold slots new rooms need.
	MaxIdleDocs int

	// FlushEvery compacts a document's persisted update log (Store.Flush)
	// after every N successfully stored updates, bounding how long the
	// per-update log grows between compactions. The flush runs synchronously
	// on the read goroutine that stored the Nth update, once per N updates, so
	// the cost amortizes. Zero (the default) disables automatic compaction;
	// the log still compacts on idle, eviction and Close, exactly as before.
	FlushEvery int

	// Backplane, when set, fans document updates between this server and
	// other instances that share it, so a horizontally-scaled deployment
	// (several servers behind a load balancer) converges on the same
	// document. For every document a server holds resident it Subscribes to
	// foreign updates (applying them to its in-memory copy and
	// re-broadcasting to its own clients) and Publishes each update its own
	// clients apply. Nil means single-instance: updates reach only the
	// clients connected to this server (plus the shared Store, if any).
	//
	// A foreign update is applied and re-broadcast locally but is NOT
	// re-persisted (the originating instance already persisted it to the
	// shared Store), does NOT fire OnChange (that fires once, on the
	// instance whose client made the edit), and is NOT re-published (which
	// would echo).
	//
	// Presence/awareness is also carried, so clients see the cursors of
	// peers on other instances: a presence update is relayed to every
	// instance holding the document, and a clean disconnect propagates an
	// explicit tombstone. Presence is best-effort (the underlying protocol
	// is lossy): a foreign entry stays alive while the owning client's
	// heartbeats keep propagating and is otherwise evicted by each
	// instance's own timeout sweep, so a dropped heartbeat can briefly show
	// a stale or missing cursor until the next one lands. All instances in a
	// cluster must run a matching ygo version (already implied by the shared
	// Store) — the backplane framing is not version-negotiated.
	//
	// Carrying presence widens the reach of a presence flood — a client
	// flooding fabricated presence IDs on one instance has them relayed to
	// every instance holding the document — but relayed presence is admitted
	// under a separate origin-partitioned sub-cap (MaxForeignAwarenessClients),
	// so it occupies at most that many of each room's presence slots and, as
	// long as that sub-cap leaves a local reservation (it is below
	// MaxAwarenessClients, the default), cannot deny a newly-connecting LOCAL
	// client its slot; the flood's fabricated IDs still consume foreign slots
	// cluster-wide until they age out (self-healing when the flooder departs).
	// Lower MaxForeignAwarenessClients to shrink a flood's foreign footprint, or
	// front untrusted clients with your own presence validation, if this matters.
	//
	// SHARED STORE REQUIRED. Because a foreign update is applied only in
	// memory and never re-persisted by the receiving instance, every
	// instance sharing a document MUST be backed by the SAME Store (one
	// database, not a per-instance file). The backplane carries live deltas;
	// the shared Store is the source of truth an instance loads from when a
	// document first becomes resident (and reloads after an eviction). With
	// per-instance Stores a document silently loses every cross-instance
	// edit on the next eviction+reload, and a newly-resident instance cannot
	// obtain a document another instance already edited only in memory. Do
	// not run multi-instance without a shared Store.
	//
	// BACKPRESSURE. Publish delivers to each peer instance in order and
	// never drops an update (dropping a delta would diverge a peer). A peer
	// instance re-broadcasts a foreign update by queuing it to its local
	// connections, which never waits for their sockets, so a slow or stuck
	// client on one instance does not hold back the publishing client's
	// edits on another; that client is closed when it falls behind its own
	// queue (see MaxSendQueue and WriteTimeout). A backplane whose delivery
	// itself stalls still applies backpressure to the publishing client.
	Backplane backplane.Backplane
}

Options configures a Server. The zero value is valid: in-memory state only, no persistence, no auth, docName taken from the URL path (see DocNameFn).

type Server

type Server struct {
	// contains filtered or unexported fields
}

Server is the http.Handler implementation. Construct with New and mount via Handler(). Safe for concurrent use.

func New

func New(opts Options) *Server

New returns a Server with the given options. The returned Server is ready to accept WS connections; call Handler() to obtain the http.Handler that performs the upgrade.

func (*Server) Apply added in v1.52.0

func (s *Server) Apply(ctx context.Context, docName string, fn func(txn *doc.TransactionMut) error) ([]byte, error)

Apply opens docName, runs Document.Apply and closes it.

func (*Server) ApplyUpdate added in v1.52.0

func (s *Server) ApplyUpdate(ctx context.Context, docName string, update []byte) error

ApplyUpdate opens docName, runs Document.ApplyUpdate and closes it.

func (*Server) Close

func (s *Server) Close(ctx context.Context) error

Close flushes every resident document through the configured Store, evicts the idle ones (a document with live connections stays until its last connection leaves), and closes the configured Backplane connection. It does not close connections that are still open: they keep working until their clients leave, and http.Server.Shutdown does not close them either, because WebSocket connections are hijacked from the HTTP server. A process that exits after Close ends them.

Returns the first error encountered while flushing or closing the backplane, but continues past errors so partial failure leaves no leaks.

func (*Server) CloseDocument added in v1.52.0

func (s *Server) CloseDocument(ctx context.Context, docName string, force bool) error

CloseDocument takes a resident document out of the server. Without force it refuses a document with connections (ErrDocumentHasConnections). With force, its y-websocket connections and the Hocuspocus sockets holding it are closed with 1001; such a socket's other documents reconnect, as providers do after any drop (docs/tech-debt.md says why one document of a socket is not closed alone). Do not call it from a hook for a document the hook's own connection holds: it would wait until ctx ends. It then waits for those connections and any open Document to go, evicts the document as after its last disconnect (Backplane unsubscribe, final flush; a retained document is dropped) and returns. Connections and OpenDocument calls for the name wait meanwhile and then load it afresh. A cancelled ctx returns early; the close then finishes on its own.

func (*Server) Flush added in v1.14.0

func (s *Server) Flush(ctx context.Context, docName string) error

Flush compacts docName's persisted update log into a single snapshot through the configured Store, forcing a durable checkpoint on demand without evicting the document or disturbing its live connections. It is the explicit form of the compaction the server already performs when a document is evicted or the server closes.

Every applied update is persisted incrementally as it arrives, so Flush does not push unsaved in-memory state; it consolidates what is already stored, keeping the log compact and the next load fast. Call it before a backup, or on a schedule for hot documents.

With no Store configured it is a no-op returning nil, as is a docName the Store has never seen. It is safe to call on a live document: a concurrent edit that commits mid-flush never loses data - when an update's causal dependency has not itself been stored yet (normal for a moment, because updates are applied and broadcast before they are persisted), Flush refuses to compact and returns persist.ErrIncompleteLog with the log untouched; retry shortly. Under heavy concurrent writes to the same document Flush may return a transient store error, in which case retry. It takes no server lock, so it never blocks connection admission or eviction.

func (*Server) HTTPSyncHandler added in v1.54.0

func (s *Server) HTTPSyncHandler() http.Handler

HTTPSyncHandler serves the server's documents over HTTP, so clients that cannot keep a WebSocket open pull and push updates with requests, and see and are seen by the WebSocket clients of the same document at once. The document's name comes from Options.DocNameFn, as for WebSocket requests.

GET  <doc>?sv=<base64 state vector>[&v=2]
POST <doc>[?sv=<base64 state vector>]   body: one V1 update

GET returns the document's update for a client at sv (the whole document without sv), with its pending updates, as a sync step 2 at that state vector carries it; v=2 returns it in V2. POST applies its body as a client's update is applied: queued to every connection, stored, published and reported to OnChange, in a transaction whose origin is a new *HTTPOrigin; with sv, the response carries the document's update for sv after the write (push and pull in one request), else it is 204. The sv parameter is base64, standard or URL-safe, padded or not.

Every response that reads the document carries StateVectorHeader and an ETag naming the document's revision; a GET whose If-None-Match holds the current one returns 304 with no body: the document has not changed since the response that carried it.

Requests are refused, before their body is read or their document loaded, by Options.OnHTTPRequest, which must be set (without it every request is 403), by Options.ReadOnly for POST (403), and when a browser's Origin is neither the request's host nor in Options.OriginPatterns (403). POST needs Content-Type application/octet-stream (415), which a cross-site form cannot send, and a body within Options.ReadLimit (413). Each request holds one of Options.MaxConns while it runs (503 past it, as at Options.MaxDocs). A GET of a document that is not resident and holds nothing does not keep it resident.

func (*Server) Handler

func (s *Server) Handler() http.Handler

Handler returns the http.Handler that performs the WebSocket upgrade and routes the resulting connection through the sync state machine. Mount it on a mux pattern such as "/" or "/collab/{docName}".

func (*Server) HocuspocusHandler added in v1.37.0

func (s *Server) HocuspocusHandler() http.Handler

HocuspocusHandler serves document-prefixed frames at any URL path. Mount it on the exact endpoint providers use (e.g. "/collab"): providers strip trailing slashes. Handler also serves these sessions at an empty doc name.

func (*Server) OpenDocument added in v1.52.0

func (s *Server) OpenDocument(ctx context.Context, docName string) (*Document, error)

OpenDocument loads the document as a connection would (from the Store, then OnLoadDocument; counted against MaxDocs) or finds it resident, and holds it open until the Document's Close. While a CloseDocument closes the document, it waits for that to finish and loads it afresh. After Close it returns ErrServerClosed.

OnLoadDocument and the Store's load run under the server's document registry lock, as for a connection: they must not call the server's document API.

func (*Server) SendStateless added in v1.37.0

func (s *Server) SendStateless(docName, payload string)

SendStateless broadcasts a message to the document's Hocuspocus keys. It queues without waiting for clients; it does not load an absent room.

func (*Server) Stats added in v1.11.0

func (s *Server) Stats() Stats

Stats returns a point-in-time snapshot of resident documents and live connections, including a per-document breakdown (Stats.Docs). It is safe for concurrent use and cheap: it walks the document registry under the registry lock, taking each document's connection lock only briefly. Adopters typically poll it to feed their own metrics, health, or capacity surfaces (pair it with the OnConnect and OnDisconnect hooks for event-level accounting). Lock order docsMu -> connsMu matches the rest of the server.

type ServerOrigin added in v1.52.0

type ServerOrigin struct {
	DocName string
}

ServerOrigin is the origin of the transaction a server write commits: each write has its own value, so Doc.OnUpdate handlers and observers on a server's document can tell server writes (and which one) from clients' updates with a type assertion.

type ServerWrite added in v1.52.0

type ServerWrite struct {
	DocName string
	// Op is "apply" (Apply) or "applyUpdate" (ApplyUpdate).
	Op string
	// Size is the update's length for ApplyUpdate, 0 for Apply (the update
	// does not exist yet).
	Size int
}

ServerWrite describes a server write to Options.OnServerWrite.

type Stats added in v1.11.0

type Stats struct {
	// Documents is the number of documents resident in memory: rooms with
	// at least one live connection, plus rooms kept warm by DocIdleTimeout
	// after their last connection departed.
	Documents int
	// IdleDocuments is how many of Documents are currently idle-resident
	// (kept warm by DocIdleTimeout, zero connections). Always zero when
	// idle keep-warm is off.
	IdleDocuments int
	// Connections is the total number of live WebSocket connections
	// across all resident documents (Hocuspocus counts document keys).
	Connections int
	// Docs is the per-document breakdown, one entry per resident document,
	// sorted by Name for a stable read. Documents is len(Docs) and
	// Connections is the sum of their Connections. Ranging over it lets an
	// adopter surface hot rooms without its own accounting.
	Docs []DocStat
	// SlowClientsClosed counts the connections the server chose to close
	// for falling behind their room since it started: a send queue at
	// Options.MaxSendQueue or MaxSendQueueBytes, or a queued message older
	// than Options.WriteTimeout. Each is counted once, when chosen; one that
	// does not read at all may end through its write deadline instead of
	// the 1013 close.
	SlowClientsClosed int64
}

Stats is a point-in-time snapshot of server load returned by Stats.

Directories

Path Synopsis
Package backplane fans document updates between ygo server instances that share a document, so several horizontally-scaled servers behind a load balancer converge on the same document.
Package backplane fans document updates between ygo server instances that share a document, so several horizontally-scaled servers behind a load balancer converge on the same document.
nats module

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL