Mirexa Go SDK — client guide
Import path: github.com/AmiraliOmidvar/mirexa/client
This is the complete guide to the public Go client: connecting, authenticating, writing candles and ticks, reading them back, gaps, discovery, subscriptions, resilience, measurement, errors and testing. The durability model is its companion and states exactly what each kind of acknowledgement promises.
The code blocks here are abbreviated: they assume a ctx, a stream and a time
range. The same flows, complete and compiling, are the Example* functions in
client/example_test.go, and go test runs every one
of them against an in-process server and checks its output. Where this page and an
example disagree, the example is right and this page is stale. Every name below is
also documented in go doc github.com/AmiraliOmidvar/mirexa/client.
1. Install, and what importing costs
go get github.com/AmiraliOmidvar/mirexa/client
Importing the package compiles in the wire protocol and the data model, and nothing
else: no storage engine, no write-ahead log, no metrics stack, and no third-party
dependency at all. TestClientPackage_DependencyFootprint fails the build if an
import ever drags one in.
The package is a curated set of type aliases and thin wrappers. Its exported names
are pinned by TestClientPackage_PublicSurfaceIsPinned, so the surface changes only
deliberately.
2. The data model
Streams
A stream is one instrument at one resolution on one exchange:
stream := client.NewStreamID("binance", "BTCUSDT", "1m")
Field |
Meaning |
|---|---|
|
the venue, free text |
|
the instrument, free text |
|
|
The server validates the timeframe on every operation. An unparseable one is refused,
never defaulted. stream.String() renders the id as symbol:timeframe:exchange
(BTCUSDT:1m:binance). That is the form listing cursors use, and
types.ParseStreamID reads it back.
You do not create a stream ahead of time. The first write to an id registers it.
Candles and ticks
type Candle struct {
Timestamp int64 // Unix nanoseconds: the START of the bar's interval
Open, High, Low, Close, Volume float64
}
type Tick struct {
Timestamp int64 // Unix nanoseconds
Price, Volume float64
}
The server validates every record it ingests:
Every value must be finite and storable. Values are stored as fixed point with four decimal places, so
|value|must be below about 9.22×10¹⁴. NaN, ±Inf and anything larger are refused.Volume must be ≥ 0. Prices may be negative: WTI settled at −$37.63 on 2020-04-20.
Candles must be consistent:
Low ≤ Open, Close ≤ High.Candles must sit on the stream’s interval grid. A 1m stream’s bars are one minute apart, measured from the stream’s first bar. Truncating the timestamp to the interval (
t.Truncate(time.Minute).UnixNano()) keeps every bar on the grid.
A batch that breaks any of these rules is refused as a whole, before anything is
stored, with ErrorCodeProtocol.
Query results: points, not just candles
A candle query returns []CandlePoint. Each point is either a bar or a gap marker:
a slot that has no bar, together with the reason it has none (see Gaps).
type CandlePoint struct {
Candle Candle // zero when IsGap
IsGap bool
Status GapStatus // meaningful only when IsGap
Reason GapReason // meaningful only when IsGap
}
3. Connecting
c, err := client.Dial("localhost:8080", client.Options{})
if err != nil {
return err
}
defer c.Close()
Dial opens the TCP connection, runs the INIT handshake and returns a ready
*Client. Options{} works as it is. A zero value in any field means “use the
default”. A value that cannot be what you meant, such as a negative timeout or a frame
cap under the 4 KiB floor, makes Dial fail with ErrInvalidOptions, so the mistake
does not show up later as a confusing connection error.
Options
Field |
Default |
Meaning |
|---|---|---|
|
nil: plaintext |
Dial TLS with this config. |
|
10s |
Bounds the TCP (and TLS) connect. |
|
30s |
Bounds each request/response exchange, the handshake included. Subscriptions are exempt: a quiet subscription is normal. |
|
empty |
The signed session token, as printed by |
|
nil |
Called for a token on every connect and reconnect. Takes precedence over |
|
false |
Turns off automatic token renewal. |
|
16 MiB |
The largest response payload accepted. Matches the server default. |
|
retries |
Re-sending of requests the server shed. See §5.6. |
|
nil |
Receives client-side measurements. See §12. |
|
nil |
Cluster routing plumbing. Leave it nil (§11). |
TLS
c, err := client.Dial("db.internal:8443", client.Options{
TLS: &tls.Config{ServerName: "db.internal", RootCAs: pool},
})
When the server has TLS enabled, a plaintext client fails at the handshake. The reverse is also true.
What a connection gives you
Method |
Returns |
|---|---|
|
The session id the server assigned. |
|
The permission bitmap the server actually granted (§4). |
|
True when the grant includes every bit in |
|
Closes the connection. Every outstanding and later call fails with |
4. Authentication and permissions
A node with security.auth.enabled: true accepts only sessions that present a token
signed by one of its trusted issuer keys. A node with auth off (the default) accepts a
tokenless client, and in that case the permissions the client asks for are taken on
trust.
Getting a token
Tokens are minted offline with mirexa-token. No service is involved:
mirexa-token keygen -name ops -dir ./keys # once: writes ops.key (0600) + ops.pub
mirexa-token issue -key ./keys/ops.key \
-perms READ_CANDLES,WRITE_CANDLES,LIST_STREAMS \
-validity 1h > token.txt
mirexa-token inspect "$(cat token.txt)" -pub ./keys/ops.pub
The node trusts the public key through security.auth.trusted_keys in its config. A
token is an Ed25519-signed statement of a tenant, a set of permissions and an expiry.
It can be valid for at most client.MaxTokenValidity (one hour), and both the issuer
and the server refuse anything longer. issue defaults to 30 minutes.
Presenting it
// A static token suits a short-lived program.
c, err := client.Dial(addr, client.Options{Token: tok})
// A long-lived program should re-read its token on every connect.
c, err := client.Dial(addr, client.Options{
TokenSource: func() (string, error) {
b, err := os.ReadFile("/run/secrets/mirexa-token")
return strings.TrimSpace(string(b)), err
},
})
Use TokenSource for anything that runs longer than a token lives. It is called
on every dial, including every reconnect. A client holding a static string would
reconnect with an expired token forever. The function runs on the dial path, so it
must be fast and must not block. If it returns an error, the connect fails.
Renewal
When TokenSource is set, the client renews its session’s token before the token
expires. Two-thirds of the way through the token’s life, it asks the TokenSource
again and sends the new token over the open connection. The connection, the session
and any subscription all carry on without a reconnect.
A failed renewal is not retried. The session continues under its current token, and that token’s expiry is handled as before (see the next subsection).
A renewal that narrows the grant ends any subscription the new grant no longer permits.
c.Reauthenticate(ctx)renews immediately. It works whether or not automatic renewal is on. If the server refuses the new token (untrusted issuer, already expired, a different tenant), you get a*RemoteErrorand nothing changes on either side.Options.DisableRenewalturns the automatic renewal off.
When a token expires mid-session
A writer or reader is refused at its next request with
ErrorCodeUnauthorized.A subscriber is disconnected at the expiry. A node may grant a grace period (
security.auth.subscriber_grace, default 0).The handshake refuses an expired token outright. A node can also revoke an issuer key cluster-wide. After that, every session signed by that key is refused at its next frame.
Permissions
Constant |
Name |
Grants |
|---|---|---|
|
|
Tick queries and tick subscriptions. |
|
|
Candle queries, candle subscriptions, |
|
|
|
|
|
|
|
|
|
|
|
|
ADMIN_CLUSTER applies only to the gRPC control plane and has no effect on this
protocol.
The grant may be narrower than the token. A node can cap every grant with
security.max_permissions, whatever the token asks for. Check the grant before
relying on it:
if !c.HasPermission(client.PermWriteCandles) {
return fmt.Errorf("session may not write: granted %v",
client.PermissionNames(c.GrantedPermissions()))
}
HasPermission requires every bit you pass. A tokenless client asks for read and
write on candles and ticks and for ADMIN_STREAM, and not LIST_STREAMS, so
listing needs a token. A node with authentication on refuses a tokenless client
outright; there the token alone decides.
5. Writing data
5.1 Live ingest
err := c.IngestCandles(ctx, stream, candles, client.DurabilityAcked)
err = c.IngestTicks(ctx, tickStream, ticks, client.DurabilityAcked)
One call sends one batch for one stream.
Durability |
Returns when |
Promise |
|---|---|---|
|
The server’s |
The batch is in the write-ahead log and the log is fsynced. |
|
The bytes are written to the socket. |
None. A batch the server refuses is dropped, and you are not told. |
Candle ingest is idempotent by (stream, timestamp): re-sending a batch does no harm. A bar the stream already stores is restated with the values you send, wherever the server keeps it, and a bar identical to what is stored is skipped without writing anything (§5.2).
What the live path accepts. Each stream has a hot cache: a window of slots near
its newest data. Its size follows the stream’s timeframe: 50,000 slots for 1m and
shorter, 10,000 for 5m, and 2,048 for 30m and longer by default. An operator can set
it for one stream with mirexa-cli cache on the node’s control listener; the SDK
cannot. New bars land inside that window or just past its leading edge.
A bar older than the window, at a time the stream already holds (a stored bar, or a hole between stored bars), is a restatement (§5.2).
A bar older than everything the stream stores is refused. Use the history route (§5.3) to load it.
A batch spanning more slots than the window holds is refused as a bad batch. Send it in smaller batches, or load old data through the history route.
A stream that has been idle for a long time resumes on its next write. The span it skipped is recorded as a gap.
When the cache is full, the server waits briefly for space to be freed. If space does
not come in time, it sheds the batch with ErrorCodeOverloaded, and the client
retries automatically (§5.6).
5.2 Corrections: restating stored bars
Exchanges routinely republish closed bars. To replace a bar the node already holds, send the new values the way you sent the old ones:
err := c.IngestCandles(ctx, stream, restated, client.DurabilityAcked)
The server decides, bar by bar, where each one goes. You do not need to know which of your bars it has flushed.
If the bar is still in the hot cache, the new values supersede it in place.
If the bar has been flushed to an immutable chunk, the server writes a patch that reads overlay on the original. You will not see the difference.
A bar identical to what is stored is skipped: nothing is written and subscribers are sent nothing for it. Re-sending a day you already sent costs a read, not a rewrite.
New bars in the same batch are appended as usual.
Restating can fill an open gap. A batch that covers a whole gap marks that gap
CLOSED. A bar inside a market closure that is already filed (GapReasonOffTime) is refused (§7).A restatement of a flushed bar is made durable on the server even when it was sent with
DurabilityFireAndForget. Measured on one laptop, restating a flushed bar took about as long as five acked writes of new bars, and re-sending an unchanged one about a two-hundredth of one.
IngestCorrectionCandles is the strict form, for code that means to correct
history:
err := c.IngestCorrectionCandles(ctx, stream, restated, client.DurabilityAcked)
It routes bars exactly as IngestCandles does, but refuses the whole batch if any bar
is newer than the newest one the stream stores. A bar it was given as a correction
and that turns out to be new means the caller’s picture of the stream is wrong, and
it is told so. Filling a gap is not new data, so gap fills take the strict form too.
A batch is either a correction or history, never both.
5.3 History backfill
Bulk historical data goes through its own route:
// Send the bulk fire-and-forget, then finish with one acked call.
for _, batch := range batches[:len(batches)-1] {
if err := c.IngestHistoryCandles(ctx, stream, batch, client.DurabilityFireAndForget); err != nil {
return err
}
}
err := c.IngestHistoryCandles(ctx, stream, batches[len(batches)-1], client.DurabilityAcked)
History bypasses the hot cache and the WAL. The server stages it, compresses it on a worker pool and installs finished chunks straight into the stream’s index. That means it can land anywhere in time, including below data you have already written live.
With fire-and-forget, the call returns once the frame is written. The candles are staged but not yet queryable.
With acked, the call blocks until the server has compressed and installed everything staged for the stream. This is when the data becomes queryable. A chunk-installed ack is a stronger promise than the live path’s WAL ack.
An install failure fails the acked call. The client is never acked for a chunk that did not reach disk.
Gaps inside a backfill are classified like any other gap.
The history route is for candles only. There is no tick backfill route.
5.4 Batching a live feed
A feed that produces one record at a time should be batched:
b, err := client.NewCandleBatcher(c, stream, client.BatchOptions{
MaxRecords: 1000, // default 1000
MaxDelay: 100 * time.Millisecond, // default 100ms
Durability: client.DurabilityAcked, // default
})
if err != nil {
return err
}
defer b.Close()
for candle := range feed {
if err := b.Add(ctx, candle); err != nil {
return err
}
}
return b.Close() // sends the last partial batch and returns the final verdict
A batch is sent as soon as either threshold is reached:
MaxRecordsbuffered, or the oldest buffered record has waitedMaxDelay. The size limit alone would strand a quiet stream. The time limit alone would send half-empty frames on a busy one.Addreturning nil means the record is buffered, not stored. A failed flush is reported by a laterAdd, byFlush, or byClose.Always check
Close. It is the only place you are guaranteed to hear about a background flush that failed, and it is what sends the final partial batch. A process that exits without calling it loses whatever was buffered.A failed flush poisons the batcher. Every later call returns that error. Accepting more records would mix stored and unstored data with no way to tell them apart.
Addblocks while a flush is in progress. That is backpressure, not a stall.A
Batcheris safe for concurrent use. Each one serves exactly one stream, so use one per symbol.NewTickBatcheris the tick equivalent.cmay be a*Clientor a*ResilientClient(anything satisfyingIngester), so you can batch and survive reconnects at the same time.AddafterClosereturnsErrBatcherClosed.
5.5 Fire-and-forget as a pipeline
If you need throughput more than per-batch receipts, send fire-and-forget and add a periodic acked batch as a barrier. Frames on one connection are processed in order, so an ack proves every batch sent before it was handled. It does not prove that each earlier batch was accepted: a refused fire-and-forget batch is still lost without notice.
5.6 Backpressure: automatic retry
When a node cannot absorb a request, it answers ErrorCodeOverloaded. That code means
nothing was stored, and it may carry a backoff hint. The client re-sends acked
ingests and reads on this code automatically:
|
Default |
Meaning |
|---|---|---|
|
1000 |
Total attempts, counting the first. |
|
5ms |
The first wait when the server sends no hint. Doubles on each attempt. |
|
250ms |
Caps each wait, including a server hint. |
The caller’s context and RequestTimeout still bound the whole call. When every
attempt is shed, the call fails with ErrRetriesExhausted, which wraps the last
*RemoteError.
These re-sends cannot duplicate data. The server sheds a batch before it reaches the WAL, so each retry sends a batch the server provably does not hold. No other error code is retried, and neither are fire-and-forget writes or subscription requests. The same code is also used when a partition is briefly frozen during a migration, or when a newly promoted primary is still replaying its log. Both clear with time, and the same retry rides through them.
IngestStat.Attempts (§12) is the only place a shed you absorbed is visible. The
server’s own counters never see a shed batch.
5.7 Writing a derived stream
A node can make a stream’s candles itself, from another stream’s trades or
candles: 1m bars from ticks, 5m from 1m, 1d from 1h. The derivation is declared
once per stream, with SetStreamLineage (§7)
or mirexa-cli lineage set on the control listener, and
from then on the node writes that stream as its source arrives. Copies receive
the derived chunks like any others; only the node serving the stream derives it.
Every ordinary write to a derived stream is refused with
ErrorCodeDerivedStream, before anything is stored, because the node would
interleave its bars with yours. If replacing derived bars is what you mean, say
so:
err := c.OverwriteCandles(ctx, fiveMin, bars, client.DurabilityAcked, client.RouteCorrection)
RouteLive, RouteHistory and RouteCorrection pick the route IngestCandles,
IngestHistoryCandles or IngestCorrectionCandles would take. Between your
write and a later re-derivation of the same bar (a source correction re-derives
down the chain), the last one written wins. On a stream nobody derives,
OverwriteCandles is the ordinary write.
6. Reading data
6.1 One range query
resp, err := c.QueryCandles(ctx, client.QueryRequest{
StreamID: stream,
StartTime: start.UnixNano(), // inclusive
EndTime: end.UnixNano(), // exclusive
})
if err != nil {
return err // transport failure or server ERROR frame
}
switch resp.Status {
case client.QueryStatusOK:
case client.QueryStatusStreamNotFound:
case client.QueryStatusInvalidRange:
}
for _, p := range resp.Points { ... }
if resp.HasMore { /* the range did not fit in one frame */ }
QueryRequest:
Field |
Meaning |
|---|---|
|
The stream to read. |
|
|
|
|
|
Return gap markers alongside the bars (§7). Ignored for ticks. |
|
Return newest first. Combined with |
|
Read ticks rather than candles. |
|
Allow an in-sync copy to answer in a cluster (§11). Candles only. |
A query has two separate failure channels:
An error means the transport failed or the server sent an ERROR frame.
resp.Statusreports an in-band answer about this request.
A missing stream is a Status, not an error.
HasMore means the range holds more than one frame can carry. To continue, advance
StartTime past the last returned timestamp (or, when descending, move EndTime
back), or let an iterator do it for you.
6.2 Iterating a range: Rows
rows := c.QueryCandlesRows(ctx, client.QueryRequest{
StreamID: stream, StartTime: start, EndTime: end, IncludeGaps: true,
})
defer rows.Close()
for rows.Next() {
p := rows.Point()
if p.IsGap {
continue
}
use(p.Candle)
}
if err := rows.Err(); err != nil { // ALWAYS
return err
}
This is the database/sql.Rows contract. The iterator fetches pages as you loop.
Pages are sized by the server, and the only sign of a page boundary is fetch latency.
A descending range pages newest first.
Always check Err(). An in-band refusal ends the loop just as a normal finish
does, so does a transport error part-way through. Skip the check and “no such stream”
looks like “no data”. A refusal surfaces as *QueryStatusError, carrying the Status
and the StreamID.
QueryTicksRows and TickRows work the same way for ticks: call rows.Tick()
instead of rows.Point(). Iterators are not safe for concurrent use.
6.3 Ticks
resp, err := c.QueryTicks(ctx, client.QueryRequest{StreamID: s, StartTime: a, EndTime: b})
for _, t := range resp.Ticks { ... }
A tick is an event, not a scheduled slot, so tick queries carry no gap markers.
6.4 Many queries in one round trip
results, err := c.QueryMultiAll(ctx, []client.QueryRequest{
{StreamID: btc, StartTime: start, EndTime: end},
{StreamID: eth, StartTime: start, EndTime: end},
{StreamID: btc, StartTime: earlier, EndTime: start}, // same stream, another window
{StreamID: btcTicks, StartTime: start, EndTime: end, Ticks: true}, // kinds may mix
})
if err != nil {
return err
}
for i, r := range results { // results[i] answers request i
if r.Status != client.QueryStatusOK {
continue // affects only this entry
}
if r.Ticks { use(r.TickData) } else { use(r.Points) }
}
Nothing is merged. You get N separate, complete series in request order. Results are keyed by position, which is why the same stream can appear twice.
One connection serves one frame at a time, so this turns N round trips into (usually) one. On a 0.5ms-RTT network that saves about 50ms for a hundred-symbol portfolio.
Each result carries its own
Status. One missing symbol among fifty marks only its own entry.If the results do not fit in one frame,
QueryMultiAllre-asks for the rest automatically.MaxResultsis a total cap per sub-query.A node limits how many sub-queries one request may carry (
max_subqueries_per_request, default 128). A larger batch is refused whole.A transport error part-way through returns the error and discards the partial results rather than handing back a half-labelled set.
c.QueryMulti(ctx, queries) is the raw single-frame form, for callers who schedule
the rounds themselves. Its MultiQueryResponse may be partial: a sub-query the frame
budget did not reach carries HasMore and a ResumeFrom point. On a raw
QueryMulti, MaxResults caps each response. A server older than the frame type
answers ErrorCodeUnsupported.
6.5 Rollups: longer bars at query time
QueryRequest.Rollup asks for bars of that length made at query time and
stored nowhere: from the stream’s candles, or with Ticks: true from its
trades. The answer is candles either way.
hourly, err := c.QueryCandles(ctx, client.QueryRequest{
StreamID: oneMinute, StartTime: from, EndTime: to,
IncludeGaps: true, Rollup: time.Hour,
})
fromTrades, err := c.QueryCandles(ctx, client.QueryRequest{
StreamID: oneMinute, StartTime: from, EndTime: to,
Ticks: true, Rollup: time.Minute,
})
A rollup runs the rules a declared derivation runs, so a 5m rollup and a stored 5m stream derived from the same source answer the same bars, INCOMPLETE marks included (§7).
Only CLOSED bars are answered: a bucket still open, or within the close grace, answers nothing, as live ingest stores closed candles only. A bar whose stamp lies before
StartTimeis not answered, so paging by “after the last bar” never sees one twice.From candles, the length must be a whole multiple, at least twice, of the stream’s own. Daily bars are the stream’s local trading date stamped 00:00 UTC and weekly bars start on Monday; above a day only 1d and 1w exist. Anything else is refused with
ErrorCodeProtocol, naming why.The stream’s own calendar is the rollup’s. It needs the read permission of what it reads:
PermReadTicksfrom trades,PermReadCandlesfrom candles.AllowStaleandRolluptogether are refused before sending.Measured 2026-10-22: a million trades into 1m bars in 45ms, a year of 1m bars into 1h in 67ms, on one laptop.
6.6 Only some columns
QueryRequest.Columns asks for only some of each candle’s values. The node
decodes and sends the timestamp and the columns named, nothing else, and
QueryColumns returns them as slices, with no struct per bar:
cols, err := c.QueryColumns(ctx, client.QueryRequest{
StreamID: s, StartTime: a, EndTime: b,
Columns: client.ColumnClose, // or client.ColumnOpen | client.ColumnVolume, client.ColumnsAll
})
for i, ts := range cols.Timestamp {
use(ts, cols.Close[i]) // cols.Open, High, Low, Volume are nil: not asked for
}
A close-only row is 17 bytes on the wire where a whole bar is 49.
QueryColumnspages likeQueryCandlesRows:MaxResultsis the total cap,Descendingreads newest first. A request naming no column isErrNoColumns; a missing stream is a*QueryStatusError.One page without the loop is
QueryCandleswithColumnsset: the rows are inresp.Columnsandresp.Pointsis empty.QueryCandlesRowsrefuses a column request.There are no gap markers in a column answer:
IncludeGapsis refused, as areTicks,AllowStaleandRollup.cols.Incomplete(i)says whether rowiis a derived bar whose source had a hole (§7).Each sub-query of
QueryMultiAllmay set its ownColumns, beside plain ones; its rows come back inMultiResult.Columns.The Python client’s
query_columnsis the same call into NumPy arrays.
7. Gaps
Gaps are results, not absences
The engine distinguishes a market that was closed from data that was lost, and keeps that distinction all the way to the client. A weekend on a 24/5 market is not an outage. A feed dropping mid-session is one, and you can still repair it.
|
Meaning |
|---|---|
|
Data is missing and can still be backfilled. |
|
A fill is in progress. |
|
Was missing and has since been filled. Kept as provenance. |
|
Not recoverable. Scheduled closures are filed this way. |
|
An INCOMPLETE mark accepted as it is (“known incomplete, keep it”). Only an INCOMPLETE record is ever ACCEPTED. |
|
Meaning |
|---|---|
|
The market was closed (trading calendar). Not data loss. |
|
Recorded causes of a real loss. |
|
Missing, cause not classified. |
|
Not a hole: a derived bar whose source had a hole under its window. The bar is stored and served, and carries the mark. |
A slot the classifier has not reached yet (still in the hot cache) reports the zero
values GapStatusOpen / GapReasonUnknown. That is an honest “not yet known”, not a
guess.
What decides the classification
The stream’s trading calendar: stream metadata the node keeps, set with
SetStreamMetadata and the closure calls (below),
or on the node’s control listener with mirexa-cli calendar. It holds weekly working hours, declared closures (a holiday, a
halt, a gap you know was expected) and, for a stream with no hours, a duration
past which a gap counts as a closure.
A calendar change re-files the stream’s recorded gaps at once, so the same
query can answer differently before and after one: a “missing” hour becomes
GapReasonOffTime when a closure is declared over it, and turns back when the
closure is removed. A gap since filled with data never changes. Do not cache a
gap’s classification as permanent; read it again.
Setting the calendar and lineage
A stream’s metadata is read with GetStreamMetadata and changed with four calls,
each answering with the metadata as the node then holds it. A stream the node
does not know is resp.Status == client.QueryStatusStreamNotFound, not an error;
metadata the node refuses (an unknown timezone, overlapping windows, a lineage
its rules cannot derive) is a *RemoteError with ErrorCodeProtocol and the
reason. All of them are safe to re-send, so they are retried like reads.
md := &client.StreamMetadata{
WorkingHours: &client.WorkingHours{Timezone: "America/New_York"},
GapThresholdLow: 2 * time.Minute,
}
for _, d := range []time.Weekday{time.Monday, time.Tuesday, time.Wednesday, time.Thursday, time.Friday} {
md.WorkingHours.Schedule = append(md.WorkingHours.Schedule, client.DaySchedule{
Day: d, Windows: []client.TimeWindow{client.NewTimeWindow(9, 30, 16, 0)},
})
}
// Create registers a stream the node does not know yet.
resp, err := c.SetStreamMetadata(ctx, client.SetStreamMetadataRequest{
StreamID: msft, Create: true, Metadata: md,
})
// resp.Created; resp.RefiledNanos is how much filed gap time changed class.
// A holiday: gaps inside it are re-filed as market closure.
_, err = c.AddStreamClosure(ctx, client.AddStreamClosureRequest{StreamID: msft,
Closure: client.Closure{StartTs: start, EndTs: end, Note: "Thanksgiving"}})
// Removing cuts any closure the range overlaps.
_, err = c.RemoveStreamClosure(ctx, client.RemoveStreamClosureRequest{
StreamID: msft, StartTs: start, EndTs: end})
// Derive this stream from another's trades, from now on (or LineageHistoryRederive
// to derive what the source already holds; LineageHistoryClear with no lineage
// makes it a plain stream again). The node stamps Since.
_, err = c.SetStreamLineage(ctx, client.SetStreamLineageRequest{
StreamID: msft5, History: client.LineageHistoryFromNow,
Lineage: &client.Lineage{Source: msftTrades, Kind: client.SourceTicks},
})
SetStreamMetadata replaces everything but the lineage, which it keeps; a
request carrying one is refused before it is sent. The changes need
PermAdminStream; reading needs PermReadCandles. A RoutingClient sends each
to the node that owns the stream. The control listener’s StreamService does
the same operations for an operator, through the same code on the node.
Gap markers in a query
Gap markers appear only when you ask for them, with IncludeGaps: true:
if p.IsGap {
if p.Reason == client.GapReasonOffTime {
continue // the market was closed
}
if p.Status == client.GapStatusOpen {
// missing data you can still repair
}
}
A query answers per interval, so a weekend on a 1m stream comes back as 2,880 gap points. To get holes as ranges, list them instead.
Listing gaps as ranges
resp, err := c.ListGaps(ctx, client.ListGapsRequest{
StreamID: stream,
StartTime: from, EndTime: to,
OpenOnly: false, // only GapStatusOpen
ExcludeOffTime: true, // drop scheduled closures
Limit: 200, // default 200, max 1000 (more is refused, not clamped)
})
for _, g := range resp.Gaps { // ordered by StartTs
ok, why := g.Fillable()
...
}
s := resp.Summary // covers the WHOLE window, not just this page
fmt.Println(s.MissingDuration, s.OffTimeDuration, s.Count, s.OpenCount, s.OffTimeCount, s.FillableCount)
A gap that overlaps the window is returned whole, because a hole does not become two holes where a window cuts it. The summary’s durations are clipped to the window.
MissingDurationcounts only time that is genuinely absent. Closures and gaps that have already been filled are excluded. This is the number to alert on. A stream for an exchange open 32 hours a week looks “80% incomplete” by any naive measure and is perfectly healthy.Only gaps in flushed data are listed. A hole still in the hot cache is not classified yet.
Paging: when
HasMoreis set, send the last gap’sStartTsasCursorwithHasCursor: true.Requires
PermReadCandles.
Filling a gap
Never decide fillability yourself from Reason. Call GapRange.Fillable(). It is
the single definition, and the server enforces with the same function:
Result |
Why |
|---|---|
|
Open, so fillable. |
|
The market was shut. Anything written here would be fabricated. |
|
Marked unrecoverable. Also returned for an unrecognised status, failing safe. |
|
Already filled. |
|
Another fill is running. |
|
An incomplete bar accepted as it is. |
To fill an open gap, send the recovered bars with IngestCorrectionCandles. Once the
bars are durable, the server marks every gap the correction wholly contains as
CLOSED. A partial fill leaves the gap OPEN. A correction into a closure is refused
before anything is written, even when the same batch also fills a real outage
elsewhere.
Real bars arriving during “closed” hours are not refused while they are new. Data arriving then is evidence that the calendar is wrong (an extended session, a moved holiday), and the server keeps it. What is refused, with or without the correction flag, is a write into a closure the node has already filed as a gap.
Auto-fill: candles made up from the neighbours
When the real bars are gone for good, FillGap asks the node to fill one gap
with candles it makes up from the real candles either side:
resp, err := c.FillGap(ctx, client.FillGapRequest{
StreamID: stream,
GapStart: g.StartTs, // exactly as ListGaps gave it
Method: client.FillMethodLinear, // or FillMethodForward, FillMethodBackward
MaxCandles: 0, // 0: the node's cap
})
// resp.Filled candles written; resp.HasMore: call again, it continues the line.
It is a request and nothing else triggers it. The node refuses a gap
Fillable()refuses (a market closure always), writes the candles as a correction, and closes the gap once every slot holds one.Every made-up candle carries zero volume, the honest value and the only mark a synthetic bar keeps once stored.
Safe to re-send: a second request finds only what the first left, and continues the same line. A start no gap has is refused rather than applied to the nearest hole; list again.
A derived stream needs
Overwrite: true(§5.7). RequiresPermWriteCandles.
INCOMPLETE marks on derived bars
A derived bar is made even when its source had a hole under its window, and it
carries an INCOMPLETE mark rather than being dropped: the data in it is real,
and the mark says it was made from less than its whole window. In a query it is
a candle (IsGap false) with Reason == GapReasonIncomplete; test it with
p.Incomplete(). ListGaps lists the mark as a range like any gap record.
A mark is resolved in one of two ways. Filling the source’s hole re-derives the bar and clears it. Or accept it as it is:
mark, err := c.AcceptGap(ctx, client.AcceptGapRequest{
StreamID: derived, GapStart: g.StartTs, Accept: true, // false puts it back to OPEN
})
GapRange.AcceptAction() says which way a record may go: accept an OPEN
mark, unaccept an ACCEPTED one, or nothing. A gap of missing data is filled or
left open, never accepted, and the node refuses that. Safe to re-send. Requires
PermWriteCandles.
8. Discovering streams and nodes
Listing streams
Requires PermListStreams.
resp, err := c.ListStreams(ctx, client.ListStreamsRequest{
Exchange: "binance", // exact; empty = any
Symbol: "BTC", // case-insensitive PREFIX
Timeframe: "1m", // exact
IncludeStats: true, // per-stream totals; costs an index read per stream
Limit: 200, // default 200, max 1000 (more is refused)
})
for i, id := range resp.Streams {
if resp.Stats != nil {
st := resp.Stats[i] // RecordCount, ByteSize, FirstTimestamp, LastTimestamp,
// MissingDuration, ChunkCount, PatchCount, GapCount,
// OpenGapCount, OffTimeCount
}
}
// next page: req.Cursor = resp.Streams[len(resp.Streams)-1].String()
Paging is key-set, not offset: the cursor means “everything after this id”. It stays correct while streams are being created, where an offset would skip or repeat entries. There is no total count.
Filters are applied by the node before the page limit. Filtering pages after they arrive would produce short pages that look like missing data.
Match: id.String()returns just that one stream. An empty result means it does not exist.SortBy(ListSortByIDby default, also last update, record count and storage size) withDescending. Any order other than by id makes the node compute stats for every stream it holds, not only those on the page. Use it sparingly.RecordCountandByteSizeare persisted totals.FirstTimestampandLastTimestampinclude the hot cache, so a stream being written right now reports aLastTimestampnewer than anythingRecordCountcounts.
ResilientClient.ListStreamsAll(ctx) runs the paging loop for you and returns every
id. Because each page is retried independently from its cursor, a reconnect in the
middle neither skips nor repeats an entry.
Nodes and node statistics
These require PermListStreams.
c.ListNodes(ctx)returns the cluster’s nodes as the answering node knows them:NodeID,Serving,Draining,Primaries,CopiesandDataAddr. An empty list means the node is not part of a cluster.c.NodeStats(ctx)returns the node’s own measurements: process CPU and memory, disk, what it holds and what it is primary of, cumulative ingest and query counters, live subscriptions, and latency histograms. A value the node did not measure is flagged as unknown, never reported as zero. A node that does not measure itself answersErrorCodeUnsupported.
Their result types are not yet exported by name from the client package. Use :=
and read the fields.
9. Subscriptions
Subscribing
sub, err := c.SubscribeStream(ctx, client.SubscribeRequest{
StreamID: stream,
Backfill: true, // send stored history first
StartTime: from.UnixNano(), // backfill from here; 0 = the earliest stored record
// Ticks: true // subscribe to ticks instead of candles
})
if err != nil {
return err
}
defer sub.Close()
for sub.Next(ctx) {
ev := sub.Event()
if ev.Live {
// history is done; everything from here on is real time
}
if ev.Dropped > 0 {
// records are GONE, not delayed: sequences MissingFirst..MissingLast
}
use(ev.Candles) // or ev.Ticks
}
if err := sub.Err(); err != nil {
return err
}
Event:
Field |
Meaning |
|---|---|
|
Exactly one is populated, matching the subscription. Both may be empty on an event that only signals a state change. |
|
This batch is stored history. |
|
The first live batch after the backfill. It is never set when you asked for no backfill. |
|
Live batches are numbered from 1. Backfill batches carry 0. |
|
Batches the server discarded because you were not keeping up. |
|
The number of records in this event. |
Two guarantees, stated exactly:
At the backfill-to-live pivot there is no gap, but there can be duplicates. The backfill window and the live queue overlap on purpose, so a record ingested during the backfill can arrive on both sides. Dedupe on (stream, timestamp) if that matters to you.
A dropped batch is gone, not delayed. Recover the range with a query or a backfilling re-subscribe. Do not try to detect drops from
Sequenceyourself: the server keeps two sequence spaces, and the SDK already accounts for both.
Rules
One subscription per
Client. The push stream belongs to the connection. A delivery for a different stream fails withErrForeignBatchrather than being silently interleaved. Request/response calls on the same client run alongside the subscription freely.Exactly one goroutine drives a
Subscription.Keep reading. The client-side push buffer is bounded, so a consumer that stops reading eventually stalls every request on that client. Long before that, the server evicts a consumer that keeps falling behind. Eviction ends the subscription with
ErrSlowConsumerbut leaves the connection open. Recover by re-subscribing with backfill.Quiet is normal. No
RequestTimeoutapplies toNext. Bound it withctxif you want a limit.Copy before keeping.
Eventslices alias that frame’s decode buffer. Copy anything you keep past the nextNext.sub.Close()ends the iteration but does not tell the server. Callsub.Unsubscribe(ctx)first if the server should stop sending. Batches already queued may still arrive.Partials(in-progress candles) is answeredErrorCodeUnsupported. The server emits only closed candles.
A subscription that survives disconnects
s, err := client.NewResumingSubscriber(addr, client.Options{TokenSource: src},
client.SubscribeRequest{StreamID: stream, Backfill: true},
client.ResumeOptions{}) // MaxAttempts 5, Backoff 200ms
if err != nil {
return err
}
defer s.Close()
for {
ev, err := s.Next(ctx)
if err != nil {
return err // ctx ended, or the reconnect budget was spent
}
use(ev)
}
When the connection fails, the subscriber redials, repeats the handshake and
re-subscribes with backfill from one nanosecond after the last record it
delivered. You see one continuous stream, with no record twice. req.Backfill
controls only the first subscribe. Every reconnect backfills, because backfill is what
fills the hole left by the disconnect. Events carrying neither records nor a state
change are skipped.
s.Reconnects()ands.Redirects()report how many times each has happened.s.Unsubscribe(ctx)tells the server to stop before you close.ResumeOptions.FollowRedirectsis for clusters (§11).A
ResumingSubscriberis not safe for concurrent use.
10. Resilience: surviving a dead connection
c, err := client.DialResilient(addr, client.Options{TokenSource: src},
client.ResilienceOptions{})
// err != nil is NOT fatal: c is usable and keeps trying. Return err only if you
// want to fail fast; starting before your database is a normal deployment.
ResilientClient has the same request methods as Client, plus ListStreamsAll,
State() and Reconnects(). It redials on demand. Concurrent callers that find the
connection dead share one redial, so there is never one dial per caller. A circuit
breaker makes a dead endpoint fail fast.
|
Default |
Meaning |
|---|---|---|
|
3 |
Connection attempts within one operation. |
|
100ms |
The first wait between attempts. Doubles, with jitter. |
|
5s |
Caps one wait. |
|
5 |
Consecutive connection failures that open the breaker. A negative value disables the breaker. |
|
30s |
How long the breaker stays open before letting one probe through. |
State() is one of StateDisconnected, StateConnected, StateOpen (the breaker
is refusing calls) or StateHalfOpen (the next call probes). While the breaker is
open, calls fail immediately with ErrCircuitOpen and are never attempted.
GrantedPermissions() returns 0 while disconnected, which means “not connected”, not
“granted nothing”.
Reads retry; writes do not
Reads are re-run across a reconnect, because re-running a query returns the same
rows. Row iterators re-fetch only the page they lost and resume exactly from their
key-based cursor. QueryMultiAll loses only the round in flight.
Writes depend on when the connection failed:
When the connection failed |
Result |
|---|---|
Before the request was sent (including a connection the server had already closed while idle) |
Not ambiguous. The batch goes out on a fresh connection as a first attempt. |
While the request was in flight |
|
For candles, re-sending the ambiguous batch with IngestCandles is safe: bars that
were stored are found unchanged and skipped, and bars that were not are written,
wherever they fall (§5.2). The SDK still does not do it for you, for two reasons:
A re-send overwrites any bar that someone else restated in the meantime with your older values.
Trades have no such key. Two trades can share a timestamp, so re-sending a trade batch can store it twice. For trades, read the range back and send only what is missing.
If the lost batch was the stream’s first, its bars are older than everything the
stream stores, and the re-send is refused. Send them with IngestHistoryCandles.
ResilientClient does not cover subscriptions. Use ResumingSubscriber for those.
11. Running against a cluster
A clustered Mirexa deployment splits streams across nodes by partition. Each
partition has one primary and possibly in-sync copies. The public client package
holds one connection to one address. It does not yet route requests to the right
node by itself. That client exists internally but is not exported. What this means
for you:
A request sent to a node that does not serve the stream is answered with a redirect: an error matching
ErrRedirect, with a*RedirectErrornaming the partition, its epoch, the serving node’s id and itsAddr. The node issues the redirect before anything is stored, so a redirected write provably did not land. Sending it toAddris a first attempt, not a retry. Re-sending to the same address gets the same answer.var re *client.RedirectError if errors.As(err, &re) { // dial re.Addr and send there }
QueryMultiAllon a plain client answers sub-queries for streams that live elsewhere in place. Those results carry status0x04(elsewhere) withMultiResult.Elsewherenaming the node. The rest of the batch is served normally.Two refusals have no exported constant but can reach you through
RemoteError.Code:client.ErrorCode(0x0008)(stale placement) means the node is behind on cluster state. Retry after its hint.client.ErrorCode(0x0009)(partition unavailable) means the partition’s primary is down or not leased. It comes back when the node is acknowledged again or the cluster fails the partition over. It carries no hint.
A migration in progress briefly sheds writes with
ErrorCodeOverloaded, which the automatic retry absorbs (§5.6).Stale reads. Setting
AllowStale: trueon a candle query lets an in-sync copy answer when the primary cannot, for example when the primary is dead but has not yet been failed over. Such an answer setsQueryResponse.Stale(andMultiResult.Stale), andLevelAtis when the copy last matched its primary, in Unix ns. Everything the primary had made durable up to that moment is included. Anything after may be missing. Stale reads are never served for ticks, and never without the flag. A copy answers only while it is within the node’scluster.copy_read_max_staleness(default 5s) of its primary; one further behind redirects, as one outside the in-sync set does, so a stale answer is never older than that bound plus one heartbeat. The client in this package sends a read where you point it and does not spread reads over copies by itself; the routing client inside the repository does, by default, and has opt-outs (dev-overview §5.12).Subscriptions. With
ResumeOptions.FollowRedirects: true, aResumingSubscribertreats a redirect as a place to resubscribe. That applies at the first subscribe and when the stream’s partition moves mid-stream. After a move it resumes with backfill from the last record delivered. Each redirect it follows must carry a strictly newer epoch, so two nodes that disagree end the stream rather than bouncing it between them.Writes are acknowledged by the primary alone. Copies pull asynchronously, so a primary that crashes can lose writes it acknowledged during roughly its last replication poll (milliseconds in practice). See the durability page.
12. Measuring the client: Observer
The SDK ships no metrics stack. Instead, implement Observer with whatever metrics
system you already run:
type Observer interface {
IngestCompleted(IngestStat) // once per ingest CALL (not per attempt)
StreamDelivered(StreamStat) // once per subscription delivery handed to you
ConnectionChanged(ConnStat) // every ResilientClient state transition
}
c, err := client.Dial(addr, client.Options{Observer: myMetrics})
Type |
Fields |
|---|---|
|
|
|
|
|
|
These numbers exist nowhere else. A shed batch never reaches the server’s counters,
and a server cannot count clients that failed to reach it. Every method runs
synchronously on the goroutine doing the work: increment a counter and return. A
slow Observer slows ingest, and a panicking Observer takes the caller’s goroutine down
with it. A plain Client never calls ConnectionChanged.
13. Errors
Sentinels (use errors.Is)
Error |
Meaning |
What to do |
|---|---|---|
|
The server sent an ERROR frame. Every |
Inspect the code. |
|
The request was shed on every attempt. Wraps the last |
Slow down, or raise |
|
The connection failed while a write was in flight. |
Read back and reconcile (§10). Never re-send blindly. |
|
The connection is gone, closed by you or by a transport error. |
Redial, or use |
|
No answer within |
For writes, treat as ambiguous. |
|
The breaker refused the call without attempting it. |
Wait out |
|
|
Fix the configuration. |
|
The node does not serve this stream (§11). |
|
|
The server evicted your subscription. |
Re-subscribe with backfill. |
|
Two subscriptions are sharing one |
Use one |
|
|
ErrorCodeDerivedStream (a *RemoteError) refuses a write to a derived stream
that did not ask to overwrite it; nothing was stored. See §5.7.
*RemoteError (use errors.As)
var re *client.RemoteError
if errors.As(err, &re) {
switch re.Code {
case client.ErrorCodeUnauthorized: // permission missing, token expired or refused
case client.ErrorCodeProtocol: // malformed or invalid request: bad batch, bad timeframe
case client.ErrorCodePayloadTooLarge:
case client.ErrorCodeUnsupported: // the server does not implement this
case client.ErrorCodeInternal: // server fault; do NOT replay blindly
case client.ErrorCodeOverloaded: // shed; nothing stored (already retried for you)
case client.ErrorCodeSlowConsumer: // subscription evicted
case client.ErrorCodeDerivedStream: // a derived stream; use OverwriteCandles on purpose
}
if wait, ok := re.RetryAfter(); ok { /* only Overloaded says yes */ }
log.Println(re.Message)
}
RemoteError.RetryAfter() is the single answer to “may I retry this?”. It says yes
only for ErrorCodeOverloaded, the one code that promises nothing was stored.
*QueryStatusError is how the row iterators report an in-band query refusal.
14. Concurrency and cancellation
A
Clientis safe for concurrent use. Any number of goroutines can issue requests on one connection, and each gets its own response, matched by correlation id. The server still processes one frame at a time per connection, so a slow query delays the responses queued behind it. When you need server-side parallelism, use oneClientper worker.ResilientClientandBatcherare safe for concurrent use.Subscription,ResumingSubscriber,CandleRowsandTickRowsare not: one goroutine drives each.Cancellation separates you from the answer, not the request from the server. A cancelled call may still execute on the server. Its late response is dropped and is never delivered to a later call. For a write, a cancellation after sending leaves the outcome unknown, exactly as
ErrAmbiguousdoes.
15. Testing your own code: clienttest
github.com/AmiraliOmidvar/mirexa/client/clienttest is an in-process server for your
unit tests: the httptest of this SDK. It speaks the real wire protocol with the
real codecs. It is not the storage engine: records live in a map and nothing is
durable. Use it to test how your code reacts to a server that answers, refuses or
disappears. Use a real node to test storage behaviour.
srv, err := clienttest.NewServer()
if err != nil {
t.Fatal(err)
}
defer srv.Close()
c, _ := client.Dial(srv.Addr(), client.Options{Token: "test-token"})
srv.SeedCandles(stream, candles) // data, without ingesting
srv.SeedTicks(tickStream, ticks)
srv.SeedGaps(stream, []client.GapRange{...}) // gaps are seeded, never inferred
srv.SeedStreamMetadata(stream, md) // a calendar or lineage, as if set
srv.PublishCandles(stream, live) // drive a subscription
srv.FailNext(client.ErrorCodeOverloaded, "shed") // next request answers this error
srv.GrantPermissions(client.PermReadCandles) // narrow every later grant
_ = srv.LastToken() // did your code pass its token?
srv.Close() // sever connections: drive reconnects
srv.RequestCount reports how many frames of a given type the server handled, which
is how a test asserts that a client retried or did not.
Gaps are seeded rather than derived because whether a hole is an outage or a closure comes from a trading calendar, not from the hole itself.
The stream-metadata calls work against it as against a node: a stream is known once
it holds data or was created, SetStreamMetadata keeps the lineage, closures merge
and are cut, and a calendar a node would refuse is refused. The calendar files no gaps
here, so RefiledNanos is always 0. The server refuses FillGap, AcceptGap,
ListNodes and NodeStats as Unsupported.
16. Defaults at a glance
Setting |
Default |
|---|---|
Transport |
plaintext TCP |
|
10s / 30s |
|
16 MiB |
Ingest durability |
|
Shed retry |
1000 attempts, 5ms doubling, each wait ≤ 250ms |
Token renewal |
on with a |
Token lifetime |
≤ 1h ( |
Tokenless request |
read + write on candles and ticks; no |
Batcher |
1,000 records or 100ms, whichever first |
|
3 attempts, 100ms → 5s backoff, breaker 5 failures / 30s |
|
5 reconnects, 200ms apart; redirects not followed |
List page size |
200 default, 1,000 max (streams and gaps) |
Sub-queries per multi-query |
128 (node setting) |
Where to look next
The durability model: what an acknowledgement actually promises, and the limits stated as plainly as the guarantees.
client/example_test.go: the flows on this page as executed code.go doc github.com/AmiraliOmidvar/mirexa/client: every name, documented.