Build a Node Type
This walkthrough declares a new Node Type, writes its Configuration Schema, places it where the
engine finds it, validates a config against it, runs the Conformance Suite on it and reads the
failures. It is written for an integrator, or an integrator's coding agent, and needs no engine
internals: everything is imported from engine.public, which the
Python API reference describes name by name.
The Node Type is a Flow Meter, shaped like the plc-generic-device Node Type in
node-types/: a device that reports a value, whose config carries exactly one of two source
sections, and whose raw records are mapped to one canonical event by a list of rules.
Every code block on this page is run. The test suite runs the blocks in order, in an empty directory, from a clean clone of the repository, and compares what they print with what is shown here, so what you read is what you get.
Before you start. Work in an empty scratch directory, not in the repository: step 2 writes a
node-types/ directory, and in a real project that directory is the repository's own. Step 6 needs a
Postgres database, because the Conformance Suite writes to the Activity Log and the trigger queue.
Set the environment variables listed in the repository's .env.example (the POSTGRES_* ones and
OLLAMA_BASE_URL) in your shell, or put them in a .env file in the directory you run from. Use a
scratch database: the Activity Log is append-only, so the entries the suite writes stay, and the
queue table it creates, trigger_queue_walkthrough, can be dropped with DROP TABLE.
1. What a Node Type is
A Node Type is a declaration, not a class to extend. It is one JSON file, node_type.json, with
three parts:
- Identity: its name, its version (
MAJOR.MINOR.PATCH) and the Node Types it works alongside. - Configuration Schema: a JSON Schema that every config file for the Node Type must satisfy.
- Event types: the events it produces, each with a JSON Schema for its fields.
Its behaviour comes from configuration plus the registries you fill in (here, a transformation
registry), so there is nothing to inherit from. The directory node-types/ is the registry of
Node Types: placing a directory there is what makes a Node Type available.
2. Declare it
The declaration below says a Flow Meter is configured with exactly one of a polling section (an
endpoint and a node to read) or an mqtt section (a host and a topic), and that it produces one
event, ReadingChanged, whose value is a number and whose source says which transport it
arrived over. state_transition_rules in the polling section is the mapping the Node uses to turn
a raw record into that event.
>>> import json
>>> from pathlib import Path
>>> declaration = {
... "identity": {"name": "Flow Meter", "version": "0.1.0", "relevant_peer_node_types": []},
... "config_schema": {
... "type": "object",
... "x-exactly-one-of": ["polling", "mqtt"],
... "properties": {
... "polling": {
... "type": "object",
... "required": ["endpoint", "node_id"],
... "properties": {
... "endpoint": {"type": "string"},
... "node_id": {"type": "string"},
... "state_transition_rules": {
... "type": "array",
... "items": {
... "type": "object",
... "properties": {
... "when": {"type": "object"},
... "then": {
... "type": "object",
... "additionalProperties": {"type": "string"},
... },
... "literals": {"type": "object"},
... },
... "additionalProperties": False,
... },
... },
... },
... "additionalProperties": False,
... },
... "mqtt": {
... "type": "object",
... "required": ["host", "topic"],
... "properties": {"host": {"type": "string"}, "topic": {"type": "string"}},
... "additionalProperties": False,
... },
... },
... "additionalProperties": False,
... },
... "event_types": [
... {
... "name": "ReadingChanged",
... "description": "The metered value changed.",
... "fields": {
... "type": "object",
... "required": ["value", "source"],
... "properties": {
... "value": {"type": "number"},
... "source": {"type": "string", "enum": ["polling", "mqtt"]},
... },
... },
... }
... ],
... }
>>> directory = Path("node-types/flow-meter")
>>> directory.mkdir(parents=True, exist_ok=True)
>>> _ = (directory / "node_type.json").write_text(json.dumps(declaration, indent=2))
Help for each field
A field or section of the Configuration Schema can carry a standard JSON Schema description. It is the field's
help: the configuration page shows it behind a ? beside the field, and the configuration assistant reads it when
its model's context window holds the whole schema (a smaller window gets the schema without its descriptions). It
is an annotation, so it changes nothing a config means: a Node Type's version does not move when a description is
added or reworded, and the release check does not count it as a change of the schema. (A field that is itself called
description is a field, not an annotation, and a change to it counts.)
Say what the field is for, its unit and default, what it excludes or requires, and the failure a person would otherwise meet when they validate. Keep it to a few sentences, no more than about 400 characters; a longer explanation is a link to the documentation. Put it on the field or section itself: the page draws help for named fields and sections, so write the text of a list or a map on the list or the map, not on its items or entries.
A description is limited Markdown, and the page draws it without ever passing it through HTML:
| To write | Write |
|---|---|
| a paragraph | a blank line between paragraphs; a single newline stays in the same paragraph |
| a list | lines that begin with - and some text |
| code | the text in backticks |
| bold, italic | two asterisks around the text, one asterisk around the text (the text holds no asterisk, and the two do not nest) |
| a link | [text](https://address); the address must be absolute and https: |
Nothing else is syntax. A heading, an image, a table, an HTML tag, nested lists, underscore emphasis, a backslash
escape, and a link to any other kind of address (http:, a relative path, javascript:, data:) are shown as the
characters that were written, and so is a marker that never closes. The repository's tests check every shipped
description for a heading, an image, an HTML tag, a link that is not an absolute https: address, and more than
about 400 characters, so a mistake is found when it is written.
3. Load and check the declaration
load_node_type_definition reads the directory's node_type.json and checks it: the shape of the
declaration, and that the Configuration Schema and each event type's fields are valid JSON
Schemas. A mistake in any of them fails here, at declaration time, instead of breaking ingestion
the first time a real record arrives.
>>> from engine.public import load_node_type_definition
>>> node_type = load_node_type_definition(directory)
>>> node_type.identity.name, node_type.identity.version
('Flow Meter', '0.1.0')
>>> [event.name for event in node_type.event_types]
['ReadingChanged']
4. Write a config and validate it
A config file wraps the Node Type's own settings in an envelope that names the Node Type and its
version, so a stale file is caught. load_node_config loads a file and raises if it is invalid;
validate_candidate checks a file and returns a verdict instead, which is what to use when you
want to report a problem rather than stop.
>>> config = {
... "node_type": "Flow Meter",
... "node_type_version": "0.1.0",
... "config_version": 1,
... "config": {
... "polling": {
... "endpoint": "opc.tcp://meter.local:4840",
... "node_id": "ns=2;s=Flow",
... "state_transition_rules": [
... {
... "when": {"event": "data_change"},
... "then": {"value": "reading"},
... "literals": {"source": "polling"},
... }
... ],
... }
... },
... }
>>> _ = Path("config.json").write_text(json.dumps(config))
>>> from engine.public import load_node_config, validate_candidate
>>> loaded = load_node_config(node_type, Path("config.json"))
>>> sorted(loaded["config"])
['polling']
>>> verdict = validate_candidate(Path("config.json"), {"Flow Meter": node_type})
>>> verdict.valid
True
5. Map raw records to events
The rules in the config become a transform. A MappingRule says: when a record matches when,
build the event from then (event field from source field) and literals (constants).
build_rule_based_transform turns a list of rules into a function, and a
TransformationRegistry holds one per source type. A record that no rule matches, and a source
type nothing was registered for, pass through unchanged.
>>> from engine.public import MappingRule, TransformationRegistry, build_rule_based_transform
>>> rules = [MappingRule(**rule) for rule in loaded["config"]["polling"]["state_transition_rules"]]
>>> registry = TransformationRegistry()
>>> registry.register("flow-meter-polling", build_rule_based_transform(rules))
>>> registry.transform("flow-meter-polling", {"event": "data_change", "reading": 12.5})
{'value': 12.5, 'source': 'polling'}
>>> registry.transform("something-else", {"reading": 12.5})
{'reading': 12.5}
6. Run the Conformance Suite
The suite checks a Node Type against the properties every Node Type must have. You describe your
Node Type's ingest path to it with a ConformanceHarness: the declaration, the event type to check,
a registered and an unregistered source type, a record that should ingest cleanly and one that
should not, and an ingest function. The suite also needs an Activity Log and a trigger queue; give
the queue a table of its own.
>>> from engine.public import (
... ActivityLog, ConformanceHarness, TriggerQueue, run_conformance_suite,
... )
>>> harness = ConformanceHarness(
... node_type=node_type,
... event_type_name="ReadingChanged",
... registered_source_type="flow-meter-polling",
... unregistered_source_type="not-registered",
... valid_raw_record={"event": "data_change", "reading": 12.5},
... malformed_raw_record={"event": "data_change", "reading": "n/a"},
... ingest=lambda source_type, raw, schema: registry.transform(source_type, raw),
... )
>>> log = ActivityLog()
>>> log.ensure_schema()
>>> queue = TriggerQueue(table_name="trigger_queue_walkthrough")
>>> queue.ensure_schema()
>>> report = run_conformance_suite(harness, log, queue, "flow-meter-walkthrough")
>>> for result in report.results:
... print(result.name, result.passed)
schema_conformance True
idempotent_event_handling True
fail_safe_unreachable_retry_exhaustion True
fail_safe_malformed_data True
fail_safe_unregistered_source_type True
>>> report.passed
True
That is a Node Type that validates and passes the suite, built from engine.public alone.
7. When something is wrong
The errors below are the ones to expect when you make a mistake, and what each one says.
A declaration is missing a field
Remove the version and the declaration is rejected, naming the field:
>>> from engine.public import ConfigValidationError, validate_node_type_definition
>>> broken = json.loads((directory / "node_type.json").read_text())
>>> del broken["identity"]["version"]
>>> try:
... validate_node_type_definition(broken)
... except ConfigValidationError as error:
... print("\n".join(str(error).splitlines()[:3]))
invalid Node Type definition: 1 validation error for NodeTypeDefinition
identity.version
Field required [type=missing, input_value=...]
A config breaks the Configuration Schema
A polling section without its node_id fails. The message names the file and says what is
missing; for a field marked x-sensitive in the schema it never repeats the value.
>>> bad = {**config, "config": {"polling": {"endpoint": "opc.tcp://meter.local:4840"}}}
>>> _ = Path("bad-config.json").write_text(json.dumps(bad))
>>> try:
... load_node_config(node_type, Path("bad-config.json"))
... except ConfigValidationError as error:
... print(error)
bad-config.json: ... 'node_id' is a required property
validate_candidate reports the same problem as a verdict you can inspect:
>>> verdict = validate_candidate(Path("bad-config.json"), {"Flow Meter": node_type})
>>> verdict.valid, verdict.failure
(False, 'invalid')
A config with both sections, or neither, fails too, because the schema says exactly one:
>>> both = {**config, "config": {**config["config"], "mqtt": {"host": "h", "topic": "t"}}}
>>> _ = Path("both-config.json").write_text(json.dumps(both))
>>> try:
... load_node_config(node_type, Path("both-config.json"))
... except ConfigValidationError as error:
... print(error)
both-config.json: config must carry exactly one of polling, mqtt, found polling, mqtt
The Conformance Suite fails
The suite reports every check, so a failure is a line to read, not a crash. Here a transform "repairs" a bad reading by inventing a value, instead of letting it fail the event's schema:
>>> sloppy = TransformationRegistry()
>>> sloppy.register("flow-meter-polling", lambda record: {"value": 0.0, "source": "polling"})
>>> sloppy_harness = ConformanceHarness(
... node_type=node_type,
... event_type_name="ReadingChanged",
... registered_source_type="flow-meter-polling",
... unregistered_source_type="not-registered",
... valid_raw_record={"event": "data_change", "reading": 12.5},
... malformed_raw_record={"event": "data_change", "reading": "n/a"},
... ingest=lambda source_type, raw, schema: sloppy.transform(source_type, raw),
... )
>>> sloppy_report = run_conformance_suite(sloppy_harness, log, queue, "flow-meter-walkthrough")
>>> sloppy_report.passed
False
>>> for result in sloppy_report.results:
... if not result.passed:
... print(result.name)
... print(result.detail)
fail_safe_malformed_data
AssertionError: malformed data was silently fabricated into something schema-valid, instead of being flagged
Reading a failure
Each check has a name and a detail. The detail of a failed check is the error it hit.
| Check | What it verifies | A failure usually means |
|---|---|---|
schema_conformance |
The event type's fields is a valid JSON Schema, and event_type_name names a declared event type. |
A typo in event_type_name, or a fields schema that is not valid JSON Schema. |
idempotent_event_handling |
Delivering the same Trigger twice does not duplicate it. | A custom enqueue_with_stable_id that makes its own id instead of using the one it is given. |
fail_safe_unreachable_retry_exhaustion |
When the target is unreachable the ingest gives up after its retries instead of hanging or crashing. | A customised unresponsive_exceptions that is empty, or whose first entry is not an exception that means the target is unreachable. |
fail_safe_malformed_data |
A malformed record comes out failing the event schema, not repaired into something valid. | A transform that invents a default for missing or unparsable input. |
fail_safe_unregistered_source_type |
A source type nothing was registered for falls back to the generic transform, which passes the record through. | The generic transform was replaced, or ingest raises for an unknown source type. |
The suite never stops at the first failure: it runs every check and returns the whole report.
Release: v0.11.0