client

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: 24 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 client is a Yjs sync provider over WebSocket: the Go equivalent of y-websocket's WebsocketProvider, for yserve and the reference y-websocket server, and, with Options.Hocuspocus, of Hocuspocus's provider, for @hocuspocus/server 2, 3 and 4.

A Client owns a live connection for one document: it runs the y-protocols handshake (SyncStep1 / SyncStep2), broadcasts local transactions as incremental SyncUpdate frames, applies remote frames to the local Doc, exchanges awareness state, and reconnects with exponential backoff until closed.

Local edits made through the Doc between (and during) connections are never lost: each (re)connect handshake diffs against the server's state vector, so offline edits flow up and missed remote edits flow down. This is the embeddable building block for bots, CLI tools, server-side agents, and the gomobile bindings.

Concurrency: while a Client is connected, remote updates commit on background goroutines. Read document state under a read transaction (Doc.ReadTxn) and resolve root types via Doc.Branch OUTSIDE any open transaction; the shared-type wrappers' lock-free read methods are only safe when the caller holds a transaction.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrPermissionDenied: the server's onAuthenticate refused the token.
	// The client closes the connection and dials again after at least
	// deniedBackoff, asking TokenFunc for a token again. To stop, call
	// Close from another goroutine (go c.Close()): Close waits for the
	// goroutine that runs OnError.
	ErrPermissionDenied = errors.New("client: permission denied")

	// ErrDocumentClosed: the server closed the document on this
	// connection (a hook's error, its idle timeout, a reset). The client
	// dials again.
	ErrDocumentClosed = errors.New("client: the server closed the document")

	// ErrUpdateRefused: the server did not apply an update this client
	// sent (SyncStatus 0: a read-only connection). The session goes on.
	ErrUpdateRefused = errors.New("client: the server did not apply an update")
)

Errors a Hocuspocus server can cause, reported through OnError wrapped with the server's reason.

View Source
var ErrServerSilent = errors.New("client: nothing read, no write progress and no pong within LivenessTimeout")

ErrServerSilent is reported through OnError when the client dropped a connection that stayed silent for LivenessTimeout.

Functions

This section is empty.

Types

type Client

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

Client is a live sync session for one document. Construct with New, start with Connect, stop with Close. Safe for concurrent use.

func New

func New(opts Options) (*Client, error)

New validates opts and returns an unconnected Client.

func (*Client) Awareness

func (c *Client) Awareness() *awareness.Awareness

Awareness returns the awareness instance this client exchanges.

func (*Client) Close

func (c *Client) Close() error

Close stops the connection loop, removes the change observer, and closes the connection. Safe to call more than once and from multiple goroutines; the teardown runs exactly once.

func (*Client) Connect

func (c *Client) Connect(ctx context.Context) error

Connect starts the connection loop and returns immediately. The loop dials, handshakes, relays updates, and reconnects with backoff until ctx is cancelled or Close is called. Calling Connect twice is an error.

func (*Client) Doc

func (c *Client) Doc() *doc.Doc

Doc returns the local document this client syncs.

func (*Client) RemoveAwarenessState

func (c *Client) RemoveAwarenessState()

RemoveAwarenessState clears the local awareness state (peers see the client leave) and broadcasts the removal.

func (*Client) Scope added in v1.36.0

func (c *Client) Scope() string

Scope is the scope the Hocuspocus server granted this connection ("read-write" or "readonly"), or "" before it authenticated and between connections.

func (*Client) SendStateless added in v1.36.0

func (c *Client) SendStateless(payload string) error

SendStateless sends a Hocuspocus stateless message (type 5) to the server's onStateless hook.

func (*Client) SetAwarenessState

func (c *Client) SetAwarenessState(jsonState []byte)

SetAwarenessState sets the local awareness state (a JSON blob, the same convention y-protocols uses) and broadcasts it.

func (*Client) Synced

func (c *Client) Synced() bool

Synced reports whether the last handshake completed and the connection is still up.

func (*Client) Unsynced added in v1.36.0

func (c *Client) Unsynced() int

Unsynced is the number of this client's sync messages a Hocuspocus server has not yet confirmed applying, as the provider's unsyncedChanges counts them: 1 at every connect (the reply to the server's SyncStep1), one more per update sent, one less per SyncStatus that says applied. 0 means the server has everything this client sent. A refused update stays counted. Always 0 outside Hocuspocus mode.

type HTTPSync added in v1.54.0

type HTTPSync struct {
	// URL is the document's URL: where HTTPSyncHandler is mounted, with the
	// document's name.
	URL string
	// Client sends the requests; nil is http.DefaultClient.
	Client *http.Client
	// Header is added to every request (an Authorization header, say).
	Header http.Header
	// V2 pulls V2 updates (POST bodies are V1).
	V2 bool
	// contains filtered or unexported fields
}

HTTPSync syncs a document with a ygo server's HTTPSyncHandler by plain requests, for clients that cannot keep a WebSocket open: each Sync pulls what the server has that the document lacks, then pushes what the document has that the server lacks.

It watches the document for local changes from the first Sync on (Close stops that), so it pushes only when there is something to push: a local change since the last push, a pending buffer other than the one last pushed (updates that wait for something, which no change event reports), or structs the server's state vector does not cover. It keeps the ETag of the last response it applied and sends it, so a pull of an unchanged document costs a 304. A Sync with another document, or after URL changed, starts afresh. An HTTPSync is safe for concurrent use; Syncs run one at a time.

func (*HTTPSync) Close added in v1.54.0

func (h *HTTPSync) Close()

Close stops watching the document.

func (*HTTPSync) Sync added in v1.54.0

func (h *HTTPSync) Sync(ctx context.Context, d *doc.Doc) (changed bool, err error)

Sync pulls then pushes. changed reports whether what the server sent changed d.

type HTTPSyncOrigin added in v1.54.0

type HTTPSyncOrigin struct{ URL string }

HTTPSyncOrigin is the origin of the transactions HTTPSync applies the server's updates in.

type Options

type Options struct {
	// URL is the server base, e.g. "ws://localhost:8080" or
	// "wss://collab.example.com". The document name is appended as
	// the URL path (y-websocket convention); in Hocuspocus mode the
	// URL is dialed as given, without a trailing slash, and the
	// document name goes in every frame.
	URL string

	// Hocuspocus selects the Hocuspocus protocol: every frame starts
	// with the document name, the connection opens with an Auth frame
	// carrying the token, the server confirms each update with a
	// SyncStatus, and Close tells the server the client is done with
	// the document. For @hocuspocus/server 2, 3 and 4; yserve does not
	// serve it.
	Hocuspocus bool

	// Token is the token a Hocuspocus server's onAuthenticate gets ("" by
	// default, as providers send). TokenFunc, when set, is asked instead
	// once each connection is up, as the provider asks its token function,
	// and whenever the server asks for the token again. It must return when
	// its context ends (with the connection, or on Close), and well within
	// the server's pre-auth timeout (30 s for server 2). An error from it
	// ends that attempt, and the next dial waits at least 30 seconds, as
	// after a denial. A refresh can overlap the next connect's call, so it
	// must be safe to call concurrently; Close does not wait for a refresh
	// in flight.
	Token     string
	TokenFunc func(ctx context.Context) (string, error)

	// OnAuthenticated fires when a Hocuspocus server accepts the token,
	// with the scope it granted ("read-write" or "readonly"), on every
	// connect.
	OnAuthenticated func(scope string)

	// OnStateless gets the payload of each stateless message (type 5) a
	// Hocuspocus server sends.
	OnStateless func(payload string)

	// DocName addresses the document on the server.
	DocName string

	// Doc is the local document the client syncs. When nil a fresh
	// Doc is created; retrieve it via Client.Doc.
	Doc *doc.Doc

	// Awareness optionally carries per-client ephemeral state
	// (cursor, name). When nil a fresh Awareness bound to the Doc's
	// clientID is created.
	Awareness *awareness.Awareness

	// OnSynced fires on synced-state transitions: true after each
	// completed handshake, false on every disconnect. Called from the
	// client's goroutines; keep it fast and do not call back into
	// blocking Client methods.
	OnSynced func(synced bool)

	// OnError observes non-fatal connection errors (dial failures,
	// dropped connections). The client keeps reconnecting regardless.
	// It runs on the client's goroutines: keep it fast, and do not call
	// Close from it directly (Close waits for those goroutines); use
	// go c.Close().
	//
	// OnError and OnSynced may be invoked concurrently from different
	// goroutines (e.g. a local-store write failure overlapping a dial
	// failure), so a callback that mutates shared state must guard it.
	OnError func(err error)

	// MinBackoff / MaxBackoff bound the reconnect backoff. Defaults:
	// 250ms / 10s.
	MinBackoff time.Duration
	MaxBackoff time.Duration

	// AwarenessTimeout is how long peers keep this client's presence
	// without hearing from it. The client renews its state at half of
	// this, checking every tenth of it (at least every 100ms), as
	// y-protocols does. Default 30s, the y-protocols value. Set it to the
	// server's timeout when that is shorter. Do not set it above 30s when
	// JavaScript peers are in the room: y-protocols times out a client it
	// has not heard from for 30 seconds, whatever the server does.
	AwarenessTimeout time.Duration

	// PeerTimeout is how long the client keeps a peer's presence without
	// hearing from it, whether or not the server sends its removal, as
	// y-protocols drops a remote state after outdatedTimeout. Default 30s,
	// that value; peers renew every 15 seconds. It is checked when the
	// client checks its own renewal, so a silent peer goes up to a tenth of
	// AwarenessTimeout (at least 100ms) after PeerTimeout. A negative value
	// keeps peers until the server removes them or the connection closes.
	PeerTimeout time.Duration

	// LivenessTimeout bounds how long a connection that died without a
	// FIN or RST (a phone that changed networks, a NAT that dropped the
	// mapping, a server that hangs) goes unnoticed. The client drops the
	// connection and reconnects, as y-websocket does after 30 seconds
	// without a message, once nothing came from the server for this long,
	// nothing it wrote made progress, and a WebSocket ping sent after half
	// of it got no pong. OnError then gets ErrServerSilent, or the read
	// error when the ping's own write blocked for 5 seconds and the
	// WebSocket library closed the connection first. While the client is
	// busy with a frame it read (a large update applying, a callback that
	// blocks), the check waits, since what the server sent meanwhile lies
	// unread; a write of which the kernel takes no 16 KiB chunk for the
	// whole timeout, with nothing read for half of it, drops the
	// connection all the same.
	//
	// Progress is counted in bytes on the TCP connection, so a transfer
	// slower than the timeout is not cut. On the write side it is the
	// kernel taking bytes into the socket's send buffer, which a dead path
	// does too until the buffer is full: a client that keeps writing is
	// dropped only after that. Pings go out whenever nothing was read for
	// half the timeout, in a quiet room about every 15 seconds.
	//
	// Default 30s; a shorter value below 1s is raised to 1s. A negative
	// value turns the check off, unlike the other durations here, where a
	// negative value means the default. With the check on, the dial is
	// bounded by the timeout too. The check is also off on js/wasm, where
	// the browser's WebSocket has no ping, and when http.DefaultTransport
	// is not an *http.Transport: the client counts bytes on the
	// connections of a clone of it, dialed with its dialers. A server that
	// answers no pings and sends nothing for the timeout is reconnected to
	// each time.
	LivenessTimeout time.Duration

	// LocalStore, when set, makes the client offline-first: on Connect
	// the document loads its persisted state from the store (so it is
	// usable before any network), every subsequent change (local edit
	// or applied remote update) is persisted, and on reconnect the
	// handshake carries any edits made while offline up to the server.
	// Keyed by DocName. A pure-Go on-device sqlite store
	// (persist/sqlite) is the typical mobile choice. nil disables
	// local persistence; the document lives only in memory.
	LocalStore persist.Store
}

Options configures a Client. URL and DocName are required; the zero value of every other field selects a sensible default.

Jump to

Keyboard shortcuts

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