sukko

package module
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Oct 18, 2026 License: MIT Imports: 26 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.

README

sdk-go

Go client SDK for Sukko — realtime infrastructure proven correct under failure, deployed in your own cloud. Real-time market-data / event subscription for backend services, data pipelines, and edge consumers.

  • Channel + iterator delivery with inherent back-pressure — a bounded stream, no unbounded buffering, no silent drops.
  • Full gap recovery — reconnect-with-replay, advisory gap → live replay, and history.
  • Automatic single-flight auth — proactive + reactive token refresh, API-key → JWT escalation.
  • WebSocket transport (SSE is planned, not yet implemented — WithTransport(TransportSSE) returns ErrSSENotImplemented rather than silently falling back to WebSocket), REST publish, push subscription management.
  • context.Context-driven lifecycle, typed errors (errors.Is/errors.As), pull-based Stats().
  • Built to the AsyncAPI v1.4.0 + gateway OpenAPI contracts.

🚧 Pre-release. The API shown below is the target design; the implementation is in progress. go get claims the module path, and symbols land as the SDK is built — so expect the surface to be incomplete until v0.1.0 is tagged. Design rationale lives in the package documentation and in the commit history; the behavioural contract is the AsyncAPI client protocol, which this SDK follows rather than any sibling SDK's current behaviour.

go get github.com/sukko-dev/sdk-go

Requires Go 1.26+.

Quickstart

package main

import (
	"context"
	"log"

	sukko "github.com/sukko-dev/sdk-go"
)

type Trade struct {
	Price float64 `json:"price"`
}

func main() {
	ctx := context.Background()

	client, err := sukko.NewClient("wss://gateway.example.com/ws", sukko.WithToken("<jwt>"))
	if err != nil {
		log.Fatal(err)
	}
	defer client.Close(ctx)

	if err := client.Connect(ctx); err != nil {
		log.Fatal(err)
	}
	if err := client.Subscribe(ctx, []string{"acme.trades"}); err != nil {
		log.Fatal(err)
	}

	for event := range client.Messages() { // live + recovered messages arrive here
		msg, ok := event.(*sukko.Message)
		if !ok {
			continue // advisory events (e.g. *sukko.PossibleGap) ride the same stream
		}
		trade, err := sukko.DataAs[Trade](msg) // typed payload decode
		if err != nil {
			log.Printf("decode %s: %v", msg.Channel, err)
			continue
		}
		log.Printf("%s %+v", msg.Channel, trade)
	}
}

Prefer a range-over-func iterator? for event := range client.Iter(ctx) { ... } is equivalent and cancels with the context.

Publishing

client.Publish(ctx, "acme.trades", data)     // over the WS connection (fire-and-forget)
client.RESTPublish(ctx, "acme.trades", data) // REST — no WS needed (available on every edition)

Auth

Credentials are sent via request headers by default (Authorization: Bearer / X-API-Key); query-param auth is opt-in. Long-lived tokens are refreshed automatically (supply a token source). An API-key connection can escalate to a JWT mid-session, re-subscribing the newly-permitted channels.

Channels

Channels are "{tenant}.{suffix}" (the tenant is the segment before the first dot; the suffix is an opaque dotted remainder).

sukko.BuildChannel("acme", "trades.btc") // -> "acme.trades.btc"
sukko.ParseChannel("acme.trades.btc")    // -> {Tenant: "acme", Suffix: "trades.btc"}

Recovery

On a Kafka backend the SDK recovers missed messages automatically: it reconnects with exponential backoff + jitter and replays from the last position, turning advisory gap notices into live replays — all surfaced through the same Messages() stream. The delivery guarantee is at-least-once within the replay window, best-effort beyond. The recovery deadline interrupts a replay or history fetch only on server silence — a long but steadily progressing recovery is never cut short by its total duration (WithRecoveryDeadline bounds the silence between recovery frames, not the whole transfer; a replay rejection or a dropped connection can still interrupt for their own reasons). On the Direct backend (no positions), a disconnect surfaces a *PossibleGap event per channel so data loss is never silent.

Errors

Every failure is a typed Go error — sentinels matchable with errors.Is (ErrNotConnected, ErrEditionRequired, …) and typed structs via errors.As (*RecoveryInterruptedError, *PayloadDecodeError, *CloseError, …). Credentials never appear in an error string or log record.

Engineering

  • Engineering principles — the rules this SDK is built and reviewed against. Code comments cite them by section: // per §VI refers to section VI of that document (or of the platform principles it adapts — each heading carries the cross-reference).
  • Architecture decision records — durable decisions with context and rejected alternatives; comments cite them as ADR-NNNN.

License

MIT — see LICENSE.

Documentation

Overview

Package sukko is the Go client SDK for the Sukko real-time WebSocket platform.

It provides a single, context-driven Client for real-time market-data and event subscription: WebSocket and SSE transports, header-default JWT / API-key auth with automatic single-flight refresh, full gap recovery (reconnect-with-replay, advisory gap to live replay, and history), bounded back-pressure with no silent drops, REST publish, and push subscription management.

The public surface and behavior derive from Sukko's authoritative contracts — the AsyncAPI v1.4.0 client-ws protocol and the gateway OpenAPI — never from a sibling SDK's current behavior. Channels are "{tenant}.{suffix}".

This package is under active development; see the specs directory for the design.

Index

Constants

View Source
const (
	// DefaultQueueSize is the delivery channel's capacity in events. It matches
	// the server's WS_CLIENT_SEND_BUFFER_SIZE and clears the construction floor
	// (DefaultHistoryLimit + MaxReplayMessages + AdvisoryHeadroom) with headroom,
	// which is what lets the zero-config quickstart construct without a capacity
	// knob.
	DefaultQueueSize = 512

	// SubscribeQueueDepth is the bound on the subscribe serializer's request queue.
	// Subscribe/Unsubscribe enqueue here and return immediately; a full queue
	// yields ErrSubscribeQueueFull. The serializer keeps one request outstanding at
	// a time (the wire's subscription_ack carries no correlation id), so this bounds
	// how many caller requests may await their turn.
	SubscribeQueueDepth = 64

	// DefaultHistoryLimit is the default number of records a History call
	// requests. It tracks the server's WS_HISTORY_MAX_LIMIT *default*.
	DefaultHistoryLimit = 100

	// MaxHistoryLimit is the validation ceiling for WithHistoryLimit — the
	// server's own validated upper bound for WS_HISTORY_MAX_LIMIT. Validation
	// deliberately uses this rather than DefaultHistoryLimit: a default is not a
	// maximum, and clamping to it would make a deployment that raised the server
	// limit unusable from this SDK.
	MaxHistoryLimit = 1000

	// MaxReplayMessages is the contract's bound on a single replay window. The
	// server enforces it, so it is not a client knob; the SDK uses it to size
	// the capacity floor.
	MaxReplayMessages = 100

	// AdvisoryHeadroom is the slice of the delivery channel reserved for
	// advisory and lifecycle events, so a saturating burst of data can never
	// starve the signals that explain it. One slot is reserved exclusively for
	// the final *Terminal event; the other 15 serve a bounded safety subset.
	// It is a constant, not a runtime quantity, because the floor it appears in
	// is validated at construction time.
	AdvisoryHeadroom = 16

	// DefaultMaxPublishSize bounds a published payload in bytes. It must match
	// the server's GATEWAY_MAX_PUBLISH_SIZE. It also derives the WebSocket
	// transport's read limit: the library's own 32 KiB default would close a
	// legal 64 KB inbound message with 1009.
	DefaultMaxPublishSize = 64 * 1024

	// DefaultMaxBackpressureReconnects is how many consecutive
	// back-pressure-induced reconnect cycles are tolerated before the client
	// terminates with ErrConsumerTooSlow. The count is consecutive and resets on
	// any healthy epoch, so a bursty-but-recovering consumer is not terminated.
	// It is an arbitrary-but-tunable backstop rather than an industry-derived
	// number — no surveyed real-time client supplies one — and
	// WithMaxBackpressureReconnects raises it.
	DefaultMaxBackpressureReconnects = 5

	// MinChannelParts is the minimum number of dot-separated parts in a channel:
	// "{tenant}.{suffix}" is at least two.
	MinChannelParts = 2

	// MaxTokenSourceAttempts is how many consecutive TokenSource failures are
	// tolerated on the connected refresh path before the client terminates with
	// ErrTokenSourceFailed. The count is consecutive and resets on any success. A
	// TokenSource failure DURING a reconnect is non-terminal: the client
	// keeps backing off rather than dialing a credential it knows is dead.
	MaxTokenSourceAttempts = 5
)

Capacity and size bounds.

View Source
const (
	// DefaultDialTimeout bounds a *reconnect* dial. It does not bound
	// Connect(ctx) — that call is bounded by the caller's own context.
	DefaultDialTimeout = 10 * time.Second

	// DefaultHeartbeatInterval is how often the client sends an app-level
	// heartbeat. It sits comfortably under the gateway's 60s
	// GATEWAY_IDLE_TIMEOUT so an idle-but-healthy connection is never reaped.
	DefaultHeartbeatInterval = 30 * time.Second

	// DefaultPongTimeout is how long the client waits for the pong reply before
	// closing locally with CloseCodeHeartbeatTimeout. It must stay below
	// DefaultHeartbeatInterval so a timeout is attributable to one heartbeat.
	DefaultPongTimeout = 10 * time.Second

	// DefaultRefreshMinInterval is the floor between auth sends, tracking the
	// gateway's GATEWAY_AUTH_REFRESH_RATE_INTERVAL. It is what stops an
	// auth_error from driving a refresh loop.
	DefaultRefreshMinInterval = 30 * time.Second

	// DefaultRefreshLead is how far ahead of a credential's expiry a proactive
	// refresh is armed. It is clamped so it never schedules inside
	// RefreshMinInterval.
	DefaultRefreshLead = 60 * time.Second

	// DefaultReplayFloor is the per-channel floor between live replay requests,
	// tracking the server's WS_REPLAY_RATE_LIMIT_INTERVAL. The automatic
	// gap-to-replay path honors it rather than provoking replay_rate_limited.
	DefaultReplayFloor = 10 * time.Second

	// DefaultRecoveryDeadline is the maximum SILENCE between recovery frames before a
	// truncated recovery is surfaced (platform ADR-0025: silence, not total duration —
	// so it needs no knowledge of the server's replay timeout). 10s of frame silence is
	// generous for a live server; a large but steadily progressing replay never trips it.
	DefaultRecoveryDeadline = 10 * time.Second

	// DefaultSSEIdleTimeout is how long an SSE stream may deliver no bytes at
	// all — neither a record nor a ": keepalive" comment — before the client
	// treats it as dead. It is 2× the gateway's 45s SSE_KEEPALIVE_INTERVAL.
	DefaultSSEIdleTimeout = 90 * time.Second

	// DefaultTokenSourceTimeout bounds a single TokenSource call. The callback
	// is caller code invoked from the SDK's own timers, so it is bounded rather
	// than trusted to return.
	DefaultTokenSourceTimeout = 10 * time.Second
)

Timing defaults. Every one of these is driven through the injectable Clock, so tests advance them deterministically rather than sleeping.

View Source
const (
	// RecoveryKindReplay is a live gap→replay (or WS reconnect-replay) window — always
	// channel-scoped and client-detected (a deadline or a mid-recovery disconnect).
	RecoveryKindReplay = "replay"
	// RecoveryKindHistory is a History request window.
	RecoveryKindHistory = "history"
	// RecoveryKindReconnectReplay is an SSE reconnect-replay window (resumed via Last-Event-ID)
	// that the server reported truncated at its cap. Connection-level, so Channel is empty — the
	// server-reported SSE analog of RecoveryKindReplay, distinct so a caller can tell them apart
	// (ADR-0016).
	RecoveryKindReconnectReplay = "reconnect_replay"
)

Recovery kinds name which recovery a *RecoveryInterruptedError describes. They are the single source of the strings, referenced instead of literals (§I).

View Source
const (
	// CloseCodeHeartbeatTimeout is sent (LOCAL) when no pong arrives within
	// PongTimeout. It shares its value (4000) with the server's REMOTE
	// force-disconnect and is told apart from it by close direction — the
	// contract's rule, mirrored by @sukko/sdk and sukko-py.
	CloseCodeHeartbeatTimeout = 4000
)

WebSocket close codes the SDK originates.

Code 4000 is reused for two meanings disambiguated by DIRECTION, exactly as the AsyncAPI contract's close-code table and both sibling SDKs (@sukko/sdk, sukko-py) define it: a REMOTE 4000 is the operator's force-disconnect, a LOCAL 4000 is the client's own heartbeat-timeout close. Numeric parity with the contract wins over any private allocation scheme (§I); the close-policy table keeps the two 4000 rows apart by direction (§XVIII: matches the siblings).

View Source
const CodeNotAvailable = "not_available"

CodeNotAvailable is the wire code the server sends when position-anchored recovery is unavailable. It is the one code the not_available bridge keys on, so it is named rather than written as a literal at each comparison.

Variables

View Source
var (
	// ErrNotConnected is returned by an operation that requires a live
	// connection. Publish returns it rather than silently discarding a message.
	ErrNotConnected = errors.New("sukko: not connected")

	// ErrClosed is returned by any method called after Close. A Client is
	// single-use: the delivery channel closes exactly once, so a closed client
	// cannot be revived.
	ErrClosed = errors.New("sukko: client is closed")

	// ErrEditionRequired means the operation needs a higher platform edition.
	ErrEditionRequired = errors.New("sukko: operation requires a higher edition")

	// ErrNotAvailable means position-anchored recovery is unavailable — the
	// Direct backend keeps no cursor. It is a capability signal, not a retryable
	// failure: the SDK degrades to a naive resubscribe and reports the gap.
	ErrNotAvailable = errors.New("sukko: pos-anchored recovery is not available")

	// ErrAlreadyConnected is returned by Connect on a client that is already
	// connecting or connected.
	ErrAlreadyConnected = errors.New("sukko: already connected")

	// ErrConsumerTooSlow terminates a client whose consumer never caught up,
	// after MaxBackpressureReconnects consecutive back-pressure cycles. It is
	// reported rather than looping silently, so the cause is visible.
	ErrConsumerTooSlow = errors.New("sukko: consumer too slow")

	// ErrUnsupportedByTransport means the chosen transport cannot perform the
	// operation — SSE cannot publish over the stream or subscribe live.
	ErrUnsupportedByTransport = errors.New("sukko: operation not supported by this transport")

	// ErrHistoryInProgress means a History call is already outstanding. History
	// is single-flight so one caller's window cannot exhaust the delivery
	// channel that another is relying on.
	ErrHistoryInProgress = errors.New("sukko: a history request is already in flight")

	// ErrHistoryLimitExceeded means a History call asked for more records than the
	// client's configured HistoryLimit. Checked locally before the send, like the
	// publish payload pre-checks — the server would also reject it, but with nothing
	// to correlate the rejection to on a fire-and-forget request.
	ErrHistoryLimitExceeded = errors.New("sukko: history limit exceeds the configured maximum")

	// ErrSubscribeQueueFull means the subscribe serializer's queue is full.
	// Subscribe-class requests are serialized because the contract carries no
	// request id, so an ack cannot otherwise be attributed to its request.
	ErrSubscribeQueueFull = errors.New("sukko: subscribe queue is full")

	// ErrPayloadTooLarge means a publish payload exceeds the configured maximum.
	// Checked locally before the write: on WebSocket, publish is fire-and-forget,
	// so a server rejection would arrive with nothing to correlate it to.
	ErrPayloadTooLarge = errors.New("sukko: publish payload exceeds the maximum size")

	// ErrPayloadNotObject means a publish payload does not marshal to a JSON
	// object, which the contract requires. Also a local pre-check.
	ErrPayloadNotObject = errors.New("sukko: publish payload must marshal to a JSON object")

	// ErrTokenSourceFailed terminates a client after MaxTokenSourceAttempts
	// consecutive TokenSource failures. Reconnecting past this point would
	// consume handshakes with a credential the SDK knows it cannot refresh.
	ErrTokenSourceFailed = errors.New("sukko: token source failed repeatedly")

	// ErrInsecureTransport is returned by NewClient for a ws:// or http:// URL
	// without WithInsecureTransport, and unconditionally when query-parameter
	// auth is combined with a non-TLS URL. Redaction removes credentials from
	// logs; it cannot remove them from the wire.
	ErrInsecureTransport = errors.New("sukko: refusing to use a non-TLS URL")

	// ErrPublishRequiresJWT means publishing was attempted with an API key
	// alone. Checked locally from the SDK's own credential state.
	ErrPublishRequiresJWT = errors.New("sukko: publishing requires a JWT, not an API key")

	// ErrEmptyToken means UpdateToken or Escalate was called with an empty string.
	// Supplying no credential where one is required is a caller mistake, not a no-op.
	ErrEmptyToken = errors.New("sukko: a non-empty token is required")

	// ErrInvalidPushOptions means a PushSubscribe option set failed the local
	// pre-check (unknown platform, no channels, or a platform's required fields
	// missing). Caught before any network I/O so a malformed registration never
	// reaches the gateway.
	ErrInvalidPushOptions = errors.New("sukko: invalid push subscription options")

	// ErrPushDisabled means the gateway has no push surface: it runs with
	// GATEWAY_PUSH_ENABLED=false and the push routes are not registered (HTTP
	// 404). This is a deployment fact, not a transient outage — the remedy is to
	// enable push on the gateway, so it is distinct from ErrPushUnavailable.
	ErrPushDisabled = errors.New("sukko: push is not enabled on this gateway")

	// ErrPushUnavailable means the push service exists but is temporarily
	// unavailable (HTTP 503) — a retryable outage, unlike the permanent
	// ErrPushDisabled.
	ErrPushUnavailable = errors.New("sukko: push service is temporarily unavailable")
)

Sentinel errors. Match with errors.Is; several are also reachable through the typed structs below.

View Source
var DefaultBackoff = BackoffConfig{
	Initial:    500 * time.Millisecond,
	Max:        30 * time.Second,
	Multiplier: 2.0,
	Jitter:     0.2,
}

DefaultBackoff is the reconnect backoff applied when WithBackoff is not given.

View Source
var ErrInvalidChannel = errors.New("sukko: invalid channel")

ErrInvalidChannel reports a channel that does not satisfy the format. It is a sentinel so a caller can branch on "this channel is malformed" without matching on message text.

Functions

func BuildChannel

func BuildChannel(tenant, suffix string) (string, error)

BuildChannel joins a tenant and suffix into a channel string, ready to pass to any client method.

The tenant must be non-empty and must not contain a dot. A dotted tenant would make the prefix ambiguous — "a.b" + "c" and "a" + "b.c" both render "a.b.c", and no parse could recover which tenant was meant. The suffix must be non-empty and free of empty segments, by the same rule ParseChannel applies.

func DataAs

func DataAs[T any](msg *Message) (T, error)

DataAs decodes a message's raw payload into a caller type.

The envelope keeps Data as json.RawMessage so the hot path never forces a decode; DataAs is the opt-in convenience for callers who want their own struct back. A decode failure surfaces as a *PayloadDecodeError carrying the channel and wrapping the cause — the public contract is the typed error, never a bare encoding/json error, so a caller matches on one SDK type while the underlying detail stays reachable through errors.Unwrap.

It is a package-level generic rather than a method because a method cannot introduce its own type parameter; committing the symbol to the public surface is accepted and semver-frozen from v0.1.0.

Types

type AuthError

type AuthError struct {
	// Code is the contract's auth error code, e.g. "invalid_token".
	Code string
	// Message is the server's human-readable description, when the frame
	// carried one. The wire frame always may, so dropping it would discard
	// diagnostics the server took the trouble to send.
	Message string
}

AuthError reports a server-side auth failure carrying a contract error code.

func (*AuthError) Error

func (e *AuthError) Error() string

type AuthMode

type AuthMode string

AuthMode distinguishes the two purposes the wire's single auth message serves. The SDK chooses the mode from credential state it owns rather than inferring it at runtime, so one value never means two things.

const (
	// AuthRefresh replaces an existing credential with a fresh one. Granted
	// subscriptions are preserved.
	AuthRefresh AuthMode = "refresh"
	// AuthEscalation supplies a JWT on an API-key connection, widening
	// permissions. Unlike a refresh it re-subscribes the newly-permitted delta.
	AuthEscalation AuthMode = "escalation"
)

func (AuthMode) String

func (m AuthMode) String() string

String returns the mode's stable lowercase form, e.g. "escalation".

type Authenticated

type Authenticated struct {
	Exp  int64
	Mode AuthMode
}

Authenticated reports a completed credential operation.

Mode distinguishes a refresh from an escalation — the SDK's own owned state, never inferred from the frame. Exp is the new expiry as a unix timestamp; zero means the credential does not expire.

type BackoffConfig

type BackoffConfig struct {
	// Initial is the base delay for the first reconnect attempt.
	Initial time.Duration
	// Max caps both the exponential base and the jittered result.
	Max time.Duration
	// Multiplier is the exponential factor applied per attempt; it must exceed 1.
	Multiplier float64
	// Jitter is the proportional spread applied to the base delay, in [0,1].
	// Zero disables jitter entirely and draws no randomness.
	Jitter float64
}

BackoffConfig parameterises reconnect backoff. Attempt n (n = 0 for the first reconnect after an epoch ends) waits:

base  = min(Initial × Multiplier^n, Max)
delay = base × (1 + Jitter × (2r − 1))    clamped to [0, Max]

where r is exactly one Rand.Float64() draw in [0,1) taken after base is computed — one draw per attempt, and none at all when Jitter is zero. The formula is pinned this precisely so a seeded Rand yields an assertable delay sequence; "exponential with jitter" alone cannot be tested.

The attempt counter resets on a *successful* re-handshake, never on a failed dial, so a flapping connection keeps backing off.

type Capabilities

type Capabilities struct {
	CanPublish        bool
	CanSubscribeLive  bool
	CanRefreshInPlace bool
}

Capabilities reports what a transport can do. It is transport-dependent and static per kind: a WebSocket is bidirectional, an SSE stream is receive-only, so the SDK can answer "can I publish on this connection?" locally rather than letting the server reject the attempt.

type Channel

type Channel struct {
	// Tenant is the segment before the first dot.
	Tenant string
	// Suffix is the remainder, which may itself contain dots.
	Suffix string
}

Channel is the split view of a channel string.

func ParseChannel

func ParseChannel(s string) (Channel, error)

ParseChannel splits a channel into its tenant and suffix.

It rejects a channel that is empty, has fewer than MinChannelParts dot-separated parts, or contains an empty segment. An empty segment matters because it makes the channel ambiguous: ".a", "a." and "a..b" each render indistinguishably from a channel that does not have it.

func (Channel) String

func (c Channel) String() string

String renders the channel in wire form. The zero Channel renders as the empty string rather than a bare dot, so an unset value cannot be mistaken for a real channel in a log line.

type Client

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

Client is a connection to the Sukko platform. It is single-use: after Close (or a terminal failure) every method returns ErrClosed, including Connect — build a new client to reconnect from scratch.

The public API lives here; the supervisor goroutine that owns the connection lifecycle is in supervisor.go, as methods on this same struct.

func NewClient

func NewClient(ctx context.Context, url string, opts ...Option) (*Client, error)

NewClient builds a client for a URL. It validates the configuration and fails fast; it does not dial — call Connect for that. The context is the client lifetime: canceling it tears the client down like Close.

func (*Client) Capabilities

func (c *Client) Capabilities() Capabilities

Capabilities reports what the client's transport can do.

func (*Client) Close

func (c *Client) Close(ctx context.Context) error

Close tears the client down and waits, bounded by ctx, for the teardown to finish. It is idempotent: a second Close returns nil. Canceling the client-lifetime context has the same effect.

func (*Client) Connect

func (c *Client) Connect(ctx context.Context) error

Connect starts the connection. The context bounds the first dial and handshake only — it is not retained, so a Connect(ctx) whose deadline passes after a successful handshake does not tear down the live connection. Connect returns the first dial's outcome: nil on success, a typed error otherwise.

func (*Client) Err

func (c *Client) Err() error

Err returns the terminal cause after Messages() has closed: nil after a clean stop — Close, lifetime cancellation, OR the WithReconnect(false) downgrade of a reconnect-class outcome (where *Terminal.Err still carries the cause for diagnosis) — and the failure otherwise. The channel close is the happens-before edge that makes it race-free to read after close.

func (*Client) Escalate

func (c *Client) Escalate(ctx context.Context, jwt string) error

Escalate widens an API-key connection to full JWT access (or replaces the JWT in escalation mode) by sending an `auth` frame carrying the caller-supplied JWT on the live socket. Like RefreshToken it is an imperative "send now" method: it REQUIRES a live socket and returns *NotConnectedError in any other state — it does not silently store the credential (that is UpdateToken). The offline path is UpdateToken(jwt) + reconnect. An empty JWT is rejected. On a successful ack the JWT is committed to the credential store (flipping the client's class to "has JWT"); a rejected escalation leaves the store unchanged. It is fire-and-forget and single-flight (latest JWT wins). An escalation accepted on a live socket that then drops before its ack is re-sent on the reconnect rather than lost.

func (*Client) History

func (c *Client) History(ctx context.Context, channel string, limit int) error

History requests up to limit historical records for a channel. They arrive in-band as *Message events with Source SourceHistory, terminated by a *HistoryComplete (or a *HistoryError if the server refuses — history is Pro + server-enabled gated). It REQUIRES a live socket and returns *NotConnectedError otherwise — a one-shot request is not meaningfully queued — and ErrClosed once the client is closed. History is SINGLE-FLIGHT: only one call may be outstanding at a time (a second returns ErrHistoryInProgress), because N concurrent windows would put N×HistoryLimit records on the bounded delivery channel. A limit of zero or less uses the configured HistoryLimit; a limit above it returns ErrHistoryLimitExceeded. Unlike a live replay, an interrupted history does not re-drive across a reconnect — an epoch death mid-history surfaces a *RecoveryInterruptedError and the caller re-requests.

func (*Client) Iter

func (c *Client) Iter(ctx context.Context) iter.Seq[Event]

Iter yields events until the caller's context ends or Messages() closes. It receives and yields in the same step, so an abandoned range strands no event.

func (*Client) Messages

func (c *Client) Messages() <-chan Event

Messages returns the in-band event stream. It is closed once, by the supervisor, after the final *Terminal.

func (*Client) PendingSubscriptions

func (c *Client) PendingSubscriptions() []string

PendingSubscriptions returns the requested-but-not-yet-granted set: channels a Subscribe asked for that are not (yet) granted — covering both a Subscribe issued while disconnected and the post-ack denial delta.

func (*Client) Publish

func (c *Client) Publish(ctx context.Context, channel string, data any) error

Publish sends data to a channel over the WebSocket. It is fire-and-forget: the call returns after a local pre-check and the frame write, and the server's outcome arrives in-band on Messages() as *PublishAccepted or *PublishError — the wire protocol has no per-call id, so a synchronous signature would be a false request/response correlation. For a genuine synchronous result, use RESTPublish.

Publish REQUIRES a live socket — a publish is an action with no meaning offline — so it returns *NotConnectedError in any non-connected state and ErrClosed once the client is closed. The local pre-check (shared with RESTPublish) rejects, before any byte reaches the socket, a payload that does not marshal to a JSON object (ErrPayloadNotObject), one larger than MaxPublishSize (ErrPayloadTooLarge), and a publish from an API-key-only client (ErrPublishRequiresJWT — the gateway refuses API-key publish; a JWT or a WithNoAuth deployment is required).

func (*Client) PushSubscribe

func (c *Client) PushSubscribe(ctx context.Context, opts PushSubscribeOptions) (int64, error)

PushSubscribe registers a device for push on the given channels and returns the gateway-assigned device id (persist it — there is no list endpoint to recover it).

The option set is validated locally first (platform, channels, platform-specific fields); a bad set returns ErrInvalidPushOptions without any network I/O. A 403 edition gate returns *EditionRequiredError naming the edition this platform needed (Pro for web, Enterprise for android/ios); a gateway without a push surface returns ErrPushDisabled; an outage ErrPushUnavailable.

func (*Client) PushUnsubscribe

func (c *Client) PushUnsubscribe(ctx context.Context, deviceID int64) error

PushUnsubscribe removes a previously registered device by its id.

func (*Client) PushVAPIDKey

func (c *Client) PushVAPIDKey(ctx context.Context) (string, error)

PushVAPIDKey fetches the tenant's Web Push VAPID public key, which a browser needs to create a Web Push subscription.

func (*Client) RESTPublish

func (c *Client) RESTPublish(ctx context.Context, channel string, data any) (*PublishResult, error)

RESTPublish publishes over HTTP and returns a genuine synchronous result — HTTP is request/response, so unlike the fire-and-forget WebSocket Publish this call returns the outcome (or a typed error) directly and never enqueues anything on Messages() . It needs no WebSocket connection; a closed client returns ErrClosed. The shared local pre-check (object, size, credential class) runs first, before any network I/O, so a bad payload never reaches the gateway.

Non-200 responses map to typed errors: 403 EDITION_LIMIT ⇒ *EditionRequiredError, 429 ⇒ *RateLimitError (with any Retry-After parsed), 413 ⇒ ErrPayloadTooLarge (the server backstop for the local size check), and every other coded response ⇒ *PublishError carrying the gateway's code.

func (*Client) RefreshToken

func (c *Client) RefreshToken(ctx context.Context) error

RefreshToken triggers an immediate credential refresh: the SDK sends an `auth` frame with the current JWT on the live connection. It is an imperative "send now" method — it REQUIRES a live socket and returns *NotConnectedError in any other state (ADR-0011), because queuing a send for the reconnect would be redundant: the reconnect's dial re-authenticates via the per-dial credential read. The offline path is UpdateToken (store) + reconnect. On a live socket it is fire-and-forget and single-flight — concurrent calls coalesce into one in-flight refresh. It returns ErrClosed once the client is closed.

func (*Client) State

func (c *Client) State() ConnectionState

State returns the current connection state.

func (*Client) Stats

func (c *Client) Stats() Stats

Stats returns an eventually-consistent snapshot of the client's counters.

func (*Client) Subscribe

func (c *Client) Subscribe(ctx context.Context, channels []string) error

Subscribe requests delivery of the given channels. Subscription is STATE, not an action: the request is enqueued on the serializer and Subscribe returns as soon as it is accepted — it is fire-and-forget, never awaits an ack, and is accepted in any non-closed state (a request made while disconnected updates the desired set and is flushed on the next connect). A full serializer queue yields ErrSubscribeQueueFull; a closed client returns ErrClosed. The grant outcome arrives in-band as *SubscriptionResult.

func (*Client) Subscriptions

func (c *Client) Subscriptions() []string

Subscriptions returns the granted set — the channels the client is actually receiving — as full tenant-prefixed strings.

func (*Client) Unsubscribe

func (c *Client) Unsubscribe(ctx context.Context, channels []string) error

Unsubscribe abandons the given channels. Like Subscribe it is fire-and-forget and accepted in any non-closed state. It prunes the channels from both the granted and the pending sets; a wire `unsubscribe` is sent only for channels currently granted (a never-granted channel is pruned locally with no wire traffic).

func (*Client) UpdateToken

func (c *Client) UpdateToken(token string) error

UpdateToken stores a JWT for the next connect and the next auth refresh. It is store-only — it never sends an auth frame, in any state (that is RefreshToken and Escalate) — and storing a JWT flips an API-key-only client's credential class to publish-capable. An empty token is rejected.

type Clock

type Clock interface {
	// Now returns the current time.
	Now() time.Time
	// NewTimer arms a one-shot timer under a purpose name.
	NewTimer(d time.Duration, purpose timerPurpose) Timer
	// NewTicker arms a repeating timer under a purpose name.
	NewTicker(d time.Duration, purpose timerPurpose) Ticker
	// BlockUntilTimer blocks until a timer with the given purpose is armed.
	//
	// It is a test rendezvous: a test calls it before advancing the clock, so
	// the advance cannot land before the goroutine under test has armed its
	// timer — the lost-wakeup that makes fake-clock suites flaky. On the
	// production clock it returns immediately.
	BlockUntilTimer(purpose timerPurpose)
}

Clock is the SDK's only source of time. Nothing in the package calls time.Now, time.After, time.NewTimer or time.NewTicker directly — a mixed clock, where timers are fake but Now is real, is the classic way a "deterministic" suite drifts on a loaded CI machine.

type CloseError

type CloseError struct {
	// Code is the WebSocket close code.
	Code int
	// Direction records whether the SDK or the server initiated the close.
	Direction closeDirection
	// Reason is the close reason, when the frame carried one.
	Reason string
}

CloseError reports a WebSocket close. Direction is part of the type because several codes are legal from both ends and mean different things: a local 1000 is the caller's own Close, a remote 1000 is the server closing normally, and only one of those is worth reconnecting.

func (*CloseError) Error

func (e *CloseError) Error() string

type Conn

type Conn interface {
	Read(ctx context.Context) ([]byte, error)
	Send(ctx context.Context, frame []byte) error
	// Close initiates a local close with a WebSocket code and reason.
	Close(code int, reason string) error
}

Conn is one live connection — a single epoch's worth of it.

Read is the only reader of the socket, deliberately: the back-pressure design relies on the decode goroutine being able to stop reading (by parking on delivery) so the TCP window closes. A connection that kept reading in the background would defeat that. Read blocks until a frame arrives, an error occurs, or the passed context is canceled — cancellation closes the connection locally.

type ConnectionState

type ConnectionState string

ConnectionState is the client's observable lifecycle state, reported by Client.State and carried on in-band state-change events.

The six values form a closed set. Two are resting states a client can terminate in: StateClosed after a clean stop (Close, lifetime-ctx cancellation, or a reconnect-class outcome with reconnect disabled), and StateError after a terminal failure. They are distinguished by Client.Err, which is nil for a clean stop.

const (
	// StateDisconnected is the initial state after NewClient, before Connect.
	// It is not re-entered once an epoch has ended.
	StateDisconnected ConnectionState = "disconnected"
	// StateConnecting is set when Connect is called, while the first dial and
	// handshake are in flight.
	StateConnecting ConnectionState = "connecting"
	// StateConnected is set once the handshake succeeds and delivery is live.
	StateConnected ConnectionState = "connected"
	// StateReconnecting is set while the supervisor is backing off and
	// re-dialing after a reconnect-class epoch termination.
	StateReconnecting ConnectionState = "reconnecting"
	// StateError is the terminal state for a failure the SDK will not retry.
	// Client.Err is non-nil in this state.
	StateError ConnectionState = "error"
	// StateClosed is the terminal state for a clean stop. Client.Err is nil in
	// this state, which is what distinguishes it from StateError.
	StateClosed ConnectionState = "closed"
)

func (ConnectionState) String

func (s ConnectionState) String() string

String returns the state's stable lowercase form, e.g. "reconnecting".

type Edition

type Edition string

Edition names a licensed platform edition. The SDK sets it from its own knowledge of which gate an operation crossed, never from a response body: the SSE transport requires Pro, and mobile push (FCM/APNs) requires Enterprise. REST publish is available on every edition and crosses no edition gate — an EDITION_LIMIT on a publish therefore only reaches this SDK from a gateway that predates that change, and is still surfaced as EditionPro (the edition that gate required).

const (
	// EditionPro is required for the SSE transport.
	EditionPro Edition = "pro"
	// EditionEnterprise is required for mobile push (FCM/APNs) delivery.
	EditionEnterprise Edition = "enterprise"
)

func (Edition) String

func (e Edition) String() string

String returns the edition's stable lowercase form, e.g. "enterprise".

type EditionRequiredError

type EditionRequiredError struct {
	// Code is the gateway's body error code, e.g. "EDITION_LIMIT".
	Code string
	// RequiredEdition is the edition the operation needs.
	RequiredEdition Edition
}

EditionRequiredError reports an operation refused by an edition gate. The required edition comes from the SDK's own knowledge of which gate the call crossed — the gateway's 403 body carries only a code — so the field is always populated rather than being a permanently-zero value.

func (*EditionRequiredError) Error

func (e *EditionRequiredError) Error() string

func (*EditionRequiredError) Is

func (e *EditionRequiredError) Is(target error) bool

Is bridges to ErrEditionRequired.

type Event

type Event interface {
	// contains filtered or unexported methods
}

Event is the sealed union delivered on Messages().

It is an interface with an unexported marker method, so the member set is closed to this package: a caller's `switch ev := ev.(type)` runs against a known roster (the dispatch table), and no external type can join it. The dominant member is *Message; everything else is an advisory or lifecycle signal that flows in-band, in receive order, on the same channel — so a *PossibleGap arrives exactly where the potential loss sits relative to the data, rather than on a second channel whose overflow policy could drop the very signals that exist to prevent silent drops.

Several members are also errors (the typed error structs): one `case *ReplayError:` yields a value errors.As matches, with no parallel wrapper hierarchy.

type Gap

type Gap struct {
	Channel string
	FromSeq int64
	ToSeq   int64
	LastPos string
	TS      int64
}

Gap reports that records were missed on a channel, per the server's own gap frame. LastPos may be empty on a backend that keeps no cursors — a real data-loss signal that cannot anchor a replay, which the recovery engine handles by pairing it with a PossibleGap rather than issuing replay{from_pos:""}.

type HandshakeError

type HandshakeError struct {
	// Status is the HTTP status of the failed upgrade.
	Status int
	// Code is the body error code, when the response carried one.
	Code string
	// Message is the body message, when the response carried one.
	Message string
	// RetryAfter is the parsed Retry-After header, or nil when absent. A
	// pointer because a present zero ("retry immediately") is a legitimate
	// value distinct from "the server said nothing".
	RetryAfter *time.Duration
}

HandshakeError reports a failed WebSocket upgrade or SSE stream open. A handshake failure carries an HTTP status and a body code and no close code at all, which is why it is its own type rather than a CloseError.

func (*HandshakeError) Error

func (e *HandshakeError) Error() string

type HistoryComplete

type HistoryComplete struct {
	Channel   string
	Count     int
	Source    HistorySource
	Truncated bool
}

HistoryComplete terminates a history response. Source reports where the records came from; Truncated is true when the response was cut short.

type HistoryError

type HistoryError struct {
	// Code is the contract's history error code, e.g. "history_disabled".
	Code string
	// Channel is the channel whose history request failed.
	Channel string
	// Message is the server's human-readable description, when present.
	Message string
}

HistoryError reports a server-side history rejection. It carries the channel because a history request names exactly one channel, and the contract marks the field required on this frame.

func (*HistoryError) Error

func (e *HistoryError) Error() string

type HistorySource

type HistorySource string

HistorySource reports where a completed history response was served from. The values mirror the contract's `history_complete.source` enum.

A caller switching on it MUST include a default: like an error code, the SDK surfaces the server's value verbatim, so a server newer than this SDK may deliver a source outside the constants below rather than have the frame rejected. Compare against the named constants and treat anything else as unknown.

const (
	// HistorySourceCache means the response was served entirely from cache.
	HistorySourceCache HistorySource = "cache"
	// HistorySourceKafka means the response was served entirely from Kafka.
	HistorySourceKafka HistorySource = "kafka"
	// HistorySourceMixed means the response combined cached and Kafka-sourced records.
	HistorySourceMixed HistorySource = "mixed"
)

func (HistorySource) String

func (s HistorySource) String() string

String returns the source's stable lowercase form, e.g. "mixed".

type InternalError

type InternalError struct {
	// Op is the SDK operation that panicked.
	Op string
	// Value is the recovered panic value, rendered as a string.
	Value string
	// Stack is the stack trace captured at recovery.
	Stack string
}

InternalError reports a panic recovered inside an SDK goroutine. It is surfaced in-band as well as logged: the SDK is quiet by default, so a log-only report would be invisible to a caller who never wired a logger, and a recovered panic that nobody hears about is a silent failure.

func (*InternalError) Error

func (e *InternalError) Error() string

type Message

type Message struct {
	Channel string
	Seq     int64
	TS      int64
	Pos     string
	Mid     string
	Data    json.RawMessage
	Source  MessageSource
}

Message is a delivered record — the union's dominant member.

Source discriminates where the record came from: SourceLive for a normal delivery, SourceHistory for a record from a history response, SourceReplay for one delivered inside a reconnect-replay window. There is no separate replayed type and no History bool; the discriminator carries that distinction, so a caller handles one shape.

Data is the raw payload, left undecoded on the hot path. DataAs[T] decodes it into a caller type; Pos is an opaque cursor, stored and echoed but never parsed or compared.

Mid is the stable message identity: the same value on every copy of a message — live, history, and replay — so a caller can deduplicate a record it already saw (for example a reconnect-replay overlap) or key idempotent processing on it. Opaque like Pos, but distinct in kind: Pos anchors recovery, Mid names the message. Empty on a server that predates the field.

type MessageSource

type MessageSource string

MessageSource says how a delivered Message reached the caller. It replaces a boolean history flag so one field carries one meaning: a record is live, replayed from a gap or reconnect window, or part of a history response.

const (
	// SourceLive marks a message delivered from the live stream. Only live
	// messages advance the per-channel recovery cursor.
	SourceLive MessageSource = "live"
	// SourceHistory marks a message delivered as part of a history response,
	// terminated by a history-complete event.
	SourceHistory MessageSource = "history"
	// SourceReplay marks a message delivered inside a replay or reconnect-replay
	// window. Replayed records may duplicate live ones — the delivery guarantee
	// is at-least-once within the window — so de-duplication is the caller's.
	SourceReplay MessageSource = "replay"
)

func (MessageSource) String

func (s MessageSource) String() string

String returns the source's stable lowercase form, e.g. "replay".

type NotConnectedError

type NotConnectedError struct {
	// Op is the method that was refused, e.g. "Publish".
	Op string
}

NotConnectedError reports an operation attempted without a live connection. It names the operation, so a caller with several in flight can tell which one was refused.

func (*NotConnectedError) Error

func (e *NotConnectedError) Error() string

func (*NotConnectedError) Is

func (e *NotConnectedError) Is(target error) bool

Is bridges to ErrNotConnected.

type Option

type Option func(*config)

Option configures a Client. Options are applied in order, so a later option of the same kind wins.

func WithAPIKey

func WithAPIKey(key string) Option

WithAPIKey sets an API-key credential. An API key alone is receive-only — publishing requires a JWT, which the SDK checks locally rather than letting the server reject the write.

func WithBackoff

func WithBackoff(b BackoffConfig) Option

WithBackoff sets the reconnect backoff parameters.

func WithClientID

func WithClientID(id string) Option

WithClientID sets the identity used to resume a session across reconnects.

Without one the SDK generates a per-process identifier, which is correct for a long-lived service but forfeits resumption across a restart — a caller that wants that must persist an ID and supply it.

func WithClock

func WithClock(clock Clock) Option

WithClock replaces the time source. It exists so tests advance time instead of sleeping; production code has no reason to set it.

func WithDialTimeout

func WithDialTimeout(d time.Duration) Option

WithDialTimeout bounds a reconnect dial. It does not bound Connect, which is bounded by the caller's own context.

func WithHTTPClient

func WithHTTPClient(client *http.Client) Option

WithHTTPClient supplies the HTTP client used for every network path: the WebSocket dial, REST publish, SSE, and push.

It is one seam rather than several because the WebSocket library dials through an *http.Client too. A WS-only TLS option would leave a caller with a private CA configured for REST and not for the socket — working in tests, failing on the transport that matters.

func WithHeartbeatInterval

func WithHeartbeatInterval(d time.Duration) Option

WithHeartbeatInterval sets how often the client sends an application-level heartbeat.

func WithHistoryLimit

func WithHistoryLimit(n int) Option

WithHistoryLimit sets how many records a History call requests.

func WithInsecureTransport

func WithInsecureTransport() Option

WithInsecureTransport permits a ws:// or http:// URL.

The check it relaxes is scheme-based only. Hostname, "localhost", private IP ranges and environment names are deliberately not inputs: each is a heuristic that is wrong somewhere, and a security decision that is right by accident is not a security decision.

func WithLogger

func WithLogger(logger *slog.Logger) Option

WithLogger supplies the logger the SDK writes to. Without one it writes nowhere: a library that logs into its caller's output uninvited is a library the caller cannot quiet.

func WithMaxBackpressureReconnects

func WithMaxBackpressureReconnects(n int) Option

WithMaxBackpressureReconnects sets how many consecutive back-pressure-induced reconnects are tolerated before the client terminates with ErrConsumerTooSlow. The run resets on any healthy epoch, so a consumer that recovers between bursts is not terminated.

func WithMaxPublishSize

func WithMaxPublishSize(n int) Option

WithMaxPublishSize bounds a published payload in bytes, and derives the transport read limit so a legal inbound message is never rejected locally. It must match the server's own limit.

func WithNoAuth

func WithNoAuth() Option

WithNoAuth declares that the target deployment has authentication disabled.

It exists because "does this server require a credential?" is a handshake-time property the constructor cannot discover, and silently allowing a credential-less client would turn a configuration mistake into a runtime failure. Declaring it explicitly keeps the constructor's fail-fast rule intact without blocking a legitimate deployment.

func WithPongTimeout

func WithPongTimeout(d time.Duration) Option

WithPongTimeout sets how long the client waits for a heartbeat reply before closing the connection locally.

func WithQueryParamAuth

func WithQueryParamAuth() Option

WithQueryParamAuth sends credentials as URL query parameters instead of headers. It is enable-only, and rejected outright over a non-TLS URL: a token in a URL is logged by every intermediary, and redaction can remove a credential from this SDK's own output but not from the wire.

func WithQueueSize

func WithQueueSize(n int) Option

WithQueueSize sets the delivery channel's capacity in events. It must leave room for a full history and replay window plus the advisory reserve, or a recovery burst could fill the channel and starve the notices that explain it.

func WithRand

func WithRand(rand Rand) Option

WithRand replaces the randomness source used for backoff jitter, so a seeded implementation yields an assertable delay sequence.

func WithReconnect

func WithReconnect(enabled bool) Option

WithReconnect enables or disables automatic reconnection. Disabling it turns every reconnect-class outcome into a clean stop: the client emits its final event and closes the delivery channel, rather than resting in a state a caller cannot observe.

func WithRecoveryDeadline

func WithRecoveryDeadline(d time.Duration) Option

WithRecoveryDeadline sets the maximum SILENCE between recovery frames before the client reports the recovery as interrupted — a replay that keeps making progress is never cut short by its total duration (platform ADR-0025).

func WithRefreshLead

func WithRefreshLead(d time.Duration) Option

WithRefreshLead sets how far ahead of expiry a proactive refresh is armed.

func WithRefreshMinInterval

func WithRefreshMinInterval(d time.Duration) Option

WithRefreshMinInterval sets the floor between credential refreshes, which is what prevents an auth error from driving a refresh loop.

func WithReplayFloor

func WithReplayFloor(d time.Duration) Option

WithReplayFloor sets the per-channel minimum interval between replay requests, matching the server's own rate limit so the SDK does not provoke it.

func WithSSEIdleTimeout

func WithSSEIdleTimeout(d time.Duration) Option

WithSSEIdleTimeout sets how long an SSE stream may deliver no bytes at all — neither a record nor a keepalive comment — before the client treats it as dead.

func WithToken

func WithToken(token string) Option

WithToken sets a JWT credential. It composes with WithAPIKey: a client may hold both and escalate from one to the other.

func WithTokenSource

func WithTokenSource(src TokenSource) Option

WithTokenSource supplies fresh credentials on demand, for refresh and for reconnects. Without one, a client's credential is whatever it was given at construction and cannot be renewed.

func WithTokenSourceTimeout

func WithTokenSourceTimeout(d time.Duration) Option

WithTokenSourceTimeout bounds a single TokenSource call. The callback is caller code on a path the SDK depends on, so it is bounded rather than trusted to return.

func WithTransport

func WithTransport(kind TransportKind) Option

WithTransport selects the transport. The choice is explicit — the SDK never infers it from the URL scheme.

type PayloadDecodeError

type PayloadDecodeError struct {
	// Channel is the channel the message arrived on.
	Channel string
	// Cause is the underlying decode failure.
	Cause error
}

PayloadDecodeError reports a payload that would not decode into the caller's type. It names the channel and wraps the decoder's own error, so the public contract stays an SDK type while the detail remains reachable.

func (*PayloadDecodeError) Error

func (e *PayloadDecodeError) Error() string

func (*PayloadDecodeError) Unwrap

func (e *PayloadDecodeError) Unwrap() error

Unwrap exposes the underlying decode failure.

type PossibleGap

type PossibleGap struct {
	Channels []string
}

PossibleGap reports channels where loss may have occurred and no recovery is possible, because the SDK holds no cursor to replay from.

It is emitted once per reconnect carrying every such granted channel — one signal, not one per channel, so a caller iterates a slice rather than correlating N events. It covers the whole Direct backend (no cursor ever arrives), a Kafka channel that saw no live message before the drop, an un-anchorable gap (empty last_pos), and every SSE reconnect. It is not emitted when that set is empty.

type ProtocolError

type ProtocolError struct {
	// Type is the wire message type the frame claimed to be.
	Type string
	// Code is the error code carried by the frame, when it had one.
	Code string
	// Message describes what was wrong with the frame.
	Message string
	// Cause is the underlying decode failure, when there was one.
	Cause error
}

ProtocolError reports a frame the SDK could decode as JSON but not accept — a known message type whose payload violates the contract, or an unknown error code within a known type. It is surfaced rather than dropped so a contract-drift bug is visible instead of silent.

func (*ProtocolError) Error

func (e *ProtocolError) Error() string

func (*ProtocolError) Unwrap

func (e *ProtocolError) Unwrap() error

Unwrap exposes the underlying decode failure.

type PublishAccepted

type PublishAccepted struct {
	Channel string
	Mid     string
}

PublishAccepted reports that a publish was accepted. It names the channel from the ack, so a caller with several publishes in flight can attribute it.

Mid is the stable message identity the gateway assigned to the accepted message — the same value subscribers receive on Message.Mid, so a publisher can correlate its publish with the delivered copy (this is the WS-path twin of PublishResult.Mid). Empty for a multi-topic fan-out publish or a gateway that predates the field.

type PublishError

type PublishError struct {
	// Code is the contract's publish error code, e.g. "message_too_large".
	Code string
	// Message is the server's human-readable description, when present.
	Message string
}

PublishError reports a server-side publish rejection.

func (*PublishError) Error

func (e *PublishError) Error() string

type PublishResult

type PublishResult struct {
	Channel string
	Mid     string
}

PublishResult is the outcome of a successful RESTPublish. The gateway's 200 body also carries a const status ("accepted") which is dropped — the caller cannot act on it.

Mid is the stable message identity the gateway assigned to the published message — the same value subscribers receive on the delivered Message.Mid, so a publisher can correlate its publish with the delivery. Empty when the publish fanned out to multiple topics (each produced message gets its own mid) or on a gateway that predates the field.

type PushError

type PushError struct {
	// Code is the gateway's push error code, e.g. "INVALID_REQUEST"; an
	// HTTP_<status> synthetic when the body carried none.
	Code string
	// Message is the server's human-readable description, when present.
	Message string
}

PushError reports a server-side push rejection that has no more specific typed mapping (an edition gate is *EditionRequiredError, an absent surface is ErrPushDisabled, an outage is ErrPushUnavailable). It carries the gateway's code so a caller can branch on the specific rejection.

func (*PushError) Error

func (e *PushError) Error() string

type PushPlatform

type PushPlatform string

PushPlatform names the delivery platform of a push subscription. The values are contract values — the gateway's push-subscribe endpoint declares a closed enum — so a named type keeps a typo a compile error rather than a 400.

const (
	// PlatformWeb is a Web Push subscription, identified by endpoint and keys.
	PlatformWeb PushPlatform = "web"
	// PlatformAndroid is an FCM subscription, identified by a device token.
	PlatformAndroid PushPlatform = "android"
	// PlatformIOS is an APNs subscription, identified by a device token.
	PlatformIOS PushPlatform = "ios"
)

func (PushPlatform) String

func (p PushPlatform) String() string

String returns the platform's wire form, e.g. "android".

type PushSubscribeOptions

type PushSubscribeOptions struct {
	// Platform is the device platform (required).
	Platform PushPlatform
	// Channels are the tenant-prefixed channels the device should receive push for
	// (required, non-empty). Treated as opaque — not validated for tenant prefix here.
	Channels []string
	// Token is the FCM/APNs device token (required for android/ios).
	Token string
	// Endpoint is the Web Push endpoint URL (required for web).
	Endpoint string
	// P256dhKey is the Web Push P-256 DH key (required for web).
	P256dhKey string
	// AuthSecret is the Web Push auth secret (required for web).
	AuthSecret string
}

PushSubscribeOptions describes a device to register. The required fields depend on Platform: web needs Endpoint/P256dhKey/AuthSecret, android and ios need Token.

type Rand

type Rand interface {
	// Float64 returns a pseudo-random number in [0,1).
	Float64() float64
}

Rand supplies the randomness for backoff jitter. It is a seam so a seeded implementation yields an exactly assertable delay sequence; "exponential with jitter" is otherwise untestable beyond "some delay happened".

type RateLimitError

type RateLimitError struct {
	// RetryAfter is the parsed Retry-After header, or nil when absent.
	RetryAfter *time.Duration
}

RateLimitError reports a rate-limited REST or push call. It is a return value only and never delivered in-band: the caller made the call and is receiving the answer, so enqueueing it as well would report one failure twice.

func (*RateLimitError) Error

func (e *RateLimitError) Error() string

type ReconnectError

type ReconnectError struct {
	// Code is the contract's reconnect error code.
	Code string
	// Message is the server's human-readable description, when present.
	Message string
}

ReconnectError reports a server-side reconnect rejection.

func (*ReconnectError) Error

func (e *ReconnectError) Error() string

func (*ReconnectError) Is

func (e *ReconnectError) Is(target error) bool

Is bridges to ErrNotAvailable on the not_available code only, for the same reason as ReplayError.

type RecoveryInterruptedError

type RecoveryInterruptedError struct {
	// Kind is the recovery that was interrupted: RecoveryKindReplay, RecoveryKindHistory,
	// or RecoveryKindReconnectReplay.
	Kind string
	// Channel is the affected channel, or empty for a connection-level interrupt
	// (RecoveryKindReconnectReplay — the whole SSE reconnect replay was truncated).
	Channel string
}

RecoveryInterruptedError reports a recovery that ended without its terminator — a replay or history window cut short by a deadline, a mid-recovery close, or an epoch ending. It exists so a truncated recovery is never surfaced as a bare disconnect, which would leave the caller believing the window completed.

func (*RecoveryInterruptedError) Error

func (e *RecoveryInterruptedError) Error() string

type ReplayComplete

type ReplayComplete struct {
	Channel          string
	MessagesReplayed int
	Truncated        bool
}

ReplayComplete terminates a replay response. MessagesReplayed may be zero; Truncated is true when delivery was cut short.

type ReplayError

type ReplayError struct {
	// Code is the contract's replay error code, e.g. "replay_rate_limited".
	Code string
	// Channel is the channel whose replay failed.
	Channel string
	// Message is the server's human-readable description, when present.
	Message string
}

ReplayError reports a server-side replay rejection. It carries the channel because the recovery engine is per-channel: an error that could not name its channel could not be attributed to the replay it belongs to, and Scenario 4's documented fallback ("call History for that channel") would have no argument.

func (*ReplayError) Error

func (e *ReplayError) Error() string

func (*ReplayError) Is

func (e *ReplayError) Is(target error) bool

Is bridges to ErrNotAvailable, but only for the not_available code — a rate-limited or out-of-range replay is a different condition and must not masquerade as "this backend cannot recover".

type Resumed

type Resumed struct {
	MessagesReplayed int
}

Resumed reports a completed reconnect-replay window and how many records it replayed — which may legitimately be zero on a cursorless backend, a success rather than a failure.

type StateChange

type StateChange struct {
	From ConnectionState
	To   ConnectionState
}

StateChange reports a connection-state transition, per the state machine.

type Stats

type Stats struct {
	// MessagesReceived counts *Message events delivered.
	MessagesReceived int64
	// Gaps counts gap frames received from the server.
	Gaps int64
	// PossibleGaps counts synthetic PossibleGap signals the SDK emitted.
	PossibleGaps int64
	// Replays counts replay requests the SDK issued.
	Replays int64
	// Reconnects counts successful reconnections.
	Reconnects int64
	// BackpressureBlocks counts blocked-on-full-channel episodes — the 0→1
	// transition of a delivery send parking, not the time spent parked.
	BackpressureBlocks int64
	// BackpressureReconnects counts reconnects induced by consumer back-pressure.
	BackpressureReconnects int64
	// Blocked is the total wall time delivery sends spent parked.
	Blocked time.Duration
	// UnknownEvents counts UnknownEvent values delivered.
	UnknownEvents int64
}

Stats is an eventually-consistent snapshot of the client's counters.

It is a plain value struct, deliberately: the internal counters are atomic.Int64 (lock-free, off the hot path's critical section), but sync/atomic.Int64 embeds a noCopy guard, so a struct of them cannot be returned by value without a go vet copylocks failure — which the own CI gate would catch. Stats and the internal counters are therefore distinct types, and Stats() copies field by field.

Each field is individually atomic; the set is not one atomic observation, so the snapshot is eventually consistent — counters are mutually consistent only to the precision that six independent loads allow. There is no drops counter: drops are structurally impossible in this delivery design, so a zero would be the only value it could ever hold.

type SubscriptionResult

type SubscriptionResult struct {
	Requested  []string
	Granted    []string
	NotGranted []string
	Count      int
}

SubscriptionResult reports the outcome of a subscribe as a grant diff.

The gateway silently drops unauthorized channels, so NotGranted — the requested channels absent from Granted — is the only place a refusal is visible. Retaining that denied set is what the escalation delta re-subscribes.

type Terminal

type Terminal struct {
	Err error
}

Terminal is the final event on every terminal path, delivered immediately before Messages() closes.

Err carries the termination cause and is nil only for a caller-initiated stop (Close or lifetime-context cancellation). It is delivered by a non-blocking send into a channel slot reserved for it alone, after every other sender has exited — so it lands even on a full channel with a hung consumer, and cannot be starved, discarded, or raced. Client.Err() reads nil for both clean-stop classes; the two differ on the WithReconnect(false) path, where Terminal.Err carries the close cause while Err() stays nil.

type Ticker

type Ticker interface {
	// C returns the channel tick times are delivered on.
	C() <-chan time.Time
	// Stop stops the ticker. It does not close the channel.
	Stop()
}

Ticker is a repeating timer.

type Timer

type Timer interface {
	// C returns the channel the firing time is delivered on.
	C() <-chan time.Time
	// Stop prevents the timer from firing, reporting whether it did so before
	// the timer fired.
	Stop() bool
}

Timer is a one-shot timer. It mirrors time.Timer closely enough to be substitutable, but exposes its channel through a method so a fake can supply one it controls.

type Token

type Token struct {
	// Value is the credential itself.
	Value string
	// Expiry is when it stops being valid, or the zero time if unknown.
	Expiry time.Time
}

Token is a credential and, optionally, when it expires.

A zero Expiry means "unknown": the SDK falls back to the expiry the server reports at auth time, which is the default behavior and costs a caller nothing. A non-zero Expiry is caller-authoritative and lets the refresh scheduler arm without waiting for a round-trip — which matters most when the server reports no expiry at all, where there would otherwise be nothing to schedule against. When both are known, the earlier instant wins.

type TokenSource

type TokenSource func(ctx context.Context) (Token, error)

TokenSource supplies fresh credentials. The SDK calls it from its own timers, so it receives a context derived from the client's lifetime and bounded by WithTokenSourceTimeout — never a caller's request context, because there is no caller present when a refresh falls due.

type TokenSourceError

type TokenSourceError struct {
	// Attempt is the 1-based attempt number within the current run of failures.
	Attempt int
	// Cause is the error the TokenSource returned, or the timeout that bounded it.
	Cause error
}

TokenSourceError reports one failed TokenSource call. It is surfaced per attempt so a caller sees credential trouble as it happens, rather than only learning of it when the client terminates with ErrTokenSourceFailed.

func (*TokenSourceError) Error

func (e *TokenSourceError) Error() string

func (*TokenSourceError) Unwrap

func (e *TokenSourceError) Unwrap() error

Unwrap exposes the caller's own error.

type Transport

type Transport interface {
	// Open dials and completes the handshake, returning a live connection. A
	// handshake that is not a successful upgrade returns a *HandshakeError.
	Open(ctx context.Context) (Conn, error)
	// Capabilities reports what this transport can do. It is static per kind.
	Capabilities() Capabilities
}

Transport dials connections to the server. It is a factory: each Open yields one Conn for one epoch, so no read or close state can leak across reconnects — the read side lives on the connection, not on the transport.

type TransportKind

type TransportKind string

TransportKind selects the transport a Client uses. The choice is explicit: the SDK never infers a transport from the URL scheme.

const (
	// TransportWebSocket is the bidirectional WebSocket transport, and the
	// default NewClient applies when no transport option is given.
	TransportWebSocket TransportKind = "websocket"
	// TransportSSE is the receive-only SSE transport: it subscribes via connect-time
	// channels (subscribe/unsubscribe bounce the stream), publishes over REST, cannot
	// subscribe live, and resumes lost messages on reconnect via the opaque Last-Event-ID
	// cursor (ADR-0015). Parity with sukko-js / sukko-py.
	TransportSSE TransportKind = "sse"
)

func (TransportKind) String

func (k TransportKind) String() string

String returns the transport's stable lowercase form, e.g. "websocket".

type UnknownEvent

type UnknownEvent struct {
	Type string
	Raw  json.RawMessage
}

UnknownEvent carries a server frame whose type the SDK does not recognize.

It is surfaced rather than dropped so a server newer than its clients does not go silently unheard — the forward-compatibility rule that lets an old client talk to a new server. Raw is the frame verbatim.

type Unsubscribed

type Unsubscribed struct {
	Channels []string
	Count    *int
	Forced   bool
}

Unsubscribed reports removed channels.

Count is a pointer so a present zero ("you now have none") is distinct from absent (the server omits it on a forced unsubscribe). Forced marks an unsolicited server-initiated removal — a credential downgrade, say — which the caller did not ask for and must not have resolve a pending request of its own.

Jump to

Keyboard shortcuts

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