Feat v0.3.2 workflow engine (#16)
Co-authored-by: Jeffrey Smith <jasafpro@gmail.com> Co-committed-by: Jeffrey Smith <jasafpro@gmail.com>
This commit was merged in pull request #16.
This commit is contained in:
282
server/workflow/engine.go
Normal file
282
server/workflow/engine.go
Normal file
@@ -0,0 +1,282 @@
|
||||
package workflow
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log"
|
||||
"time"
|
||||
|
||||
"switchboard-core/events"
|
||||
"switchboard-core/models"
|
||||
"switchboard-core/sandbox"
|
||||
"switchboard-core/store"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// MaxConsecutiveAutomated is the cycle guard limit for automated stages.
|
||||
const MaxConsecutiveAutomated = 10
|
||||
|
||||
// Engine orchestrates workflow instance lifecycle.
|
||||
type Engine struct {
|
||||
stores store.Stores
|
||||
bus *events.Bus
|
||||
runner *sandbox.Runner
|
||||
}
|
||||
|
||||
// NewEngine creates a workflow engine.
|
||||
func NewEngine(stores store.Stores, bus *events.Bus, runner *sandbox.Runner) *Engine {
|
||||
return &Engine{stores: stores, bus: bus, runner: runner}
|
||||
}
|
||||
|
||||
// Start creates a new workflow instance and kicks off the first stage.
|
||||
func (e *Engine) Start(ctx context.Context, workflowID string, initialData json.RawMessage, userID string) (*models.WorkflowInstance, error) {
|
||||
wf, err := e.stores.Workflows.GetByID(ctx, workflowID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("workflow not found: %w", err)
|
||||
}
|
||||
if !wf.IsActive {
|
||||
return nil, fmt.Errorf("workflow %q is not active", wf.Name)
|
||||
}
|
||||
|
||||
ver, err := e.stores.Workflows.GetLatestVersion(ctx, workflowID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("no published version: %w", err)
|
||||
}
|
||||
|
||||
var stages []models.WorkflowStage
|
||||
if err := json.Unmarshal(ver.Snapshot, &stages); err != nil {
|
||||
return nil, fmt.Errorf("corrupt version snapshot: %w", err)
|
||||
}
|
||||
if len(stages) == 0 {
|
||||
return nil, fmt.Errorf("workflow has no stages")
|
||||
}
|
||||
|
||||
inst := &models.WorkflowInstance{
|
||||
WorkflowID: workflowID,
|
||||
WorkflowVersion: ver.VersionNumber,
|
||||
CurrentStage: stages[0].Name,
|
||||
StageData: initialData,
|
||||
Status: models.InstanceStatusActive,
|
||||
StartedBy: userID,
|
||||
Metadata: json.RawMessage(`{}`),
|
||||
}
|
||||
|
||||
if wf.EntryMode == "public_link" {
|
||||
tok := uuid.New().String()
|
||||
inst.EntryToken = &tok
|
||||
}
|
||||
|
||||
if err := e.stores.Workflows.CreateInstance(ctx, inst); err != nil {
|
||||
return nil, fmt.Errorf("create instance: %w", err)
|
||||
}
|
||||
|
||||
// Create initial assignment if first stage has a team
|
||||
if stages[0].AssignmentTeamID != nil {
|
||||
a := &models.WorkflowAssignment{
|
||||
InstanceID: inst.ID,
|
||||
Stage: stages[0].Name,
|
||||
TeamID: *stages[0].AssignmentTeamID,
|
||||
}
|
||||
if err := e.stores.Workflows.CreateAssignment(ctx, a); err != nil {
|
||||
log.Printf("[workflow-engine] create initial assignment: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
e.emit(ctx, "workflow.started", inst.ID, map[string]any{
|
||||
"workflow_id": workflowID,
|
||||
"instance_id": inst.ID,
|
||||
"started_by": userID,
|
||||
})
|
||||
|
||||
// If first stage is automated, process it
|
||||
if stages[0].StageMode == models.StageModeAutomated {
|
||||
if err := e.processAutomatedStage(ctx, inst, stages, 0); err != nil {
|
||||
log.Printf("[workflow-engine] automated stage error on start: %v", err)
|
||||
}
|
||||
// Re-read instance after automated processing
|
||||
inst, _ = e.stores.Workflows.GetInstance(ctx, inst.ID)
|
||||
}
|
||||
|
||||
return inst, nil
|
||||
}
|
||||
|
||||
// Advance moves an instance to the next stage.
|
||||
func (e *Engine) Advance(ctx context.Context, instanceID string, stageData json.RawMessage, userID string) (*models.WorkflowInstance, error) {
|
||||
return e.advanceInternal(ctx, instanceID, stageData, userID, 0)
|
||||
}
|
||||
|
||||
func (e *Engine) advanceInternal(ctx context.Context, instanceID string, stageData json.RawMessage, userID string, autoDepth int) (*models.WorkflowInstance, error) {
|
||||
inst, err := e.stores.Workflows.GetInstance(ctx, instanceID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("instance not found: %w", err)
|
||||
}
|
||||
if inst.Status != models.InstanceStatusActive {
|
||||
return nil, fmt.Errorf("instance is %s, not active", inst.Status)
|
||||
}
|
||||
|
||||
ver, err := e.stores.Workflows.GetVersion(ctx, inst.WorkflowID, inst.WorkflowVersion)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("version not found: %w", err)
|
||||
}
|
||||
|
||||
var stages []models.WorkflowStage
|
||||
if err := json.Unmarshal(ver.Snapshot, &stages); err != nil {
|
||||
return nil, fmt.Errorf("corrupt snapshot: %w", err)
|
||||
}
|
||||
|
||||
// Find current stage ordinal
|
||||
currentOrdinal := -1
|
||||
for _, s := range stages {
|
||||
if s.Name == inst.CurrentStage {
|
||||
currentOrdinal = s.Ordinal
|
||||
break
|
||||
}
|
||||
}
|
||||
if currentOrdinal < 0 {
|
||||
return nil, fmt.Errorf("current stage %q not found in snapshot", inst.CurrentStage)
|
||||
}
|
||||
currentStage := stages[currentOrdinal]
|
||||
|
||||
// Merge stage data
|
||||
merged := mergeJSON(inst.StageData, stageData)
|
||||
|
||||
// Resolve next stage
|
||||
nextOrdinal, err := ResolveNextStage(stages, currentOrdinal, merged)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("resolve next stage: %w", err)
|
||||
}
|
||||
|
||||
// Terminal — complete the instance
|
||||
if nextOrdinal >= len(stages) {
|
||||
if err := e.stores.Workflows.CompleteInstance(ctx, instanceID); err != nil {
|
||||
return nil, fmt.Errorf("complete: %w", err)
|
||||
}
|
||||
e.emit(ctx, "workflow.completed", instanceID, map[string]any{
|
||||
"instance_id": instanceID,
|
||||
})
|
||||
return e.stores.Workflows.GetInstance(ctx, instanceID)
|
||||
}
|
||||
|
||||
nextStage := stages[nextOrdinal]
|
||||
|
||||
// Advance in store
|
||||
if err := e.stores.Workflows.AdvanceStage(ctx, instanceID, nextStage.Name, merged); err != nil {
|
||||
return nil, fmt.Errorf("advance store: %w", err)
|
||||
}
|
||||
|
||||
// Cancel old assignments for the previous stage
|
||||
oldAssignments, _ := e.stores.Workflows.ListAssignmentsByInstance(ctx, instanceID)
|
||||
for _, a := range oldAssignments {
|
||||
if a.Stage == currentStage.Name && (a.Status == models.AssignmentStatusUnassigned || a.Status == models.AssignmentStatusClaimed) {
|
||||
e.stores.Workflows.CancelAssignment(ctx, a.ID)
|
||||
}
|
||||
}
|
||||
|
||||
// Create new assignment if next stage has a team
|
||||
if nextStage.AssignmentTeamID != nil {
|
||||
a := &models.WorkflowAssignment{
|
||||
InstanceID: instanceID,
|
||||
Stage: nextStage.Name,
|
||||
TeamID: *nextStage.AssignmentTeamID,
|
||||
}
|
||||
if err := e.stores.Workflows.CreateAssignment(ctx, a); err != nil {
|
||||
log.Printf("[workflow-engine] create assignment: %v", err)
|
||||
} else {
|
||||
e.emit(ctx, "workflow.assigned", a.TeamID, map[string]any{
|
||||
"instance_id": instanceID,
|
||||
"stage": nextStage.Name,
|
||||
"assignment_id": a.ID,
|
||||
"team_id": a.TeamID,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
e.emit(ctx, "workflow.advanced", instanceID, map[string]any{
|
||||
"instance_id": instanceID,
|
||||
"previous_stage": currentStage.Name,
|
||||
"current_stage": nextStage.Name,
|
||||
})
|
||||
|
||||
// If next stage is automated, process it
|
||||
if nextStage.StageMode == models.StageModeAutomated {
|
||||
if err := e.processAutomatedStage(ctx, inst, stages, autoDepth+1); err != nil {
|
||||
log.Printf("[workflow-engine] automated stage error: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
return e.stores.Workflows.GetInstance(ctx, instanceID)
|
||||
}
|
||||
|
||||
// Cancel terminates an active instance and all its open assignments.
|
||||
func (e *Engine) Cancel(ctx context.Context, instanceID string, userID string) error {
|
||||
inst, err := e.stores.Workflows.GetInstance(ctx, instanceID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("instance not found: %w", err)
|
||||
}
|
||||
if inst.Status != models.InstanceStatusActive {
|
||||
return fmt.Errorf("instance is %s, not active", inst.Status)
|
||||
}
|
||||
|
||||
if err := e.stores.Workflows.CancelInstance(ctx, instanceID); err != nil {
|
||||
return fmt.Errorf("cancel: %w", err)
|
||||
}
|
||||
|
||||
// Cancel all open assignments
|
||||
assignments, _ := e.stores.Workflows.ListAssignmentsByInstance(ctx, instanceID)
|
||||
for _, a := range assignments {
|
||||
if a.Status == models.AssignmentStatusUnassigned || a.Status == models.AssignmentStatusClaimed {
|
||||
e.stores.Workflows.CancelAssignment(ctx, a.ID)
|
||||
}
|
||||
}
|
||||
|
||||
e.emit(ctx, "workflow.cancelled", instanceID, map[string]any{
|
||||
"instance_id": instanceID,
|
||||
"cancelled_by": userID,
|
||||
})
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// emit publishes an event on the bus.
|
||||
func (e *Engine) emit(_ context.Context, label, room string, payload map[string]any) {
|
||||
if e.bus == nil {
|
||||
return
|
||||
}
|
||||
e.bus.Publish(events.Event{
|
||||
Label: label,
|
||||
Room: room,
|
||||
Payload: events.MustJSON(payload),
|
||||
Ts: time.Now().UnixMilli(),
|
||||
})
|
||||
}
|
||||
|
||||
// mergeJSON merges b into a (shallow). Returns a if b is empty.
|
||||
func mergeJSON(a, b json.RawMessage) json.RawMessage {
|
||||
if len(b) == 0 || string(b) == "{}" || string(b) == "null" {
|
||||
if len(a) == 0 {
|
||||
return json.RawMessage(`{}`)
|
||||
}
|
||||
return a
|
||||
}
|
||||
if len(a) == 0 || string(a) == "{}" || string(a) == "null" {
|
||||
return b
|
||||
}
|
||||
|
||||
var ma, mb map[string]json.RawMessage
|
||||
if json.Unmarshal(a, &ma) != nil {
|
||||
return b
|
||||
}
|
||||
if json.Unmarshal(b, &mb) != nil {
|
||||
return a
|
||||
}
|
||||
for k, v := range mb {
|
||||
ma[k] = v
|
||||
}
|
||||
merged, err := json.Marshal(ma)
|
||||
if err != nil {
|
||||
return b
|
||||
}
|
||||
return merged
|
||||
}
|
||||
Reference in New Issue
Block a user