Mirexa

Wiki Reference

Go SDK

Every exported name of the public Go package github.com/AmiraliOmidvar/mirexa/client, grouped by purpose, with the contract each one carries.

github.com/AmiraliOmidvar/mirexa/client is the public Go package for talking to a Mirexa node: dial it, write candles and ticks, read them back, list streams and gaps, change a stream's metadata, and subscribe to live data. It speaks Mirexa's binary wire protocol directly. This page lists every exported name, grouped by what it is for, with the promise each one makes. For a walkthrough rather than a reference, start with the quickstart and the writing, reading and subscription guides.

What the package is

The package is a thin layer of type aliases and wrappers over internal packages; every name in it is a deliberate, reviewed commitment. Two tests hold that line:

  • TestClientPackage_PublicSurfaceIsPinned fails if a name is added to or removed from the package without the pinned list in /client/surface_test.go being updated, and fails for any export without a doc comment.[1]
  • TestClientPackage_DependencyFootprint fails if importing the package pulls in the storage engine, the write-ahead log, the metrics stack, or any third-party module. Importing it costs the wire codec and the data model and nothing else.[2]
bash
go get github.com/AmiraliOmidvar/mirexa/client

The module declares Go 1.25. client/clienttest is a second public package: an in-process server for your own tests (see Testing against a fake node).

Because most names are aliases, their methods are documented on the internal type they alias: go doc -all ./internal/wireclient shows Client's and ResilientClient's methods, and go doc -all ./internal/wire the request and response structs. This page summarises both.

What the public package does not include

The internal client also has a routing client (DialRouting) that holds a connection per node, follows redirects, splits multi-queries across nodes, spreads reads over in-sync copies and falls back to stale reads. It is not exported: a Client or ResilientClient holds one connection to one address and returns a redirect to you as an error rather than following it (see Redirects). mirexa-cli load and the dashboard use the routing client internally. The Python SDK does follow redirects.

A complete program

This is the package's own runnable example, Example, with the fake server swapped for a real address and a token read from the file a single node writes for itself (<data_dir>/auth/admin.token; see Authentication).[3]

go
package main

import (
	"context"
	"fmt"
	"log"
	"os"
	"strings"
	"time"

	"github.com/AmiraliOmidvar/mirexa/client"
)

func main() {
	c, err := client.Dial("127.0.0.1:8080", client.Options{
		TokenSource: func() (string, error) {
			b, err := os.ReadFile("data/auth/admin.token")
			return strings.TrimSpace(string(b)), err
		},
	})
	if err != nil {
		log.Fatal(err)
	}
	defer c.Close()

	ctx := context.Background()
	stream := client.NewStreamID("binance", "BTCUSDT", "1m")
	start := time.Now().Truncate(time.Minute).Add(-5 * time.Minute)

	candles := make([]client.Candle, 5)
	for i := range candles {
		f := float64(i)
		candles[i] = client.Candle{
			Timestamp: start.Add(time.Duration(i) * time.Minute).UnixNano(),
			Open: 67_012.50 + f, High: 67_248.75 + f, Low: 66_981.25 + f,
			Close: 67_104.00 + f, Volume: 1_482_113.5 + f*1000,
		}
	}
	// DurabilityAcked is the zero value: this returns once the batch is in the
	// write-ahead log and the log is fsynced.
	if err := c.IngestCandles(ctx, stream, candles, client.DurabilityAcked); err != nil {
		log.Fatal(err)
	}

	resp, err := c.QueryCandles(ctx, client.QueryRequest{
		StreamID:  stream,
		StartTime: start.UnixNano(),
		EndTime:   start.Add(5 * time.Minute).UnixNano(),
	})
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(resp.Status, len(resp.Points))
}

Connecting

Name Kind What it is
Dial func Dial(addr string, opts Options) (*Client, error): connect to host:port, run the INIT handshake, return a ready client.
Options struct Dial options (alias of the internal ClientOptions). The zero value is usable.
Client type One connection to one node. Safe for concurrent use.
ErrInvalidOptions error Dial refused an option that cannot be meant: a negative timeout, a frame cap below the 4 KiB floor. Zero values are never invalid; zero means "default".
ErrClientClosed error Every operation on a Client whose connection is gone, closed by you or torn down by a transport error.
ErrRequestTimeout error The node did not answer within Options.RequestTimeout. The request may still run on the node; its late answer is discarded, never delivered to a later call.

Options fields

Field Default Meaning
TLS *tls.Config nil (plaintext) Enables TLS with this client config.
DialTimeout 10s Bounds the TCP and TLS connect.
RequestTimeout 30s Bounds each request/response exchange, including the handshake. Does not apply to waiting for subscription data.
Token string empty A session token as printed by mirexa-cli token issue. Empty dials unauthenticated, which only a node with authentication off accepts; it is on by default.
TokenSource func() (string, error) nil Consulted on every connect and reconnect, and takes precedence over Token. With a source set, the client also renews its token over the open connection once two-thirds of the token's life has passed.
DisableRenewal bool false Turns automatic renewal off; Client.Reauthenticate still renews by hand.
MaxFramePayloadBytes uint32 16 MiB Largest response payload accepted. Floor 4 KiB.
Retry RetryOptions see Backpressure How shed requests are re-sent.
Observer Observer nil Receives client-side measurements.
Redirector nil An internal type the public package cannot construct; leave it nil. With it set, writes carry the partition epoch the client was last told.

Without a token the client asks for an unsigned grant of READ_CANDLES, WRITE_CANDLES, READ_TICKS, WRITE_TICKS, ADMIN_STREAM and LIST_STREAMS, valid for 30 minutes. A node with authentication on refuses it; a node with authentication off grants it, clamped by security.max_permissions.[4] See Permissions.

Concurrency

Any number of goroutines may call request/response methods on one Client. A single read loop matches replies to callers by the correlation id every frame carries, so a reply never reaches the wrong caller (TestClient_ConcurrentCallersShareOneConnection). The node serves one frame at a time per connection, so a slow query delays the replies queued behind it: use one Client per worker when you want the node to work in parallel.

The subscription side of a connection is one ordered stream. Exactly one goroutine should drive a subscription, and a second subscription on the same Client is refused with ErrForeignBatch. Use one Client per subscription. A consumer that stops reading eventually stalls the whole connection, because the push buffer is bounded.

Cancellation

Every operation takes a context.Context. Cancelling it detaches the caller from the answer, not the request from the node: the operation may still run, and its late answer is dropped. A context deadline also bounds the dial and the handshake (TestResilient_ACallersDeadlineBoundsTheHandshake).

Authentication and permissions

Name Kind What it is
MaxTokenValidity const One hour: the longest lifetime a token may carry. mirexa-cli token issue refuses longer, and so does the node.
PermReadTicks, PermReadCandles, PermWriteTicks, PermWriteCandles const Permission bits for reading and writing each kind of record.
PermListStreams const Stream discovery (ListStreams, NodeStats; ListNodes also accepts a read bit). Separate from the read bits: a node can serve prices without disclosing its catalog.
PermAdminStream const Changing a stream's metadata: calendar, closures, lineage. Reading metadata needs only PermReadCandles.
PermissionNames func PermissionNames(bitmap uint64) []string: render a bitmap as names, for logs.

There is no ADMIN_CLUSTER constant here; that bit is for the control-plane gRPC API, which this package does not speak.

Client methods for the session:

Method What it does
GrantedPermissions() uint64 The bitmap the node actually granted, from INIT_ACK. It can be narrower than the token asked for, because the node clamps every grant with security.max_permissions.
HasPermission(perm uint64) bool True when the grant carries every bit in perm.
SessionID() uint32 The session id the node assigned.
Reauthenticate(ctx) error Renews the token over the open connection (REAUTH). The session and its subscriptions are kept. A refused token (untrusted issuer, expired, another tenant) is a *RemoteError and changes nothing (TestReauth_ARenewedSubscriptionOutlivesItsFirstToken).

On a ResilientClient, GrantedPermissions() returns 0 while it is not connected; read 0 as "ask again once connected", not "granted nothing". See Authentication and tokens.

Streams and records

Name Kind What it is
StreamID struct Exchange, Symbol, Timeframe.
NewStreamID func NewStreamID(exchange, symbol, timeframe string) StreamID. The node validates the timeframe ("1m", "5m", "1h" …) on every operation and refuses one it cannot parse (TestServer_IngestRejectsUnparseableTimeframe).
Candle struct Timestamp int64 (Unix ns), Open, High, Low, Close, Volume float64.
Tick struct Timestamp int64 (Unix ns), Price, Volume float64. A negative price is legal.
CandlePoint struct One item of a query result: Candle, IsGap bool, and Status/Reason classifying a gap. Incomplete() reports a derived bar whose source had a hole under it.

StreamID.String() renders symbol:timeframe:exchange (for example BTCUSDT:1m:binance). That is the form a ListStreams cursor and the dashboard API use. The command-line tools take the opposite order, exchange:symbol:timeframe.[5]

Values are stored as fixed point with four decimal places; more digits are rounded. See Candles and ticks.

Writing

Name Kind What it is
Durability type What an ingest call means by "done".
DurabilityAcked const The zero value. Blocks until the node's INGEST_ACK: the batch is in the write-ahead log and the log is fsynced.
DurabilityFireAndForget const Returns once the frame is written to the socket. A batch the node refuses is dropped with no signal. Never retried.
WriteRoute type Which candle write route OverwriteCandles takes.
RouteLive, RouteHistory, RouteCorrection const The routes IngestCandles, IngestHistoryCandles and IngestCorrectionCandles take.
Ingester interface IngestCandles + IngestTicks; both Client and ResilientClient satisfy it.

Client write methods (all ctx, streamID, records, Durability):

Method Route and contract
IngestCandles The live route. A bar the stream already stores is restated with the batch's values wherever the node keeps it; a bar identical to what is stored is skipped, so re-sending a batch rewrites nothing. A bar older than anything the stream stores is refused: only the history route installs it.
IngestCorrectionCandles The strict form: restates stored bars and refuses the batch if any bar is newer than the newest one stored. Cannot be combined with history.
IngestHistoryCandles Bulk back-fill. Staged and compressed straight into chunks with no WAL. Fire-and-forget batches are staged and not yet readable; an acked call compresses and installs everything staged for the stream, which is when it becomes readable. Send the bulk fire-and-forget and finish with one acked call.
IngestTicks Trades. Semantics match IngestCandles.
OverwriteCandles(ctx, sid, candles, d, route) Writes a derived stream, which every other write refuses with ErrorCodeDerivedStream. A later re-derivation of the same bar writes over it again. On a stream nobody derives it is the ordinary write.

None of the write routes writes into a market closure the stream has filed. See Writing data and Corrections, restatements and history.

Batching

Name Kind What it is
Batcher[T] generic type Buffers records for one stream and sends a batch when either threshold is reached. Safe for concurrent Add.
BatchOptions struct MaxRecords (default 1,000), MaxDelay (default 100ms, measured from the oldest buffered record), Durability (default acked).
NewCandleBatcher func NewCandleBatcher(c Ingester, streamID StreamID, opts BatchOptions) (*Batcher[Candle], error).
NewTickBatcher func The same for ticks.
ErrBatcherClosed error Add on a closed batcher.

Add returns once a record is buffered, not stored; a failed background flush surfaces at a later Add, at Flush, or at Close. Close sends the last partial batch and returns the first error the batcher ever hit, so always check it.

go
b, err := client.NewCandleBatcher(c, stream, client.BatchOptions{
	MaxRecords: 4,
	MaxDelay:   50 * time.Millisecond,
})
if err != nil {
	return err
}
for _, candle := range candles {
	if err := b.Add(ctx, candle); err != nil {
		return err
	}
}
return b.Close() // the last partial batch, and the final verdict

Reading

Name Kind What it is
QueryRequest struct One range query over [StartTime, EndTime) in Unix ns.
QueryResponse struct Status, HasMore, Points []CandlePoint, Stale, LevelAt, Columns.
TickResponse struct Status, HasMore, Ticks []Tick.
QueryStatus type The in-band outcome of a query, distinct from a transport error.
QueryStatusOK, QueryStatusStreamNotFound, QueryStatusInvalidRange const A missing stream is a status, not an error: the call succeeded.
CandleRows type Iterator over a candle range that fetches pages as you loop: Next, Point, Err, Close.
TickRows type The same for ticks: Next, Tick, Err, Close.
QueryStatusError type An in-band refusal (stream not found, invalid range) surfaced through CandleRows/TickRows.Err, which have no status field.

QueryRequest fields

Field Meaning
StreamID The stream.
StartTime, EndTime [start, end) in Unix ns.
MaxResults uint32 On QueryCandles, a cap per response (0 = as many as fit one frame). On the row iterators, QueryColumns and QueryMultiAll, the total across pages.
IncludeGaps bool Adds a gap marker for each slot with no candle. Ignored for ticks.
Ticks bool Raw trades instead of candles. The tick methods set it for you.
Descending bool Newest first. With MaxResults it selects the last N records (TestServer_DescendingWithMaxResultsReturnsTheNewest).
AllowStale bool Lets an in-sync copy answer when the node asked is not the stream's primary. The answer sets Stale and LevelAt. Candles only. See Reads from copies.
Rollup time.Duration Bars of this length made at query time from the stream's candles, or with Ticks from its trades. Only closed buckets are answered; nothing is stored. Not with AllowStale. See Deriving bars.
Columns ColumnSet Only these value columns (see Columns). Not with Ticks, IncludeGaps, AllowStale or Rollup (TestQueryPayload_AColumnQueryMisuseIsRefusedOnBothSides).

Client read methods

Method What it does
QueryCandles(ctx, q) (QueryResponse, error) One round trip. When HasMore is set, continue by moving StartTime past the last record.
QueryCandlesRows(ctx, q) *CandleRows Pages for you. Always check Err() after the loop: a transport error mid-range otherwise reads as a short but plausible result. Descending ranges page newest-first.
QueryTicks(ctx, q) (TickResponse, error) One tick page.
QueryTicksRows(ctx, q) *TickRows Pages ticks.
QueryColumns(ctx, q) (*ColumnBatch, error) The whole range as columns; pages internally. Returns ErrNoColumns when q.Columns is zero.
go
rows := c.QueryCandlesRows(ctx, client.QueryRequest{
	StreamID: stream, StartTime: from, EndTime: to,
})
defer rows.Close()
for rows.Next() {
	if p := rows.Point(); !p.IsGap {
		use(p.Candle)
	}
}
if err := rows.Err(); err != nil { // an in-band refusal ends iteration too
	return err
}

Reading columns

Name Kind What it is
ColumnSet type Bit set of value columns; combine with |. The stamp is always sent.
ColumnOpen, ColumnHigh, ColumnLow, ColumnClose, ColumnVolume const One column each.
ColumnsAll const Every value column.
ColumnBatch struct Set, Timestamp []int64, Open, High, Low, Close, Volume []float64 (nil when not asked for), Marks []uint8; Len() is the row count.
ErrNoColumns error A column query naming no column.

Slots with no candle are not rows, and there are no gap markers in a column answer (TestQueryColumns_ReturnsOnlyTheColumnsAskedFor). From ExampleClient_QueryColumns:

go
cols, err := c.QueryColumns(ctx, client.QueryRequest{
	StreamID: stream, StartTime: from, EndTime: to,
	Columns:  client.ColumnClose, // the stamps and the close, nothing else
})
if err != nil {
	return err
}
fmt.Println(cols.Len(), cols.Close[0], cols.Open == nil) // Open was not asked for

Many queries in one round trip

Name Kind What it is
MultiResult struct One sub-query's complete answer from QueryMultiAll: Status, Ticks, Points, TickData, Columns, Elsewhere, Err, Stale, LevelAt.
MultiQueryResponse struct The raw one-frame answer from QueryMulti; may be partial.
MultiQueryResult struct One sub-query within it: HasMore and ResumeFrom say where to continue.

QueryMultiAll(ctx, []QueryRequest) ([]MultiResult, error) runs many sub-queries (several streams, or several windows of one stream) to completion. Results are positional: result i answers request i, so one stream may appear twice with different windows. Nothing is merged. A missing stream marks only its own result. QueryMulti is the raw single-frame form for callers scheduling rounds themselves. A node refuses a batch with more sub-queries than its network.max_subqueries_per_request (128 by default). A node that predates the frame answers ErrorCodeUnsupported.

On a cluster, a sub-query for a stream the node asked does not serve comes back with Status 4 ("elsewhere") and Elsewhere naming the node that does; a plain Client hands it back rather than following it.

Gaps

Name Kind What it is
GapRange struct StartTs, EndTs, Status, Reason. Fillable() (bool, FillRefusal) is the one definition of whether a gap may take supplied candles; AcceptAction() says what may be done about an INCOMPLETE mark.
GapStatus type GapStatusOpen, GapStatusFilling, GapStatusClosed, GapStatusPermanent, GapStatusAccepted.
GapReason type GapReasonUnknown, GapReasonCorruption, GapReasonNetwork, GapReasonCrash, GapReasonMaintenance, GapReasonRateLimit, GapReasonExchange, GapReasonManual, GapReasonOffTime (market closure), GapReasonIncomplete (a derived bar, not a gap).
FillRefusal type Why a gap will not take supplied candles; the zero value means it will.
FillRefusalNone, FillRefusalMarketClosed, FillRefusalPermanent, FillRefusalAlreadyClosed, FillRefusalInProgress, FillRefusalAccepted const The reasons.
ListGapsRequest struct StreamID, StartTime, EndTime, Cursor/HasCursor, Limit (0 = 200, above 1,000 refused), OpenOnly, ExcludeOffTime.
ListGapsResponse struct Gaps (by start, ascending), Summary, HasMore. Resume with the last gap's StartTs as Cursor.
GapSummary struct Over the whole requested window, not the page: MissingDuration (excludes closed gaps), OffTimeDuration, Count, OpenCount, OffTimeCount, FillableCount. Durations are clipped to the window.
FillMethod type How the node makes up candles for a fill.
FillMethodLinear, FillMethodForward, FillMethodBackward const A line from the previous close to the next open; the previous close repeated; the next open repeated. The zero value is refused.
FillGapRequest struct StreamID, GapStart (exactly as ListGaps reported it), Method, MaxCandles (0 = node's cap), Overwrite (needed for a derived stream).
FillGapResponse struct Filled, HasMore (call again; it continues the same line), Gap as found.
AcceptGapRequest struct StreamID, GapStart, Accept (true marks an INCOMPLETE mark ACCEPTED; false puts it back to OPEN).
AcceptGapResponse struct Gap, the mark as it now stands.

Client gap methods:

Method What it does
ListGaps(ctx, ListGapsRequest) A stream's gaps as stored ranges, rather than one marker per interval. A gap overlapping the window is returned whole. Needs PermReadCandles.
FillGap(ctx, FillGapRequest) The node writes made-up candles (zero volume) into one gap. Refuses a market closure, a start no gap has, and a method with no neighbour to start from. Safe to re-send: a repeat fills only what is still missing. Needs PermWriteCandles.
AcceptGap(ctx, AcceptGapRequest) Accepts or un-accepts a derived bar's INCOMPLETE mark. Safe to re-send. Needs PermWriteCandles.

Never derive fillability from a gap's reason yourself: call GapRange.Fillable, the rule the node enforces with. A market closure is never fillable, because anything written there would be invented. See Gaps and trading calendars and Finding and filling gaps.

Discovery

Name Kind What it is
ListStreamsRequest struct IncludeStats, Limit (0 = 200, above 1,000 refused), Cursor (the last id's String()), Match (exactly one stream), Exchange, Symbol (case-insensitive prefix), Timeframe, SortBy, Descending, ServedHere. Filters apply on the node, before the page limit.
ListStreamsResponse struct Streams, Stats (parallel slice when asked for), HasMore.
Method What it does
Client.ListStreams(ctx, req) One page of the streams this node holds. Key-set pagination: the next page is everything strictly after the cursor, which stays correct while streams are being created. Needs PermListStreams.
ResilientClient.ListStreamsAll(ctx) ([]StreamID, error) Pages to the end; each page is retried on its own across a reconnect. Only on ResilientClient.
ListNodes(ctx) The cluster's nodes as this node's applied control-plane state holds them; an empty list means no cluster. Returns wire.ListNodesResponse, a type the public package does not alias (use :=). Needs PermListStreams, PermReadCandles or PermReadTicks — any one (TestListNodes_NeedsAReadOrTheListPermission; the method's own doc comment says only PermListStreams).
NodeStats(ctx) The node's own measurements (holdings, process and disk figures, counters, latency histograms). Returns wire.NodeStats, not aliased. Needs PermListStreams; a node that does not measure itself answers Unsupported.

Stream metadata

Name Kind What it is
StreamMetadata struct WorkingHours, GapThresholdLow, GapThresholdHigh, Closures, Lineage, CacheCapacity, CustomFields.
WorkingHours struct Timezone (IANA) and Schedule []DaySchedule. Outside it a gap is market closure.
DaySchedule struct One weekday's trading windows.
TimeWindow struct One window within a day, local time.
NewTimeWindow func NewTimeWindow(openHour, openMinute, closeHour, closeMinute int) TimeWindow.
TimeOfDay struct Hour and minute, local time; 24:00 is the day's end.
Closure struct One declared closure (holiday, halt): [StartTs, EndTs), Note.
Lineage struct A derived stream's source: Source, Kind, CloseGrace, NoTradeLimit, Since (stamped by the node), Rederive.
SourceKind type What a derived stream is made from.
SourceTicks, SourceCandles const Its source's trades, or its source's shorter candles.
LineageHistory type What a lineage declaration does with the source's existing history.
LineageHistoryFromNow, LineageHistoryRederive, LineageHistoryClear const Derive from now on; also derive everything the source holds; make the stream plain again.
SetStreamMetadataRequest struct StreamID, Create (register a stream the node does not know), Metadata.
SetStreamLineageRequest struct StreamID, History, Lineage.
AddStreamClosureRequest struct StreamID, Closure.
RemoveStreamClosureRequest struct StreamID, StartTs, EndTs.
StreamMetadataResponse struct Status (QueryStatusStreamNotFound for an unknown stream), Created, RefiledNanos (how much filed gap time the change re-classified), Metadata.
Method What it does
GetStreamMetadata(ctx, sid) Read. Needs PermReadCandles.
SetStreamMetadata(ctx, req) Replace everything but the lineage, and re-file the stream's gaps under the new calendar at once. A request carrying a lineage is refused before it is sent. Needs PermAdminStream.
AddStreamClosure(ctx, req) Declare one closure; it merges with any it overlaps, and gaps inside become market closure.
RemoveStreamClosure(ctx, req) Remove closures inside a range, cutting any that straddle it, and re-file the gaps they covered.
SetStreamLineage(ctx, req) Declare, change or clear what a stream is derived from.

The same settings are reachable from a shell through mirexa-cli's calendar, lineage and cache commands, which use the control listener instead. A stream's cache size (CacheCapacity) is set only there; SetStreamMetadata keeps the current value. See Derived streams and lineage.

Subscriptions

Name Kind What it is
SubscribeRequest struct StreamID, Ticks, Backfill (stored history first), StartTime (backfill start; 0 = earliest stored), AckWindow (bounded-ack delivery when non-zero), Offloadable, Offloaded, Partials.
UnsubscribeRequest struct StreamID, Ticks.
Subscription type Iterator over one subscription: Next(ctx) bool, Event() Event, Err(), Unsubscribe(ctx), Close(). Not safe for concurrent use.
Event struct One delivery with the wire's flags interpreted (fields below). Records() counts its records.
StreamData struct One raw delivery as the node framed it. Prefer SubscribeStream and Event.
ErrForeignBatch error A delivery for a stream this subscription did not ask for: two subscriptions are sharing one Client.
ErrSlowConsumer error The node evicted this subscription because the consumer fell behind. It ends the subscription, not the connection (TestSubscription_EvictionIsTypedAndTheConnectionSurvives); recover by re-subscribing with backfill.

Event fields: Sequence (live batches numbered from 1; backfill batches carry 0), Backfill, Live (the first live batch after backfill), Stale and LevelAt (a batch an in-sync copy sent), Dropped, MissingFirst, MissingLast, and Candles or Ticks.

Two guarantees are easy to get wrong, which is why Event computes them for you:

  • No gap, not no duplicate. The backfill window and the live queue overlap on purpose, so a record written during the backfill can arrive on both sides of the Live pivot. Ingest is idempotent by (stream, timestamp); dedupe on the same key if it matters.
  • Dropped means gone. A non-zero Dropped counts batches the node discarded because this consumer was not keeping up. Recover them with a query or a backfilling re-subscribe. The two sequence spaces are why drop detection is not a plain sequence comparison (TestSubscription_TheBackfillFlagIsWhatExcludesABatch).

Client subscription methods: SubscribeStream(ctx, req) (*Subscription, error) (preferred; consumes the node's confirmation), and the raw Subscribe, NextStreamData and Unsubscribe. No RequestTimeout applies while waiting for data: silence on a subscription is normal, so bound it with your context.

go
sub, err := c.SubscribeStream(ctx, client.SubscribeRequest{StreamID: stream, Backfill: true})
if err != nil {
	return err
}
defer sub.Close()
for sub.Next(ctx) {
	ev := sub.Event()
	if ev.Dropped > 0 {
		log.Printf("%d batches dropped (sequences %d-%d)", ev.Dropped, ev.MissingFirst, ev.MissingLast)
	}
	handle(ev.Candles)
}
return sub.Err()

The node refuses Partials (in-progress candles) with ErrorCodeUnsupported: it publishes closed candles only.[6] With AckWindow set, the node sends at most that many live batches past the last one acknowledged and never drops one; a subscriber whose buffer on the node overflows is evicted instead. Subscription.Next acknowledges the batches it has yielded, so holding an event without calling Next holds the window open.

Resuming subscriptions

Name Kind What it is
ResumingSubscriber type A subscription that survives losing its connection: it redials, repeats the handshake and re-subscribes with backfill from one nanosecond past the last record delivered. Next(ctx) (Event, error), Unsubscribe, Close, Reconnects(), Redirects(), Offloads(). Not safe for concurrent use.
NewResumingSubscriber func NewResumingSubscriber(addr string, opts Options, req SubscribeRequest, resume ResumeOptions) (*ResumingSubscriber, error). req.Backfill controls only the first subscribe; every resume backfills.
ResumeOptions struct MaxAttempts (default 5 consecutive reconnects), Backoff (default 200ms), FollowRedirects (off by default; resubscribe where a redirect points, each hop at a strictly newer partition epoch), NoOffload (keep the subscriber on the primary even when it is saturated).

By default a candle subscription offers to be moved to an in-sync copy when the primary is saturated; such events are marked Stale. See Subscribing to live data.

Resilience

Name Kind What it is
DialResilient func DialResilient(addr string, opts Options, res ResilienceOptions) (*ResilientClient, error). A failed first dial is not fatal: the client is returned alongside the error and keeps trying.
ResilientClient type A client that redials, with a circuit breaker. Safe for concurrent use; goroutines that find the connection dead share one redial.
ResilienceOptions struct Reconnect and breaker settings (below).
ConnState type Connection state as a ResilientClient sees it.
StateDisconnected, StateConnected, StateOpen, StateHalfOpen const No connection (dials on demand); connected; breaker refusing to dial; cooldown over, next operation probes.
ErrCircuitOpen error An operation refused without being attempted, because the endpoint failed to connect BreakerThreshold times in a row.
ErrAmbiguous error A write whose outcome is unknown: the connection failed while it was in flight.

ResilienceOptions fields that a ResilientClient reads:

Field Default Meaning
MaxAttempts 3 Connection attempts within one operation; 1 = dial once.
Backoff 100ms First wait between attempts, doubling, with jitter.
MaxBackoff 5s Cap on one wait.
BreakerThreshold 5 Consecutive connection failures that open the breaker; negative disables it.
BreakerCooldown 30s How long the breaker stays open before a probe.

ResilienceOptions also has FanOutLegTimeout, FanOutMaxSubQueries, PrimaryReads and ReadAfterWrite. Only the unexported routing client reads them; through the public package they have no effect.

The split that matters: reads retry across a reconnect, writes do not. A query re-run on a new connection returns the same rows, and the row iterators resume from their key-based cursor. A connection that fails while an ingest is in flight returns ErrAmbiguous; the batch may or may not be stored. A connection already known to be dead before the write is sent is not ambiguous: the batch goes out on a fresh connection as a first attempt (TestResilient_AWriteAfterTheServerClosedAnIdleConnectionIsSentFresh). FillGap, AcceptGap and the metadata calls are safe to re-send and are retried like reads.

Recovering from ErrAmbiguous: read the range back and compare, or re-send the candle batch, which is well defined for bars the node already holds (a stored bar is restated, an identical one skipped). A trade batch has no such key, because two trades may share a timestamp, so a re-sent tick batch can store a trade twice. ResilientClient has the same read, write, gap, metadata and discovery methods as Client, plus ListStreamsAll, Reconnects() and State(); it has no subscription methods (use ResumingSubscriber) and no Reauthenticate.

Backpressure and retries

Name Kind What it is
RetryOptions struct MaxAttempts (total attempts, default 1,000; 1 disables retry), BaseBackoff (default 5ms, doubling, used when the node gives no hint), MaxBackoff (default 250ms, caps every wait including the node's hint).
ErrRetriesExhausted error Every attempt was shed. Wraps the last *RemoteError.

A node under load answers ErrorCodeOverloaded from its admission check, before the batch reaches the write-ahead log, so a re-send cannot duplicate anything. The client re-sends acked ingests and reads that were shed, waiting the node's hint capped at MaxBackoff (TestIngest_DefaultsRideOutASustainedShed, TestRetryWait_DefaultsCapAHintAtAQuarterSecond, TestMockServer_AShedReadIsRetriedLikeAShedWrite). No other code is retried. Fire-and-forget writes and subscription requests are never retried. Your context and RequestTimeout still bound a call.

Observing the client

Name Kind What it is
Observer interface IngestCompleted(IngestStat), StreamDelivered(StreamStat), ConnectionChanged(ConnStat). Called synchronously on the goroutine doing the work: count and return.
IngestStat struct One completed ingest call: StreamID, Ticks, Records, Attempts (more than 1 means the node shed it), Duration (including backoff), Err.
StreamStat struct One subscription delivery: StreamID, Ticks, Records, Backfill, Live, Dropped.
ConnStat struct One ResilientClient state change: Addr, State, Reconnects, Failures (consecutive), Err. A plain Client never reports one.

The SDK ships no metrics stack; this is where you attach yours. IngestStat.Attempts is the one figure nothing else has: a shed batch never reaches the node's counters, so a producer riding out constant backpressure looks idle from the server side (TestObserver_CountsTheRetriesTheClientAbsorbed).

Errors and how to classify them

Name Kind What it is
ErrRemote error Matches any ERROR frame the node returned: errors.Is(err, client.ErrRemote).
RemoteError struct The decoded frame: Code ErrorCode, Message, RetryAfterMillis. RetryAfter() (time.Duration, bool) reports whether a retry is appropriate at all. Reach it with errors.As.
ErrorCode type Why the node refused.
ErrorCodeProtocol, ErrorCodePayloadTooLarge, ErrorCodeUnauthorized, ErrorCodeInternal, ErrorCodeUnsupported, ErrorCodeSlowConsumer, ErrorCodeOverloaded, ErrorCodeDerivedStream const The codes exported here.
ErrRedirect error Matches any *RedirectError.
RedirectError struct Embeds the redirect: Partition, Epoch, NodeID, Addr.

The wire protocol has three more codes the package does not name as constants: StalePlacement (0x0008), PartitionUnavailable (0x0009) and HistoryRequired (0x000B, "send these bars by the history route"). Compare RemoteError.Code with client.ErrorCode(0x000B) when you need one. The full list is in Error codes.

How to decide what to do with an error:

Error Did the node store anything? What to do
*RemoteError with ErrorCodeOverloaded No, guaranteed Already retried for you; ErrRetriesExhausted means every attempt was shed. Back off and resend.
*RemoteError, any other code No for writes refused before dispatch A statement about the request. Re-sending it unchanged gets the same answer.
ErrAmbiguous Unknown Reconcile: read the range back, or re-send a candle batch (see above). Never re-send ticks blindly.
ErrRedirect / *RedirectError No, guaranteed Send the request to Addr; it is a first attempt there.
ErrRequestTimeout Unknown for writes As ErrAmbiguous for a write; retry a read.
ErrClientClosed, ErrCircuitOpen No Reconnect, or wait for the breaker cooldown.
QueryStatusStreamNotFound in a response — Not an error: the stream does not exist on this node.
go
err = c.IngestCandles(ctx, stream, batch, client.DurabilityAcked)
var remote *client.RemoteError
switch {
case err == nil:
case errors.As(err, &remote):
	if _, retryable := remote.RetryAfter(); retryable {
		// shed on every attempt: back off and try again later
	}
case errors.Is(err, client.ErrAmbiguous):
	// read the range back before deciding anything
}

Redirects and clusters

On a cluster each stream is served by one node, the primary of its partition. A node asked about a stream it does not serve answers with a redirect before it touches storage, so a redirected write provably did not land. Client and ResilientClient return it as a *RedirectError naming the node that does serve it, and do not follow it themselves. ResumingSubscriber follows redirects when ResumeOptions.FollowRedirects is set. A write carries no partition epoch through the public package (its Redirector cannot be built), so the node treats it as unfenced. See Partitions and routing.

Testing against a fake node

github.com/AmiraliOmidvar/mirexa/client/clienttest starts an in-process server that speaks the real wire codecs, for your own unit tests. Every example in /client/example_test.go runs against it.

Name What it does
NewServer() (*Server, error) Starts a server on a loopback port.
Server.Addr() string The host:port to dial.
Server.Close() error Stops it and severs every connection.
Server.SeedCandles(sid, candles) / SeedTicks / SeedGaps / SeedStreamMetadata Store data so queries find it, bypassing ingest.
Server.PublishCandles(sid, candles) Deliver candles to every subscriber of the stream as a live batch.
Server.FailNext(code, message) Make the next request answer with an ERROR frame (for example ErrorCodeOverloaded to exercise retries).
Server.GrantPermissions(bitmap) Cap every later handshake's grant, to drive your permission-denied path.
Server.LastToken() string The token presented at the latest handshake.
Server.RequestCount(frameType) int How many frames of a type it handled, to assert that your client retried or did not.

The fake does not implement storage semantics (gap classification, restatement routing, calendars); seed what a test needs.

References

Source

Tests

Further reading

External

  • Package context, The Go Authors — https://pkg.go.dev/context
  • Go Modules Reference, The Go Authors — https://go.dev/ref/mod

  1. TestClientPackage_PublicSurfaceIsPinned in /client/surface_test.go. ↩︎

  2. TestClientPackage_DependencyFootprint in /client/client_test.go; the package comment in /client/client.go. ↩︎

  3. Example in /client/example_test.go, which runs against clienttest.Server and checks its output. ↩︎

  4. initFrame and unauthenticatedRequest in /internal/wireclient/client.go. ↩︎

  5. StreamID.String and ParseStreamID in /internal/types/stream.go; the CLI's -stream parser in /cmd/cli/main.go. ↩︎

  6. the Partials refusal in handleSubscribe, /internal/network/server.go. ↩︎