WebSocketFeed
The worker is Virtufin.Worker.WebSocketFeed (worker type websocketfeed,
engine application/x-dotnet-dll); the connection code it is built on is the
library Virtufin.WebSocket.DevKit, both in this repo
(WebSocketFeed,
WebSocketDevKit).
How a feed works (serving topics, how a frame travels): How WebSocketFeed works. Opening feeds from an orchestrator: Open feeds for your workers' topics.
Config, commands and events
The worker's README
lists every config key, command and attribute, and the
config schema (JSON Schema 2020-12,
also packed under schema/ in the worker nupkg) defines each key formally. The
schema describes the decoded config, the shape of a preset's config; on the
wire every value is a string: true/false, a number's text, an array or
object (handshake, routing, subscribe, an object maxitemsperchannel) as
its JSON text. Custom keys, for {config:KEY}, start with x; any other
unknown key is invalid. In short:
| Config | Meaning |
|---|---|
url |
ws:// / wss://, required |
topics |
the topics served from the first start; serve changes them |
topicitems |
the rules [{topic, channel?, routingkey?, values?}] mapping a topic to a venue item |
publishtopic, routing |
where unrouted frames go; routing is {key_path, split_arrays, keys?, time_path?, time_format?}, key_path may be compound (T,S); time_path (dot path) and time_format (epoch_ms, epoch_us, epoch_ns, rfc3339) name the venue's own event time, for the latency gauges |
handshake |
the login steps [{text\|base64, expect?, fail?}], text with {secret:NAME} / {config:KEY} |
subscribeframe, unsubscribeframe, subscribeitem, frameper |
the derived subscription's templates |
symbolformat, symbolcase |
how a topic's canonical {pair} is spelled at the venue |
maxitems, maxitemsperchannel |
limits; excluded items make the feed degraded |
routingkeyitem |
the routing key of an item, for rules without their own routingkey |
subscribe |
fixed frames sent after the login on every open |
metricsseconds |
seconds between pushes of the counters on wrk.websocketfeed.metrics (default 5, 0 off) |
autoreconnect, reconnectmaxattempts |
reconnect policy (default: forever) |
releasewhenidleminutes |
opt-in: delete itself after serving nothing for this many minutes (unset: never) |
Every key above is read by the feed. A feed is created with the
CreateWorkerRequest field library_reload = LIBRARY_RELOAD_OFF
(a platform setting, never a config key): no bounce on library releases.
Each command takes its input message and answers with its answer message
(Virtufin.WebSocket.DevKit's virtufin.websocket package, @virtufin/websocket-devkit
in TypeScript), content types
application/x-virtufin-websocketfeed-<command>-command+protobuf and
...-answer+protobuf. The feed registers their schemas when it starts. JSON commands
are refused.
| Command | Input | Effect |
|---|---|---|
serve |
ServeCommand |
set replaces the served topics, add / remove change them; all or nothing, saved; the delta is (un)subscribed and the routing recomputed. Refused while the feed releases itself |
send |
SendCommand |
one frame (text or binary); replay also on every later open; with expect/fail (regular expressions) and timeout_ms, request/reply: the answer carries the first inbound frame that matches (reply, reply_ms) |
publish, unpublish |
PublishCommand, none |
the topic and explicit routing of unrouted frames (saved) |
status |
none | state, URL, publish topic, routing (with the served topics' keys), served topics, subscribed and excluded items, release, counters |
A send that needs the venue's answer waits for it in the same call, so a
caller never has to subscribe to the feed's topic and correlate frames. A
SendCommand (shown in its JSON form):
{"frame": {"text": "{\"method\":\"LIST_SUBSCRIPTIONS\",\"id\":3}"}, "expect": "\"id\":3", "timeout_ms": 5000}
answers a SendAnswer with sent: true, reply (frame.text {"result":[...],"id":3} and its ingest_time) and reply_ms: 41.
Only frames that arrive after the send count; the reply is published as well.
A command on the command topic (asynchronous) gets the same answer on its
replytopic. Commands published on the command topic while the feed moves to
another Runtime pod are replayed to its new activation once (WorkManager
0.36.1).
Frames are published as com.virtufin.websocketfeed.message from
urn:com.virtufin:worker:websocketfeed with the attributes ingesttime
(when the frame came off the socket), websocketid (= the worker id) and
websocketurl.
Status goes out as the worker's lifecycle status event. The counters (received,
published, skipped, unpublished, publishfailures, opens, sessions) and
the gauges served (topics served) and subscribed (venue items subscribed) are
pushed on wrk.websocketfeed.metrics as {workerid, counters, at}, every
metricsseconds (default 5) when they changed, so a dashboard follows them
instead of polling status; a serve by anyone shows within one interval.
With a routing time_path (the venue presets name it: Binance data.E in
epoch_ms, Alpaca t in rfc3339), the feed also measures how far it is
behind the venue: per routed message, its ingesttime minus the venue's event
time. The metrics then carry the last interval's latencyp50ms and
latencyp90ms (when it saw messages), latencysamples (messages in the
interval) and the counter untimed (frames without a readable time). The
sample is bounded (2048 per interval, a uniform reservoir past that); status
shows the interval the last push took. The number includes the skew between the
venue's clock and the node's.
To tell latency from skew, a feed with a clockprobe (0.7.0+; the Binance
preset's reads https://api.binance.com/api/v3/time) reads the venue's clock
every few minutes: three GETs, the shortest round trip believed, and
offset = venue time − (sent + received)/2, give or take half the round trip.
The metrics then carry clockoffsetms (positive: the venue's clock is ahead)
and clockrttms. A latency is only physical when it is at least half the round
trip and the offset is within its bound; latencynegative counts messages
stamped in the future, a sure sign of skew. The node clocks run chrony and are
alerted on (cluster-medusa node_time.yml).
From 0.2.x (0.3.0): the feed serves topics; attach/detach, attachments,
the lifecycle subscription, symbols/currencypairs/channels, pinned,
releaseafterminutes and resource are gone, and consumers no longer name a
feed (requires is gone from the worker devkit). From 0.1.x: handshake=none|script|alpaca and handshakescript are gone
(handshake is the step list; Alpaca's login is the alpaca preset);
orderbooklimit is maxitemsperchannel; channels has no default; status
reports handshake as a step count and subscribed/excluded as
{channel: [symbols]}.
Templates: the venue is config
The worker contains no venue: a venue's protocol is a handful of templates and
values, kept as a preset next to the venue's naming fragment in
market-data-devkit (feeds/<preset>.json: binance, alpaca,
fakevenue-binance, fakevenue-alpaca). A preset names its venue and maps the
venue's market families (orderbook.update, trade.update, candle.update)
to channels; VenueFeeds.Config(preset, overrides, world) (C#) and
virtufin.marketdata_devkit.feeds.config(preset, overrides, world=...)
(Python) turn one into plain feed config, rendering topicitems from the
venue's naming fragment (its topic patterns, symbol spelling and interval
names), so no topic is written by hand; VenueFeeds.Secrets(preset) names
the worker secrets its login needs.
| Placeholder | In | Value |
|---|---|---|
{secret:NAME} |
handshake text |
the worker secret NAME, resolved on every open, never stored |
{config:KEY} |
every template | the feed's config value KEY |
{items} |
subscribeframe, unsubscribeframe |
a JSON array of the rendered subscribeitems |
{channel} |
frames, items, routing keys | the item's channel ({channel:lower}, {channel:upper}) |
{seq} |
frames | 1, 2, ... per socket (a request id) |
{symbol} |
subscribeitem, routingkeyitem, a rule's routingkey |
the venue symbol ({symbol:lower}, {symbol:upper}) |
{pair}, {symbol}, {interval}, ... |
a rule's topic |
one whole segment of a served topic; {pair} is spelled by symbolformat, the others feed the rule's channel (through its values) |
A template that starts with {" or [ is JSON: a string value is
JSON-escaped (it sits inside a string literal) and the result must be one JSON
value; any other template is plain text.
flowchart TB
orch[orchestrator<br/>FeedResolver + FeedOrchestrator]
topics[served topics<br/>config topics, serve]
rules[topicitems<br/>first matching rule]
fmt[symbolformat / symbolcase<br/>BTC_USD to the venue symbol]
want[items in served order<br/>channel, symbol]
lim{maxitems<br/>maxitemsperchannel}
excl[excluded<br/>status degraded]
sub[subscribeframe x frameper<br/>every open: all; serve: the delta]
rk[routing key per topic<br/>rule routingkey or routingkeyitem]
route[routing: served keys + explicit keys]
venue[(venue)]
out[the served topics]
orch --> topics --> rules --> fmt --> want --> lim
lim -- within --> sub --> venue
lim -- beyond --> excl
rules --> rk --> route
venue -- frames --> route --> out
Binance (binance, venue binance): no login; one frame for every item,
items <symbol>@<channel>, frames name their stream. The preset:
{
"preset": "binance",
"venue": "binance",
"config": {
"url": "wss://stream.binance.com:9443/stream",
"subscribeframe": "{\"method\":\"SUBSCRIBE\",\"params\":{items},\"id\":{seq}}",
"unsubscribeframe": "{\"method\":\"UNSUBSCRIBE\",\"params\":{items},\"id\":{seq}}",
"subscribeitem": "{symbol:lower}@{channel}",
"frameper": "all",
"maxitems": 1024,
"routing": {"key_path": "stream"},
"routingkeyitem": "{symbol:lower}@{channel}"
},
"topics": {
"orderbook.update": {"channel": "depth@100ms"},
"trade.update": {"channel": "trade"},
"candle.update": {"channel": "kline_{interval}"}
}
}
renders (world act; symbolformat {BASE}{QUOTE} and the month's 1M come
from the virtufin.venue.binance fragment):
"topicitems": [
{"topic": "act.exchange.binance.orderbook.update.{pair}", "channel": "depth@100ms"},
{"topic": "act.exchange.binance.trade.update.{pair}", "channel": "trade"},
{"topic": "act.exchange.binance.candle.update.{pair}.{interval}", "channel": "kline_{interval}", "values": {"interval": {"1mo": "1M"}}}
]
Serving act.exchange.binance.orderbook.update.BTC_USDT and
act.exchange.binance.candle.update.ETH_USDT.1m sends
{"method":"SUBSCRIBE","params":["btcusdt@depth@100ms","ethusdt@kline_1m"],"id":1}
and routes the stream btcusdt@depth@100ms to the first topic.
Alpaca (alpaca, venue alpaca): a login from the worker secrets, one
frame per channel, array frames naming each message's kind in T and its
symbol in S, 10 order books and one connection per account:
{
"preset": "alpaca",
"venue": "alpaca",
"maxconnections": 1,
"config": {
"url": "wss://stream.data.alpaca.markets/v1beta3/crypto/us",
"handshake": [{"text": "{\"action\":\"auth\",\"key\":\"{secret:alpacakey}\",\"secret\":\"{secret:alpacasecret}\"}",
"expect": "\"msg\":\"authenticated\"", "fail": "\"T\":\"error\""}],
"subscribeframe": "{\"action\":\"subscribe\",\"{channel}\":{items}}",
"unsubscribeframe": "{\"action\":\"unsubscribe\",\"{channel}\":{items}}",
"frameper": "channel",
"maxitemsperchannel": {"orderbooks": 10},
"routing": {"key_path": "T,S", "split_arrays": true}
},
"topics": {
"orderbook.update": {"channel": "orderbooks", "routingkey": "o|{symbol}"},
"trade.update": {"channel": "trades", "routingkey": "t|{symbol}"}
}
}
created with the secrets alpacakey/alpacasecret as references into the
worker Secret. The compound key T,S sends a pair's book (o|BTC/USD) and its
trades (t|BTC/USD) on one connection to two topics. The resolver never puts
an 11th order book on the one connection: it reports the plan as over the
preset's limits instead (maxconnections); a feed given one anyway reports
degraded and lists it in status.excluded.
Token-carrying stream URLs: connect and keepalive
Some venue streams live at a URL that carries a token obtained per connection
(Binance's user-data stream: a signed POST /api/v3/userDataStream returns a
listenKey, valid 60 minutes, extended by a PUT every 30). The feed still
holds no venue: two generic blocks and a URL template express it.
connect— run before every open, so a reconnect gets a fresh token:{method, url, query?, headers?, sign?, extract}.url,queryandheadersare templates ({secret:NAME},{config:KEY},{timestamp}= Unix milliseconds);signappends HMAC-SHA256 of the rendered query as one more parameter ({scheme: "hmac-sha256", secret, parameter, encoding: "hex"});extractnames the response's string field.url— withconnectset, a template carrying the extracted field:wss://stream.example/ws/{connect:listenkey}(the field name lower-cased).keepalive—{method, url, query?, headers?, sign?, intervalms}, re-sent everyintervalms(default 30 minutes) while the socket is open; its templates may also use{connect:FIELD}.
Both request URLs and the resolved stream URL pass the same SSRF guard as
url, and none of them is ever logged or reported (they carry the token):
logs and status name the host. A keepalive failure only logs — the token
expires, the stream ends, and the next open runs connect again. Secrets are
resolved on every open and every keepalive tick, so a rotated key applies
without a restart.
{
"connect": {"method": "POST", "url": "https://api.binance.com/api/v3/userDataStream",
"headers": {"X-MBX-APIKEY": "{secret:binanceapikey}"}, "extract": "listenKey"},
"keepalive": {"method": "PUT", "url": "https://api.binance.com/api/v3/userDataStream",
"query": "listenKey={connect:listenkey}",
"headers": {"X-MBX-APIKEY": "{secret:binanceapikey}"}, "intervalms": 1800000},
"url": "wss://stream.binance.com:9443/ws/{connect:listenkey}",
"routing": {"key_path": "e", "keys": {"executionReport": "act.exchange.binance.order.update"}}
}
A stream config has no subscribeframe/topicitems (nothing to subscribe)
and routes with explicit routing.keys; it is created with library_reload
OFF like every feed.
Signed handshake frames: sign
Some venues authenticate a WebSocket connection with a signed request frame
(Binance's Spot WebSocket API: session.logon with an Ed25519 signature, then
userDataStream.subscribe). A handshake step may carry a sign block:
{"text": "{\"id\":\"1\",\"method\":\"session.logon\",\"params\":{\"apiKey\":\"{secret:apikey}\",\"timestamp\":{timestamp},\"signature\":\"{signature}\"}}",
"sign": {"scheme": "ed25519", "secret": "ed25519private",
"canonical": "apiKey={secret:apikey}×tamp={timestamp}", "encoding": "base64"},
"expect": "\"status\":200"}
The step's canonical template is rendered, signed with the worker secret
secret, and the signature replaces {signature} in the frame text.
scheme is hmac-sha256 or ed25519 (a PEM, a base64 PKCS#8 DER or a 32-byte
seed); encoding is hex or base64. {timestamp} (Unix milliseconds) is
available in every handshake, connect and keepalive template. As everywhere
else, the rendered frame is never logged.
The DevKit
Virtufin.WebSocket.DevKit holds what a worker needs to own a socket, with
no platform code in it:
| Type | What it does |
|---|---|
WebSocketSession |
connect, open handler, receive loop, reconnect with capped backoff, handoff login retry, graceful close, status callback |
HandshakeStep, HandshakeRunner |
the login steps (send, expect, fail, timeouts) |
TextTemplate, SymbolFormat |
frame templates ({name}, {name:arg}, JSON escaping and validity) and canonical-pair spelling |
PublishRouting, PublishRouter |
content-based routing to sub-topics |
JsonFrames |
the one-JSON-value publish rule |
WebSocketUrlValidator |
the SSRF guard (operator: WEBSOCKETFEED_ALLOWED_HOSTS, WEBSOCKETFEED_ALLOW_PRIVATE_HOSTS) |
WebSocketFeedNames |
the virtufin.worker.websocketfeed naming fragment it embeds |