presence

package
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Oct 29, 2026 License: MIT Imports: 7 Imported by: 0

Documentation

Overview

Package presence carries the sync engine's ephemeral plane: the state that only matters while someone is connected. Cursors, selections, "who is viewing this", typing indicators. None of it is stored, none of it is replayed, and none of it touches the mutation log.

Bus is the seam a multi-node deployment plugs a shared implementation into, installed with server.WithPresenceBus; presencetest.Conformance is the behavior suite such an implementation must pass, and pgpresence is one over Postgres LISTEN/NOTIFY. Local is strictly single-node: an event published on one process never reaches watchers on another, so a two-node deployment left on the default shows each node only the participants it is itself serving.

At most once

Delivery carries no guarantee. An event the bus could not hand over — a watcher that is not reading, a broker that dropped it, a payload that did not fit — is gone, and nothing replays it.

Presence survives that because it is soft state rather than a change log: Registry re-announces every record it is responsible for on a fixed interval, and drops a record nobody has re-announced within the expiry window. A lost update is therefore corrected within one announce interval, and a session whose process died is forgotten without anything having to notice it die. That is what lets the plane run with no TTL table, no GC horizon and no storage of any kind.

A broadcast message has no such backstop. It reaches whoever is watching at the moment it arrives and nobody else, which is the whole contract; an app that cannot lose one writes a row instead.

Index

Constants

View Source
const DefaultAnnounce = 5 * time.Second

DefaultAnnounce is the interval a Registry re-announces its own records on, and the unit its expiry window is a multiple of.

It is the knob the whole plane's feel hangs off. Shorter makes a departure that was never announced — a killed tab, a lost connection — disappear sooner, and costs one bus event per local record per interval. Longer costs less and leaves ghosts on screen for longer. It must also stay comfortably under the window a client's own reconnect takes, or a watcher that reconnects mid-interval sees the room empty until the next sweep.

View Source
const DefaultMaxParticipants = 128

DefaultMaxParticipants caps the records a Registry keeps per room.

Variables

View Source
var ErrClosed = errors.New("presence: registry is closed")

ErrClosed is returned by a Registry whose Close has run.

Functions

This section is empty.

Types

type Bus

type Bus interface {
	Publish(ctx context.Context, ev Event) error
	Subscribe(topic Topic) (<-chan Event, func())
}

Bus fans presence events out to every node serving a topic.

What an implementation must guarantee

Publish must not block on a watcher that is not reading; a bus that cannot deliver drops instead, and drops are expected (see the package doc). Publish returns an error only when the event could not be ACCEPTED at all — an oversize payload, a broker that is down — so a caller can surface the failure to the publisher rather than have it disappear silently.

Subscribe returns a channel of events for exactly one topic and a cancel func. The channel is closed after cancel, and cancel is idempotent. A subscriber sees events published on any node, including its own, and including its own publishes.

An implementation MAY coalesce KindState events for one (topic, session, issuer, subject) down to the one with the highest revision, keeping the later of two equal revisions, because a receiver keeps only the highest anyway. It must NOT keep a lower revision in place of a higher one — events do not always arrive in revision order — and must NOT fold together events of two issuers or two subjects, because a receiver keeps a record for the issuer and subject that wrote it. It must NOT coalesce KindMessage events, which are each distinct — it may only drop them.

Every method is safe for concurrent use.

type Event

type Event struct {
	Topic Topic
	Kind  Kind
	// Participant is the session the event concerns. KindState carries the
	// whole record; KindLeave and KindMessage set only SessionID, Issuer and
	// Subject, naming the departing session and the sender respectively.
	Participant Participant
	// Payload is the broadcast body, set only for KindMessage.
	Payload []byte
}

Event is one thing that happened in one topic.

Ordering

There is no ordering across topics, and none between the presence plane and the mutation log. Within one topic, two KindState events for the same session are ordered by Participant.Revision, which the publisher mints and increments per (session, topic): a receiver keeps the highest revision it has seen and discards anything lower. That is what lets a bus reorder, re-deliver or coalesce state without the roster flickering.

A KindLeave carries no revision, so it is not ordered against the state it supersedes. A leave that overtakes a later state of the same session removes a record that is still live — and the next announce puts it back, which is the window the design accepts rather than the guarantee it makes.

type Kind

type Kind uint8

Kind discriminates what an Event says.

const (
	// KindState writes or refreshes one session's record in the topic. A
	// re-announcement is one of these, carrying the revision the state was
	// first published with.
	KindState Kind = iota
	// KindLeave withdraws one session from the topic. It carries no state.
	KindLeave
	// KindMessage is a broadcast: a payload for whoever is watching now.
	KindMessage
)

func (Kind) String

func (k Kind) String() string

type Local

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

Local is an in-process Bus: events reach subscribers in this process and nowhere else. It is the default, and the right one for a single-node deployment.

func NewLocal

func NewLocal() *Local

NewLocal returns an in-process Bus.

func (*Local) Publish

func (l *Local) Publish(_ context.Context, ev Event) error

Publish hands the event to every subscriber of its topic. It never blocks and never fails.

func (*Local) Subscribe

func (l *Local) Subscribe(topic Topic) (<-chan Event, func())

Subscribe returns this topic's event channel and its teardown.

type Options

type Options struct {
	// Announce is the re-announce interval; see DefaultAnnounce. Zero or
	// negative takes the default.
	Announce time.Duration
	// MaxParticipants caps the records kept per room. Zero or negative takes
	// DefaultMaxParticipants. Beyond it a room keeps the lowest session ids and
	// reports itself truncated — lowest rather than newest so that two nodes
	// holding the same over-full room keep the same participants, and every
	// watcher is shown the same prefix.
	MaxParticipants int
	// Now reads the current time, and is the only clock a Registry consults.
	// Nil takes time.Now.
	Now func() time.Time
	// WorkspacePrefix partitions this Registry's share of a shared Bus: it is
	// prepended to every topic's workspace id on the way to the bus and
	// removed from every event taken off it, and an event whose topic does not
	// carry it is dropped. Empty — the default — is a Registry that owns the
	// whole bus.
	//
	// It is how a host serving several applications over one bus keeps rooms
	// with the same workspace id apart, so that the bus itself needs no notion
	// of an application. The prefix must end in a separator no workspace id
	// can contain.
	//
	// Topics are bare on every other side of the Registry: what a caller
	// joins, publishes and reads off a Watch is the topic it named.
	WorkspacePrefix string
}

Options configures a Registry. The zero value is valid and takes every default.

type Participant

type Participant struct {
	// SessionID identifies the publishing session. It is the identity every
	// other field hangs off: records are keyed by it, a departure names it, and
	// an expiry is measured per session.
	SessionID string
	// Issuer is the issuer of the publishing principal, stamped by the server
	// with Subject. Empty when the principal names no issuer. A bus must carry
	// it verbatim and must never let a payload set it. It never reaches a
	// client.
	Issuer string
	// Subject is who is publishing, stamped by the server from the request
	// principal. Empty when the publisher was unauthenticated. A bus must carry
	// it verbatim and must never let a payload set it.
	Subject string
	// State is the app's own bytes, opaque to the engine and to the bus.
	State []byte
	// Revision orders two deliveries of the same session's state in the same
	// topic; see Event for the rule.
	Revision uint64
	// Seq is the workspace sequence the state was authored against, as the
	// publisher last saw it. 0 means the publisher did not say.
	Seq uint64
}

Participant is one session's record in one room.

type Registry

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

Registry is one node's view of the rooms it is serving, and the state machine that keeps that view honest without storing anything.

It holds a record per (topic, session) it has heard about, subscribes to the bus once per topic however many local streams watch it, and fans what arrives out to those streams. Sweep is the whole liveness mechanism: it re-announces the records of sessions whose Watch stream this node holds, and drops records nobody has re-announced within the expiry window, reporting them as departures. Nothing else expires anything, and nothing is persisted.

A Registry is safe for concurrent use. It reads the clock only through Options.Now, so expiry and re-announcement advance on the caller's clock rather than on wall time.

func NewRegistry

func NewRegistry(bus Bus, opts Options) *Registry

NewRegistry returns a Registry fanning out over bus.

func (*Registry) Announce

func (r *Registry) Announce() time.Duration

Announce reports the re-announce interval in force, which is also the interval Sweep is meant to be called on.

func (*Registry) Close

func (r *Registry) Close()

Close releases every bus subscription and closes every open Watch. It is idempotent, and a Registry does not come back.

func (*Registry) MaxParticipants

func (r *Registry) MaxParticipants() int

MaxParticipants reports the per-room record cap in force.

func (*Registry) Open

func (r *Registry) Open(issuer, subject, sessionID string, fronted ...string) *Watch

Open registers a stream that the principal of issuer and subject opened for sessionID, plus any further sessions it is responsible for. Those ids are what records are keyed on, and holding them here is what makes this node re-announce them.

The stream keeps alive only the records written under the same issuer and subject. A session id is shown to every watcher of a room, so naming one is no proof of owning it: a stream that names a session whose record another owner wrote does not re-announce that record, and the record expires when its owner's streams are gone. Two issuers' principals with one subject are two owners.

A browser shares one stream across an account's tabs and the tabs that are not holding it still publish, so fronting several sessions is the normal case rather than an exception; a session named by nobody's stream is forgotten within the expiry window.

The returned Watch must be closed when the stream ends; leaving it open leaves this node re-announcing records for sessions that are gone.

func (*Registry) Publish

func (r *Registry) Publish(ctx context.Context, ev Event) error

Publish sends an event to every node serving its topic, this one included. The event comes back through the bus subscription rather than being applied here, so a publisher's own node updates on exactly the path every other node does.

It returns the bus's error when the event could not be accepted at all; a successful return means the event was handed over, not that anybody received it.

func (*Registry) Sweep

func (r *Registry) Sweep(ctx context.Context)

Sweep advances the liveness machinery to now. It is meant to be called every Announce interval, and does two things in one pass:

  • Re-announces every record whose session has a Watch stream on this node opened by the record's owner, its issuer and subject, so the other nodes keep it alive. The record's own revision is carried unchanged, so an announcement that overtakes a newer state is discarded by revision rather than winning.
  • Drops every record that has gone an expiry window without being written or re-announced, reporting it to local watchers as a departure.

A record this node owns is also refreshed locally, so a bus that dropped the announcement costs the other nodes their view of it and not this one's.

Publishing happens with r's lock released, so a slow bus delays the next sweep rather than blocking every join and publish behind it.

type Topic

type Topic struct {
	WorkspaceID string
	Name        string
	Entity      string
	Key         string
}

Topic addresses one room. It is comparable, so it is usable as a map key — which is how a Registry and a Bus index their subscriptions.

A topic is either ANCHORED to a row (Entity and Key both set) or not (both empty). The distinction is an authorization one and belongs to the server: an anchored topic admits only callers who could read the row it names. The bus treats the four fields as an opaque address.

func (Topic) Anchored

func (t Topic) Anchored() bool

Anchored reports whether the topic names a row.

func (Topic) String

func (t Topic) String() string

String renders a topic for logs. Anchored topics read as `ws/name@entity/key`.

func (Topic) Validate

func (t Topic) Validate() error

Validate checks the topic's shape: a valid workspace id, a valid room name, and an anchor that is either complete or absent. It does NOT check that the entity is registered or that the row exists — those are the server's questions, asked at the join gate.

type Watch

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

Watch is one Watch stream's registration with a Registry: the topics it has joined and the single channel every frame for them arrives on.

Events is the channel the stream's tail loop selects on. It is closed when Close runs or the Registry shuts down, which is how a stream learns to end.

func (*Watch) Close

func (w *Watch) Close()

Close releases every topic this stream joined and closes Events. It is idempotent.

func (*Watch) Dropped

func (w *Watch) Dropped() uint64

Dropped reports how many events this stream's outbox has discarded because the stream was not reading fast enough.

func (*Watch) Events

func (w *Watch) Events() <-chan Event

Events carries every frame for every topic this stream has joined. It is closed on Close.

func (*Watch) Join

func (w *Watch) Join(topic Topic) (participants []Participant, truncated bool, err error)

Join adds a topic to this stream and returns the node's current roster for it, ordered by session id, together with whether the room has turned participants away for the cap.

The roster is what this node knows, which is the sessions whose streams it holds plus whatever the bus has told it. A node that has just created the room sees an empty one until the other nodes' next announce.

Joining a topic twice is a no-op that still returns the roster.

func (*Watch) Joined

func (w *Watch) Joined(topic Topic) bool

Joined reports whether this stream currently holds the topic. It is the cheap answer to "has this session already been admitted here", which a publisher on the same node can rely on instead of re-running the gate.

func (*Watch) Leave

func (w *Watch) Leave(topic Topic)

Leave removes a topic from this stream. The stream stops receiving its frames; the session's RECORD in that room is untouched, and withdrawing it is a Publish of a leave event.

func (*Watch) SessionID

func (w *Watch) SessionID() string

SessionID reports the session that opened this stream. Its records, and those of every session it fronts, are re-announced for as long as it is open.

Directories

Path Synopsis
Package pgpresence implements the ephemeral plane's fan-out over PostgreSQL LISTEN/NOTIFY, so rooms reach clients connected to any node rather than only the one holding a given session's stream.
Package pgpresence implements the ephemeral plane's fan-out over PostgreSQL LISTEN/NOTIFY, so rooms reach clients connected to any node rather than only the one holding a given session's stream.
Package presencetest provides a shared Ginkgo behavior suite every presence.Bus implementation must pass.
Package presencetest provides a shared Ginkgo behavior suite every presence.Bus implementation must pass.

Jump to

Keyboard shortcuts

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