Skip to content

Own a WebSocket connection in a worker

Most workers never open a WebSocket: WebSocketFeed serves a venue's stream, and a venue's protocol is a preset of its config, not code (Open feeds for your workers' topics). Use the WebSocketDevKit library only when a worker must own the connection itself, for example a protocol a preset cannot express.

This guide builds the connection part of such a C# worker: a session that logs in, routes each frame to a topic and publishes it through the host.

1. Reference the package

<PackageReference Include="Virtufin.WebSocket.DevKit" />

2. Check the URL

Run every configured URL through the SSRF guard before connecting:

var url = WebSocketUrlValidator.ParseWebSocketUrl(config["url"]);
await new WebSocketUrlValidator(allowedHosts: "stream.example.com").ValidateAsync(url, stop);

3. Log in on every open

The open handler runs before any frame is handed on, on the first open and on every reconnect. Describe the login as handshake steps:

IReadOnlyList<HandshakeStep> login =
[
    new(Text: $$"""{"action":"auth","key":"{{key}}"}""", Expect: "\"authenticated\"", Fail: "\"error\""),
    new(Text: """{"action":"subscribe","trades":["BTC/USD"]}""", Expect: "\"subscription\""),
];

Task OnOpenAsync(WebSocket socket, OpenReason reason, int attempt, CancellationToken ct)
    => HandshakeRunner.RunAsync(socket, login, TimeSpan.FromSeconds(10), ct, context.Logger);

Take the key from the worker's secrets (IWorkerContext.Secrets), never from an event: the handshake's messages are never logged, but a credential on a topic would be.

4. Route and publish each frame

var routing = PublishRouting.FromJson(JsonNode.Parse("""
    {"key_path": "T", "split_arrays": true, "keys": {"t": "act.exchange.example.trade"}}
    """));

async ValueTask OnFrameAsync(ReceivedFrame frame, CancellationToken ct)
{
    if (!JsonFrames.IsSingleJsonValue(frame.Payload)) return;  // only one JSON value is published
    var events = PublishRouter.Route("act.exchange.example.other", routing, frame.Payload)
        .Select(r => ToCloudEvent(r.Topic, r.Payload, frame.IngestTime));
    await context.PublishAsync(events, ct);
}

ToCloudEvent is yours: give each event its type and topic, and stamp WebSocketFeedNames.IngestTimeAttribute with frame.IngestTime as WebSocketFeed does.

5. Start and stop the session

var session = new WebSocketSession(url, OnFrameAsync, OnOpenAsync,
    onStatus: s => { context.Logger.LogInformation("{State} {Detail}", s.State, s.Detail); return ValueTask.CompletedTask; },
    options: new WebSocketSessionOptions { ReconnectMaxDelay = TimeSpan.FromSeconds(30) },
    logger: context.Logger);
await session.StartAsync();   // OpenReason.Handoff when the connection was open elsewhere before

// in StopAsync
await session.CloseAsync(deadline);

The session reconnects by itself with backoff; Completion ends when it is closed or gives up (ReconnectMaxAttempts).

See WebSocketDevKit for every type and option, and How WebSocketFeed works for the worker built on it.