Documentation
¶
Overview ¶
Package cometgo is a realtime web framework: publish Postgres queries as live subscriptions and expose server-authoritative methods over a WebSocket wire protocol (see PROTOCOL.md).
Index ¶
- Constants
- Variables
- func InstallIdempotency(ctx context.Context, db *pgxpool.Pool) error
- func InstallTriggers(ctx context.Context, db *pgxpool.Pool, tables ...string) error
- func Method[A, R any](a *App, name string, fn func(c *Call, args A) (R, error))
- func Publish[A any](a *App, name string, opts PubOptions, ...)
- type App
- func (a *App) Emit(ctx context.Context, pubName string, args any, scope, topic string, data any) error
- func (a *App) Revalidate(ctx context.Context, userID string) error
- func (a *App) ServeHTTP(w http.ResponseWriter, r *http.Request)
- func (a *App) Shutdown(ctx context.Context) error
- func (a *App) Start(ctx context.Context) error
- type Call
- type ColSchema
- type Config
- type DescribeOptions
- type Error
- type Identity
- type MethodSchema
- type Metric
- type PubOptions
- type PubSchema
- type Query
- type Schema
- type Scope
- type SubCtx
Constants ¶
const ( CodeBadRequest = "BAD_REQUEST" CodeValidation = "VALIDATION" CodeUnauthenticated = "UNAUTHENTICATED" CodeAuthExpired = "AUTH_EXPIRED" CodeForbidden = "FORBIDDEN" CodeNotFound = "NOT_FOUND" CodeConflict = "CONFLICT" CodeRateLimited = "RATE_LIMITED" CodeTimeout = "TIMEOUT" CodeCanceled = "CANCELED" CodeResultTooLarge = "RESULT_TOO_LARGE" CodeOverloaded = "OVERLOADED" CodeInternal = "INTERNAL" )
Stable error codes (PROTOCOL.md §9). Application codes use the "app." prefix.
const ( MetricTick = "tick_seconds" // duration of one engine tick MetricTickRuns = "tick_runs" // observer queries run in that tick MetricObservers = "observers" // gauge: live observers MetricSubscriptions = "subscriptions" // gauge: bound subscriptions MetricQueuedBytes = "queued_bytes" // gauge: bytes queued to all sockets MetricCoalescing = "coalescing_conns" // gauge: connections coalescing (§8.1) MetricFenceWait = "fence_wait_seconds" // duration: commit to fence release, per call MetricFenceLag = "fence_lag" // counter: a call answered with lag:true MetricSlowClose = "slow_closes" // counter: a socket closed with 4429 MetricListenReconnect = "listen_reconnects" // counter: the LISTEN connection dropped MetricPubRun = "pub_run_seconds" // duration of one observer query, with Pub )
Metric names. A "gauge" is the current value, reported after every engine tick; a "counter" reports 1 per occurrence; a "duration" reports one observation in seconds.
const Subprotocol = "cometgo.1.json"
Subprotocol is the WebSocket subprotocol for wire protocol v1 with JSON encoding.
Variables ¶
var ErrEventTooLarge = errors.New("cometgo: event too large")
ErrEventTooLarge is returned by Emit and EmitAfterCommit when the encoded event exceeds the 7,500-byte notification limit. Nothing is sent.
var ErrForbidden = NewError(CodeForbidden, "forbidden")
ErrForbidden is a convenience FORBIDDEN error.
var ErrUserIDTooLong = errors.New("cometgo: revalidate: user ID too long")
ErrUserIDTooLong is returned by Revalidate and RevalidateAfterCommit for a userID of 8,000 bytes or more, which a Postgres notification cannot carry. Nothing is sent, and the method's transaction is not touched.
Functions ¶
func InstallIdempotency ¶
InstallIdempotency creates the comet_idempotency table that stores the results of calls carrying an idempotency key (PROTOCOL.md §5 ik). It is idempotent; run it at startup or from a migration. Apps whose clients never send ik do not need it.
result is json rather than jsonb so a retry returns the exact bytes the first call returned.
func InstallTriggers ¶
InstallTriggers installs the change-feed triggers (PROTOCOL.md §11) on each table. It is idempotent; run it at startup or from a migration. Tables must have a primary key.
Per table it creates statement-level AFTER triggers with transition tables, one per event (a transition-table trigger cannot list several events), and a TRUNCATE trigger. Each statement sends one notification on channel "comet": the changed primary keys, or a table-dirty marker when more than 1,000 rows changed or the key set does not fit in a payload.
Types ¶
type App ¶
type App struct {
// contains filtered or unexported fields
}
App is a CometGo server. It implements http.Handler for the WebSocket endpoint; mount it at /_comet.
func (*App) Emit ¶
func (a *App) Emit(ctx context.Context, pubName string, args any, scope, topic string, data any) error
Emit sends an ephemeral event to every subscription of the publication pubName with the given args and scope: the subs that share one observer. args must encode to the same JSON value the client subscribed with. scope is the subscribers' Identity.Scope() (their UserID when they have no ScopeKey) for a ScopeUser publication and is ignored for ScopeShared. The bare ScopeKey is not a scope: an event sent to it reaches no one. The publication must have PubOptions.Events set.
Delivery is at-most-once and best-effort: an event reaches the subs bound at the moment the engine processes it, after any changes committed before the emit, and is never replayed to a client that resyncs (PROTOCOL.md §7.1). To emit about data a method writes, use Call.EmitAfterCommit instead, so the event cannot arrive before that data or for a write that rolled back.
func (*App) Revalidate ¶
Revalidate re-runs the publication fn of every live subscription held by sessions whose Identity.UserID is userID, including sessions waiting to be resumed, on every node listening to this database. A sub whose fn now returns an error ends with that error; the others are untouched. Call it after changing a permission that fn checks but that its query does not read (a query that reads the permission table, listed in Tables, picks up the change by itself).
Only an error ends a sub: a fn that narrows its Query instead (say, to the teams the user still belongs to) changes nothing, since the observer keeps the Query it was created with. Any error ends the sub, a transient one too.
It sends a notification and returns; each node re-checks on its next tick after receiving it, against what fn reads then, so call it after the change has committed. Inside a method, use Call.RevalidateAfterCommit. A node whose listener is reconnecting when the notification is sent misses it, as with events. An empty userID does nothing.
func (*App) ServeHTTP ¶
func (a *App) ServeHTTP(w http.ResponseWriter, r *http.Request)
ServeHTTP upgrades the request to a CometGo WebSocket connection.
func (*App) Shutdown ¶
Shutdown stops the server gracefully (PROTOCOL.md §7.3):
- Every session is sent goaway with a random retryInMs of 0–5 s, and new WebSocket upgrades are refused with 503.
- New calls are refused with UNAVAILABLE; calls already running finish and their results are sent.
- Once no call is in flight (or ctx is done), every socket is closed with 4503 after what is queued for it has been written.
- The engine, the listener and the idempotency cleanup stop.
It returns ctx.Err() if ctx ended before the calls or the closes finished; the remaining sockets are then closed at once. A concurrent or later Shutdown waits for the first (or for its own ctx) and returns its result. Call it before http.Server.Shutdown, which does not wait for hijacked connections.
func (*App) Start ¶
Start runs the Postgres listener, the tick engine and the idempotency-key cleanup until ctx is done or Shutdown stops them. Shutdown needs them running while it drains, so with Shutdown pass a ctx that outlives the shutdown signal. After Shutdown, Start does nothing.
Start first checks that every table in a publication's Tables exists under exactly that name and has the triggers InstallTriggers creates, and returns an error without starting anything if not. The check needs the database: if it is unreachable, Start fails after at most Config.QueryTimeout. A later Start may retry.
type Call ¶
type Call struct {
Context context.Context
Identity *Identity // nil when anonymous
// Tx is the method's transaction. Writes made through it are fenced:
// the client's call resolves only after their effects reach its subs.
Tx pgx.Tx
// contains filtered or unexported fields
}
Call is passed to method handlers.
func (*Call) EmitAfterCommit ¶
EmitAfterCommit is Emit inside the method's transaction, with the same arguments (scope is the subscribers' Identity.Scope()): the event is sent only if the transaction commits, and reaches subscribers after the tx carrying the method's writes and before the method's res (unless the call was sent with noFence, whose res does not wait).
func (*Call) RevalidateAfterCommit ¶
RevalidateAfterCommit is Revalidate inside the method's transaction: the re-check is sent only if the transaction commits, and runs once the method's writes are visible. A sub it ends gets its end before the method's res (unless the call was sent with noFence).
type ColSchema ¶
ColSchema is one result column: its wire type code (PROTOCOL.md §10), whether it can be null, and for an enum (or array of one) its labels.
type Config ¶
type Config struct {
// DB is the Postgres pool used for publications, methods and LISTEN.
DB *pgxpool.Pool
// Authenticate validates a bearer token sent in hello or auth. Return an
// *Error (e.g. UNAUTHENTICATED) to reject it. If nil, tokens are rejected.
Authenticate func(ctx context.Context, token string) (*Identity, error)
// AuthenticateRequest resolves cookie-session identity at WebSocket
// upgrade, used when hello carries no token. Return (nil, nil) for
// anonymous; an error closes the connection with 4401.
AuthenticateRequest func(r *http.Request) (*Identity, error)
// Build identifies the current client build; sent in welcome (§3.1).
Build string
// OriginPatterns lists extra allowed WebSocket origins (host patterns).
// Same-origin is always allowed.
OriginPatterns []string
// Heartbeat is the liveness interval. Default 25s.
Heartbeat time.Duration
// MinTickInterval is the minimum time between ticks, coalescing bursts
// of changes. Default 20ms.
MinTickInterval time.Duration
// FenceTimeout bounds how long a method result waits for its writes to
// reach the client before being sent with lag:true. Default 5s.
FenceTimeout time.Duration
// QueryTimeout is the hard per-observer query timeout. Default 30s.
QueryTimeout time.Duration
// IdempotencyTTL is how long the result of a call carrying an
// idempotency key is kept for retries. Default 24h.
IdempotencyTTL time.Duration
MaxSubs int // default 500
MaxInflight int // default 32
MaxMsg int // default 1 MiB
MaxRows int // per-observer row cap, default 10,000
// MaxObservers caps live queries (observers) on the server. A sub that
// would create one more ends with OVERLOADED; a sub joining an existing
// observer is unaffected. 0 means no limit.
MaxObservers int
// MaxConns caps open WebSocket connections; MaxConnsPerIP caps them per
// ClientIP. Over either, the upgrade is refused with HTTP 503. 0 means
// no limit.
MaxConns int
MaxConnsPerIP int
// ClientIP returns the address MaxConnsPerIP counts against. Default,
// and when it returns "": the host of r.RemoteAddr. Behind a proxy,
// return the client address the proxy forwards, or every client shares
// the proxy's limit.
ClientIP func(r *http.Request) string
// ResumeGrace is how long a session outlives a lost socket, waiting for
// the client to resume it (§7.2). Default 60s; negative disables resume.
// Resume needs sticky routing when several nodes serve one endpoint.
ResumeGrace time.Duration
// ResumeBuffer caps the bytes of unacked messages kept per session for
// replay. A detached session that overflows it ends. Default 1 MiB, at
// most 4 MiB.
ResumeBuffer int
Logger *slog.Logger
// Metrics, if set, receives engine and connection health measurements
// (see the Metric* constants). It is called synchronously from the
// engine and connection goroutines, so it must be fast and safe for
// concurrent use. Nil reports nothing.
Metrics func(Metric)
}
Config configures an App.
type DescribeOptions ¶
type DescribeOptions struct {
// Identity is passed to publication builders, for those that refuse
// anonymous callers. Nil describes them as anonymous.
Identity *Identity
}
DescribeOptions configures Describe.
type Error ¶
type Error struct {
Code string `json:"code"`
Msg string `json:"msg"`
Details any `json:"details,omitempty"`
RetryAfterMs int64 `json:"retryAfterMs,omitempty"`
}
Error is a structured error sent to clients. Return one from a method or publication to control what the client sees; any other error is reported as INTERNAL with a log correlation ref.
func ValidationError ¶
ValidationError returns a VALIDATION error carrying per-field messages.
type Identity ¶
type Identity struct {
// UserID identifies the user. Publications with ScopeUser are shared only
// between connections with the same Scope().
UserID string
// ScopeKey, if set, partitions one user's identities, e.g. by tenant: two
// identities with the same UserID but different ScopeKey get separate
// ScopeUser observers and Emit targets, and are different principals for
// resume, re-auth and idempotency keys. Set it when the query depends on
// more than the user. It is always combined with UserID (see Scope).
ScopeKey string
// User is sent to the client in welcome/authRes. Defaults to {"id": UserID}.
User any
// ExpiresAt, if set, downgrades the connection to anonymous when reached
// unless the client refreshes its token first.
ExpiresAt time.Time
// Data is free-form server-side data available to methods and publications.
Data any
}
Identity is an authenticated principal.
func (*Identity) Scope ¶
Scope is the identity's scope: what ScopeUser observers are keyed by and what Emit's scope argument must be. It is UserID when ScopeKey is empty, otherwise UserID and ScopeKey joined by a NUL byte, so it never equals another user's scope as long as UserIDs contain no NUL. "" when nil.
type MethodSchema ¶
type MethodSchema struct {
Name, Args, Result string
}
MethodSchema describes a method. Args and Result are TypeScript types of the JSON the method accepts and returns.
type Metric ¶
type Metric struct {
Name string // one of the Metric* constants
Pub string // the publication, for MetricPubRun; "" otherwise
Value float64 //
}
Metric is one measurement passed to Config.Metrics. Durations are in seconds; counts and gauges are plain numbers.
type PubOptions ¶
type PubOptions struct {
// Tables the query reads ("todos" or "schema.todos"). Changes to these
// tables re-run the query. Each must have triggers installed with
// InstallTriggers.
Tables []string
// Key lists the primary-key columns of the result. Default ["id"].
Key []string
// Unordered marks results whose row order carries no meaning; the client
// then receives no positions.
Unordered bool
Scope Scope
// Events lets the server send ephemeral events to this publication's
// subscriptions with App.Emit and Call.EmitAfterCommit.
Events bool
// Row, if set, is a struct value describing one result row for
// Describe, which then does not run the query. Use it for a query that
// cannot run with zero-value args. Fields map to columns by their json
// tag or name; a pointer field is nullable (see Describe).
Row any
}
PubOptions configures a publication.
type PubSchema ¶
PubSchema describes a publication: the TypeScript type of its args, and the columns of its rows.
type Query ¶
type Query struct {
SQL string
Args []any
// Match, if set, lets the engine skip re-running this query for writes
// that cannot affect it (PROTOCOL.md §11). It must describe the query's
// row set exactly: the publication reads one table, Key is that table's
// primary key (same columns, same order), and the result is every row
// of the table where each column equals its value, with no LIMIT,
// OFFSET, join, subquery or other condition. An empty map means every
// row. Values are compared as pgx decodes the column: string for text
// and enums (deterministic collations only), int types for integers,
// bool, and [16]byte or its string form for uuid. Anything else, a nil
// value, or a column the table lacks, makes every change re-run the
// query, as without Match.
Match map[string]any
}
Query is the SQL a publication runs. It is re-run whenever a table it reads changes, so it must be deterministic for a given snapshot; use ORDER BY for ordered publications.
type Schema ¶
type Schema struct {
Methods []MethodSchema // sorted by name
Publications []PubSchema // sorted by name
}
Schema describes an App's methods and publications, for generating client types (Schema.TypeScript).
func Describe ¶
Describe reports a's methods and publications. Method args and results come from their Go types. A publication's row comes from PubOptions.Row when set; otherwise its builder is called with zero-value args and opts.Identity, and the query is run with LIMIT 0 to read the result columns. Postgres reports no nullability for result columns, so a column is non-null only when the publication reads a single table and the column is a NOT NULL column of it (an outer self-join can still make it null; use Row then). Every other column is nullable.
Describe needs the database the App uses; it changes nothing in it.
func (*Schema) TypeScript ¶
TypeScript renders s as a TypeScript module declaring Methods, Publications and Schema, for connect<Schema>() in @cometgo/client. The output is sorted by name, so it changes only when the schema does.