Subscriptions

Live data, backfill, and the reconnecting subscriber.

SubscribeRequest

SubscribeRequest registers for live data; with Backfill set, stored history from StartTime is streamed first. The guarantee at the backfill-to-live boundary is NO GAP, not no duplicate: a record ingested mid-backfill below the cutoff can arrive twice, so dedupe by (stream, timestamp) if that matters to you.

type SubscribeRequest struct {
	StreamID StreamID
	// Ticks subscribes to raw ticks instead of candles.
	Ticks bool
	// Backfill asks the server to send stored history before live data.
	Backfill bool
	// Partials asks for in-progress candles as they update, not only closed
	// ones.
	Partials bool
	// StartTime is the oldest timestamp the backfill should cover, in Unix
	// nanoseconds. It travels only when Backfill is set — encoding it with the
	// flag clear is an error rather than a silent drop.
	//
	// Zero means "from the earliest record this node still stores", which is
	// the useful default for a client that has never seen the stream. A client
	// resuming from a checkpoint sends the timestamp after its last known
	// record instead.
	StartTime int64
	// AckWindow selects BOUNDED-ACK delivery when non-zero (Phase 8 §8.2.3):
	// the server sends at most AckWindow live batches beyond the last one the
	// client acknowledged with STREAM_ACK, and NEVER drops one — a subscriber
	// whose buffer on the server overflows is evicted instead. Zero is
	// fire-and-forget, where a full buffer drops batches and the sequence gap
	// says so.
	AckWindow uint16
	// Offloadable lets a saturated primary send this subscriber to an
	// in-sync copy with an OFFLOAD_SUBSCRIPTION, and Offloaded is set on the
	// SUBSCRIBE that follows one, to that copy (Phase 8 §8.2.4). Candles only:
	// a copy serves no tick read, so either flag on a tick subscription is
	// refused by the codec on both sides.
	Offloadable bool
	Offloaded   bool
}

SubscribeRequest is a decoded SUBSCRIBE_STREAM payload.

func ParseSubscribePayload(payload []byte) (SubscribeRequest, error)

ParseSubscribePayload decodes a SUBSCRIBE_STREAM payload. Reserved flag bits are rejected rather than ignored, so a future flag can never be misread as absent by an older server.

The trailing 8-byte StartTime is expected exactly when the backfill flag is set. Both directions are enforced — a backfill request without it and a plain request carrying it are both ErrPayloadFormat — so length alone never decides how a payload is read.

UnsubscribeRequest

UnsubscribeRequest cancels a subscription.

type UnsubscribeRequest struct {
	StreamID StreamID
	Ticks    bool
}

UnsubscribeRequest is a decoded UNSUBSCRIBE_STREAM payload. Ticks must match the SUBSCRIBE it cancels: it is part of the subscription’s identity.

func ParseUnsubscribePayload(payload []byte) (UnsubscribeRequest, error)

ParseUnsubscribePayload decodes an UNSUBSCRIBE_STREAM payload. Backfill and partials are meaningless when canceling, so setting them is rejected rather than ignored.

Subscription

Subscription is a live subscription with a lifecycle — the iterator over Client.SubscribeStream. Same shape as CandleRows: Next/Event/Err/Close.

sub, err := c.SubscribeStream(ctx, req)
defer sub.Close()
for sub.Next(ctx) {
    ev := sub.Event()
    ...
}
if err := sub.Err(); err != nil { ... }

NOT safe for concurrent use, and it owns the connection’s subscription stream: use one Client per subscription.

type Subscription struct {
	// Has unexported fields.
}

Subscription is a live subscription with a lifecycle: it owns the delivery contract, so a caller loops instead of decoding frames.

sub, err := c.SubscribeStream(ctx, req)
defer sub.Close()
for sub.Next(ctx) {
    ev := sub.Event()
    ...
}
if err := sub.Err(); err != nil { ... }

The iterator shape is the one CandleRows already uses here, for the same reason: it is database/sql.Rows, whose contract every Go developer knows. It owns no goroutine, so there is no lifecycle to leak — Next blocks on the ctx the caller passes, and silence on a live subscription is a normal state rather than a timeout.

NOT safe for concurrent use, and it owns the CONNECTION’s subscription stream, not just this stream’s share of it: the push channel underneath is per-connection, so a second subscription on the same Client would interleave two sequence spaces into one counter. A batch for another stream is therefore reported as ErrForeignBatch rather than filtered out, because filtering would silently discard records the server considers delivered. One Client per subscription until a demultiplexer exists.

func (s *Subscription) Close() error

Close ends the iteration. It does NOT close the Client and does not unsubscribe — the connection is the caller’s, and a server that should be told needs Unsubscribe. Safe to call more than once.

func (s *Subscription) Err() error

Err returns the error that ended the iteration, or nil if it ended because the caller stopped. Always check it after the loop.

func (s *Subscription) Event() Event

Event returns the delivery the last Next produced. Its slices alias the decode buffer for that frame only; copy anything kept past the next Next.

func (s *Subscription) Next(ctx context.Context) bool

Next advances to the next delivery, reporting whether one arrived. It returns false at the end of the stream — check Err to tell an ordinary unsubscribe from a failure.

The Established confirmation is never yielded: it is a handshake detail, and SubscribeStream has already consumed the one the server sends.

On a bounded-ack subscription (AckWindow > 0) calling Next is what says the previous event is processed: it acknowledges the live batches yielded so far, every ackEvery of them, before waiting for the next. A caller that holds an event without calling Next holds the node’s window open on it.

func (s *Subscription) Unsubscribe(ctx context.Context) error

Unsubscribe tells the server to stop, releasing its queue and push goroutine before a socket teardown races them. Batches already queued may still arrive.

Event

Event is one subscription delivery with the wire’s flags interpreted: which side of the backfill-to-live pivot it falls on, and how many batches the server dropped before it.

type Event struct {
	// Sequence is the server's per-subscription batch number, monotonic from 1
	// over LIVE batches. Backfill batches are outside that space and carry 0.
	Sequence uint64
	// Backfill marks this batch as stored history rather than live data.
	Backfill bool
	// Live marks the FIRST live batch after backfill finished — the pivot from
	// catching up to keeping up. A subscription that asked for no backfill
	// never sets it: there was nothing to pivot from.
	//
	// The guarantee at the pivot is NO GAP, NOT NO DUPLICATE. The backfill
	// window and the live queue deliberately overlap, so a record ingested
	// during the backfill below its cutoff arrives on both sides of the pivot.
	// Ingest is idempotent by (stream, timestamp); a consumer that cares must
	// dedupe on the same key.
	Live bool
	// Stale marks a batch a COPY of the partition sent, not its primary
	// (§8.2.4): it trails the primary by about one replication poll.
	Stale bool
	// LevelAt is, on a stale batch, when the copy was last level with its
	// primary, on the copy's clock: everything the primary had made durable by
	// then has reached this subscriber. Zero on a fresh batch, or when the
	// copy did not say.
	LevelAt time.Time
	// Dropped is how many batches the server discarded before this one because
	// this consumer was not keeping up — 0 on a healthy stream. Non-zero means
	// records are GONE, not delayed; recover them with a query or a backfilling
	// re-subscribe over [MissingSince, this batch).
	Dropped uint64
	// MissingFirst and MissingLast bound the dropped sequence numbers
	// inclusively, and are meaningful only when Dropped is non-zero.
	MissingFirst uint64
	MissingLast  uint64
	Candles []Candle
	Ticks   []Tick
}

Event is one subscription delivery, with the wire’s flags interpreted.

Exactly one of Candles or Ticks is populated, matching the subscription’s kind. Both empty is legal and means the batch carried only a state change — the backfill-to-live pivot, most usefully.

func (e Event) Records() int

Records reports how many data records this event carries, across whichever of the two kinds the subscription is for.

Value receiver, against this repo’s usual pointer-receiver rule: Event is what Event() hands back by value, so a pointer receiver would make the obvious sub.Event().Records() fail to compile on an unaddressable value. The cost is a per-BATCH struct copy, not a per-record one.

StreamData

StreamData is one raw subscription delivery, as the server framed it. Prefer Client.SubscribeStream and Event: the raw form leaves the caller to interpret two sequence spaces, and the last consumer that tried got it wrong.

type StreamData struct {
	// Sequence is monotonic per subscription, starting at 1. The Established
	// confirmation uses 0.
	Sequence uint64
	StreamID StreamID
	Ticks    bool
	// Backfill marks this batch as historical rather than live.
	Backfill bool
	// Live marks the first batch after backfill completed.
	Live bool
	// Established marks the subscription confirmation: sequence 0, no records.
	Established bool
	// Stale marks a batch a copy sent, not the primary (Phase 8 §8.2.4).
	Stale bool
	// LevelAt is, on a stale batch, when the copy was last level with its
	// primary's durable watermark, in Unix nanoseconds on the copy's clock —
	// what a stale QUERY_RESPONSE carries too. 0 means the copy did not say.
	// It rides as an 8-byte trailer before the CRC, present exactly when
	// Stale is set, so a fresh frame's bytes are unchanged.
	LevelAt  int64
	Candles  []Candle
	TickData []Tick
}

StreamData is a decoded STREAM_DATA payload. Exactly one of Candles and TickData is populated, selected by Ticks; an Established frame carries neither.

func ParseStreamDataPayload(payload []byte) (StreamData, error)

ParseStreamDataPayload decodes a STREAM_DATA payload, verifying the CRC before any record is trusted.

ResumingSubscriber

ResumingSubscriber is a subscription that survives losing its connection: it redials, replays the handshake, and re-subscribes with backfill from one nanosecond past the last record delivered, so the caller sees a continuous stream and no record twice. NOT safe for concurrent use.

func NewResumingSubscriber(addr string, opts Options, req SubscribeRequest, resume ResumeOptions) (*ResumingSubscriber, error)
type ResumingSubscriber struct {
	// Has unexported fields.
}

ResumingSubscriber is a subscription that survives losing its connection.

Next blocks for the next batch. If the connection fails it redials, replays the INIT handshake, and re-subscribes with backfill from one NANOSECOND past the last record it delivered — so the caller sees a continuous stream rather than an error, and never sees the same record twice.

It is NOT safe for concurrent use: Next owns the connection.

func NewResumingSubscriber(
	addr string, opts Options, req SubscribeRequest, resume ResumeOptions,
) (*ResumingSubscriber, error)

NewResumingSubscriber dials addr, subscribes, and returns a subscriber that reconnects on failure.

req.Backfill controls only the FIRST subscribe: whether the caller wants history before live data. Reconnects always request backfill regardless, because that is the entire mechanism by which the hole left by the disconnect gets filled.

func (s *ResumingSubscriber) Close() error

Close releases the connection. It does not unsubscribe; call Unsubscribe first if the server should be told.

func (s *ResumingSubscriber) Next(ctx context.Context) (Event, error)

Next returns the next event, reconnecting as needed. It blocks until data arrives, ctx ends, or the reconnect budget is spent — silence on a live subscription is a normal state, so only ctx bounds the quiet stretches.

Delivery semantics come from Subscription, which this holds one of per connection: the Established confirmation is consumed there, drops are counted there, and backfill is kept out of the live sequence space there. This adds exactly two things on top — reconnecting, and skipping events that carry nothing at all. An event with no records is still returned when it carries a state change (the backfill-to-live pivot, or a drop report), because that is information the caller cannot recover elsewhere.

func (s *ResumingSubscriber) Offloads() int

Offloads reports how many times a saturated primary sent this subscriber to a copy.

func (s *ResumingSubscriber) Reconnects() int

Reconnects reports how many times the stream has been re-established. Zero means the original connection has held for the life of this subscriber.

func (s *ResumingSubscriber) Redirects() int

Redirects reports how many redirects this subscriber has followed.

func (s *ResumingSubscriber) Unsubscribe(ctx context.Context) error

Unsubscribe cancels the subscription on the server, releasing its queue and push goroutine before the socket teardown races with them.

ResumeOptions

ResumeOptions tunes reconnect behavior; the zero value is usable.

type ResumeOptions struct {
	// MaxAttempts bounds consecutive reconnects before Next gives up. Default 5.
	MaxAttempts int
	// Backoff is the delay between reconnect attempts. Default 200ms.
	Backoff time.Duration
	// FollowRedirects makes a REDIRECT a place to resubscribe rather than the
	// end of the stream (§7.9): at the first SUBSCRIBE, sent to a node that
	// does not serve the stream, and mid-stream, when its partition moves and
	// the old primary ends the subscription with the new primary's address.
	// The resume after a move backfills from the last record delivered, as
	// after any break. Each redirect followed must carry a strictly newer
	// epoch than the last, the routing client's convergence rule, so two
	// nodes that disagree end the stream with the redirect rather than
	// bouncing it between them. Off by default: a caller that knows one node
	// sees the redirect.
	FollowRedirects bool
	// NoOffload keeps this subscriber on the primary even when it is
	// saturated (§8.2.4). By default a candle subscription offers to be sent
	// to an in-sync copy, whose feed trails the primary by about one
	// replication poll and is marked Event.Stale.
	NoOffload bool
}

ResumeOptions tunes reconnect behavior. The zero value is usable.