noderunner

package module
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Nov 25, 2026 License: MIT Imports: 21 Imported by: 1 module, 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.

README

noderun

The workflow engine for nodestore-based flows — deploys, runs, and stops workflows, entirely over nodestore interfaces.

Core types

  • WorkflowEngine (NewWorkflowEngine()) — owns the node registry, per-workflow run state, node state, the durable inbox, and the run journal. Deploy with DeployWorkflow / DeployWorkflowPartial, stop with StopWorkflow, fire nodes with InjectMessage / FireInjectNode.
  • NodeExecutor — the contract every node implements: ID(), Type(), Execute(ctx, msg), Validate(). Executors embed nodestore.NodeInterface so identity/type/Data live on the node entity.
  • PortRouter — optional executor interface: choose which output ports a message continues on (switch-node semantics).
  • MessageExpander — optional executor interface: turn one output into a sequence (split-node semantics).
  • Stopper, Activator — lifecycle hooks for nodes holding live resources or needing activation on deploy.
  • RegisterNodeType(typeID, NodeFactory) — uniform registration for built-ins and node packs; duplicate typeID is an error. Registration carries the editor descriptor served to the admin palette.

Execution model

  • Bounded-inbox model: each node has an incremental queue; traversal runs per-message on its own goroutine — nothing preserves order between separate injects/emits. FIFO consumers use deliverSync.
  • Durable by default: every hop persists to the shared store, so any runner attached to the same database can claim undelivered work; deployed workflows re-activate on restart and drain durable inboxes.
  • Pending HTTP responses are tracked by message ID (ResolveResponse / DiscardPending); fire-and-forget injects must discard, and event-node messages must preserve the original msgId.

Relationship to nodes

The built-in node executors live in the separate nodebase package — they are engine-agnostic, written against the NodeHost contract they define. WorkflowEngine implements NodeHost: it passes itself to node factories and hosts any pack built on the same contract. Dependency direction: noderun → nodebase → nodestore.

Contents

  • Engine core, leases, deploy diffing/observation
  • Inbox, durable queues, run journal (execution log)
  • Node-type registry (RegisterNodeType) and the NodeHost implementation backing executor runtime seams
  • Subflow/module composition, context and credential persistence
  • Filesystem abstractions (local/ftp/sftp) and inbound HTTP routing

Rules

  • Executors never resolve engine state inside Stop() (deadlock — StopWorkflow holds the run mutex); resolve eagerly in Execute and cache the state pointer on the executor shell.
  • Imports nodestore only — never nodeadmin.

Documentation

Index

Constants

View Source
const (
	DefaultLeaseTTL               = 15 * time.Second
	DefaultLeaseHeartbeatInterval = 5 * time.Second
)

Default lease timing: heartbeat every 5s, leases live for 15s — a dead runner's leases are claimable after ~3 missed heartbeats.

View Source
const DefaultMaxInflightTraversals = 512

DefaultMaxInflightTraversals is the fallback bound on concurrently running traversals — see WorkflowEngine.MaxInflightTraversals.

View Source
const DefaultMaxSteps = 10000

DefaultMaxSteps is the fallback step quota when neither the engine (MaxSteps engine option) nor the workflow (view "maxSteps") configures one. A wired cycle re-executes nodes until this trips.

View Source
const JournalMasked = "********"

JournalMasked replaces credential-keyed values in journaled payload summaries — the journal is inspectable via the admin API, so secrets must never be stored in it.

View Source
const MaxJournalPayloadBytes = 4096

MaxJournalPayloadBytes bounds the JSON-serialized size of each summarized input/output stored in a journal entry. Larger payloads are replaced by a {truncated, bytes, preview} marker so a fat message (binary file, bulk row set) cannot bloat the ring — 4 KiB keeps one entry comfortably inspectable in the editor while the worst-case memory of a full 20-entry ring stays under ~80 KiB/node.

View Source
const MaxJournalScrubDepth = 8

MaxJournalScrubDepth bounds the recursion of the credential scrub so a pathological nested payload cannot stack-overflow the summarizer.

View Source
const ProblemQueueAutoNodeID = "__problems__"

ProblemQueueAutoNodeID is the well-known node id of the built-in system problem queue materialized by view.onError="auto".

View Source
const RunJournalSize = nodebase.RunJournalSize

RunJournalSize bounds how many execution records the engine keeps per (workflow, node). 20 is a deliberately small ring: enough to see the recent behaviour of a node during a debug session (FastGPT-style "run details"), small enough that a 1000-node flow journaling every execution stays in the tens of megabytes worst-case (each stored payload summary is itself bounded by MaxJournalPayloadBytes). The constant lives in nodes (the runner-agnostic contract package) so the admin API can report the bound without importing noderunner.

Variables

This section is empty.

Functions

func ContextWithWorkflowID

func ContextWithWorkflowID(ctx context.Context, workflowID string) context.Context

ContextWithWorkflowID returns ctx carrying the run's workflow id. The engine stamps it once when a run context is created (startRun), so every Execute/Activate — deploy-time activation, wired delivery, inject and emit traversals alike — observes the same value.

func ExpandSubflows

func ExpandSubflows(w nodestore.WorkflowInterface, allowOSEnv bool) error

ExpandSubflows rewrites w in place: every "subflow:<defId>" instance node is replaced by a namespaced copy of its definition's internal graph and the definition nodes themselves are removed (they are templates, not executable nodes). Definitions are parsed from nodes of type "subflow" living in the same workflow. allowOSEnv permits "env"-typed env vars to read the process environment (see WorkflowEngine.AllowOSEnv). Returns a descriptive error for unknown definitions, out-of-range ports, recursive nesting and expansion beyond maxExpandedNodes.

func NodeDisabled

func NodeDisabled(workflow nodestore.WorkflowInterface, node nodestore.NodeInterface) bool

NodeDisabled reports whether node is disabled in workflow — the exported form of the deploy-time predicate, for optional packages (e.g. pkg/flowdashboard) that collect node subsets of a deployed workflow and must honor the same disabled semantics.

func ParseDurableFlag

func ParseDurableFlag(value interface{}) (bool, bool)

ParseDurableFlag normalizes an "inboxDurable" config value. It accepts booleans, truthy strings ("true"/"yes"/"1"/"on") and numbers, matching how loosely-typed editor data arrives.

func ProblemQueueIDFromView

func ProblemQueueIDFromView(workflow nodestore.WorkflowInterface) (string, bool)

ProblemQueueIDFromView returns the designated problem queue node id configured on the workflow view ("onError"). "auto" resolves to the built-in system queue id (ProblemQueueAutoNodeID).

func WorkflowIDFromContext

func WorkflowIDFromContext(ctx context.Context) (workflowID string, ok bool)

WorkflowIDFromContext returns the id of the workflow run ctx belongs to. nodestore.NodeInterface packs whose factories receive only the engine (the frozen nodes.NodeFactory signature has no workflow parameter) use it to attribute side effects — e.g. a dashboard widget pushing state to the hub — to the correct run. ok is false outside a run traversal (e.g. a node executed directly in a test).

Types

type DeployMode

type DeployMode int

DeployMode selects how a deploy treats a workflow that is already running (Node-RED's deploy modes: full / modified flows / modified nodes — this engine offers full and partial).

const (
	// DeployFull restarts every node: all stoppers are shut down and
	// re-activated. This is the default and matches a cold deploy.
	DeployFull DeployMode = iota
	// DeployPartial diffs the incoming flow against the running one
	// and only stops/starts the changed nodes. Unchanged Stoppers
	// (tcpIn/mqttIn listeners, inject timers, queue drainers) keep
	// running — Node-RED "modified nodes" semantics.
	DeployPartial
)

type DeployObserver

type DeployObserver interface {
	// WorkflowActivated fires after a run's activation succeeded —
	// initial deploy, full redeploy and partial redeploy alike. The
	// argument is the just-activated workflow definition; treat it
	// as read-only.
	WorkflowActivated(workflow nodestore.WorkflowInterface)
	// WorkflowStopped fires when a run's registration is torn down:
	// StopWorkflow and abandonRun (failed activation) alike. The id
	// may refer to a run the observer never saw activate.
	WorkflowStopped(workflowID string)
}

DeployObserver is the engine's generic run-lifecycle seam: an optional hook the host wires (like HTTPAuthenticator, FileRoot or nodes.ContextStore) to observe deploys and stops. Nil — the default — means no observation; a consumer that installs nothing gets zero overhead and zero behavior change. pkg/flowdashboard installs itself through it; other subsystems (metrics, audit) could too.

Both events are raised inline on the deploy/stop path, so implementations must be cheap and must not call back into DeployWorkflow/StopWorkflow (deadlock). The engine holds no locks it does not already hold at those points — see the call sites.

type DirQueueStore

type DirQueueStore struct {
	// contains filtered or unexported fields
}

DirQueueStore is a DurableInboxStore persisting every queued item as its own JSON file in one directory. It additionally implements itemReloader so the queue re-reads the file at release time.

Storage goes through the nodebase.Fs seam (task remote_fs): a local path uses the os adapter, an sftp:// or ftp:// locator uses the remote adapter — the materialized "one file per item" debugging workflow is unchanged, only the wire differs. All nodebase.Fs ops run under the store mutex, so a single-threaded remote connection is safe.

func NewDirQueueStore

func NewDirQueueStore(dir string) (*DirQueueStore, error)

NewDirQueueStore creates (or reuses) dir as a materialized queue. The store is unscoped: it manages every parseable item file in dir. Queue nodes should use NewScopedDirQueueStore.

func NewDirQueueStoreFS

func NewDirQueueStoreFS(fsys nodebase.Fs, dir, nodeID string) (*DirQueueStore, error)

NewDirQueueStoreFS is the nodebase.Fs-locator form of NewScopedDirQueueStore: the caller resolves the locator via nodebase.OpenFs and hands the connected filesystem in. The store takes ownership of fs — Close releases it.

func NewScopedDirQueueStore

func NewScopedDirQueueStore(dir, nodeID string) (*DirQueueStore, error)

NewScopedDirQueueStore creates a DirQueueStore that only claims files whose body nodeId equals nodeID. Two queue nodes may then share one directory: each sees, reloads and deletes only its own staged files, and per-node seqs may collide harmlessly (filenames stay distinct via the msgid component).

func (*DirQueueStore) Close

func (s *DirQueueStore) Close() error

Close releases the underlying nodebase.Fs (an sftp/ftp connection; a no-op for local dirs). Called when the owning queue stops.

func (*DirQueueStore) DeleteInboxItem

func (s *DirQueueStore) DeleteInboxItem(workflowID string, seq int64) error

DeleteInboxItem implements DurableInboxStore: removes the file whose body seq matches. A file already gone (external delete) is not an error — the files are advisory.

func (*DirQueueStore) DeleteWorkflowInbox

func (s *DirQueueStore) DeleteWorkflowInbox(workflowID string) error

DeleteWorkflowInbox implements DurableInboxStore: drops every OWNED item file whose body workflowId matches (files without one — e.g. hand-written — are left alone, and a scoped store never touches other nodes' files even in the same workflow).

func (*DirQueueStore) LoadInbox

func (s *DirQueueStore) LoadInbox(workflowID string) ([]DurableInboxItem, error)

LoadInbox implements DurableInboxStore: scan the dir, return items in seq order. Files removed externally simply do not appear.

func (*DirQueueStore) LoadInboxItem

func (s *DirQueueStore) LoadInboxItem(workflowID string, seq int64) (*DurableInboxItem, error)

LoadInboxItem implements itemReloader: re-reads one item's file at release time so external edits are delivered. Returns an error when the file no longer exists or cannot be parsed — the queue treats that as "externally removed" and drops the entry.

func (*DirQueueStore) SaveInboxItem

func (s *DirQueueStore) SaveInboxItem(item *DurableInboxItem) error

SaveInboxItem implements DurableInboxStore: assigns the next seq and writes `{seq}-{msgid}.json` atomically.

type DurableInboxItem

type DurableInboxItem struct {
	WorkflowID string
	NodeID     string
	Seq        int64
	Payload    nodestore.MessageInterface
	EnqueuedAt time.Time
}

DurableInboxItem is one persisted inbox row. Seq is assigned by the store on save and defines global dequeue order.

type DurableInboxStore

type DurableInboxStore interface {
	// LoadInbox returns all surviving queued items for a workflow in
	// sequence order.
	LoadInbox(workflowID string) ([]DurableInboxItem, error)
	// SaveInboxItem persists item and fills in its Seq.
	SaveInboxItem(item *DurableInboxItem) error
	// DeleteInboxItem removes one persisted row (delivery ack).
	DeleteInboxItem(workflowID string, seq int64) error
	// DeleteWorkflowInbox drops every queued row for a workflow
	// (called when the workflow itself is deleted).
	DeleteWorkflowInbox(workflowID string) error
}

DurableInboxStore is the persistence contract behind the durable inbox backend. It lives in flowrunner (like LeaseStore) because the import direction is flowadmin/storage -> flowrunner. Implementations must return rows ordered by Seq.

type InboxBackend

type InboxBackend interface {
	// Enqueue appends item to the global queue and the per-node count.
	Enqueue(item InboxItem) error
	// Dequeue removes and returns the globally-oldest queued item.
	Dequeue() (InboxItem, bool, error)
	// RemoveOldest removes and returns the oldest queued item for
	// nodeID (drop-oldest policy).
	RemoveOldest(nodeID string) (InboxItem, bool, error)
	// Pending reports how many items are queued for nodeID.
	Pending(nodeID string) (int, error)
	// Close releases backend resources (no-op for memory).
	Close() error
}

InboxBackend is the storage contract behind node inboxes. The memory backend (memInboxBackend) is the default; the durable neat-backed implementation from the durable_message_queue task plugs in through WorkflowEngine.InboxBackendFactory.

Implementations must preserve global FIFO order for Dequeue while tracking a pending count per node. All calls happen on the traversal goroutine for the memory backend; a durable backend serving several runners is responsible for its own synchronization.

func NewDurableInboxBackend

func NewDurableInboxBackend(workflowID string, store DurableInboxStore) InboxBackend

NewDurableInboxBackend creates the backend plugged in via WorkflowEngine.DurableInboxStore (or returned from a custom InboxBackendFactory). Nodes are marked durable via SetDurableNodes, called by newInbox after resolving config.

type InboxClaimer

type InboxClaimer interface {
	ClaimInboxItem(workflowID string, seq int64, runnerID string, ttl time.Duration) (claimed bool, err error)
}

InboxClaimer is the optional DurableInboxStore extension for the pending -> claimed -> deleted lifecycle. ClaimInboxItem performs one atomic conditional UPDATE: it succeeds only when the row is pending, its previous claim expired, or runnerID already holds it. claimed=false means a live claim by another runner — the drainer must skip the row.

type InboxItem

type InboxItem struct {
	NodeID  string
	Payload nodestore.MessageInterface
	Seq     int64
}

InboxItem is one queued unit of work: a target node plus the payload clone it will receive when executed. Seq carries the persisted row id for claim-capable durable stores (0 = transient or already-acked on dequeue): the engine passes it to inbox.ack after dispatch so the row outlives mid-process crashes.

type Lease

type Lease struct {
	WorkflowID string    `json:"workflow_id"`
	RunnerID   string    `json:"runner_id"`
	ExpiresAt  time.Time `json:"expires_at"`
	Generation int64     `json:"generation"`
}

Lease represents a workflow execution lease held by a runner. A workflow may run on at most one runner at a time; the lease is renewed by heartbeat and can be taken over once it expires.

type LeaseStore

type LeaseStore interface {
	// ClaimLease attempts to acquire (or re-acquire) the lease for
	// workflowID on behalf of runnerID. held=false means another live
	// runner owns it; holder then carries that runner's ID.
	ClaimLease(workflowID, runnerID string, ttl time.Duration) (held bool, holder string, err error)
	// RenewLease extends the lease expiry. ok=false means the lease
	// was lost (expired and claimed by another runner, or released).
	RenewLease(workflowID, runnerID string, ttl time.Duration) (ok bool, err error)
	// ReleaseLease drops the lease if (and only if) runnerID owns it.
	ReleaseLease(workflowID, runnerID string) error
	// ListLeases returns all workflow leases (expired ones included).
	ListLeases() ([]Lease, error)
	// UpsertRunner registers/refreshes a runner heartbeat row.
	UpsertRunner(r Runner) error
	// ListRunners returns all known runners.
	ListRunners() ([]Runner, error)
}

LeaseStore is the persistence contract the engine uses for multi-runner lease coordination. It lives in flowrunner (not flowadmin/storage) because the import direction is flowadmin/storage -> flowrunner. Implementations must compare expiry against the database clock (CURRENT_TIMESTAMP), not the caller's clock, so hosts with skewed clocks still agree.

type NeatInboxStore

type NeatInboxStore struct {
	// contains filtered or unexported fields
}

NeatInboxStore is the neat-backed DurableInboxStore. Construct it on the same *sql.DB the entitystore uses (see nodeadmin) so workflows and their queued messages share one database — that sharing is what makes handoff visible to every runner.

func NewNeatInboxStore

func NewNeatInboxStore(sqlDB *sql.DB) (*NeatInboxStore, error)

NewNeatInboxStore wraps an open *sql.DB in a neat Database (driver auto-detected) and migrates the node_inbox_messages table. The caller keeps ownership of sqlDB — Close only releases neat's bookkeeping.

func (*NeatInboxStore) ClaimInboxItem

func (s *NeatInboxStore) ClaimInboxItem(workflowID string, seq int64, runnerID string, ttl time.Duration) (bool, error)

ClaimInboxItem implements InboxClaimer: one atomic conditional UPDATE transitions the row to 'claimed' with this runner's id and a fresh expiry. RowsAffected==0 means a live claim by another runner (or no such row) — the item is skipped, never double-delivered.

func (*NeatInboxStore) DeleteInboxItem

func (s *NeatInboxStore) DeleteInboxItem(workflowID string, seq int64) error

DeleteInboxItem implements DurableInboxStore (the delivery ack).

func (*NeatInboxStore) DeleteWorkflowInbox

func (s *NeatInboxStore) DeleteWorkflowInbox(workflowID string) error

DeleteWorkflowInbox implements DurableInboxStore: drops every queued row for the workflow.

func (*NeatInboxStore) LoadInbox

func (s *NeatInboxStore) LoadInbox(workflowID string) ([]DurableInboxItem, error)

LoadInbox implements DurableInboxStore: surviving pending rows and expired claims for the workflow in seq order. A live claim held by another runner is excluded — that runner owns the row.

func (*NeatInboxStore) LoadInboxFor

func (s *NeatInboxStore) LoadInboxFor(workflowID, runnerID string) ([]DurableInboxItem, error)

LoadInboxFor implements workflowClaimLoader: additionally returns rows already claimed by runnerID, so a restarting runner requeues its own mid-process crash leftovers immediately instead of waiting out the claim TTL.

func (*NeatInboxStore) SaveInboxItem

func (s *NeatInboxStore) SaveInboxItem(item *DurableInboxItem) error

SaveInboxItem implements DurableInboxStore: serializes the envelope and inserts a 'pending' row; item.Seq is assigned from the auto-increment id — that IS the seq-at-persist ordering key.

type NeatLeaseStore

type NeatLeaseStore struct {
	// contains filtered or unexported fields
}

NeatLeaseStore is the neat-backed LeaseStore for the new stack. Construct it on the same *sql.DB the entitystore uses (see nodeadmin) so leases coordinate every runner on that database.

func NewNeatLeaseStore

func NewNeatLeaseStore(sqlDB *sql.DB) (*NeatLeaseStore, error)

NewNeatLeaseStore wraps an open *sql.DB in a neat Database (driver auto-detected) and migrates the lease/runner tables. The caller keeps ownership of sqlDB — Close only releases neat's bookkeeping.

func (*NeatLeaseStore) ClaimLease

func (s *NeatLeaseStore) ClaimLease(workflowID, runnerID string, ttl time.Duration) (bool, string, error)

ClaimLease implements LeaseStore. The conditional UPDATE is atomic because SQL writers serialize; it succeeds only when the lease is free, expired (per the DB clock) or already ours. When no row exists yet we insert one, then fall back to the UPDATE — which resolves the concurrent-insert race the same way (one side loses the PK insert, retries the UPDATE, sees a live holder).

func (*NeatLeaseStore) ListLeases

func (s *NeatLeaseStore) ListLeases() ([]Lease, error)

ListLeases implements LeaseStore.

func (*NeatLeaseStore) ListRunners

func (s *NeatLeaseStore) ListRunners() ([]Runner, error)

ListRunners implements LeaseStore.

func (*NeatLeaseStore) ReleaseLease

func (s *NeatLeaseStore) ReleaseLease(workflowID, runnerID string) error

ReleaseLease implements LeaseStore.

func (*NeatLeaseStore) RenewLease

func (s *NeatLeaseStore) RenewLease(workflowID, runnerID string, ttl time.Duration) (bool, error)

RenewLease implements LeaseStore. Zero rows affected means the lease was lost (taken over or released).

func (*NeatLeaseStore) UpsertRunner

func (s *NeatLeaseStore) UpsertRunner(r Runner) error

UpsertRunner implements LeaseStore.

type NodeEvent

type NodeEvent = nodebase.NodeEvent

NodeEvent is a single timestamped entry in a workflow's execution log — an alias of the runner-agnostic nodebase.NodeEvent contract so admin surfaces (nodeadmin/api) can consume workflow events without importing this package.

type Queue

type Queue struct {
	// contains filtered or unexported fields
}

Queue is the shared staging queue behind a queue node. One instance per workflow+node, stored in engine.states. All fields are guarded by mu.

func (*Queue) Arm

func (q *Queue) Arm(ctx context.Context)

arm starts the drainer once and recovers surviving durable rows. Idempotent — activation calls it, and it is the only place rows are adopted from the store.

func (*Queue) Count

func (q *Queue) Count() int

Count reports the queued depth (excluding the block waitlist).

func (*Queue) DeleteItem

func (q *Queue) DeleteItem(seq int64) error

DeleteItem drops the queued item with the given seq, removing its persisted row.

func (*Queue) Enqueue

func (q *Queue) Enqueue(p nodestore.MessageInterface) error

enqueue stages a delivered payload under the queue's capacity and overflow policy. Persisted rows are written before the entry becomes drainable; a persist failure rejects the delivery (error event on the queue node) rather than degrading to memory.

func (*Queue) Held

func (q *Queue) Held() bool

Held reports whether the queue is held (accepting, not draining).

func (*Queue) Items

func (q *Queue) Items() []nodebase.QueueItem

Items returns the queued entries in FIFO order.

func (*Queue) ReleaseItem

func (q *Queue) ReleaseItem(seq int64, route string, approvedBy string) error

ReleaseItem is the route-parameterized requeue used by checkpoints: route picks which outgoing edge the item takes (a route label or an "output_N" port key; empty = all edges, identical to RequeueItem). On a routed release the payload records the approval metadata under Metadata["checkpoint"] = {route, approvedBy, at}.

func (*Queue) RequeueItem

func (q *Queue) RequeueItem(seq int64) error

RequeueItem releases one queued item downstream immediately, out of order, and removes its persisted row — the manual single-item release used by the inspection API / dead-letter rework.

func (*Queue) RouteLabels

func (q *Queue) RouteLabels() []string

RouteLabels returns the checkpoint's route labels in port order — routes[i] labels output_{i+1}. An empty/unlabeled route reports its port key ("output_2" style). Plain queues report nil.

func (*Queue) SetHold

func (q *Queue) SetHold(hold bool)

SetHold toggles the hold gate at runtime; releasing wakes the drainer.

func (*Queue) Stop

func (q *Queue) Stop()

stop shuts the drainer down (nodebase.Stopper path, idempotent) and releases the store's filesystem connection (an sftp/ftp session is a real connection; a local dir is a no-op).

type Runner

type Runner struct {
	RunnerID     string    `json:"runner_id"`
	Hostname     string    `json:"hostname"`
	Version      string    `json:"version"`
	LastSeen     time.Time `json:"last_seen"`
	RunningCount int       `json:"running_count"`
}

Runner describes an engine process registered in the shared store.

type WorkflowEngine

type WorkflowEngine struct {

	// AllowExec gates the exec node's arbitrary command execution.
	// Default off; enabled by the consuming application (wired in main).
	AllowExec bool
	// FileRoot restricts file/fileIn node paths to a root directory.
	// Empty means unrestricted; set by the consuming application (wired in main).
	FileRoot string
	// HTTPAuthenticator authenticates requests arriving at node-served
	// HTTP listeners (submitIn auth "admin"). It returns the
	// authenticated username — stamped into msg.submit.submittedBy.
	// Nil means no credentials are configured; wired in main from the
	// same auth-file env var the consuming application's admin UI uses.
	HTTPAuthenticator func(r *http.Request) (username string, ok bool)
	// nodebase.HTTPRouter is the optional shared-listener seam (see
	// http_router.go): when installed, httpTrigger/submitIn nodes
	// configured with listener "main" mount their route on the host's
	// HTTP server — behind its middleware — instead of binding a
	// private port. Nil disables the mode: main-mode nodes fail
	// activation. Wired in main from the admin's router adapter.
	HTTPRouter nodebase.HTTPRouter
	// RunnerID identifies this process for lease coordination.
	// Defaults to the OS hostname; override via the consuming application's runner-id env var.
	RunnerID string
	// RunnerVersion is stamped into the runners table on heartbeat.
	RunnerVersion string
	// LeaseStore enables multi-runner lease coordination. Nil means
	// leases are disabled (single-runner behaviour, unchanged).
	LeaseStore LeaseStore
	// CredentialsProvider returns the deploy-time credential map
	// (nodeID → key → value) for a workflow — the entity-backed
	// replacement for flowadmin's injectCredentials. Nil means no
	// credential storage is configured: sentinel markers pass through
	// to executors (single-user dev installs keep working unchanged).
	// Wired by the admin surface from nodestore.CredentialMapForWorkflow.
	CredentialsProvider func(ctx context.Context, workflowID string) (map[string]map[string]string, error)
	// LeaseTTL is how long a claimed lease lives without renewal
	// (default DefaultLeaseTTL = 15s).
	LeaseTTL time.Duration
	// LeaseHeartbeatInterval is the renew/janitor tick
	// (default DefaultLeaseHeartbeatInterval = 5s).
	LeaseHeartbeatInterval time.Duration

	// InboxCapacity is the engine-wide default bound for per-node
	// inboxes; <=0 means unbounded (legacy sequential-BFS behaviour).
	// Per-node node.GetData()["inboxCapacity"] and flow-level
	// workflow.GetView()["inboxCapacity"] override it.
	InboxCapacity int
	// InboxPolicy is the engine-wide default overflow policy applied
	// when a bounded inbox is full (empty defaults to nodebase.OverflowBlock).
	InboxPolicy nodebase.OverflowPolicy
	// InboxBackendFactory creates the storage backend behind each
	// traversal's node inboxes. Nil falls back to DurableInboxStore
	// (durable-by-default: every hop persists) and then to the
	// in-memory backend.
	InboxBackendFactory func(workflowID string) InboxBackend
	// DurableInboxStore enables the write-through durable inbox
	// backend for EVERY node inbox (GOD ruling 2026-11-24: multiple
	// runners may share one DB, so every hop must leave a durable
	// record — the superseded "inboxDurable" opt-in flags are ignored).
	// Nil keeps every inbox in memory (standalone dev without a DB).
	// Wired by the admin surface — see NeatInboxStore.
	DurableInboxStore DurableInboxStore
	// InboxDurable is DEPRECATED (superseded by durable-by-default):
	// kept for config compatibility only, no longer consulted.
	InboxDurable bool
	// MaxSteps is the engine-wide step quota: the maximum number of
	// node executions a single message lineage may trigger before the
	// traversal halts (runaway-loop guard). 0 falls back to
	// DefaultMaxSteps; <0 disables the quota. Per-workflow
	// workflow.GetView()["maxSteps"] overrides it (same semantics).
	// Wired in main by the consuming application.
	MaxSteps int
	// MaxInflightTraversals bounds concurrently running message
	// traversals (inject/Emit/DeliverSync): each external injection
	// launches a goroutine and — with a durable inbox — one DB row
	// per hop, so an unbounded flood is a goroutine + write
	// amplification DoS. 0 falls back to
	// DefaultMaxInflightTraversals; <0 disables the bound.
	// Wired in main by the consuming application.
	MaxInflightTraversals int

	// AllowOSEnv gates whether flows may read process environment
	// variables — "env"-typed vars in group/subflow/flow/global env
	// layers and the env.get OS fallback in function nodes. Default
	// off: a flow author should not be able to exfiltrate process
	// secrets (DB DSNs, cloud credentials) via env.get. Enable via
	// the consuming application's opt-in env var (wired in main) — mirrors AllowExec.
	AllowOSEnv bool
	// nodebase.ContextStore persists function-node context (node/flow/global
	// scopes) across engine restarts and undeploy/redeploy — wired in
	// main via a type assertion on the storage backend, like
	// DurableInboxStore. Nil falls back to a process-local in-memory
	// store (context survives redeploys but not restarts).
	ContextStore nodebase.ContextStore
	// contains filtered or unexported fields
}

WorkflowEngine manages the execution of workflows

func NewWorkflowEngine

func NewWorkflowEngine() *WorkflowEngine

NewWorkflowEngine creates a new WorkflowEngine

func (*WorkflowEngine) BuildQueueStore

func (e *WorkflowEngine) BuildQueueStore(backend, dir, nodeID string, nodeData map[string]interface{}) (DurableInboxStore, error)

buildStore resolves this queue's persistence backend. "durable" uses the engine-wide DurableInboxStore; "dir" constructs a DirQueueStore rooted at dir, scoped to this queue's node ID so several queue nodes can share one directory without cross-deleting or cross-reloading each other's files. Construction errors are stored on the queue (sticky) so every store user reports the same failure.

func (*WorkflowEngine) DeliverSync

func (e *WorkflowEngine) DeliverSync(workflowID, fromNodeID string, payload nodestore.MessageInterface, ports []string) error

DeliverSync performs the same bookkeeping as inject but runs the downstream traversal on the calling goroutine, returning only when it completes. Used by the queue drainer, which must deliver queued items strictly in FIFO order — separate async traversals would race. ports restricts which outgoing edges of fromNodeID are seeded (nil = all edges); checkpoint route releases pass a single port.

func (*WorkflowEngine) DeployWorkflow

func (e *WorkflowEngine) DeployWorkflow(ctx context.Context, workflow nodestore.WorkflowInterface, input nodestore.MessageInterface) (string, error)

DeployWorkflow starts a workflow and waits for activation to finish. A failed activation (e.g. a trigger that cannot bind its port) is returned as an error, and no listener is left running. A redeploy of a running workflow is a FULL deploy: every node restarts.

func (*WorkflowEngine) DeployWorkflowPartial

func (e *WorkflowEngine) DeployWorkflowPartial(ctx context.Context, workflow nodestore.WorkflowInterface, input nodestore.MessageInterface) (string, error)

DeployWorkflowPartial is DeployWorkflow with DeployPartial semantics: the incoming flow is diffed against the running one and only changed nodes are stopped and re-activated (Node-RED "modified nodes" mode). Unchanged Stoppers — tcpIn/mqttIn sockets, inject timers, queue drainers — keep running. On a cold deploy (nothing running) it is identical to a full deploy.

func (*WorkflowEngine) DiscardPending

func (e *WorkflowEngine) DiscardPending(msgID string)

DiscardPending removes a pending response channel without answering it (e.g. when the requester timed out or disconnected).

func (*WorkflowEngine) Emit

func (e *WorkflowEngine) Emit(workflowID, nodeID string, payload nodestore.MessageInterface, ports []string) error

emit schedules a fire-and-forget message from nodeID, restricted to the given output ports (nil = all outgoing edges). The pending response channel registered by inject is discarded — emitted messages never expect a reply. Used by nodes that produce asynchronous output (e.g. the trigger node's delayed second output).

func (*WorkflowEngine) EmitEvent

func (e *WorkflowEngine) EmitEvent(workflowID, nodeID, nodeName, level, message string)

EmitEvent appends an event to the workflow's bounded event log

func (*WorkflowEngine) EnsureQueue

func (e *WorkflowEngine) EnsureQueue(node nodestore.NodeInterface, checkpoint bool, routes []string) (nodebase.QueueContract, error)

EnsureQueue implements nodebase.QueueService: returns the shared Queue for node, creating and configuring it on first use (resolved capacity/policy/hold plus the persistence backend). checkpoint and routes mark the queue manual (a checkpoint never self-drains) and carry its named release routes.

func (*WorkflowEngine) ExecAllowed

func (e *WorkflowEngine) ExecAllowed() bool

ExecAllowed implements nodebase.NodeHost: whether the exec node may run arbitrary system commands.

func (*WorkflowEngine) ExecuteDownstream

func (e *WorkflowEngine) ExecuteDownstream(ctx context.Context, workflowID, fromNodeID string, workflow nodestore.WorkflowInterface, payload nodestore.MessageInterface, ports []string)

ExecuteDownstream performs an edge-aware breadth-first traversal of the nodes downstream of fromNodeID. Each queued item carries its own payload clone so fan-out branches do not share (and mutate) the same Data map. Nodes implementing nodebase.PortRouter select which of their outgoing edges fire; all other nodes fan out to every outgoing edge. A failing node aborts only its own branch — sibling branches continue.

func (*WorkflowEngine) ExecuteWorkflow

func (e *WorkflowEngine) ExecuteWorkflow(ctx context.Context, workflow nodestore.WorkflowInterface, input nodestore.MessageInterface) (string, error)

ExecuteWorkflow starts a workflow; activation runs in the background. Use DeployWorkflow when the caller needs the activation outcome.

func (*WorkflowEngine) FileRootPath

func (e *WorkflowEngine) FileRootPath() string

FileRootPath implements nodebase.NodeHost: the root directory file nodes are restricted to (empty = unrestricted).

func (*WorkflowEngine) FireInjectNode

func (e *WorkflowEngine) FireInjectNode(workflowID, nodeID string) error

FireInjectNode triggers the configured payload of a running inject node — the engine-side equivalent of clicking Node-RED's inject button. Returns an error when the workflow is not running or the node is not a live inject node.

func (*WorkflowEngine) GetNode

func (e *WorkflowEngine) GetNode(id string) (nodebase.NodeExecutor, bool)

GetNode returns a node executor by ID

func (*WorkflowEngine) GetNodeState

func (e *WorkflowEngine) GetNodeState(workflowID, nodeID string) interface{}

GetNodeState returns the buffered state stored for a node within a workflow (nil when none was stored yet). Stateful executors (join, sort, batch) are rebuilt per message so their buffers live here.

func (*WorkflowEngine) GetOrCreateNodeState

func (e *WorkflowEngine) GetOrCreateNodeState(workflowID, nodeID string, factory func() interface{}) interface{}

GetOrCreateNodeState returns the existing node state or stores and returns the value built by factory — atomically, so concurrent messages can't create duplicate buffers for the same node.

func (*WorkflowEngine) GetWorkflowSnapshot

func (e *WorkflowEngine) GetWorkflowSnapshot(workflowID string, since int64) (string, map[string]string, []NodeEvent, int64)

GetWorkflowSnapshot returns the workflow run status, per-node statuses and the events recorded since the given sequence number, plus the current last sequence for incremental polling.

func (*WorkflowEngine) GetWorkflowStatus

func (e *WorkflowEngine) GetWorkflowStatus(workflowID string) (string, error)

GetWorkflowStatus returns the status of a workflow execution

func (*WorkflowEngine) HTTPAuthFunc

func (e *WorkflowEngine) HTTPAuthFunc() func(r *http.Request) (username string, ok bool)

HTTPAuthFunc implements nodebase.NodeHost: authenticates requests at node-served HTTP listeners. Nil means no credentials configured.

func (*WorkflowEngine) HTTPAuthenticatorFunc

func (e *WorkflowEngine) HTTPAuthenticatorFunc() func(r *http.Request) (username string, ok bool)

HTTPAuthenticatorFunc returns the engine-configured HTTP authenticator (see the HTTPAuthenticator field); nil when unset. Lets optional packages reuse the engine's credentials without reaching into the struct field through an interface seam.

func (*WorkflowEngine) HasDurableStore

func (e *WorkflowEngine) HasDurableStore() bool

HasDurableStore implements nodebase.QueueService.

func (*WorkflowEngine) HasOutgoingEdges

func (e *WorkflowEngine) HasOutgoingEdges(workflowID, nodeID string, ports []string) bool

HasOutgoingEdges reports whether nodeID has at least one outgoing edge in the running workflow — any edge when ports is nil, or an edge on one of the given ports. The queue drainer uses it to hold items rather than emit them into nowhere.

func (*WorkflowEngine) InjectMessage

func (e *WorkflowEngine) InjectMessage(workflowID, fromNodeID string, payload nodestore.MessageInterface) (string, chan nodestore.MessageInterface, error)

InjectMessage routes an externally-originated payload (e.g. an HTTP trigger request) through the nodes downstream of fromNodeID in the running workflow. It returns a message ID whose response can be awaited via ResolveResponse — used by httpResponse nodes to reply to the original request.

func (*WorkflowEngine) LeaseRunner

func (e *WorkflowEngine) LeaseRunner(workflowID string) string

LeaseRunner returns the runner ID currently holding the workflow's lease, or "" when unleased / leases are not configured. Used by the API to surface runner_id on workflow-status.

func (*WorkflowEngine) LoadTLSConfig

func (e *WorkflowEngine) LoadTLSConfig(workflowID, ref string) (*tls.Config, error)

LoadTLSConfig resolves a tlsConfig node reference (node id within the workflow) into a ready *tls.Config for a client dial. It returns an error when the referenced node is missing, is not a tlsConfig node, or its files cannot be loaded.

func (*WorkflowEngine) LookupNode

func (e *WorkflowEngine) LookupNode(workflowID, nodeID string) (nodestore.NodeInterface, bool)

LookupNode returns the definition of a node within a running workflow. Link nodes use it to resolve linkIn targets at message time. Note that link targets only resolve within the SAME workflow — cross-workflow (Node-RED cross-tab) links are not supported yet.

func (*WorkflowEngine) MarkProblemDelivery

func (e *WorkflowEngine) MarkProblemDelivery(workflowID, nodeID string, p nodestore.MessageInterface)

MarkProblemDelivery stamps the loop-guard flag on a payload about to be delivered downstream by the problem queue (drainer or manual requeue). A failure of that delivery must not re-enqueue into the same queue.

func (*WorkflowEngine) MaxStepsLimit

func (e *WorkflowEngine) MaxStepsLimit(workflow nodestore.WorkflowInterface) int

MaxStepsLimit resolves the effective step quota for a workflow: workflow.GetView()["maxSteps"] > engine MaxSteps > DefaultMaxSteps. A negative value at either level disables the quota entirely; zero or unparseable values fall through to the next level.

func (*WorkflowEngine) NodeEnv

func (e *WorkflowEngine) NodeEnv(workflowID, nodeID, name string) (interface{}, bool)

NodeEnv resolves an env var for a node inside a running workflow using the Node-RED scoping chain (task env_scoping):

group env (view.groups[].env) → subflow overlay (node.GetData()["_env"])
→ flow env (view.env) → global-config (engine.globalEnv)

The caller (the function node's env.get) falls back to os.Getenv when every layer misses. Group and flow entries use the Node-RED env-var shape [{name,type,value}] — the same typing rules as subflow env (num/bool/json/str/env).

func (*WorkflowEngine) NodesInScope

func (e *WorkflowEngine) NodesInScope(workflowID, sourceNodeID, nodeType string) []string

NodesInScope returns the ids of nodes of nodeType in the running workflow whose scope covers sourceNodeID. A node's scope is configured via Data["scope"] ("all" — default/empty — or "selected") and Data["nodes"] (a []interface{} of ids or a comma-separated string). The source node itself is never returned.

func (*WorkflowEngine) OSEnvAllowed

func (e *WorkflowEngine) OSEnvAllowed() bool

OSEnvAllowed reports whether flows may read process environment variables — consulted by the function node's env.get OS fallback (and the engine's own "env"-typed resolution) via an optional interface, so hosts without the method keep Node-RED behaviour.

func (*WorkflowEngine) QueueHandle

func (e *WorkflowEngine) QueueHandle(workflowID, nodeID string) (nodebase.QueueInspector, bool)

QueueHandle returns the live queue behind a queue node for the inspection API — the engine-agnostic nodebase.QueueInspector contract, so admin surfaces need no noderunner types. ok is false when the workflow is not running or the node has no queue yet.

func (*WorkflowEngine) QueueService

func (e *WorkflowEngine) QueueService() nodebase.QueueService

QueueService implements nodebase.NodeHost: the engine is its own queue service — the shared Queue machinery lives here because the engine's auto problem queue reuses it.

func (*WorkflowEngine) RegisterNode

func (e *WorkflowEngine) RegisterNode(node nodebase.NodeExecutor) error

RegisterNode adds a node executor to the engine

func (*WorkflowEngine) RegisterNodeType

func (e *WorkflowEngine) RegisterNodeType(typeID string, factory nodebase.NodeFactory) error

RegisterNodeType registers factory under typeID for this engine only — useful for tests or hosts that want a type scoped to one engine instance rather than process-wide. Engine-scoped registrations win over the global registry; registering the same typeID twice on one engine is an error.

func (*WorkflowEngine) ResolveQueueConfig

ResolveQueueConfig reads capacity/policy/hold/backend off the node using inbox-key precedence (node > flow view > engine default). Backend defaults to "durable"; "dir" also resolves node.GetData()["dir"].

func (*WorkflowEngine) ResolveResponse

func (e *WorkflowEngine) ResolveResponse(msgID string, payload nodestore.MessageInterface) error

ResolveResponse delivers a payload to a pending injected message (e.g. an httpResponse node replying to an HTTP trigger request).

func (*WorkflowEngine) ResolvedContextStore

func (e *WorkflowEngine) ResolvedContextStore() nodebase.ContextStore

ResolvedContextStore resolves the store backing function-node context: the configured persistent store, or a lazily created process-local in-memory store when none is wired (context then survives undeploy/redeploy but not a process restart).

func (*WorkflowEngine) ResumeDeployed

func (e *WorkflowEngine) ResumeDeployed(ctx context.Context, store nodestore.StoreInterface) []error

ResumeDeployed re-activates every workflow whose stored deployed flag is set — the boot-time continuation path (durability is a semantic, not a flag). Called in the background by the host on mount (e.g. nodeadmin), it returns one error per workflow that failed to redeploy; an empty result means a clean resume.

A crash mid-traversal is a full redeploy of that workflow — the engine restarts it from activation. Durable inbox rows left undelivered are drained by the deploy path itself (requeueDurable runs at the tail of executeWorkflow), so persisted-but-undelivered messages resume processing after restart. Node-level durable state (queue-dir backends) reconciles when the store is opened.

func (*WorkflowEngine) RouteFailure

func (e *WorkflowEngine) RouteFailure(workflowID string, node nodestore.NodeInterface, in nodestore.MessageInterface, cause error)

RouteFailure is the single failure-routing entry point. The precedence ladder (task error_catch_port):

  1. the node's own opt-in "error" output port, when errorCatch is enabled AND that port is wired (an enabled-but-unwired port must not swallow the error);
  2. catch nodes in scope (Node-RED semantics);
  3. the designated problem queue — including messages already marked fromCatch, whose catch branch failure is itself uncaught.

func (*WorkflowEngine) RunContext

func (e *WorkflowEngine) RunContext(workflowID string) context.Context

RunContext returns the live run context for workflowID — bound to StopWorkflow so node-side emissions cancel with the run. Falls back to context.Background when the workflow is not running.

func (*WorkflowEngine) RunJournal

func (e *WorkflowEngine) RunJournal(workflowID, nodeID string) ([]nodebase.RunJournalEntry, bool)

RunJournal returns a copy of the node's recorded execution journal (oldest first). ok is false when the workflow is not running — the journal is run-scoped state like node statuses and is dropped when the workflow stops or redeploys.

func (*WorkflowEngine) RunningFlow

func (e *WorkflowEngine) RunningFlow(workflowID string) (nodestore.WorkflowInterface, bool)

RunningFlow returns the expanded in-memory workflow definition a run is executing — node executors consult it for graph context (e.g. link target lookups, config-node resolution). ok is false when the workflow is not running on this engine.

func (*WorkflowEngine) RunningWorkflows

func (e *WorkflowEngine) RunningWorkflows() []nodestore.WorkflowInterface

RunningWorkflows returns the definitions of all currently registered runs. A late-installed DeployObserver uses it to replay WorkflowActivated for runs that predate it (e.g. a dashboard hub mounted after workflows were already deployed). Definitions are the live run copies — treat as read-only.

func (*WorkflowEngine) SetDeployObserver

func (e *WorkflowEngine) SetDeployObserver(o DeployObserver)

SetDeployObserver installs the engine's run lifecycle observer; pass nil to remove it. Wire it before the first DeployWorkflow — the field is not synchronized against mid-run swaps (same contract as HTTPAuthenticator).

func (*WorkflowEngine) SetGlobalEnv

func (e *WorkflowEngine) SetGlobalEnv(raw interface{})

SetGlobalEnv installs the resolved global-config env map consulted by env.get after group/subflow/flow and before the OS environment. raw is the env entry list ([{name,type,value}] or {NAME: value} — the same shapes the editor and Node-RED produce). Passing nil/empty clears the layer.

func (*WorkflowEngine) SetNodeState

func (e *WorkflowEngine) SetNodeState(workflowID, nodeID string, state interface{})

SetNodeState stores buffered state for a node within a workflow.

func (*WorkflowEngine) SharedHTTPRouter

func (e *WorkflowEngine) SharedHTTPRouter() nodebase.HTTPRouter

SharedHTTPRouter implements nodebase.NodeHost: the optional shared listener HTTP-serving nodes mount routes on.

func (*WorkflowEngine) StopWorkflow

func (e *WorkflowEngine) StopWorkflow(workflowID string) error

StopWorkflow stops a running workflow

Jump to

Keyboard shortcuts

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