Skip to content

WebSocketDevKit

The library a worker uses to own one WebSocket connection. It is built for WebSocketFeed and holds no platform code: the worker publishes through its host (IWorkerContext.PublishAsync) and keeps its state in IWorkerContext.State.

Package Language What it ships
Virtufin.WebSocket.DevKit C# the connection, handshake, routing, template and URL-guard types below, and the virtufin.worker.websocketfeed naming fragment
virtufin-websocket-devkit Python (3.14+) the same naming fragment, through the virtufin.naming entry point, so NameRegistry.load() knows the feed worker's names in Python (e.g. the TUI)

Source: WebSocketDevKit/ in this repository. Both packages share one version (WebSocketDevKit/versions.env).

Connection

WebSocketSession

One connection's lifetime: connect, run the open handler (login, subscriptions) before any frame is handed on, give every whole message to the frame handler, reconnect with capped exponential backoff, and close gracefully (a normal close frame, then abort).

public WebSocketSession(Uri url,
    Func<ReceivedFrame, CancellationToken, ValueTask> onFrame,
    WebSocketOpenHandler? onOpen = null,
    Func<WebSocketSessionStatus, ValueTask>? onStatus = null,
    WebSocketSessionOptions? options = null,
    ILogger? logger = null);

A second constructor takes a urlProvider (Func<CancellationToken, ValueTask<Uri>>): it resolves the URL once per open, for a stream URL that carries a per-connection token (e.g. a listen key). url is then for display only; the resolved URL is never logged.

Member Meaning
StartAsync(OpenReason reason = Connect) starts the connection; reason is handed to the open handler
SendAsync(message, text, ct) sends one message (text or binary)
CloseAsync(deadline) closes for good; a closed session is not reopened
State, IsConnected, Opens the current WebSocketSessionState, whether it is Connected, how many opens so far
Completion the supervisor task; ends when the session is closed or gives up

WebSocketSessionState: Idle, Connecting, Connected (open and logged in), Reconnecting, Disconnected (not retrying any more), Closed.

OpenReason: Connect (first open), Reconnect (the socket dropped), Handoff (the first open of a connection that was open elsewhere: a failed login is retried, since the previous owner may still hold a provider's one-connection-per-account slot).

WebSocketOpenHandler(WebSocket socket, OpenReason reason, int attempt, CancellationToken ct) runs on every open, before frames are handed on. ReceivedFrame(byte[] Payload, bool IsText, DateTimeOffset IngestTime) is one whole message. WebSocketSessionStatus(State, Reason, Attempt, Detail) goes to onStatus on every change.

WebSocketSessionOptions

Option Default Meaning
AutoReconnect true reopen after a drop
ReconnectBaseDelay 1 s first backoff delay
ReconnectMaxDelay 30 s backoff cap
ReconnectMaxAttempts 0 (unlimited) reconnect attempts before Disconnected
HandoffMaxAttempts 5 login retries on a Handoff open
ConnectTimeout 15 s one open's timeout
CloseTimeout 1 s how long a graceful close may take before abort

Login

HandshakeStep(Text?, Base64?, Expect?, Fail?): send Text or Base64, then wait for a frame matching the regular expression Expect; a frame matching Fail fails the login. Regular expressions run with a 1 s match timeout. HandshakeStep.ListFromJson reads a list of steps from a worker's config.

HandshakeRunner.RunAsync(socket, steps, timeout, ct, logger) runs the steps on an open socket, each reply within timeout, and throws HandshakeFailedException (its Reason says which step and why). Message contents are never logged or put into an error.

Frames

Type Meaning
TextTemplate a frame template with {name}/{name:arg} placeholders (only the names a caller allows); a JSON template must render exactly one JSON value, string values escaped. Render takes a TemplateValue per placeholder (Text, Raw, Json)
SymbolFormat spells a canonical pair (BTC_USD) the venue's way: a format ({BASE}{QUOTE}) and a case; ToVenueSymbol
JsonFrames.IsSingleJsonValue the publish rule: only a frame that is exactly one JSON value is published

Routing

PublishRouting(KeyPath, SplitArrays, Keys) routes frames to sub-topics by content:

  • the key at key_path (several dot paths separated by , make a compound key, values joined by |: T,S gives o|BTC/USD);
  • keys maps a key to its topic; split_arrays splits an array frame into its elements;
  • time_path and time_format (epoch_ms, epoch_us, epoch_ns, rfc3339; EventTimeFormat) read a message's own venue event time (TimeOf).

JSON form: {key_path, split_arrays, keys?, time_path?, time_format?} (FromJson, ToJson); WithKeys adds derived keys, explicit ones win.

PublishRouter.Route(baseTopic, routing, frame, eventTimes) returns the (Topic, Payload) pairs of one frame, and collects each routed message's event time in eventTimes in the same pass. Without routing, the frame goes to baseTopic as it is.

URL guard

WebSocketUrlValidator(allowedHosts, blockPrivateAddresses = true), the SSRF guard: ws:// and wss:// only, an optional host allow-list, and no loopback, private, link-local or unspecified address unless an operator allows private ones. ParseWebSocketUrl parses and checks the scheme; ValidateAsync resolves the host and checks every address.

Names

WebSocketFeedNames, from the embedded virtufin.worker.websocketfeed fragment:

Member Value
MessageType com.virtufin.websocketfeed.message, a relayed frame
Source urn:com.virtufin:worker:websocketfeed
CommandTopic(workerId) wrk.websocketfeed.command.<id>
CommandType, ResponseType, ErrorType the worker's command, response and error ce-types
IngestTimeAttribute, WebSocketIdAttribute, WebSocketUrlAttribute ingesttime, websocketid, websocketurl on every relayed frame

Not in the library

  • A pub/sub handshake request and reply: it would put credentials on a reply topic. A worker computes its login in-process from its secrets.
  • Connection records and a publication fence: the WorkManager Runtime's lease does that.
  • A batching publisher: the Runtime's outbox does that.

See also: How WebSocketFeed works, Own a WebSocket connection in a worker.