events

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Oct 12, 2026 License: Apache-2.0 Imports: 14 Imported by: 0 modules, 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 events defines the realtime event vocabulary and appends events to the global event log inside a store write transaction.

Index

Constants

View Source
const (
	// ActivityWindow: a user is online while a connection of theirs was
	// active within it, idle while connected without such activity.
	ActivityWindow = 5 * time.Minute
	// OfflineGrace: a user with no connections turns offline only after it,
	// so a reconnect does not flap their presence.
	OfflineGrace = 30 * time.Second
	// PresenceSweepInterval is how often the app calls SweepPresence.
	PresenceSweepInterval = 5 * time.Second
	// PresenceCoalesce is the least gap between two presence.changed events of
	// one user. A change inside the gap is held and published by the first
	// SweepPresence after the gap, carrying the state current at that point.
	PresenceCoalesce = 5 * time.Second
)

Presence timing (plan pipeline step 4).

View Source
const (
	Retention     = 7 * 24 * time.Hour
	PruneInterval = time.Hour
)

Retention of the event log: older events are pruned and a resume point before the oldest retained event gets resync_required.

View Source
const (
	TypeMessageCreated = "message.created"
	TypeMessageUpdated = "message.updated"
	TypeMessageDeleted = "message.deleted"

	TypeReactionAdded   = "reaction.added"
	TypeReactionRemoved = "reaction.removed"

	TypePinAdded   = "pin.added"
	TypePinRemoved = "pin.removed"

	TypeChannelCreated      = "channel.created"
	TypeChannelUpdated      = "channel.updated"
	TypeChannelArchived     = "channel.archived"
	TypeChannelUnarchived   = "channel.unarchived"
	TypeChannelMemberJoined = "channel.member_joined"
	TypeChannelMemberLeft   = "channel.member_left"

	TypeMembershipUpdated = "membership.updated"
	TypeReadUpdated       = "read.updated"
	TypeUserUpdated       = "user.updated"
	TypePresenceChanged   = "presence.changed"
	TypeTyping            = "typing"
	TypeAlertUpdated      = "alert.updated"
	TypeCommandInvoked    = "command.invoked"
	TypeEphemeralMessage  = "ephemeral.message"
	TypeSettingsUpdated   = "settings.updated"
	TypeSessionRevoked    = "session.revoked"
)

Event types (docs/protocol.md). Persisted events carry a seq; ephemeral frames (typing, presence) are sent with seq 0 and never appended.

View Source
const (
	CloseSlowConsumer   = 4008
	CloseSessionRevoked = 4009
	CloseServerReset    = 4010 // factory reset
	CloseContentCleared = 4011

	ReasonSlowConsumer   = "slow_consumer"
	ReasonSessionRevoked = "session_revoked"
	ReasonServerReset    = "server_reset"
	ReasonContentCleared = "content_cleared"
)

WebSocket close codes sent by the server, with their reason strings.

View Source
const QueueSize = 256

QueueSize is the per-connection send queue length. A connection whose queue is full when an event arrives is closed with CloseSlowConsumer; the client resumes from its last seq.

View Source
const TypingInterval = 3 * time.Second

TypingInterval is the minimum gap between two relayed typing signals of one user in one channel; extra signals are dropped. Clients expire a typing indicator 6 s after the last signal.

Variables

View Source
var ErrEphemeral = errors.New("ephemeral event type is never persisted")

ErrEphemeral is returned (wrapped) by Append for ephemeral event types: typing, presence.changed and ephemeral.message are broadcast only.

Types lists every event type.

Functions

func Append

func Append(tx *store.Tx, e Event) (int64, error)

Append inserts e into the events table inside tx and returns its seq. An empty Payload is stored as {}; a zero CreatedAt takes tx.Now(). Seq on the input is ignored. When a Publisher is set on the database, the stored event is published to it after the transaction commits.

func Bounds

func Bounds(ctx context.Context, q Querier) (oldest, head int64, err error)

Bounds returns the oldest retained seq (0 when the log is empty) and the sequence head: the highest seq ever assigned, which survives pruning and matches the bootstrap snapshot's seq_head.

func Count

func Count(ctx context.Context, q Querier, after, upTo int64) (int64, error)

Count returns how many retained events have after < seq <= upTo. Seqs are unique and only the oldest prefix is ever pruned, so the range is fully retained exactly when Count equals upTo-after.

func EncodeFrame

func EncodeFrame(e Event) ([]byte, error)

EncodeFrame renders e as its wire envelope (protocol.Event). Live delivery and replay share it.

func IsEphemeral

func IsEphemeral(t string) bool

IsEphemeral reports whether t is sent as a seq-0 frame only and must never be appended to the event log.

func Known

func Known(t string) bool

Known reports whether t is a defined event type.

func Prune

func Prune(ctx context.Context, db *store.DB, now time.Time) (int64, error)

Prune deletes the events created before now - Retention, oldest first, in transactions of at most 500 rows, and returns how many it deleted. It always removes a prefix of the log (every seq up to the newest expired one), so the retained events stay contiguous even if the clock stepped backwards. Nothing is published.

func SetPublisher

func SetPublisher(db *store.DB, p Publisher)

SetPublisher makes p receive every event appended through db from now on (nil stops publishing). Callers of Append need no changes: Append finds the publisher through the transaction and registers an AfterCommit hook, so a rolled-back transaction publishes nothing.

func Visible

func Visible(v Viewer, e Event, m Membership) bool

Visible reports whether the viewer may receive e. It is the one rule set shared by live delivery and replay (plan pipeline step 2):

  • user-scoped events (read.updated, membership.updated, session.revoked, ephemeral.message) go to the user in e.UserID only; command.invoked goes to the owning app's account, also named by e.UserID;
  • settings.updated goes to everyone;
  • user.updated and presence.changed go to every non-guest, to the user themself and to guests sharing a channel with that user;
  • typing goes to the channel's members except the typist;
  • channel lifecycle (created, updated, archived, unarchived) goes to the members, and for public channels to every non-guest as well;
  • channel.member_left also reaches the departing user;
  • every other channel event goes to the channel's current members.

An app viewer with a channel allowlist never sees events of channels outside it; one marked CommandsOnly sees nothing but its own command.invoked events. Unknown event types are visible to no one.

Types

type Event

type Event struct {
	Seq       int64
	Type      string
	ChannelID string
	UserID    string
	Payload   json.RawMessage
	CreatedAt int64 // unix ms
}

Event is one row of the events table. Empty ChannelID / UserID are stored as NULL; UserID targets a user-scoped event at one user's connections.

func Range

func Range(ctx context.Context, q Querier, after, upTo int64, limit int) ([]Event, error)

Range returns up to limit retained events with after < seq <= upTo, in seq order.

type Frame

type Frame struct {
	Seq  int64
	Data []byte
}

Frame is one encoded server-to-client event frame (a protocol.Event). Seq is 0 for ephemeral frames.

type Hub

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

Hub is the in-process realtime fan-out. Events reach it through Publish: persisted events from the store writer after commit (see SetPublisher), ephemeral ones (typing, presence) from the hub itself. A single dispatcher goroutine delivers them in publish order to the subscriptions allowed to see them (Visible), indexed by user and, through the membership cache, by channel. Publish never blocks.

func NewHub

func NewHub(o HubOptions) *Hub

NewHub starts a hub and registers it as the post-commit publisher of o.DB. Close stops it.

func (*Hub) Close

func (h *Hub) Close()

Close stops the dispatcher; later publishes are dropped. Subscriptions are left to their owners (see the gateway's CloseAll). It is idempotent.

func (*Hub) Membership

func (h *Hub) Membership() *MembershipCache

Membership exposes the hub's live membership cache. It is the entry point the reset lifecycle uses to call InvalidateAll once the content is wiped.

func (*Hub) Online

func (h *Hub) Online(userID string) bool

Online reports whether userID is online right now (a connection with activity within ActivityWindow; idle and offline users are not). The notification rules use it for @here.

func (*Hub) PresenceSnapshot

func (h *Hub) PresenceSnapshot(v Viewer) []Frame

PresenceSnapshot returns presence.changed frames (seq 0) for every non-offline user v may see, sorted by user id. A new connection sends it after its replay; users not listed are offline.

func (*Hub) Publish

func (h *Hub) Publish(e Event)

Publish queues e for delivery. It never blocks: it is called on the store writer goroutine after each commit, in seq order.

func (*Hub) Subscribe

func (h *Hub) Subscribe(v Viewer, sessionID string, closeFn func(code int, reason string)) *Subscription

Subscribe registers a connection of v (cookie session sessionID, "" for bearer principals). From the moment it returns, every event published and visible to v is queued on Frames. closeFn is called at most once, from the dispatcher, when the hub ends the subscription (slow consumer, revoked session or token, deactivated user, CloseAll); it must not block. A bearer subscription whose token expires is closed from a timer at that instant, so closeFn may also run from that timer's goroutine.

func (*Hub) Subscribers

func (h *Hub) Subscribers(userID string) int

Subscribers returns the number of live subscriptions of userID, or of everyone when userID is "".

func (*Hub) SweepPresence

func (h *Hub) SweepPresence()

SweepPresence re-evaluates every connected or recently disconnected user (online -> idle after ActivityWindow, -> offline after OfflineGrace), flushes presence changes held by PresenceCoalesce, and forgets expired typing, coalescing and focus records. The app calls it every PresenceSweepInterval.

func (*Hub) UserFocusedRecently

func (h *Hub) UserFocusedRecently(userID string, within time.Duration) bool

UserFocusedRecently reports whether userID has a connection whose window is visible now, or had one within the last within (Web Push suppression).

type HubOptions

type HubOptions struct {
	// DB is the database whose appended events the hub publishes; its read
	// pool backs the membership cache. Required.
	DB *store.DB
	// Now is the presence, typing and focus clock; nil means time.Now.
	Now func() time.Time
	// Logger receives membership load failures; nil discards them.
	Logger *slog.Logger
}

HubOptions configures NewHub.

type Membership

type Membership interface {
	// ChannelKind returns the channel's kind, or "" when it is unknown.
	ChannelKind(channelID string) string
	// IsMember reports whether userID currently belongs to channelID.
	IsMember(channelID, userID string) bool
	// SharesChannel reports whether a and b are members of a common channel.
	SharesChannel(a, b string) bool
}

Membership answers the channel questions visibility asks. The hub keeps a long-lived cached implementation; a replay builds a fresh one so it sees the current state of the database.

Invariant the cache relies on: every write to channels or memberships must be committed together with an event of type channel.created, channel.member_joined, channel.member_left or membership.updated (whichever describes it). The hub invalidates the affected entries when such an event passes through it, so a write without one leaves the cache stale.

type MembershipCache

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

MembershipCache is a Membership loaded lazily from the read pool and memoized in two LRU maps capped at maxCachedChannels and maxCachedUsers. The hub owns one for its lifetime and invalidates entries as membership events pass through it; a replay uses a fresh one. Channels that do not exist are never memoized, so random ids cannot grow the cache. Load errors fail closed (not a member) and are not cached. Safe for concurrent use.

func NewMembershipCache

func NewMembershipCache(ctx context.Context, db *sql.DB, logger *slog.Logger) *MembershipCache

NewMembershipCache returns an empty cache over the read pool db. ctx bounds every load; logger may be nil.

func (*MembershipCache) ChannelKind

func (c *MembershipCache) ChannelKind(channelID string) string

ChannelKind implements Membership.

func (*MembershipCache) InvalidateAll

func (c *MembershipCache) InvalidateAll()

InvalidateAll empties the cache. The reset lifecycle calls it after the content is wiped, so no membership survives the reset.

func (*MembershipCache) InvalidateChannel

func (c *MembershipCache) InvalidateChannel(channelID string)

InvalidateChannel drops the cached state of channelID.

func (*MembershipCache) InvalidateUser

func (c *MembershipCache) InvalidateUser(userID string)

InvalidateUser drops the cached channel list of userID.

func (*MembershipCache) IsMember

func (c *MembershipCache) IsMember(channelID, userID string) bool

IsMember implements Membership.

func (*MembershipCache) Members

func (c *MembershipCache) Members(channelID string) []string

Members returns the current member ids of channelID.

func (*MembershipCache) SharesChannel

func (c *MembershipCache) SharesChannel(a, b string) bool

SharesChannel implements Membership.

type MultiPublisher

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

MultiPublisher hands every event to several Publishers, in the order they were given. Install it with SetPublisher to let the notification dispatcher see the events the hub sees. Each Publisher must not block (see Publisher), so the writer goroutine is never held up by a slow consumer.

func NewMultiPublisher

func NewMultiPublisher(ps ...Publisher) *MultiPublisher

NewMultiPublisher returns a Publisher that forwards to ps. nil entries are skipped. The set is fixed at construction.

func (*MultiPublisher) Publish

func (m *MultiPublisher) Publish(e Event)

Publish forwards e to every Publisher.

type Publisher

type Publisher interface {
	Publish(e Event)
}

Publisher receives every appended event after its transaction commits. Publish runs on the store writer goroutine, in commit (= seq) order, and must never block.

type Querier

type Querier interface {
	QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error)
	QueryRowContext(ctx context.Context, query string, args ...any) *sql.Row
}

Querier is the read side shared by *sql.DB and *sql.Tx.

type Subscription

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

Subscription is one realtime connection registered with the hub.

func (*Subscription) Close

func (s *Subscription) Close(code int, reason string)

Close ends the subscription and calls its closeFn with code and reason. Only the first Close or Leave has an effect.

func (*Subscription) Focus

func (s *Subscription) Focus(visible bool)

Focus records whether the connection's window is visible and focused (channelID is informational). Becoming visible counts as activity.

func (*Subscription) Frames

func (s *Subscription) Frames() <-chan Frame

Frames is the subscription's send queue (QueueSize). It is never closed.

func (*Subscription) Leave

func (s *Subscription) Leave()

Leave ends the subscription without calling closeFn (the connection is already going away).

func (*Subscription) SetPresence

func (s *Subscription) SetPresence(state string)

SetPresence records a client presence report: protocol.PresenceActive (user activity now) or protocol.PresenceIdle.

func (*Subscription) Typing

func (s *Subscription) Typing(channelID string)

Typing relays a typing signal for channelID to the channel's other members as an ephemeral (seq 0) typing event, at most once per TypingInterval per user and channel. The sender must be a member of the channel: unknown, foreign or disallowed channels are dropped silently before any throttle state is touched or anything is published. Typing counts as activity.

func (*Subscription) Viewer

func (s *Subscription) Viewer() Viewer

Viewer returns the subscription's current viewer.

type Viewer

type Viewer struct {
	UserID string
	// Role is protocol.RoleAdmin, RoleMember or RoleGuest.
	Role string
	// Kind is protocol.KindHuman or KindApp.
	Kind string
	// ChannelIDs is an app token's channel allowlist; nil means the
	// principal has none and only membership decides.
	ChannelIDs []string
	// CommandsOnly limits an app viewer to the command.invoked events of its
	// own commands: an app token without the events:read scope receives no
	// channel events at all.
	CommandsOnly bool
	// NoContent withholds the events that carry message bodies (message.created,
	// message.updated, pin.added, alert.updated): an app token needs messages:read
	// as well as events:read to see them.
	NoContent bool
	// TokenID and AppID identify the app token behind a bearer connection
	// (empty for cookie sessions). A session.revoked event naming the token,
	// or the app, closes the connection.
	TokenID string
	AppID   string
	// TokenExpiresAt is the token's expiry in unix ms; 0 means it never
	// expires. The hub closes the connection at that instant.
	TokenExpiresAt int64
}

Viewer is the identity events are delivered to: the account behind one realtime connection.

Jump to

Keyboard shortcuts

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