feat: database layer + canvas validator/converter + LLM inference activities
ci / test (push) Failing after 2m11s
ci / test (push) Failing after 2m11s
- Add pkg/db models and CRUD methods for workflows - Add internal/routing canvas validator (DAG check, connectivity) - Add internal/routing canvas converter (Canvas → WorkflowSpec) - Register LLMInferenceActivity and LLMBatchInferenceActivity - Update api/server and cmd/server with database integration - Add K8s environment variable support - Update activity knowledge base with LLM activities - Add .env.example configuration template
This commit is contained in:
@@ -0,0 +1,101 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"go.temporal.io/sdk/client"
|
||||
|
||||
"github.com/rockliang/poimen/workflows/pkg/db"
|
||||
)
|
||||
|
||||
// Server handles HTTP routing for workflow APIs
|
||||
type Server struct {
|
||||
api *WorkflowAPI
|
||||
logger *log.Logger
|
||||
}
|
||||
|
||||
// NewServer creates new HTTP server with database connection
|
||||
func NewServer(database *db.DB, temporalClient client.Client, logger *log.Logger) *Server {
|
||||
return &Server{
|
||||
api: NewWorkflowAPI(database, temporalClient, logger),
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
// ServeHTTP dispatches HTTP requests to appropriate handler
|
||||
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
// Enable CORS
|
||||
w.Header().Set("Access-Control-Allow-Origin", "*")
|
||||
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
|
||||
w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization")
|
||||
|
||||
if r.Method == http.MethodOptions {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
return
|
||||
}
|
||||
|
||||
path := r.URL.Path
|
||||
method := r.Method
|
||||
|
||||
s.logger.Printf("%s %s", method, path)
|
||||
|
||||
// Route requests
|
||||
switch {
|
||||
// Workflow endpoints
|
||||
case path == "/workflows" && method == http.MethodPost:
|
||||
s.api.CreateWorkflow(w, r)
|
||||
case path == "/workflows" && method == http.MethodGet:
|
||||
s.api.ListWorkflows(w, r)
|
||||
case strings.HasPrefix(path, "/workflows/") && method == http.MethodGet:
|
||||
id := strings.TrimPrefix(path, "/workflows/")
|
||||
// Exclude special paths
|
||||
if !strings.Contains(id, "/") {
|
||||
s.api.GetWorkflow(w, r, id)
|
||||
} else if strings.HasSuffix(id, "/executions") {
|
||||
// GET /workflows/{id}/executions
|
||||
workflowID := strings.TrimSuffix(id, "/executions")
|
||||
s.api.ListExecutions(w, r, workflowID)
|
||||
}
|
||||
case strings.HasPrefix(path, "/workflows/") && method == http.MethodPut:
|
||||
id := extractID(path, "/workflows/")
|
||||
s.api.UpdateWorkflow(w, r, id)
|
||||
case strings.HasPrefix(path, "/workflows/") && method == http.MethodDelete:
|
||||
id := extractID(path, "/workflows/")
|
||||
s.api.DeleteWorkflow(w, r, id)
|
||||
|
||||
// Execute workflow
|
||||
case strings.HasSuffix(path, "/execute") && method == http.MethodPost:
|
||||
// POST /workflows/{id}/execute
|
||||
parts := strings.Split(path, "/")
|
||||
if len(parts) >= 4 && parts[1] == "workflows" && parts[3] == "execute" {
|
||||
s.api.ExecuteWorkflow(w, r, parts[2])
|
||||
}
|
||||
|
||||
// Execution endpoints
|
||||
case strings.HasPrefix(path, "/executions/") && method == http.MethodGet:
|
||||
id := extractID(path, "/executions/")
|
||||
s.api.GetExecution(w, r, id)
|
||||
|
||||
default:
|
||||
http.Error(w, "Not found", http.StatusNotFound)
|
||||
}
|
||||
}
|
||||
|
||||
// extractID extracts resource ID from path
|
||||
func extractID(path, prefix string) string {
|
||||
id := strings.TrimPrefix(path, prefix)
|
||||
if idx := strings.Index(id, "/"); idx != -1 {
|
||||
return id[:idx]
|
||||
}
|
||||
return id
|
||||
}
|
||||
|
||||
// Start starts the HTTP server
|
||||
func (s *Server) Start(port int) error {
|
||||
addr := fmt.Sprintf(":%d", port)
|
||||
s.logger.Printf("Starting API server on %s", addr)
|
||||
return http.ListenAndServe(addr, s)
|
||||
}
|
||||
@@ -0,0 +1,589 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"go.temporal.io/sdk/client"
|
||||
|
||||
"github.com/rockliang/poimen/workflows/internal/routing"
|
||||
"github.com/rockliang/poimen/workflows/pkg/db"
|
||||
)
|
||||
|
||||
// WorkflowNode matches frontend node type
|
||||
type WorkflowNode struct {
|
||||
ID string `json:"id"`
|
||||
Type string `json:"type"` // "activity", "start", "end"
|
||||
Position map[string]interface{} `json:"position"`
|
||||
Data struct {
|
||||
Label string `json:"label"`
|
||||
Activity string `json:"activity"`
|
||||
Config map[string]interface{} `json:"config"`
|
||||
} `json:"data"`
|
||||
}
|
||||
|
||||
// WorkflowEdge matches frontend edge type
|
||||
type WorkflowEdge struct {
|
||||
ID string `json:"id"`
|
||||
Source string `json:"source"`
|
||||
Target string `json:"target"`
|
||||
Data map[string]interface{} `json:"data,omitempty"`
|
||||
}
|
||||
|
||||
// WorkflowDef is the request body for creating/updating workflows
|
||||
type WorkflowDef struct {
|
||||
Name string `json:"name"`
|
||||
Description string `json:"description"`
|
||||
Nodes []WorkflowNode `json:"nodes"`
|
||||
Edges []WorkflowEdge `json:"edges"`
|
||||
Status string `json:"status"` // "draft", "active"
|
||||
}
|
||||
|
||||
// WorkflowResponse is the workflow with metadata
|
||||
type WorkflowResponse struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Description string `json:"description"`
|
||||
Status string `json:"status"`
|
||||
Version int `json:"version"`
|
||||
Nodes []WorkflowNode `json:"nodes"`
|
||||
Edges []WorkflowEdge `json:"edges"`
|
||||
CreatedAt string `json:"createdAt"`
|
||||
UpdatedAt string `json:"updatedAt"`
|
||||
CreatedBy string `json:"createdBy"`
|
||||
}
|
||||
|
||||
// ExecutionRequest is the request to execute a workflow
|
||||
type ExecutionRequest struct {
|
||||
Inputs map[string]interface{} `json:"inputs"`
|
||||
}
|
||||
|
||||
// ExecutionResponse is the execution result
|
||||
type ExecutionResponse struct {
|
||||
ID string `json:"id"`
|
||||
WorkflowID string `json:"workflowId"`
|
||||
Status string `json:"status"` // "pending", "running", "success", "failed"
|
||||
StartedAt string `json:"startedAt"`
|
||||
CompletedAt string `json:"completedAt,omitempty"`
|
||||
Inputs map[string]interface{} `json:"inputs"`
|
||||
Outputs map[string]interface{} `json:"outputs,omitempty"`
|
||||
Errors []string `json:"errors,omitempty"`
|
||||
Logs []ExecutionLog `json:"logs"`
|
||||
}
|
||||
|
||||
// ExecutionLog is a log entry from execution
|
||||
type ExecutionLog struct {
|
||||
Timestamp string `json:"timestamp"`
|
||||
NodeID string `json:"nodeId"`
|
||||
Level string `json:"level"` // "info", "warn", "error"
|
||||
Message string `json:"message"`
|
||||
}
|
||||
|
||||
// WorkflowAPI handles workflow endpoints
|
||||
type WorkflowAPI struct {
|
||||
db *db.DB
|
||||
temporalClient client.Client
|
||||
logger *log.Logger
|
||||
customerID string // TODO: Extract from JWT token
|
||||
}
|
||||
|
||||
// NewWorkflowAPI creates new API handler
|
||||
func NewWorkflowAPI(database *db.DB, tc client.Client, logger *log.Logger) *WorkflowAPI {
|
||||
return &WorkflowAPI{
|
||||
db: database,
|
||||
temporalClient: tc,
|
||||
logger: logger,
|
||||
customerID: "default-customer", // TODO: From auth context
|
||||
}
|
||||
}
|
||||
|
||||
// CreateWorkflow handles POST /workflows
|
||||
func (api *WorkflowAPI) CreateWorkflow(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
|
||||
var req WorkflowDef
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
http.Error(w, fmt.Sprintf("Invalid request: %v", err), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
if req.Name == "" {
|
||||
http.Error(w, "Workflow name required", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
// Create workflow in database
|
||||
id := uuid.New().String()
|
||||
now := time.Now()
|
||||
|
||||
// Convert nodes and edges to JSONB
|
||||
nodesJSON, err := json.Marshal(req.Nodes)
|
||||
if err != nil {
|
||||
http.Error(w, fmt.Sprintf("Failed to marshal nodes: %v", err), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
edgesJSON, err := json.Marshal(req.Edges)
|
||||
if err != nil {
|
||||
http.Error(w, fmt.Sprintf("Failed to marshal edges: %v", err), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
status := req.Status
|
||||
if status == "" {
|
||||
status = "draft"
|
||||
}
|
||||
|
||||
workflow := &db.Workflow{
|
||||
ID: id,
|
||||
CustomerID: api.customerID,
|
||||
Name: req.Name,
|
||||
Description: req.Description,
|
||||
Status: status,
|
||||
Version: 1,
|
||||
Nodes: nodesJSON,
|
||||
Edges: edgesJSON,
|
||||
CreatedBy: "anonymous", // Use JWT claim in real implementation
|
||||
CreatedAt: now,
|
||||
UpdatedAt: now,
|
||||
}
|
||||
|
||||
if err := api.db.SaveWorkflow(r.Context(), workflow); err != nil {
|
||||
api.logger.Printf("Failed to save workflow: %v", err)
|
||||
http.Error(w, "Failed to create workflow", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
response := WorkflowResponse{
|
||||
ID: workflow.ID,
|
||||
Name: workflow.Name,
|
||||
Description: workflow.Description,
|
||||
Status: workflow.Status,
|
||||
Version: workflow.Version,
|
||||
Nodes: req.Nodes,
|
||||
Edges: req.Edges,
|
||||
CreatedAt: workflow.CreatedAt.Format(time.RFC3339),
|
||||
UpdatedAt: workflow.UpdatedAt.Format(time.RFC3339),
|
||||
CreatedBy: workflow.CreatedBy,
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
json.NewEncoder(w).Encode(response)
|
||||
}
|
||||
|
||||
// ListWorkflows handles GET /workflows
|
||||
func (api *WorkflowAPI) ListWorkflows(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodGet {
|
||||
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
|
||||
page := 1
|
||||
limit := 10
|
||||
// Parse pagination params if needed
|
||||
|
||||
workflows, err := api.db.ListWorkflows(r.Context(), api.customerID, limit, (page-1)*limit)
|
||||
if err != nil {
|
||||
api.logger.Printf("Failed to list workflows: %v", err)
|
||||
http.Error(w, "Failed to list workflows", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
list := make([]WorkflowResponse, 0)
|
||||
for _, wf := range workflows {
|
||||
var nodes []WorkflowNode
|
||||
var edges []WorkflowEdge
|
||||
|
||||
json.Unmarshal(wf.Nodes, &nodes)
|
||||
json.Unmarshal(wf.Edges, &edges)
|
||||
|
||||
list = append(list, WorkflowResponse{
|
||||
ID: wf.ID,
|
||||
Name: wf.Name,
|
||||
Description: wf.Description,
|
||||
Status: wf.Status,
|
||||
Version: wf.Version,
|
||||
Nodes: nodes,
|
||||
Edges: edges,
|
||||
CreatedAt: wf.CreatedAt.Format(time.RFC3339),
|
||||
UpdatedAt: wf.UpdatedAt.Format(time.RFC3339),
|
||||
CreatedBy: wf.CreatedBy,
|
||||
})
|
||||
}
|
||||
|
||||
response := map[string]interface{}{
|
||||
"workflows": list,
|
||||
"total": len(list),
|
||||
"page": page,
|
||||
"limit": limit,
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(response)
|
||||
}
|
||||
|
||||
// GetWorkflow handles GET /workflows/{id}
|
||||
func (api *WorkflowAPI) GetWorkflow(w http.ResponseWriter, r *http.Request, id string) {
|
||||
if r.Method != http.MethodGet {
|
||||
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
|
||||
workflow, err := api.db.FetchWorkflow(r.Context(), id, api.customerID)
|
||||
if err != nil {
|
||||
http.Error(w, "Workflow not found", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
|
||||
var nodes []WorkflowNode
|
||||
var edges []WorkflowEdge
|
||||
|
||||
json.Unmarshal(workflow.Nodes, &nodes)
|
||||
json.Unmarshal(workflow.Edges, &edges)
|
||||
|
||||
response := WorkflowResponse{
|
||||
ID: workflow.ID,
|
||||
Name: workflow.Name,
|
||||
Description: workflow.Description,
|
||||
Status: workflow.Status,
|
||||
Version: workflow.Version,
|
||||
Nodes: nodes,
|
||||
Edges: edges,
|
||||
CreatedAt: workflow.CreatedAt.Format(time.RFC3339),
|
||||
UpdatedAt: workflow.UpdatedAt.Format(time.RFC3339),
|
||||
CreatedBy: workflow.CreatedBy,
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(response)
|
||||
}
|
||||
|
||||
// UpdateWorkflow handles PUT /workflows/{id}
|
||||
func (api *WorkflowAPI) UpdateWorkflow(w http.ResponseWriter, r *http.Request, id string) {
|
||||
if r.Method != http.MethodPut {
|
||||
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
|
||||
// Fetch existing workflow
|
||||
workflow, err := api.db.FetchWorkflow(r.Context(), id, api.customerID)
|
||||
if err != nil {
|
||||
http.Error(w, "Workflow not found", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
|
||||
var req WorkflowDef
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
http.Error(w, fmt.Sprintf("Invalid request: %v", err), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
// Update fields
|
||||
if req.Name != "" {
|
||||
workflow.Name = req.Name
|
||||
}
|
||||
if req.Description != "" {
|
||||
workflow.Description = req.Description
|
||||
}
|
||||
if req.Nodes != nil {
|
||||
nodesJSON, _ := json.Marshal(req.Nodes)
|
||||
workflow.Nodes = nodesJSON
|
||||
}
|
||||
if req.Edges != nil {
|
||||
edgesJSON, _ := json.Marshal(req.Edges)
|
||||
workflow.Edges = edgesJSON
|
||||
}
|
||||
if req.Status != "" {
|
||||
workflow.Status = req.Status
|
||||
}
|
||||
|
||||
workflow.Version++
|
||||
workflow.UpdatedAt = time.Now()
|
||||
|
||||
if err := api.db.SaveWorkflow(r.Context(), workflow); err != nil {
|
||||
api.logger.Printf("Failed to update workflow: %v", err)
|
||||
http.Error(w, "Failed to update workflow", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
var nodes []WorkflowNode
|
||||
var edges []WorkflowEdge
|
||||
|
||||
json.Unmarshal(workflow.Nodes, &nodes)
|
||||
json.Unmarshal(workflow.Edges, &edges)
|
||||
|
||||
response := WorkflowResponse{
|
||||
ID: workflow.ID,
|
||||
Name: workflow.Name,
|
||||
Description: workflow.Description,
|
||||
Status: workflow.Status,
|
||||
Version: workflow.Version,
|
||||
Nodes: nodes,
|
||||
Edges: edges,
|
||||
CreatedAt: workflow.CreatedAt.Format(time.RFC3339),
|
||||
UpdatedAt: workflow.UpdatedAt.Format(time.RFC3339),
|
||||
CreatedBy: workflow.CreatedBy,
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(response)
|
||||
}
|
||||
|
||||
// DeleteWorkflow handles DELETE /workflows/{id}
|
||||
func (api *WorkflowAPI) DeleteWorkflow(w http.ResponseWriter, r *http.Request, id string) {
|
||||
if r.Method != http.MethodDelete {
|
||||
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
|
||||
if err := api.db.DeleteWorkflow(r.Context(), id, api.customerID); err != nil {
|
||||
http.Error(w, "Workflow not found", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
// ExecuteWorkflow handles POST /workflows/{id}/execute
|
||||
func (api *WorkflowAPI) ExecuteWorkflow(w http.ResponseWriter, r *http.Request, id string) {
|
||||
if r.Method != http.MethodPost {
|
||||
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
|
||||
workflow, err := api.db.FetchWorkflow(r.Context(), id, api.customerID)
|
||||
if err != nil {
|
||||
http.Error(w, "Workflow not found", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
|
||||
var req ExecutionRequest
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
http.Error(w, fmt.Sprintf("Invalid request: %v", err), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
// Unmarshal nodes and edges
|
||||
var nodes []WorkflowNode
|
||||
var edges []WorkflowEdge
|
||||
json.Unmarshal(workflow.Nodes, &nodes)
|
||||
json.Unmarshal(workflow.Edges, &edges)
|
||||
|
||||
// Convert to workflow response for spec conversion
|
||||
workflowResp := &WorkflowResponse{
|
||||
ID: workflow.ID,
|
||||
Name: workflow.Name,
|
||||
Description: workflow.Description,
|
||||
Status: workflow.Status,
|
||||
Version: workflow.Version,
|
||||
Nodes: nodes,
|
||||
Edges: edges,
|
||||
CreatedBy: workflow.CreatedBy,
|
||||
}
|
||||
|
||||
// Convert nodes/edges to WorkflowSpec
|
||||
spec := api.nodesToWorkflowSpec(workflowResp, req.Inputs)
|
||||
|
||||
// Execute via Temporal RoutingWorkflow
|
||||
execID := uuid.New().String()
|
||||
workflowOptions := client.StartWorkflowOptions{
|
||||
ID: execID,
|
||||
TaskQueue: "default",
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
|
||||
_, err = api.temporalClient.ExecuteWorkflow(ctx, workflowOptions, "RoutingWorkflow", spec)
|
||||
if err != nil {
|
||||
api.logger.Printf("Failed to execute workflow: %v", err)
|
||||
http.Error(w, fmt.Sprintf("Execution failed: %v", err), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
// Save execution to database
|
||||
inputsJSON, _ := json.Marshal(req.Inputs)
|
||||
now := time.Now()
|
||||
|
||||
execution := &db.WorkflowExecution{
|
||||
ID: execID,
|
||||
WorkflowID: id,
|
||||
CustomerID: api.customerID,
|
||||
TemporalID: execID,
|
||||
Status: "running",
|
||||
Inputs: inputsJSON,
|
||||
StartedAt: now,
|
||||
}
|
||||
|
||||
if err := api.db.SaveExecution(r.Context(), execution); err != nil {
|
||||
api.logger.Printf("Failed to save execution: %v", err)
|
||||
http.Error(w, "Failed to save execution", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
// Create execution response
|
||||
execResp := ExecutionResponse{
|
||||
ID: execID,
|
||||
WorkflowID: id,
|
||||
Status: "running",
|
||||
StartedAt: now.Format(time.RFC3339),
|
||||
Inputs: req.Inputs,
|
||||
Outputs: make(map[string]interface{}),
|
||||
Logs: []ExecutionLog{},
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
json.NewEncoder(w).Encode(execResp)
|
||||
}
|
||||
|
||||
// GetExecution handles GET /executions/{id}
|
||||
func (api *WorkflowAPI) GetExecution(w http.ResponseWriter, r *http.Request, id string) {
|
||||
if r.Method != http.MethodGet {
|
||||
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
|
||||
execution, err := api.db.FetchExecution(r.Context(), id)
|
||||
if err != nil {
|
||||
http.Error(w, "Execution not found", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
|
||||
// Get logs from database
|
||||
logs, err := api.db.FetchExecutionLogs(r.Context(), id)
|
||||
if err != nil {
|
||||
api.logger.Printf("Failed to fetch logs: %v", err)
|
||||
}
|
||||
|
||||
execLogs := make([]ExecutionLog, 0)
|
||||
for _, log := range logs {
|
||||
execLogs = append(execLogs, ExecutionLog{
|
||||
Timestamp: log.LoggedAt.Format(time.RFC3339),
|
||||
NodeID: log.NodeID,
|
||||
Level: log.Level,
|
||||
Message: log.Message,
|
||||
})
|
||||
}
|
||||
|
||||
// Parse inputs/outputs
|
||||
var inputs map[string]interface{}
|
||||
var outputs map[string]interface{}
|
||||
json.Unmarshal(execution.Inputs, &inputs)
|
||||
if execution.Outputs != nil {
|
||||
json.Unmarshal(execution.Outputs, &outputs)
|
||||
}
|
||||
|
||||
// Check Temporal workflow status
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
|
||||
desc, err := api.temporalClient.DescribeWorkflowExecution(ctx, execution.TemporalID, "")
|
||||
status := execution.Status
|
||||
if err == nil && desc != nil {
|
||||
switch desc.Status.String() {
|
||||
case "RUNNING":
|
||||
status = "running"
|
||||
case "COMPLETED":
|
||||
status = "success"
|
||||
case "FAILED":
|
||||
status = "failed"
|
||||
}
|
||||
}
|
||||
|
||||
completedAtStr := ""
|
||||
if execution.CompletedAt != nil {
|
||||
completedAtStr = execution.CompletedAt.Format(time.RFC3339)
|
||||
}
|
||||
|
||||
execResp := ExecutionResponse{
|
||||
ID: execution.ID,
|
||||
WorkflowID: execution.WorkflowID,
|
||||
Status: status,
|
||||
StartedAt: execution.StartedAt.Format(time.RFC3339),
|
||||
CompletedAt: completedAtStr,
|
||||
Inputs: inputs,
|
||||
Outputs: outputs,
|
||||
Logs: execLogs,
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(execResp)
|
||||
}
|
||||
|
||||
// ListExecutions handles GET /workflows/{id}/executions
|
||||
func (api *WorkflowAPI) ListExecutions(w http.ResponseWriter, r *http.Request, workflowID string) {
|
||||
if r.Method != http.MethodGet {
|
||||
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
|
||||
// TODO: Implement query by workflow_id in database
|
||||
// For now, return empty list (needs DB method for filtering by workflow_id)
|
||||
list := make([]ExecutionResponse, 0)
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(list)
|
||||
}
|
||||
|
||||
// nodesToWorkflowSpec converts frontend nodes/edges to routing.WorkflowSpec
|
||||
func (api *WorkflowAPI) nodesToWorkflowSpec(wf *WorkflowResponse, inputs map[string]interface{}) *routing.WorkflowSpec {
|
||||
spec := &routing.WorkflowSpec{
|
||||
Name: wf.Name,
|
||||
Input: inputs,
|
||||
States: []routing.State{},
|
||||
}
|
||||
|
||||
// Build states from nodes
|
||||
stateMap := make(map[string]*routing.State)
|
||||
|
||||
// Create all states
|
||||
for _, node := range wf.Nodes {
|
||||
if node.Type == "activity" {
|
||||
state := &routing.State{
|
||||
Name: node.ID,
|
||||
Type: routing.StateTypeTask,
|
||||
Resource: node.Data.Activity,
|
||||
Parameters: node.Data.Config,
|
||||
End: false,
|
||||
}
|
||||
stateMap[node.ID] = state
|
||||
spec.States = append(spec.States, *state)
|
||||
}
|
||||
}
|
||||
|
||||
// Wire edges (transitions)
|
||||
for _, edge := range wf.Edges {
|
||||
if state, exists := stateMap[edge.Source]; exists {
|
||||
state.Next = edge.Target
|
||||
}
|
||||
}
|
||||
|
||||
// Mark last state as End
|
||||
if len(spec.States) > 0 {
|
||||
// Find state with no outgoing edge
|
||||
for i := range spec.States {
|
||||
hasNext := false
|
||||
for _, edge := range wf.Edges {
|
||||
if edge.Source == spec.States[i].Name {
|
||||
hasNext = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !hasNext {
|
||||
spec.States[i].End = true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return spec
|
||||
}
|
||||
@@ -473,10 +473,130 @@
|
||||
"dependencies": [],
|
||||
"notes": "Must run before LLM Router to provide auth token. Call early in workflow."
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "LLMInferenceActivity",
|
||||
"description": "Call LLM API with custom prompt and get response text",
|
||||
"category": "llm",
|
||||
"inputs": {
|
||||
"model": {
|
||||
"type": "string",
|
||||
"description": "Model ID (reasoning, ornith:35b, ornith:13b, qwen2.5:3b)",
|
||||
"required": true,
|
||||
"examples": ["reasoning", "ornith:35b"]
|
||||
},
|
||||
"system_prompt": {
|
||||
"type": "string",
|
||||
"description": "System instruction for the model",
|
||||
"required": false,
|
||||
"default": ""
|
||||
},
|
||||
"user_prompt": {
|
||||
"type": "string",
|
||||
"description": "User message to send to the model",
|
||||
"required": true
|
||||
},
|
||||
"temperature": {
|
||||
"type": "number",
|
||||
"description": "Sampling temperature (0.0-1.0, higher=more creative)",
|
||||
"required": false,
|
||||
"default": 0.7
|
||||
},
|
||||
"max_tokens": {
|
||||
"type": "integer",
|
||||
"description": "Maximum tokens in response",
|
||||
"required": false
|
||||
}
|
||||
},
|
||||
"outputs": {
|
||||
"response": {
|
||||
"type": "string",
|
||||
"description": "LLM response text"
|
||||
},
|
||||
"model": {
|
||||
"type": "string",
|
||||
"description": "Model used for inference"
|
||||
},
|
||||
"stop_reason": {
|
||||
"type": "string",
|
||||
"description": "Why inference stopped (stop_sequence, length, etc)"
|
||||
},
|
||||
"tokens_used": {
|
||||
"type": "integer",
|
||||
"description": "Total tokens consumed"
|
||||
}
|
||||
},
|
||||
"constraints": {
|
||||
"defaultTimeout": "120s",
|
||||
"isFlaky": true,
|
||||
"recommendedRetries": 2,
|
||||
"retryBackoff": 2.0,
|
||||
"dependencies": [],
|
||||
"notes": "API-dependent. Network flaky. Use for single prompts. See LLMBatchInferenceActivity for multiple."
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "LLMBatchInferenceActivity",
|
||||
"description": "Call LLM API multiple times sequentially with different prompts",
|
||||
"category": "llm",
|
||||
"inputs": {
|
||||
"model": {
|
||||
"type": "string",
|
||||
"description": "Model ID (reasoning, ornith:35b, ornith:13b, qwen2.5:3b)",
|
||||
"required": true
|
||||
},
|
||||
"system_prompt": {
|
||||
"type": "string",
|
||||
"description": "System instruction (same for all prompts)",
|
||||
"required": false
|
||||
},
|
||||
"prompts": {
|
||||
"type": "array",
|
||||
"description": "List of user prompts to process",
|
||||
"required": true,
|
||||
"items": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"temperature": {
|
||||
"type": "number",
|
||||
"description": "Sampling temperature (0.0-1.0)",
|
||||
"required": false,
|
||||
"default": 0.7
|
||||
}
|
||||
},
|
||||
"outputs": {
|
||||
"responses": {
|
||||
"type": "array",
|
||||
"description": "List of LLM responses (parallel to input prompts)",
|
||||
"items": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"model": {
|
||||
"type": "string",
|
||||
"description": "Model used"
|
||||
},
|
||||
"errors": {
|
||||
"type": "array",
|
||||
"description": "Error messages for failed prompts",
|
||||
"items": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
"constraints": {
|
||||
"defaultTimeout": "600s",
|
||||
"isFlaky": true,
|
||||
"recommendedRetries": 1,
|
||||
"retryBackoff": 2.0,
|
||||
"dependencies": [],
|
||||
"notes": "Sequential processing of multiple prompts. Use for batch analysis, summarization, etc."
|
||||
}
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"totalActivities": 10,
|
||||
"totalActivities": 12,
|
||||
"lastUpdated": "2025-08-31T00:00:00Z",
|
||||
"categories": {
|
||||
"repository": 1,
|
||||
@@ -488,7 +608,8 @@
|
||||
"approval": 1,
|
||||
"storage": 1,
|
||||
"memory": 1,
|
||||
"authentication": 1
|
||||
"authentication": 1,
|
||||
"llm": 2
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,178 @@
|
||||
package routing
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/rockliang/poimen/workflows/pkg/db"
|
||||
)
|
||||
|
||||
// CanvasConverter converts visual canvas to executable WorkflowSpec
|
||||
type CanvasConverter struct {
|
||||
validator *CanvasValidator
|
||||
}
|
||||
|
||||
// NewCanvasConverter creates a converter
|
||||
func NewCanvasConverter() *CanvasConverter {
|
||||
return &CanvasConverter{
|
||||
validator: NewCanvasValidator(),
|
||||
}
|
||||
}
|
||||
|
||||
// CanvasToWorkflowSpec converts canvas to WorkflowSpec
|
||||
func (cc *CanvasConverter) CanvasToWorkflowSpec(canvas *db.Canvas) (*WorkflowSpec, error) {
|
||||
// Validate first
|
||||
if err := cc.validator.ValidateCanvas(canvas); err != nil {
|
||||
return nil, fmt.Errorf("canvas validation failed: %w", err)
|
||||
}
|
||||
|
||||
// Get topological order
|
||||
sortedNodes, err := cc.validator.TopoSort(canvas.Nodes, canvas.Edges)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("topological sort failed: %w", err)
|
||||
}
|
||||
|
||||
// Build states from sorted nodes
|
||||
states := []State{}
|
||||
nodeToState := make(map[string]int) // node ID to state index
|
||||
|
||||
for i, node := range sortedNodes {
|
||||
state := cc.nodeToState(node, canvas.Edges)
|
||||
states = append(states, state)
|
||||
nodeToState[node.ID] = i
|
||||
}
|
||||
|
||||
// Wire up transitions
|
||||
for i, node := range sortedNodes {
|
||||
outgoing := cc.getOutgoingEdges(node.ID, canvas.Edges)
|
||||
|
||||
if len(outgoing) == 0 {
|
||||
// Last state - no transitions
|
||||
continue
|
||||
}
|
||||
|
||||
if len(outgoing) == 1 {
|
||||
// Single outgoing edge
|
||||
targetNode := outgoing[0]
|
||||
targetIdx := nodeToState[targetNode]
|
||||
if targetIdx > i {
|
||||
states[i].Next = states[targetIdx].Name
|
||||
}
|
||||
} else {
|
||||
// Multiple outgoing edges - parallel
|
||||
states[i].Type = "Parallel"
|
||||
branches := []interface{}{}
|
||||
for _, targetNode := range outgoing {
|
||||
branches = append(branches, map[string]string{
|
||||
"state": states[nodeToState[targetNode]].Name,
|
||||
})
|
||||
}
|
||||
if states[i].Branches == nil {
|
||||
states[i].Branches = branches
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
spec := &WorkflowSpec{
|
||||
Name: canvas.Name,
|
||||
Input: map[string]interface{}{},
|
||||
States: states,
|
||||
}
|
||||
|
||||
return spec, nil
|
||||
}
|
||||
|
||||
// nodeToState converts a canvas node to a workflow state
|
||||
func (cc *CanvasConverter) nodeToState(node db.WorkflowNode, edges []db.WorkflowEdge) State {
|
||||
// Map node type to activity name
|
||||
activityName := cc.mapActivityType(node.Type)
|
||||
|
||||
state := State{
|
||||
Name: node.ID,
|
||||
Type: TaskActivity,
|
||||
Activity: activityName,
|
||||
Retry: &RetryPolicy{MaxAttempts: 3, BackoffSeconds: 2},
|
||||
Timeout: "300s",
|
||||
Parameters: node.Data,
|
||||
}
|
||||
|
||||
return state
|
||||
}
|
||||
|
||||
// mapActivityType maps canvas activity type to Poimen activity
|
||||
func (cc *CanvasConverter) mapActivityType(canvasType string) string {
|
||||
typeMap := map[string]string{
|
||||
"clone-repo": "CloneRepoActivity",
|
||||
"analyze-code": "AnalyzeCodeActivity",
|
||||
"security-scan": "SecurityScanActivity",
|
||||
"generate-report": "GenerateReportActivity",
|
||||
"deployment-precheck": "DeploymentPreCheckActivity",
|
||||
"notify-status": "NotifyStatusActivity",
|
||||
"approve-workflow": "ApproveWorkflowActivity",
|
||||
"archive-results": "ArchiveResultsActivity",
|
||||
"retrieve-memory": "RetrieveMemoryActivity",
|
||||
"assume-role": "AssumeRoleActivity",
|
||||
"llm-inference": "LLMInferenceActivity",
|
||||
"llm-batch-inference": "LLMBatchInferenceActivity",
|
||||
}
|
||||
|
||||
if mapped, ok := typeMap[canvasType]; ok {
|
||||
return mapped
|
||||
}
|
||||
|
||||
return canvasType // fallback to type as-is
|
||||
}
|
||||
|
||||
// getOutgoingEdges returns target node IDs for a given source node
|
||||
func (cc *CanvasConverter) getOutgoingEdges(nodeID string, edges []db.WorkflowEdge) []string {
|
||||
targets := []string{}
|
||||
seen := make(map[string]bool)
|
||||
|
||||
for _, edge := range edges {
|
||||
if edge.Source == nodeID && !seen[edge.Target] {
|
||||
targets = append(targets, edge.Target)
|
||||
seen[edge.Target] = true
|
||||
}
|
||||
}
|
||||
|
||||
return targets
|
||||
}
|
||||
|
||||
// CanvasToExecutionPlan converts canvas to sequential activity list
|
||||
func (cc *CanvasConverter) CanvasToExecutionPlan(canvas *db.Canvas) ([]ExecutionStep, error) {
|
||||
// Validate first
|
||||
if err := cc.validator.ValidateCanvas(canvas); err != nil {
|
||||
return nil, fmt.Errorf("canvas validation failed: %w", err)
|
||||
}
|
||||
|
||||
// Get topological order
|
||||
sortedNodes, err := cc.validator.TopoSort(canvas.Nodes, canvas.Edges)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("topological sort failed: %w", err)
|
||||
}
|
||||
|
||||
steps := []ExecutionStep{}
|
||||
for i, node := range sortedNodes {
|
||||
step := ExecutionStep{
|
||||
Index: i,
|
||||
NodeID: node.ID,
|
||||
ActivityName: cc.mapActivityType(node.Type),
|
||||
Label: node.Label,
|
||||
Parameters: node.Data,
|
||||
Timeout: "300s",
|
||||
}
|
||||
steps = append(steps, step)
|
||||
}
|
||||
|
||||
return steps, nil
|
||||
}
|
||||
|
||||
// ExecutionStep represents one activity in execution plan
|
||||
type ExecutionStep struct {
|
||||
Index int `json:"index"`
|
||||
NodeID string `json:"node_id"`
|
||||
ActivityName string `json:"activity_name"`
|
||||
Label string `json:"label"`
|
||||
Parameters map[string]interface{} `json:"parameters"`
|
||||
Timeout string `json:"timeout"`
|
||||
DependsOn []int `json:"depends_on,omitempty"` // Indices of predecessor steps
|
||||
}
|
||||
@@ -0,0 +1,316 @@
|
||||
package routing
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/rockliang/poimen/workflows/pkg/db"
|
||||
)
|
||||
|
||||
// CanvasValidator validates React Flow canvas (nodes + edges)
|
||||
type CanvasValidator struct {
|
||||
activityRegistry map[string]bool
|
||||
}
|
||||
|
||||
// NewCanvasValidator creates validator with activity registry
|
||||
func NewCanvasValidator() *CanvasValidator {
|
||||
return &CanvasValidator{
|
||||
activityRegistry: map[string]bool{
|
||||
"clone-repo": true,
|
||||
"analyze-code": true,
|
||||
"security-scan": true,
|
||||
"generate-report": true,
|
||||
"deployment-precheck": true,
|
||||
"notify-status": true,
|
||||
"approve-workflow": true,
|
||||
"archive-results": true,
|
||||
"retrieve-memory": true,
|
||||
"assume-role": true,
|
||||
"llm-inference": true,
|
||||
"llm-batch-inference": true,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// ValidateCanvas checks canvas structure, connectivity, and DAG
|
||||
func (cv *CanvasValidator) ValidateCanvas(canvas *db.Canvas) error {
|
||||
if canvas == nil {
|
||||
return fmt.Errorf("canvas is nil")
|
||||
}
|
||||
|
||||
if len(canvas.Nodes) == 0 {
|
||||
return fmt.Errorf("canvas has no nodes")
|
||||
}
|
||||
|
||||
// Step 1: Validate nodes
|
||||
if err := cv.validateNodes(canvas.Nodes); err != nil {
|
||||
return fmt.Errorf("node validation failed: %w", err)
|
||||
}
|
||||
|
||||
// Step 2: Validate edges
|
||||
if err := cv.validateEdges(canvas.Nodes, canvas.Edges); err != nil {
|
||||
return fmt.Errorf("edge validation failed: %w", err)
|
||||
}
|
||||
|
||||
// Step 3: Check for cycles (must be DAG)
|
||||
if err := cv.detectCycles(canvas.Nodes, canvas.Edges); err != nil {
|
||||
return fmt.Errorf("cycle detected: %w", err)
|
||||
}
|
||||
|
||||
// Step 4: Check connectivity (all nodes reachable from start)
|
||||
if err := cv.validateConnectivity(canvas.Nodes, canvas.Edges); err != nil {
|
||||
return fmt.Errorf("connectivity check failed: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// validateNodes checks each node has required fields and valid type
|
||||
func (cv *CanvasValidator) validateNodes(nodes []db.WorkflowNode) error {
|
||||
if len(nodes) == 0 {
|
||||
return fmt.Errorf("no nodes in canvas")
|
||||
}
|
||||
|
||||
nodeIds := make(map[string]bool)
|
||||
|
||||
for i, node := range nodes {
|
||||
// Check required fields
|
||||
if node.ID == "" {
|
||||
return fmt.Errorf("node[%d] has empty ID", i)
|
||||
}
|
||||
|
||||
if nodeIds[node.ID] {
|
||||
return fmt.Errorf("node[%d] has duplicate ID: %s", i, node.ID)
|
||||
}
|
||||
nodeIds[node.ID] = true
|
||||
|
||||
if node.Label == "" {
|
||||
return fmt.Errorf("node[%d] (%s) has empty label", i, node.ID)
|
||||
}
|
||||
|
||||
if node.Position == nil {
|
||||
return fmt.Errorf("node[%d] (%s) has no position", i, node.ID)
|
||||
}
|
||||
|
||||
// Check activity type (if present)
|
||||
if node.Type != "" && !cv.activityRegistry[strings.ToLower(node.Type)] {
|
||||
return fmt.Errorf("node[%d] (%s) has unknown activity type: %s", i, node.ID, node.Type)
|
||||
}
|
||||
|
||||
// Check data structure
|
||||
if node.Data == nil {
|
||||
return fmt.Errorf("node[%d] (%s) has no data", i, node.ID)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// validateEdges checks edges reference valid nodes
|
||||
func (cv *CanvasValidator) validateEdges(nodes []db.WorkflowNode, edges []db.WorkflowEdge) error {
|
||||
nodeIds := make(map[string]bool)
|
||||
for _, node := range nodes {
|
||||
nodeIds[node.ID] = true
|
||||
}
|
||||
|
||||
for i, edge := range edges {
|
||||
// Check required fields
|
||||
if edge.Source == "" {
|
||||
return fmt.Errorf("edge[%d] has empty source", i)
|
||||
}
|
||||
|
||||
if edge.Target == "" {
|
||||
return fmt.Errorf("edge[%d] has empty target", i)
|
||||
}
|
||||
|
||||
// Check source node exists
|
||||
if !nodeIds[edge.Source] {
|
||||
return fmt.Errorf("edge[%d] references unknown source node: %s", i, edge.Source)
|
||||
}
|
||||
|
||||
// Check target node exists
|
||||
if !nodeIds[edge.Target] {
|
||||
return fmt.Errorf("edge[%d] references unknown target node: %s", i, edge.Target)
|
||||
}
|
||||
|
||||
// Check self-loops (discouraged but allow for now)
|
||||
if edge.Source == edge.Target {
|
||||
// Could warn here but not fail
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// detectCycles checks for cycles in the DAG (must be acyclic)
|
||||
func (cv *CanvasValidator) detectCycles(nodes []db.WorkflowNode, edges []db.WorkflowEdge) error {
|
||||
// Build adjacency list
|
||||
graph := make(map[string][]string)
|
||||
inDegree := make(map[string]int)
|
||||
|
||||
for _, node := range nodes {
|
||||
graph[node.ID] = []string{}
|
||||
inDegree[node.ID] = 0
|
||||
}
|
||||
|
||||
for _, edge := range edges {
|
||||
graph[edge.Source] = append(graph[edge.Source], edge.Target)
|
||||
inDegree[edge.Target]++
|
||||
}
|
||||
|
||||
// Kahn's algorithm: topological sort
|
||||
queue := []string{}
|
||||
for _, node := range nodes {
|
||||
if inDegree[node.ID] == 0 {
|
||||
queue = append(queue, node.ID)
|
||||
}
|
||||
}
|
||||
|
||||
processed := 0
|
||||
for len(queue) > 0 {
|
||||
// Dequeue
|
||||
current := queue[0]
|
||||
queue = queue[1:]
|
||||
processed++
|
||||
|
||||
// Visit neighbors
|
||||
for _, neighbor := range graph[current] {
|
||||
inDegree[neighbor]--
|
||||
if inDegree[neighbor] == 0 {
|
||||
queue = append(queue, neighbor)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// If we didn't process all nodes, there's a cycle
|
||||
if processed != len(nodes) {
|
||||
return fmt.Errorf("graph has cycle (processed %d/%d nodes)", processed, len(nodes))
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// validateConnectivity checks all nodes are reachable from start nodes
|
||||
func (cv *CanvasValidator) validateConnectivity(nodes []db.WorkflowNode, edges []db.WorkflowEdge) error {
|
||||
if len(nodes) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Build adjacency list
|
||||
graph := make(map[string][]string)
|
||||
inDegree := make(map[string]int)
|
||||
|
||||
for _, node := range nodes {
|
||||
graph[node.ID] = []string{}
|
||||
inDegree[node.ID] = 0
|
||||
}
|
||||
|
||||
for _, edge := range edges {
|
||||
graph[edge.Source] = append(graph[edge.Source], edge.Target)
|
||||
inDegree[edge.Target]++
|
||||
}
|
||||
|
||||
// Find start nodes (in-degree 0)
|
||||
startNodes := []string{}
|
||||
for _, node := range nodes {
|
||||
if inDegree[node.ID] == 0 {
|
||||
startNodes = append(startNodes, node.ID)
|
||||
}
|
||||
}
|
||||
|
||||
if len(startNodes) == 0 {
|
||||
return fmt.Errorf("no start nodes found (all nodes have incoming edges)")
|
||||
}
|
||||
|
||||
// BFS from all start nodes
|
||||
visited := make(map[string]bool)
|
||||
queue := startNodes
|
||||
|
||||
for len(queue) > 0 {
|
||||
// Dequeue
|
||||
current := queue[0]
|
||||
queue = queue[1:]
|
||||
|
||||
if visited[current] {
|
||||
continue
|
||||
}
|
||||
visited[current] = true
|
||||
|
||||
// Visit neighbors
|
||||
for _, neighbor := range graph[current] {
|
||||
if !visited[neighbor] {
|
||||
queue = append(queue, neighbor)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Check all nodes were visited
|
||||
if len(visited) != len(nodes) {
|
||||
unreached := []string{}
|
||||
for _, node := range nodes {
|
||||
if !visited[node.ID] {
|
||||
unreached = append(unreached, node.ID)
|
||||
}
|
||||
}
|
||||
return fmt.Errorf("unreachable nodes: %v", unreached)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// TopoSort returns nodes in topological order (execution order)
|
||||
func (cv *CanvasValidator) TopoSort(nodes []db.WorkflowNode, edges []db.WorkflowEdge) ([]db.WorkflowNode, error) {
|
||||
if len(nodes) == 0 {
|
||||
return []db.WorkflowNode{}, nil
|
||||
}
|
||||
|
||||
// Build adjacency list and in-degree map
|
||||
graph := make(map[string][]string)
|
||||
inDegree := make(map[string]int)
|
||||
nodeMap := make(map[string]db.WorkflowNode)
|
||||
|
||||
for _, node := range nodes {
|
||||
graph[node.ID] = []string{}
|
||||
inDegree[node.ID] = 0
|
||||
nodeMap[node.ID] = node
|
||||
}
|
||||
|
||||
for _, edge := range edges {
|
||||
graph[edge.Source] = append(graph[edge.Source], edge.Target)
|
||||
inDegree[edge.Target]++
|
||||
}
|
||||
|
||||
// Kahn's algorithm
|
||||
queue := []string{}
|
||||
for _, node := range nodes {
|
||||
if inDegree[node.ID] == 0 {
|
||||
queue = append(queue, node.ID)
|
||||
}
|
||||
}
|
||||
|
||||
result := []db.WorkflowNode{}
|
||||
processed := make(map[string]bool)
|
||||
|
||||
for len(queue) > 0 {
|
||||
// Dequeue
|
||||
current := queue[0]
|
||||
queue = queue[1:]
|
||||
|
||||
result = append(result, nodeMap[current])
|
||||
processed[current] = true
|
||||
|
||||
// Visit neighbors
|
||||
for _, neighbor := range graph[current] {
|
||||
inDegree[neighbor]--
|
||||
if inDegree[neighbor] == 0 {
|
||||
queue = append(queue, neighbor)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if len(result) != len(nodes) {
|
||||
return nil, fmt.Errorf("topological sort failed: graph has cycle")
|
||||
}
|
||||
|
||||
return result, nil
|
||||
}
|
||||
Reference in New Issue
Block a user