pgpresence

package
v0.10.0 Latest Latest
Warning

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

Go to latest
Published: Nov 20, 2026 License: MIT Imports: 10 Imported by: 0

Documentation

Overview

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.

Install it with server.WithPresenceBus. It is independent of which storage adapter is in use, and a deployment reaching for a second node usually already has a Postgres — which is what makes this cheaper than standing up NATS or Redis for the same job.

What it does and does not guarantee

Delivery is at most once, which is the seam's contract rather than a shortcut taken here — see engine/presence. Three places lean on that licence: a full publish queue drops rather than blocks, an event published while the listener is reconnecting is gone (Postgres buffers nothing across a dropped LISTEN), and a subscriber that is not reading loses what overflows its queue.

Presence heals from all three within one announce interval, because a record is re-announced by the node holding its session's stream rather than replayed from anywhere. Broadcast messages do not heal, and an app that cannot lose one writes a row instead.

The one failure that is NOT silent is an oversize payload. Postgres caps a NOTIFY payload at 8000 bytes and the state travels base64-encoded inside it, so an event that will not fit is refused at Publish — the publisher learns its state is too large instead of watching it vanish on every node but its own. The engine caps state and message size at the RPC boundary (Limits.MaxPresenceStateBytes, Limits.MaxBroadcastBytes) well under this, so reaching it means those limits were raised past what the transport can carry.

Shape

Publish does two things: it fans out LOCALLY first, then queues a pg_notify. The local half keeps same-node latency off the database round trip; the remote half reaches the other nodes. Every payload carries the publishing node's id and a node discards its own events on the way back in, because — unlike a content-free poke — delivering a broadcast twice would show it twice.

The transport underneath is engine/pglisten: one connection parked on the channel, one issuing pg_notify, and the reconnect loop over both. What arrives feeds a presence.Local.

Open dials its own transport. A deployment that also runs pgnotify passes both a shared one instead, halving the connections either would open alone:

link, err := pglisten.Open(ctx, dsn)
...
defer link.Close()
bus, err := pgpresence.New(ctx, link)

Hosting several applications

One bus serves every app a server.Manager hosts. Each app's room registry prefixes the workspace id of every topic it puts on the bus with its own share of the id space, so two apps that both have a workspace "team" do not serve each other's rooms and this package needs no notion of an app:

b, err := pgpresence.Open(ctx, dsn)
...
server.NewManager(ctx, root, server.WithServerOptions(server.WithPresenceBus(b)))

Index

Constants

View Source
const DefaultChannel = "syncplane_presence"

DefaultChannel is the LISTEN/NOTIFY channel used unless WithChannel says otherwise. One channel carries every topic of every app on it; the payload's routing prefix separates them.

It differs from pgnotify's channel so the two can share one transport: a pglisten.Conn delivers a payload only to the listener registered for its channel, so neither package ever sees the other's traffic.

Variables

This section is empty.

Functions

This section is empty.

Types

type Bus

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

Bus is a presence.Bus backed by LISTEN/NOTIFY. It holds the transport, the publisher goroutine and the node-local fan-out.

func New

func New(ctx context.Context, link *pglisten.Conn, opts ...Option) (*Bus, error)

New builds a bus on an existing transport, so a process also running pgnotify opens one pair of connections rather than two.

New blocks until the channel is subscribed, which spans a reconnect if the database is down; ctx bounds that wait. link must outlive the bus — Close stops publishing and delivery but leaves the transport running.

func Open

func Open(ctx context.Context, dsn string, opts ...Option) (*Bus, error)

Open connects to the Postgres named by dsn and starts listening, on a transport of its own that Close takes down with it.

The listener connection is established before returning, so a bad DSN or an unreachable database fails here rather than degrading silently into a bus that never delivers.

func (*Bus) Close

func (b *Bus) Close() error

Close stops publishing and delivery. It is idempotent. A bus from Open closes its transport; one from New leaves the caller's alone.

func (*Bus) Publish

func (b *Bus) Publish(_ context.Context, ev presence.Event) error

Publish fans the event out to this node's subscribers and queues it for the others.

It returns an error only when the event cannot be carried at all — a payload past what a NOTIFY can hold — and then it is delivered nowhere, so a publisher never has to reason about a partial send. Everything else is best-effort by contract.

func (*Bus) Subscribe

func (b *Bus) Subscribe(topic presence.Topic) (<-chan presence.Event, func())

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

type Option

type Option func(*config)

Option configures Open and New.

func WithChannel

func WithChannel(name string) Option

WithChannel sets the LISTEN/NOTIFY channel. Give separate deployments that share one database separate channels, or each will serve the other's rooms. Must match [a-z_][a-z0-9_]*.

func WithLogger

func WithLogger(l *slog.Logger) Option

WithLogger installs the logger used for this package's own trouble — undecodable events, failed publishes. Defaults to slog.Default. Open passes it on to the transport it dials; a transport handed to New keeps whatever logger it was opened with.

Jump to

Keyboard shortcuts

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