presencebridge

package
v0.9.0 Latest Latest
Warning

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

Go to latest
Published: Nov 15, 2026 License: MIT Imports: 13 Imported by: 0

Documentation

Overview

Package presencebridge joins the rooms of a local syncplane engine to the rooms of the origin server it syncs with, so that people connected to the origin and people connected to the local engine see each other's presence and broadcasts.

A Bridge is a presence.Bus. Install it on the local engine with server.WithPresenceBus, wrapping the bus the engine would otherwise use:

origin, _ := client.New("https://origin.example", client.WithInterceptors(auth))
bridge := presencebridge.New(presence.NewLocal(), origin.PresenceService(),
	presencebridge.WithWorkspaces("acme"))
defer bridge.Close()
srv, _ := server.New(store, server.WithPresenceBus(bridge))

What crosses the hop

Upward, every presence update, departure and broadcast published on the local engine in a bridged workspace is published to the origin's PresenceService under the session id it carries locally. The origin stamps every one of them with the principal of the bridge's own connection, so participants from the local engine appear on the origin with the bridge's subject. A session id is claimed by the first local principal that publishes it; publishes naming that session from another local principal are not forwarded.

Downward, the bridge watches the origin for every room in a bridged workspace that has a watcher on the local engine, and relays what it sees to the local engine only. Origin participants and broadcast senders appear locally with the subject the origin reports and with the issuer OriginIssuer. Sessions that the local engine published are left out, so a local participant never comes back as a second participant.

The workspace sequence carried by a presence update is not translated between the two servers; it is cleared on both hops.

Liveness

Presence stays soft state across the hop. Local records reach the origin again with every re-announcement of the local engine and lapse on the origin when those stop. Origin participants are re-announced locally for as long as the origin stream that reported them is up; when it is lost they lapse locally after the local expiry window, and the bridge reconnects with backoff and restores them from the origin's roster. Local presence keeps working while the origin is unreachable.

Delivery is at most once on both hops, as on any presence.Bus. A broadcast sent while the origin is unreachable is lost.

Access on the origin

The origin gates every bridged room on the bridge's principal, not on the local caller's. A room the origin refuses stays local and is retried with backoff, so a room anchored to a row the origin does not hold yet joins once the row arrives. The origin runs its room gate for every forwarded publish, re-announcements included, because the bridge holds no origin stream for the sessions it publishes as.

Limits

A Bridge serves one engine built with server.New. A server.Manager prefixes the workspace ids it puts on its bus, and the bridge would forward them with the prefix. On a local deployment of several nodes over a shared inner bus, install a Bridge on every node: each relays the origin to its own node's rooms only.

Example

A local engine whose rooms in workspace "acme" are joined to the origin's. The origin client carries the credentials the bridge uses on the origin.

package main

import (
	"log"
	"net/http"

	"github.com/levelfourab/syncplane/engine/client"
	"github.com/levelfourab/syncplane/engine/presence"
	"github.com/levelfourab/syncplane/engine/server"
	"github.com/levelfourab/syncplane/engine/storage/sqlitestore"
	"github.com/levelfourab/syncplane/engine/upstream/presencebridge"
)

func main() {
	origin, err := client.New("https://sync.example.com",
		client.WithInterceptors( /* an interceptor that sets the origin credentials */ ))
	if err != nil {
		log.Fatal(err)
	}
	bridge := presencebridge.New(presence.NewLocal(), origin.PresenceService(),
		presencebridge.WithWorkspaces("acme"))
	defer bridge.Close()

	store, err := sqlitestore.Open("local.db")
	if err != nil {
		log.Fatal(err)
	}
	defer store.Close()
	local, err := server.New(store, server.WithPresenceBus(bridge))
	if err != nil {
		log.Fatal(err)
	}
	// Close the engine before the bridge, so no local room outlives it.
	defer local.Close()

	log.Fatal(http.ListenAndServe("127.0.0.1:8787", local.HTTPHandler()))
}

Index

Examples

Constants

View Source
const (
	DefaultMaxTopicsPerStream = 64
	DefaultMaxPublishItems    = 32
	DefaultMinBackoff         = 250 * time.Millisecond
	DefaultMaxBackoff         = 30 * time.Second
)

Default values of the options.

View Source
const OriginIssuer = "syncplane.upstream"

OriginIssuer is the issuer a Bridge puts on every participant and broadcast sender it relays from the origin. Local presence records are owned by issuer and subject together, so a local principal with this issuer could write into the records of origin participants; an authenticator must not issue it.

Variables

This section is empty.

Functions

This section is empty.

Types

type Bridge

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

Bridge is a presence.Bus that joins the rooms of bridged workspaces to the origin's rooms. See the package documentation for what crosses the hop.

Publish and Subscribe never wait for the origin. A Bridge is safe for concurrent use.

func New

New returns a Bridge over inner, the bus the local engine would use without it, that reaches the origin through origin. A nil inner takes presence.NewLocal(). origin carries the bridge's identity on the origin, so it must authenticate as a principal that may watch and publish the bridged rooms; client.Client.PresenceService returns one.

New starts the bridge's goroutines and does not contact the origin. Close stops them. New panics if origin is nil.

func (*Bridge) Close

func (b *Bridge) Close() error

Close stops watching and publishing to the origin, and withdraws every origin participant from the local rooms. It does not close the inner bus, and subscriptions keep delivering its events. After Close the Bridge forwards nothing and watches nothing. Close is idempotent and blocks until the bridge's goroutines have stopped; records already forwarded lapse on the origin after its expiry window.

func (*Bridge) Publish

func (b *Bridge) Publish(ctx context.Context, ev presence.Event) error

Publish hands ev to the inner bus and, when ev's workspace is bridged and the inner bus accepted it, queues it for the origin. It returns the inner bus's error. It never blocks on the origin: when the origin queue is full, the event is not forwarded.

func (*Bridge) Subscribe

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

Subscribe returns the topic's events from the inner bus and, for a bridged workspace, the origin's participants and broadcasts. The first subscription to a bridged topic starts watching it on the origin; the cancel of the last one stops. Events from the origin reach only the subscribers of this Bridge, never the inner bus.

type Option

type Option func(*config)

Option configures New.

func WithAnnounce

func WithAnnounce(d time.Duration) Option

WithAnnounce sets how often the bridge re-announces origin participants locally. It must be at most the local engine's room announce interval (server.WithRoomAnnounce), or origin participants lapse locally while the origin stream is up. Zero or negative takes presence.DefaultAnnounce, which is also the engine's default.

func WithLogger

func WithLogger(l *slog.Logger) Option

WithLogger sets the logger for failed origin calls and lost origin streams. The default is slog.Default.

func WithOriginLimits

func WithOriginLimits(maxTopicsPerStream, maxPublishItems int) Option

WithOriginLimits sets the origin's room limits the bridge must stay within: the rooms one Watch stream may carry (the origin's MaxRoomsPerStream) and the items one Publish may carry (its MaxPublishItems). Zero or negative takes DefaultMaxTopicsPerStream and DefaultMaxPublishItems, which match the engine's defaults. The bridge opens one origin stream per maxTopicsPerStream watched rooms.

func WithReconnectBackoff

func WithReconnectBackoff(minimum, maximum time.Duration) Option

WithReconnectBackoff bounds the wait before the bridge retries a failed origin call: it starts at minimum, doubles per consecutive failure up to maximum, and has jitter. Zero or negative values take DefaultMinBackoff and DefaultMaxBackoff.

func WithWorkspaceFilter

func WithWorkspaceFilter(fn func(workspaceID string) bool) Option

WithWorkspaceFilter bridges the workspaces for which fn returns true. It replaces an earlier WithWorkspaces or WithWorkspaceFilter.

fn is called on every publish and every room subscription, from many goroutines, and must be fast and safe for concurrent use. A room that is already open on the local engine keeps the answer fn gave when the room opened, for its downward half; publishes follow the current answer.

func WithWorkspaces

func WithWorkspaces(ids ...string) Option

WithWorkspaces bridges the named workspaces and no others. It replaces an earlier WithWorkspaces or WithWorkspaceFilter. Without either, every workspace is bridged.

Jump to

Keyboard shortcuts

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