### Gorkflow Main Function Example Source: https://cai139193541.gitbook.io/gorkflow/docs/getting-started/quick-start A complete Go program demonstrating the creation, building, execution, and retrieval of a simple calculation workflow using the Gorkflow library. It includes step definitions, workflow composition, engine setup, and result fetching. ```go package main import ( "context" "fmt" "log" "github.com/sicko7947/gorkflow" "github.com/sicko7947/gorkflow/engine" "github.com/sicko7947/gorkflow/store" ) // Define your data types type CalculationInput struct { A int `json:"a"` B int `json:"b"` } type SumOutput struct { Sum int `json:"sum"` } type ProductOutput struct { Product int `json:"product"` } type ResultOutput struct { Result int `json:"result"` Message string `json:"message"` } func main() { // Step 1: Create steps addStep := gorkflow.NewStep( "add", "Add Numbers", func(ctx *gorkflow.StepContext, input CalculationInput) (SumOutput, error) { sum := input.A + input.B ctx.Logger.Info().Int("sum", sum).Msg("Addition completed") return SumOutput{Sum: sum}, nil }, ) multiplyStep := gorkflow.NewStep( "multiply", "Multiply by 2", func(ctx *gorkflow.StepContext, input SumOutput) (ProductOutput, error) { product := input.Sum * 2 ctx.Logger.Info().Int("product", product).Msg("Multiplication completed") return ProductOutput{Product: product}, nil }, ) formatStep := gorkflow.NewStep( "format", "Format Result", func(ctx *gorkflow.StepContext, input ProductOutput) (ResultOutput, error) { message := fmt.Sprintf("Final result: %d", input.Product) return ResultOutput{ Result: input.Product, Message: message, }, }, ) // Step 2: Build the workflow wf, err := gorkflow.NewWorkflow("calculation", "Calculation Workflow"). WithDescription("A simple calculation workflow"). WithVersion("1.0"). Sequence(addStep, multiplyStep, formatStep). Build() if err != nil { log.Fatal("Failed to build workflow:", err) } // Step 3: Create engine and storage store := store.NewMemoryStore() eng := engine.NewEngine(store) // Step 4: Execute the workflow ctx := context.Background() runID, err := eng.StartWorkflow( ctx, wf, CalculationInput{A: 10, B: 5}, ) if err != nil { log.Fatal("Failed to start workflow:", err) } fmt.Printf("Workflow started with ID: %s\n", runID) // Step 5: Get the result run, err := eng.GetRun(ctx, runID) if err != nil { log.Fatal("Failed to get workflow status:", err) } fmt.Printf("Status: %s\n", run.Status) fmt.Printf("Progress: %.0f%%\n", run.Progress*100) if run.Output != nil { fmt.Printf("Output: %s\n", string(run.Output)) } } ``` -------------------------------- ### Verify Gorkflow Installation Source: https://cai139193541.gitbook.io/gorkflow/docs/getting-started/installation A basic Go program to create and print the name of a Gorkflow instance, confirming successful installation. Run with `go run main.go`. ```go package main import ( "fmt" workflow "github.com/sicko7947/gorkflow" ) func main() { wf, err := workflow.NewWorkflow("test", "Test Workflow").Build() if err != nil { panic(err) } fmt.Printf("Created workflow: %s\n", wf.Name) } ``` -------------------------------- ### Start Workflow Server Source: https://cai139193541.gitbook.io/gorkflow/example/parallel Command to start the Go application server for the workflow. This command assumes the main entry point is in `main/main.go` and is used to make the workflow API available. ```bash go run main/main.go ``` -------------------------------- ### Run Validation Example (Bash) Source: https://cai139193541.gitbook.io/gorkflow/example/validation Command to navigate to the validation example directory and execute the Go program. ```bash cd example/validation go run main.go ``` -------------------------------- ### Project Setup for Gorkflow User Registration Source: https://cai139193541.gitbook.io/gorkflow/docs/getting-started/first-workflow This snippet demonstrates the initial setup for a new Gorkflow project. It involves creating a project directory, initializing Go modules, and fetching the Gorkflow dependency. This is a prerequisite for building the workflow. ```bash mkdir user-registration cd user-registration go mod init user-registration go get github.com/sicko7947/gorkflow ``` -------------------------------- ### Complete Workflow Example with Conditional Steps (Go) Source: https://cai139193541.gitbook.io/gorkflow/docs/advanced-usage/conditional-execution A full example demonstrating a workflow with multiple conditional steps. It includes setup, processing, and formatting steps, each controlled by specific conditions derived from the workflow's state. ```go package main import ( "github.com/sicko7947/gorkflow" ) type SetupInput struct { ProcessData bool `json:"processData"` UseFormatted bool `json:"useFormatted"` } type SetupOutput struct { ProcessData bool `json:"processData"` UseFormatted bool `json:"useFormatted"` } type ProcessedData struct { Data string `json:"data"` } type FormattedData struct { Formatted string `json:"formatted"` } func main() { // Setup step - sets flags in state setupStep := gorkflow.NewStep( "setup", "Setup Flags", func(ctx *gorkflow.StepContext, input SetupInput) (SetupOutput, error) { // Store flags in workflow state ctx.State.Set(ctx.Context, "process_data", input.ProcessData) ctx.State.Set(ctx.Context, "use_formatted", input.UseFormatted) return SetupOutput{ ProcessData: input.ProcessData, UseFormatted: input.UseFormatted, }, nil }, ) // Processing step - conditional processStep := gorkflow.NewStep( "process", "Process Data", func(ctx *gorkflow.StepContext, input SetupOutput) (ProcessedData, error) { return ProcessedData{Data: "Processed!"}, nil }, ) // Formatting step - conditional formatStep := gorkflow.NewStep( "format", "Format Data", func(ctx *gorkflow.StepContext, input ProcessedData) (FormattedData, error) { return FormattedData{Formatted: "Formatted: " + input.Data}, nil }, ) // Condition: Should we process? shouldProcess := func(ctx *gorkflow.StepContext) (bool, error) { var processData bool ctx.State.Get("process_data", &processData) return processData, nil } // Condition: Should we format? shouldFormat := func(ctx *gorkflow.StepContext) (bool, error) { var useFormatted bool ctx.State.Get("use_formatted", &useFormatted) return useFormatted, nil } // Build workflow with conditional steps wf, _ := gorkflow.NewWorkflow("conditional-wf", "Conditional Workflow"). ThenStep(setupStep). ThenStepIf(processStep, shouldProcess, nil). ThenStepIf(formatStep, shouldFormat, nil). Build() } ``` -------------------------------- ### Initialize LibSQL Store for Development in Go Source: https://cai139193541.gitbook.io/gorkflow/docs/storage/libsql-store Example of initializing a LibSQL store using a local file path, suitable for development environments. Assumes the 'store' package is available. ```go store, _ := store.NewLibSQLStore("file:./dev-workflows.db") ``` -------------------------------- ### Choosing LibSQL for Small Applications in Go Source: https://cai139193541.gitbook.io/gorkflow/docs/storage/overview Example code for selecting the LibSQL store with a local file for small applications with Gorkflow. This approach balances persistence with ease of setup for smaller workloads. ```go // Use LibSQL with local file store, _ := store.NewLibSQLStore("file:./workflows.db") ``` -------------------------------- ### Turso CLI Installation (macOS/Linux) Source: https://cai139193541.gitbook.io/gorkflow/docs/storage/libsql-store Provides instructions for installing the Turso command-line interface on macOS and Linux systems. This CLI is used for managing Turso databases, including creation and authentication. ```bash # macOS/Linux curl -sSfL https://get.tur.so/install.sh | bash # Or with Homebrew brew install tursodatabase/tap/turso ``` -------------------------------- ### Install Go Extension for VS Code Source: https://cai139193541.gitbook.io/gorkflow/docs/getting-started/installation Command to install the official Go extension for Visual Studio Code, providing enhanced Go development features. ```bash code --install-extension golang.go ``` -------------------------------- ### Install Optional DynamoDB Store Dependencies Source: https://cai139193541.gitbook.io/gorkflow/docs/getting-started/installation Installs the necessary AWS SDK v2 packages to enable Gorkflow's DynamoDB storage backend. ```bash go get github.com/aws/aws-sdk-go-v2 go get github.com/aws/aws-sdk-go-v2/service/dynamodb ``` -------------------------------- ### Go: Set Workflow State in Setup Step Source: https://cai139193541.gitbook.io/gorkflow/example/conditional This Go code demonstrates how to store data within the gorkflow context's state during a setup step. The `ctx.State.Set` method is used to persist the `enable_doubling` flag, making it accessible for condition checks in subsequent conditional steps. ```go ctx.State.Set("enable_doubling", input.EnableDoubling) ``` -------------------------------- ### Initialize Gorkflow Engine and Storage in Go Source: https://cai139193541.gitbook.io/gorkflow/docs/getting-started/quick-start Set up the Gorkflow execution environment by creating a storage backend (e.g., `store.NewMemoryStore`) and an engine instance (`engine.NewEngine`). The engine orchestrates workflow execution, and the store persists workflow state. ```go store := store.NewMemoryStore() eng := engine.NewEngine(store) ``` -------------------------------- ### Correct Gorkflow Package Imports Source: https://cai139193541.gitbook.io/gorkflow/docs/getting-started/installation Demonstrates the correct import paths for the main Gorkflow package and its sub-packages like 'engine' and 'store'. Essential for avoiding import errors. ```go import ( "github.com/sicko7947/gorkflow" // Main package "github.com/sicko7947/gorkflow/engine" // Engine "github.com/sicko7947/gorkflow/store" // Storage backends ) ``` -------------------------------- ### Install Optional LibSQL/SQLite Store Dependency Source: https://cai139193541.gitbook.io/gorkflow/docs/getting-started/installation Installs the LibSQL client library for Go, allowing Gorkflow to use local SQLite files or remote Turso databases as a storage backend. ```bash go get github.com/tursodatabase/libsql-client-go/libsql ``` -------------------------------- ### Start Gorkflow with Runtime Tags Source: https://cai139193541.gitbook.io/gorkflow/docs/core-concepts/workflows Demonstrates how to provide runtime-specific tags when starting a Gorkflow execution using `eng.StartWorkflow`. These tags can be used for granular tracking and filtering of individual workflow runs. ```go runID, _ := eng.StartWorkflow(ctx, wf, input, gorkflow.WithTags(map[string]string{ "user_id": "12345", "request_id": "abc-def", }), ) ``` -------------------------------- ### Add Gorkflow to Go Project Source: https://cai139193541.gitbook.io/gorkflow/docs/getting-started/installation Installs the Gorkflow library into your Go project and updates your `go.mod` file. Ensure you have Go 1.21 or higher and a module-enabled project. ```bash go get github.com/sicko7947/gorkflow ``` ```go require ( github.com/sicko7947/gorkflow v0.1.0 ) ``` -------------------------------- ### Define Parallel Workflow Steps in Go Source: https://cai139193541.gitbook.io/gorkflow/example/parallel Illustrates how to use the `Sequence` and `Parallel` builder methods to construct a workflow with parallel execution paths in Go. This method is used to define the structure of the workflow, starting with an initial step and then branching into parallel operations. ```go builder. Sequence(NewStartStep()). Parallel( NewAddStep(), NewMultiplyStep(), ) ``` -------------------------------- ### Execute a Gorkflow Workflow in Go Source: https://cai139193541.gitbook.io/gorkflow/docs/getting-started/quick-start Initiate workflow execution using `eng.StartWorkflow`, providing a context, the workflow definition, and input data. The engine returns a unique run ID for tracking the workflow's execution. ```go ctx := context.Background() runID, err := eng.StartWorkflow( ctx, wf, CalculationInput{A: 10, B: 5}, ) if err != nil { log.Fatal("Failed to start workflow:", err) } fmt.Printf("Workflow started with ID: %s\n", runID) ``` -------------------------------- ### Integrate Custom Logger with Gorkflow Engine in Go Source: https://cai139193541.gitbook.io/gorkflow/docs/getting-started/quick-start Shows how to integrate a custom logger, specifically Zerolog, with the Gorkflow engine. This allows for more detailed and structured logging of workflow execution. Requires the zerolog and gorkflow libraries. ```go logger := zerolog.New(os.Stdout).With().Timestamp().Logger() eng := engine.NewEngine(store, engine.WithLogger(logger)) ``` -------------------------------- ### Gorkflow Complete Parallel Execution Example Source: https://cai139193541.gitbook.io/gorkflow/docs/advanced-usage/parallel-execution A comprehensive Go example illustrating parallel execution in Gorkflow. It defines input/output structures for parallel processing steps and an aggregation step that collects results from parallel tasks. The workflow is built using the Parallel() builder, showcasing a practical implementation. ```go package main import ( "fmt" "time" "github.com/sicko7947/gorkflow" ) type DataInput struct { ID int `json:"id"` } type ProcessedA struct { ResultA string `json:"resultA"` } type ProcessedB struct { ResultB string `json:"resultB"` } type ProcessedC struct { ResultC string `json:"resultC"` } type AggregatedOutput struct { Combined string `json:"combined"` } func main() { // Create parallel steps processA := gorkflow.NewStep( "process-a", "Process A", func(ctx *gorkflow.StepContext, input DataInput) (ProcessedA, error) { time.Sleep(1 * time.Second) // Simulate work return ProcessedA{ResultA: fmt.Sprintf("A-%d", input.ID)}, nil }, ) processB := gorkflow.NewStep( "process-b", "Process B", func(ctx *gorkflow.StepContext, input DataInput) (ProcessedB, error) { time.Sleep(1 * time.Second) // Simulate work return ProcessedB{ResultB: fmt.Sprintf("B-%d", input.ID)}, nil }, ) processC := gorkflow.NewStep( "process-c", "Process C", func(ctx *gorkflow.StepContext, input DataInput) (ProcessedC, error) { time.Sleep(1 * time.Second) // Simulate work return ProcessedC{ResultC: fmt.Sprintf("C-%d", input.ID)}, nil }, ) // Aggregate results aggregate := gorkflow.NewStep( "aggregate", "Aggregate Results", func(ctx *gorkflow.StepContext, input DataInput) (AggregatedOutput, error) { // Get outputs from all parallel steps var a ProcessedA var b ProcessedB var c ProcessedC ctx.Outputs.Get(ctx.Context, "process-a", &a) ctx.Outputs.Get(ctx.Context, "process-b", &b) ctx.Outputs.Get(ctx.Context, "process-c", &c) combined := fmt.Sprintf("%s|%s|%s", a.ResultA, b.ResultB, c.ResultC) return AggregatedOutput{Combined: combined}, nil }, ) // Build workflow with parallel execution wf, _ := gorkflow.NewWorkflow("parallel-wf", "Parallel Workflow"). Parallel(processA, processB, processC). ThenStep(aggregate). Build() } ``` -------------------------------- ### Migrate Workflows from Memory to LibSQL Store Source: https://cai139193541.gitbook.io/gorkflow/docs/storage/overview Provides an example of migrating from a Memory store to a LibSQL store. This involves setting up both stores and then initializing the engine with the new LibSQL store for continued operation. ```go // Old development setup memStore := store.NewMemoryStore() // New production setup libsqlStore, _ := store.NewLibSQLStore("file:./workflows.db") // Use libsqlStore instead of memStore eng := engine.NewEngine(libsqlStore) ``` -------------------------------- ### Retrieve Gorkflow Run Status and Output in Go Source: https://cai139193541.gitbook.io/gorkflow/docs/getting-started/quick-start Fetch the status, progress, and output of a running or completed workflow using `eng.GetRun` with the workflow's run ID. This allows monitoring and retrieving results. ```go run, err := eng.GetRun(ctx, runID) if err != nil { log.Fatal("Failed to get workflow status:", err) } fmt.Printf("Status: %s\n", run.Status) fmt.Printf("Progress: %.0f%%\n", run.Progress*100) if run.Output != nil { fmt.Printf("Output: %s\n", string(run.Output)) } ``` -------------------------------- ### Example of Using Reusable Steps in Go Workflows Source: https://cai139193541.gitbook.io/gorkflow/docs/getting-started/project-structure Demonstrates how to instantiate and use a reusable email sending step within different Gorkflow definitions. This example shows the `email.NewSendStep` function being called in both a registration and a password reset workflow context, highlighting its reusability. ```go // In registration workflow emailStep := email.NewSendStep(emailService) // In password reset workflow emailStep := email.NewSendStep(emailService) ``` -------------------------------- ### Build a Gorkflow Workflow in Go Source: https://cai139193541.gitbook.io/gorkflow/docs/getting-started/quick-start Compose workflow steps into a sequence using Gorkflow's fluent builder API. Use `gorkflow.NewWorkflow` to initialize, `Sequence()` to define step order, and `Build()` to finalize the workflow definition. ```go wf, err := gorkflow.NewWorkflow("calculation", "Calculation Workflow"). WithDescription("A simple calculation workflow"). WithVersion("1.0"). Sequence(addStep, multiplyStep, formatStep). Build() if err != nil { log.Fatal("Failed to build workflow:", err) } ``` -------------------------------- ### Install Gorkflow using Go Modules Source: https://cai139193541.gitbook.io/gorkflow/docs This command installs the Gorkflow library using Go's built-in package management system. It ensures that the latest version of the library is fetched and made available for use in your Go projects. ```bash go get github.com/sicko7947/gorkflow ``` -------------------------------- ### Create Gorkflow Steps in Go Source: https://cai139193541.gitbook.io/gorkflow/docs/getting-started/quick-start Define individual workflow steps using `gorkflow.NewStep`. Each step includes a unique ID, a human-readable name, and a function containing the business logic. Go generics are used for type-safe inputs and outputs. ```go addStep := gorkflow.NewStep( "add", "Add Numbers", func(ctx *gorkflow.StepContext, input CalculationInput) (SumOutput, error) { sum := input.A + input.B ctx.Logger.Info().Int("sum", sum).Msg("Addition completed") return SumOutput{Sum: sum}, nil }, ) multiplyStep := gorkflow.NewStep( "multiply", "Multiply by 2", func(ctx *gorkflow.StepContext, input SumOutput) (ProductOutput, error) { product := input.Sum * 2 ctx.Logger.Info().Int("product", product).Msg("Multiplication completed") return ProductOutput{Product: product}, nil }, ) formatStep := gorkflow.NewStep( "format", "Format Result", func(ctx *gorkflow.StepContext, input ProductOutput) (ResultOutput, error) { message := fmt.Sprintf("Final result: %d", input.Product) return ResultOutput{ Result: input.Product, Message: message, }, }, ) ``` -------------------------------- ### Enable Input or Output Validation Only (Go) Source: https://cai139193541.gitbook.io/gorkflow/example/validation Demonstrates how to selectively enable either input validation or output validation for a gorkflow step. ```go // Validate input only step := workflow.NewStep( "my_step", "My Step", handler, workflow.WithInputValidation(), ) // Validate output only step := workflow.NewStep( "my_step", "My Step", handler, workflow.WithOutputValidation(), ) ``` -------------------------------- ### Configure Step Retries and Timeouts in Go Source: https://cai139193541.gitbook.io/gorkflow/docs/getting-started/quick-start Demonstrates how to configure retry attempts and execution timeouts for a Gorkflow step. This ensures robustness by automatically retrying failed steps and preventing them from running indefinitely. Relies on the gorkflow library. ```go step := gorkflow.NewStep("my-step", "My Step", handler, gorkflow.WithRetries(3), gorkflow.WithTimeout(30 * time.Second), ) ``` -------------------------------- ### Initialize Memory Store in Go Source: https://cai139193541.gitbook.io/gorkflow/docs/storage/overview Demonstrates how to create and use an in-memory store for Gorkflow. This is suitable for development and testing as it requires zero setup and offers fast performance but lacks persistence and scalability. ```go import "github.com/sicko7947/gorkflow/store" // Create store store := store.NewMemoryStore() // Use with engine eng := engine.NewEngine(store) ``` -------------------------------- ### Build a Sequential Workflow in Go Source: https://cai139193541.gitbook.io/gorkflow/example/sequential Assembles a sequential workflow using the gorkflow builder pattern. The .Sequence() method chains multiple steps in the desired order, creating a linear execution flow. The workflow is finalized with the .Build() method. ```go builder.NewWorkflow("sequential", "Simple Math Workflow"). Sequence( NewAddStep(), NewMultiplyStep(), NewFormatStep(), ). Build() ``` -------------------------------- ### Enable Step with Custom Validator Instance (Go) Source: https://cai139193541.gitbook.io/gorkflow/example/validation Shows how to integrate a custom validator instance, potentially with registered custom validation rules, into a gorkflow step. ```go import "github.com/go-playground/validator/v10" // Create custom validator with custom rules customValidator := validator.New() customValidator.RegisterValidation("custom_rule", myCustomValidationFunc) step := workflow.NewStep( "my_step", "My Step", handler, workflow.WithCustomValidator(customValidator), workflow.WithValidation(workflow.DefaultValidationConfig), ) ``` -------------------------------- ### Create Focused Gorkflow Steps Source: https://cai139193541.gitbook.io/gorkflow/docs/core-concepts/steps Illustrates the principle of keeping Gorkflow steps focused on a single task. This example shows creating separate steps for validation, creation, and emailing, promoting modularity. ```go validateStep := gorkflow.NewStep("validate", "Validate", validateHandler) createStep := gorkflow.NewStep("create", "Create", createHandler) emailStep := gorkflow.NewStep("email", "Send Email", emailHandler) ``` -------------------------------- ### Add Tags to Gorkflow Execution in Go Source: https://cai139193541.gitbook.io/gorkflow/docs/getting-started/quick-start Illustrates how to attach metadata tags to a Gorkflow execution. Tags can be used for organizing, filtering, and identifying workflows, such as specifying the environment or team responsible. Uses the gorkflow library. ```go runID, _ := eng.StartWorkflow(ctx, wf, input, gorkflow.WithTags(map[string]string{ "environment": "production", "team": "backend", }), ) ``` -------------------------------- ### Inspect LibSQL Database with sqlite3 (Bash) Source: https://cai139193541.gitbook.io/gorkflow/example/libsql_persistence Provides bash commands to inspect the `workflow.db` SQLite file created by the LibSQL store. Users can open the database, list tables, and query workflow run and step execution data directly using SQL. ```bash # Open the database with sqlite3 sqlite3 workflow.db # View tables .tables # View workflow runs SELECT run_id, workflow_id, status, created_at FROM workflow_runs; # View step executions (sorted by execution_index) SELECT run_id, step_id, execution_index, status FROM step_executions ORDER BY execution_index; # Exit .quit ``` -------------------------------- ### Test Gorkflow Workflows in Go Source: https://cai139193541.gitbook.io/gorkflow/docs/troubleshooting/common-issues Shows a basic Go test case for a Gorkflow. It sets up an engine with a MemoryStore, starts a workflow, and asserts that the workflow completes successfully and has the expected status. ```go func TestMyWorkflow(t *testing.T) { store := store.NewMemoryStore() eng := engine.NewEngine(store) wf, _ := NewMyWorkflow() runID, err := eng.StartWorkflow(context.Background(), wf, input) if err != nil { t.Fatal(err) } run, _ := eng.GetRun(context.Background(), runID) if run.Status != "completed" { t.Errorf("Expected completed, got %s", run.Status) } } ``` -------------------------------- ### Go User Input with Documentation Example Source: https://cai139193541.gitbook.io/gorkflow/docs/core-concepts/validation Shows a Go struct for user input with detailed inline documentation explaining the validation rules for each field. This includes email format, username constraints, and age limits. ```go // UserInput represents user registration data. // // Validation Rules: // - Email: Required, must be valid email format // - Username: Required, 3-20 alphanumeric characters // - Age: Required, must be 18-120 type UserInput struct { Email string `json:"email" validate:"required,email" Username string `json:"username" validate:"required,min=3,max=20,alphanum" Age int `json:"age" validate:"required,gte=18,lte=120" } ``` -------------------------------- ### Initialize LibSQL Store for Production in Go Source: https://cai139193541.gitbook.io/gorkflow/docs/storage/libsql-store Shows how to initialize a LibSQL store for production by connecting to a Turso URL obtained from an environment variable. Requires the 'os' package. ```go import "os" store, _ := store.NewLibSQLStore(os.Getenv("TURSO_URL")) ``` -------------------------------- ### Use Persistent Storage in Gorkflow Source: https://cai139193541.gitbook.io/gorkflow/docs/getting-started/first-workflow Provides examples of configuring Gorkflow to use persistent storage backends instead of in-memory storage. It shows how to set up both AWS DynamoDB and LibSQL (SQLite) for storing workflow state and data. ```go // Use DynamoDB cfg, _ := config.LoadDefaultConfig(context.Background()) client := dynamodb.NewFromConfig(cfg) store, _ := store.NewDynamoDBStore(client, "workflows") // Or use LibSQL store, _ := store.NewLibSQLStore("file:./workflows.db") ``` -------------------------------- ### Initialize LibSQL Store with Remote Turso Database (Go) Source: https://cai139193541.gitbook.io/gorkflow/docs/storage/libsql-store Shows how to connect to a remote Turso database using a connection string that includes the database URL and an authentication token. This enables cloud-based, scalable data storage. ```go // Connect to Turso store, err := store.NewLibSQLStore( "libsql://my-database-user.turso.io?authToken=your-auth-token", ) ``` -------------------------------- ### Define Go Data Types for Workflow Source: https://cai139193541.gitbook.io/gorkflow/docs/getting-started/quick-start Define input and output data structures for your workflow steps using Go structs with JSON tags. These types ensure type safety and enable automatic data marshaling between steps. ```go package main import ( "context" "fmt" "log" "github.com/sicko7947/gorkflow" "github.com/sicko7947/gorkflow/engine" "github.com/sicko7947/gorkflow/store" ) // Define your data types type CalculationInput struct { A int `json:"a"` B int `json:"b"` } type SumOutput struct { Sum int `json:"sum"` } type ProductOutput struct { Product int `json:"product"` } type ResultOutput struct { Result int `json:"result"` Message string `json:"message"` } ``` -------------------------------- ### Initialize LibSQL Store with Local File (Go) Source: https://cai139193541.gitbook.io/gorkflow/docs/storage/libsql-store Demonstrates how to create or open a local SQLite database file using the LibSQL store. The database file is specified by its path. The store automatically creates the necessary tables if they don't exist. ```go import "github.com/sicko7947/gorkflow/store" // Create store with local file store, err := store.NewLibSQLStore("file:./workflows.db") if err != nil { panic(err) } // Use with engine // eng := engine.NewEngine(store) ``` -------------------------------- ### Troubleshoot Module Resolution Issues Source: https://cai139193541.gitbook.io/gorkflow/docs/getting-started/installation Command to resolve missing or incorrect Go module dependencies. Run this if you encounter module resolution errors. ```bash go mod tidy ``` -------------------------------- ### Connect to Remote LibSQL (Turso) (Go) Source: https://cai139193541.gitbook.io/gorkflow/example/libsql_persistence Shows how to configure the LibSQL store to connect to a remote Turso database instead of a local file. Requires replacing the local file path with the Turso database URL and authentication token. This enables production-ready, distributed persistence. ```go // Replace the dbPath with your Turso database URL dbPath := "libsql://your-database.turso.io?authToken=your-token" libsqlStore, err := store.NewLibSQLStore(dbPath) ``` -------------------------------- ### Initialize LibSQL Store (Go) Source: https://cai139193541.gitbook.io/gorkflow/example/libsql_persistence Creates a new LibSQL store using a local SQLite database file. Handles potential errors during creation and ensures the store is closed properly using defer. This store enables persistent storage for workflow runs and step executions. ```go dbPath := "file:./workflow.db" libsqlStore, err := store.NewLibSQLStore(dbPath) if err != nil { log.Fatal("Failed to create LibSQL store:", err) } defer libsqlStore.Close() ``` -------------------------------- ### Gorkflow Core Dependencies Source: https://cai139193541.gitbook.io/gorkflow/docs/getting-started/installation Lists the essential dependencies required for Gorkflow's core functionality, including UUID generation, structured logging, and input validation. ```go require ( github.com/google/uuid v1.6.0 // UUID generation for workflow runs github.com/rs/zerolog v1.34.0 // Structured logging github.com/go-playground/validator/v10 v10.12.0 // Validation ) ``` -------------------------------- ### Direct SQL Queries in Go Source: https://cai139193541.gitbook.io/gorkflow/docs/storage/libsql-store Demonstrates how to open a LibSQL database connection and execute SQL queries to retrieve workflow run data and calculate average step execution times. Assumes the 'libsql' driver is imported. ```go import "database/sql" // Open database db, err := sql.Open("libsql", "file:./workflows.db") // Query workflows rows, err := db.Query(` SELECT run_id, workflow_name, status, created_at FROM workflow_runs WHERE status = 'completed' ORDER BY created_at DESC LIMIT 10 `) // Query step execution times rows, err := db.Query(` SELECT step_name, AVG(completed_at - started_at) as avg_duration FROM step_executions WHERE status = 'completed' GROUP BY step_name `) ``` -------------------------------- ### Update Gorkflow and Resolve Conflicts Source: https://cai139193541.gitbook.io/gorkflow/docs/getting-started/installation Commands to update Gorkflow to the latest version and tidy up dependencies, useful for resolving version conflicts. Ensure your `go.mod` file has compatible versions. ```bash go get -u github.com/sicko7947/gorkflow go mod tidy ``` -------------------------------- ### Check gorkflow Workflow Status via cURL Source: https://cai139193541.gitbook.io/gorkflow/example/sequential Retrieves the status of a running gorkflow workflow using its `runId`. This is done by sending a GET request to the workflow status endpoint. ```bash curl http://localhost:3000/api/v1/workflows/ ``` -------------------------------- ### Connect to Existing SQLite Database with LibSQL Source: https://cai139193541.gitbook.io/gorkflow/docs/storage/libsql-store Shows how to initialize a LibSQL store by directly referencing an existing SQLite database file, facilitating migration from SQLite. ```bash # Use existing SQLite database store, _ := store.NewLibSQLStore("file:./existing-sqlite.db") ``` -------------------------------- ### Create Turso Database with Replication Source: https://cai139193541.gitbook.io/gorkflow/docs/storage/libsql-store Demonstrates creating a Turso database with specified locations for replication, enabling automatic read replication to the nearest region for improved performance. ```bash # Create database with replication turso db create gorkflow-workflows --location ord --location fra # Automatic read replication to closest region ``` -------------------------------- ### Add Validation Tags to Structs Source: https://cai139193541.gitbook.io/gorkflow/docs/core-concepts/steps Provides an example of using validation tags within a Go struct for input validation in Gorkflow steps. This example specifies required fields and value constraints. ```go type Input struct { Email string `json:"email" validate:"required,email" Age int `json:"age" validate:"required,gte=0,lte=150" } ``` -------------------------------- ### Retrieve and List Workflow Data (Go) Source: https://cai139193541.gitbook.io/gorkflow/example/libsql_persistence Demonstrates retrieving a specific workflow run by its ID and listing all step executions associated with a run. It also shows how to list all workflow runs based on a filter, showcasing the persistent data retrieval capabilities of the LibSQL store. ```go // Retrieve workflow run run, err := eng.GetRun(ctx, runID) // List all step executions (sorted by execution_index) steps, err := libsqlStore.ListStepExecutions(ctx, runID) // List all workflow runs runs, err := libsqlStore.ListRuns(ctx, workflow.RunFilter{ WorkflowID: "simple_math", }) ``` -------------------------------- ### Execute Gorkflow Workflow in Go Source: https://cai139193541.gitbook.io/gorkflow/docs/getting-started/first-workflow This Go program defines and executes a registration workflow using the Gorkflow engine. It initializes the workflow, sets up storage and the engine, prepares input data, starts the workflow, and then retrieves and displays the run status and output. It requires the 'gorkflow/engine' and 'gorkflow/store' packages. ```go package main import ( "context" "encoding/json" "fmt" "log" "github.com/sicko7947/gorkflow/engine" "github.com/sicko7947/gorkflow/store" ) func main() { // Create workflow wf, err := NewRegistrationWorkflow() if err != nil { log.Fatal("Failed to create workflow:", err) } // Create storage and engine store := store.NewMemoryStore() eng := engine.NewEngine(store) // Prepare input input := RegistrationInput{ Email: "user@example.com", Username: "johndoe", Password: "securepassword123", } // Start workflow ctx := context.Background() runID, err := eng.StartWorkflow(ctx, wf, input) if err != nil { log.Fatal("Failed to start workflow:", err) } fmt.Printf("Workflow started: %s\n", runID) // Get result run, err := eng.GetRun(ctx, runID) if err != nil { log.Fatal("Failed to get run:", err) } fmt.Printf("Status: %s\n", run.Status) fmt.Printf("Progress: %.0f%%\n", run.Progress*100) // Parse output if run.Output != nil { var output RegistrationOutput if err := json.Unmarshal(run.Output, &output); err != nil { log.Fatal("Failed to parse output:", err) } fmt.Printf("\nRegistration Complete!\n") fmt.Printf("User ID: %s\n", output.UserID) fmt.Printf("Username: %s\n", output.Username) fmt.Printf("Email: %s\n", output.Email) fmt.Printf("Email Sent: %v\n", output.EmailSent) } if run.Error != nil { fmt.Printf("Error: %s\n", *run.Error) } } ``` -------------------------------- ### Go Conditional Validation Example Source: https://cai139193541.gitbook.io/gorkflow/docs/core-concepts/validation Illustrates conditional validation in Go using the `required_if` tag. This example shows how the `Email` field is required only if `Type` is 'email', and the `Phone` field is required only if `Type` is 'phone'. ```go type ConditionalInput struct { Type string `validate:"required,oneof=email phone" Email string `validate:"required_if=Type email,omitempty,email" Phone string `validate:"required_if=Type phone,omitempty,e164" } ``` -------------------------------- ### Trigger Workflow via HTTP POST Source: https://cai139193541.gitbook.io/gorkflow/example/parallel Example using `curl` to send a POST request to trigger the 'simple-math' workflow. It specifies the content type as JSON and provides input data including `val1`, `val2`, and `mult` for the workflow execution. ```bash curl -X POST http://localhost:3000/api/v1/workflows/simple-math \ -H "Content-Type: application/json" \ -d '{"val1": 10, "val2": 5, "mult": 2}' ``` -------------------------------- ### Create and Execute a Simple Workflow in Go Source: https://cai139193541.gitbook.io/gorkflow/project_index This Go code snippet demonstrates how to define a simple workflow with a single step, build the workflow, and then execute it using the Gorkflow engine. It includes setting up a memory store and a logger for execution. ```go import ( workflow "github.com/sicko7947/gorkflow" "github.com/sicko7947/gorkflow" "github.com/sicko7947/gorkflow/engine" "github.com/sicko7947/gorkflow/store" "context" "os" "github.com/rs/zerolog" ) // Define step step := workflow.NewStep( "hello", "Say Hello", func(ctx *workflow.StepContext, input string) (string, error) { return "Hello, " + input, nil }, ) // Build workflow wf, _ := builder.NewWorkflow("greeting", "Greeting Workflow"). Sequence(step). Build() // Execute store := store.NewMemoryStore() logger := zerolog.New(os.Stdout) eng := engine.NewEngine(store, logger, engine.DefaultEngineConfig) runID, _ := eng.StartWorkflow(context.Background(), wf, "World") ``` -------------------------------- ### Use Parallel for Independent Operations (Go) Source: https://cai139193541.gitbook.io/gorkflow/docs/advanced-usage/parallel-execution Illustrates the best practice of using parallel execution for operations that are independent of each other. It shows a 'Good' example with unrelated tasks like sending emails and updating databases, and a 'Bad' example where tasks have clear dependencies, which negates the benefits of parallelism. ```go .Parallel( sendEmail, updateDatabase, callWebhook, ) ``` ```go .Parallel( validateUser, // Must run first createUser, // Depends on validation ) ``` -------------------------------- ### Turso Authentication and Database Management Source: https://cai139193541.gitbook.io/gorkflow/docs/storage/libsql-store Covers the steps to sign up for Turso, create a new database, retrieve its connection URL, and generate an authentication token using the Turso CLI. These are essential for connecting your application to a Turso database. ```bash turso auth signup # Create database turso db create gorkflow-workflows # Get connection URL turso db show gorkflow-workflows --url # Create auth token turso db tokens create gorkflow-workflows ``` -------------------------------- ### Verify Turso Database Connection Source: https://cai139193541.gitbook.io/gorkflow/docs/storage/libsql-store Illustrates Turso CLI commands to troubleshoot connection errors, including accessing the database shell and listing authentication tokens. ```bash # Verify connection turso db shell gorkflow-workflows # Check auth token turso db tokens list gorkflow-workflows ``` -------------------------------- ### Get Database Size in Go Source: https://cai139193541.gitbook.io/gorkflow/docs/storage/libsql-store Retrieves the current size of the database in bytes by querying the `pragma_page_count` and `pragma_page_size` values. Requires 'database/sql' and 'fmt' packages. ```go import "database/sql" import "fmt" var size int64 db.QueryRow("SELECT page_count() * page_size() FROM pragma_page_count(), pragma_page_size()").Scan(&size) fmt.Printf("Database size: %d bytes\n", size) ``` -------------------------------- ### Using Environment Variable for LibSQL URL (Go) Source: https://cai139193541.gitbook.io/gorkflow/docs/storage/libsql-store Demonstrates how to configure the LibSQL store to use a database connection URL provided via an environment variable. This is a common practice for managing connection details in different deployment environments. ```go import ( "os" "github.com/sicko7947/gorkflow/store" ) url := os.Getenv("LIBSQL_URL") store, _ := store.NewLibSQLStore(url) ``` -------------------------------- ### Numeric Validation Tags Overview (Text) Source: https://cai139193541.gitbook.io/gorkflow/example/validation Lists common validation tags for numeric types in go-playground/validator, covering equality, inequality, and boundary comparisons. ```text Numeric Validators * `eq=N` - Equal to N * `ne=N` - Not equal to N * `gt=N` - Greater than N * `gte=N` - Greater than or equal to N * `lt=N` - Less than N * `lte=N` - Less than or equal to N ``` -------------------------------- ### Build User Registration Workflow in Go Source: https://cai139193541.gitbook.io/gorkflow/docs/getting-started/first-workflow Constructs a gorkflow.Workflow for user registration, defining its name, description, version, and execution configuration. It sequences the previously defined steps: validation, user creation, email sending, and output formatting. ```go package main import ( "github.com/sicko7947/gorkflow" ) func NewRegistrationWorkflow() (*gorkflow.Workflow, error) { return gorkflow.NewWorkflow("user-registration", "User Registration"). WithDescription("Register a new user with validation and email"). WithVersion("1.0"). WithConfig(gorkflow.ExecutionConfig{ MaxRetries: 2, RetryDelayMs: 1000, RetryBackoff: gorkflow.BackoffLinear, TimeoutSeconds: 60, }). Sequence( NewValidationStep(), NewCreateUserStep(), NewSendEmailStep(), NewFormatStep(), ). Build() } ``` -------------------------------- ### Initialize Gorkflow with DynamoDB Store (Go) Source: https://cai139193541.gitbook.io/gorkflow/docs/storage/dynamodb-store Demonstrates how to initialize the Gorkflow engine with the DynamoDB store. It loads default AWS configuration, creates a DynamoDB client, instantiates the store with a table name, and then creates the engine. ```go import ( "context" "github.com/aws/aws-sdk-go-v2/config" "github.com/aws/aws-sdk-go-v2/service/dynamodb" "github.com/sicko7947/gorkflow/store" "github.com/sicko7947/gorkflow/engine" ) func main() { // Load AWS configuration cfg, err := config.LoadDefaultConfig(context.Background()) if err != nil { panic(err) } // Create DynamoDB client client := dynamodb.NewFromConfig(cfg) // Create store store, err := store.NewDynamoDBStore(client, "workflow-executions") if err != nil { panic(err) } // Use with engine eng := engine.NewEngine(store) } ``` -------------------------------- ### Define Email Sent Output Structure (Go) Source: https://cai139193541.gitbook.io/gorkflow/example/validation Defines the structure for email sent output, validating required fields like MessageID, Status, and SentTo. ```go type EmailSentOutput struct { MessageID string `validate:"required" Status string `validate:"required,oneof=sent failed pending" SentTo string `validate:"required,email" } ``` -------------------------------- ### Check Gorkflow Run Status (Go) Source: https://cai139193541.gitbook.io/gorkflow/docs/core-concepts/workflows Provides an example of how to retrieve the status of a Gorkflow run using `eng.GetRun()` and how to handle different statuses like 'completed', 'failed', and 'cancelled'. ```go run, _ := eng.GetRun(ctx, runID) switch run.Status { case "completed": // Success case "failed": fmt.Println("Error:", *run.Error) case "cancelled": // Cancelled by user } ``` -------------------------------- ### Enable Default Validation Config for Step (Go) Source: https://cai139193541.gitbook.io/gorkflow/example/validation Configures a gorkflow step to use the default validation configuration, enabling both input and output validation with fail-on-error behavior. ```go step := workflow.NewStep( "my_step", "My Step", handler, workflow.WithValidation(workflow.DefaultValidationConfig), ) ``` -------------------------------- ### Create Turso Development Branch Source: https://cai139193541.gitbook.io/gorkflow/docs/storage/libsql-store Shows how to create a new development branch from an existing Turso database, allowing for isolated testing of changes before merging them into the main database. ```bash # Create development branch turso db create gorkflow-dev --from-db gorkflow-workflows # Test changes in dev environment ``` -------------------------------- ### Define Validated User Output Structure (Go) Source: https://cai139193541.gitbook.io/gorkflow/example/validation Defines the structure for validated user output, enforcing rules for UserID, Email, and Username using struct tags. ```go type ValidatedUserOutput struct { UserID string `validate:"required,uuid4" Email string `validate:"required,email" Username string `validate:"required" IsActive bool `json:"isActive" } ``` -------------------------------- ### Define, Build, and Execute a Simple Workflow in Go Source: https://cai139193541.gitbook.io/gorkflow/docs This Go code snippet demonstrates the basic usage of Gorkflow. It defines custom input and output types for a calculation step, creates a sequential workflow, and then executes it using an in-memory store and the Gorkflow engine. This example highlights type-safe step definitions and the fluent builder API. ```go // Define your types type CalculationInput struct { A int `json:"a"` B int `json:"b"` } type SumOutput struct { Sum int `json:"sum"` } // Create steps addStep := gorkflow.NewStep( "add", "Add Numbers", func(ctx *gorkflow.StepContext, input CalculationInput) (SumOutput, error) { return SumOutput{Sum: input.A + input.B}, nil }, ) // Build workflow wf, _ := gorkflow.NewWorkflow("calc", "Calculator"). Sequence(addStep). Build() // Execute store := store.NewMemoryStore() eng := engine.NewEngine(store) runID, _ := eng.StartWorkflow(context.Background(), wf, CalculationInput{A: 10, B: 5}) ``` -------------------------------- ### Enable Custom Validation Config for Step (Go) Source: https://cai139193541.gitbook.io/gorkflow/example/validation Allows for a custom validation configuration for a gorkflow step, specifying whether to validate input/output and if validation errors should cause the step to fail. ```go step := workflow.NewStep( "my_step", "My Step", handler, workflow.WithValidation(workflow.ValidationConfig{ ValidateInput: true, ValidateOutput: true, FailOnValidationError: true, CustomValidator: nil, // Use default validator }), ) ``` -------------------------------- ### Run Gorkflow from Command Line Source: https://cai139193541.gitbook.io/gorkflow/docs/getting-started/first-workflow This command executes the Go program defined in main.go, which in turn runs the Gorkflow workflow. Ensure you are in the project directory containing the main.go file before running this command. ```bash go run . ```