state

package
v0.15.0 Latest Latest
Warning

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

Go to latest
Published: Nov 9, 2026 License: Apache-2.0 Imports: 5 Imported by: 0

Documentation

Overview

Package state provides a continuation-passing style framework for building composable state machines and processing pipelines.

Core Concepts

Step - The Building Block

A Step represents a single operation that processes a context and returns the next step to execute (or nil to terminate):

type Step interface {
    Run(context.Context) Step
}

Example - Writing a custom Step:

// A simple step that prints and continues
type PrintStep struct {
    message string
    next    Step
}

func (p *PrintStep) Run(ctx context.Context) Step {
    fmt.Println(p.message)
    if p.next != nil {
        return p.next.Run(ctx)
    }
    return nil
}

NewStep - The Composition Unit

A NewStep is a factory function that creates a Step when given the next step to execute. This enables continuation-passing style composition:

type NewStep func(next Step) Step

ContextFunc - The Work Unit

A ContextFunc is a function that does work with context. It takes a context, performs operations, and returns the context (potentially modified) so it can be threaded through the pipeline:

type ContextFunc func(context.Context) context.Context

Use with Do to add work to the pipeline.

Example - Creating reusable NewSteps:

type ctxKey string

// A NewStep that adds a value to context
func AddValue(key ctxKey, value string) NewStep {
    return NewStepFunc(func(ctx context.Context, next Step) Step {
        fmt.Printf("adding %s=%s to context\n", key, value)
        newCtx := context.WithValue(ctx, key, value)
        return Continue(newCtx, next)
    })
}

// A NewStep that checks a condition
func CheckError() NewStep {
    return NewStepFunc(func(ctx context.Context, next Step) Step {
        if ctx.Err() != nil {
            fmt.Println("Error detected, stopping")
            return nil
        }
        return Continue(ctx, next)
    })
}

// A NewStep that reads from context
func PrintUser() NewStep {
    return NewStepFunc(func(ctx context.Context, next Step) Step {
        user := ctx.Value(ctxKey("user")).(string)
        fmt.Printf("current user: %s\n", user)
        return Continue(ctx, next)
    })
}

// Compose them - context values flow through the pipeline:
pipeline := Sequence(
    AddValue(ctxKey("user"), "alice"),
    CheckError(),
    PrintUser(),  // Can access "user" value set earlier
    AddValue(ctxKey("processed"), "true"),
)
Run(context.Background(), pipeline)
// Output:
// adding user=alice to context
// current user: alice
// adding processed=true to context

Running a Pipeline

Use Run to execute a NewStep pipeline:

func Run(ctx context.Context, newStep NewStep)

The pipeline executes to completion using continuation-passing style.

Error Handling

By default, Continue stops the pipeline when context is cancelled. You can customize this behavior:

// Default: stops on cancellation
ctx := context.Background()
pipeline := Sequence(step1, step2, step3)
Run(ctx, pipeline)

// With error handler: cleanup on cancellation
ctx = WithErrorHandler(ctx, func(err error) Step {
    log.Printf("pipeline cancelled: %v", err)
    return cleanupStep.Step()
})
Run(ctx, pipeline)

A non-nil Step returned by the handler runs with the handler cleared from context, so Continue calls inside the recovery path stop quietly instead of re-entering it. The context is still cancelled while recovery runs, which stops a Continue-linked sequence at its first link: build the recovery path from a terminal step or a single step that does its work in the body.

Helper Functions

The package provides helper functions for common patterns. These are all built on top of Step and NewStep:

Basic Helpers:

  • NewStepFunc(fn) - Create a NewStep from func(context.Context, next Step) Step
  • Do(fn ContextFunc) - Lift a work function into a pipeline step
  • Continue(ctx, next) - Run the next step if it exists and context is not cancelled
  • WithErrorHandler(ctx, handler) - Set an error handler for cancelled contexts
  • Terminal - Stop pipeline execution
  • Noop - Continue to next step without doing anything

Composition Operators:

  • Sequence(...steps) - Execute steps sequentially
  • Parallel(...steps) - Execute steps concurrently
  • Decision(predicate, ifTrue, ifFalse) - Binary branching (if/else)
  • Enum(selector, cases, default) - Multi-way branching on comparable types
  • Switch(selector, cases, default) - Multi-way branching on strings

A panic in a step is a programming error and is left to crash the process by default. Parallel branches run on their own goroutines, so their panics bypass a recover installed outside the pipeline; a crash handler must run inside the branch. Register one as ambient middleware with CrashHandler (or Deferred) — Parallel applies the ambient stack inside every branch — or apply a raw wrapper with Map. See Parallel.

Choosing a Pattern

What do you need to do?

├─ Run steps in order?
│  └─ Use: Sequence(a, b, c)
│
├─ Run steps concurrently?
│  └─ Use: Parallel(a, b, c)
│
├─ Make a binary choice (if/else)?
│  └─ Use: Decision(predicate, ifTrue, ifFalse)
│
├─ Choose from multiple options (switch/case)?
│  ├─ String-based? → Use: Switch(selector, cases, default)
│  └─ Generic type?  → Use: Enum(selector, cases, default)
│
└─ Do work in a step?
   └─ Use: Do(contextFunc)

Basic Usage

Simple Sequential Pipeline:

type ctxKey string

pipeline := state.Sequence(
    state.Do(func(ctx context.Context) context.Context {
        fmt.Println("step 1: setting user")
        return context.WithValue(ctx, ctxKey("user"), "alice")
    }),
    state.Do(func(ctx context.Context) context.Context {
        user := ctx.Value(ctxKey("user")).(string)
        fmt.Printf("step 2: user is %s, adding request ID\n", user)
        return context.WithValue(ctx, ctxKey("requestID"), "req-123")
    }),
    state.Do(func(ctx context.Context) context.Context {
        user := ctx.Value(ctxKey("user")).(string)
        reqID := ctx.Value(ctxKey("requestID")).(string)
        fmt.Printf("step 3: processing request %s for user %s\n", reqID, user)
        return ctx
    }),
)

state.Run(context.Background(), pipeline)
// Output:
// step 1: setting user
// step 2: user is alice, adding request ID
// step 3: processing request req-123 for user alice

Conditional Branching:

type ctxKey string

pipeline := state.Sequence(
    state.Do(func(ctx context.Context) context.Context {
        fmt.Println("checking authorization")
        return context.WithValue(ctx, ctxKey("authorized"), true)
    }),
    state.Decision(
        func(ctx context.Context) bool {
            return ctx.Value(ctxKey("authorized")).(bool)
        },
        // True branch - user is authorized
        state.Do(func(ctx context.Context) context.Context {
            fmt.Println("access granted, setting permissions")
            return context.WithValue(ctx, ctxKey("permissions"), "read,write")
        }),
        // False branch - user is not authorized
        state.Do(func(ctx context.Context) context.Context {
            fmt.Println("access denied")
            return context.WithValue(ctx, ctxKey("permissions"), "none")
        }),
    ),
    state.Do(func(ctx context.Context) context.Context {
        perms := ctx.Value(ctxKey("permissions")).(string)
        fmt.Printf("final permissions: %s\n", perms)
        return ctx
    }),
)

Parallel Execution:

type ctxKey string

pipeline := state.Sequence(
    state.Do(func(ctx context.Context) context.Context {
        fmt.Println("initializing request context")
        ctx = context.WithValue(ctx, ctxKey("requestID"), "req-456")
        return context.WithValue(ctx, ctxKey("userID"), "user-789")
    }),
    state.Parallel(
        // Each parallel branch receives the same context
        state.Do(func(ctx context.Context) context.Context {
            reqID := ctx.Value(ctxKey("requestID")).(string)
            fmt.Printf("validating request %s\n", reqID)
            return ctx
        }),
        state.Do(func(ctx context.Context) context.Context {
            userID := ctx.Value(ctxKey("userID")).(string)
            fmt.Printf("loading user profile %s\n", userID)
            return ctx
        }),
        state.Do(func(ctx context.Context) context.Context {
            reqID := ctx.Value(ctxKey("requestID")).(string)
            fmt.Printf("logging request %s\n", reqID)
            return ctx
        }),
    ),
    state.Do(func(ctx context.Context) context.Context {
        reqID := ctx.Value(ctxKey("requestID")).(string)
        fmt.Printf("all parallel work complete for %s\n", reqID)
        return ctx
    }),
)

To collect results from parallel branches, allocate a ctxkey box per result before the Parallel and let each branch fill its own. The box itself is not synchronized: the pattern is race-free because each box has exactly one writer, and Parallel's WaitGroup barrier orders the branch writes before the post-parallel read.

import "github.com/authzed/ctxkey"

type ValidationResult struct { Valid bool }
type PermissionsResult struct { Allowed bool }

var (
    validationKey  = ctxkey.NewBoxedWithDefault(ValidationResult{})
    permissionsKey = ctxkey.NewBoxedWithDefault(PermissionsResult{})
)

pipeline := state.Sequence(
    // Allocate boxes before parallel execution
    state.Do(func(ctx context.Context) context.Context {
        ctx = validationKey.SetBox(ctx)
        return permissionsKey.SetBox(ctx)
    }),
    // Each branch fills exactly one box (Set writes through the existing box)
    state.Parallel(
        state.Do(func(ctx context.Context) context.Context {
            return validationKey.Set(ctx, ValidationResult{Valid: validate(ctx)})
        }),
        state.Do(func(ctx context.Context) context.Context {
            return permissionsKey.Set(ctx, PermissionsResult{Allowed: checkPermissions(ctx)})
        }),
    ),
    // After parallel completes, read the results
    state.Do(func(ctx context.Context) context.Context {
        validation := validationKey.Value(ctx)
        permissions := permissionsKey.Value(ctx)
        fmt.Printf("Valid: %v, Allowed: %v\n", validation.Valid, permissions.Allowed)
        return ctx
    }),
)

Multi-way Branching with Enum:

type ctxKey string

pipeline := state.Sequence(
    state.Do(func(ctx context.Context) context.Context {
        // Resource type set by earlier processing
        return context.WithValue(ctx, ctxKey("resourceType"), "deployment")
    }),
    state.Enum(
        func(ctx context.Context) string {
            return ctx.Value(ctxKey("resourceType")).(string)
        },
        map[string]state.NewStep{
            "deployment": state.Do(func(ctx context.Context) context.Context {
                fmt.Println("handling deployment")
                return context.WithValue(ctx, ctxKey("replicas"), 3)
            }),
            "service": state.Do(func(ctx context.Context) context.Context {
                fmt.Println("handling service")
                return context.WithValue(ctx, ctxKey("port"), 8080)
            }),
            "configmap": state.Do(func(ctx context.Context) context.Context {
                fmt.Println("handling configmap")
                return context.WithValue(ctx, ctxKey("dataKeys"), []string{"config.yaml"})
            }),
        },
        // Default case
        state.Do(func(ctx context.Context) context.Context {
            fmt.Println("unknown resource type")
            return ctx
        }),
    ),
    state.Do(func(ctx context.Context) context.Context {
        // Values set by the enum branch are available here
        if replicas, ok := ctx.Value(ctxKey("replicas")).(int); ok {
            fmt.Printf("deployment configured with %d replicas\n", replicas)
        }
        return ctx
    }),
)

String-based Branching with Switch:

pipeline := state.Switch(
    func(ctx context.Context) string {
        return getOperationPhase(ctx)
    },
    map[string]state.NewStep{
        "pending":   initializationStep,
        "running":   monitoringStep,
        "completed": cleanupStep,
        "failed":    recoveryStep,
    },
    unknownPhaseStep, // Default case
)

Controller Example

A typical controller pipeline:

// Main controller pipeline
mainPipeline := state.Sequence(
    state.Do(func(ctx context.Context) context.Context {
        // Set finalizer
        return ctx
    }),
    state.Do(func(ctx context.Context) context.Context {
        // Check for safe deletion
        return ctx
    }),
    state.Do(func(ctx context.Context) context.Context {
        // Check pause condition
        return ctx
    }),
    state.Decision(
        func(ctx context.Context) bool {
            return hasDatabaseInstance(ctx)
        },
        // New style: has database instance
        state.Sequence(
            ensureMetadata,
            createScopedCredentials,
        ),
        // Old style: direct secret reference
        state.Sequence(
            adoptExistingSecret,
            ensureMetadata,
        ),
    ),
)

// Execute the pipeline
state.Run(ctx, mainPipeline)

Key Benefits

  1. No ID Management: Direct references eliminate the need for step IDs and lookup
  2. Simpler Composition: Steps compose naturally without complex builder patterns
  3. Type Safety: Factory functions provide compile-time safety
  4. Multi-way Branching: Enum and Switch operators handle complex branching logic elegantly
  5. Clear Control Flow: Continuation-passing makes execution flow explicit
  6. Reusability: Steps can be easily reused across different pipelines
  7. Testability: Individual steps and compositions are easy to test

Integration with Queue Operations

The state package works seamlessly with the existing queue operations:

import "github.com/authzed/controller-idioms/queue"

validationStep := state.Do(func(ctx context.Context) context.Context {
    if err := validateResource(ctx); err != nil {
        queue.NewQueueOperationsCtx().RequeueErr(ctx, err)
        return ctx
    }
    // Continue processing...
    return ctx
})

The continuation-passing style provides a clean, functional approach to building complex state machines.

Package state contains Step units used to compose reconciliation loops for controllers.

You write functions or types that implement the Step interface, and then compose them via NewStep functions and composition operators.

NewStep functions are used for creating Step instances, and Handlers are the things that actually process requests - each step returns the next step to execute, or nil to terminate.

Writing controllers in this style permits composition patterns including Sequence, Parallel, Decision, and other operations like Map and Bind.

Why Context?

This package uses context.Context as the state container instead of a custom type or generic map for several reasons:

  1. **Integration**: Controllers already use context.Context for cancellation, deadlines, and request-scoped values. Using it here means zero friction.

  2. **Standardization**: Context is Go's standard way to pass request-scoped data. Using it makes the pattern immediately familiar to Go developers.

  3. **Immutability**: context.WithValue() returns a new context, encouraging immutable transformations (though this isn't enforced - see ContextFunc docs).

  4. **Ecosystem**: Existing middleware, logging, tracing, and client libraries already understand context.Context.

  5. **Cancellation**: Built-in support for cancellation and deadlines, crucial for long-running controller operations.

Think of Context as a "sufficiently capable state container" rather than as purely a cancellation mechanism. For type-safe operations, use typedctx.

Example (BranchingComparison)
ctx := context.Background()

// This is equivalent to the complex handler branching example:
// hasSecretHandler := chain(c.ensureMetadata, c.ensureScopedDatabaseCreds(...))
// directSecretHandler := chain(c.adoptDBRootSecret, c.removeMissingSecretCondition, hasSecretHandler)
// mainHandler := chain(c.setFinalizer, c.safeDelete, c.checkPause, c.validateInstance(hasSecretHandler, directSecretHandler))

// Define reusable stage builders
ensureMetadata := Do(func(ctx context.Context) context.Context {
	fmt.Println("ensuring metadata")
	return ctx
})

ensureScopedDatabaseCreds := Do(func(ctx context.Context) context.Context {
	fmt.Println("ensuring scoped database credentials")
	return ctx
})

createLogicalDatabase := Do(func(ctx context.Context) context.Context {
	fmt.Println("creating logical database")
	return ctx
})

adoptDBRootSecret := Do(func(ctx context.Context) context.Context {
	fmt.Println("adopting DB root secret")
	return ctx
})

removeMissingSecretCondition := Do(func(ctx context.Context) context.Context {
	fmt.Println("removing missing secret condition")
	return ctx
})

// hasSecretChain - runs when secret is found via database instance
hasSecretChain := Sequence(
	ensureMetadata,
	ensureScopedDatabaseCreds,
	createLogicalDatabase,
)

// directSecretChain - runs when database instance not found (old style)
directSecretChain := Sequence(
	adoptDBRootSecret,
	removeMissingSecretCondition,
	hasSecretChain, // Reuse the hasSecret chain
)

// validateInstance - decides between the two branches
validateInstance := Decision(
	func(_ context.Context) bool {
		// In real code, this would check if database instance exists
		fmt.Println("validating instance")
		return true // Has database instance
	},
	hasSecretChain,    // True branch
	directSecretChain, // False branch
)

// Main controller pipeline
mainHandler := Sequence(
	Do(func(ctx context.Context) context.Context {
		fmt.Println("setting finalizer")
		return ctx
	}),
	Do(func(ctx context.Context) context.Context {
		fmt.Println("safe delete check")
		return ctx
	}),
	Do(func(ctx context.Context) context.Context {
		fmt.Println("checking pause")
		return ctx
	}),
	validateInstance,
)

Run(ctx, mainHandler)
Output:
setting finalizer
safe delete check
checking pause
validating instance
ensuring metadata
ensuring scoped database credentials
creating logical database
Example (BuilderReplacement)
ctx := context.Background()

// In the old handler system, you needed:
// 1. Builder functions
// 2. Chain() to compose builders
// 3. .Handler(id) to instantiate
// 4. Complex ID management for branching

// In the state system, it's much simpler:
// Just compose NewStep functions directly

// Old way (conceptually):
// validationBuilder := func(next Handler) Handler { ... }
// processingBuilder := func(next Handler) Handler { ... }
// pipeline := Chain(validationBuilder, processingBuilder).Handler("myPipeline")

// New way:
validation := Do(func(ctx context.Context) context.Context {
	fmt.Println("validation")
	return ctx
})

processing := Do(func(ctx context.Context) context.Context {
	fmt.Println("processing")
	return ctx
})

pipeline := Sequence(validation, processing)

Run(ctx, pipeline)
Output:
validation
processing
Example (ComplexConditionals)
userRoleKey := ctxkey.New[string]()
ctx := userRoleKey.Set(context.Background(), "admin")

// Multi-way branching using Enum - much cleaner than nested decisions
pipeline := Sequence(
	Do(func(ctx context.Context) context.Context {
		fmt.Println("authentication")
		return ctx
	}),
	Enum(
		func(ctx context.Context) string {
			return userRoleKey.MustValue(ctx)
		},
		map[string]NewStep{
			"admin": Do(func(ctx context.Context) context.Context {
				fmt.Println("admin workflow")
				return ctx
			}),
			"user": Do(func(ctx context.Context) context.Context {
				fmt.Println("user workflow")
				return ctx
			}),
			"moderator": Do(func(ctx context.Context) context.Context {
				fmt.Println("moderator workflow")
				return ctx
			}),
		},
		Do(func(ctx context.Context) context.Context {
			fmt.Println("guest workflow")
			return ctx
		}),
	),
	Do(func(ctx context.Context) context.Context {
		fmt.Println("logging user action")
		return ctx
	}),
)

Run(ctx, pipeline)
Output:
authentication
admin workflow
logging user action
Example (ComplexPipeline)
ctx := context.Background()

// A more complex example showing composition
pipeline := Sequence(
	Do(func(ctx context.Context) context.Context {
		fmt.Println("initialization")
		return ctx
	}),
	Decision(
		func(_ context.Context) bool {
			return true // some validation logic
		},
		// Validation passed - processing
		Do(func(ctx context.Context) context.Context {
			fmt.Println("validation passed")
			return ctx
		}),
		// Validation failed
		Do(func(ctx context.Context) context.Context {
			fmt.Println("validation failed")
			return ctx
		}),
	),
	Do(func(ctx context.Context) context.Context {
		fmt.Println("finalization")
		return ctx
	}),
)

Run(ctx, pipeline)
Output:
initialization
validation passed
finalization
Example (ConditionalExecution)
shouldProcessKey := ctxkey.New[bool]()
ctx := shouldProcessKey.Set(context.Background(), false)

pipeline := Sequence(
	Do(func(ctx context.Context) context.Context {
		fmt.Println("starting process")
		return ctx
	}),
	Decision(
		func(ctx context.Context) bool {
			return shouldProcessKey.MustValue(ctx)
		},
		Do(func(ctx context.Context) context.Context {
			fmt.Println("processing enabled")
			return ctx
		}),
		Do(func(ctx context.Context) context.Context {
			fmt.Println("processing disabled")
			return ctx
		}),
	),
	Do(func(ctx context.Context) context.Context {
		fmt.Println("cleanup")
		return ctx
	}),
)

Run(ctx, pipeline)
Output:
starting process
processing disabled
cleanup
Example (ControllerWithEnum)
operationKey := ctxkey.New[string]()
ctx := operationKey.Set(context.Background(), "reconcile")

// Define reusable stages
setFinalizer := Do(func(ctx context.Context) context.Context {
	fmt.Println("setting finalizer")
	return ctx
})

validateSpec := Do(func(ctx context.Context) context.Context {
	fmt.Println("validating spec")
	return ctx
})

createResources := Do(func(ctx context.Context) context.Context {
	fmt.Println("creating resources")
	return ctx
})

updateResources := Do(func(ctx context.Context) context.Context {
	fmt.Println("updating resources")
	return ctx
})

deleteResources := Do(func(ctx context.Context) context.Context {
	fmt.Println("deleting resources")
	return ctx
})

removeFinalizer := Do(func(ctx context.Context) context.Context {
	fmt.Println("removing finalizer")
	return ctx
})

// Main controller pipeline using Enum for operation dispatch
pipeline := Sequence(
	Do(func(ctx context.Context) context.Context {
		fmt.Println("starting controller operation")
		return ctx
	}),
	Enum(
		func(ctx context.Context) string {
			return operationKey.MustValue(ctx)
		},
		map[string]NewStep{
			"reconcile": Sequence(
				setFinalizer,
				validateSpec,
				Decision(
					func(_ context.Context) bool {
						// Check if resources exist
						return false // Assume they don't exist
					},
					updateResources,
					createResources,
				),
			),
			"delete": Sequence(
				deleteResources,
				removeFinalizer,
			),
			"validate": validateSpec,
		},
		Do(func(ctx context.Context) context.Context {
			fmt.Println("unsupported operation")
			return ctx
		}),
	),
	Do(func(ctx context.Context) context.Context {
		fmt.Println("operation completed")
		return ctx
	}),
)

Run(ctx, pipeline)
Output:
starting controller operation
setting finalizer
validating spec
creating resources
operation completed
Example (EnumBranching)
resourceTypeKey := ctxkey.New[string]()
ctx := resourceTypeKey.Set(context.Background(), "deployment")

pipeline := Sequence(
	Do(func(ctx context.Context) context.Context {
		fmt.Println("processing resource")
		return ctx
	}),
	Enum(
		func(ctx context.Context) string {
			return resourceTypeKey.MustValue(ctx)
		},
		map[string]NewStep{
			"deployment": Sequence(
				Do(func(ctx context.Context) context.Context {
					fmt.Println("validating deployment spec")
					return ctx
				}),
				Do(func(ctx context.Context) context.Context {
					fmt.Println("creating deployment")
					return ctx
				}),
			),
			"service": Sequence(
				Do(func(ctx context.Context) context.Context {
					fmt.Println("validating service spec")
					return ctx
				}),
				Do(func(ctx context.Context) context.Context {
					fmt.Println("creating service")
					return ctx
				}),
			),
			"configmap": Do(func(ctx context.Context) context.Context {
				fmt.Println("creating configmap")
				return ctx
			}),
		},
		Do(func(ctx context.Context) context.Context {
			fmt.Println("unsupported resource type")
			return ctx
		}),
	),
	Do(func(ctx context.Context) context.Context {
		fmt.Println("resource processing complete")
		return ctx
	}),
)

Run(ctx, pipeline)
Output:
processing resource
validating deployment spec
creating deployment
resource processing complete
Example (MonadicPatterns)
configKey := ctxkey.New[string]()
validatedConfigKey := ctxkey.New[string]()
ctx := configKey.Set(context.Background(), "production")

// Sequential composition with context transformation
pipeline := Sequence(
	Do(func(ctx context.Context) context.Context {
		config := configKey.MustValue(ctx)
		return validatedConfigKey.Set(ctx, config+"-validated")
	}),
	Do(func(ctx context.Context) context.Context {
		config := validatedConfigKey.MustValue(ctx)
		fmt.Printf("using config: %s\n", config)
		return ctx
	}),
	Do(func(ctx context.Context) context.Context {
		fmt.Println("first operation")
		return ctx
	}),
	Do(func(ctx context.Context) context.Context {
		fmt.Println("dependent operation")
		return ctx
	}),
)

Run(ctx, pipeline)
Output:
using config: production-validated
first operation
dependent operation
Example (ReusableStages)
ctx := context.Background()

// Define reusable stages
logStart := func(name string) NewStep {
	return Do(func(ctx context.Context) context.Context {
		fmt.Printf("starting %s\n", name)
		return ctx
	})
}

logEnd := func(name string) NewStep {
	return Do(func(ctx context.Context) context.Context {
		fmt.Printf("completed %s\n", name)
		return ctx
	})
}

// Wrap a stage with logging
withLogging := func(name string, stage NewStep) NewStep {
	return Sequence(
		logStart(name),
		stage,
		logEnd(name),
	)
}

// Use the reusable pattern
pipeline := Sequence(
	withLogging("validation", Do(func(ctx context.Context) context.Context {
		fmt.Println("validating input")
		return ctx
	})),
	withLogging("processing", Do(func(ctx context.Context) context.Context {
		fmt.Println("processing work")
		return ctx
	})),
	withLogging("cleanup", Do(func(ctx context.Context) context.Context {
		fmt.Println("cleaning up")
		return ctx
	})),
)

Run(ctx, pipeline)
Output:
starting validation
validating input
completed validation
starting processing
processing work
completed processing
starting cleanup
cleaning up
completed cleanup
Example (SwitchWorkflow)
phaseKey := ctxkey.New[string]()
ctx := phaseKey.Set(context.Background(), "pending")

pipeline := Sequence(
	Do(func(ctx context.Context) context.Context {
		fmt.Println("checking resource phase")
		return ctx
	}),
	Switch(
		func(ctx context.Context) string {
			return phaseKey.MustValue(ctx)
		},
		map[string]NewStep{
			"pending": Sequence(
				Do(func(ctx context.Context) context.Context {
					fmt.Println("initializing resources")
					return ctx
				}),
				Do(func(ctx context.Context) context.Context {
					fmt.Println("setting up dependencies")
					return ctx
				}),
			),
			"running": Do(func(ctx context.Context) context.Context {
				fmt.Println("monitoring running state")
				return ctx
			}),
			"failed": Sequence(
				Do(func(ctx context.Context) context.Context {
					fmt.Println("analyzing failure")
					return ctx
				}),
				Do(func(ctx context.Context) context.Context {
					fmt.Println("attempting recovery")
					return ctx
				}),
			),
			"completed": Do(func(ctx context.Context) context.Context {
				fmt.Println("cleaning up completed resources")
				return ctx
			}),
		},
		Do(func(ctx context.Context) context.Context {
			fmt.Println("unknown phase - logging for investigation")
			return ctx
		}),
	),
)

Run(ctx, pipeline)
Output:
checking resource phase
initializing resources
setting up dependencies

Index

Examples

Constants

This section is empty.

Variables

Noop creates a step that does nothing and continues to the next step.

View Source
var Terminal = NewTerminalStepFunc(func(context.Context) {})

Terminal creates a step that terminates the pipeline.

Functions

func CapturedStepName added in v0.15.0

func CapturedStepName(ctx context.Context) string

CapturedStepName returns the step name written into the capture slot set up by WithStepNameCapture. Returns "" if no slot was allocated or no Named step ran.

func RecordTermination added in v0.15.0

func RecordTermination(ctx context.Context, detail string, cause error)

RecordTermination annotates the enclosing bracket's outcome: the pipeline is being terminated deliberately, with a short label for observability ("done", "requeued") and an optional error. Outcome-aware hooks then receive Outcome{Kind: OutcomeTerminated, Detail: detail, Cause: cause} instead of a bare termination.

Detail is attested, not derived: the interpreter reports it only when the step in fact terminated — a step that records a termination and then continues anyway reports OutcomeContinued and the attestation is dropped. An attested termination also takes precedence over a recorded cancellation, because queue operations cancel the context as an implementation detail of stopping the pipeline.

RecordTermination is a no-op when no outcome-aware hook is registered around the step. The queue package calls it from its OperationsContext methods, so queue.Done, queue.Requeue, and hand-rolled steps that invoke queue operations directly are all annotated without further wiring.

func Run

func Run(ctx context.Context, newStep NewStep)

Run executes a NewStep pipeline until completion. With continuation-passing style, the pipeline executes completely in one call.

func StepName added in v0.15.0

func StepName(ctx context.Context) string

StepName returns the name of the currently-executing step from context. Returns the name set by Named if present, otherwise "".

func WithAmbientMiddleware added in v0.15.0

func WithAmbientMiddleware(ctx context.Context, mw Middleware) context.Context

WithAmbientMiddleware composes mw into the ambient middleware stack and returns an updated context. The first-registered middleware is outermost. Passing the zero Middleware is a no-op.

func WithErrorHandler

func WithErrorHandler(ctx context.Context, handler func(error) Step) context.Context

WithErrorHandler adds an error handler to the context. When Continue encounters a cancelled context, it calls this handler with the cancellation cause instead of stopping the pipeline. A non-nil Step returned by the handler is run as a recovery path; see Continue for its semantics.

Example
ctx, cancel := context.WithCancel(context.Background()) //nolint:gosec // cancel called inside pipeline step

// Set up error handler
ctx = WithErrorHandler(ctx, func(_ error) Step {
	fmt.Println("handling cancellation")
	return nil
})

pipeline := Sequence(
	Do(func(ctx context.Context) context.Context {
		fmt.Println("step 1")
		cancel() // Simulate cancellation
		return ctx
	}),
	Do(func(ctx context.Context) context.Context {
		fmt.Println("step 2 (should not run)")
		return ctx
	}),
)

Run(ctx, pipeline)
Output:
step 1
handling cancellation

func WithStepNameCapture added in v0.15.0

func WithStepNameCapture(ctx context.Context) context.Context

WithStepNameCapture allocates a capture slot in context that the first (outermost) Named step fills with its name. This lets observability middleware read the step name even for terminal steps that never invoke their continuation. The slot is a pointer to an atomic, so concurrent Named branches (e.g. under Parallel) fill it without racing and the first writer wins. Pair with CapturedStepName to read the result.

func WithoutAmbientMiddleware added in v0.15.0

func WithoutAmbientMiddleware(ctx context.Context) context.Context

WithoutAmbientMiddleware clears the ambient middleware stack, so steps run under the returned context — including branches of a Parallel reached from it — run with no ambient middleware.

Its signature is a ContextFunc, so it drops straight into a pipeline to exempt everything downstream:

Sequence(Do(WithoutAmbientMiddleware), Parallel(a, b, c))

Use it to carve a subtree out of middleware that is registered globally.

Types

type ContextFunc

type ContextFunc func(context.Context) context.Context

ContextFunc is a function that does work with context. It takes a context, performs operations, and returns the (potentially modified) context so it can be threaded through the pipeline.

type DecisionStep

type DecisionStep struct {
	// contains filtered or unexported fields
}

DecisionStep implements conditional execution.

func (*DecisionStep) Run

func (d *DecisionStep) Run(ctx context.Context) Step

type EnumStep

type EnumStep[T comparable] struct {
	// contains filtered or unexported fields
}

EnumStep implements multi-way branching based on enum values.

func (*EnumStep[T]) Run

func (e *EnumStep[T]) Run(ctx context.Context) Step

type Middleware added in v0.15.0

type Middleware struct {
	// contains filtered or unexported fields
}

Middleware is an opaque, immutable stack of paired before/after hooks that dispatch applies around each step. The zero value is the identity middleware, and Compose makes Middleware a monoid.

Middleware is sealed: the only constructors are the hook generators — Before, After, AfterOutcome, Deferred, and CrashHandler, plus the Around pair — and Compose. This is what makes the laws in FORMAL.md ("The Bracket Laws") theorems about the type rather than conventions for its users — a Middleware value is hook data, not code, so it cannot invoke a step twice, substitute a continuation, or resurrect a terminated pipeline. The one control capability a hook can hold is scoped and constructor-chosen: Deferred and CrashHandler hooks run on the unwinding defer chain and may recover a panic (converting it into a termination, or re-raising it), while Before/After/AfterOutcome hooks are pure observations and cannot. Everything else lives in the interpreter (see Wrap and AmbientDispatch).

For step transformations that hooks cannot express — retries, panic recovery, custom scoping — write a plain func(NewStep) NewStep and apply it directly or with Map. Such wrappers are ordinary composition: they make no law claims and do not ride the ambient dispatch path.

middleware.Log (in state/middleware) is an example of a Middleware.

func After added in v0.15.0

func After(fn ContextFunc) Middleware

After returns a Middleware with a single after hook: fn runs once the wrapped step completes — including when the step is terminal, cancels the context, or panics, none of which invoke the continuation — so finalizers (stop a timer, end a span, record a metric) always fire.

The hook is released by a defer, so it also runs while a panic unwinds. It is observation-only: a library adapter, not fn itself, is the defer operand, so recover inside fn is a no-op and the panic propagates with its value and stack untouched (see Deferred for the recover-capable form). As with any finalizer, a hook that itself panics masks the original panic.

fn runs for its side effects: the context it returns is threaded to subsequent steps only when the wrapped step continued the pipeline.

In a composed stack, before hooks execute in composition order and after-form hooks close in reverse composition order (see Compose). A nil fn returns the zero (identity) Middleware.

func AfterOutcome added in v0.15.0

func AfterOutcome(fn func(context.Context, Outcome) context.Context) Middleware

AfterOutcome returns a Middleware with a single after hook that also receives the Outcome of the wrapped step: continued, terminated (with any attested detail), cancelled (with the cancellation cause), or panicked. Use it for observability that should classify results — span statuses, outcome-labeled metrics, log levels that escalate on failure.

AfterOutcome hooks hold the same capability as After hooks: observation only. On the panic path the hook runs while the panic unwinds with Kind OutcomePanicked, but the panic value is not exposed and recover inside the hook is a no-op — interception requires Deferred or CrashHandler.

As with After, fn runs for its side effects: its returned context is threaded onward only when the step continued. A nil fn returns the zero (identity) Middleware.

func AmbientMiddleware added in v0.15.0

func AmbientMiddleware(ctx context.Context) Middleware

AmbientMiddleware returns the composed middleware from context. Returns the zero (identity) Middleware if none has been registered.

func Around added in v0.15.0

func Around(before, after ContextFunc) Middleware

Around returns the classic paired bracket — Compose(Before(before), After(after)): before runs ahead of the step, and after is guaranteed once the step completes, on every outcome. Either hook may be nil; if both are nil the result is the zero (identity) Middleware.

func Before added in v0.15.0

func Before(fn ContextFunc) Middleware

Before returns a Middleware with a single before hook: fn runs ahead of the wrapped step, and the context it returns threads into the step. A nil fn returns the zero (identity) Middleware.

func Compose added in v0.15.0

func Compose(mws ...Middleware) Middleware

Compose combines middleware into one stack. The first argument is outermost — its before hook fires first and its after hook last — matching the registration order of WithAmbientMiddleware. In general: before hooks execute in composition order, and after-form hooks close in reverse composition order, like nested defers. Compose is associative and the zero Middleware is its identity, making Middleware a monoid; these laws are verified in formal_test.go.

func CrashHandler added in v0.15.0

func CrashHandler(fn func(context.Context, ...func(context.Context, any))) Middleware

CrashHandler is the deferred-hook variant whose signature matches crash-handler conventions: the hook receives the bracket-entry context by value and is deferred directly, so a recover() in its body — or in the body of a handler passed whole, since the handler itself is the defer operand — is effective.

The shape is chosen so that utilruntime.HandleCrashWithContext is assignable as-is (the variadic parameter is why a plain func(ctx) variant would not accept it):

ctx = state.WithAmbientMiddleware(ctx, state.CrashHandler(utilruntime.HandleCrashWithContext))

This must be the whole hook, not a call inside one: recover is effective only in the deferred function itself, so wrapping the handler in a closure silently disables it.

Unlike Deferred's pointer hook, the context is passed by value as observed at bracket entry — the hook cannot amend the forwarded context, which suits crash handlers: on the panic path there is no threaded context anyway, and the entry context carries the loggers and values the handler needs.

A nil fn returns the zero (identity) Middleware.

func Deferred added in v0.15.0

func Deferred(fn func(*context.Context)) Middleware

Deferred returns a Middleware whose single after hook is the defer operand itself: it runs as `defer fn(&ctx)` around the wrapped step, so the hook sits on the panicking defer chain and a recover() written directly in its body is effective. This is a constructor for hand-written crash-handler middleware; registered ambient, it covers every Parallel branch on the branch's own goroutine.

Semantics beyond After hooks:

  • recover() in the hook body intercepts a panicking step. Recovering without re-panicking converts the panic into a termination — the pipeline stops as if the step were terminal, and responsibility for the abandoned work is the hook's. Re-panic (panic(r)) to observe the panic and keep the crash loud.
  • The recover must appear literally in the hook body. Go makes recover effective only when called directly by the deferred function, so helpers that recover internally silently do nothing when called from the hook. To use such a helper (utilruntime.HandleCrashWithContext, for example) as the hook itself, see CrashHandler, whose hook signature matches it directly.
  • On the normal path the hook still runs (recover returns nil when no panic is active); read and write the context through the pointer, which observes the context the step threaded forward (B3).

A nil fn returns the zero (identity) Middleware.

func (Middleware) IsZero added in v0.15.0

func (m Middleware) IsZero() bool

IsZero reports whether m is the identity middleware (no hooks).

func (Middleware) Wrap added in v0.15.0

func (m Middleware) Wrap(step NewStep) NewStep

Wrap applies the middleware to a single step: m's before hooks run (outermost first), then the step, then m's after hooks (innermost first), with the after hooks guaranteed on every outcome — continue, terminal, cancel, or panic unwind. Wrap is the interpreter for Middleware, and it uses the least machinery each stack requires:

  • zero middleware: returns step unchanged — exact identity.
  • before hooks only: stays in the pure algebra — the result is literally Sequence(Do(before)..., step), so it inherits the Kleisli laws.
  • any after hook: delimits the step with the package's one control operator (see runBracketed), because a finalizer that survives terminal steps is not expressible by Kleisli composition (the Absorption Theorem in FORMAL.md).

type NewStep

type NewStep func(next Step) Step

NewStep is a function that creates a Step when given the next step to execute. This is the basic building block for composing step pipelines using continuation-passing style.

func AmbientDispatch added in v0.15.0

func AmbientDispatch(steps ...NewStep) NewStep

AmbientDispatch wraps each step so that ambient middleware registered in context fires around every step as the pipeline executes. It is the opt-in mechanism for ambient middleware support:

state.Run(ctx, state.AmbientDispatch(a, b, c))

Each step argument is wrapped individually — middleware fires once per step, not once for the whole group. Middleware registered via WithAmbientMiddleware before Run applies to all steps. Middleware registered mid-pipeline (inside a step) applies to all subsequent steps in the same AmbientDispatch call.

AmbientDispatch works for any NewStep, including raw StepFunc closures and struct method steps — no special constructor is required.

Composite steps are opaque to it: a Sequence or Parallel passed to AmbientDispatch is one step, so middleware fires once around the whole group rather than once per inner step. Parallel additionally dispatches into its own branches, so under AmbientDispatch a Parallel fires middleware once for the group and once more inside each branch.

func Decision

func Decision(predicate func(context.Context) bool, trueHandler, falseHandler NewStep) NewStep

Decision creates a conditional step that chooses between two paths.

Example
ctx := context.Background()

// Decision based on a simple condition
condition := true

pipeline := Decision(
	func(_ context.Context) bool {
		return condition
	},
	Do(func(ctx context.Context) context.Context {
		fmt.Println("true branch")
		return ctx
	}),
	Do(func(ctx context.Context) context.Context {
		fmt.Println("false branch")
		return ctx
	}),
)

Run(ctx, pipeline)
Output:
true branch

func Dispatch added in v0.15.0

func Dispatch(step NewStep) NewStep

Dispatch is the single-step form of AmbientDispatch. It carries the ambient middleware stack across a boundary that middleware applied outside cannot reach.

Dispatch is a plain step transformer, not a Middleware: it is part of the interpreter that applies Middleware, one level up from the sealed type.

Parallel already applies it to its own branches, so most code never needs it directly. Reach for it when writing a combinator of your own that crosses a goroutine boundary.

Like AmbientDispatch, Dispatch is inert when no middleware is registered.

func Do

func Do(fn ContextFunc) NewStep

Do lifts a ContextFunc into a pipeline step. This is the primary way to add work to a pipeline.

func Enum

func Enum[T comparable](
	selector func(context.Context) T,
	cases map[T]NewStep,
	defaultHandler NewStep,
) NewStep

Enum creates a multi-way branching step based on a selector function. The selector function returns a value that is matched against the cases map. If no match is found, the defaultHandler is executed.

Example
operationKey := ctxkey.New[string]()
ctx := operationKey.Set(context.Background(), "create")

pipeline := Enum(
	func(ctx context.Context) string {
		return operationKey.MustValue(ctx)
	},
	map[string]NewStep{
		"create": Do(func(ctx context.Context) context.Context {
			fmt.Println("creating resource")
			return ctx
		}),
		"update": Do(func(ctx context.Context) context.Context {
			fmt.Println("updating resource")
			return ctx
		}),
		"delete": Do(func(ctx context.Context) context.Context {
			fmt.Println("deleting resource")
			return ctx
		}),
	},
	Do(func(ctx context.Context) context.Context {
		fmt.Println("unknown operation")
		return ctx
	}),
)

Run(ctx, pipeline)
Output:
creating resource

func Map added in v0.15.0

func Map(wrapper func(NewStep) NewStep, steps ...NewStep) []NewStep

Map applies wrapper to each step and returns the resulting slice. This is useful for applying a uniform policy to a set of steps before passing them to Parallel or other combinators. The wrapper is a plain step transformer; pass a Middleware's Wrap method to apply sealed middleware:

Parallel(Map(instrument.Wrap, step1, step2, step3)...)

or pass a raw func(NewStep) NewStep for transformations that hooks cannot express, such as a deferred crash handler.

The wrapper is called once per step when Map is called.

func Named added in v0.15.0

func Named(name string, step NewStep) NewStep

Named annotates a step with a human-readable name for observability. The name is stored in context before the step executes, making it available to middleware via StepName(ctx).

Named is entirely optional — pipelines behave identically without it.

func NewStepFunc

func NewStepFunc(fn func(ctx context.Context, next Step) Step) NewStep

NewStepFunc creates a NewStep from a function that takes both context and next step. This is a convenience wrapper that eliminates boilerplate:

func MyStep() NewStep {
    return NewStepFunc(func(ctx context.Context, next Step) Step {
        // your logic here
        return Continue(ctx, next)
    })
}

func NewTerminalStepFunc

func NewTerminalStepFunc(fn func(ctx context.Context)) NewStep

NewTerminalStepFunc creates a NewStep that executes a side-effect function and terminates the pipeline. This is a convenience wrapper for steps that don't need to continue to the next step.

Example:

markComplete := state.NewTerminalStepFunc(func(ctx context.Context) {
    log.Println("Processing complete")
    queue.NewQueueOperationsCtx().Done(ctx)
})

func Parallel

func Parallel(steps ...NewStep) NewStep

Parallel composes multiple NewStep functions to run in parallel, then continues to the next step after all complete. Each step runs in a new goroutine.

Ambient middleware registered with WithAmbientMiddleware is applied inside each branch, on that branch's own goroutine. This is the default because the alternative fails silently: middleware whose effect is goroutine-local — a deferred crash handler, say — would look installed while never covering a branch. It follows that such middleware runs concurrently, once per branch, so it must be safe for concurrent use. It is inert when none is registered. To run branches without it, clear the stack first:

Sequence(Do(WithoutAmbientMiddleware), Parallel(a, b, c))

A panicking step crashes the process. Parallel installs no recover, and recover cannot cross a goroutine boundary, so a branch panic bypasses any recover the caller installed around the pipeline: a crash handler wrapping Run never observes it. No information is lost — the process dies with the branch's stack. Because each branch is bracketed on its own goroutine, ambient after-hooks close during the unwind, and a crash handler registered as an ambient CrashHandler observes branch panics from inside each branch (see CrashHandler and the state/middleware package docs). A raw wrapper applied with Map works too.

Example
ctx := context.Background()

// Use atomic counter to demonstrate parallel execution
var counter int32

pipeline := Parallel(
	Do(func(ctx context.Context) context.Context {
		atomic.AddInt32(&counter, 1)
		return ctx
	}),
	Do(func(ctx context.Context) context.Context {
		atomic.AddInt32(&counter, 1)
		return ctx
	}),
	Do(func(ctx context.Context) context.Context {
		atomic.AddInt32(&counter, 1)
		return ctx
	}),
)

Run(ctx, pipeline)
fmt.Printf("counter: %d", atomic.LoadInt32(&counter))
Output:
counter: 3

func Sequence

func Sequence(steps ...NewStep) NewStep

Sequence composes multiple NewStep functions into a sequential pipeline. Each step in the sequence executes in order with proper context threading.

Example
ctx := context.Background()

pipeline := Sequence(
	Do(func(ctx context.Context) context.Context {
		fmt.Println("first stage")
		return ctx
	}),
	Do(func(ctx context.Context) context.Context {
		fmt.Println("second stage")
		return ctx
	}),
	Do(func(ctx context.Context) context.Context {
		fmt.Println("third stage")
		return ctx
	}),
)

Run(ctx, pipeline)
Output:
first stage
second stage
third stage

func Switch

func Switch(
	selector func(context.Context) string,
	cases map[string]NewStep,
	defaultHandler NewStep,
) NewStep

Switch creates a multi-way branching step based on string values. This is a convenience function for the common case of string-based branching.

Example
statusKey := ctxkey.New[string]()
ctx := statusKey.Set(context.Background(), "pending")

pipeline := Sequence(
	Do(func(ctx context.Context) context.Context {
		fmt.Println("processing status")
		return ctx
	}),
	Switch(
		func(ctx context.Context) string {
			return statusKey.MustValue(ctx)
		},
		map[string]NewStep{
			"pending": Do(func(ctx context.Context) context.Context {
				fmt.Println("handling pending status")
				return ctx
			}),
			"complete": Do(func(ctx context.Context) context.Context {
				fmt.Println("handling complete status")
				return ctx
			}),
			"failed": Do(func(ctx context.Context) context.Context {
				fmt.Println("handling failed status")
				return ctx
			}),
		},
		Do(func(ctx context.Context) context.Context {
			fmt.Println("handling unknown status")
			return ctx
		}),
	),
)

Run(ctx, pipeline)
Output:
processing status
handling pending status

func When

func When(predicate func(context.Context) bool, trueHandler NewStep) NewStep

When creates a conditional step with only a true branch. If the predicate returns true, the trueHandler is executed and the pipeline terminates. If the predicate returns false, execution continues to the next step.

This is equivalent to Decision(predicate, trueHandler, Noop) but more readable when there is no meaningful false branch:

state.When(
    func(ctx context.Context) bool { return !resourceReady(ctx) },
    queue.RequeueAfter(30 * time.Second),
)

func (NewStep) Step

func (ns NewStep) Step() Step

Step converts a NewStep to a Step by calling it with nil as the next step.

type Outcome added in v0.15.0

type Outcome struct {
	Kind OutcomeKind
	// Cause is the cancellation cause when Kind is OutcomeCancelled, or the
	// error recorded by the terminal operation (e.g. queue.RequeueErr) when
	// Kind is OutcomeTerminated with a Detail. The panic value is
	// deliberately not exposed here: observation hooks run during the unwind
	// without recovering, so the value remains attached to the propagating
	// panic.
	Cause error
	// Detail is a terminal operation's self-reported refinement of a
	// Terminated outcome — "done" or "requeued" from the queue package —
	// and empty otherwise. See RecordTermination.
	Detail string
}

Outcome reports how a bracketed step's extent ended, as the pipeline itself acted on it (the fidelity law, B5 in FORMAL.md).

type OutcomeKind added in v0.15.0

type OutcomeKind int

OutcomeKind classifies how a bracketed step's extent ended.

const (
	// OutcomeContinued: the step invoked its continuation; the pipeline
	// carries on downstream.
	OutcomeContinued OutcomeKind = iota
	// OutcomeTerminated: the step ended the pipeline deliberately (a
	// terminal step such as Terminal, queue.Done, or queue.Requeue).
	OutcomeTerminated
	// OutcomeCancelled: the step stopped because its context was cancelled.
	OutcomeCancelled
	// OutcomePanicked: the step panicked; the hook observing this outcome is
	// running while the panic unwinds.
	OutcomePanicked
)

func (OutcomeKind) String added in v0.15.0

func (k OutcomeKind) String() string

String returns a stable lowercase label suitable for metrics and logs.

type ParallelStep

type ParallelStep struct {
	// contains filtered or unexported fields
}

ParallelStep implements parallel execution of steps.

func (*ParallelStep) Run

func (p *ParallelStep) Run(ctx context.Context) Step

type Step

type Step interface {
	Run(context.Context) Step
}

Step represents a step in a processing pipeline. Each step processes a context and returns the next step to execute, or nil to terminate.

func Continue

func Continue(ctx context.Context, next Step) Step

Continue runs the next step if it exists and context is not cancelled. If context is cancelled:

  • If an error handler is set via WithErrorHandler, calls the handler and, when the handler returns a non-nil recovery Step, runs it with the handler cleared from context. The context is still cancelled while the recovery step runs, so any Continue inside it stops the recovery path rather than re-entering the handler; build recovery from a terminal step or a single step that does its work in the body.
  • Otherwise, stops the pipeline (returns nil)

This is a helper to avoid the common pattern:

if ctx.Err() != nil {
    return nil
}
if next != nil {
    return next.Run(ctx)
}
return nil

type StepFunc

type StepFunc func(ctx context.Context) Step

StepFunc is a function type that implements Step

func (StepFunc) Run

func (f StepFunc) Run(ctx context.Context) Step

Directories

Path Synopsis
Package middleware provides ready-made state.Middleware implementations for common cross-cutting concerns.
Package middleware provides ready-made state.Middleware implementations for common cross-cutting concerns.

Jump to

Keyboard shortcuts

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