Documentation
¶
Overview ¶
Package pubsub bridges between chalkd instances using Postgres LISTEN/NOTIFY. Sending a message inserts it into the database and emits a NOTIFY in the same transaction; every chalkd instance has a Listener goroutine subscribed to the channel and routes incoming notifications to local handlers for fan-out to connected WebSocket clients.
Phase 06 extended the Event envelope for presence and friend operations. Phase 08 added Kind="channel" (channel_event push) and the ChannelEventPayload field to carry the proto.ChannelSummary.
Event Kind discriminator:
- "message" -- message inserted into a channel; carries MessageID, TS, ChannelID. Published per-channel via PublishMessageWithTx; receivers fetch the row.
- "presence" -- aggregated state change; carries UserID. Published on chalk_global.
- "friend" -- friend op; carries UserID (recipient), FromUserID, and FriendKind (request_received/accepted/declined/removed). Published on chalk_global.
- "channel" -- channel membership change (phase 08); carries UserID (recipient), ChannelID, FriendKind (overloaded as channel-event-kind: added/removed), and ChannelEventPayload (JSON-encoded proto.ChannelSummary). Published on chalk_global so non-members receive it.
Index ¶
- Constants
- func ChannelTopic(channelID uuid.UUID) string
- func PublishEphemeral(ctx context.Context, pool *pgxpool.Pool, ev Event) error
- func PublishMessageWithTx(ctx context.Context, tx pgx.Tx, ev Event) error
- func PublishWithTx(ctx context.Context, tx pgx.Tx, ev Event) error
- type Event
- type Handler
- type Listener
Constants ¶
const Channel = "chalk_global"
Channel is the Postgres NOTIFY channel name for non-channel-scoped events (presence, friend, channel-membership pushes). Per-channel message events use ChannelTopic(channelID) instead.
Variables ¶
This section is empty.
Functions ¶
func ChannelTopic ¶
ChannelTopic returns the Postgres NOTIFY topic name for the given channel ID. Format: "chalk_chan_<uuid-no-dashes>".
Why this shape:
- Prefix "chalk_chan_" lets ops grep for "chalk_*" to see all our topics; distinguishes channel topics from chalk_global.
- UUID with dashes removed is 32 hex chars; prefix is 11; total 43. Well under Postgres' 63-char identifier limit.
- Lowercase letters + digits + underscore only -- safe to use without quoting in LISTEN/UNLISTEN/NOTIFY (the listener still quotes defensively).
The function is deterministic, so any chalkd publishing to channel C and any chalkd subscribed for C will agree on the topic without coordination.
func PublishEphemeral ¶ added in v0.3.45
PublishEphemeral emits a NOTIFY on ev's per-channel topic WITHOUT a transaction (phase 43-2, typing indicators).
This is only correct for events that reference no row. Anything durable must use PublishMessageWithTx so the NOTIFY is delivered at the same COMMIT that inserts the row the receiver will go and fetch -- publish a pointer to a row that hasn't committed yet and receivers race the writer. A typing ping carries its whole meaning in the event and touches no table, so a transaction here would be a BEGIN/COMMIT round trip protecting nothing.
The bare pg_notify runs in its own implicit transaction and is delivered immediately.
func PublishMessageWithTx ¶
PublishMessageWithTx emits a NOTIFY on the per-channel topic for ev's ChannelID, in the same transaction as the message INSERT.
This replaces (for Kind="message" events) the path through PublishWithTx that targeted chalk_global. The wire format of the Event payload is identical -- only the NOTIFY channel name differs -- so listeners that consume both topics use the same dispatch logic.
Phase 06 friend/presence events keep using PublishWithTx (chalk_global). They aren't per-channel scoped, and routing them through a single topic keeps the simple model.
As with PublishWithTx, the row this event refers to MUST be inserted by the same tx; NOTIFY is delivered at COMMIT.
func PublishWithTx ¶
PublishWithTx emits a NOTIFY on chalk_global inside an existing transaction. Use this for presence, friend, and channel-event notifications. Per-channel message events use PublishMessageWithTx (see channel_topics.go).
NOTIFY is delivered at COMMIT; the row(s) referenced in the event MUST be inserted/updated by the same transaction.
Types ¶
type Event ¶
type Event struct {
// Kind discriminates: "message", "presence", "friend", "channel",
// "prefs", "kp_low" (phase 11c-5: KeyPackage low-stock push; UserID
// is the device owner to notify), "message_deleted" (phase 26: a
// message was soft-deleted; reuses the message fields MessageID, TS,
// ChannelID and is published per-channel via PublishMessageWithTx --
// receivers fetch the now-tombstoned row and push message_deleted).
// "message_edited" (phase 37-2: a message's body was replaced in place;
// same message fields and same per-channel publish as message_deleted,
// and likewise a routing pointer -- receivers re-fetch the row so
// concurrent edits converge on whatever the last write stored).
// "reaction" (phase 37-4: UserID's emoji set for MessageID changed;
// also per-channel, also a routing pointer -- receivers re-read that one
// row, and an ABSENT row means the user cleared their reactions).
// "governance" (gov-1b-1: a proposal/mode change; UserID is the
// recipient member, FriendKind the sub-kind, and the
// GovernanceEventPayload JSON rides the ChannelEventPayload slot).
// "read" (33-1: UserID's read cursor for ChannelID moved; a routing
// pointer only -- receivers re-read the cursor from the store).
// "thread_read" (42-4: same as "read" one level down -- UserID's cursor
// for ThreadID moved. Also a routing pointer; receivers re-read it).
// "typing" (43-3: UserID is composing in ChannelID. The one kind that is
// NOT a routing pointer and references no row at all -- it carries its
// whole meaning, is published per-channel WITHOUT a transaction via
// PublishEphemeral, and is delivered to every member EXCEPT UserID).
Kind string `json:"k"`
// Message fields (Kind="message"). MessageID and TS together
// identify a row in the partitioned messages table.
MessageID uuid.UUID `json:"m,omitempty"`
TS time.Time `json:"t,omitempty"`
ChannelID uuid.UUID `json:"c,omitempty"`
SenderDeviceID uuid.UUID `json:"s,omitempty"`
// SenderConnID is the per-conn UUID of the sender's WebSocket
// connection (Conn.ID). Phase 09a step 3: receivers suppress the
// echo by connID rather than deviceID so multiple tabs of the
// same device coexist (each tab has a unique connID).
//
// Carried as a string because pubsub doesn't import internal/server
// and connID is generated server-side via uuid.New().String().
// Empty string when the sender isn't a connection (e.g. presence
// or friend events that didn't originate from a WebSocket send).
SenderConnID string `json:"sc,omitempty"`
// ClientMsgID carries the sender's optimistic idempotency key (a UUID)
// for Kind="message" so the echo builder can put it back in the pushed
// MessagePayload. The originating client matches it to its optimistic
// row and replaces it instead of duplicating (matters on reconnect,
// where per-conn echo-suppression misses the sender's new conn). Small
// (a UUID) so it stays well under the 8000-byte NOTIFY cap. Empty for
// non-message events and for older clients.
ClientMsgID string `json:"cmi,omitempty"`
// Presence, friend, and channel fields.
// UserID:
// For Kind="presence", the user whose aggregated state changed.
// For Kind="friend", the recipient (whose local devices
// should be notified).
// For Kind="channel", the recipient (a member of the channel).
// FriendKind:
// For Kind="friend", one of "request_received", "accepted",
// "declined", "removed".
// For Kind="channel", one of "added", "removed".
// FromUserID:
// For Kind="friend", the other party.
// Unused for "presence" and "channel".
UserID uuid.UUID `json:"u,omitempty"`
FriendKind string `json:"fk,omitempty"`
FromUserID uuid.UUID `json:"f,omitempty"`
// ChannelEventPayload is the JSON-encoded proto.ChannelSummary
// for Kind="channel" events. Pubsub doesn't import proto (cycle),
// so we carry it as opaque bytes; the receiver in server.go
// decodes into proto.ChannelEventPayload.
ChannelEventPayload json.RawMessage `json:"cp,omitempty"`
// ThreadID identifies the thread for Kind="thread_read" (42-4). A thread's
// id is its head message's id, so this is unique on its own; ChannelID
// rides along too because the push names both.
ThreadID uuid.UUID `json:"th,omitempty"`
// InstanceID tags which chalkd published this. Informational.
InstanceID string `json:"i,omitempty"`
}
Event is the shape of every NOTIFY payload. Kept tiny on purpose to stay well under PG's 8000-byte NOTIFY payload limit. The actual content (message rows, channel rows) lives in the database; this is mostly a routing pointer, with one exception: Kind="channel" events carry the full ChannelSummary so receivers don't have to query to render the sidebar entry.
type Handler ¶
type Handler func(Event)
Handler is invoked once per received Event. Implementations should be fast and non-blocking; long work belongs in a separate goroutine.
type Listener ¶
type Listener struct {
// Tunables.
BackoffInitial time.Duration
BackoffMax time.Duration
// CmdPollInterval bounds how long Subscribe blocks waiting for the
// listener goroutine to apply a LISTEN. Smaller = lower latency but
// more idle CPU; larger = batchier. 50ms is a good default.
CmdPollInterval time.Duration
// contains filtered or unexported fields
}
Listener holds a dedicated Postgres connection that runs LISTEN and dispatches notifications to a Handler. The connection is held outside the pool because pgx pools cannot be used for LISTEN: a pooled connection might be returned and reused by another query, dropping pending notifications.
Phase 08 extends the listener with dynamic subscription: in addition to the always-on chalk_global topic, callers can Subscribe(topic) and Unsubscribe(topic) on a refcounted set of per-channel topics. The dedicated conn stays single-goroutine-owned -- subscribe/unsubscribe commands are queued on a buffered channel and applied between notification waits.
Concurrency model: Subscribe/Unsubscribe touch a refcount map under subMu, then drop a subCmd onto l.cmds. The Run goroutine owns the hijacked conn; it pumps notifications via WaitForNotification with a short timeout (cmdPollInterval). On timeout, it drains pending cmds. On a real notification, it dispatches first, then drains cmds, then loops. This guarantees pgconn.PgConn is only ever touched by Run.
func NewListener ¶
NewListener constructs a Listener. pool must NOT have its connections re-used for unrelated queries -- the listener acquires and hijacks one connection for its lifetime.
func (*Listener) Ready ¶
func (l *Listener) Ready() <-chan struct{}
Ready returns a channel closed when the listener has subscribed to chalk_global at least once.
func (*Listener) Run ¶
Run blocks until ctx is canceled, dispatching every received event through the handler. On connection errors it reconnects with exponential backoff capped at BackoffMax. After reconnect, all previously-subscribed topics are re-issued (their refcounts persist across connection loss).
func (*Listener) Subscribe ¶
Subscribe increments the refcount for topic and issues LISTEN if this is the first reference. Idempotent across multiple callers; only the LAST Unsubscribe matching a Subscribe triggers UNLISTEN.
Blocks until the LISTEN has been applied by the listener goroutine (or returns ctx.Err()). Safe to call concurrently.
func (*Listener) SubscriptionCounts ¶
SubscriptionCounts returns a snapshot of the current refcount map. For tests and ops endpoints.
func (*Listener) Unsubscribe ¶
Unsubscribe decrements the refcount and queues UNLISTEN if the refcount reaches zero. Non-blocking. Safe to call concurrently.