engine

package
v0.0.0-...-bea47b1 Latest Latest
Warning

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

Go to latest
Published: Nov 22, 2026 License: MIT Imports: 14 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

Index

Constants

View Source
const (
	NodeTypeHumanTask = "humantask"
	WaitHuman         = "HUMAN_WAIT"
	WaitSignal        = "SIGNAL_WAIT"
)
View Source
const PortsKey = "__ports"

PortsKey is the output envelope key used by port-aware executors: {"__ports": {"0": <data>, "1": <data>}}. A port that is absent carries no data, so edges leaving it are dead and their targets may be skipped.

Variables

View Source
var ErrStepConflict = errors.New("step was changed concurrently")

ErrStepConflict is returned when a step changed concurrently (e.g. a waiting step was already resumed, or a reclaimed step is now owned by another worker) and the transition was not applied.

Functions

func ApplyHumanTaskConfig

func ApplyHumanTaskConfig(step *models.ExecutionStep, n *models.Node)

ApplyHumanTaskConfig copies assignee/claim fields from node config onto a step.

func ExecutionIDFromContext

func ExecutionIDFromContext(ctx context.Context) string

func FindNode

func FindNode(wf *models.Workflow, nodeID string) *models.Node

FindNode returns the node definition by ID.

func IsInteractiveNode

func IsInteractiveNode(n models.Node) bool

IsInteractiveNode returns true when the node should not be auto-claimed by workers (humantask or execution_mode=interactive).

func IsPermanent

func IsPermanent(err error) bool

IsPermanent reports whether err (or anything it wraps) is permanent.

func MergeActionPayload

func MergeActionPayload(existingInput, action, payload string) string

MergeActionPayload merges action + payload JSON into an output map.

func NamespaceFromContext

func NamespaceFromContext(ctx context.Context) string

func NewStepForNode

func NewStepForNode(ns, execID, nodeID, input string, n *models.Node) *models.ExecutionStep

NewStepForNode creates a PENDING or WAITING step based on node type/mode.

func WithEngine

func WithEngine(ctx context.Context, e *Engine) context.Context

WithEngine attaches the engine pointer for setvariable durable writes.

func WithExecutionContext

func WithExecutionContext(ctx context.Context, namespace, execID string) context.Context

WithExecutionContext attaches namespace/execID for nodes that need durable vars.

Types

type Engine

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

func EngineFromContext

func EngineFromContext(ctx context.Context) *Engine

func NewEngine

func NewEngine(s storage.Storage, r *Registry) *Engine

func (*Engine) Advance

func (e *Engine) Advance(ctx context.Context, namespace, execID, nodeID, action, payload string) (string, []*models.ExecutionStep, error)

Advance completes a WAITING (or PENDING interactive) step synchronously. action is a free-form string (approve/reject/submit); payload is JSON.

func (*Engine) CancelExecution

func (e *Engine) CancelExecution(ctx context.Context, namespace string, execID string) error

func (*Engine) CheckAccess

func (e *Engine) CheckAccess(ctx context.Context, resource, action string) error

CheckAccess runs the configured AuthProvider (no-op when unset).

func (*Engine) ClaimTask

func (e *Engine) ClaimTask(ctx context.Context, namespace, execID, nodeID, actor string) error

ClaimTask assigns a waiting human task to an actor.

func (*Engine) CompleteStep

func (e *Engine) CompleteStep(ctx context.Context, step *models.ExecutionStep, output string) error

CompleteStep handles the transition after a node finishes. The step must still be in the state the caller read (WAITING, or RUNNING and owned by the same worker); otherwise ErrStepConflict is returned and nothing changes. Scheduling continues even if ctx is cancelled after the step was persisted, so children are never orphaned by a disconnected caller.

func (*Engine) CompleteTask

func (e *Engine) CompleteTask(ctx context.Context, namespace, execID, nodeID, actor, action, payload string) (string, []*models.ExecutionStep, error)

CompleteTask claims (if needed) and advances a human task.

func (*Engine) EventBus

func (e *Engine) EventBus() *EventBus

EventBus returns the engine's event bus.

func (*Engine) Execute

func (e *Engine) Execute(ctx context.Context, namespace, workflowID string, input []byte) (string, error)

Execute is an alias for StartWorkflow (accepts []byte input)

func (*Engine) ExecutionSnapshot

func (e *Engine) ExecutionSnapshot(ctx context.Context, namespace, execID string) (*models.Execution, *models.Workflow, []*models.ExecutionStep, error)

ExecutionSnapshot returns an execution with its workflow and steps, without auth checks. It is meant for executors running inside that execution (e.g. expression engines resolving other nodes' outputs).

func (*Engine) FailExecution

func (e *Engine) FailExecution(ctx context.Context, namespace string, execID string, message string) error

func (*Engine) GetExecutionStatus

func (e *Engine) GetExecutionStatus(ctx context.Context, namespace string, execID string) (*models.Execution, error)

func (*Engine) GetExecutionSteps

func (e *Engine) GetExecutionSteps(ctx context.Context, namespace string, execID string) ([]*models.ExecutionStep, error)

func (*Engine) GetLogger

func (e *Engine) GetLogger() *slog.Logger

func (*Engine) GetVar

func (e *Engine) GetVar(ctx context.Context, namespace, execID, key string) (interface{}, error)

GetVar reads a durable execution variable.

func (*Engine) GetVars

func (e *Engine) GetVars(ctx context.Context, namespace, execID string) (map[string]interface{}, error)

GetVars returns all durable variables.

func (*Engine) ListCompensationJournal

func (e *Engine) ListCompensationJournal(ctx context.Context, namespace, execID string) ([]*models.CompensationRecord, error)

ListCompensationJournal returns compensation/rollback records for an execution.

func (*Engine) ListExecutions

func (e *Engine) ListExecutions(ctx context.Context, namespace string) ([]*models.Execution, error)

ListExecutions returns all executions in a namespace.

func (*Engine) ListTasks

func (e *Engine) ListTasks(ctx context.Context, namespace string, filter TaskFilter) ([]*models.ExecutionStep, error)

ListTasks returns WAITING human/interactive steps.

func (*Engine) MergeVars

func (e *Engine) MergeVars(ctx context.Context, namespace, execID string, vars map[string]interface{}) error

MergeVars merges a map into durable execution variables.

func (*Engine) NodeRegistry

func (e *Engine) NodeRegistry() *Registry

NodeRegistry returns the executor registry used by this engine.

func (*Engine) ReapTimeouts

func (e *Engine) ReapTimeouts(ctx context.Context, namespace string) error

ReapTimeouts checks for WAITING steps that have passed their timeout period.

func (*Engine) RegisterWorkflow

func (e *Engine) RegisterWorkflow(ctx context.Context, namespace string, wf *models.Workflow) error

RegisterWorkflow saves a workflow definition to storage

func (*Engine) ReleaseTask

func (e *Engine) ReleaseTask(ctx context.Context, namespace, execID, nodeID, actor string) error

ReleaseTask clears the claim on a waiting task.

func (*Engine) RollbackTo

func (e *Engine) RollbackTo(ctx context.Context, namespace, execID, nodeID, reason, actor string) error

RollbackTo records a journal entry and enqueues compensation for the target node's CompensateNodeID (or the node itself if it is a compensate node).

func (*Engine) SetAuthProvider

func (e *Engine) SetAuthProvider(provider auth.AuthProvider) *Engine

SetAuthProvider sets the auth provider for authorization checks If not set, all operations are allowed (no auth)

func (*Engine) SetEventBus

func (e *Engine) SetEventBus(bus *EventBus) *Engine

SetEventBus replaces the engine event bus (async handlers).

func (*Engine) SetHostHooks

func (e *Engine) SetHostHooks(h HostHooks) *Engine

SetHostHooks sets a synchronous host integration handler (WS, notifications).

func (*Engine) SetVar

func (e *Engine) SetVar(ctx context.Context, namespace, execID, key string, value interface{}) error

SetVar sets a durable execution variable.

func (*Engine) SetWorkflowStatus

func (e *Engine) SetWorkflowStatus(ctx context.Context, namespace, workflowID string, status models.WorkflowStatus) error

SetWorkflowStatus marks a workflow definition ACTIVE or INACTIVE without auth checks (for trigger hosts such as the n8n handler).

func (*Engine) SignalExecution

func (e *Engine) SignalExecution(ctx context.Context, namespace string, execID string, nodeID string, output string) error

func (*Engine) StartWorker

func (e *Engine) StartWorker(ctx context.Context, namespace, workerID string)

StartWorker starts a worker loop that processes tasks (one at a time). It blocks until ctx is cancelled and in-flight work has been released.

func (*Engine) StartWorkerWithOptions

func (e *Engine) StartWorkerWithOptions(ctx context.Context, namespace, workerID string, opts WorkerOptions)

StartWorkerWithOptions starts a worker with custom concurrency/polling.

func (*Engine) StartWorkflow

func (e *Engine) StartWorkflow(ctx context.Context, namespace, workflowID string, input string) (string, error)

StartWorkflow creates a new execution for a workflow

func (*Engine) SweepStuckExecutions

func (e *Engine) SweepStuckExecutions(ctx context.Context, namespace string, olderThan time.Duration) (int, error)

SweepStuckExecutions finishes RUNNING executions whose steps have all settled but that were never finalized (e.g. a process crashed between completing a step and scheduling its children). It returns how many executions changed state. Workers call it periodically.

func (*Engine) WithLogger

func (e *Engine) WithLogger(l *slog.Logger) *Engine

func (*Engine) WorkflowDefinition

func (e *Engine) WorkflowDefinition(ctx context.Context, namespace, id string) (*models.Workflow, error)

WorkflowDefinition loads a workflow definition without auth checks (for executors that run other workflows of the same namespace).

func (*Engine) WorkflowDefinitions

func (e *Engine) WorkflowDefinitions(ctx context.Context, namespace string) ([]*models.Workflow, error)

WorkflowDefinitions lists workflow definitions of a namespace without auth checks (for trigger routing).

type Event

type Event struct {
	Type      EventType
	Namespace string
	Execution *models.Execution
	Step      *models.ExecutionStep
	Workflow  *models.Workflow
	Metadata  map[string]interface{}
}

Event represents a workflow event

type EventBus

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

EventBus manages event handlers

func NewEventBus

func NewEventBus() *EventBus

func (*EventBus) Emit

func (eb *EventBus) Emit(ctx context.Context, event Event)

Emit sends event to all registered handlers (async, non-blocking)

func (*EventBus) EmitSync

func (eb *EventBus) EmitSync(ctx context.Context, event Event) []error

EmitSync sends event synchronously (blocking, waits for all handlers)

func (*EventBus) RegisterGlobalHandler

func (eb *EventBus) RegisterGlobalHandler(handler EventHandler)

RegisterGlobalHandler adds a handler for ALL known event types.

func (*EventBus) RegisterHandler

func (eb *EventBus) RegisterHandler(eventType EventType, handler EventHandler)

RegisterHandler adds an event handler for specific event type

type EventHandler

type EventHandler interface {
	HandleEvent(ctx context.Context, event Event) error
}

EventHandler is the interface for handling workflow events

type EventType

type EventType string

EventType represents different workflow events

const (
	EventTypeWorkflowStarted       EventType = "workflow.started"
	EventTypeWorkflowCompleted     EventType = "workflow.completed"
	EventTypeWorkflowFailed        EventType = "workflow.failed"
	EventTypeWorkflowCancelled     EventType = "workflow.cancelled"
	EventTypeStepStarted           EventType = "step.started"
	EventTypeStepCompleted         EventType = "step.completed"
	EventTypeStepFailed            EventType = "step.failed"
	EventTypeStepRetrying          EventType = "step.retrying"
	EventTypeStepWaitingSignal     EventType = "step.waiting_signal"
	EventTypeStepWaitingHuman      EventType = "step.waiting_human"
	EventTypeSignalReceived        EventType = "signal.received"
	EventTypeTaskClaimed           EventType = "task.claimed"
	EventTypeTaskCompleted         EventType = "task.completed"
	EventTypeCompensationTriggered EventType = "compensation.triggered"
	EventTypeRollbackStarted       EventType = "rollback.started"
	EventTypeScheduleCreated       EventType = "schedule.created"
	EventTypeScheduleUpdated       EventType = "schedule.updated"
	EventTypeSchedulePaused        EventType = "schedule.paused"
	EventTypeScheduleResumed       EventType = "schedule.resumed"
	EventTypeScheduleDeleted       EventType = "schedule.deleted"
	EventTypeScheduleFired         EventType = "schedule.fired"
	EventTypeScheduleFireFailed    EventType = "schedule.fire_failed"
)

func AllEventTypes

func AllEventTypes() []EventType

AllEventTypes lists every known event type (for global handlers).

type Graph

type Graph struct {
	Nodes        map[string]models.Node
	Edges        map[string][]models.Edge // source -> outgoing edges
	InDegree     map[string]int           // target -> number of incoming edges
	Predecessors map[string][]string      // target -> list of parent node IDs
}

Graph represents the structure of the workflow

func NewGraph

func NewGraph(wf *models.Workflow) (*Graph, error)

NewGraph builds a graph from workflow definition

func (*Graph) GetInitialNodes

func (g *Graph) GetInitialNodes() []string

GetInitialNodes returns nodes with no predecessors

func (*Graph) GetNextNodes

func (g *Graph) GetNextNodes(nodeID string) []string

GetNextNodes returns direct children of the given node (standard routing)

func (*Graph) GetNextNodesWithBranch

func (g *Graph) GetNextNodesWithBranch(nodeID string, output string) []string

GetNextNodesWithBranch returns children based on output branch (intelligent routing)

func (*Graph) Validate

func (g *Graph) Validate() error

Validate checks for cycles in the graph

type HostHooks

type HostHooks = EventHandler

HostHooks is an alias for sync host integration (WS, notifications).

type InputBuilder

type InputBuilder interface {
	BuildInput(inputs []PortInput) (string, error)
}

InputBuilder is implemented by executors that need per-edge input (e.g. n8n Merge with two inputs). When implemented, the engine passes every active incoming edge instead of its default aggregation, and does not merge execution variables into the input.

type NodeExecutor

type NodeExecutor interface {
	Execute(ctx context.Context, config map[string]interface{}, input string) (string, error)
	Validate(config map[string]interface{}) error
}

NodeExecutor defines the interface for a node's logic

type PermanentError

type PermanentError interface {
	error
	Permanent() bool
}

PermanentError can be implemented by executor errors that must not be retried (e.g. a blocked destination or invalid input). The step fails immediately instead of going through the retry policy.

type PortInput

type PortInput struct {
	FromNode string          `json:"fromNode"`
	FromPort string          `json:"fromPort"`
	ToPort   int             `json:"toPort"`
	Data     json.RawMessage `json:"data"`
}

PortInput is the data delivered to a node over one active incoming edge.

type Registry

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

Registry holds the map of available node executors and functions

func NewRegistry

func NewRegistry() *Registry

func (*Registry) Get

func (r *Registry) Get(nodeType string) (NodeExecutor, error)

func (*Registry) GetFunction

func (r *Registry) GetFunction(name string) (func(context.Context, map[string]interface{}) (map[string]interface{}, error), bool)

GetFunction retrieves a registered function by name

func (*Registry) ListFunctions

func (r *Registry) ListFunctions() []string

ListFunctions returns all registered function names

func (*Registry) Register

func (r *Registry) Register(nodeType string, executor NodeExecutor)

func (*Registry) RegisterFunction

func (r *Registry) RegisterFunction(name string, handler func(ctx context.Context, input map[string]interface{}) (map[string]interface{}, error))

RegisterFunction registers a HandlerFunc as a function node executor

type TaskFilter

type TaskFilter = storage.TaskFilter

TaskFilter is re-exported conceptually via storage; engine uses storage.TaskFilter.

type Telemetry

type Telemetry struct{}

Telemetry bridge to Prometheus

func GetTelemetry

func GetTelemetry() *Telemetry

func (*Telemetry) IncFailed

func (t *Telemetry) IncFailed()

Keep legacy methods for basic worker support (mapped to default labels)

func (*Telemetry) IncProcessed

func (t *Telemetry) IncProcessed(namespace, nodeType string, status string)

func (*Telemetry) IncProcessedLegacy

func (t *Telemetry) IncProcessedLegacy()

func (*Telemetry) IncRetried

func (t *Telemetry) IncRetried()

func (*Telemetry) ObserveDuration

func (t *Telemetry) ObserveDuration(namespace, nodeType string, duration time.Duration)

func (*Telemetry) WorkerStarted

func (t *Telemetry) WorkerStarted(id string)

func (*Telemetry) WorkerStartedLegacy

func (t *Telemetry) WorkerStartedLegacy()

func (*Telemetry) WorkerStopped

func (t *Telemetry) WorkerStopped(id string)

func (*Telemetry) WorkerStoppedLegacy

func (t *Telemetry) WorkerStoppedLegacy()

type WaitUntilError

type WaitUntilError struct {
	At     time.Time
	Output string
}

WaitUntilError is returned by an executor that wants to pause until a point in time without blocking a worker: the step is stored as WAITING with Output already computed, and the timeout reaper completes it once At has passed (durable across restarts).

func (*WaitUntilError) Error

func (w *WaitUntilError) Error() string

type Worker

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

func NewWorker

func NewWorker(id string, engine *Engine, registry *Registry, interval time.Duration) *Worker

func (*Worker) SetConcurrency

func (w *Worker) SetConcurrency(n int)

SetConcurrency sets how many steps the worker runs in parallel (min 1).

func (*Worker) SetNamespace

func (w *Worker) SetNamespace(namespace string)

SetNamespace pins the worker to a specific namespace

func (*Worker) Start

func (w *Worker) Start(ctx context.Context)

Start runs the worker until ctx is cancelled. On shutdown it stops claiming new steps, cancels in-flight executors, releases their steps back to the queue (without consuming a retry attempt) and returns once they are done.

type WorkerOptions

type WorkerOptions struct {
	// Concurrency is the number of steps processed in parallel (default 1).
	Concurrency int
	// PollInterval is how long an idle worker waits before polling storage
	// again (default 100ms). A busy worker claims the next step immediately.
	PollInterval time.Duration
}

WorkerOptions tunes a worker.

Jump to

Keyboard shortcuts

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