flow

package module
v0.0.0-...-b8cd951 Latest Latest
Warning

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

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

Dgmos Flow

A workflow orchestration engine for Go applications. Provides DAG-based execution, distributed task processing, and durable state management.

Installation

go get github.com/dgmos/flow

All dependencies (database drivers, Redis client, etc.) are automatically installed.

Requirements

  • Go 1.23 or higher
  • MySQL 5.7+, PostgreSQL 12+, or Redis 6+ (optional - in-memory storage available)

Quick Start

package main

import (
    "context"
    "github.com/dgmos/flow"
    _ "github.com/go-sql-driver/mysql"
    "github.com/jmoiron/sqlx"
)

func main() {
    // Initialize storage
    db, _ := sqlx.Connect("mysql", "user:pass@tcp(localhost:3306)/db?parseTime=true")
    storage, _ := flow.NewMySQLStorage(db)
    
    // Create engine and registry
    registry := flow.NewRegistry()
    engine := flow.NewEngine(storage, registry)
    
    // Register function
    registry.RegisterFunction("ProcessData", func(ctx context.Context, input map[string]interface{}) (map[string]interface{}, error) {
        // Your logic here
        return map[string]interface{}{"status": "processed"}, nil
    })
    
    // Define workflow
    wf := flow.NewWorkflow("process-workflow", "Data Processing").
        AddNode("process", flow.NodeTypeFunction).
            WithConfig("function", "ProcessData").
        Build()
    
    // Register and execute
    ctx := context.Background()
    engine.RegisterWorkflow(ctx, "default", wf)
    
    // Start worker
    go engine.StartWorker(ctx, "default", "worker-1")
    
    // Execute workflow
    execID, _ := engine.Execute(ctx, "default", "process-workflow", []byte(`{"data":"value"}`))
    
    // Query status
    execution, _ := engine.GetExecution(ctx, "default", execID)
}

Storage Backends

MySQL
db, _ := sqlx.Connect("mysql", "user:pass@tcp(host:3306)/db?parseTime=true")
storage, _ := flow.NewMySQLStorage(db)

Database schema is created automatically on first connection.

PostgreSQL
db, _ := sqlx.Connect("postgres", "postgres://user:pass@host/db?sslmode=disable")
storage, _ := flow.NewPostgreSQLStorage(db)
Redis
storage := flow.NewRedisStorage("localhost:6379", "", 0)
In-Memory
storage := flow.NewMemoryStorage()

Suitable for development and testing.

API Reference

Engine
engine := flow.NewEngine(storage, registry)
engine.WithLogger(logger)
engine.RegisterWorkflow(ctx, namespace, workflow)
engine.Execute(ctx, namespace, workflowID, input)
engine.GetExecution(ctx, namespace, executionID)
engine.GetExecutionSteps(ctx, namespace, executionID)
engine.CancelExecution(ctx, namespace, executionID)
engine.FailExecution(ctx, namespace, executionID, message)
engine.SignalExecution(ctx, namespace, executionID, nodeID, data)
engine.StartWorker(ctx, namespace, workerID)
Registry
registry := flow.NewRegistry()
registry.RegisterFunction(name, handlerFunc)
registry.Register(nodeType, executor)
Workflow Builder
wf := flow.NewWorkflow(id, name).
    AddNode(nodeID, nodeType).
        WithConfig(key, value).
        WithRetry(count).
        WithSaga(compensateNodeID).
    Connect(sourceID, targetID).
    ConnectIf(sourceID, targetID, condition).
    Build()
Worker
worker := flow.NewWorker(workerID, engine, registry, interval)
worker.SetNamespace(namespace)
worker.SetConcurrency(16) // run up to 16 steps in parallel (default 1)
worker.Start(ctx)         // blocks until ctx is cancelled

// or
go engine.StartWorkerWithOptions(ctx, "default", "worker-1", flow.WorkerOptions{
    Concurrency:  16,
    PollInterval: 100 * time.Millisecond, // idle polling; busy workers claim immediately
})

On shutdown (cancel ctx) the worker stops claiming, cancels in-flight steps, puts them back to PENDING without consuming a retry attempt, and returns once they are released.

Node Types

Built-in node types are automatically registered:

  • function - Execute registered Go functions
  • http - HTTP requests
  • condition - Conditional branching
  • log - Logging
  • transform - Data transformation
  • signal - Wait for external signals
  • subworkflow - Nested workflows
  • ai - LLM API calls
  • notify - Notifications
  • switch - Multi-way branching
  • wait - Delay execution
  • setvariable - Context manipulation

n8n Workflows

Import and run n8n workflow exports and templates. Every n8n node becomes a durable engine step; expressions, items, paired items, loops, sub-workflows, AI agents (OpenAI, Anthropic, Gemini, …), RAG (Qdrant, Pinecone, Supabase) and 90+ integrations are supported. On the 299 most-viewed public templates, all import and run: 297 fully, and 2 contain unfilled placeholders that make one node fail, exactly as in n8n. The importer reports exactly what is missing for any workflow.

eng.EnableN8N(flow.N8NOptions{Credentials: myVault})
res, err := eng.InstallN8NWorkflow(ctx, "default", workflowJSON, flow.N8NInstallOptions{})
http.Handle("/n8n/", http.StripPrefix("/n8n", eng.N8NHandler(flow.N8NHandlerOptions{Namespace: "default"})))

See docs/n8n.md for the full guide (supported nodes, endpoints, credentials, security).

Configuration

Retry Policy
node := flow.Node{
    ID: "task",
    Type: flow.NodeTypeFunction,
    RetryPolicy: &flow.RetryPolicy{
        MaxAttempts:        5,
        InitialInterval:    time.Second,
        BackoffCoefficient: 2.0,
        MaximumInterval:    time.Minute,
    },
}

MaxAttempts is the number of retries after the first failure. The delay before retry n is InitialInterval * BackoffCoefficient^(n-1), capped at MaximumInterval.

Errors that can never succeed are not retried: return an error implementing flow.PermanentError (Permanent() bool) from a custom node to fail the step immediately. Outbound policy violations and invalid node config are permanent.

Step Timeout

Any node can set execution_timeout (Go duration). The executor's context is cancelled when it expires and the attempt fails (and is retried per policy):

builder.AddNode("call", flow.NodeTypeHTTP).
    WithConfig("url", "https://api.example.com/slow").
    WithConfig("execution_timeout", "45s")
Outbound Network Policy (SSRF protection)

The http and notify nodes may only reach public internet addresses by default. Loopback, private (RFC 1918 / ULA), link-local (including the 169.254.169.254 cloud metadata endpoint) and CGNAT ranges are blocked; the check runs on the resolved IP for every connection, so redirects and DNS rebinding cannot bypass it. Only http/https URLs are allowed, responses are capped at 10 MiB, and environment proxy settings are ignored.

To reach internal services, allow them explicitly:

engine.SetOutboundPolicy(flow.OutboundPolicy{
    AllowedHosts:     []string{"billing.internal", "10.20.0.0/16"},
    MaxResponseBytes: 50 << 20, // 50 MiB; -1 = unlimited
    Timeout:          time.Minute,
})

// or, only when every workflow definition is fully trusted:
engine.SetOutboundPolicy(flow.OutboundPolicy{AllowPrivateNetworks: true})

Blocked requests fail with flow.ErrDestinationBlocked (errors.Is).

Compensation (Saga Pattern)
builder.AddNode("charge", flow.NodeTypeFunction).
    WithSaga("refund")
Encryption
// Key must be 32 bytes encoded as 64 hex characters
crypto, _ := flow.NewCrypto("0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef")
storage.(*sql.SQLStorage).SetEncryption(crypto)

Triggers

Cron
_ = engine.CronManager.Start(ctx)
id, _ := engine.CronManager.AddScheduleWithOpts(ctx, namespace, workflowID, "0 0 9 * * *", input, flow.ScheduleOpts{
    Name: "daily-backup", Timezone: "Europe/Istanbul", CatchUp: true,
})
expr := "0 30 9 * * *"
_ = engine.CronManager.UpdateSchedule(ctx, namespace, id, flow.ScheduleUpdateOpts{CronExpression: &expr})
_ = engine.CronManager.PauseSchedule(ctx, namespace, id)  // soft disable
_ = engine.CronManager.RemoveSchedule(ctx, namespace, id) // hard delete
api := flow.NewAPIManager(webhookMgr).WithCron(engine.CronManager)

Multi-replica safe (atomic fire claim). Pause = soft disable; DELETE = hard remove. Table: schedules (or {prefix}schedules).

Webhooks
webhookMgr := flow.NewWebhookManager(engine)
http.Handle("/webhooks/", webhookMgr)
REST API
apiMgr := flow.NewAPIManager(webhookMgr)
http.Handle("/", apiMgr)

Endpoints:

  • GET /health - Health check
  • GET /metrics - Prometheus metrics
  • GET /api/{namespace}/executions - List executions
  • GET /api/{namespace}/executions/{id} - Get execution
  • GET /api/{namespace}/executions/{id}/steps - Get execution steps
  • POST /api/{namespace}/executions/{id}/cancel - Cancel execution
  • POST /api/{namespace}/executions/{id}/signal/{nodeID} - Send signal
  • POST /api/{namespace}/executions/{id}/rollback - Start saga rollback
  • POST /api/{namespace}/executions/{id}/tasks/{nodeId}/claim|complete|advance - Human tasks
  • GET /api/{namespace}/tasks - List waiting human tasks

Events

Engine emits lifecycle events via SetHostHooks (sync) and/or SetEventBus.

engine.SetHostHooks(handler) // WS / notification bridge

eventBus := flow.NewEventBus()
eventBus.RegisterHandler(flow.EventWorkflowCompleted, handler)
eventBus.RegisterGlobalHandler(handler)
engine.SetEventBus(eventBus)

Event types include:

  • EventWorkflowStarted / Completed / Failed / Cancelled
  • EventStepStarted / Completed / Failed / Retrying
  • EventStepWaitingSignal / EventStepWaitingHuman
  • EventSignalReceived / EventTaskClaimed / EventTaskCompleted
  • EventCompensationTriggered / EventRollbackStarted

Interactive & Human Tasks

_, next, err := engine.CompleteTask(ctx, ns, execID, "approve", "user-1", "approve", `{"note":"ok"}`)
out, next, err := engine.Advance(ctx, ns, execID, "step-2", "submit", `{}`)
tasks, _ := engine.ListTasks(ctx, ns, flow.TaskFilter{Assignee: "user-1"})

Variables

_ = engine.MergeVars(ctx, ns, execID, map[string]interface{}{"process_data": data})

Authorization

Dgmos Flow provides a flexible, pluggable authorization system. Bring your own auth!

Recommended resources: workflow:{ns}:{id}, execution:{ns}:{id}, task:{ns}:{stepId}.

Interface
type AuthProvider interface {
    CheckAccess(ctx context.Context, resource string, action string) error
}
Usage
1. No Auth (Development)
engine := flow.NewEngine(storage, registry)
// No auth provider set - everything is allowed
2. Simple Custom Auth
type MyAuth struct{}

func (a *MyAuth) CheckAccess(ctx context.Context, resource string, action string) error {
    userID := ctx.Value("user_id").(string)
    
    // Your custom logic
    if userID == "" {
        return errors.New("unauthorized")
    }
    
    // Check permissions in your database, Firebase, Auth0, etc.
    return nil
}


engine := flow.NewEngine(storage, registry)
engine.SetAuthProvider(&MyAuth{})
3. Multi-Tenant with Customer Isolation
type MultiTenantAuth struct{}

func (a *MultiTenantAuth) CheckAccess(ctx context.Context, resource string, action string) error {
    customerID := ctx.Value("customer_id").(string)
    userID := ctx.Value("user_id").(string)
    role := ctx.Value("role").(string)
    
    // Get workflow metadata
    workflow := getWorkflowFromDB(resource)
    
    // CRITICAL: Tenant isolation
    if workflow.Metadata["customer_id"] != customerID {
        return errors.New("forbidden: wrong tenant")
    }
    
    // Admin can do anything
    if role == "admin" {
        return nil
    }
    
    // Owner can do anything
    if workflow.Metadata["owner_id"] == userID {
        return nil
    }
    
    // Check visibility
    if workflow.Metadata["visibility"] == "organization" {
        if action == "view" || action == "execute" {
            return nil
        }
    }
    
    return errors.New("forbidden")
}

engine.SetAuthProvider(&MultiTenantAuth{})
4. Store Auth Metadata in Workflows
wf := &flow.Workflow{
    ID:   "my-workflow",
    Name: "My Workflow",
    Metadata: map[string]interface{}{
        // Use ANY field names you want - we don't enforce structure
        "customer_id": "acme-corp",     // Multi-tenant isolation
        "user_id":     "user-123",      // Owner
        "owner":       "john@acme.com", // Email-based
        "slug":        "acme/my-wf",    // Slug-based
        "team_id":     "eng-team",      // Team access
        "visibility":  "organization",  // Visibility level
        
        // Or use your own auth system fields
        "firebase_uid": "abc123",
        "auth0_org":    "org_xyz",
    },
}

// Add auth context when registering
ctx = context.WithValue(ctx, "customer_id", "acme-corp")
ctx = context.WithValue(ctx, "user_id", "user-123")
engine.RegisterWorkflow(ctx, "default", wf)
Actions

Common actions (you can define your own):

  • "create" - Create/register workflow
  • "view" - View workflow definition
  • "execute" - Trigger execution
  • "edit" - Modify workflow
  • "delete" - Delete workflow
Key Principles
  1. Fully pluggable - Use any auth system (Firebase, Auth0, custom DB, etc.)
  2. No prescribed structure - Use user_id, userId, email, slug, or whatever you want
  3. Context-based - Pass auth info via context.Context
  4. Metadata is flexible - Store any auth-related data in workflow.Metadata
Complete Example

See examples/auth/ for a full multi-tenant implementation with:

  • Customer/tenant isolation
  • Role-based access control (admin, user, viewer)
  • Team-based visibility
  • Organization-wide workflows

Monitoring

Prometheus Metrics
import "github.com/prometheus/client_golang/prometheus/promhttp"

http.Handle("/metrics", promhttp.Handler())

Available metrics:

  • workflows_started_total
  • workflows_completed_total
  • workflows_failed_total
  • steps_processed_total
  • step_duration_seconds
  • active_workers
Logging
import "log/slog"

logger := slog.New(slog.NewJSONHandler(os.Stdout, nil))
engine.WithLogger(logger)

Testing

# Unit tests (default)
go test

# Unit tests with coverage
go test -cover

# Race detector
go test -race

# Integration / E2E (requires Docker: MySQL, PostgreSQL, Redis)
bash scripts/test-integration.sh
# or manually:
# docker compose up -d mysql postgres redis
# go test -tags=integration ./... -timeout=10m

# Full local suite (unit + stability + benchmarks)
bash scripts/test-full.sh

Examples

See examples/ directory for complete working examples:

  • examples/auth/ - Multi-tenant authorization
  • examples/interactive_approval/ - Human task approval flow

Database Schema

Tables are created automatically when using SQL storage backends:

  • workflows - Workflow definitions
  • executions - Workflow execution instances (includes variables)
  • execution_steps - Individual task states (includes task_meta)
  • compensation_journal - Saga/rollback audit trail
  • schedules - Durable cron schedules

Indexes are optimized for:

  • Namespace-based queries
  • Status filtering
  • Worker task claims
  • Execution lookups

Concurrency Model

  • Workers claim tasks using database-level locking (SKIP LOCKED)
  • Multiple workers can run concurrently across different processes/hosts
  • Running tasks hold a lease that the worker renews every 30s; a task is reassigned only after its lease has been silent for 5 minutes (worker crash), so long-running tasks are not executed twice
  • Join nodes (multiple incoming edges) are scheduled exactly once, even when parallel branches finish at the same time
  • No message broker required - coordination through storage backend

Error Handling

  • Failed tasks can be retried with configurable policies
  • Saga pattern supported for compensation logic
  • Workflow status tracked: PENDING, RUNNING, COMPLETED, FAILED, CANCELLED
  • Task status tracked: PENDING, RUNNING, COMPLETED, FAILED, SKIPPED, WAITING, CANCELLED

License

MIT License. See LICENSE file.

Contributing

See CONTRIBUTING.md for guidelines.

Documentation

Full API documentation: https://pkg.go.dev/github.com/dgmos/flow

Documentation

Overview

Package flow provides a high-performance workflow orchestration engine for Go.

Quick Start with MySQL:

import (
    "github.com/dgmos/flow"
    _ "github.com/go-sql-driver/mysql"
    "github.com/jmoiron/sqlx"
)

func main() {
    // Connect to MySQL
    db, _ := sqlx.Connect("mysql", "user:pass@tcp(localhost:3306)/db?parseTime=true")

    // Create storage (auto-creates tables!)
    storage, _ := flow.NewMySQLStorage(db)

    // Create engine
    registry := flow.NewRegistry()
    engine := flow.NewEngine(storage, registry)

    // Register your functions
    registry.RegisterFunction("MyTask", func(ctx context.Context, input map[string]interface{}) (map[string]interface{}, error) {
        return map[string]interface{}{"status": "done"}, nil
    })

    // Start worker
    go engine.StartWorker(ctx, "default", "worker-1")

    // Execute workflow
    execID, _ := engine.Execute(ctx, "default", "my-workflow", `{"key":"value"}`)
}

Index

Constants

View Source
const (
	NodeTypeFunction    = "function"
	NodeTypeHTTP        = "http"
	NodeTypeCondition   = "condition"
	NodeTypeLog         = "log"
	NodeTypeTransform   = "transform"
	NodeTypeSignal      = "signal"
	NodeTypeSubWorkflow = "subworkflow"
	NodeTypeAI          = "ai"
	NodeTypeNotify      = "notify"
	NodeTypeSwitch      = "switch"
	NodeTypeWait        = "wait"
	NodeTypeSetVariable = "setvariable"
	NodeTypeHumanTask   = "humantask"
)

Node types (use these strings in Node.Type field)

View Source
const (
	WorkflowActive   = models.WorkflowActive
	WorkflowInactive = models.WorkflowInactive
)

Workflow statuses

View Source
const (
	StatusPending   = models.TaskPending
	StatusRunning   = models.TaskRunning
	StatusCompleted = models.TaskCompleted
	StatusFailed    = models.TaskFailed
	StatusSkipped   = models.TaskSkipped
	StatusWaiting   = models.TaskWaiting
	StatusCancelled = models.TaskCancelled
)

Task/Execution statuses

View Source
const (
	ClaimAny   = models.ClaimAny
	ClaimAll   = models.ClaimAll
	ClaimFirst = models.ClaimFirst
)

Claim mode constants

View Source
const (
	EventWorkflowStarted       = engine.EventTypeWorkflowStarted
	EventWorkflowCompleted     = engine.EventTypeWorkflowCompleted
	EventWorkflowFailed        = engine.EventTypeWorkflowFailed
	EventWorkflowCancelled     = engine.EventTypeWorkflowCancelled
	EventStepStarted           = engine.EventTypeStepStarted
	EventStepCompleted         = engine.EventTypeStepCompleted
	EventStepFailed            = engine.EventTypeStepFailed
	EventStepRetrying          = engine.EventTypeStepRetrying
	EventStepWaitingSignal     = engine.EventTypeStepWaitingSignal
	EventStepWaitingHuman      = engine.EventTypeStepWaitingHuman
	EventSignalReceived        = engine.EventTypeSignalReceived
	EventTaskClaimed           = engine.EventTypeTaskClaimed
	EventTaskCompleted         = engine.EventTypeTaskCompleted
	EventCompensationTriggered = engine.EventTypeCompensationTriggered
	EventRollbackStarted       = engine.EventTypeRollbackStarted
	EventScheduleCreated       = engine.EventTypeScheduleCreated
	EventScheduleUpdated       = engine.EventTypeScheduleUpdated
	EventSchedulePaused        = engine.EventTypeSchedulePaused
	EventScheduleResumed       = engine.EventTypeScheduleResumed
	EventScheduleDeleted       = engine.EventTypeScheduleDeleted
	EventScheduleFired         = engine.EventTypeScheduleFired
	EventScheduleFireFailed    = engine.EventTypeScheduleFireFailed
)

Event types

View Source
const N8NTriggerKey = n8n.TriggerKey

N8NTriggerKey selects the trigger that starts an execution of an imported workflow: Execute(ctx, ns, id, []byte(`{"__trigger": "Schedule Trigger"}`)). Without it the workflow's default trigger runs.

Variables

View Source
var (
	ErrDestinationBlocked = node.ErrDestinationBlocked
	ErrResponseTooLarge   = node.ErrResponseTooLarge
)

Errors returned by http/notify nodes when the OutboundPolicy is violated. They are permanent: the step fails without retries.

View Source
var (
	WorkflowsStarted   = telemetry.WorkflowsStarted
	WorkflowsCompleted = telemetry.WorkflowsCompleted
	WorkflowsFailed    = telemetry.WorkflowsFailed
	StepsProcessed     = telemetry.StepsProcessed
	StepDuration       = telemetry.StepDuration
	ActiveWorkers      = telemetry.ActiveWorkers
	SchedulesActive    = telemetry.SchedulesActive
	ScheduleFires      = telemetry.ScheduleFires
)

Prometheus metrics (pre-registered)

View Source
var ErrN8NNotRunnable = errors.New("n8n workflow uses unsupported features")

ErrN8NNotRunnable is returned by InstallN8NWorkflow when the workflow uses unsupported features and AllowPartial is false.

View Source
var ErrN8NWebhookConflict = errors.New("webhook path is already used by another workflow")

ErrN8NWebhookConflict is returned when another workflow already serves a webhook path the imported workflow wants.

Functions

func ImportN8NWorkflow

func ImportN8NWorkflow(data []byte, opts N8NImportOptions) (*Workflow, *N8NReport, error)

ImportN8NWorkflow converts an n8n workflow export (or a template from the n8n template API) into a Workflow and reports unsupported nodes, required credentials and triggers. It does not register the workflow.

func MetricsRegistry

func MetricsRegistry() prometheus.Registerer

MetricsRegistry returns the default Prometheus registerer.

func N8NNodeSupported

func N8NNodeSupported(nodeType string) bool

N8NNodeSupported reports whether an n8n node type is implemented.

func ToMermaid

func ToMermaid(wf *Workflow) string

ToMermaid generates a Mermaid.js diagram from a workflow

Types

type APIManager

type APIManager struct {
	*trigger.APIManager
}

APIManager provides REST API for workflow management

func NewAPIManager

func NewAPIManager(webhookMgr *WebhookManager) *APIManager

NewAPIManager creates a REST API handler.

Example:

apiMgr := flow.NewAPIManager(webhookMgr).WithCron(engine.CronManager)
http.Handle("/", apiMgr)

Endpoints:

  • GET /health
  • GET /metrics (Prometheus)
  • GET /api/{namespace}/executions
  • GET /api/{namespace}/executions/{id}
  • GET /api/{namespace}/executions/{id}/steps
  • POST /api/{namespace}/executions/{id}/cancel
  • POST /api/{namespace}/executions/{id}/signal/{nodeID}
  • POST /api/{namespace}/executions/{id}/rollback
  • POST /api/{namespace}/executions/{id}/tasks/{nodeId}/claim|release|complete|advance
  • GET /api/{namespace}/tasks
  • GET|POST /api/{namespace}/schedules
  • GET|PUT|DELETE /api/{namespace}/schedules/{id}
  • POST /api/{namespace}/schedules/{id}/pause|resume
  • POST /api/{namespace}/schedules/preview

func (*APIManager) ServeHTTP

func (a *APIManager) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP handles API requests

func (*APIManager) WithCron

func (a *APIManager) WithCron(c *CronManager) *APIManager

WithCron enables schedule management REST endpoints.

type AuthProvider

type AuthProvider = auth.AuthProvider

AuthProvider is the pluggable authorization interface.

type CompensationRecord

type CompensationRecord = models.CompensationRecord

CompensationRecord audits saga/rollback activity.

type CronManager

type CronManager struct {
	*trigger.CronManager
}

CronManager manages scheduled workflow execution

func NewCronManager

func NewCronManager(eng *Engine, store Storage, logger *slog.Logger) *CronManager

NewCronManager creates a durable cron scheduler backed by storage.

Example:

cronMgr := flow.NewCronManager(engine, storage, logger)
_ = cronMgr.Start(ctx)
id, _ := cronMgr.AddSchedule(ctx, "default", "backup-workflow", "0 0 2 * * *", `{"type":"daily"}`)

func (*CronManager) AddSchedule

func (c *CronManager) AddSchedule(ctx context.Context, namespace, workflowID, cronExpr, input string) (string, error)

AddSchedule persists and registers a cron trigger; returns durable schedule ID.

func (*CronManager) AddScheduleWithOpts

func (c *CronManager) AddScheduleWithOpts(ctx context.Context, namespace, workflowID, cronExpr, input string, opts ScheduleOpts) (string, error)

AddScheduleWithOpts is AddSchedule with CatchUp and related options.

func (*CronManager) GetSchedule

func (c *CronManager) GetSchedule(ctx context.Context, namespace, scheduleID string) (*Schedule, error)

GetSchedule returns a durable schedule definition.

func (*CronManager) ListSchedules

func (c *CronManager) ListSchedules(ctx context.Context, namespace string) ([]*Schedule, error)

ListSchedules lists schedules for a tenant namespace.

func (*CronManager) ListSchedulesFiltered

func (c *CronManager) ListSchedulesFiltered(ctx context.Context, namespace string, filter ScheduleListFilter) ([]*Schedule, error)

ListSchedulesFiltered lists schedules with optional filters.

func (*CronManager) PauseSchedule

func (c *CronManager) PauseSchedule(ctx context.Context, namespace, scheduleID string) error

PauseSchedule soft-disables a schedule without deleting it.

func (*CronManager) PreviewNextRuns

func (c *CronManager) PreviewNextRuns(cronExpr, timezone string, n int) ([]time.Time, error)

PreviewNextRuns returns upcoming fire times for a cron expression (UI helper).

func (*CronManager) RemoveSchedule

func (c *CronManager) RemoveSchedule(ctx context.Context, namespace, scheduleID string) error

RemoveSchedule deletes a schedule from storage and unregisters it from memory.

func (*CronManager) ResumeSchedule

func (c *CronManager) ResumeSchedule(ctx context.Context, namespace, scheduleID string) error

ResumeSchedule reactivates a paused schedule.

func (*CronManager) SetAuthProvider

func (c *CronManager) SetAuthProvider(provider AuthProvider)

SetAuthProvider sets authorization checks for schedule operations.

func (*CronManager) SetEventBus

func (c *CronManager) SetEventBus(bus *EventBus)

SetEventBus wires schedule.* lifecycle events.

func (*CronManager) SetHostHooks

func (c *CronManager) SetHostHooks(h EventHandler)

SetHostHooks wires sync host integration for schedule events.

func (*CronManager) Start

func (c *CronManager) Start(ctx context.Context) error

Start loads active schedules from storage and begins the cron runner.

func (*CronManager) Stop

func (c *CronManager) Stop()

Stop halts the cron scheduler

func (*CronManager) UpdateSchedule

func (c *CronManager) UpdateSchedule(ctx context.Context, namespace, scheduleID string, patch ScheduleUpdateOpts) error

UpdateSchedule applies a partial patch to an existing schedule.

type Crypto

type Crypto = storage.Crypto

Crypto provides data-at-rest encryption

func NewCrypto

func NewCrypto(key string) (*Crypto, error)

NewCrypto creates a new encryption instance

Example:

crypto, _ := flow.NewCrypto("your-32-byte-encryption-key-here")
sqlStorage.(*sql.SQLStorage).SetEncryption(crypto)

type Edge

type Edge = models.Edge

type Engine

type Engine struct {
	*engine.Engine
	CronManager *CronManager
	// contains filtered or unexported fields
}

Engine is the workflow execution engine

func NewEngine

func NewEngine(storage Storage, registry *Registry) *Engine

NewEngine creates a new workflow engine

func (*Engine) Advance

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

Advance interactively completes a waiting/interactive step.

func (*Engine) CancelExecution

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

CancelExecution cancels a running execution

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 claims a human task for an actor.

func (*Engine) CompleteTask

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

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

func (*Engine) EnableN8N

func (e *Engine) EnableN8N(opts N8NOptions) *Engine

EnableN8N registers the n8n node types with this engine. Call it once, before registering or running imported workflows.

func (*Engine) Execute

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

Execute starts a new workflow execution (alias for StartWorkflow)

func (*Engine) FailExecution

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

FailExecution marks an execution as failed

func (*Engine) GetExecution

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

GetExecution retrieves an execution by ID

func (*Engine) GetExecutionStatus

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

GetExecutionStatus retrieves an execution's status

func (*Engine) GetExecutionSteps

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

GetExecutionSteps retrieves all steps for an execution

func (*Engine) GetLogger

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

GetLogger returns the engine's 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 execution variables.

func (*Engine) InstallN8NWorkflow

func (e *Engine) InstallN8NWorkflow(ctx context.Context, namespace string, data []byte, opts N8NInstallOptions) (*N8NInstallResult, error)

InstallN8NWorkflow imports, registers and activates an n8n workflow: schedule triggers become durable schedules (requires the CronManager to be started), webhook/chat/form triggers are served by N8NHandler.

func (*Engine) ListCompensationJournal

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

ListCompensationJournal lists compensation/rollback records.

func (*Engine) ListExecutions

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

ListExecutions lists all executions in a namespace.

func (*Engine) ListTasks

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

ListTasks lists WAITING human/interactive tasks.

func (*Engine) MergeVars

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

MergeVars merges into durable execution variables.

func (*Engine) N8NHandler

func (e *Engine) N8NHandler(opts N8NHandlerOptions) http.Handler

N8NHandler serves the entry points of imported workflows in a namespace: /webhook/{path} (Webhook, Telegram/WhatsApp triggers), /chat/{workflowID} and /form/{workflowID}. Mount it under a prefix, e.g.

http.Handle("/n8n/", http.StripPrefix("/n8n", engine.N8NHandler(flow.N8NHandlerOptions{Namespace: "default"})))

func (*Engine) ReapTimeouts

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

ReapTimeouts checks for and handles timed-out tasks

func (*Engine) RegisterWorkflow

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

RegisterWorkflow saves a workflow definition

func (*Engine) ReleaseTask

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

ReleaseTask releases a claimed human task.

func (*Engine) RollbackTo

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

RollbackTo journals and enqueues compensation toward a node.

func (*Engine) SetAuthProvider

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

SetAuthProvider sets authorization for the engine and CronManager.

func (*Engine) SetEventBus

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

SetEventBus replaces the engine event bus and rewires CronManager.

func (*Engine) SetHostHooks

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

SetHostHooks wires a synchronous host integration handler (e.g. WebSocket bridge).

func (*Engine) SetOutboundPolicy

func (e *Engine) SetOutboundPolicy(p OutboundPolicy) *Engine

SetOutboundPolicy replaces the network policy of the built-in "http" and "notify" nodes registered by NewEngine. By default they may only reach public internet addresses (SSRF protection); use AllowedHosts or AllowPrivateNetworks to reach internal services.

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) SignalExecution

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

SignalExecution sends a signal to resume a waiting workflow

func (*Engine) StartWorker

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

StartWorker starts a worker that processes tasks one at a time. It blocks until ctx is cancelled; in-flight steps are released back to the queue on shutdown.

func (*Engine) StartWorkerWithOptions

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

StartWorkerWithOptions starts a worker with custom concurrency and polling.

go engine.StartWorkerWithOptions(ctx, "default", "worker-1", flow.WorkerOptions{Concurrency: 16})

func (*Engine) StartWorkflow

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

StartWorkflow starts a new workflow execution

func (*Engine) WithLogger

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

WithLogger sets a custom logger for the engine and bound CronManager.

type Event

type Event = engine.Event

Event represents a workflow event

type EventBus

type EventBus struct {
	*engine.EventBus
}

EventBus manages event subscriptions

func NewEventBus

func NewEventBus() *EventBus

NewEventBus creates a new event bus

Example:

eventBus := flow.NewEventBus()
eventBus.RegisterHandler(flow.EventWorkflowCompleted, myHandler)

func (*EventBus) Emit

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

Emit emits an event asynchronously

func (*EventBus) EmitSync

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

EmitSync emits an event synchronously

func (*EventBus) RegisterGlobalHandler

func (eb *EventBus) RegisterGlobalHandler(handler EventHandler)

RegisterGlobalHandler registers a handler for all events

func (*EventBus) RegisterHandler

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

RegisterHandler registers a handler for a specific event type

type EventHandler

type EventHandler = engine.EventHandler

EventHandler handles workflow events

type EventType

type EventType = engine.EventType

EventType represents workflow event types

type Execution

type Execution = models.Execution

type ExecutionStep

type ExecutionStep = models.ExecutionStep

type Graph

type Graph = engine.Graph

Graph represents the DAG structure of a workflow

func NewGraph

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

NewGraph creates a new graph from a workflow

type HandlerFunc

type HandlerFunc func(ctx context.Context, input map[string]interface{}) (map[string]interface{}, error)

HandlerFunc is the signature for workflow functions

Example:

func ProcessOrder(ctx context.Context, input map[string]interface{}) (map[string]interface{}, error) {
    orderID := input["order_id"].(string)
    // ... process order ...
    return map[string]interface{}{"status": "processed"}, nil
}

type HostHooks

type HostHooks = engine.HostHooks

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

type LegacyStep

type LegacyStep = models.LegacyStep

LegacyStep describes a linear/legacy workflow step for ImportStepChain.

type N8NChatMemoryReplacer

type N8NChatMemoryReplacer = n8n.ChatMemoryReplacer

N8NChatMemoryReplacer is an optional extension of N8NChatMemoryStore used by the Chat Memory Manager's override and delete modes.

type N8NChatMemoryStore

type N8NChatMemoryStore = n8n.ChatMemoryStore

N8NChatMemoryStore stores AI chat history for memory nodes.

type N8NChatMessage

type N8NChatMessage = n8n.ChatMessage

N8NChatMessage is one stored chat turn.

type N8NCredentialProvider

type N8NCredentialProvider = n8n.CredentialProvider

N8NCredentialProvider resolves n8n credentials (back it with a vault).

type N8NCredentialRef

type N8NCredentialRef = n8n.CredentialRef

N8NCredentialRef identifies a credential referenced by an n8n node.

type N8NHandlerOptions

type N8NHandlerOptions = n8n.HandlerOptions

N8NHandlerOptions configures the n8n webhook/chat/form HTTP handler.

type N8NImportOptions

type N8NImportOptions = n8n.ImportOptions

N8NImportOptions configures ImportN8NWorkflow.

type N8NInstallOptions

type N8NInstallOptions struct {
	N8NImportOptions
	// AllowPartial registers the workflow even when the report has blocking
	// issues (nodes that are not supported fail when reached).
	AllowPartial bool
	// SkipSchedules does not create schedules for Schedule Trigger nodes.
	SkipSchedules bool
}

N8NInstallOptions configures InstallN8NWorkflow.

type N8NInstallResult

type N8NInstallResult struct {
	Workflow    *Workflow
	Report      *N8NReport
	ScheduleIDs []string
}

N8NInstallResult is returned by InstallN8NWorkflow.

type N8NIssue

type N8NIssue = n8n.Issue

N8NIssue is one finding of an N8NReport.

type N8NItem

type N8NItem = n8n.Item

N8NItem is one n8n data item.

func N8NOutputItems

func N8NOutputItems(output string) []N8NItem

N8NOutputItems decodes the items of an n8n step or execution output.

type N8NOptions

type N8NOptions = n8n.Options

N8NOptions configures the n8n runtime (credentials, outbound network policy, chat memory, timeouts, timezone).

type N8NPollStateStore

type N8NPollStateStore = n8n.PollStateStore

N8NPollStateStore persists polling trigger cursors.

type N8NPollStateSwapper

type N8NPollStateSwapper = n8n.PollStateSwapper

N8NPollStateSwapper is an optional extension of N8NPollStateStore that advances cursors atomically so overlapping polls never emit duplicates.

type N8NReport

type N8NReport = n8n.Report

N8NReport describes how well an n8n workflow is supported.

type N8NStaticCredentials

type N8NStaticCredentials = n8n.StaticCredentials

N8NStaticCredentials is an in-memory N8NCredentialProvider.

func NewN8NStaticCredentials

func NewN8NStaticCredentials() *N8NStaticCredentials

NewN8NStaticCredentials returns an empty in-memory credential store.

type N8NTrigger

type N8NTrigger = n8n.TriggerSpec

N8NTrigger describes one way an imported workflow can be started.

type Node

type Node = models.Node

type NodeBuilder

type NodeBuilder struct {
	*builder.NodeBuilder
}

NodeBuilder provides a fluent API for configuring nodes

func (*NodeBuilder) If

func (nb *NodeBuilder) If(targetID, condition string) *NodeBuilder

If creates a conditional connection

func (*NodeBuilder) Then

func (nb *NodeBuilder) Then(targetID string) *NodeBuilder

Then connects this node to the next node

func (*NodeBuilder) WithConfig

func (nb *NodeBuilder) WithConfig(key string, value interface{}) *NodeBuilder

WithConfig adds configuration to a node

func (*NodeBuilder) WithRetry

func (nb *NodeBuilder) WithRetry(count int) *NodeBuilder

WithRetry sets retry count

func (*NodeBuilder) WithSaga

func (nb *NodeBuilder) WithSaga(compensateNodeID string) *NodeBuilder

WithSaga sets a compensation node (saga pattern)

type NodeExecutor

type NodeExecutor = engine.NodeExecutor

NodeExecutor defines the interface for custom node types

type OutboundPolicy

type OutboundPolicy = node.OutboundPolicy

OutboundPolicy controls which network destinations the built-in http and notify nodes may reach, plus response size and timeout limits.

type PermanentError

type PermanentError = engine.PermanentError

PermanentError marks executor errors that should not be retried. Return an error implementing it from a custom node to skip the retry policy.

type Registry

type Registry struct {
	*engine.Registry
}

Registry manages workflow function handlers

func NewRegistry

func NewRegistry() *Registry

NewRegistry creates a new function registry

func (*Registry) Get

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

Get retrieves a registered executor by type

func (*Registry) Register

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

Register registers a custom node executor

func (*Registry) RegisterFunction

func (r *Registry) RegisterFunction(name string, handler HandlerFunc)

RegisterFunction registers a function handler

Example:

registry.RegisterFunction("SendEmail", func(ctx context.Context, input map[string]interface{}) (map[string]interface{}, error) {
    email := input["email"].(string)
    // Send email...
    return map[string]interface{}{"sent": true}, nil
})

type RetryPolicy

type RetryPolicy = models.RetryPolicy

type SQLStorageOptions

type SQLStorageOptions = sqlstore.Options

SQLStorageOptions configures table prefix and migrations.

type Schedule

type Schedule = models.Schedule

type ScheduleListFilter

type ScheduleListFilter = trigger.ScheduleListFilter

ScheduleListFilter filters ListSchedules results.

type ScheduleOpts

type ScheduleOpts = trigger.ScheduleOpts

ScheduleOpts configures optional schedule create behavior.

type ScheduleUpdateOpts

type ScheduleUpdateOpts = trigger.ScheduleUpdateOpts

ScheduleUpdateOpts is a partial update patch for schedules.

type Storage

type Storage = storage.Storage

Storage interface for persistence

func NewMemoryStorage

func NewMemoryStorage() Storage

NewMemoryStorage creates an in-memory storage backend (for development)

func NewMySQLStorage

func NewMySQLStorage(db *sqlx.DB) (Storage, error)

NewMySQLStorage creates a MySQL storage backend with auto-migration

func NewMySQLStorageWithOptions

func NewMySQLStorageWithOptions(db *sqlx.DB, opts SQLStorageOptions) (Storage, error)

NewMySQLStorageWithOptions creates MySQL storage with prefix / migrate options.

func NewPostgreSQLStorage

func NewPostgreSQLStorage(db *sqlx.DB) (Storage, error)

NewPostgreSQLStorage creates a PostgreSQL storage backend with auto-migration

func NewPostgreSQLStorageWithOptions

func NewPostgreSQLStorageWithOptions(db *sqlx.DB, opts SQLStorageOptions) (Storage, error)

NewPostgreSQLStorageWithOptions creates Postgres storage with options.

func NewRedisStorage

func NewRedisStorage(addr string, password string, db int) Storage

NewRedisStorage creates a Redis storage backend

Example:

storage := flow.NewRedisStorage("localhost:6379", "", 0)

func NewSQLStorageFromDB

func NewSQLStorageFromDB(db *sql.DB, dialect string, opts SQLStorageOptions) (Storage, error)

NewSQLStorageFromDB wraps database/sql.DB (dialect: "mysql" or "postgres").

type TaskFilter

type TaskFilter = engine.TaskFilter

TaskFilter filters ListTasks results.

type TaskStatus

type TaskStatus = models.TaskStatus

type WebhookManager

type WebhookManager struct {
	*trigger.WebhookManager
}

WebhookManager handles HTTP webhook triggers

func NewWebhookManager

func NewWebhookManager(eng *Engine) *WebhookManager

NewWebhookManager creates a webhook handler

Example:

webhookMgr := flow.NewWebhookManager(engine)
http.Handle("/webhooks/", webhookMgr)

POST /webhooks/{namespace}/{workflow_id} with JSON body to trigger workflows

func (*WebhookManager) ServeHTTP

func (w *WebhookManager) ServeHTTP(rw http.ResponseWriter, r *http.Request)

ServeHTTP handles webhook requests

type Worker

type Worker struct {
	*engine.Worker
}

Worker executes workflow tasks

func NewWorker

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

NewWorker creates a new worker instance

func (*Worker) SetConcurrency

func (w *Worker) SetConcurrency(n int)

SetConcurrency sets how many steps the worker runs in parallel.

func (*Worker) SetNamespace

func (w *Worker) SetNamespace(namespace string)

SetNamespace sets the worker's namespace

func (*Worker) Start

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

Start begins the worker's task processing loop

type WorkerOptions

type WorkerOptions = engine.WorkerOptions

WorkerOptions configures worker concurrency and polling.

type Workflow

type Workflow = models.Workflow

func ImportStepChain

func ImportStepChain(id, name string, steps []LegacyStep) (*Workflow, error)

ImportStepChain converts a linear/legacy step list into a Workflow DAG.

type WorkflowBuilder

type WorkflowBuilder struct {
	*builder.WorkflowBuilder
}

WorkflowBuilder provides a fluent API for building workflows

func NewWorkflow

func NewWorkflow(id, name string) *WorkflowBuilder

NewWorkflow creates a new workflow builder

Example:

wf := flow.NewWorkflow("order-processing", "Order Processing Workflow").
    AddNode("validate", flow.NodeTypeFunction).
        WithConfig("functionName", "ValidateOrder").
        Then("process").
    AddNode("process", flow.NodeTypeFunction).
        WithConfig("functionName", "ProcessOrder").
    Build()

func (*WorkflowBuilder) AddNode

func (b *WorkflowBuilder) AddNode(id, nodeType string) *NodeBuilder

AddNode adds a node to the workflow

func (*WorkflowBuilder) Build

func (b *WorkflowBuilder) Build() *Workflow

Build returns the completed workflow

func (*WorkflowBuilder) Connect

func (b *WorkflowBuilder) Connect(sourceID, targetID string) *WorkflowBuilder

Connect creates an edge between two nodes

func (*WorkflowBuilder) ConnectIf

func (b *WorkflowBuilder) ConnectIf(sourceID, targetID, condition string) *WorkflowBuilder

ConnectIf creates a conditional edge

func (*WorkflowBuilder) Visualize

func (b *WorkflowBuilder) Visualize() string

Visualize generates a Mermaid diagram of the workflow

type WorkflowStatus

type WorkflowStatus = models.WorkflowStatus

Directories

Path Synopsis
examples
auth command
n8n command
Command n8n runs n8n workflow exports on the flow engine.
Command n8n runs n8n workflow exports on the flow engine.
internal
n8n
Package n8n runs n8n workflow definitions on the flow engine.
Package n8n runs n8n workflow definitions on the flow engine.

Jump to

Keyboard shortcuts

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