pushhub

package
v0.195.0 Latest Latest
Warning

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

Go to latest
Published: Oct 24, 2026 License: MIT Imports: 8 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 pushhub is the in-process fan-out behind the browser's single /v1/ws connection (Q2). Publishers (job persist, the event tap, decision/session writes, worker presence) only ever call the non-blocking Notify* methods; the hub turns those into frames on per-connection bounded queues. A queue that fills drops the increment and flags the connection for a `resync`, so a slow browser can never stall recordEvent or persist.

The package is a leaf: it knows topics, frames and queues, nothing about jobs, stores or HTTP (G022).

A connection may carry a project scope (caller-scope ceilings, gofer-7798): it then only hears the changes of the projects its scope admits, and its snapshot topics are computed for that scope. The zero scope is unrestricted and keeps the original single shared frame per topic.

Index

Constants

View Source
const (
	TopicStats     = "stats"
	TopicPending   = "pending"
	TopicJobs      = "jobs"
	TopicSessions  = "sessions"
	TopicRunners   = "runners"
	TopicMeta      = "meta"
	TopicPlans     = "plans"
	TopicWorkflows = "workflows"
	TopicSchedules = "schedules"
	TopicWork      = "work"
	// TopicWorkerEnrollments is a pure invalidation (no payload) for worker enrollment
	// requests; subscribing needs worker.manage (httpapi.wsTopicAllowed).
	TopicWorkerEnrollments = "worker-enrollments"

	JobTopicPrefix = "job:"
)

Topics. A `job:<id>` topic carries one job's increments; the rest are global.

View Source
const (
	DefaultQueueSize         = 64
	DefaultMaxConnsPerCaller = 16
	// DefaultStatsInterval: stats is heavy (two 200ms-budget passes), so it is
	// coalesced to at most one computation per interval, and only with subscribers.
	DefaultStatsInterval = 2 * time.Second
	// DefaultSessionsInterval: session churn (turn counters) is throttled the same way.
	DefaultSessionsInterval = 2 * time.Second
	// DefaultInvalInterval spaces the cheap invalidations (jobs, runners, ...) so a burst
	// of writes reaches the browser as one refetch trigger.
	DefaultInvalInterval = 300 * time.Millisecond
	// DefaultPendingInterval keeps the bell snappy while still merging a burst.
	DefaultPendingInterval = 200 * time.Millisecond
)

Defaults (the design's numbers).

Variables

View Source
var ErrClosed = errors.New("pushhub: connection closed")

ErrClosed is returned by Conn.Next once the connection or hub is closed.

View Source
var ErrTooManyConns = errors.New("pushhub: too many connections for this caller")

ErrTooManyConns is Register's refusal once a caller already holds the maximum.

Functions

func ErrorFrame

func ErrorFrame(msg string, topics []string) []byte

ErrorFrame tells a client one of its frames was refused.

func JobTopic

func JobTopic(id string) string

JobTopic names one job's topic.

func PongFrame

func PongFrame() []byte

PongFrame is the reply to a client `ping`.

func ValidTopic

func ValidTopic(topic string) bool

ValidTopic reports whether a client may subscribe to topic.

Types

type BackfillFunc

type BackfillFunc func(jobID string, sinceSeq int64) ([]JobEvent, error)

BackfillFunc returns the events of one job after a sequence cursor.

type Conn

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

Conn is one browser connection: a bounded outbound queue plus its subscriptions.

func (*Conn) Caller

func (c *Conn) Caller() string

Caller is the authenticated identity the connection was registered under.

func (*Conn) Close

func (c *Conn) Close()

Close unregisters the connection and unblocks Next. Idempotent.

func (*Conn) Next

func (c *Conn) Next(ctx context.Context) ([]byte, error)

Next blocks for the next outbound frame. A pending overflow is reported first, as a `resync` frame, ahead of whatever is still queued.

func (*Conn) Push

func (c *Conn) Push(b []byte)

Push queues an arbitrary pre-built frame (hello/pong style) for this connection.

func (*Conn) Subscribe

func (c *Conn) Subscribe(topics []string, sinceSeq map[string]int64) (rejected []string)

Subscribe adds topics (invalid ones are returned as rejected). sinceSeq carries the per-`job:<id>` resume cursors. Snapshot topics are answered with their current snapshot, a cursor-carrying job topic with the events it missed.

func (*Conn) Topics added in v0.163.0

func (c *Conn) Topics() []string

Topics copies the topics this connection is currently subscribed to. The push caller uses it to re-compute what its subscriptions need: the permission rule of design §6 is declared per topic, and a permission can go away while the connection is open.

func (*Conn) Unsubscribe

func (c *Conn) Unsubscribe(topics []string)

Unsubscribe drops topics.

type ConnScope added in v0.178.0

type ConnScope struct {
	// Key fingerprints the restriction: connections with the same Key share one computed
	// snapshot frame and one cache entry. It must identify the project set, never the
	// connection. Ignored when Scope is nil; RegisterScoped makes it unique when a scoped
	// caller passes none, so two restrictions can never be confused for one another.
	Key string
	// Scope reports whether a project key is inside the restriction. It runs on the hub's
	// and the publishers' goroutines, so it must be cheap and must not panic.
	Scope func(project string) bool
}

ConnScope is the project restriction of one push connection. The zero value is an unrestricted connection: it receives every frame exactly as it did before the ceilings existed (that path is kept byte-identical on purpose).

type Hub

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

Hub is the subscription table plus the coalescers that feed it.

func New

func New(o Options) *Hub

New builds a Hub.

func (*Hub) CloseAll

func (h *Hub) CloseAll()

CloseAll drops every connection and refuses new ones (server shutdown).

func (*Hub) ConnCount

func (h *Hub) ConnCount() int

ConnCount is the number of live connections.

func (*Hub) NoteEvent

func (h *Hub) NoteEvent(scope string, ev JobEvent)

NoteEvent routes one recorded event (any scope) onto the topics it affects. seq is the event's row sequence, scope the job id or a synthetic `plan:<id>`-style scope.

func (*Hub) Notify

func (h *Hub) Notify(topic string)

Notify marks a global topic changed. Snapshot topics (stats, pending) are recomputed, the rest get an `inval`; either way bursts are coalesced and the work happens on a hub goroutine, so Notify is safe on any hot path.

func (*Hub) NotifyJob

func (h *Hub) NotifyJob(id, status string)

NotifyJob reports that job id changed to status: it feeds the `jobs` list invalidation (with the id), the `job:<id>` topic, and stats.

func (*Hub) NotifyJobProject added in v0.178.0

func (h *Hub) NotifyJobProject(id, status, project string)

NotifyJobProject is NotifyJob for a change whose project the publisher knows (the jobstore.Change.Project of a single-row write). The project both narrows the `jobs` invalidation for restricted connections and filters the `job:<id>` increment.

func (*Hub) NotifyProject added in v0.178.0

func (h *Hub) NotifyProject(topic, project string)

NotifyProject is Notify for a change whose project the publisher knows: a restricted connection hears it only if the project is inside its scope (an empty project is a bulk / id-less write and reaches every connection).

func (*Hub) PublishJobEvent

func (h *Hub) PublishJobEvent(id string, ev JobEvent)

PublishJobEvent forwards one recorded event to the job's subscribers. It is a no-op (and allocation-free) when nobody watches the job.

func (*Hub) PublishJobKind

func (h *Hub) PublishJobKind(id, kind string)

PublishJobKind sends a typed hint (e.g. "interaction") to a job's subscribers.

func (*Hub) PublishJobKindProject added in v0.178.0

func (h *Hub) PublishJobKindProject(id, kind, project string)

PublishJobKindProject is PublishJobKind for a change whose project the publisher knows: a restricted connection only receives the hint when the job is inside its scope (gofer-7798 第二期).

func (*Hub) Register

func (h *Hub) Register(caller string) (*Conn, error)

Register admits a new connection for caller. The hello frame is already queued.

func (*Hub) RegisterScoped added in v0.178.0

func (h *Hub) RegisterScoped(caller string, scope ConnScope) (*Conn, error)

RegisterScoped admits a new connection for caller under a project restriction. A zero ConnScope registers an unrestricted connection (the same thing Register does).

func (*Hub) SetBackfill

func (h *Hub) SetBackfill(fn BackfillFunc)

SetBackfill installs the `job:<id>` since_seq source.

func (*Hub) SetJobProject added in v0.178.0

func (h *Hub) SetJobProject(fn func(jobID string) (project string, ok bool))

SetJobProject installs the resolver a restricted connection uses to bind the project of a `job:<id>` topic it subscribes to (nil clears). It is called at subscribe time, never on the publish hot path. Without it a job topic stays unbound and its increments reach every subscriber — acceptable only because subscription itself is already gated by the caller's scope in httpapi (the ws topic check).

func (*Hub) SetScopedSnapshot added in v0.178.0

func (h *Hub) SetScopedSnapshot(topic string, fn ScopedSnapFunc)

SetScopedSnapshot installs the payload source of a snapshot topic for a restricted connection. A restricted connection whose topic has no scoped source gets NO snapshot at all — it never falls back to the unrestricted payload, which would carry the rows of every project (fail closed). The producers of the payload (the httpapi/ws_handler snapshot builders) own the actual per-project filtering.

func (*Hub) SetSnapshot

func (h *Hub) SetSnapshot(topic string, fn SnapFunc)

SetSnapshot installs the payload source of a snapshot topic (stats, pending) for an unrestricted connection.

func (*Hub) Stats

func (h *Hub) Stats() (dropped, resyncs int64)

Stats reports the drop and resync counters (tests and diagnostics).

func (*Hub) Subscribers

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

Subscribers is the number of connections subscribed to topic.

type JobEvent

type JobEvent struct {
	Seq    int64  `json:"seq"`
	Type   string `json:"type"`
	Detail string `json:"detail,omitempty"`
	At     int64  `json:"at"`
}

JobEvent is one lifecycle event as backfilled for a `job:<id>` subscription.

type Options

type Options struct {
	QueueSize         int
	MaxConnsPerCaller int
	StatsInterval     time.Duration
	SessionsInterval  time.Duration
	InvalInterval     time.Duration
	PendingInterval   time.Duration
	// Version is stamped on the hello frame; a changed value tells the page a new build
	// is running.
	Version func() string
	Now     func() time.Time
}

Options tunes a Hub; zero values take the defaults above.

type ScopedSnapFunc added in v0.178.0

type ScopedSnapFunc func(scope func(project string) bool) (any, error)

ScopedSnapFunc computes one snapshot topic's payload for a project restriction (caller-scope ceilings). scope is nil for the unrestricted computation — the frame every unrestricted connection shares; non-nil means the payload may only carry the rows of projects scope admits. Like SnapFunc it runs on the hub's goroutines.

type SnapFunc

type SnapFunc func() (any, error)

SnapFunc computes one snapshot topic's payload. It runs on the hub's own goroutines (never on a publisher's), and may be slow.

Jump to

Keyboard shortcuts

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