Skip to content

C# Client Library

The Virtufin API Client library (Virtufin.Api.Client) provides a high-level C# interface for interacting with the Virtufin API gateway.

Installation

From Gitea NuGet Registry

Add the Virtufin package source with a personal access token (scope: read:packages):

dotnet nuget add source https://nuget.haenerconsulting.com/api/packages/virtufin/nuget/index.json \
  --name Virtufin --username <your-gitea-username> --password <your-gitea-token>

dotnet add package Virtufin.Api.Client

Or configure via NuGet.Config:

<configuration>
  <packageSources>
    <add key="Virtufin" value="https://nuget.haenerconsulting.com/api/packages/virtufin/nuget/index.json" />
  </packageSources>
  <packageSourceCredentials>
    <Virtufin>
      <add key="Username" value="<your-gitea-username>" />
      <add key="ClearTextPassword" value="<your-gitea-token>" />
    </Virtufin>
  </packageSourceCredentials>
</configuration>

From Local Source

<ProjectReference Include="path/to/Virtufin.Api.Client/Virtufin.Api.Client.csproj" />

Overview

The client library provides three main classes:

Class Description
ApiClient Main entry point with async-only operations
ServiceClient Service-specific method invocation (async-only)
ApiKeyClientInterceptor Sends x-api-key on every call of a channel
ServiceCollectionExtensions.AddVirtufinApi Registers the gateway's typed clients for a service
CloudEventFactory Builds JSON CloudEvents for PublishEventAsync
IInstanceIdProvider / InstanceIdProvider This replica's id (the pod name)

Note: This library is async-only. For synchronous usage patterns, wrap calls in Task.Run() or use a different approach.

Quick Start

using Virtufin.Api.Client;

// Create and dispose when done
        using var client = new ApiClient("localhost", 5002);

        // Discover services
        Console.WriteLine("Available Services:");
        var services = await client.ListServicesAsync();
        foreach (var service in services)
        {
            Console.WriteLine($"  - {service}");

            // List methods for each service
            var methods = await client.ListMethodsAsync(service);
            foreach (var method in methods.Take(3)) // First 3 methods
            {
                var streaming = method["isServerStreaming"] == "True" ? " (stream)" : "";
                Console.WriteLine($"    {method["name"]}{streaming}");
            }
            if (methods.Count > 3)
                Console.WriteLine($"    ... and {methods.Count - 3} more");
        }

        Console.WriteLine();

        // Invoke a method
        Console.WriteLine("Invoking workmanager.ListWorkers:");
        try
        {
            var response = await client.InvokeAsync("workmanager", "ListWorkers");
            Console.WriteLine($"Response: {System.Text.Json.JsonSerializer.Serialize(response)}");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error: {ex.Message}");
        }
    }
}

Dynamic Dispatch

The C# client uses the dynamic keyword to allow client.<service>.<method>() syntax. Under the hood, ApiClient and ServiceClient both extend System.Dynamic.DynamicObject and override TryGetMember:

  • client.<service> triggers ApiClient.TryGetMember, which returns a cached ServiceClient for the named service.
  • <service>.<method> triggers ServiceClient.TryGetMember, which returns a Func<Dictionary<string, object?>, Task<Dictionary<string, object?>>> that invokes the named method via the Gateway's InvokeJson RPC.

The dictionary argument is serialized to JSON and sent to the Gateway, which unmarshals it to the typed proto request, runs the backend RPC, and marshals the response back to JSON.

Dynamic Keyword Semantics

Because the accessor returns a dynamic, you can either:

// Option 1: assign to a 'dynamic' variable, then call methods on it.
dynamic workmanager = client.workmanager;
var workers = await workmanager.ListWorkers();

// Option 2: chain the access in a single expression.
var workers = await client.workmanager.ListWorkers();

The result of <service>.<method>(...) is Task<Dictionary<string, object?>>, so it must be awaited. The Dictionary<string, object?> is the JSON-unmarshaled response; field access uses string keys (e.g. w["id"]).

WorkManager

using var client = new ApiClient("localhost", 5002);
dynamic workmanager = client.workmanager;

// ListWorkers — no request fields; returns {"workers": [...]}
var workers = await workmanager.ListWorkers();
foreach (var w in workers["workers"])
    Console.WriteLine($"  {w["id"]}: {w["status"]} ({w["language"]})");

// CreateWorker — CodeSource oneof (url | content), mime_type, topic, group
var createResult = await workmanager.CreateWorker(new Dictionary<string, object?>
{
    ["code_source"] = new Dictionary<string, object?> { ["url"] = "https://example.com/worker.py" },
    ["mime_type"] = "text/x-python",
    ["topic"] = "worker-commands",
});
var workerId = (string)createResult["id"];

// StartWorker — id field
await workmanager.StartWorker(new Dictionary<string, object?> { ["id"] = workerId });

A WebSocket connection (WebSocketFeed worker)

A WebSocket connection is a WebSocketFeed worker of the WorkManager: create and start it, talk to it with InvokeWorkerCommand (serve, send, publish, unpublish, status), remove it with DeleteWorker. The example below is a raw feed (every frame to one topic); a feed that serves market topics gets its topics and topicitems from a venue preset (market-data-devkit VenueFeeds, or FeedResolver/FeedOrchestrator, which also create and update the feeds a set of topics needs).

dynamic workmanager = client.workmanager;

var feed = await workmanager.CreateWorker(new Dictionary<string, object?>
{
    ["code_source"] = new Dictionary<string, object?> { ["url"] = "<Virtufin.Worker.WebSocketFeed .nupkg URL>" },
    ["mime_type"] = "application/x-dotnet-dll",
    ["topics"] = new[] { "wrk.websocketfeed.command.{worker_id}" },
    ["config"] = new Dictionary<string, object?>
    {
        ["url"] = "wss://stream.example.com/feed",
        ["autoreload"] = "false",
        ["publishtopic"] = "x.examples.feed",
    },
});
var feedId = (string)feed["id"];
await workmanager.StartWorker(new Dictionary<string, object?> { ["id"] = feedId });

// InvokeWorkerCommand — returns {"outputs": [...]}, none of them published
var status = await workmanager.InvokeWorkerCommand(new Dictionary<string, object?>
{
    ["id"] = feedId,
    ["command"] = "status",
});

// DeleteWorker — closes the socket
await workmanager.DeleteWorker(new Dictionary<string, object?> { ["id"] = feedId });

From a notebook, examples/dotnet/platform.cs wraps this (ServeTopicsAsync, SendAsync, CommandAsync, FeedStatusAsync).

See also: proto-to-client-mapping spec §Layer 3a (C# wrapper) and §Layer 4 (Dynamic dispatch).


Pub/Sub Operations

The ApiClient provides pub/sub messaging via the Pubsub gRPC service.

Methods

Task<PublishResponse> PublishEventAsync(string topic, CloudEvent cloudEvent, CancellationToken cancellationToken = default)
Task<PubsubSubscribeResponse> PublishWithResultAsync(string topic, CloudEvent cloudEvent, string replyTopic, TimeSpan? timeout = null, CancellationToken cancellationToken = default)
Task<Subscription> SubscribeAsync(IEnumerable<string> topics, CancellationToken cancellationToken = default)
Task<PublishEventsResponse> PublishEventsAsync(IEnumerable<(string Topic, CloudEvent CloudEvent)> events, CancellationToken cancellationToken = default)
Task<IReadOnlyList<TopicInfo>> ListTopicsAsync(CancellationToken cancellationToken = default)

SubscribeAsync completes once the API confirms the subscription (daprd holds it), so a request published after the await cannot outrun it. The returned Subscription is an IAsyncEnumerable<SubscribeResponse>: read it once with await foreach; a stream failure or cancellation is thrown there. Dispose it to unsubscribe.

PublishEventsAsync publishes a batch in one call: each topic's events in the given order, different topics in parallel; at most 1000 events, and an invalid event rejects the whole call before anything is published.

ListTopicsAsync lists the topics seen at the gateway (published to or subscribed to), sorted by name, with when each was last seen.

PublishEventAsync publishes a CloudEvent to the given topic. Parameters:

  • topic — Topic to publish to
  • cloudEvent — The CloudEvent message (use CloudNative.CloudEvents.V1.CloudEvent proto)
  • cancellationToken — Optional cancellation token

PublishWithResultAsync implements the request-reply pattern over pub/sub using correlation IDs. Parameters:

  • topic — Topic to publish the request to
  • cloudEvent — The CloudEvent message (use CloudNative.CloudEvents.V1.CloudEvent proto)
  • replyTopic — Topic to listen for the correlated response on
  • timeout — Maximum wait time (default: 30s)
  • cancellationToken — Optional cancellation token

Raises: TimeoutException if no response arrives within the timeout.

Note on broadcast semantics: Pubsub.Subscribe is a per-API-process broadcast subscription — multiple in-process callers on the same topic all receive every message (per the Pub/Sub Topics spec §Subscription Implementation Pattern). If you want a single in-process handler to receive each message, manage the SubscribeToTopic call yourself. If you want multiple in-process handlers each receiving every message, just call SubscribeToTopic multiple times.

Resource usage: PublishWithResultAsync shares one persistent gRPC Subscribe stream per reply topic across all callers (started lazily on first use, reconnecting with backoff if it drops) and demuxes responses by correlationid. The underlying Dapr subscription is created once and stays warm; per-call cost is one pending waiter entry. Readers are cancelled by Dispose()/DisposeAsync().

Example: Publish

var cloudEvent = new CloudEvent
{
    Id = Guid.NewGuid().ToString(),
    Source = new Uri("urn:my-app"),
    Type = "my-event",
    Data = new ByteStringContent(System.Text.Encoding.UTF8.GetBytes("{\"key\": \"value\"}"), "application/json")
};
var response = await client.PublishEventAsync("my-topic", cloudEvent);
Console.WriteLine($"Published: {response.Status.Success}");

Example: Request-Reply

var cloudEvent = new CloudEvent
{
    Id = Guid.NewGuid().ToString(),
    Source = new Uri("urn:my-app"),
    Type = "my-command",
    Data = new ByteStringContent(System.Text.Encoding.UTF8.GetBytes("{\"command\": \"status\"}"), "application/json")
};
var response = await client.PublishWithResultAsync(
    topic: "worker-commands",
    cloudEvent: cloudEvent,
    replyTopic: "worker-responses",
    timeout: TimeSpan.FromSeconds(10)
);
Console.WriteLine($"Response: {Encoding.UTF8.GetString(response.CloudEvent.Data.ToByteArray())}");

Example: Subscribe

await using var sub = await client.SubscribeAsync(["my-topic"]);
// Live from here: publish requests now, their replies cannot be missed.
await foreach (var evt in sub)
{
    Console.WriteLine($"Event: {evt.Topic} - {Encoding.UTF8.GetString(evt.Data.ToByteArray())}");
}

Using the gateway from a service

A service that calls the gateway (WorkManager, the Runtime) registers its typed clients with one call:

builder.Services.AddVirtufinApi(builder.Configuration);
// GrpcChannel, CallInvoker (sends VIRTUFIN_API_KEY as x-api-key),
// Pubsub.PubsubClient, State.StateClient, Trigger.TriggerClient, IInstanceIdProvider

The endpoint is VIRTUFIN_API_HOST:VIRTUFIN_API_GRPC_PORT (ApiEndpoint, default localhost:5002). Registrations already present are kept. For a channel of your own, attach the key with channel.Intercept(new ApiKeyClientInterceptor(apiKey)).

Lifecycle events are JSON CloudEvents:

var ce = CloudEventFactory.Json(source, type, subject, payload.ToJsonString());
await pubsub.PublishEventAsync(new PublishRequest { Topic = topic, Cloudevent = ce });

InstanceIdProvider returns HOSTNAME (the pod name) when it is set and non-empty, otherwise a GUID fixed for the life of the process.

IVirtufinApi: one interface, two hosts

ApiClient implements IVirtufinApi, the union of four capability interfaces:

Interface Members
IStateApi SaveStateAsync, GetStateAsync, GetBulkStateAsync, QueryStateAsync, DeleteStateAsync, DeleteBulkStateAsync
IPubsubApi PublishEventAsync, PublishEventsAsync, SubscribeAsync, PublishWithResultAsync, ListTopicsAsync
ITriggerApi ScheduleTriggerAsync, GetTriggerAsync, DeleteTriggerAsync, ListTriggersAsync
IGatewayApi ListServicesAsync, typed InvokeAsync<TRequest, TResponse>

Write workers and tools against IVirtufinApi, not ApiClient: a WorkManager worker receives one through its IWorkerContext, and the worker devkit's local WorkManager supplies an in-process implementation (in-memory state, the local bus as pub/sub), so the same worker runs with or without a gateway. The dynamic client.service.Method(dictionary) dispatch is not part of the interface: it is JSON over reflection and does not work under NativeAOT.

Typed Invoke

InvokeAsync<TRequest, TResponse>(service, method, request, TResponse.Parser, timeout?) calls a backend method through Gateway.Invoke with protobuf bytes in and out. A backend failure the gateway reports in-band is thrown as GatewayInvokeException (Service, Method, Status, Detail; IsTransient for DEADLINE_EXCEEDED/UNAVAILABLE, which includes a tripped circuit breaker).

IVirtufinApi api = new ApiClient("api.virtufin.com", 443, tls: true, apiKey: key);
var workers = await api.InvokeAsync("workmanager", "ListWorkers",
    new ListWorkersRequest(), ListWorkersResponse.Parser, timeout: TimeSpan.FromSeconds(30));

ApiClient(CallInvoker invoker, host, port) builds a client over a caller-owned invoker: for a host that shares one channel between several clients, and for wire tests over a scripted CallInvoker. Subscription(IAsyncEnumerable<SubscribeResponse>, dispose) is public for the same reason: another host can hand out the type SubscribeAsync returns.

Protobuf Dependencies

The client library requires the generated protobuf classes. Ensure your project references:

<PackageReference Include="Google.Protobuf" />
<PackageReference Include="Grpc.Net.Client" />
<PackageReference Include="Grpc.Tools" />

The proto files (gateway.proto, config.proto) must be compiled into: - Virtufin.Api.Protos.Gateway - Virtufin.Api.Protos.Config

SDK Reference