Skip to content

EventStore

Stores the payload of every CloudEvent it receives that is not a command in QuestDB, as the rows a declarative mapping in its config describes. The worker holds no venue and no contract: what a candle, a fill or a snapshot becomes is data (platform-workers#16).

flowchart LR
    T(["topics it is created with"]) --> E["EventStore"]
    E -->|"command? skip"| X(( ))
    E -->|"first matching rule, else the fallback table"| M["rows"]
    M -->|"/exec: CREATE TABLE ... DEDUP, once per table"| Q[("QuestDB")]
    M -->|"/write: line protocol, before the input completes"| Q
    E -.->|"mapping error, refusal, unreachable: input fails"| D(["dlq.<topic>"])
Property Value
Project Virtufin.Worker.EventStore
Worker type eventstore
Engine application/x-dotnet-dll
Inputs the topics it is created with, explicitly (no wildcard)
Outputs none; the status command answers on com.virtufin.eventstore.response; the counts go out on wrk.eventstore.metrics
Database QuestDB over HTTP: /exec for each table's DDL, /write (line protocol) for the rows

Config

Key Default Meaning
mappings none The rules, as JSON: {"mappings": [...]} or the bare list. See below.
fallbacktable cloudevents The table for events no rule takes. none: such an event fails instead (and is dead-lettered).
questdburl http://questdb.questdb.svc.cluster.local:9000/ QuestDB's HTTP endpoint.
retryseconds 20 How long one input retries while QuestDB is unreachable, within the call's 30 s budget.
metricsseconds 5 Seconds between pushes of the counts on wrk.eventstore.metrics (only when they changed); 0 turns them off.

The mapping

A list of rules; the first whose match holds makes the event's rows.

{"mappings": [{
  "match": {"type": "com.virtufin.exchange.binance.candle.closed"},
  "table": "candle_{ext:exchange}",
  "timestamp": "$.window_end",
  "symbols": {"symbol": "$.pair", "world": "{ext:marketworld}"},
  "columns": {"open": {"value": "$.open.cardinal", "scale": "$.open.precision"},
              "close": {"value": "$.close.cardinal", "scale": "$.close.precision"},
              "volume": {"value": "$.volume.cardinal", "scale": "$.volume.precision"}}
}]}
Key Meaning
match Required, at least one of: type (equal), typeprefix, typesuffix, subjectprefix, extensions ({"name": "value"}, all equal). Every condition given must hold.
table The table, a template: candle_{ext:exchange}. Lowercase [a-z][a-z0-9_]* once rendered.
timestamp QuestDB's designated timestamp. Default: the event's time.
explode A payload path with [*] or a slice ([:20], [2:5]): one row per element, read with @ paths. Or a list of them, concatenated; each entry may be {"path": ..., "set": {"field": value}, "index": "field"}, which adds constant fields and the element's position in its path to each element.
symbols Columns of QuestDB's indexed SYMBOL type, {"column": "source"}.
columns The other columns, {"column": "source:type"}.
keys Optional: the columns that identify a row, e.g. ["venue", "world", "symbol", "interval"] for a candle. The table deduplicates on the timestamp and these, so the same row published again (another instance, a backfill) stays one row.

Sources: - $.a.b[0]: the payload. @.x or @[1]: the current explode element. - {ext:NAME}: an extension attribute. {attr:NAME}: id, type, source, subject, time, datacontenttype or dataschema. {config:KEY}: the worker's config. Other text is literal; placeholders and text combine. - {"value": "<source>", "type": "<type>", "scale": "<source>"}: the same, with the value divided by 10^n, n read from the event, exactly: for fixed-point numbers sent as integers (a price cardinal and its precision). A scaled value is a double, or its exact text with string. - :type at the end: double, long, boolean, string, timestamp (symbol under symbols). Without one, a number is a double, a boolean a boolean, anything else a string. A timestamp is RFC 3339, or milliseconds since the epoch.

A value that is missing leaves its column out of the row. A value of the wrong type, a missing timestamp, or a table template without a value fails the input.

Every row also has ce_id (the event id) and, when exploded, ce_row (the element index). Each table is created on its first row with DEDUP UPSERT KEYS(ts, ce_id[, ce_row]), so an input delivered again (inputs are at least once) overwrites its own row; with keys, with DEDUP UPSERT KEYS(ts, <keys>) instead. A table that already exists is left as it is.

The fallback table keeps an event no rule takes: type, source, datacontenttype (symbols), subject, extensions (JSON), payload (its JSON, or its text), ce_id and the event's time.

Never stored: the worker's own config and secrets. The Runtime stamps both onto every input as extensions; they are left out of extensions, and a mapping that reads a secret with {ext:NAME} fails the start.

Binary payloads: from the schema registry

A binary payload is read into JSON with the schema its producer registered with the gateway (Gateway.GetPayloadSchema by content type; producers register when they start). The worker links no producer's types and has no schema config: the schema is data. A content type's schema is fetched once; one without a registered schema is asked for again at most every 30 seconds.

  • Protobuf is read as standard protobuf JSON: proto field names, default values written, 64-bit integers as strings, enums by name, timestamps as RFC 3339 text. An exact decimal (virtufin.core.DecimalAmount) is {"cardinal": "250010", "precision": 2}: map it with scale (below), which keeps it exact.
  • FlatBuffers is read into its tables: the root table's fields by their schema names, integers as integers, structs and tables as objects, vectors and fixed arrays as arrays, enums as numbers. A scalar the buffer leaves out (FlatBuffers does not write defaults) gets its default; an absent string or table is left out, an absent vector is []; union values are left out. A buffer with another file identifier than the schema's fails the input.

A binary payload whose content type has no registered schema goes to the fallback table as base64. A registered schema that does not build, or a payload that does not read with it, fails the input.

Examples

Candles (candle.closed, protobuf virtufin.marketdata.Candle, content type application/x-virtufin-candle+protobuf) of every venue in one table, keyed on their identity (a candle published again, by another instance or a backfill, stays one row). Each amount is its cardinal divided by 10^precision, exactly, stored as a double; add "type": "string" to a column to store its exact text ("60983.93") instead:

{"mappings": [{
  "match": {"typeprefix": "com.virtufin.exchange.", "typesuffix": ".candle.closed"},
  "table": "candle",
  "timestamp": "$.window_end",
  "keys": ["venue", "world", "universe", "symbol", "interval"],
  "symbols": {"venue": "{ext:exchange}", "world": "{ext:marketworld}", "universe": "{ext:marketuniverse}",
              "symbol": "$.pair", "interval": "$.interval"},
  "columns": {"open": {"value": "$.open.cardinal", "scale": "$.open.precision"},
              "high": {"value": "$.high.cardinal", "scale": "$.high.precision"},
              "low": {"value": "$.low.cardinal", "scale": "$.low.precision"},
              "close": {"value": "$.close.cardinal", "scale": "$.close.precision"},
              "volume": {"value": "$.volume.cardinal", "scale": "$.volume.precision"},
              "window_start": "$.window_start:timestamp"}
}]}

Trades (trade.executed, protobuf virtufin.marketdata.Trade, content type application/x-virtufin-trade+protobuf), one row per trade, price and quantity scaled exactly into double columns ("type": "string" keeps their exact text):

{"mappings": [{
  "match": {"typeprefix": "com.virtufin.exchange.", "typesuffix": ".trade.executed"},
  "table": "trade",
  "timestamp": "$.trade_time",
  "keys": ["venue", "world", "symbol", "trade_id"],
  "symbols": {"venue": "{ext:exchange}", "world": "{ext:marketworld}", "symbol": "{subject}", "side": "$.side"},
  "columns": {"trade_id": "$.trade_id",
              "price": {"value": "$.price.cardinal", "scale": "$.price.precision"},
              "quantity": {"value": "$.quantity.cardinal", "scale": "$.quantity.precision"}}
}]}

Order books (orderbook.changed, a FlatBuffers image: market-data-devkit's schemas/orderbook.fbs, content type application/x-virtufin-orderbook+flatbuffers), the top 20 levels per side, one row each. Its JSON is {pair, last_update_id, event_time_unix_ns, price_precision, size_precision, bids: [{price, size}], asks: [...]}, prices and sizes as integer cardinals at their precision:

{"mappings": [{
  "match": {"typeprefix": "com.virtufin.exchange.", "typesuffix": ".orderbook.changed"},
  "table": "orderbook",
  "explode": [{"path": "$.bids[:20]", "set": {"side": "bid"}, "index": "level"},
              {"path": "$.asks[:20]", "set": {"side": "ask"}, "index": "level"}],
  "keys": ["venue", "world", "universe", "symbol", "side", "level"],
  "symbols": {"venue": "{ext:exchange}", "world": "{ext:marketworld}", "universe": "{ext:marketuniverse}",
              "symbol": "$.pair", "side": "@.side"},
  "columns": {"level": "@.level:long",
              "price": {"value": "@.price", "scale": "$.price_precision"},
              "size": {"value": "@.size", "scale": "$.size_precision"},
              "last_update_id": "$.last_update_id:long"}
}]}

A book changes many times a second; each change is 40 rows here.

What is not stored

Commands: an event with a command extension, com.virtufin.workmanager.worker.command, or any com.virtufin.<type>.command. A worker cannot see the topic an input came on, so a command is told by its type and extension, not its topic.

Failures

An input completes only once its rows are written. Otherwise it fails, and the Runtime dead-letters it once, unchanged, to dlq.<topic>, from where it can be replayed: - QuestDB unreachable: the input retries for retryseconds with backoff, the status turns degraded (and ok on the next write), then it fails; - QuestDB refuses the rows (HTTP 4xx, a type conflict): it fails at once; - the event does not fit its rule: it fails at once, the reason names the rule.

The status command (InvokeWorkerCommand) answers the counts and the mapping in use, as its messages (openspec worker-management, Command Payloads; proto/virtufin/eventstore/commands.proto): the input StatusCommand is empty (send no data, application/x-virtufin-eventstore-status-command+protobuf), the answer StatusAnswer (application/x-virtufin-eventstore-status-answer+protobuf) carries events, rows, failed, rules, fallback_table and last_error. The worker registers both schemas when it starts, so the TUI and the app read the answer from the registry. The counts are also pushed on wrk.eventstore.metrics (ce-type com.virtufin.eventstore.metrics, subject worker/<id>, data {workerid, counters: {events, rows, failed}, at}), every metricsseconds (default 5) when they changed, so a dashboard follows them instead of polling.

Build and deploy: Deploy EventStore.