API Reference
The gateway is gRPC and gRPC-Web only, both on its gRPC port; the HTTP port serves only the health checks. See Calling the gateway.
Complete API documentation for the Virtufin API gateway.
Generated API Documentation
- C# SDK Reference — Auto-generated docs for
Virtufin.ApiandVirtufin.Api.Client - Python SDK Reference — Auto-generated docs for
virtufinpackage - TypeScript SDK Reference — Auto-generated docs for TypeScript client
Table of Contents
Health Check
GET /health
Returns the health status of the API gateway.
Response:
{
"status": "Healthy",
"totalDuration": "00:00:00.0100000",
"entries": {
"dapr": {
"status": "Healthy",
"description": "Dapr is available"
},
"grpc-channel-pool": {
"status": "Healthy",
"description": "gRPC channel pool is initialized"
}
}
}
gRPC Services
The Virtufin API exposes two main gRPC services defined in gateway.proto and config.proto.
Gateway Service (virtufin.Gateway)
| Method | Request | Response | Description |
|---|---|---|---|
Invoke |
InvokeRequest |
InvokeResponse |
Invoke a method on a service |
ListServices |
ListServicesRequest |
ListServicesResponse |
List all registered services |
ListMethods |
ListMethodsRequest |
ListMethodsResponse |
List methods for a service |
GetMethodSchema |
GetMethodSchemaRequest |
GetMethodSchemaResponse |
Describe a method's wire format |
RegisterPayloadSchema |
RegisterPayloadSchemaRequest |
RegisterPayloadSchemaResponse |
Register the schema of a binary payload a producer emits |
GetPayloadSchema |
GetPayloadSchemaRequest |
PayloadSchema |
A payload schema by content type or hash |
ListPayloadSchemas |
ListPayloadSchemasRequest |
ListPayloadSchemasResponse |
Every registered payload content type |
State Service (virtufin.State)
| Method | Request | Response | Description |
|---|---|---|---|
SaveState |
SaveStateRequest |
SaveStateResponse |
Save state and publish event |
GetState |
GetStateRequest |
GetStateResponse |
Get a single state value |
DeleteState |
DeleteStateRequest |
DeleteStateResponse |
Delete state and publish event |
QueryState |
QueryStateRequest |
QueryStateResponse |
Search state entries via Dapr's query-state DSL (requires a Query-API-capable store; see QueryState) |
GetBulkState |
GetBulkStateRequest |
GetBulkStateResponse |
Get multiple state values by key |
DeleteBulkState |
DeleteBulkStateRequest |
DeleteBulkStateResponse |
Delete multiple state entries by key |
Config Service (virtufin.Config)
| Method | Request | Response | Description |
|---|---|---|---|
ListServices |
ListConfigServicesRequest |
ListConfigServicesResponse |
List all service configs |
GetService |
GetConfigServiceRequest |
GetConfigServiceResponse |
Get a specific service config |
Gateway Service Methods
Invoke
Invokes a method on a registered service.
Request (InvokeRequest):
message InvokeRequest {
string service = 1; // Service name (e.g., "workmanager")
string method = 2; // Method name (e.g., "GetWorker")
string request_data = 3; // JSON request payload
}
Response (InvokeResponse):
message InvokeResponse {
bool success = 1; // Whether the call succeeded
string status = 2; // gRPC status code
string message = 3; // Error message if failed
string response_data = 4; // JSON response payload
bytes status_details = 5; // On a failure: the encoded google.rpc.Status, with its ErrorInfo
}
The envelope reports the backend's outcome, its google.rpc.ErrorInfo included; see
Errors.
ListServices
Lists all services registered with the gateway.
Request: ListServicesRequest (empty)
Response:
message ListServicesResponse {
repeated string services = 1; // List of service names
}
ListMethods
Lists all methods available on a service.
Request:
message ListMethodsRequest {
string service = 1; // Service name
}
Response:
message ListMethodsResponse {
repeated MethodInfo methods = 1;
}
message MethodInfo {
string name = 1;
string full_name = 2;
string input_type = 3;
string output_type = 4;
bool is_client_streaming = 5;
bool is_server_streaming = 6;
}
Payload schemas
Binary event payloads (protobuf or FlatBuffers, named by datacontenttype) carry no
schema of their own. Producers register them; generic readers (the TUI, the app, the
EventStore) look them up.
- Register.
RegisterPayloadSchematakes aPayloadSchemawith: content_type;encoding:PROTOBUFfor agoogle.protobuf.FileDescriptorSetholding the message's file and every file it imports, orFLATBUFFERSfor a.bfbs;message_name: the message's full name, or the root table;schema: the bytes.
The answer gives the schema's SHA-256 (hash) and whether the content type's schema
changed. Registering the same schema again changes nothing.
worker-devkit registers every payload a worker emits when the worker starts.
- What is refused (INVALID_ARGUMENT):
- a descriptor set that does not parse, does not build (an imported file is missing) or
does not declare message_name;
- a FlatBuffers schema without the BFBS identifier;
- a schema larger than 1 MiB.
- Look up. GetPayloadSchema takes content_type (its current schema) or hash (any
schema the content type has had); NOT_FOUND when there is none.
ListPayloadSchemas lists every content type with its current hash and earlier hashes,
without the bytes.
- Decode (C#). ProtoJson.Messages(schema) builds the descriptors of a protobuf schema,
and ProtoJson.For(messages).Decode(bytes, messages[messageName]) writes the payload as
JSON (proto field names, default values, well-known types in their JSON forms), for a
reader that does not link the producer's types. Both are in Virtufin.Api.Client.
- Storage. One JSON record, sys.api.payload-schema.catalog, maps each content type to
its encoding, message, current and earlier hashes. Each schema's bytes are stored raw
under sys.api.payload-schema.blob.<hash>.
Subscribe
Subscribes to one or more pub/sub topics. Server-streaming; defined on the Pubsub
service, not on Gateway.
Request:
message SubscribeRequest {
repeated string topics = 1; // Topics to subscribe to
google.protobuf.Timestamp replay_since = 2; // Optional: replay retained entries first
bool replay_only = 3; // Optional: only the replay, then the call ends
bool announce_live = 4; // Optional: a first response with live = true
bool accept_batches = 5; // Optional: a batch entry as one response
}
A subscription starts at each topic's tail: what was published before it opened is not
delivered, and everything published after it is. On the Redis backend a closed
subscription's leftover reader in daprd can take the next message on its topic
(common#28); the gateway
finds that message within seconds and delivers it to the topic's open subscription, 2-7 s
late and possibly out of order, instead of dropping it. To avoid that path, a topic's Dapr
subscription stays open PubsubSubscriptionLingerSeconds (default 10, 0 closes at once)
after its last caller left: a caller that subscribes again meanwhile joins it, so a quick
resubscribe never closes and reopens one. What is published while nobody is subscribed is
not delivered to a later caller (no catch-up).
A subscriber that is behind holds nobody back and loses nothing: when its buffer (1024
events) is full, the gateway serves it from the topic's stream at its own pace, and puts
it back on live delivery when it has caught up. It gets every event in the stream's
order, each once in the normal case (at-least-once, as everywhere: deduplicate by
CloudEvent source and id). The call ends when that is not possible:
| Status | Meaning | What to do |
|---|---|---|
DATA_LOSS |
The subscriber is behind further than the stream reaches back (streamTTL on the Redis backend, the stream's max_age / max_bytes on NATS JetStream): events are missing. |
Subscribe again; treat it as a gap. |
RESOURCE_EXHAUSTED |
The subscriber took no event for PubsubSubscriberStallSeconds (default 300), or its backlog cannot be read from a stream (the Redis and NATS JetStream backends have one). |
Subscribe again, with replay_since for what the stream still holds. |
With replay_since set, the gateway first delivers every entry the topic's
stream still retains from that time on (the stream's own clock; Redis stream ids are
milliseconds), oldest first, and then the live messages, skipping a live message the
replay already delivered (matched by CloudEvent id). The response headers are sent once
the live subscription is active, before the replayed entries. Replay is meant for
low-rate topics that must survive a resubscription, such as a worker's command topic
while the WorkManager Runtime moves the worker to another pod; it reads the stream (Redis XRANGE, NATS JetStream batched direct get) and moves no
consumer group. It needs the Redis pub/sub backend with PubsubRedisHost, or the NATS
JetStream backend with PubsubNatsUrl (FAILED_PRECONDITION otherwise), and a topic that retains
more events since then than PubsubReplayMaxEntries (default 10000; a batch entry counts as the events it holds), or more payload
bytes than PubsubReplayMaxBytes (default 64 MiB), is OUT_OF_RANGE; both fail before
the headers. The stream is read in pages of 256 entries and the read stops at the first
limit passed, so an overrun never loads the whole stream.
replay_only = 3 (with replay_since): the call delivers the retained entries and then
ends with OK; no live subscription is opened (no Dapr subscription, no consumer group).
For a subscriber that already receives the topic live and needs only what it missed: the
WorkManager Runtime catches a worker that moved to another pod up on its input topics
this way, merging the replay with its shared live stream by CloudEvent id. Without
replay_since it is INVALID_ARGUMENT.
announce_live = 4: the first response of the call is live = true, without a topic or
an event, sent once every topic is subscribed, right after the response headers. For a
client that cannot see the headers before the first body bytes (a browser over gRPC-Web
in Firefox). Ignored with replay_only.
accept_batches = 5: the events a publisher sent together with PublishEvents, which
the gateway stores as one stream entry, arrive as one response with batch set instead
of one response per event.
- The events and their order are the same either way. An event stored alone still
arrives in
cloudevent, so the subscriber handles both shapes. batchholds an encodedio.cloudevents.v1.CloudEventBatch. The gateway forwards the stored bytes without reading the events; parse them withCloudEventBatch.- The buffer counts events, so a batch of 1000 events takes the room of 1000.
- On a live call with
replay_sinceevery response stays a single event. Withreplay_onlythe retained entries arrive as stored, and the bounds still count events. - Meant for a subscriber that takes events in bulk, such as the WorkManager Runtime. The client wrappers do not set it.
Subscribefilters by topic only — there is no service or event-type filter on the wire. An emptytopicslist does not mean "all topics"; it defaults to["sys.api.state.saved", "sys.api.state.deleted"]. Discriminate further oncloudevent.type.
Response (stream):
message SubscribeResponse {
string topic = 1;
io.cloudevents.v1.CloudEvent cloudevent = 2; // One event
bool live = 3; // Only with announce_live, on the first response
bytes batch = 4; // Only with accept_batches: an encoded CloudEventBatch
}
An event arrives as it was published: the data (binary_data, text_data or
proto_data) and every attribute in the type the publisher sent. A time sent as a
string arrives as a timestamp. See
How events are stored.
Paced publishing
A publisher that can wait (a replay, a simulation, synthetic data) sets pace on
Pubsub.PublishEvents, so it never runs further ahead of its slowest consumer than the
topic's stream retains. Consumers report where they are with Pubsub.ReportProgress.
The rule is the same for every topic, act. or hyp.. Why it works this way:
Paced publishing.
message PublishEventsRequest {
repeated PublishRequest events = 1;
bool pace = 2; // Wait while a consumer of the topics is behind
string consumer = 3; // The publisher's own consumer id: its own positions do not hold it back
}
message ConsumerPosition {
string topic = 1;
string consumer = 2; // Opaque; the WorkManager Runtime sends worker/<id>
google.protobuf.Timestamp position = 3; // At or before the last finished event's stream entry
bool idle = 4; // Nothing of the topic waits for it: not behind
bool removed = 5; // Gone from the topic: forget it now
string last_id = 6; // Id of the last event finished: a new one counts as movement
}
message ReportProgressRequest { repeated ConsumerPosition positions = 1; }
message ReportProgressResponse { uint32 accepted = 1; }
- Held. A paced call waits while a consumer of one of its topics that reported its
progress and is not idle lags (now − position) by
PubsubPaceHighWaterSecondsor more. It is published once none does. - Refused. Held for
PubsubPaceMaxWaitSeconds, the call ends withRESOURCE_EXHAUSTED. Nothing is published, and the status names the slowest consumer and its lag. - Reports. Send one
ReportProgresscall per reporter and interval, never one per event. Repeat an unmoved position at least every halfPubsubProgressLeaseSeconds. A consumer that did not report within the lease, or did not move forPubsubProgressStallSecondswhile not idle (neither its position nor itslast_idchanged), no longer counts. At most 10,000 positions per call. A position is required unless the consumer is idle or removed. - Clients. Pacing is off unless asked for:
| Client | Paced publish |
|---|---|
| C# | PublishEventsPacedAsync(events, retryHeld: true) (IPubsubApi; a local test double throws NotSupportedException) |
| Python | publish_events_async(events, pace=True, retry_held=True) |
| TypeScript | publishEvents(events, true, true) (pace, retryHeld) |
With retryHeld / retry_held the client publishes a refused call again until it goes
through; without it the RESOURCE_EXHAUSTED error reaches the caller. Never pace live
data: a venue does not wait.
| Setting | Default | What it bounds |
|---|---|---|
PubsubPaceHighWaterSeconds |
30 | The lag that holds a paced publish: half the chart's streamTTL of one minute, so a held consumer has the other half to catch up. |
PubsubPaceMaxWaitSeconds |
60 | How long a paced publish is held before RESOURCE_EXHAUSTED. |
PubsubProgressLeaseSeconds |
15 | How long a reported position counts. |
PubsubProgressStallSeconds |
60 | How long a consumer that is not idle may keep the same position and still count: one retention, after which it has lost events anyway. |
PubsubPaceRecheckSeconds |
1 | How often a held publish looks again without a report (leases and stalls run out without one). |
Set them from the deployment's streamTTL when it is not one minute.
Request/Response Examples
Using gRPC with C
using Grpc.Net.Client;
using Virtufin.Api.Protos;
// Create channel
var channel = GrpcChannel.ForAddress("http://localhost:5002");
var client = new Gateway.GatewayClient(channel);
// List services
var services = client.ListServices(new ListServicesRequest());
Console.WriteLine($"Services: {string.Join(", ", services.Services)}");
// Invoke a method
var invokeResponse = client.Invoke(new InvokeRequest
{
Service = "workmanager",
Method = "ListWorkers",
RequestData = "{}"
});
Console.WriteLine($"Success: {invokeResponse.Success}");
Console.WriteLine($"Response: {invokeResponse.ResponseData}");
Using gRPC with Python
import grpc
import gateway_pb2
import gateway_pb2_grpc
channel = grpc.insecure_channel('localhost:5002')
stub = gateway_pb2_grpc.GatewayStub(channel)
# List services
response = stub.ListServices(gateway_pb2.ListServicesRequest())
print(f"Services: {response.services}")
# Invoke a method
invoke_response = stub.Invoke(gateway_pb2.InvokeRequest(
service="workmanager",
method="ListWorkers",
request_data="{}"
))
print(f"Success: {invoke_response.success}")
Health check
curl http://localhost:5001/health
Dynamic Dispatch
The Gateway's InvokeJson RPC accepts a service name, method name, and
JSON-serialized request, and returns a JSON-serialized response. This
allows callers to invoke any backend RPC without importing the backend's
proto definition or generated stub. The Gateway uses gRPC reflection on
the target backend service to discover the method's request/response
types, marshals the JSON into the appropriate Protobuf message, invokes
the backend's gRPC method, and marshals the response back to JSON.
gRPC InvokeJson
# WorkManager.ListWorkers — no request fields
grpcurl -plaintext -import-path src/Virtufin.Api.Protos/proto -proto gateway.proto \
-d '{"service": "workmanager", "method": "ListWorkers", "request_data": "{}"}' \
localhost:5002 virtufin.Gateway/InvokeJson
More calls, the same way:
# WorkManager.CreateWorker -- CodeSource oneof (url | content), mime_type, topic
grpcurl -plaintext -import-path src/Virtufin.Api.Protos/proto -proto gateway.proto \
-d '{"service": "workmanager", "method": "CreateWorker", "request_data": "{\"code_source\":{\"url\":\"https://example.com/worker.py\"},\"mime_type\":\"text/x-python\",\"topic\":\"worker-commands\"}"}' \
localhost:5002 virtufin.Gateway/InvokeJson
# WorkManager.InvokeWorkerCommand -- a command to a running worker, answered with its outputs
# (here the status of a WebSocketFeed worker; payload is bytes, so base64 in JSON)
grpcurl -plaintext -import-path src/Virtufin.Api.Protos/proto -proto gateway.proto \
-d '{"service": "workmanager", "method": "InvokeWorkerCommand", "request_data": "{\"id\":\"<feed worker id>\",\"command\":\"status\"}"}' \
localhost:5002 virtufin.Gateway/InvokeJson
Response shape:
{
"success": true,
"status": "OK",
"message": "",
"response_data": "{\"workers\":[{\"id\":\"abc123\",\"status\":\"RUNNING\",\"language\":\"python\"}]}"
}
The response_data field is a JSON-encoded string of the backend's typed
proto response. Parse it client-side to get the typed fields.
See also: The per-language client docs (python-client.md,
csharp-client.md, typescript-client.md) for higher-level wrappers
around InvokeJson. The
proto-to-client-mapping spec
§Layer 4 documents the full call chain including gRPC reflection lookup
and JSON ↔ Protobuf marshaling.