engine

package
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 8, 2026 License: Apache-2.0 Imports: 11 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package engine implements the Emberwire flow runtime: messages, the flow graph, the scheduler and message dispatch.

Property expressions are Node-RED compatible. The reference implementation is RED.util.normalisePropertyExpression in @node-red/util/lib/util.js; the grammar accepted here is deliberately the same one, because every flow written against Node-RED encodes property paths in it and we import those flows verbatim.

Index

Constants

View Source
const (
	TypeTab     = "tab"
	TypeSubflow = "subflow"
	TypeGroup   = "group"

	// SubflowInstancePrefix marks a node that is an instance of a subflow
	// template, e.g. "subflow:a1b2c3d4e5f60718".
	SubflowInstancePrefix = "subflow:"
)

Reserved type names that identify structural entries rather than runnable nodes.

View Source
const (
	PropPayload  = "payload"
	PropTopic    = "topic"
	PropMsgID    = "_msgid"
	PropError    = "error"
	PropParts    = "parts"
	PropComplete = "complete"
)

Conventional property names, spelled once so a typo cannot diverge.

View Source
const FlowFileIndent = "    "

FlowFileIndent is the indentation Node-RED writes with, from JSON.stringify(flows, null, 4). Matching it is what lets a file written here be byte-identical to one written there.

View Source
const SubflowScopeSeparator = ":"

SubflowScopeSeparator joins an instance id to a template node id to make the id of the copy.

It has to be a character Node-RED never puts in an id — ids there are hex from RED.util.generateId — so that a derived id can never collide with a real one. It also has to be stable across deploys, because context stores are keyed by node id and a fresh id every deploy would lose a subflow's node context.

Variables

View Source
var ErrInvalidPath = errors.New("invalid property expression")

ErrInvalidPath is the sentinel wrapping every parse failure, so callers can distinguish a malformed expression from a missing property.

Functions

func DeleteProperty

func DeleteProperty(root any, expr string) error

DeleteProperty removes expr from root. Deleting a missing property is not an error, matching JavaScript's delete operator.

func Denormalise

func Denormalise(v any) any

Denormalise recursively converts *[]any back into []any. Mutation uses pointer slices so that growth propagates; everything outside the engine — JSON encoding, the JS bridge, node implementations — expects plain slices.

func GenerateID

func GenerateID() string

GenerateID returns a 16-character hex identifier.

Node-RED's RED.util.generateId concatenates eight random bytes as hex, and node ids, message ids and group ids all share that shape. Matching it means an Emberwire-generated id is indistinguishable from a Node-RED one, so exported flows stay interchangeable. crypto/rand replaces Math.random; the extra cost is irrelevant next to the work of actually moving a message.

func GetProperty

func GetProperty(root any, expr string) (any, bool, error)

GetProperty reads expr from root. The boolean reports whether the property exists; a property present but set to nil returns (nil, true), which is a distinction switch nodes depend on.

func SetProperty

func SetProperty(root any, expr string, value any) error

SetProperty writes value at expr, creating intermediate containers as it goes. A missing container is created as a map, unless the next token is an index, in which case it is created as a slice — the same auto-vivification Node-RED performs, so that msg.payload.a[0].b = 1 works on an empty message.

Setting a slice element beyond the current length grows the slice and pads with nil, matching JavaScript's sparse-array assignment.

func SplitDerivedID

func SplitDerivedID(id string) (scopeID, templateNodeID string, ok bool)

SplitDerivedID reverses derivedID, reporting whether the id was one.

Types

type EnvScope

type EnvScope struct {
	// ID names the scope for diagnostics — an instance id or a tab id.
	ID   string
	Vars []EnvVar
}

EnvScope is one frame of environment-variable resolution: the variables declared by a subflow instance, a template, or a tab.

type EnvVar

type EnvVar struct {
	Name  string
	Type  string
	Value any
}

EnvVar is a tab- or subflow-scoped environment variable. Subflow properties are how an instance is parameterised — the same template behaves differently per instance because env resolution walks the instance path.

type Expansion

type Expansion struct {
	// Flows is the graph to execute. It is not the graph to save: see
	// Flows.Expanded.
	Flows *Flows

	// EnvChains maps a node id to the environment scopes enclosing it,
	// innermost first. This is Node-RED's _path resolution: a node inside two
	// nested instances sees the inner instance's variables, then the outer
	// one's, then the tab's, then the process environment.
	EnvChains map[string][]EnvScope

	// ParentScope maps a subflow instance's scope id to the scope containing it,
	// so an error nobody caught inside a subflow can be offered to the flow that
	// called it.
	ParentScope map[string]string

	// Instances lists the scope id of every expanded instance, in the order they
	// were expanded.
	Instances []string

	Warnings []string
}

Expansion is a flow set with every subflow instance replaced by a running copy of its template.

func ExpandSubflows

func ExpandSubflows(f *Flows) *Expansion

ExpandSubflows returns the graph to run.

The input is left completely untouched. When there are no subflow instances the returned Flows is the input itself, so the ordinary case costs nothing.

type Flows

type Flows struct {
	Tabs     map[string]*Tab
	Subflows map[string]*Subflow
	Groups   map[string]*Group
	Nodes    map[string]*Node

	// Order is the ids of every entry, in original file order.
	Order []string

	// Rev is the revision token used for optimistic concurrency on deploy, the
	// same mechanism as Node-RED's /flows rev field.
	Rev string

	// Warnings collects non-fatal problems found while parsing: dangling wires,
	// unknown group members, nodes on a missing tab. Node-RED tolerates all of
	// these and so do we, but silently repairing a flow is how you lose a
	// customer's work without telling them.
	Warnings []string

	// Expanded marks a graph produced by ExpandSubflows: the one the runtime
	// executes, holding a copy of every subflow template's nodes under a derived
	// id. It is not the graph to save, and render refuses to write it rather
	// than trusting nobody will ever try — saving one would replace a
	// customer's tidy subflow with its inlined guts, permanently.
	Expanded bool
	// contains filtered or unexported fields
}

Flows is a parsed flow file.

Order preserves the original array order so that a save does not reshuffle the document, and orig preserves each entry's original bytes so that key order inside an entry survives too. Together those give a byte-identical round-trip for anything the caller did not actually change — see Marshal.

func ParseFlows

func ParseFlows(data []byte) (*Flows, error)

ParseFlows parses a Node-RED v1 flow file.

It accepts both the bare array form written to disk and the wrapped {"rev":...,"flows":[...]} form returned by the admin API since Node-RED 0.15.

func (*Flows) ConfigNodes

func (f *Flows) ConfigNodes() []string

ConfigNodes returns the ids of every configuration node, in file order.

func (*Flows) Entry

func (f *Flows) Entry(id string) (map[string]any, bool)

Entry returns the raw object for any id, whatever kind of entry it is.

func (*Flows) GroupChain

func (f *Flows) GroupChain(nodeID string) []string

GroupChain returns the group ids containing a node, innermost first, ending at the outermost group. An ungrouped node yields nil.

func (*Flows) GroupDepth

func (f *Flows) GroupDepth(groupID string) int

GroupDepth returns how deeply a group is nested, counting from 0 at the outermost group. It is the basis of Catch and Status handler selection, where the handler closest to the erroring node wins.

A cycle in the parent chain — which a hand-edited flow can contain — is treated as terminating rather than looping forever.

func (*Flows) Marshal

func (f *Flows) Marshal() ([]byte, error)

Marshal renders the flow file the way Node-RED's flowFilePretty does: a v1 array indented with four spaces.

A file that was read and not modified comes back out byte for byte. Entries that were changed are re-encoded; everything else keeps the bytes it arrived with, so a deploy diffs only the nodes actually touched rather than reshuffling the whole file.

func (*Flows) MarshalJSON

func (f *Flows) MarshalJSON() ([]byte, error)

MarshalJSON writes the flow file back as a compact v1 array, in original entry order and with each entry's original key order.

func (*Flows) NodesInScope

func (f *Flows) NodesInScope(scopeID string) []string

NodesInScope returns the ids of every non-config node belonging to a tab or subflow, in file order.

func (*Flows) StripCredentials

func (f *Flows) StripCredentials() map[string]map[string]any

StripCredentials removes inline credential objects from every node and returns them keyed by node id.

Node-RED never writes credentials into the flow file: the editor posts them inline on deploy, the runtime splits them out, and they are stored separately and encrypted. Doing the same split here is what stops a broker password ending up in a git-committed flows.json.

func (*Flows) Touch

func (f *Flows) Touch(id string)

Touch marks an entry as modified, forcing it to be re-encoded on the next save even if it currently deep-equals what was read.

Needed only when a caller has mutated a nested value in place and wants the canonical form written back. Ordinary edits are detected automatically.

type Group

type Group struct {
	ID    string
	Z     string // containing tab
	G     string // parent group id, for nested groups
	Name  string
	Nodes []string // member node ids
	Raw   map[string]any
}

Group is a visual grouping of nodes. Groups are not execution containers, but they are not purely cosmetic either: Catch and Status resolution prefers the handler closest in the group hierarchy, so the nesting is load-bearing.

type ImmutableBytes

type ImmutableBytes []byte

ImmutableBytes is a byte slice whose contents are guaranteed never to change after construction. Clone shares it instead of copying, which is what keeps large binary payloads — a file read, an HTTP body, a captured frame — cheap to fan out across many wires.

The guarantee is the producer's to keep. Any node that might mutate its buffer must emit a plain []byte, which Clone copies defensively.

func (ImmutableBytes) Bytes

func (b ImmutableBytes) Bytes() []byte

Bytes returns the underlying slice. Callers must not write to it.

func (ImmutableBytes) MarshalJSON

func (b ImmutableBytes) MarshalJSON() ([]byte, error)

MarshalJSON encodes ImmutableBytes exactly as []byte does, so the wire format does not depend on which of the two a node chose to emit.

type Msg

type Msg struct {
	// Data holds every property, including payload, topic and _msgid.
	Data map[string]any
}

Msg is a message travelling along a wire.

Node-RED messages are arbitrary JavaScript objects with three conventional properties — payload, topic and _msgid — and any number of user-defined ones. Modelling that as a map rather than a struct is not laziness: flows address properties by runtime string expression (see property.go), and a struct cannot answer msg["whatever the user typed"].

A Msg is owned by exactly one node at a time. The scheduler clones on fan-out, so a node may mutate the message it was handed without coordinating with anybody. It must not retain a reference after returning.

func NewMsg

func NewMsg() *Msg

NewMsg returns an empty message carrying a freshly generated id.

func NewMsgWithPayload

func NewMsgWithPayload(payload any) *Msg

NewMsgWithPayload is the common case: a message carrying a single payload.

func WrapMsg

func WrapMsg(data map[string]any) *Msg

WrapMsg adopts an existing map as a message, generating an id if it has none. The map is taken by reference, not copied — used when decoding a message that arrived over the wire.

func (*Msg) Clone

func (m *Msg) Clone() *Msg

Clone returns a deep copy of the message.

This deliberately diverges from Node-RED. Node-RED hands the *first* recipient on a wire the original object and clones only for recipients after it, which makes the last-wired branch share mutable state with the sender. That is a documented memory optimisation and an undocumented source of aliasing bugs — two branches editing what looks like their own message and stepping on each other. Emberwire clones for every recipient. The cost is bounded by the ImmutableBytes fast path above, which covers the payloads big enough for the copy to matter.

func (*Msg) Delete

func (m *Msg) Delete(expr string) error

Delete removes a property expression. Removing an absent property is a no-op.

func (*Msg) EnsureID

func (m *Msg) EnsureID() string

EnsureID assigns a message id if one is missing, returning the id in use. Node-RED does this on receive so that every message is traceable in the debug sidebar even when a node fabricated it without one.

func (*Msg) Get

func (m *Msg) Get(expr string) (any, bool, error)

Get reads a property expression such as "payload.value" or "payload[0].id". The boolean distinguishes a property that is absent from one that is present and nil — switch nodes rely on telling those apart.

func (*Msg) ID

func (m *Msg) ID() string

ID returns the message id, or "" if it is absent or not a string.

func (*Msg) Payload

func (m *Msg) Payload() any

Payload returns msg.payload.

func (*Msg) Set

func (m *Msg) Set(expr string, v any) error

Set writes a property expression, creating intermediate containers as needed.

func (*Msg) SetPayload

func (m *Msg) SetPayload(v any)

SetPayload sets msg.payload.

func (*Msg) SetTopic

func (m *Msg) SetTopic(t string)

SetTopic sets msg.topic.

func (*Msg) Topic

func (m *Msg) Topic() string

Topic returns msg.topic as a string, or "" if absent or not a string.

type Node

type Node struct {
	ID    string
	Type  string
	Z     string // containing tab or subflow id; "" for global config nodes
	G     string // containing group id; "" if ungrouped
	Name  string
	Wires [][]string // outer index is the output port number
	X, Y  float64

	// Disabled mirrors the "d" property. A disabled node stays in the flow file
	// and in the editor but is never started and never receives a message.
	Disabled bool

	// IsConfig reports whether this is a configuration node — one referenced by
	// id from other nodes' properties rather than wired into the graph.
	IsConfig bool

	Raw map[string]any
}

Node is one entry from the flow file.

Raw holds the complete original object. The typed fields are a parsed view of it, not a replacement: a flow may carry properties belonging to node types we have never heard of, and dropping them would corrupt the user's flow the first time we saved it. Raw is the source of truth on write.

func (*Node) Outputs

func (n *Node) Outputs() int

Outputs returns the number of output ports the node is wired for.

func (*Node) Prop

func (n *Node) Prop(key string) (any, bool)

Prop reads a raw property. Node implementations use this to pull their own configuration out of the flow entry.

func (*Node) PropBool

func (n *Node) PropBool(key string, def bool) bool

PropBool reads a boolean property. Node-RED edit dialogs sometimes persist booleans as the strings "true"/"false", so both spellings are accepted.

func (*Node) PropFloat

func (n *Node) PropFloat(key string, def float64) float64

PropFloat reads a numeric property. JSON numbers decode as float64, but edit dialogs persist numbers as strings often enough that both are handled.

func (*Node) PropInt

func (n *Node) PropInt(key string, def int) int

PropInt reads an integer property.

func (*Node) PropString

func (n *Node) PropString(key, def string) string

PropString reads a string property, returning def when absent or not a string.

func (*Node) SubflowTemplateID

func (n *Node) SubflowTemplateID() (string, bool)

SubflowTemplateID returns the template id for a subflow instance node, and whether this node is one.

type ParseError

type ParseError struct {
	Index  int    // position in the flow array, or -1
	NodeID string // id of the offending entry, if known
	Msg    string
}

ParseError is a fatal problem that prevents a flow file being loaded at all.

func (*ParseError) Error

func (e *ParseError) Error() string

type Path

type Path []Token

Path is a parsed property expression.

func ParsePath

func ParsePath(expr string) (Path, error)

ParsePath parses a Node-RED property expression.

Accepted forms, all of which appear in real flows:

payload                 a bare key
payload.value           dotted keys
payload[0]              numeric index
payload["a key"]        quoted key, single or double quotes
payload[msg.index]      nested expression, resolved per message
a.b[2]["c d"].e         any combination of the above

A bare numeric first segment (e.g. "0.foo") is rejected: Node-RED treats a leading digit-run as a key only inside brackets, and silently accepting it here would change how an imported flow behaves.

func (Path) Static

func (p Path) Static() bool

Static reports whether the path contains no nested sub-expressions. A static path resolves identically for every message, so callers that cache lookups can only do so when this is true.

func (Path) String

func (p Path) String() string

String renders the whole path. Leading dots are elided so a.b[0] does not come back as a.b.[0].

type Subflow

type Subflow struct {
	ID       string
	Name     string
	Info     string
	Category string
	In       []SubflowPort
	Out      []SubflowPort
	Env      []EnvVar
	Raw      map[string]any
}

Subflow is a subflow template. Instances of it appear in the graph as nodes with type "subflow:<ID>".

type SubflowPort

type SubflowPort struct {
	X, Y  float64
	Wires []SubflowWire
}

SubflowPort is one input or output of a subflow template. Wires holds the internal nodes the port connects to.

type SubflowWire

type SubflowWire struct {
	ID   string
	Port int
}

SubflowWire is a connection between a subflow port and an internal node.

type Tab

type Tab struct {
	ID       string
	Label    string
	Disabled bool
	Info     string
	Env      []EnvVar
	Raw      map[string]any
}

Tab is a flow tab — one canvas in the editor, and one scope for flow context.

type Token

type Token struct {
	Key     string
	Index   int
	IsIndex bool
	Nested  Path
}

Token is one step of a property path.

Exactly one of the three forms is active:

Key    != ""     — an object key, e.g. the "b" in a.b
IsIndex          — an array index, e.g. the 0 in a[0]
Nested != nil    — a sub-expression, e.g. the msg.i in a[msg.i]

Nested is what makes a[msg.i] work. Node-RED resolves the inner expression against the message at evaluation time, so the same path can address a different element on every message. That means a Path is not fully static and cannot be pre-flattened to a string.

func (Token) String

func (t Token) String() string

String renders a token back into expression syntax. Round-tripping a parsed path through String and ParsePath yields an equivalent path, which is what the editor relies on when it echoes a property back into an edit dialog.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL