Table of Contents

Class ApiClient

Namespace
Virtufin.Api.Client
Assembly
Virtufin.Api.Client.dll

Client for the Virtufin API Gateway: dynamic per-service RPC dispatch (service names as dynamic members, e.g. client.workmanager.SomeMethod()), plus direct methods for state, pub/sub, triggers and config.

public class ApiClient : DynamicObject, IDynamicMetaObjectProvider, IVirtufinApi, IStateApi, IPubsubApi, ITriggerApi, IGatewayApi, IDisposable, IAsyncDisposable
Inheritance
ApiClient
Implements
Inherited Members

Examples

using var client = new ApiClient();
var workers = await client.workmanager.ListWorkers();
// Equivalent to:
var workers = await client.InvokeAsync("workmanager", "ListWorkers");

Remarks

client.workmanager triggers TryGetMember(GetMemberBinder, out object?), which creates or returns a cached ServiceClient for "workmanager". service.ListWorkers() triggers TryGetMember(GetMemberBinder, out object?), which returns a callable that invokes via the Gateway's InvokeJson RPC.

Constructors

ApiClient(CallInvoker, string, int)

A client over a caller-owned invoker (already carrying any api-key interceptor): for a host that shares one channel with other clients, and for wire tests. Disposing the client does not shut the invoker down.

public ApiClient(CallInvoker invoker, string host = "localhost", int port = 0)

Parameters

invoker CallInvoker
host string
port int

ApiClient(GrpcChannel)

Creates a new ApiClient from a pre-built gRPC channel -- the escape hatch for anything the host/port/tls/apiKey constructor can't express (a custom HttpMessageHandler, etc.). Host and HttpPort are not meaningful from a raw channel and are left at their defaults ("localhost", 0).

public ApiClient(GrpcChannel channel)

Parameters

channel GrpcChannel

The gRPC channel to use for communication.

ApiClient(string, int?, bool, string?)

Creates a new ApiClient.

public ApiClient(string host = "localhost", int? grpcPort = null, bool tls = false, string? apiKey = null)

Parameters

host string

The host address (default: "localhost").

grpcPort int?

The gRPC port (default: DefaultGrpcPort).

tls bool

Use an HTTPS channel, verified against system CA roots.

apiKey string

Sent as x-api-key on every call, through an ApiKeyClientInterceptor. Null sends no key.

Properties

Host

The host address of the gateway.

public string Host { get; }

Property Value

string

HttpPort

The gRPC port of the gateway.

public int HttpPort { get; }

Property Value

int

InvokeTimeout

Default gRPC deadline for InvokeAsync(string, string, Dictionary<string, object?>?) and dynamic calls (client.workmanager.CreateWorker(...)). Null (the default) sends no deadline, and the gateway applies its own 30s default to the call it forwards. Set it longer for an operation that legitimately takes more time, e.g. a cold CreateWorker. The gateway honors it up to its 300s cap.

public TimeSpan? InvokeTimeout { get; set; }

Property Value

TimeSpan?

Methods

AddTriggerToGroupAsync(string, string, CancellationToken)

Adds the trigger to group (the WorkManager's membership calls).

public Task AddTriggerToGroupAsync(string id, string group, CancellationToken cancellationToken = default)

Parameters

id string
group string
cancellationToken CancellationToken

Returns

Task

ClearTriggerOwnerAsync(string, CancellationToken)

Clears the trigger's owner worker without rescheduling it.

public Task ClearTriggerOwnerAsync(string id, CancellationToken cancellationToken = default)

Parameters

id string
cancellationToken CancellationToken

Returns

Task

Close()

Closes the client synchronously.

public void Close()

CloseAsync()

Closes the client asynchronously.

public Task CloseAsync()

Returns

Task

DeleteBulkStateAsync(string, IEnumerable<string>, bool, ChangeNotification?, CancellationToken)

Deletes multiple state entries for a service.

public Task<DeleteBulkStateResponse> DeleteBulkStateAsync(string service, IEnumerable<string> keys, bool publishChange = false, ChangeNotification? change = null, CancellationToken cancellationToken = default)

Parameters

service string
keys IEnumerable<string>
publishChange bool

If true, a single state change event is published (sys.api.state.deleted) for the whole bulk. Default false.

change ChangeNotification

Optional. See SaveStateAsync(string, string, string, string?, bool, bool, ChangeNotification?, CancellationToken) for what this selects.

cancellationToken CancellationToken

Returns

Task<DeleteBulkStateResponse>

DeleteStateAsync(string, string, bool, bool, ChangeNotification?, CancellationToken)

Deletes a state entry and broadcasts a delete event to subscribers asynchronously.

public Task<DeleteStateResponse> DeleteStateAsync(string service, string key, bool publishChange = false, bool includeValue = false, ChangeNotification? change = null, CancellationToken cancellationToken = default)

Parameters

service string

The service name.

key string

The state key.

publishChange bool

If true, a state change event is published (sys.api.state.saved/deleted). Default false.

includeValue bool

If true, the last value is included in the state change event payload. Only relevant when publishChange=true.

change ChangeNotification

Optional. See SaveStateAsync(string, string, string, string?, bool, bool, ChangeNotification?, CancellationToken) for what this selects.

cancellationToken CancellationToken

Cancellation token.

Returns

Task<DeleteStateResponse>

An empty response: the delete succeeded. A failure throws RpcException with an ErrorInfo.

DeleteTriggerAsync(string, CancellationToken)

Deletes the trigger, its tags and groups; NotFound when there is none.

public Task DeleteTriggerAsync(string id, CancellationToken cancellationToken = default)

Parameters

id string
cancellationToken CancellationToken

Returns

Task

Dispose()

Disposes of the client resources.

public void Dispose()

DisposeAsync()

Disposes of the client resources asynchronously.

public ValueTask DisposeAsync()

Returns

ValueTask

GetBulkStateAsync(string, IEnumerable<string>, CancellationToken)

Gets multiple state values for a service and list of keys.

public Task<List<StateItemDto>> GetBulkStateAsync(string service, IEnumerable<string> keys, CancellationToken cancellationToken = default)

Parameters

service string
keys IEnumerable<string>
cancellationToken CancellationToken

Returns

Task<List<StateItemDto>>

GetConfigServiceAsync(string, CancellationToken)

Gets one service's configuration. Throws RpcException with NotFound if the name is not registered.

public Task<GetConfigServiceResponse> GetConfigServiceAsync(string name, CancellationToken cancellationToken = default)

Parameters

name string
cancellationToken CancellationToken

Returns

Task<GetConfigServiceResponse>

GetMethodSchemaAsync(string, string, string?, CancellationToken)

The schema of a method's input (default) or output message.

public Task<MethodSchema> GetMethodSchemaAsync(string service, string method, string? type = null, CancellationToken cancellationToken = default)

Parameters

service string

The service name.

method string

The method name.

type string

"input" (default) or "output".

cancellationToken CancellationToken

Cancellation token.

Returns

Task<MethodSchema>

Exceptions

RpcException

NotFound for an unknown service or method.

GetPayloadSchemaAsync(GetPayloadSchemaRequest, CancellationToken)

A payload schema by content type (its current one) or by hash; null when there is none (or no gateway).

public Task<PayloadSchema?> GetPayloadSchemaAsync(GetPayloadSchemaRequest request, CancellationToken cancellationToken = default)

Parameters

request GetPayloadSchemaRequest
cancellationToken CancellationToken

Returns

Task<PayloadSchema>

GetService(string)

Gets a client for a specific service.

public ServiceClient GetService(string name)

Parameters

name string

The service name.

Returns

ServiceClient

A ServiceClient for the service.

Remarks

ServiceClients are cached internally. Calling this method multiple times with the same service name returns the same cached instance.

GetStateAsync(string, string, CancellationToken)

Gets a single state value asynchronously by service and key.

public Task<(string Value, string Etag)> GetStateAsync(string service, string key, CancellationToken cancellationToken = default)

Parameters

service string

The service name.

key string

The state key.

cancellationToken CancellationToken

Cancellation token.

Returns

Task<(string Value, string Etag)>

Tuple of (value, etag).

GetTriggerAsync(string, CancellationToken)

The trigger; NotFound when there is none.

public Task<TriggerDetail> GetTriggerAsync(string id, CancellationToken cancellationToken = default)

Parameters

id string
cancellationToken CancellationToken

Returns

Task<TriggerDetail>

InvokeAsync(string, string, Dictionary<string, object?>?)

Invokes a method on a service asynchronously.

public Task<Dictionary<string, object?>> InvokeAsync(string service, string method, Dictionary<string, object?>? requestData = null)

Parameters

service string

The service name.

method string

The method name.

requestData Dictionary<string, object>

Optional request data as dictionary.

Returns

Task<Dictionary<string, object>>

The response as a dictionary.

Remarks

The Dictionary<string, object?> payload is (de)serialized with Virtufin.Api.Client.ApiClient.JsonOptions: source-generated, with reflection as a fallback where it is enabled.

Exceptions

GatewayInvokeException

Thrown when the invocation fails, with the failure's ErrorInfo.

InvokeAsync(string, string, Dictionary<string, object?>?, TimeSpan?)

InvokeAsync(string, string, Dictionary<string, object?>?) with an explicit gRPC deadline for this call (null: no deadline). A separate overload rather than a new optional parameter, so code already compiled against the three-argument signature keeps binding to it.

public Task<Dictionary<string, object?>> InvokeAsync(string service, string method, Dictionary<string, object?>? requestData, TimeSpan? timeout)

Parameters

service string
method string
requestData Dictionary<string, object>
timeout TimeSpan?

Returns

Task<Dictionary<string, object>>

InvokeAsync<TRequest, TResponse>(string, string, TRequest, MessageParser<TResponse>, TimeSpan?, CancellationToken)

Calls method on the backend service through Gateway.Invoke, protobuf bytes in and out. A backend failure the gateway reports in-band (its status/message) is thrown as GatewayInvokeException. No JSON and no reflection: safe under NativeAOT, unlike the dynamic client.service.Method(dictionary) form. parser is the response message's Parser (e.g. CreateWorkerResponse.Parser); a null timeout leaves the deadline to the gateway's default (30 s).

public Task<TResponse> InvokeAsync<TRequest, TResponse>(string service, string method, TRequest request, MessageParser<TResponse> parser, TimeSpan? timeout = null, CancellationToken cancellationToken = default) where TRequest : IMessage where TResponse : IMessage<TResponse>

Parameters

service string
method string
request TRequest
parser MessageParser<TResponse>
timeout TimeSpan?
cancellationToken CancellationToken

Returns

Task<TResponse>

Type Parameters

TRequest
TResponse

ListConfigServicesAsync(CancellationToken)

Lists every registered service, including non-dialable entries (those that exist only to resolve Dapr component names).

public Task<ListConfigServicesResponse> ListConfigServicesAsync(CancellationToken cancellationToken = default)

Parameters

cancellationToken CancellationToken

Returns

Task<ListConfigServicesResponse>

Remarks

Contrast ListServicesAsync(), which returns only the backends the gateway can actually invoke.

ListMethodsAsync(string)

Lists all methods for a given service asynchronously.

public Task<List<Dictionary<string, object?>>> ListMethodsAsync(string service)

Parameters

service string

The service name.

Returns

Task<List<Dictionary<string, object>>>

List of method information dictionaries; kind is the gateway's (openspec api-gateway, Method Kinds): "read", "write", or "unspecified" from a gateway that does not say.

ListPayloadSchemasAsync(CancellationToken)

Every registered payload content type, without the schemas' bytes; empty without a gateway.

public Task<IReadOnlyList<PayloadSchemaEntry>> ListPayloadSchemasAsync(CancellationToken cancellationToken = default)

Parameters

cancellationToken CancellationToken

Returns

Task<IReadOnlyList<PayloadSchemaEntry>>

ListServicesAsync()

Lists all available services asynchronously.

public Task<List<string>> ListServicesAsync()

Returns

Task<List<string>>

List of service names.

ListServicesAsync(CancellationToken)

public Task<List<string>> ListServicesAsync(CancellationToken cancellationToken)

Parameters

cancellationToken CancellationToken

Returns

Task<List<string>>

ListTopicsAsync(CancellationToken)

Lists the topics seen at the gateway (published to or subscribed to), sorted by name, with when each was last seen. Topics unseen for 7 days drop out.

public Task<IReadOnlyList<TopicInfo>> ListTopicsAsync(CancellationToken cancellationToken = default)

Parameters

cancellationToken CancellationToken

Cancellation token.

Returns

Task<IReadOnlyList<TopicInfo>>

ListTriggersAsync(ListTriggersRequest, CancellationToken)

The triggers matching request's owner, tag filters and group (all, when none is set).

public Task<IReadOnlyList<TriggerDetail>> ListTriggersAsync(ListTriggersRequest request, CancellationToken cancellationToken = default)

Parameters

request ListTriggersRequest
cancellationToken CancellationToken

Returns

Task<IReadOnlyList<TriggerDetail>>

PublishEventAsync(string, CloudEvent, CancellationToken)

Publishes a CloudEvent to a topic asynchronously.

public Task<PublishResponse> PublishEventAsync(string topic, CloudEvent cloudevent, CancellationToken cancellationToken = default)

Parameters

topic string

The topic name.

cloudevent CloudEvent

The CloudEvent proto to publish.

cancellationToken CancellationToken

Cancellation token.

Returns

Task<PublishResponse>

An empty response: the event was published. A failure throws RpcException with an ErrorInfo.

PublishEventsAsync(IEnumerable<(string Topic, CloudEvent CloudEvent)>, CancellationToken)

Publishes several events in one call: each topic's events in the given order, different topics in parallel. At most 1000 events; an invalid event rejects the whole call (InvalidArgument) before anything is published.

public Task<PublishEventsResponse> PublishEventsAsync(IEnumerable<(string Topic, CloudEvent CloudEvent)> events, CancellationToken cancellationToken = default)

Parameters

events IEnumerable<(string Topic, CloudEvent CloudEvent)>

The events, each with its topic.

cancellationToken CancellationToken

Cancellation token.

Returns

Task<PublishEventsResponse>

The count published (every event). A call that published only some throws RpcException (Aborted, PartialFailure) whose PublishEventsFailure detail (DetailOf<T>(RpcException)) lists the failed indexes.

PublishEventsPacedAsync(IEnumerable<(string Topic, CloudEvent CloudEvent)>, bool, CancellationToken)

Publishes several events in one paced call: the gateway holds it while a consumer of one of the topics is behind, so a source that can wait (a replay, a bulk publish) loses no event past the stream's retention. Never for live data. A call held for the gateway's whole wait ends with ResourceExhausted and publishes nothing; retryHeld publishes it again until it goes through. An implementation that cannot pace (a local test double) throws NotSupportedException.

public Task<PublishEventsResponse> PublishEventsPacedAsync(IEnumerable<(string Topic, CloudEvent CloudEvent)> events, bool retryHeld = false, CancellationToken cancellationToken = default)

Parameters

events IEnumerable<(string Topic, CloudEvent CloudEvent)>
retryHeld bool
cancellationToken CancellationToken

Returns

Task<PublishEventsResponse>

PublishWithResultAsync(string, CloudEvent, string, TimeSpan?, string?, CancellationToken)

Publishes to a topic and waits for a correlated response on a reply topic. Implements the request-reply pattern over pub/sub using correlation IDs. Sets correlationid and replytopic as CloudEvent attributes before publishing.

public Task<SubscribeResponse> PublishWithResultAsync(string topic, CloudEvent cloudevent, string replyTopic, TimeSpan? timeout = null, string? correlationId = null, CancellationToken cancellationToken = default)

Parameters

topic string

The topic to publish the request to.

cloudevent CloudEvent

The CloudEvent proto to publish.

replyTopic string

The topic to listen for responses on.

timeout TimeSpan?

Maximum time to wait for a response (default: 30s).

correlationId string

Optional correlation ID (auto-generated if null).

cancellationToken CancellationToken

Cancellation token.

Returns

Task<SubscribeResponse>

The correlated SubscribeResponse.

Exceptions

TimeoutException

Thrown if no response arrives within the timeout.

QueryStateAsync(string, string, int, CancellationToken)

Gets all state key-value pairs asynchronously for a service.

public Task<List<StateItemDto>> QueryStateAsync(string service, string query, int limit = 0, CancellationToken cancellationToken = default)

Parameters

service string

The service name.

query string

The Dapr JSON query string.

limit int

Max results (0 = no limit).

cancellationToken CancellationToken

Cancellation token.

Returns

Task<List<StateItemDto>>

List of state items with key, value, etag.

RegisterPayloadSchemaAsync(PayloadSchema, CancellationToken)

Registers the schema of a binary payload the caller emits (openspec api-gateway, Payload Schema Registry); registering the same schema again changes nothing. The default does nothing: an in-process host has no gateway registry. ApiClient registers with the gateway.

public Task<RegisterPayloadSchemaResponse> RegisterPayloadSchemaAsync(PayloadSchema schema, CancellationToken cancellationToken = default)

Parameters

schema PayloadSchema
cancellationToken CancellationToken

Returns

Task<RegisterPayloadSchemaResponse>

RemoveTriggerFromGroupAsync(string, string, bool, CancellationToken)

Removes the trigger from group and answers the groups it still belongs to. With forGroupDeletion (a DeleteGroup), empty means it is marked deleting, for the caller to delete; without, empty means it is in no group and keeps running.

public Task<IReadOnlyList<string>> RemoveTriggerFromGroupAsync(string id, string group, bool forGroupDeletion = false, CancellationToken cancellationToken = default)

Parameters

id string
group string
forGroupDeletion bool
cancellationToken CancellationToken

Returns

Task<IReadOnlyList<string>>

SaveStateAsync(string, string, string, string?, bool, bool, ChangeNotification?, CancellationToken)

Saves state and broadcasts a change event to subscribers asynchronously.

public Task<SaveStateResponse> SaveStateAsync(string service, string key, string value, string? etag = null, bool publishChange = false, bool includeValue = false, ChangeNotification? change = null, CancellationToken cancellationToken = default)

Parameters

service string

The service name.

key string

The state key.

value string

The state value.

etag string

Optional etag for concurrency.

publishChange bool

If true, a state change event is published (sys.api.state.saved/deleted). Default false.

includeValue bool

If true, the value is included in the state change event payload. Only relevant when publishChange=true.

change ChangeNotification

Optional. With publishChange, selects where the notification goes. Unset means the Tier 0 sys.api.state.saved/deleted topic, correct for infra state. For domain state (positions, portfolios, orders) supply a ChangeNotification carrying both a topic and a CloudEvent: the API publishes that event verbatim after the write and skips the Tier 0 topic. It cannot build the event itself -- it has the key and the bytes but not the scenario, world markers, clock type, or your service identity. Tier 0 events carry no version, so consuming the value without a read-back assumes writes to that key are serialized; carry a monotonic token in your own event if you need ordering. Publication is at-most-once and not atomic with the write.

cancellationToken CancellationToken

Cancellation token.

Returns

Task<SaveStateResponse>

The value's etag after the write. A failure throws RpcException with an ErrorInfo (ErrorInfoOf(RpcException)).

ScheduleTriggerAsync(ScheduleTriggerRequest, CancellationToken)

Schedules a trigger and answers its id: request.id when given, else a generated UUID of version 7. A given id that exists fails with AlreadyExists (IdExists).

public Task<string> ScheduleTriggerAsync(ScheduleTriggerRequest request, CancellationToken cancellationToken = default)

Parameters

request ScheduleTriggerRequest
cancellationToken CancellationToken

Returns

Task<string>

Remarks

When it fires, the API publishes an empty CloudEvent to the request's target_topic.

SubscribeAsync(IEnumerable<string>, CancellationToken)

Subscribes to one or more pub/sub topics. Completes once the API confirms the subscription (its response headers: daprd holds the subscription), so a request published after the await cannot outrun it. Read the events with await foreach; dispose the subscription to end it.

public Task<Subscription> SubscribeAsync(IEnumerable<string> topics, CancellationToken cancellationToken = default)

Parameters

topics IEnumerable<string>

Topics to subscribe to. Filtering is by topic only -- SubscribeRequest carries no service or event-type filter, so discriminate further on cloudevent.type. An empty list is not "all topics": the server defaults it to the state-change topics (sys.api.state.saved, sys.api.state.deleted), so name your topics explicitly.

cancellationToken CancellationToken

Cancels the subscribe and, later, the stream.

Returns

Task<Subscription>

The live subscription. A failure (or cancellation) while reading it is thrown from the await foreach.

TryGetMember(GetMemberBinder, out object?)

Dynamic property access returns a ServiceClient for the named service.

public override bool TryGetMember(GetMemberBinder binder, out object? result)

Parameters

binder GetMemberBinder
result object

Returns

bool

UpdateTriggerTagsAsync(string, IReadOnlyDictionary<string, string>?, IEnumerable<string>?, CancellationToken)

Sets set and removes remove in one atomic step; the next firing stays.

public Task UpdateTriggerTagsAsync(string id, IReadOnlyDictionary<string, string>? set, IEnumerable<string>? remove, CancellationToken cancellationToken = default)

Parameters

id string
set IReadOnlyDictionary<string, string>
remove IEnumerable<string>
cancellationToken CancellationToken

Returns

Task