Connecting

Dialing a node, the options, and the reconnecting client.

Client

Client is a mirexa wire-protocol client. See the package comment for the concurrency contract. Construct with Dial.

func Dial(addr string, opts Options) (*Client, error)
type Client struct {
	// Has unexported fields.
}

Client is a wire-protocol client. It is SAFE for concurrent use: any number of goroutines may issue requests on one Client, and each receives its own response.

How: a single read-loop goroutine owns the frame reader and demultiplexes by the correlation id every frame carries — responses go to the waiter that registered the id, STREAM_DATA pushes go to the subscription stream. Writes serialize under a mutex, so frames never interleave on the wire. The claim this type carried until 2026-09-06 — “NOT safe for concurrent use — one request in flight at a time” — was true, never tested, and is now retired by TestClient_ConcurrentCallersShareOneConnection, which fails against the serial implementation with stolen responses and reader races.

What concurrency here buys and does not buy: requests overlap on the wire (no caller waits for another caller’s round trip to START), but the server’s serve loop is serial per connection, so one slow query still delays the responses behind it on this connection. Callers needing server-side parallelism use one Client per worker; a pooled client is future work.

Subscriptions: the SUBSCRIPTION side is a single ordered stream. Exactly one goroutine should consume NextStreamData (and call Subscribe/Unsubscribe); request/response calls may run concurrently with it freely. A subscription consumer that stops reading eventually blocks the read loop (the push buffer is bounded), which stalls every request on this Client — the bound is the honest alternative to unbounded memory, and the server evicts subscribers it considers too slow long before the client-side buffer matters.

func Dial(addr string, opts Options) (*Client, error)

Dial connects to addr, performs the INIT handshake, and returns a ready Client. Dial takes ClientOptions BY VALUE, and keeps doing so now that Retry has pushed the struct past gocritic’s hugeParam threshold: the zero value is the documented way to configure this client, and Dial(addr, ClientOptions{}) reading as well as it does is worth more than one 80-byte copy per CONNECTION. Same reasoning at the three other flagged sites.

func (c *Client) AcceptGap(ctx context.Context, req AcceptGapRequest) (AcceptGapResponse, error)

AcceptGap marks a derived bar’s INCOMPLETE mark ACCEPTED (“known incomplete, keep it”), or with req.Accept false puts an accepted mark back to OPEN. Requires PermWriteCandles. The node refuses anything but an incomplete mark, a start no gap has (re-read ListGaps) and a mark in the wrong status, each with its reason.

SAFE TO RE-SEND, like FillGap: a mark already where it was asked to be is answered as it stands.

func (c *Client) AddStreamClosure(ctx context.Context, req AddStreamClosureRequest) (StreamMetadataResponse, error)

AddStreamClosure declares one closure — a holiday, a halt — on a known stream; it merges with any it overlaps, and gaps inside it are re-filed as market closure.

func (c *Client) Close() error

Close closes the underlying connection. Every outstanding and future operation fails with ErrClientClosed.

func (c *Client) FillGap(ctx context.Context, req FillGapRequest) (FillGapResponse, error)

FillGap asks the node to fill one gap with candles it makes up from the real candles either side, by req.Method: a straight line (linear), the previous candle’s close carried forward, or the next candle’s open carried back. Every made-up candle has zero volume. Requires PermWriteCandles.

The node refuses a market closure, a start no gap has (re-read ListGaps) and a method with no neighbor to start from. It writes at most req.MaxCandles (or its own cap); resp.HasMore says to call again, and the next call carries on the same line.

SAFE TO RE-SEND, which is why a lost connection is retried here rather than reported ambiguous: a repeated request fills only the slots still missing, with the values the first would have written, and one that finds none answers Filled 0.

func (c *Client) GetStreamMetadata(ctx context.Context, sid StreamID) (StreamMetadataResponse, error)

GetStreamMetadata reads a stream’s metadata.

func (c *Client) GrantedPermissions() uint64

GrantedPermissions returns the permission bitmap the server actually granted this session, from INIT_ACK.

It MAY BE NARROWER than the token asked for: a node can be configured with a ceiling (security.max_permissions) that clamps every grant regardless of what any token carried. Check it rather than assuming the token was honored – discovering a missing permission here costs one branch, discovering it as a rejected ingest costs the batch.

Use wire.PermissionNames to render it, or HasPermission to test bits.

func (c *Client) HasPermission(perm uint64) bool

HasPermission reports whether this session’s grant carries every bit in perm.

Every, not any: HasPermission(wire.PermWriteCandles|wire.PermWriteTicks) is false on a session that may write only candles. wire.GrantIncludes defines the rule and is shared with the server’s own view, so the two cannot drift.

Unlike ResilientClient.GrantedPermissions, there is no “not connected” case to disambiguate here: a Client exists only after a successful handshake, so false means denied.

func (c *Client) IngestCandles(
	ctx context.Context,
	streamID StreamID,
	candles []Candle,
	d Durability,
) error

IngestCandles sends one candle batch for streamID. With DurabilityAcked it blocks until the server’s INGEST_ACK — a durability receipt — or an ERROR frame returned as an error wrapping ErrRemote; with DurabilityFireAndForget it returns once the frame is written. Canceling ctx abandons the wait, not the server-side operation; the late response is dropped, never misdelivered.

A bar the stream already stores is RESTATED with the batch’s values, wherever the server keeps it, and one identical to what is stored is skipped — so re-sending a batch is safe and rewrites nothing. IngestCorrectionCandles is the strict form, refusing new bars. A bar older than anything stored is still refused: only IngestHistoryCandles installs one.

func (c *Client) IngestCorrectionCandles(
	ctx context.Context,
	streamID StreamID,
	candles []Candle,
	d Durability,
) error

IngestCorrectionCandles restates bars the server has already stored — an exchange republishing a closed bar, which is routine — and REFUSES any bar past the newest one the stream holds.

IngestCandles restates stored bars too: the server routes each bar itself, superseding one still in its hot cache through the version chain and writing a patch chunk, which the query planner overlays on read, for one already in an immutable chunk. This call is the strict form, for a caller that means to correct history and wants to be told, with ErrBadBatch, when a bar it sends is new instead. A bar identical to what is stored is skipped by both.

Corrections cannot be combined with history ingest.

func (c *Client) IngestHistoryCandles(
	ctx context.Context,
	streamID StreamID,
	candles []Candle,
	d Durability,
) error

IngestHistoryCandles sends one batch of BULK HISTORICAL candles for streamID.

History takes a different route below the wire than live data: it stages in the server’s own columnar arena, compresses on a worker pool, and installs chunks straight into the stream index with no WAL. The live path would refuse these candles outright — the hot cache is a ring anchored near the present.

The two durabilities are the throughput/commit split a backfill client wants:

  • DurabilityFireAndForget returns once the frame is written. Candles are STAGED and are not yet queryable.

  • DurabilityAcked blocks until the server has compressed the stream’s staged candles and installed the chunks, which is when they become queryable. Being chunk-installed rather than merely logged, this is a stronger promise than the live acked path makes.

Send the bulk of a backfill fire-and-forget and finish with one acked call.

func (c *Client) IngestTicks(ctx context.Context, streamID StreamID, ticks []Tick, d Durability) error

IngestTicks sends one tick batch for streamID. Semantics match IngestCandles.

func (c *Client) ListGaps(ctx context.Context, req ListGapsRequest) (ListGapsResponse, error)

ListGaps asks the node where a stream’s data is missing, as RANGES.

Not the same question as a candle query with gaps included. That one answers per INTERVAL – a weekend on a 1m stream is one hole and 2,880 gap points – and leaves the caller to rebuild ranges by spotting runs of adjacent points, which is a second definition of what a gap is. gap.idx stores ranges; this returns them as stored.

Requires PermReadCandles: a gap listing describes one stream’s data, and where data is absent is as much a fact about it as where it is present.

The response’s Summary covers the whole requested window rather than the returned page, so paging does not change it. Whether any given gap may be FILLED is not on the wire: call types.GapRange.Fillable, which is the one definition both sides share.

func (c *Client) ListNodes(ctx context.Context) (wire.ListNodesResponse, error)

ListNodes asks the node for the cluster’s nodes as its own applied control-plane state holds them. An empty list means the node has no cluster: it is the only node. Requires PermListStreams — the list exists for cluster-wide discovery.

func (c *Client) ListStreams(ctx context.Context, req ListStreamsRequest) (ListStreamsResponse, error)

ListStreams returns one page of the streams this node holds.

Requires the LIST_STREAMS permission, which is separate from the read permissions on purpose: a node can serve prices without disclosing which instruments it carries.

Pagination is key-set, not offset-based. Pass the String() form of the last identity from the previous page as req.Cursor; the next page is everything strictly greater in the registry’s sorted order. That stays correct while streams are being created, which an offset would not – it would skip or repeat entries under a paging client.

Most callers want ListStreamsAll instead; see the note there about why the paging loop belongs here rather than in a caller.

func (c *Client) NextStreamData(ctx context.Context) (StreamData, error)

NextStreamData blocks until the next STREAM_DATA frame arrives, ctx ends, or the connection dies. An ERROR frame belonging to the subscription (slow-consumer eviction) is returned as an error wrapping ErrRemote.

Unlike request/response calls, NO RequestTimeout applies here (changed 2026-09-07 with the context migration): silence on a subscription is a normal state, not a failure, and the old behavior — erroring after RequestTimeout of quiet — forced every consumer into a retry loop around ordinary idleness. A caller that wants a bound passes a ctx that carries one.

func (c *Client) NodeStats(ctx context.Context) (wire.NodeStats, error)

NodeStats asks the node for its own measurements: what it holds, what it is primary of, its process and disk figures, its cumulative counters and latency histograms. Requires PermListStreams. A node that does not measure itself answers Unsupported.

func (c *Client) OverwriteCandles(
	ctx context.Context,
	streamID StreamID,
	candles []Candle,
	d Durability,
	route WriteRoute,
) error

OverwriteCandles writes a DERIVED stream: one the node writes itself from its source, and which every other write refuses with wire.ErrorCodeDerivedStream. The write lands by route like the matching Ingest call; a later re-derivation of the same bar writes over it again — the last one written wins. On a stream nobody derives it is that ordinary write.

func (c *Client) QueryCandles(ctx context.Context, q QueryRequest) (QueryResponse, error)

QueryCandles runs one range query and returns the decoded response. A server-side ERROR frame is returned as an error wrapping ErrRemote; in-band statuses (stream not found, invalid range) come back in QueryResponse.Status.

func (c *Client) QueryCandlesRows(ctx context.Context, q QueryRequest) *CandleRows

QueryCandlesRows starts a paged iteration over q’s range.

q.MaxResults, when set, is the TOTAL cap across all pages — the iterator stops after that many points. Page sizing is the server’s business (it fills frames up to its frame cap); the caller never sees page boundaries except as fetch latency. Descending ranges page newest-first: the cursor walks EndTime backward instead of StartTime forward.

func (c *Client) QueryColumns(ctx context.Context, q QueryRequest) (*ColumnBatch, error)

QueryColumns reads q’s whole range as columns: q.Columns names the value columns wanted, and the batch holds those and the stamps, nothing else. A node decodes, sends and this holds only what was asked for, so one column of a long stream costs a third of what reading it whole does (BenchmarkQuery_AWholeStream). q.MaxResults is the total cap; ranges larger than one frame are paged here. Gap markers, ticks, stale reads and rollups are not column queries.

func (c *Client) QueryMulti(ctx context.Context, queries []QueryRequest) (MultiQueryResponse, error)

QueryMulti sends one QUERY_MULTI frame and returns its decoded response — exactly one round trip, no re-planning.

The response may be PARTIAL: results are filled in request order until the server’s frame budget runs out, and a result the server did not reach carries HasMore with its resume point at the untouched start of its window. Most callers want QueryMultiAll, which owns that loop. This raw form exists for callers doing their own scheduling across rounds.

MaxResults on a sub-query caps records PER RESPONSE here, exactly as it does on a single query; QueryMultiAll is the layer that turns it into a total cap.

func (c *Client) QueryMultiAll(ctx context.Context, queries []QueryRequest) ([]MultiResult, error)

QueryMultiAll runs a batch to COMPLETION: every sub-query either delivers its full range (subject to its MaxResults, which this layer treats as a total cap, matching CandleRows) or reports its own terminal status.

One logical operation, N round trips where N is set by how much data fits a frame — the caller never sees the paging. Queries are pure reads, so a transport error mid-way loses nothing but time; the error is returned and the partial accumulation discarded rather than handed over half-labeled.

func (c *Client) QueryTicks(ctx context.Context, q QueryRequest) (TickResponse, error)

QueryTicks runs one tick range query. The request’s Ticks flag is set for the caller, so q.Ticks need not be set.

func (c *Client) QueryTicksRows(ctx context.Context, q QueryRequest) *TickRows

QueryTicksRows starts a paged iteration over q’s tick range. Semantics match QueryCandlesRows; q.Ticks is set for the caller.

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

Reauthenticate renews the session’s token over the open connection: it asks the TokenSource (or takes Token) for a token, sends it in a REAUTH frame, and on the server’s REAUTH_ACK adopts the grant it names. The connection, the session and its subscriptions are kept; a subscription then runs past the old token’s expiry, and the server holds requests to the new grant. A refusal — a token not from a trusted issuer, expired, or naming another tenant — is a *RemoteError, and changes nothing on either side.

func (c *Client) RemoveStreamClosure(ctx context.Context, req RemoveStreamClosureRequest) (StreamMetadataResponse, error)

RemoveStreamClosure removes closures inside [req.StartTs, req.EndTs), cutting any that straddle it, and re-files the gaps they covered.

func (c *Client) SessionID() uint32

SessionID returns the session id assigned by the server’s INIT_ACK.

func (c *Client) SetStreamLineage(ctx context.Context, req SetStreamLineageRequest) (StreamMetadataResponse, error)

SetStreamLineage declares a known stream derived from req.Lineage’s source, deriving from now on (LineageHistoryFromNow) or also from the source’s whole history (LineageHistoryRederive); LineageHistoryClear with no lineage makes it a plain stream again. The node stamps Since.

func (c *Client) SetStreamMetadata(ctx context.Context, req SetStreamMetadataRequest) (StreamMetadataResponse, error)

SetStreamMetadata replaces a stream’s metadata — calendar, gap thresholds, closures, custom fields — and re-files its gaps under the new calendar (resp.RefiledNanos says how much). The stream’s lineage is kept: it is set only by SetStreamLineage, and a request carrying one is refused before it is sent. req.Create registers a stream the node does not know (resp.Created).

func (c *Client) Subscribe(ctx context.Context, req SubscribeRequest) error

Subscribe registers a live subscription on this connection and blocks until the server confirms it with the Established frame.

The subscription stream is single-consumer: exactly one goroutine should call Subscribe/NextStreamData/Unsubscribe, while request/response methods may run concurrently on other goroutines. Two goroutines consuming NextStreamData would split one ordered stream between them arbitrarily.

func (c *Client) SubscribeStream(ctx context.Context, req SubscribeRequest) (*Subscription, error)

SubscribeStream registers a subscription and returns an iterator over its deliveries. The server’s confirmation is consumed here, so the first Next yields data.

func (c *Client) Unsubscribe(ctx context.Context, req UnsubscribeRequest) error

Unsubscribe cancels a subscription. The server does not answer, so this returns as soon as the frame is written; batches already queued may still arrive before delivery stops.

Options

Options configures Dial. The zero value is usable: plaintext TCP, 10s dial timeout, 30s request timeout, read+write permissions on candles and ticks. (Named Options, not ClientOptions: the package name already says client.)

type Options struct {
	// Redirector, when set, fences this client's WRITES: each carries the
	// partition epoch the client was last told, so a primary can refuse one
	// formed under a superseded view of where the partition lives.
	//
	// Without it a write carries no epoch and the primary treats it as
	// unfenced, which is also what every write does before the client has been
	// redirected even once — a first request has to work.
	Redirector *Redirector
	// TLS enables TLS with the given client config; nil dials plaintext.
	TLS *tls.Config
	// DialTimeout bounds the TCP (and TLS) connect. Default 10s.
	DialTimeout time.Duration
	// RequestTimeout bounds each request/response exchange, including the
	// INIT handshake. Default 30s.
	RequestTimeout time.Duration
	// Token is the signed session token to present at the handshake, as
	// printed by `mirexa-token issue`. Empty dials UNAUTHENTICATED, which only
	// an auth-disabled server accepts.
	//
	// The token carries the tenant, the permissions and the expiry, all signed.
	// That is why there are no TenantID/Permissions/TokenValidity options
	// beside it any more: until 2026-09-10 a client filled those in ITSELF and
	// the server enforced whatever arrived, so "permissions" was a request the
	// server rubber-stamped. Leaving the fields would invite a caller to set
	// one and expect it to mean something.
	//
	// The server may grant LESS than the token asks for; read
	// GrantedPermissions after Dial rather than assuming.
	Token string
	// TokenSource, when set, is consulted for a token on EVERY connect,
	// including every reconnect, and takes precedence over Token.
	//
	// This is what lets a long-lived client outlive its own token. Tokens
	// expire within the hour by design; a ResilientClient holding a static
	// string would reconnect with the same expired token forever, turning a
	// routine reconnect into a permanent outage the first time it happened
	// after expiry. Point this at whatever re-reads the file or environment
	// your orchestrator refreshes.
	//
	// It is called synchronously on the dial path, so it should be cheap and
	// must not block indefinitely. An error fails the connect.
	//
	// With a TokenSource the client also RENEWS its session's token before it
	// expires (§7.8.1): once two-thirds of the token's life has passed it asks
	// the TokenSource again and hands the new token over the open connection
	// (Reauthenticate), so a subscription outlives its tokens without a
	// reconnect. A renewal that fails is not retried: the session goes on under
	// the token it has, and its expiry is handled as it always was.
	TokenSource func() (string, error)
	// DisableRenewal turns the automatic renewal off; Reauthenticate still
	// renews by hand.
	DisableRenewal bool
	// MaxFramePayloadBytes bounds accepted response payloads. Default 16MiB,
	// matching the server default.
	MaxFramePayloadBytes uint32
	// Retry tunes automatic re-sending of ACKED ingests and reads the server
	// shed. The zero value retries — see RetryOptions for why that is the
	// default and why only ErrorCodeOverloaded qualifies.
	Retry RetryOptions
	// Observer receives client-side measurements — most usefully the retry
	// count, which exists nowhere else because a shed batch never reaches the
	// server's own counters. Nil measures nothing, which is the default.
	Observer Observer
}

ClientOptions configures Dial.

ResilientClient

ResilientClient is a Client that redials: it survives a dropped connection, a restarting server, and a network blip, with a circuit breaker so a dead endpoint fails fast instead of costing every call a full backoff schedule.

READS retry across a reconnect — re-running a query returns the same rows. WRITES do not. A connection that fails while an ingest is in flight leaves the batch’s fate genuinely unknown, so the call returns ErrAmbiguous and the caller reconciles; re-sending blindly risks duplicating a bar the server already holds. A connection known to be down BEFORE the attempt is not ambiguous — the batch simply goes out on a fresh one.

Subscriptions are not covered here: they need re-subscription with backfill from the last record delivered, which is ResumingSubscriber.

func DialResilient(addr string, opts Options, res ResilienceOptions) (*ResilientClient, error)
type ResilientClient struct {
	// Has unexported fields.
}

ResilientClient is a Client that redials.

It is safe for concurrent use. Operations share one underlying connection and one reconnect: when several goroutines find the connection dead, one dials and the rest wait for that result rather than opening a connection each.

It does NOT cover subscriptions — those are a single ordered stream that must re-subscribe with backfill from the last record delivered, which is ResumingSubscriber’s whole job. Use that.

func DialResilient(addr string, opts Options, res ResilienceOptions) (*ResilientClient, error)

DialResilient connects to addr and returns a client that redials.

The initial dial is attempted eagerly, but its failure is NOT fatal: the returned client is usable and will keep trying, because a program that starts before its database is a normal deployment and not an error. The dial error is returned alongside a live client so a caller who wants to fail fast still can.

func (rc *ResilientClient) AcceptGap(ctx context.Context, req AcceptGapRequest) (AcceptGapResponse, error)

AcceptGap accepts or puts back one mark, redialing if the connection is dead. Retried on either kind of connection failure, like a read: re-sending it is safe (see Client.AcceptGap).

func (rc *ResilientClient) AddStreamClosure(ctx context.Context, req AddStreamClosureRequest) (StreamMetadataResponse, error)

AddStreamClosure declares one closure, redialing if needed.

func (rc *ResilientClient) Close() error

Close releases the current connection. Later operations fail with ErrClientClosed.

func (rc *ResilientClient) FillGap(ctx context.Context, req FillGapRequest) (FillGapResponse, error)

FillGap fills one gap, redialing if the connection is dead. Retried on either kind of connection failure, like a read: re-sending it is safe (see Client.FillGap).

func (rc *ResilientClient) GetStreamMetadata(ctx context.Context, sid StreamID) (StreamMetadataResponse, error)

GetStreamMetadata reads a stream’s metadata, redialing if needed.

func (rc *ResilientClient) GrantedPermissions() uint64

GrantedPermissions returns the permission bitmap the server granted on the CURRENT connection, or 0 if there is none.

Zero means NOT CONNECTED, not “granted nothing”: “granted nothing”, because a token granting nothing is refused at issuance and a session with no permissions could not do anything anyway. Treat 0 as “ask again once connected”.

The grant is re-read on every reconnect rather than cached, since the token is re-presented each time and a node’s ceiling can change under a restart.

func (rc *ResilientClient) IngestCandles(
	ctx context.Context, streamID StreamID, candles []Candle, d Durability,
) error

IngestCandles sends a batch, dialing first if the connection is down.

A connection that fails WHILE the batch is in flight returns ErrAmbiguous: the batch may or may not be stored, and this package will not guess. Query the range back to find out. A connection already known to be down before the attempt is not ambiguous — the batch simply goes out on a fresh one.

func (rc *ResilientClient) IngestCorrectionCandles(
	ctx context.Context, streamID StreamID, candles []Candle, d Durability,
) error

IngestCorrectionCandles restates stored bars; same ambiguity contract, and the natural recovery from an ambiguous plain ingest.

func (rc *ResilientClient) IngestHistoryCandles(
	ctx context.Context, streamID StreamID, candles []Candle, d Durability,
) error

IngestHistoryCandles is the bulk backfill route; same ambiguity contract.

func (rc *ResilientClient) IngestTicks(
	ctx context.Context, streamID StreamID, ticks []Tick, d Durability,
) error

IngestTicks is IngestCandles for ticks; same ambiguity contract.

func (rc *ResilientClient) ListGaps(ctx context.Context, req ListGapsRequest) (ListGapsResponse, error)

ListGaps reads one page of a stream’s gaps, redialing if the connection is dead. A read, so it is retried on either kind of connection failure.

func (rc *ResilientClient) ListNodes(ctx context.Context) (wire.ListNodesResponse, error)

ListNodes asks for the cluster’s nodes, redialing if the connection is dead. A read, so it is retried on either kind of connection failure.

func (rc *ResilientClient) ListStreams(
	ctx context.Context,
	req ListStreamsRequest,
) (ListStreamsResponse, error)

ListStreams pages the node’s stream catalog, redialing if the connection is dead. A read, so it is retried on either kind of connection failure.

func (rc *ResilientClient) ListStreamsAll(ctx context.Context) ([]StreamID, error)

ListStreamsAll pages until the catalog is exhausted.

NOTE the retry boundary: each PAGE is retried independently, so a reconnect mid-listing resumes from the current cursor rather than restarting. Because the cursor is a stream id in a stable total order, that resumption is exact – no entry is skipped or repeated. An offset-based cursor could not make that promise across a reconnect.

func (rc *ResilientClient) NodeStats(ctx context.Context) (wire.NodeStats, error)

NodeStats asks for the node’s measurements, redialing if the connection is dead. A read, so it is retried on either kind of connection failure.

func (rc *ResilientClient) OverwriteCandles(
	ctx context.Context, streamID StreamID, candles []Candle, d Durability, route WriteRoute,
) error

OverwriteCandles writes a derived stream; same ambiguity contract.

func (rc *ResilientClient) QueryCandles(ctx context.Context, q QueryRequest) (QueryResponse, error)

QueryCandles runs a range query, reconnecting if the connection failed.

func (rc *ResilientClient) QueryCandlesRows(ctx context.Context, q QueryRequest) *CandleRows

QueryCandlesRows pages a range through the reconnecting connection: a page fetch that loses the connection redials and re-fetches THAT page, and the cursor is key-based, so the iteration resumes exactly where it was.

func (rc *ResilientClient) QueryColumns(ctx context.Context, q QueryRequest) (*ColumnBatch, error)

QueryColumns is Client.QueryColumns over a connection that redials: a page that loses its connection is fetched again, which is safe because the cursor is key-based.

func (rc *ResilientClient) QueryMulti(
	ctx context.Context,
	queries []QueryRequest,
) (MultiQueryResponse, error)

QueryMulti sends one batch, reconnecting if the connection failed.

func (rc *ResilientClient) QueryMultiAll(ctx context.Context, queries []QueryRequest) ([]MultiResult, error)

QueryMultiAll runs a batch to completion across reconnects. Each ROUND reconnects independently, so a connection lost mid-batch costs one round, not the accumulated results.

func (rc *ResilientClient) QueryTicks(ctx context.Context, q QueryRequest) (TickResponse, error)

QueryTicks is QueryCandles for ticks.

func (rc *ResilientClient) QueryTicksRows(ctx context.Context, q QueryRequest) *TickRows

QueryTicksRows is QueryCandlesRows for ticks.

func (rc *ResilientClient) Reconnects() int

Reconnects reports how many times a new connection has replaced a dead one. It excludes the initial dial.

func (rc *ResilientClient) RemoveStreamClosure(ctx context.Context, req RemoveStreamClosureRequest) (StreamMetadataResponse, error)

RemoveStreamClosure removes closures in a range, redialing if needed.

func (rc *ResilientClient) SetStreamLineage(ctx context.Context, req SetStreamLineageRequest) (StreamMetadataResponse, error)

SetStreamLineage declares or clears a lineage, redialing if needed.

func (rc *ResilientClient) SetStreamMetadata(ctx context.Context, req SetStreamMetadataRequest) (StreamMetadataResponse, error)

SetStreamMetadata replaces a stream’s metadata, redialing if needed.

func (rc *ResilientClient) State() ConnState

State reports the current connection state.

ResilienceOptions

ResilienceOptions tunes reconnection and the breaker. The zero value is usable: 3 attempts per operation, 100ms doubling to 5s, breaker after 5 consecutive connection failures with a 30s cooldown.

type ResilienceOptions struct {
	// MaxAttempts bounds connection attempts within ONE operation, so a
	// caller's single call cannot block on an unbounded retry schedule.
	// Default 3; 1 means "dial once, do not retry".
	MaxAttempts int
	// Backoff is the first wait between connection attempts, doubling per
	// attempt with jitter added on top. Default 100ms.
	Backoff time.Duration
	// MaxBackoff caps one wait. Default 5s.
	MaxBackoff time.Duration
	// BreakerThreshold is how many CONSECUTIVE connection failures open the
	// breaker. Default 5; 0 uses the default, and a negative value disables
	// the breaker entirely.
	BreakerThreshold int
	// BreakerCooldown is how long the breaker stays open before admitting a
	// probe. Default 30s.
	BreakerCooldown time.Duration
	// FanOutLegTimeout bounds one node's part of a RoutingClient.QueryMultiAll
	// — the leg sent to that node — so one slow node ends its own leg rather
	// than holding the call to the caller's deadline. Zero leaves the caller's
	// context as the only bound; there is no default, because nothing measures
	// how long a deployment's largest batch takes.
	FanOutLegTimeout time.Duration
	// FanOutMaxSubQueries is the most sub-queries one leg of a
	// RoutingClient.QueryMultiAll carries; a node's part of a batch over it is
	// sent as several legs at once. A node refuses a QUERY_MULTI over its own
	// max_subqueries_per_request whole, so this must not exceed the smallest
	// cap in the cluster (TestFanOut_ABatchOverANodesPerRequestCapIsSentInPieces).
	// Default 128, the node's default cap; 0 uses the default.
	FanOutMaxSubQueries int
	// PrimaryReads turns replica reads off for a RoutingClient: every candle
	// query goes to the stream's primary and is answered fresh, as before
	// Phase 8 §8.12. The default (false) sends a candle query to an in-sync copy
	// of its partition when one exists, so the answer MAY BE STALE — marked as
	// such, and no further behind than the node's cluster.copy_read_max_staleness.
	// One call opts out with WithFreshReads instead.
	PrimaryReads bool
	// ReadAfterWrite is how long after this client writes a stream its reads of
	// it stay on the primary, so a client that writes and reads back (above all
	// one reconciling an ErrAmbiguous write) never reads from a copy that has
	// not caught up. Default 10s; negative turns the pin off. It cannot see
	// writes made by another process.
	ReadAfterWrite time.Duration
}

ResilienceOptions tunes reconnection and the breaker. The zero value is usable: 3 attempts, 100ms doubling to 5s, breaker after 5 consecutive connection failures with a 30s cooldown.

ConnState

ConnState is the connection lifecycle: disconnected, connected, open (breaker refusing), half-open (probing).

type ConnState uint8

ConnState is the connection lifecycle as ResilientClient sees it.

const (
	// StateDisconnected has no usable connection and will dial on demand.
	StateDisconnected ConnState = iota
	// StateConnected holds a live connection.
	StateConnected
	// StateOpen is the breaker refusing to dial until its cooldown expires.
	StateOpen
	// StateHalfOpen is the cooldown having expired: the next operation
	// dials, and its outcome closes or re-opens the breaker.
	StateHalfOpen
)
func (s ConnState) String() string

RetryOptions

RetryOptions tunes automatic re-sending of ACKED ingests and reads the server shed. Set Options.Retry to override; the zero value makes up to 1,000 attempts, honoring the server’s backoff hint and capping each wait at 250ms.

type RetryOptions struct {
	// MaxAttempts bounds TOTAL attempts, not retries after the first — so 3
	// means one send plus at most two more. Default 1000: a bulk load meets a
	// node whose caches are all full at once, which sheds every writer for a few
	// milliseconds at a time, and a budget of 3 gave up during exactly that
	// (TestIngest_DefaultsRideOutASustainedShed). The caller's context and
	// RequestTimeout still bound a call. Set to 1 to disable retry entirely;
	// negative is refused by validate.
	MaxAttempts int
	// BaseBackoff is the first wait when the server sheds WITHOUT a hint, and
	// doubles per attempt. A server that sends a hint overrides it. Default
	// 5ms.
	BaseBackoff time.Duration
	// MaxBackoff caps any single wait, INCLUDING a server hint, so a writer
	// comes back while the eviction it was told to wait for is in progress
	// rather than seconds after it. Default 250ms
	// (TestRetryWait_DefaultsCapAHintAtAQuarterSecond).
	MaxBackoff time.Duration
}

RetryOptions tunes automatic retry of shed requests — acked ingests and reads alike. The zero value is usable and retries: backpressure a caller has to hand-roll a reaction to is backpressure most callers will ignore.