realtime

package
v1.1.2 Latest Latest
Warning

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

Go to latest
Published: Jun 28, 2026 License: MIT Imports: 11 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CheckAccess

func CheckAccess(ctx context.Context, db *pgxpool.Pool, role, table, rowID string) bool

CheckAccess returns true if the authenticated role may read the row identified by rowID in table. It executes:

BEGIN;
SET LOCAL role = {role};
SELECT 1 FROM {table} WHERE id = $1;
ROLLBACK;

The SET LOCAL role applies the caller's JWT role, which activates RLS policies defined for that role. A successful SELECT means the row is visible.

Positive results are cached for 5 seconds per (role, table, rowID) triplet to avoid hammering Postgres with repeated access checks on broadcast storms.

func Handler

func Handler(hub *Hub, jwtSecret string, presenceTrackers map[string]*PresenceTracker, mu interface {
	Lock()
	Unlock()
}) http.Handler

Handler returns an http.Handler for the /realtime/v1/ endpoint. It upgrades incoming requests to WebSocket and handles:

  • "auth" event: client sends JWT; verified before routing begins
  • "subscribe" event: client subscribes to a Postgres NOTIFY channel
  • "broadcast" event: client sends a message to all subscribers of a topic
  • "presence:join" event: client joins the presence set of a topic
  • "presence:leave" event: client leaves the presence set

jwtSecret is the GoTrue JWT secret used to verify access tokens. hub routes notifications to subscribers. presenceTrackers is a map of channel → *PresenceTracker (created lazily per channel in the calling code).

func LivenessHandler

func LivenessHandler() http.HandlerFunc

LivenessHandler returns a GET-only handler for HTTP health checks (no WebSocket upgrade). Mounted at /realtime/v1/health when the realtime hub is enabled.

Types

type Hub

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

Hub routes notifications from Postgres to subscribed WebSocket clients. It is safe for concurrent use.

func NewHub

func NewHub() *Hub

NewHub creates an empty Hub.

func (*Hub) Broadcast

func (h *Hub) Broadcast(channel string, payload []byte)

Broadcast sends payload to all subscribers of channel. Non-blocking: if a subscriber's send buffer is full, the message is dropped with no error (slow consumers should be disconnected by the handler's write timeout).

func (*Hub) ChannelCount

func (h *Hub) ChannelCount() int

ChannelCount returns the number of active channels with at least one subscriber.

func (*Hub) Subscribe

func (h *Hub) Subscribe(s *Subscriber, channel string)

Subscribe registers s as a subscriber for channel.

func (*Hub) Unsubscribe

func (h *Hub) Unsubscribe(s *Subscriber)

Unsubscribe removes s from its channel's subscriber list.

type ListenPool

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

ListenPool maintains a dedicated set of pgx connections for LISTEN/NOTIFY. These connections are NOT shared with the main request pool because LISTEN state is per-connection and must not be reused for regular queries.

func NewListenPool

func NewListenPool(connString string, size int) *ListenPool

NewListenPool creates a ListenPool with size dedicated connections. connString is a libpq-compatible DSN (e.g. "postgres://user:pass@host/db"). Call Start(ctx) to open connections and begin listening.

func (*ListenPool) Listen

func (p *ListenPool) Listen(ctx context.Context, channel string) error

Listen adds a LISTEN on channel across all pool connections.

func (*ListenPool) Notifications

func (p *ListenPool) Notifications() <-chan Notification

Notifications returns the channel on which received notifications are sent. Consumers should read from this channel continuously; a slow consumer will cause the channel buffer to fill and notifications to be dropped with a log warning.

func (*ListenPool) Start

func (p *ListenPool) Start(ctx context.Context, channels []string) error

Start opens the pool connections and begins listening. Returns an error if any connection fails to open. All connections are closed when ctx is cancelled.

type Notification

type Notification struct {
	Channel string
	Payload string
}

Notification is a single LISTEN/NOTIFY payload received from Postgres.

type PresenceEntry

type PresenceEntry struct {
	Key       string        `json:"key"`
	State     PresenceState `json:"state"`
	JoinedAt  time.Time     `json:"joined_at"`
	UpdatedAt time.Time     `json:"updated_at"`
}

PresenceEntry represents one client's presence in a channel.

type PresenceEvent

type PresenceEvent struct {
	Event   string          `json:"event"` // "presence" always
	Topic   string          `json:"topic"`
	Payload PresencePayload `json:"payload"`
}

PresenceEvent is the payload broadcast when the presence set changes.

type PresencePayload

type PresencePayload struct {
	Joins  map[string]PresenceEntry `json:"joins,omitempty"`
	Leaves map[string]PresenceEntry `json:"leaves,omitempty"`
}

PresencePayload contains joins and leaves for a single presence delta.

type PresenceState

type PresenceState map[string]interface{}

PresenceState is the user-supplied metadata for a presence entry.

type PresenceTracker

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

PresenceTracker maintains the presence set for a channel and broadcasts join/leave diffs to the Hub.

func NewPresenceTracker

func NewPresenceTracker(channel string, hub *Hub) *PresenceTracker

NewPresenceTracker creates a tracker for channel, broadcasting via hub.

func (*PresenceTracker) Join

func (pt *PresenceTracker) Join(key string, state PresenceState)

Join adds or updates a presence entry for key with state. A "presence" event containing the join diff is broadcast to all subscribers.

func (*PresenceTracker) Leave

func (pt *PresenceTracker) Leave(key string)

Leave removes the presence entry for key and broadcasts the leave diff.

func (*PresenceTracker) State

func (pt *PresenceTracker) State() map[string]PresenceEntry

State returns a snapshot of all current presence entries.

type Subscriber

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

Subscriber represents a connected WebSocket client listening on one channel.

Jump to

Keyboard shortcuts

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