Go Step Generator
Make ordinary Go functions available to Argyll with generated registration and serving.
The generator exposes Go functions as Steps, deriving Attributes from their parameters and results. Serve them over HTTP or run them inside an embedded engine.
Installation
The generator ships with the Go SDK:
go get github.com/kode4food/argyll/sdk/go
Quick Start
For a standalone Step server, use package main, pass -server before the package pattern, and add a directive to a function:
package main
//go:generate go run github.com/kode4food/argyll/sdk/go/gen/cmd/argyll-gen -server .
type RiskArgs struct {
CustomerID string
Amount int64
}
type RiskResult struct {
Score int
Approved bool
}
//argyll:step
func CalculateRisk(args RiskArgs) (RiskResult, error) {
return RiskResult{
Score: int(args.Amount / 100),
Approved: args.Amount < 10_000,
}, nil
}
Run go generate ./..., then build or run the package normally. The generated zz_argyll_gen.go contains main, registers every Step in the package, and serves their handlers. Each invocation is logged through the default slog logger with its Step ID.
-server requires package main and rejects a package that already declares main.
The generated server reads ARGYLL_ENGINE_URL, STEP_HOSTNAME, and STEP_PORT from the environment.
Custom Server
Leave off -server when the application owns its startup, HTTP server, or logging:
//go:generate go run github.com/kode4food/argyll/sdk/go/gen/cmd/argyll-gen ./...
Normal generation emits ArgyllServiceSteps() for use with your application’s server and logging. Pass those definitions to gen.Serve, or use gen.Register and gen.Mux to configure the HTTP server yourself:
import "github.com/kode4food/argyll/sdk/go/gen"
func main() {
if err := gen.Serve(context.Background(), ArgyllServiceSteps()...); err != nil {
log.Fatal(err)
}
}
Embedded Engine
Normal generation also emits ArgyllEmbeddedHandlers() and ArgyllEmbeddedSteps(), which run the same functions inside an embedded engine. Install the handlers alongside the built-in ones, then register the Steps:
client := builtins.NewHTTPClient(30 * time.Second)
handlers := builtins.All(client, nil)
eng, err := argyll.New(argyll.Options{
Backend: open,
Handlers: handlers.With(ArgyllEmbeddedHandlers()),
})
if err != nil {
return err
}
if err := eng.Start(); err != nil {
return err
}
return eng.RegisterSteps(ArgyllEmbeddedSteps()...)
Each embedded Step’s type names the handler that runs it, and ArgyllEmbeddedHandlers() keys each handler by that type. The type is the Step ID unless //argyll:embed names one. ArgyllEmbeddedSteps() carries the same Attributes, predicate, Work Item settings, tags, and handling as ArgyllServiceSteps(), and reaches its handler in process.
A handler serves every Step of its type, so one function can back several Steps. Name the type:
//argyll:step
//argyll:embed greeter
func Greet(args struct{ Name string }) struct{ Greeting string }
Then register another Step of that type, mapping its own Attributes onto the function’s invocation names:
err := eng.RegisterStep(&api.Step{
ID: "welcome",
Name: "Welcome",
Type: "greeter",
Attributes: api.AttributeSpecs{
"guest": {
Role: api.RoleRequired,
Required: &api.RequiredConfig{
Mapping: &api.MappingConfig{Name: "name"},
},
},
"welcome": {
Role: api.RoleOutput,
Output: &api.OutputConfig{
Mapping: &api.MappingConfig{Name: "greeting"},
},
},
},
})
The welcome Step runs Greet with its guest Attribute as name and records the greeting as welcome, alongside the generated greet Step. Step types take the same lowercase, hyphenated form as IDs. Each type names one function, and service, script, and flow belong to the built-in Step types. //argyll:embed shapes the embedded output alone, so -server generation serves the same Steps over HTTP.
Meta Attributes are filled from the running Work Item: flow_id, step_id, and receipt_token, plus any key in the Flow’s metadata. A compensator receives the compensated Attributes, the same set a generated HTTP compensation endpoint receives.
Directives
Every generated Step starts with one primary directive in the function’s doc comment:
| Directive | Function shape |
|---|---|
//argyll:step | Zero arguments or one argument struct, zero results or one result struct, and an optional trailing error |
//argyll:wrap | Ordinary positional arguments and results |
Additional directives in that same doc comment configure the Step:
| Directive | Configuration |
|---|---|
//argyll:memoize | Memoized handling |
//argyll:compensate Refund | Compensated handling through Refund |
//argyll:predicate argyll:amount > 0 | Execution predicate |
//argyll:work max_retries:3 | Retry and concurrency settings |
//argyll:http timeout:2500 | HTTP invocation settings |
//argyll:tags domain:risk | Step tags |
//argyll:description scores a customer | Step description |
//argyll:embed greeter | Embedded Step type |
Directives and field tags share one option format: a leading value names the subject, and semicolon-separated key:value properties configure it. Whitespace around values and separators is optional. For example, this declares the Step ID charge-card-v2 and the display name Charge Card (v2):
//argyll:step charge-card-v2;name:Charge Card (v2)
Currency string `argyll:"iso_currency;role:optional;default:USD"`
On a struct field, the leading value overrides the inferred Attribute name. This tag names the Attribute iso_currency, assigns the optional role, and gives it the default USD.
memoize is a marker and compensate names one function, and a Step takes at most one of these two handling modes. http and work accept properties and may be repeated across lines, as may tags, which takes plain semicolon-separated values.
An omitted ID is the function name in kebab-case. IDs use lowercase letters and digits, separated by hyphens.
The optional name property follows the ID on //argyll:step or //argyll:wrap, defaulting to the function name in Title Case.
//argyll:step
A Step function accepts these signatures, using named or anonymous structs:
func()
func() Result
func() (Result, error)
func() error
func(Args)
func(Args) Result
func(Args) error
func(Args) (Result, error)
Fields of the argument struct become Step inputs, and fields of the result struct become Step outputs.
//argyll:wrap
Use //argyll:wrap with a positional function. Square brackets mark optional parts:
//argyll:wrap [step-id] [(input, ...)] [-> (output, ...)] [;name:Display Name]
The lists name Attributes in the same order as the function’s parameters and non-error results. The -> separates inputs from outputs, and a trailing error is never an output Attribute. Omitted lists are inferred from named Go parameters or results, while () explicitly declares an empty side.
With both sides named in Go, the bare directive can infer the complete contract and convert names to snake_case:
//argyll:wrap
func CalculateRisk(
customerID string, amount int64,
) (score int, approved bool, err error)
That yields inputs customer_id and amount, plus outputs score and approved.
Unnamed results need an output list. Here the omitted input list is inferred from the named parameters, while (score, approved) names the two results:
//argyll:wrap -> (score, approved)
func CalculateRisk(customerID string, amount int64) (int, bool, error)
Names supplied by the directive are used verbatim. This complete declaration sets the Step ID to score-v2, overrides both input names, and names both results:
//argyll:wrap score-v2(customer-id, amount) -> (score, approved)
func CalculateRisk(customerID string, amount int64) (int, bool, error)
For a source function with no parameters, () -> (score) explicitly declares no inputs and names its one output:
//argyll:wrap () -> (score)
func CurrentScore() int
The generator checks the declared names against the function signature at build time and reports mismatches at their source position.
//argyll:predicate
Declares the script that gates the Step. Use the argyll: prefix for Argyll Expressions:
//argyll:step
//argyll:predicate argyll:amount > 0
func ChargeCard(args ChargeArgs) (ChargeResult, error)
The recognized language prefixes are argyll: and lua:. Without a recognized prefix, the script defaults to Lua. Any other prefix is part of that Lua script.
//argyll:work
Configures retries, Work Item concurrency, and memoized result lifetime. It is repeatable:
//argyll:work max_retries: 3; init_backoff: 100; max_backoff: 5000
//argyll:work backoff_type: exponential; parallelism: 4
| Property | Effect |
|---|---|
backoff_type | Retry backoff: fixed, linear, or exponential |
max_retries | Maximum retries, or -1 to retry without a limit |
init_backoff | Initial retry delay in milliseconds |
max_backoff | Maximum retry delay in milliseconds |
parallelism | Maximum concurrent Work Items |
memo_ttl | How long memoized results stay reusable, in milliseconds |
//argyll:memoize
Marks a Step as memoized:
//argyll:step
//argyll:memoize
func CalculateRisk(args RiskArgs) (RiskResult, error)
The engine reuses successful results for matching inputs. //argyll:memoize and //argyll:compensate select mutually exclusive handling modes.
//argyll:compensate
Names the function that reverses a successful Step invocation:
type ChargeArgs struct {
OrderID string `argyll:"compensated:true"`
}
type ChargeResult struct {
ChargeID string `argyll:"compensated:true"`
}
type RefundArgs struct {
ChargeID string
}
//argyll:step
//argyll:compensate Refund;timeout:5000
func Charge(args ChargeArgs) (ChargeResult, error)
func Refund(args RefundArgs) error
A //argyll:step compensator takes zero arguments or one argument struct. Every field in that struct must match an Attribute marked compensated:true on the Step, using its invocation name, but the struct may omit compensated Attributes it does not use.
When a compensator wants everything the Step took and returned, it can embed both structs to include all their fields. Every included field has to be a compensated Attribute, so this fits a Step whose inputs are compensated whole:
type RefundArgs struct {
ChargeArgs
ChargeResult
}
A //argyll:wrap compensator’s named positional arguments select the Step Attributes it consumes. A compensator returns either nothing or an error.
The generator validates the signature and serves the function at POST /<step-id>/compensate. The optional timeout property overrides the invocation timeout for compensation, which otherwise inherits the Step’s timeout. The directive selects compensated handling. The referenced function becomes a Step of its own only when it carries a //argyll:step or //argyll:wrap directive.
//argyll:http
Configures the generated Step’s HTTP invocation:
//argyll:step charge-card;name:Charge Card
//argyll:http timeout: 2500
func ChargeCard(args ChargeArgs) (ChargeResult, error)
| Property | Effect |
|---|---|
timeout | Invocation timeout in milliseconds |
The engine enforces timeout around the invocation. Generated Steps serve their synchronous handlers through POST at an endpoint the generator derives from the Step ID.
//argyll:tags
Step tags, repeatable and semicolon separated. A tag is an opaque string, so it carries any prefix:value convention through as written:
//argyll:step
//argyll:tags domain:risk; domain:payments
//argyll:tags tier:gold; example
func CalculateRisk(args RiskArgs) (RiskResult, error)
The generator sorts and dedupes the four tags, so their order across lines is free.
//argyll:description
Step description, taking the rest of the line as prose:
//argyll:step
//argyll:description score a customer for risk
func CalculateRisk(args RiskArgs) (RiskResult, error)
One description per Step: repeating the directive is an error, as is leaving it empty.
Contract Inference
By default, field names map to attribute names as snake_case. An argyll field tag overrides the default per field:
| Go field | Attribute |
|---|---|
CustomerID string | customer_id |
HTTPServer string | http_server |
Amount int64 | amount |
Note *string | note, optional |
Currency string `argyll:"iso_currency"` | iso_currency |
The function name becomes the Step identity, as kebab-case: func CalculateRisk registers as ID calculate-risk, name Calculate Risk.
Field Tags
An argyll struct tag overrides that default and names the attribute explicitly:
type EnrollArgs struct {
Currency string `argyll:"iso_currency"`
Scratch string `argyll:"-"`
}
A tag of - excludes the field from the contract and serialized data. Unexported fields are also excluded.
The tag applies wherever the struct appears, in inputs, in outputs, and at any nesting depth. The generator rejects a property it does not know, reporting the file, line, and field.
Embedded Structs
An embedded struct flattens, so each of its fields becomes an Attribute of the outer struct:
type ChargeArgs struct {
OrderID string `argyll:"compensated:true"`
}
type ChargeResult struct {
ChargeID string `argyll:"compensated:true"`
}
type RefundArgs struct {
ChargeArgs
ChargeResult
}
RefundArgs carries order_id and charge_id as top-level Attributes. Flattening applies at any depth and keeps each field’s tag.
Any argyll tag on the embedded field opts out of flattening, making it one nested object Attribute like an ordinary field, named by the tag or by the embedded type. A tag of - drops it entirely:
type RefundArgs struct {
ChargeArgs `argyll:"charge"`
}
Flattened fields must have unique Attribute names and Go field names. A collision is reported as an ambiguous embedded field.
Attribute Properties
Properties after the name configure the attribute. Leave the name off to keep the snake_case default and still set properties:
type ChargeArgs struct {
OrderID string `argyll:"for_each:true;collect:all"`
Note string `argyll:"role:optional"`
Currency string `argyll:"role:optional;default:USD;deadline:5000"`
Gateway string `argyll:"role:const;value:stripe"`
FlowID string `argyll:"flow;role:meta;key:flow_id"`
Amount int64 `argyll-match:"argyll:value > 0"`
Receipt string `argyll:"compensated:true"`
}
| Property | Effect |
|---|---|
role | required, optional, const, or meta, defaulting to required for a value field and optional for a pointer |
default | Default value of an optional input |
value | Fixed value of a const input |
key | Execution metadata key filling a meta input |
collect | first, last, all, some, or none |
deadline | Optional input’s inactivity interval in milliseconds, where each timely value resets its window (see Collection Deadline) |
for_each | true to expand the attribute into one Work Item per collected value, requiring collect:all or collect:some |
mapping | Name the attribute is mapped to |
compensated | true to include the Attribute in compensation requests |
Each property belongs to an Attribute role. Validation reports both the property and required role: default uses optional, value uses const, key uses meta, and mapping uses an input or output.
default and value reach the engine as JSON, and the generator quotes the value of a string field for you, so default:USD is written plainly.
Use argyll-match for a field’s match condition and argyll-mapping for its value transformation:
Amount int64 `argyll-match:"argyll:value > 0" argyll-mapping:"argyll:amount * 100"`
Both tags use [language:]script, where the optional known language is lua or argyll. Both default to Argyll Expressions. A match needs a required input, while a mapping script needs an input or output. In this example, the match tests the candidate as value, and the input mapping converts the accepted amount from dollars to cents.
Generated scripts follow the same validation and failure behavior as scripts registered directly. Invocation Mapping describes output script bindings and language limitations.
A for_each field uses the element type: OrderID string above receives one order ID per Work Item.
An output can set its name, mapping, argyll-mapping script, and compensation flag. Fields nested inside an arguments or outputs struct are values within an Attribute, so their tags configure only the field name.
Field Types
A pointer field is an optional attribute. Structs and maps nest to any depth, including recursively:
type Node struct {
Name string
Children []Node
Next *Node
}
Unsupported field types fail generation with their source position. Embedded handlers convert persisted numeric values from and to float64.
Failures
A returned error responds 422 with problem details, which permanently fails the Work Item. A recovered panic responds 500 and logs the panic value with its stack, and the engine retries the Work Item.
To choose the status, return an *argyll.HTTPError:
return argyll.NewHTTPError(http.StatusNotFound, "no such customer")
The status decides what happens next: a 5xx status retries the Work Item, and every other non-2xx status fails it permanently.
In an embedded engine, a returned error or a recovered panic fails the Work Item directly, and a panic keeps its value and stack in the failure.
Validation
The generator assembles an api.Step and applies the engine’s validation rules during go generate. Validation errors include the source file and line, covering cases such as an unknown collect value, for_each without collect:all or collect:some, an invalid JSON default, or a URL placeholder that has no required input.
The generated file carries the validated Step as an api.Step value. Registration adds the Step server’s reachable host and submits that definition.
Generated Output
Each package gets one zz_argyll_gen.go. In normal mode, its package-level symbols are ArgyllServiceSteps(), ArgyllEmbeddedHandlers(), and ArgyllEmbeddedSteps().
With -server, the generator produces a main function that registers and serves the Steps over HTTP with invocation logging.
One go:generate line is enough for a whole tree in normal mode. The generator scans every file of every package matching the pattern, so ./... reaches the directive’s own package and everything beneath it, writing a file into each package that declares Steps. Use a package-specific pattern such as . with -server, because every matched package that declares Steps must be a package main. Extra go:generate lines are safe.
Treat it as a build artifact, gitignored and rebuilt by your generate target, so it always matches the directives and the generator. Run go generate ./... ahead of go build in your Makefile and container builds.
Choosing Between the Generator and the Builder
Use the generator when the Go function owns the Step contract: its signature defines the Attributes, and directives add predicates, Work Item configuration, HTTP settings, tags, and handling. Use the builder to register existing HTTP services (sync or async), Script Steps, Flow Steps, and to start Flows. Both paths produce the same Step definition and can be used together in one package.