Add a worker
How to add a platform worker to this repo. A worker here is one top-level directory with its own versions.env, CHANGELOG.md, README.md, config/config.json and tests/, plus a CI workflow and an entry in the worker registry. Domain workers (market data, indicators, strategies, execution) belong in their domain's workers repo, not here.
The devkits are documented on their own sites; this guide covers only what is particular to this repo:
- C#: Worker DevKit, in particular Base classes, Behavior workers and Packaging a worker
- Python and the engines: WorkManager, in particular Engine System
- Names (worker type, topics, ce-types): naming reference
Name it
A worker is named after its behavior, never its technology or the word "worker": directory Echo/, package Virtufin.Worker.Echo (or virtufin-worker-echo), worker type echo, class EchoWorker. The worker type gives every name through the naming library: source urn:com.virtufin:worker:echo, responses com.virtufin.echo.response on wrk.echo.response, errors com.virtufin.echo.error on wrk.echo.error, command topic wrk.echo.command.{worker_id}. A caller's replytopic changes the topic, never the type.
A C# worker
Echo/
├── Directory.Packages.props # central versions for the Virtufin.* and test packages
├── versions.env # LIBRARY_VERSION, the published package version
├── config/config.json # topics (read by virtufin-worker create)
├── src/Virtufin.Worker.Echo.Managed/
│ ├── Virtufin.Worker.Echo.Managed.csproj
│ └── EchoWorker.cs
└── tests/Virtufin.Worker.Echo.Tests/
Derive from WorkerBase<TInput, TOutput>, or from BehaviorWorkerBase when the logic is a Virtufin.Core behavior. The base decodes the payload with its codec, builds the response envelope and turns an exception into an error response:
using System.Text.Json.Nodes;
using CloudNative.CloudEvents;
using Virtufin.Worker.DevKit;
using Virtufin.Worker.Host;
namespace Virtufin.Worker.Echo;
public sealed class EchoWorker() : WorkerBase<JsonNode, JsonObject>("echo", new StrictJsonCodec())
{
protected override Task<JsonObject?> ProcessAsync(CloudEvent input, JsonNode payload, IWorkerContext context)
=> Task.FromResult<JsonObject?>(new JsonObject { ["echo"] = payload.DeepClone() });
}
The engine creates the assembly's one public IWorker type through its public parameterless constructor. Keep per-instance configuration on the CloudEvent (the Runtime stamps CreateWorkerRequest.config onto every input as extension attributes), never in environment variables, which every worker in the Runtime process shares.
A worker that calls the platform (state, pubsub, triggers) uses context.Api, the IVirtufinApi of the IWorkerContext every call carries: the Runtime's gateway on the cluster, an in-memory API under a LocalWorkManager or BehaviorTestHost. See The worker context.
The csproj
Package the worker with the DevKit's shared VirtufinPackageWorker target, as HttpGet does. dotnet publish then writes a nupkg with lib/net11.0/<AssemblyName>.dll and a nuspec that lists the worker's PackageReferences; the Runtime resolves them when it loads the worker, at the latest Virtufin.* versions:
<PropertyGroup>
<OutputType>Library</OutputType>
<TargetFramework>net11.0</TargetFramework>
<AssemblyName>EchoWorker</AssemblyName>
<PackageId>Virtufin.Worker.Echo</PackageId>
<PackageVersion>0.0.0-local</PackageVersion> <!-- virtufin-worker build passes LIBRARY_VERSION -->
<Authors>Virtufin</Authors>
<Description>Echo worker: replies with its input payload.</Description>
<VirtufinPackageWorker>true</VirtufinPackageWorker>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Virtufin.Worker.Host" />
<PackageReference Include="Virtufin.Worker.DevKit" />
</ItemGroup>
A plain dotnet publish writes the nupkg to bin/worker-nupkg/; virtufin-worker build sets VirtufinWorkerNupkgDir to build/<Worker>/ itself. The other properties are in Packaging a worker.
A native build (optional)
Add a native build only with a reason to (see Engines). Follow HttpGet/src/Virtufin.Worker.HttpGet.Native/: a second project with PublishAot, the same AssemblyName, RuntimeIdentifiers linux-x64;linux-arm64, the shared source files compiled in by <Compile Include="..\…Managed\….cs" Link="…" />, and a worker class that adds the two C exports:
public sealed class EchoWorkerNative() : WorkerBase<JsonNode, JsonObject>("echo", new StrictJsonCodec())
{
protected override Task<JsonObject?> ProcessAsync(CloudEvent input, JsonNode payload, IWorkerContext context)
=> EchoLogic.ProcessAsync(input, payload);
[UnmanagedCallersOnly(EntryPoint = "Process")]
public static unsafe int Process(IntPtr host, IntPtr inBuf, int inLen, IntPtr outBuf, IntPtr outLen)
=> AotNative<EchoWorkerNative>.ProcessStatic(host, inBuf, inLen, (IntPtr*)outBuf, (int*)outLen);
[UnmanagedCallersOnly(EntryPoint = "FreeResult")]
public static void FreeResult(IntPtr result)
=> AotNative<EchoWorkerNative>.FreeResultStatic(result);
}
AotNative<T> (Virtufin.Worker.Host) handles the ABI v2 wire protocol. virtufin-worker build --native then produces one nupkg with both layouts; set ships_native: true in the CI workflow.
Tests
Test through the worker's public ProcessAsync(CloudEvent, IWorkerContext): build a CloudEvent, call the worker with a context (new WorkerContext("test", new LocalVirtufinApi()), or BehaviorTestHost), assert on the returned CloudEvents. HttpGet's tests take an injected HttpClient through a public constructor.
A Python worker
Echo/
├── pyproject.toml # [project] name and dependencies only, no build system
├── versions.env
├── config/config.json # script_path (the entry file) and topics
├── src/echo.py # becomes worker.py in the wheel
└── tests/test_echo.py
Subclass a base from virtufin-worker-devkit and expose the module-level Process the engine calls:
| Base | Use when |
|---|---|
WorkerBase |
you handle the CloudEvent yourself (handle(event_data)) |
CommandWorker |
the data is JSON with a command field (handle_command(input, command, data)) |
ApiWorker / ApiCommandWorker |
as above, with a gateway client in self.api |
from virtufin.worker_devkit import WorkerBase
class EchoWorker(WorkerBase):
def handle(self, event_data):
return self.response(event_data, "echo", True, message=str(event_data.get("data")))
_worker = EchoWorker(worker_type="echo")
def Process(cloud_event):
return _worker.process(cloud_event)
virtufin-worker build builds a wheel holding only worker.py and the Requires-Dist lines from pyproject.toml; the engine installs the dependencies when it loads the worker. The MIME type is application/x-python.
Inputs can arrive twice
Make the worker safe for an input delivered again: Inputs can arrive twice says what the devkit does for you and what a custom worker must do.
Counters: push, don't wait to be asked
A worker whose counts someone watches (events, rows, frames, failures) pushes them
with worker-devkit's
WorkerMetrics: started in
StartAsync, disposed in StopAsync. It publishes the counts on wrk.<type>.metrics
every metricsseconds (default 5, 0 turns it off), and only when they changed. A
dashboard subscribes to that topic instead of asking every worker its status over
and over. EventStore and WebSocketFeed do this. A status command can still answer
the same counts for a one-off look. List metricsseconds in the worker's
registry entry's config_schema.
Wire it into the repo
- CI. Add
.github/workflows/<name>-nuget.yaml(copyhttpget-nuget.yaml, which calls common'sworker-nuget-common.yaml) or<name>-package.yaml(copyhello-package.yaml). A push tomasterthat changes the worker's directory tests it and publishesLIBRARY_VERSION; bump it, with aCHANGELOG.mdentry, in the same commit as every code change. Python tests also run inpython-workers-test.yaml. - Registry. Once its first version is published, add an entry to the worker registry,
workers.tomlin worker-registry, with itssource_url,mime_type, the publishedversions,authentication = "virtufin"and the JSON Schema of itsconfig, and release the registry. Every later release adds its version there (Add a worker version). Optionaltopicspre-fill the clients' New Worker forms; a topic per pair is written once as a naming template, e.g.act.exchange.binance.trade.update.{pair}withtopic_params = { pair = "currencypairs" }(the fields). - Docs. Give the worker a reference page
docs/v1/reference/<name>.md(what it does, configuration, topics, response) and a how-todocs/v1/howtos/deploy-<name>.md(build and deploy), add them to the Reference > Workers and How-to guides sections ofdocs/mkdocs_v1.yml, to the worker tables of Home and Overview, and to the table inAGENTS.md. Link the page from the worker's README.
Deploy
Create the worker through the API gateway. The org feeds are private, so a package URL on them needs the named credential virtufin, which the WorkManager resolves server-side:
from virtufin.api import ApiClient
async with ApiClient("localhost", 5002) as api:
created = await api.gateway.workmanager.CreateWorker({
"code_source": {"url": package_url, "credential": {"named": "virtufin"}},
"mime_type": "application/x-dotnet-dll",
"topics": ["wrk.echo.command.{worker_id}"],
})
await api.gateway.workmanager.StartWorker({"id": created["id"]})
CreateWorker returns before the code is loaded. Follow the worker on sys.workmanager.worker.lifecycle: registered, loaded, starting, online; a load-failed or failed event carries error_type and error_message. A message the worker fails on goes to dlq.<input topic>. See Worker Lifecycle.
See also
- Engines: managed, native and Python for the workers here
- Packaging Modes: managed, native and both in one nupkg
- Build Script: what
virtufin-worker builddoes