Skip to content

Behavior workers

Virtufin.Behavior.DevKit turns any Virtufin.Core behavior (IProcess, IAsyncProcess, IDecide, IIndicator, IExecutor, IAlgebra) into a worker by binding it to CloudEvents:

public sealed class MyWorker() : BehaviorWorkerBase(
    "my",                                   // worker type: names the source and errors
    myProcess.FromCloudEvents(Decode)       // decode, or Decoded<T>.Skip
             .ToCloudEvents(Encode)         // zero or more Outgoing per step
             .RequireConfig("threshold"));  // checked before stepping

In BehaviorWorkerBase, one input may produce zero, one or several outputs (IWorker.ProcessAsync returns them in order), each with its own id (derived from the input, see Inputs can arrive twice), type, topic and subject, and the envelope (StampEnvelope: by default the generic one, carried correlationid and inherited eventtime; a domain base stamps its domain attributes, see Envelope). The domain devkits are thin layers over it: StrategyWorkerBase (strategy-devkit), ExecutorWorkerBase (execution-devkit), IndicatorWorkerBase (indicator-devkit) and MarketDataWorkerBase (market-data-devkit).

Composing processes

BehaviorExtensions holds the generic combinators; every result is a plain value, testable without WorkManager or CloudEvents:

Combinator Result
process.AsAsync() lifts an IProcess to IAsyncProcess
algebra.AsProcess() an IAlgebra as a process whose output is the folded state
process.PerKey<…, TKey>() one independent copy of the process per key (e.g. per symbol)

The domain adapters live with their domains: decide.WithPortfolio(algebra) in Strategy.DevKit, executor.AsAsyncProcess() in Execution.DevKit, and indicator.AsProcess() in Indicator.DevKit.

Binary payloads

A binding's decoder normally receives the event's JSON payload, decoded by the strict codec (StrictJsonCodec), where a payload that is not JSON is an error. For a payload that is not JSON (an order book image, a FlatBuffers sample), construct the worker with LenientJsonCodec (BehaviorWorkerBase(workerType, new LenientJsonCodec())): such an event decodes to an empty object and the decoder reads CloudEvent.Data (bytes) from the event it is given.

Names

NameFragments.For(typeof(MyWorker)) composes the worker's naming registry: virtufin.core, every fragment embedded in the worker's assembly, and the platform fragments this package embeds (copies of virtufin.service.api and virtufin.service.workmanager). It owns no domain names: a worker lists the assemblies of the devkits whose fragments it uses, e.g. NameFragments.For(typeof(MyWorker), typeof(MarketNames).Assembly) (domain-devkit's DomainNames.For adds virtufin.worlds). Names are never built by hand (naming library).

Inputs can arrive twice

Since WorkManager 0.38.0 a worker's input topics survive a move: the Runtime saves a cursor per worker and topic at most every 250 ms and catches the worker up from it on its next pod. After a hard crash the events the worker finished in that last window are delivered again: at least once, not exactly once (see Inputs across a move). Worker state is in memory, so the crashed worker itself starts empty and folds each event once; the duplicates land on its consumers, which keep running: the crashed worker processes its replayed inputs again and publishes what it published before.

BehaviorWorkerBase (and every domain base on it) handles both sides:

  • Derived ids. An output's id is a name-based UUID of the worker id, the input's source and id, the output's type, topic and subject, and its position among the outputs with those names (DerivedEventId). Processing the same input again republishes the same ids; two workers on one input never share one.
  • Seen inputs. An input whose source and id the instance already took (SeenEvents: the last 100 000 within 10 minutes, in memory) is dropped before it is decoded: no step, no output, no error.

So a fold (an indicator window, a position delta, an executor's fill) counts a redelivered event once without any code of its own. What the bases cannot do is make a side effect outside the event stream idempotent: an order sent to an exchange, a row written to a database. Give such a call a key derived from the input (the order id as Binance's newClientOrderId, as LiveExecutor does), look it up before acting again, and treat "already exists" as success.

A WorkerCore worker of your own gets neither: call SeenEvents.TryAdd(input) first and return nothing for a duplicate, and set each output's id with DerivedEventId.For(Context.WorkerId, input, type, topic, subject, n). A base on BehaviorWorkerBase that needs an id of its own to survive a redelivery calls DerivedId(input, type, topic, subject, n) (0.42.0): strategy-devkit derives the order ids from the decision's trigger that way.

Python (virtufin-worker-devkit 0.42.0): WorkerBase.process does both, with the same algorithm (virtufin.worker_devkit.redelivery: derived_event_id, SeenEvents; C# and Python are tested against the same vectors, conformance/redelivery.v1.json). The worker id comes from the activation's Start(ctx), so a module exports the base's hook next to Process:

_worker = MyWorker()
Process = _worker.process
Start = _worker.Start   # derived ids scoped to the worker id

Without Start the ids are scoped to the instance: never shared, but a fresh activation derives different ones. self.derived_id(input, type, topic, subject, n) derives an id of the worker's own (an order id, say).

Create the worker with input replay off instead (input_replay = INPUT_REPLAY_OFF, a typed CreateWorker field read by the WorkManager, never a config key; see platform settings) when it resynchronizes itself after a gap: the order-book workers number their updates and rebuild from a snapshot, so replaying stale deltas only delays them. With input replay off the inputs start at the tail after a move: nothing twice, but what was published during the move is lost.

To test it, send the same event twice: BehaviorTestHost.SendAsync(CloudEvent) takes an event as given (its id and source kept), ideally decoded from the wire (CloudEventProtoCodec.Decode(CloudEventProtoCodec.Encode(ce))), and the second call must return nothing and leave the state as the first left it.

Testing

BehaviorTestHost drives a worker in-process the way a host does: the first SendAsync starts the worker with a context (its config and secrets as a created worker's; new BehaviorTestHost(worker, LocalRunOptions) also takes platform variables by reference), SendAsync returns every output of one input (an event built from a type and data, or a CloudEvent as given), Published collects what the worker publishes through its context, Payload decodes an output's JSON data, and StopAsync (or DisposeAsync) stops the worker. A binding sees the lifecycle too (ICloudEventBinding.StartAsync/StopAsync, default no-ops); its context-aware decoders read the context it was started with.

To run several workers together, wired by topics and under the Runtime's per-event rules, use the local WorkManager. The worker workflow shows where each tool fits.