-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathflow.go
More file actions
628 lines (533 loc) · 18.9 KB
/
flow.go
File metadata and controls
628 lines (533 loc) · 18.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
// Package flow provides a high-performance workflow orchestration engine for Go.
//
// Quick Start with MySQL:
//
// import (
// "github.com/parevo/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"}`)
// }
package flow
import (
"context"
"log/slog"
"net/http"
"time"
"github.com/jmoiron/sqlx"
"github.com/parevo/flow/internal/builder"
"github.com/parevo/flow/internal/engine"
"github.com/parevo/flow/internal/models"
"github.com/parevo/flow/internal/node"
"github.com/parevo/flow/internal/storage"
"github.com/parevo/flow/internal/storage/memory"
"github.com/parevo/flow/internal/storage/redis"
"github.com/parevo/flow/internal/storage/sql"
"github.com/parevo/flow/internal/telemetry"
"github.com/parevo/flow/internal/trigger"
"github.com/prometheus/client_golang/prometheus"
"github.com/robfig/cron/v3"
)
// ========================================
// CORE TYPES
// ========================================
// Engine is the workflow execution engine
type Engine struct {
*engine.Engine
}
// Registry manages workflow function handlers
type Registry struct {
*engine.Registry
}
// Storage interface for persistence
type Storage = storage.Storage
// Worker executes workflow tasks
type Worker struct {
*engine.Worker
}
// Graph represents the DAG structure of a workflow
type Graph = engine.Graph
// ========================================
// WORKFLOW MODELS
// ========================================
type (
Workflow = models.Workflow
Node = models.Node
Edge = models.Edge
Execution = models.Execution
ExecutionStep = models.ExecutionStep
RetryPolicy = models.RetryPolicy
WorkflowStatus = models.WorkflowStatus
TaskStatus = models.TaskStatus
)
// Node types (use these strings in Node.Type field)
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"
)
// Workflow statuses
const (
WorkflowActive = models.WorkflowActive
WorkflowInactive = models.WorkflowInactive
)
// Task/Execution statuses
const (
StatusPending = models.TaskPending
StatusRunning = models.TaskRunning
StatusCompleted = models.TaskCompleted
StatusFailed = models.TaskFailed
StatusSkipped = models.TaskSkipped
StatusWaiting = models.TaskWaiting
StatusCancelled = models.TaskCancelled
)
// ========================================
// FUNCTION HANDLER TYPE
// ========================================
// 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 HandlerFunc func(ctx context.Context, input map[string]interface{}) (map[string]interface{}, error)
// NodeExecutor defines the interface for custom node types
type NodeExecutor = engine.NodeExecutor
// ========================================
// ENGINE METHODS
// ========================================
// NewEngine creates a new workflow engine
func NewEngine(storage Storage, registry *Registry) *Engine {
// Auto-register all built-in node types
funcNode := node.NewFunctionNode()
funcNode.SetRegistry(registry.Registry)
registry.Register("function", funcNode)
registry.Register("http", &node.HTTPNode{})
registry.Register("condition", &node.ConditionNode{})
registry.Register("log", &node.LogNode{})
registry.Register("transform", &node.TransformNode{})
registry.Register("signal", &node.SignalNode{})
registry.Register("subworkflow", &node.SubWorkflowNode{})
registry.Register("ai", &node.AINode{})
registry.Register("notify", &node.NotifyNode{})
registry.Register("switch", &node.SwitchNode{})
registry.Register("wait", &node.WaitNode{})
registry.Register("setvariable", &node.SetVariableNode{})
return &Engine{engine.NewEngine(storage, registry.Registry)}
}
// WithLogger sets a custom logger for the engine
func (e *Engine) WithLogger(l *slog.Logger) *Engine {
e.Engine.WithLogger(l)
return e
}
// GetLogger returns the engine's logger
func (e *Engine) GetLogger() *slog.Logger {
return e.Engine.GetLogger()
}
// RegisterWorkflow saves a workflow definition
func (e *Engine) RegisterWorkflow(ctx context.Context, namespace string, wf *Workflow) error {
return e.Engine.RegisterWorkflow(ctx, namespace, wf)
}
// Execute starts a new workflow execution (alias for StartWorkflow)
func (e *Engine) Execute(ctx context.Context, namespace, workflowID string, input []byte) (string, error) {
return e.Engine.StartWorkflow(ctx, namespace, workflowID, string(input))
}
// StartWorkflow starts a new workflow execution
func (e *Engine) StartWorkflow(ctx context.Context, namespace, workflowID string, input string) (string, error) {
return e.Engine.StartWorkflow(ctx, namespace, workflowID, input)
}
// GetExecution retrieves an execution by ID
func (e *Engine) GetExecution(ctx context.Context, namespace, execID string) (*Execution, error) {
return e.Engine.GetExecutionStatus(ctx, namespace, execID)
}
// GetExecutionStatus retrieves an execution's status
func (e *Engine) GetExecutionStatus(ctx context.Context, namespace, execID string) (*Execution, error) {
return e.Engine.GetExecutionStatus(ctx, namespace, execID)
}
// GetExecutionSteps retrieves all steps for an execution
func (e *Engine) GetExecutionSteps(ctx context.Context, namespace, execID string) ([]*ExecutionStep, error) {
return e.Engine.GetExecutionSteps(ctx, namespace, execID)
}
// CancelExecution cancels a running execution
func (e *Engine) CancelExecution(ctx context.Context, namespace, execID string) error {
return e.Engine.CancelExecution(ctx, namespace, execID)
}
// FailExecution marks an execution as failed
func (e *Engine) FailExecution(ctx context.Context, namespace, execID, message string) error {
return e.Engine.FailExecution(ctx, namespace, execID, message)
}
// SignalExecution sends a signal to resume a waiting workflow
func (e *Engine) SignalExecution(ctx context.Context, namespace, execID, nodeID, output string) error {
return e.Engine.SignalExecution(ctx, namespace, execID, nodeID, output)
}
// ReapTimeouts checks for and handles timed-out tasks
func (e *Engine) ReapTimeouts(ctx context.Context, namespace string) error {
return e.Engine.ReapTimeouts(ctx, namespace)
}
// StartWorker starts a worker that processes tasks
func (e *Engine) StartWorker(ctx context.Context, namespace, workerID string) {
e.Engine.StartWorker(ctx, namespace, workerID)
}
// ========================================
// REGISTRY METHODS
// ========================================
// NewRegistry creates a new function registry
func NewRegistry() *Registry {
return &Registry{
Registry: engine.NewRegistry(),
}
}
// 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
// })
func (r *Registry) RegisterFunction(name string, handler HandlerFunc) {
// Wrap user handler to match internal signature
wrappedHandler := func(ctx context.Context, input map[string]interface{}) (map[string]interface{}, error) {
return handler(ctx, input)
}
r.Registry.RegisterFunction(name, wrappedHandler)
}
// Register registers a custom node executor
func (r *Registry) Register(nodeType string, executor NodeExecutor) {
r.Registry.Register(nodeType, executor)
}
// Get retrieves a registered executor by type
func (r *Registry) Get(nodeType string) (NodeExecutor, error) {
return r.Registry.Get(nodeType)
}
// ========================================
// WORKER
// ========================================
// NewWorker creates a new worker instance
func NewWorker(id string, eng *Engine, registry *Registry, interval time.Duration) *Worker {
return &Worker{engine.NewWorker(id, eng.Engine, registry.Registry, interval)}
}
// SetNamespace sets the worker's namespace
func (w *Worker) SetNamespace(namespace string) {
w.Worker.SetNamespace(namespace)
}
// Start begins the worker's task processing loop
func (w *Worker) Start(ctx context.Context) {
w.Worker.Start(ctx)
}
// ========================================
// STORAGE BACKENDS
// ========================================
// NewMemoryStorage creates an in-memory storage backend (for development)
func NewMemoryStorage() Storage {
return memory.NewMemoryStorage()
}
// NewMySQLStorage creates a MySQL storage backend with auto-migration
//
// Example:
//
// db, _ := sqlx.Connect("mysql", "user:pass@tcp(localhost:3306)/db?parseTime=true")
// storage, _ := flow.NewMySQLStorage(db)
//
// Tables are automatically created if they don't exist.
func NewMySQLStorage(db *sqlx.DB) (Storage, error) {
return sql.NewSQLStorage(db, "mysql")
}
// NewPostgreSQLStorage creates a PostgreSQL storage backend with auto-migration
//
// Example:
//
// db, _ := sqlx.Connect("postgres", "postgres://user:pass@localhost/db?sslmode=disable")
// storage, _ := flow.NewPostgreSQLStorage(db)
//
// Tables are automatically created if they don't exist.
func NewPostgreSQLStorage(db *sqlx.DB) (Storage, error) {
return sql.NewSQLStorage(db, "postgres")
}
// NewRedisStorage creates a Redis storage backend
//
// Example:
//
// storage := flow.NewRedisStorage("localhost:6379", "", 0)
func NewRedisStorage(addr string, password string, db int) Storage {
return redis.NewRedisStorage(addr, password, db)
}
// ========================================
// ENCRYPTION
// ========================================
// Crypto provides data-at-rest encryption
type Crypto = storage.Crypto
// NewCrypto creates a new encryption instance
//
// Example:
//
// crypto, _ := flow.NewCrypto("your-32-byte-encryption-key-here")
// sqlStorage.(*sql.SQLStorage).SetEncryption(crypto)
func NewCrypto(key string) (*Crypto, error) {
return storage.NewCrypto(key)
}
// ========================================
// WORKFLOW BUILDER
// ========================================
// WorkflowBuilder provides a fluent API for building workflows
type WorkflowBuilder struct {
*builder.WorkflowBuilder
}
// NodeBuilder provides a fluent API for configuring nodes
type NodeBuilder struct {
*builder.NodeBuilder
}
// 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 NewWorkflow(id, name string) *WorkflowBuilder {
return &WorkflowBuilder{builder.NewWorkflow(id, name)}
}
// AddNode adds a node to the workflow
func (b *WorkflowBuilder) AddNode(id, nodeType string) *NodeBuilder {
return &NodeBuilder{b.WorkflowBuilder.AddNode(id, nodeType)}
}
// Connect creates an edge between two nodes
func (b *WorkflowBuilder) Connect(sourceID, targetID string) *WorkflowBuilder {
b.WorkflowBuilder.Connect(sourceID, targetID)
return b
}
// ConnectIf creates a conditional edge
func (b *WorkflowBuilder) ConnectIf(sourceID, targetID, condition string) *WorkflowBuilder {
b.WorkflowBuilder.ConnectIf(sourceID, targetID, condition)
return b
}
// Build returns the completed workflow
func (b *WorkflowBuilder) Build() *Workflow {
return b.WorkflowBuilder.Build()
}
// Visualize generates a Mermaid diagram of the workflow
func (b *WorkflowBuilder) Visualize() string {
return b.Visualise()
}
// WithConfig adds configuration to a node
func (nb *NodeBuilder) WithConfig(key string, value interface{}) *NodeBuilder {
nb.NodeBuilder.WithConfig(key, value)
return nb
}
// WithSaga sets a compensation node (saga pattern)
func (nb *NodeBuilder) WithSaga(compensateNodeID string) *NodeBuilder {
nb.NodeBuilder.WithSaga(compensateNodeID)
return nb
}
// WithRetry sets retry count
func (nb *NodeBuilder) WithRetry(count int) *NodeBuilder {
nb.NodeBuilder.WithRetry(count)
return nb
}
// Then connects this node to the next node
func (nb *NodeBuilder) Then(targetID string) *NodeBuilder {
return &NodeBuilder{nb.NodeBuilder.Then(targetID)}
}
// If creates a conditional connection
func (nb *NodeBuilder) If(targetID, condition string) *NodeBuilder {
return &NodeBuilder{nb.NodeBuilder.If(targetID, condition)}
}
// ToMermaid generates a Mermaid.js diagram from a workflow
func ToMermaid(wf *Workflow) string {
return builder.ToMermaid(wf)
}
// ========================================
// DAG / GRAPH
// ========================================
// NewGraph creates a new graph from a workflow
func NewGraph(wf *Workflow) (*Graph, error) {
return engine.NewGraph(wf)
}
// ========================================
// TRIGGERS
// ========================================
// CronManager manages scheduled workflow execution
type CronManager struct {
*trigger.CronManager
}
// NewCronManager creates a new cron scheduler
//
// Example:
//
// cronMgr := flow.NewCronManager(engine, logger)
// cronMgr.Start()
// cronMgr.AddSchedule("default", "backup-workflow", "0 2 * * *", `{"type":"daily"}`)
func NewCronManager(eng *Engine, logger *slog.Logger) *CronManager {
return &CronManager{trigger.NewCronManager(eng.Engine, logger)}
}
// Start begins the cron scheduler
func (c *CronManager) Start() {
c.CronManager.Start()
}
// Stop halts the cron scheduler
func (c *CronManager) Stop() {
c.CronManager.Stop()
}
// AddSchedule schedules a workflow with cron expression
func (c *CronManager) AddSchedule(namespace, workflowID, cronExpr, input string) (cron.EntryID, error) {
return c.CronManager.AddSchedule(namespace, workflowID, cronExpr, input)
}
// WebhookManager handles HTTP webhook triggers
type WebhookManager struct {
*trigger.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 NewWebhookManager(eng *Engine) *WebhookManager {
return &WebhookManager{trigger.NewWebhookManager(eng.Engine)}
}
// ServeHTTP handles webhook requests
func (w *WebhookManager) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
w.WebhookManager.ServeHTTP(rw, r)
}
// APIManager provides REST API for workflow management
type APIManager struct {
*trigger.APIManager
}
// NewAPIManager creates a REST API handler
//
// Example:
//
// apiMgr := flow.NewAPIManager(webhookMgr)
// http.Handle("/", apiMgr)
//
// Endpoints:
// - GET /health
// - GET /metrics (Prometheus)
// - GET /api/{namespace}/executions/{id}
// - POST /api/{namespace}/executions/{id}/cancel
// - POST /api/{namespace}/executions/{id}/signal/{nodeID}
func NewAPIManager(webhookMgr *WebhookManager) *APIManager {
return &APIManager{trigger.NewAPIManager(webhookMgr.WebhookManager)}
}
// ServeHTTP handles API requests
func (a *APIManager) ServeHTTP(w http.ResponseWriter, r *http.Request) {
a.APIManager.ServeHTTP(w, r)
}
// ========================================
// EVENTS
// ========================================
// EventType represents workflow event types
type EventType = engine.EventType
// Event types
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
EventSignalReceived = engine.EventTypeSignalReceived
EventCompensationTriggered = engine.EventTypeCompensationTriggered
)
// Event represents a workflow event
type Event = engine.Event
// EventHandler handles workflow events
type EventHandler = engine.EventHandler
// EventBus manages event subscriptions
type EventBus struct {
*engine.EventBus
}
// NewEventBus creates a new event bus
//
// Example:
//
// eventBus := flow.NewEventBus()
// eventBus.RegisterHandler(flow.EventWorkflowCompleted, myHandler)
func NewEventBus() *EventBus {
return &EventBus{engine.NewEventBus()}
}
// RegisterHandler registers a handler for a specific event type
func (eb *EventBus) RegisterHandler(eventType EventType, handler EventHandler) {
eb.EventBus.RegisterHandler(eventType, handler)
}
// RegisterGlobalHandler registers a handler for all events
func (eb *EventBus) RegisterGlobalHandler(handler EventHandler) {
eb.EventBus.RegisterGlobalHandler(handler)
}
// Emit emits an event asynchronously
func (eb *EventBus) Emit(ctx context.Context, event Event) {
eb.EventBus.Emit(ctx, event)
}
// EmitSync emits an event synchronously
func (eb *EventBus) EmitSync(ctx context.Context, event Event) []error {
return eb.EventBus.EmitSync(ctx, event)
}
// ========================================
// TELEMETRY / METRICS
// ========================================
// Prometheus metrics (pre-registered)
var (
WorkflowsStarted = telemetry.WorkflowsStarted
WorkflowsCompleted = telemetry.WorkflowsCompleted
WorkflowsFailed = telemetry.WorkflowsFailed
StepsProcessed = telemetry.StepsProcessed
StepDuration = telemetry.StepDuration
ActiveWorkers = telemetry.ActiveWorkers
)
// MetricsRegistry returns the Prometheus registry
func MetricsRegistry() *prometheus.Registry {
return prometheus.DefaultRegisterer.(*prometheus.Registry)
}
// ========================================
// BUILT-IN NODE TYPES
// ========================================
// Built-in node types are automatically registered when creating an Engine
// No need to manually register them - just use the node type constants:
// - flow.NodeTypeFunction
// - flow.NodeTypeHTTP
// - flow.NodeTypeCondition
// etc.