Documentation
¶
Overview ¶
Package headless runs Resterm requests and workflows without the TUI.
The package exposes a library API for CI/CD, automation, and other non-interactive integrations. Choose the entrypoint based on how you run:
- Call Run for a one-shot execution.
- Call Build and then RunPlan when you want to prepare once and reuse the same validated plan across retries, repeated runs, or concurrent calls.
The primary workflow is:
- Construct Options.
- Call Build to prepare and validate a reusable Plan.
- Call RunPlan to execute the prepared plan, or call Run for a one-shot run.
- Inspect the returned Report, Result, and Step values.
- Serialize the report with Report.Encode using JSON, JUnit, or Text.
Reports expose structured failure metadata through Failure values on failed results, steps, and profile iterations. Report.FailureCodes returns the unique failure codes present in a report, and Report.ExitCode returns either detailed classified CI exit codes or the legacy summary pass/fail codes.
WriteJSON, WriteJUnit, and WriteText remain available as helpers over Encode. Programmatic format selection is available through the Format constants JSON, JUnit, and Text, and ParseFormat converts user-provided names into a Format value.
json.Unmarshal reads report JSON back into a Report, including the output of the resterm run --format json command.
Invalid library inputs are reported as UsageError values. Use IsUsageError to classify them, and errors.Is to match specific sentinels such as ErrNoSourcePath or ErrTooFewTargets.
Index ¶
- Constants
- Variables
- func IsUsageError(err error) bool
- type Compare
- type CompareOptions
- type EnvironmentGroup
- type EnvironmentGroups
- type EnvironmentOptions
- type EnvironmentSelection
- type EnvironmentSet
- type ExitCodeMode
- type Failure
- type FailureCategory
- type FailureChain
- type FailureCode
- type FailureFrame
- type FailurePos
- type Format
- type GRPC
- type GRPCOptions
- type GroupedEnvironmentSet
- type HTTP
- type HTTPOptions
- type HistBin
- type Kind
- type Latency
- type Options
- type Percentile
- type Plan
- type Profile
- type ProfileFailure
- type ProfileOptions
- type Report
- func (r *Report) Encode(w io.Writer, f Format) error
- func (r *Report) ExitCode(mode ExitCodeMode) int
- func (r *Report) FailureCodes() []FailureCode
- func (r *Report) HasFailures() bool
- func (r Report) MarshalJSON() ([]byte, error)
- func (r *Report) UnmarshalJSON(b []byte) error
- func (r *Report) WriteJSON(w io.Writer) error
- func (r *Report) WriteJUnit(w io.Writer) error
- func (r *Report) WriteText(w io.Writer) error
- type Result
- type Selection
- type Source
- type StateOptions
- type Status
- type Step
- type StopReason
- type Stream
- type Test
- type Trace
- type TraceBreach
- type TraceBudget
- type UsageError
Examples ¶
Constants ¶
const ( ExitPass = 0 ExitFailure = 1 ExitUsage = 2 ExitInternal = 3 ExitTimeout = 20 ExitNetwork = 21 ExitTLS = 22 ExitAuth = 23 ExitScript = 24 ExitFilesystem = 25 ExitProtocol = 26 ExitRoute = 27 ExitCanceled = 130 )
const DefaultHTTPTimeout = 30 * time.Second
DefaultHTTPTimeout is the timeout applied when Options.HTTP.Timeout is zero.
Variables ¶
var ( // ErrNoSourcePath reports that Options.Source.Path was empty. ErrNoSourcePath = errors.New("headless: source path is required") // ErrNilContext reports that a nil context was passed to Run or RunPlan. ErrNilContext = errors.New("headless: nil context") // ErrTooFewTargets reports that compare mode was enabled without enough targets. ErrTooFewTargets = errors.New("headless: compare requires at least two target environments") // ErrInvalidPlan reports that a zero-value or otherwise invalid Plan was used. ErrInvalidPlan = errors.New("headless: invalid plan") // ErrNilReport reports an attempt to encode a nil report. ErrNilReport = errors.New("headless: nil report") // ErrNilWriter reports an attempt to write to a nil writer. ErrNilWriter = errors.New("headless: nil writer") // ErrUnknownFormat reports a format other than JSON, JUnit or Text. ErrUnknownFormat = errors.New("headless: unknown format") )
Functions ¶
func IsUsageError ¶
IsUsageError reports whether err contains a UsageError.
Types ¶
type Compare ¶
type Compare struct {
Baseline string `json:"baseline,omitempty"`
Group string `json:"group,omitempty"`
}
Compare contains compare-run summary fields.
type CompareOptions ¶ added in v0.27.3
type CompareOptions struct {
Targets []string `json:"targets,omitempty"`
Base string `json:"base,omitempty"`
Group string `json:"group,omitempty"`
}
CompareOptions configures compare runs across multiple environments.
type EnvironmentGroup ¶ added in v0.49.1
type EnvironmentGroup struct {
Default string `json:"default,omitempty"`
Profiles EnvironmentSet `json:"profiles,omitempty"`
}
type EnvironmentGroups ¶ added in v0.49.1
type EnvironmentGroups map[string]EnvironmentGroup
type EnvironmentOptions ¶ added in v0.27.3
type EnvironmentOptions struct {
Set EnvironmentSet `json:"set,omitempty"`
Grouped *GroupedEnvironmentSet `json:"grouped,omitempty"`
Name string `json:"name,omitempty"`
Selection EnvironmentSelection `json:"selection,omitempty"`
FilePath string `json:"filePath,omitempty"`
}
EnvironmentOptions controls environment loading and selection.
type EnvironmentSelection ¶ added in v0.49.1
type EnvironmentSet ¶ added in v0.27.3
EnvironmentSet maps environment names to variable values.
type ExitCodeMode ¶ added in v0.31.1
type ExitCodeMode string
ExitCodeMode selects whether Report.ExitCode returns detailed classified codes or the legacy pass/fail summary codes.
const ( // ExitCodeDetailed returns classified CI exit codes such as timeout, // network, TLS, auth, script, filesystem, protocol, route, or canceled. ExitCodeDetailed ExitCodeMode = "detailed" // ExitCodeSummary returns the legacy pass/fail/usage-style code for reports. ExitCodeSummary ExitCodeMode = "summary" )
type Failure ¶ added in v0.31.1
type Failure struct {
Code FailureCode
Category FailureCategory
ExitCode int
Message string
Source string
Chain []FailureChain
Frames []FailureFrame
}
Failure contains structured machine-readable metadata for a failed result, workflow step, compare step, or profile iteration.
func (Failure) MarshalJSON ¶ added in v1.14.0
MarshalJSON writes the failure the way it appears in the report JSON.
func (*Failure) UnmarshalJSON ¶ added in v1.14.0
UnmarshalJSON reads the failure the way it appears in the report JSON.
type FailureCategory ¶ added in v0.31.1
type FailureCategory string
FailureCategory groups failure codes into broader operational categories.
const ( CategorySemantic FailureCategory = "semantic" CategoryTimeout FailureCategory = "timeout" CategoryNetwork FailureCategory = "network" CategoryTLS FailureCategory = "tls" CategoryAuth FailureCategory = "auth" CategoryScript FailureCategory = "script" CategoryFilesystem FailureCategory = "filesystem" CategoryProtocol FailureCategory = "protocol" CategoryRoute FailureCategory = "route" CategoryCanceled FailureCategory = "canceled" CategoryInternal FailureCategory = "internal" )
type FailureChain ¶ added in v0.36.1
type FailureChain = runfmt.FailureChain
FailureChain contains one context or cause entry in a failure chain.
type FailureCode ¶ added in v0.31.1
type FailureCode string
FailureCode identifies the stable machine-readable reason for a failed item.
const ( FailureAssertion FailureCode = "assertion" FailureTraceBudget FailureCode = "trace_budget" FailureTimeout FailureCode = "timeout" FailureNetwork FailureCode = "network" FailureTLS FailureCode = "tls" FailureAuth FailureCode = "auth" FailureScript FailureCode = "script" FailureFilesystem FailureCode = "filesystem" FailureProtocol FailureCode = "protocol" FailureRoute FailureCode = "route" FailureCanceled FailureCode = "canceled" FailureInternal FailureCode = "internal" FailureUnknown FailureCode = "unknown" )
type FailureFrame ¶ added in v0.36.1
type FailureFrame = runfmt.FailureFrame
FailureFrame contains one runtime stack frame attached to a failure.
type FailurePos ¶ added in v0.36.1
type FailurePos = runfmt.FailurePos
FailurePos identifies a source location in a failure.
type GRPC ¶
type GRPC struct {
Code string `json:"code,omitempty"`
StatusCode int `json:"statusCode,omitempty"`
StatusMessage string `json:"statusMessage,omitempty"`
StatusDetails []string `json:"statusDetails,omitempty"`
}
GRPC contains gRPC response summary fields.
type GRPCOptions ¶ added in v0.27.3
type GRPCOptions struct {
Plaintext *bool `json:"plaintext,omitempty"`
}
GRPCOptions configures default gRPC behavior.
type GroupedEnvironmentSet ¶ added in v0.49.1
type GroupedEnvironmentSet struct {
Groups EnvironmentGroups `json:"groups,omitempty"`
}
type HTTP ¶
type HTTP struct {
Status string `json:"status,omitempty"`
StatusCode int `json:"statusCode,omitempty"`
Protocol string `json:"protocol,omitempty"`
}
HTTP contains HTTP response summary fields.
type HTTPOptions ¶ added in v0.27.3
type HTTPOptions struct {
Timeout time.Duration `json:"timeout,omitempty"`
FollowRedirects *bool `json:"followRedirects,omitempty"`
MaxRedirects *int `json:"maxRedirects,omitempty"`
MaxResponseBytes *int64 `json:"maxResponseBytes,omitempty"`
InsecureSkipVerify bool `json:"insecureSkipVerify,omitempty"`
ProxyURL string `json:"proxyURL,omitempty"`
}
HTTPOptions configures default HTTP client behavior.
type HistBin ¶
HistBin contains one profile histogram bin.
func (HistBin) MarshalJSON ¶ added in v1.14.0
MarshalJSON writes the bin the way it appears in the report JSON.
func (*HistBin) UnmarshalJSON ¶ added in v1.14.0
UnmarshalJSON reads the bin the way it appears in the report JSON.
type Kind ¶
type Kind string
Kind identifies the executed result type.
type Latency ¶
type Latency struct {
Count int
Min time.Duration
Max time.Duration
Mean time.Duration
Median time.Duration
StdDev time.Duration
}
Latency contains aggregate profile latency statistics.
func (Latency) MarshalJSON ¶ added in v1.14.0
MarshalJSON writes the latency the way it appears in the report JSON.
func (*Latency) UnmarshalJSON ¶ added in v1.14.0
UnmarshalJSON reads the latency the way it appears in the report JSON.
type Options ¶ added in v0.27.3
type Options struct {
Version string `json:"version,omitempty"`
Source Source `json:"source,omitempty"`
WorkspaceRoot string `json:"workspaceRoot,omitempty"`
Recursive bool `json:"recursive,omitempty"`
State StateOptions `json:"state,omitempty"`
FailFast bool `json:"failFast,omitempty"`
Environment EnvironmentOptions `json:"environment,omitempty"`
Compare CompareOptions `json:"compare,omitempty"`
Profile ProfileOptions `json:"profile,omitempty"`
HTTP HTTPOptions `json:"http,omitempty"`
GRPC GRPCOptions `json:"grpc,omitempty"`
Selection Selection `json:"selection,omitempty"`
}
Options configures a headless run.
type Percentile ¶
Percentile contains one profile percentile.
func (Percentile) MarshalJSON ¶ added in v1.14.0
func (p Percentile) MarshalJSON() ([]byte, error)
MarshalJSON writes the percentile the way it appears in the report JSON.
func (*Percentile) UnmarshalJSON ¶ added in v1.14.0
func (p *Percentile) UnmarshalJSON(b []byte) error
UnmarshalJSON reads the percentile the way it appears in the report JSON.
type Plan ¶ added in v0.29.1
type Plan struct {
// contains filtered or unexported fields
}
Plan stores a prepared run configuration. A Plan can be reused across multiple RunPlan calls, including concurrently. The zero value is invalid.
type Profile ¶
type Profile struct {
Count int
Warmup int
Delay time.Duration
TotalRuns int
WarmupRuns int
SuccessfulRuns int
FailedRuns int
Latency *Latency
Percentiles []Percentile
Histogram []HistBin
Failures []ProfileFailure
}
Profile contains profile-run summary fields.
func (Profile) MarshalJSON ¶ added in v1.14.0
MarshalJSON writes the profile the way it appears in the report JSON.
func (*Profile) UnmarshalJSON ¶ added in v1.14.0
UnmarshalJSON reads the profile the way it appears in the report JSON.
type ProfileFailure ¶ added in v0.27.3
type ProfileFailure struct {
Iteration int
Warmup bool
Reason string
Status string
StatusCode int
Duration time.Duration
Failure *Failure
}
ProfileFailure contains one failed profile iteration.
func (ProfileFailure) MarshalJSON ¶ added in v1.14.0
func (p ProfileFailure) MarshalJSON() ([]byte, error)
MarshalJSON writes the profile failure the way it appears in the report JSON.
func (*ProfileFailure) UnmarshalJSON ¶ added in v1.14.0
func (p *ProfileFailure) UnmarshalJSON(b []byte) error
UnmarshalJSON reads the profile failure the way it appears in the report JSON.
type ProfileOptions ¶ added in v0.28.2
type ProfileOptions struct {
Enabled bool `json:"enabled,omitempty"`
}
ProfileOptions configures profile runs.
type Report ¶
type Report struct {
SchemaVersion string
Version string
FilePath string
EnvName string
EnvironmentSelection EnvironmentSelection
StartedAt time.Time
EndedAt time.Time
Duration time.Duration
Results []Result
Total int
Passed int
Failed int
Skipped int
StopReason StopReason
// Warnings holds parse warnings with their source location. They never
// affect HasFailures or the exit code.
Warnings []string
}
Report contains the results of a headless run.
func Run ¶
Run executes a request or workflow file and returns a stable public report. Use Run for one-shot execution when you do not need to reuse a prepared plan.
Example ¶
package main
import (
"bytes"
"context"
"fmt"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"github.com/unkn0wn-root/resterm/headless"
)
func main() {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, _ = fmt.Fprint(w, `{"ok":true}`)
}))
defer srv.Close()
dir, err := os.MkdirTemp("", "headless-example-*")
if err != nil {
fmt.Println(err)
return
}
defer func() { _ = os.RemoveAll(dir) }()
path := filepath.Join(dir, "api.http")
src := fmt.Sprintf("# @name ok\nGET %s\n", srv.URL)
err = os.WriteFile(path, []byte(src), 0o600)
if err != nil {
fmt.Println(err)
return
}
// Run is the simplest entrypoint when you only need a single execution.
rep, err := headless.Run(context.Background(), headless.Options{
Source: headless.Source{Path: path},
})
if err != nil {
fmt.Println(err)
return
}
var out bytes.Buffer
if err := rep.Encode(&out, headless.Text); err != nil {
fmt.Println(err)
return
}
fmt.Println(rep.Passed, rep.Failed)
}
Output: 1 0
func RunPlan ¶ added in v0.29.1
RunPlan executes a prepared plan and returns a stable public report. Use RunPlan with Build when you want to prepare once and execute the same validated plan multiple times.
Example ¶
package main
import (
"context"
"fmt"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"github.com/unkn0wn-root/resterm/headless"
)
func main() {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, _ = fmt.Fprint(w, `{"ok":true}`)
}))
defer srv.Close()
dir, err := os.MkdirTemp("", "headless-example-*")
if err != nil {
fmt.Println(err)
return
}
defer func() { _ = os.RemoveAll(dir) }()
path := filepath.Join(dir, "api.http")
src := fmt.Sprintf("# @name ok\nGET %s\n", srv.URL)
err = os.WriteFile(path, []byte(src), 0o600)
if err != nil {
fmt.Println(err)
return
}
// Build once when you want to reuse the same validated input across
// repeated runs, retries, or concurrent callers.
pl, err := headless.Build(headless.Options{
Source: headless.Source{Path: path},
})
if err != nil {
fmt.Println(err)
return
}
rep1, err := headless.RunPlan(context.Background(), pl)
if err != nil {
fmt.Println(err)
return
}
rep2, err := headless.RunPlan(context.Background(), pl)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(rep1.Passed, rep2.Passed)
}
Output: 1 1
func (*Report) ExitCode ¶ added in v0.31.1
func (r *Report) ExitCode(mode ExitCodeMode) int
ExitCode returns the report exit code for the requested mode.
func (*Report) FailureCodes ¶ added in v0.31.1
func (r *Report) FailureCodes() []FailureCode
FailureCodes returns the unique failure codes present in the report.
func (*Report) HasFailures ¶
HasFailures reports whether the report failed, which is when ExitCode is not 0.
func (Report) MarshalJSON ¶ added in v0.27.3
MarshalJSON writes the canonical report JSON format.
func (*Report) UnmarshalJSON ¶ added in v1.14.0
UnmarshalJSON reads the report JSON format. Durations come back in whole milliseconds.
func (*Report) WriteJUnit ¶
WriteJUnit writes r as JUnit XML.
type Result ¶
type Result struct {
Kind Kind
Name string
Method string
Target string
EffectiveTarget string
Environment string
EnvironmentSelection EnvironmentSelection
Status Status
Summary string
Duration time.Duration
Canceled bool
SkipReason string
Error string
ErrorDetail string
ScriptError string
ScriptErrorDetail string
Failure *Failure
HTTP *HTTP
GRPC *GRPC
Stream *Stream
Trace *Trace
Tests []Test
Compare *Compare
Profile *Profile
Steps []Step
Warnings []string
}
Result contains one executed request, workflow, compare run, or profile run.
func (Result) Failed ¶
Failed reports whether the result failed. A failed step, profile run or stream counts too.
func (Result) MarshalJSON ¶ added in v0.27.3
MarshalJSON writes the canonical result JSON format.
func (*Result) UnmarshalJSON ¶ added in v1.14.0
UnmarshalJSON reads the result JSON format.
type Selection ¶ added in v0.27.3
type Selection struct {
Request string `json:"request,omitempty"`
Workflow string `json:"workflow,omitempty"`
Tag string `json:"tag,omitempty"`
All bool `json:"all,omitempty"`
}
Selection narrows which request or workflow to run.
type Source ¶ added in v0.29.1
Source identifies the request document to execute. Path is required and provides the logical file identity and relative-resolution anchor. Path may be synthetic when Content is provided. Content overrides the bytes loaded from Path when provided.
type StateOptions ¶ added in v0.27.3
type StateOptions struct {
ArtifactDir string `json:"artifactDir,omitempty"`
StateDir string `json:"stateDir,omitempty"`
PersistGlobals bool `json:"persistGlobals,omitempty"`
PersistAuth bool `json:"persistAuth,omitempty"`
History bool `json:"history,omitempty"`
}
StateOptions controls artifacts and persisted runtime state.
type Status ¶
type Status string
Status reports whether a result passed, failed, or was skipped.
type Step ¶
type Step struct {
Name string
Method string
Target string
EffectiveTarget string
Environment string
EnvironmentSelection EnvironmentSelection
Branch string
Iteration int
Total int
Status Status
Summary string
Duration time.Duration
Canceled bool
SkipReason string
Error string
ErrorDetail string
ScriptError string
ScriptErrorDetail string
Failure *Failure
HTTP *HTTP
GRPC *GRPC
Stream *Stream
Trace *Trace
Tests []Test
}
Step contains one workflow or compare step result.
func (Step) MarshalJSON ¶ added in v0.27.3
MarshalJSON writes the canonical step JSON format.
func (*Step) UnmarshalJSON ¶ added in v1.14.0
UnmarshalJSON reads the step JSON format.
type StopReason ¶ added in v0.31.1
type StopReason string
StopReason explains why a run stopped before all selected work completed. The zero value means the run completed normally.
const ( // StopReasonFailFast means Options.FailFast stopped execution after a failure. StopReasonFailFast StopReason = "fail_fast" // StopReasonCanceled means the run context was canceled. StopReasonCanceled StopReason = "canceled" )
type Stream ¶
type Stream struct {
Kind string
EventCount int
Summary map[string]any
TranscriptPath string
Error string
}
Stream contains streaming response metadata.
func (Stream) MarshalJSON ¶ added in v1.14.0
MarshalJSON writes the stream the way it appears in the report JSON.
func (*Stream) UnmarshalJSON ¶ added in v1.14.0
UnmarshalJSON reads the stream the way it appears in the report JSON.
type Test ¶
Test contains one assertion result.
func (Test) MarshalJSON ¶ added in v1.14.0
MarshalJSON writes the test the way it appears in the report JSON.
func (*Test) UnmarshalJSON ¶ added in v1.14.0
UnmarshalJSON reads the test the way it appears in the report JSON.
type Trace ¶
type Trace struct {
Duration time.Duration
Error string
Budget *TraceBudget
Breaches []TraceBreach
ArtifactPath string
}
Trace contains trace summary metadata.
func (Trace) MarshalJSON ¶ added in v1.14.0
MarshalJSON writes the trace the way it appears in the report JSON.
func (*Trace) UnmarshalJSON ¶ added in v1.14.0
UnmarshalJSON reads the trace the way it appears in the report JSON.
type TraceBreach ¶
TraceBreach contains one trace budget breach.
func (TraceBreach) MarshalJSON ¶ added in v1.14.0
func (t TraceBreach) MarshalJSON() ([]byte, error)
MarshalJSON writes the breach the way it appears in the report JSON.
func (*TraceBreach) UnmarshalJSON ¶ added in v1.14.0
func (t *TraceBreach) UnmarshalJSON(b []byte) error
UnmarshalJSON reads the breach the way it appears in the report JSON.
type TraceBudget ¶
type TraceBudget struct {
Total time.Duration
Tolerance time.Duration
Phases map[string]time.Duration
}
TraceBudget contains trace budget limits.
func (TraceBudget) MarshalJSON ¶ added in v1.14.0
func (t TraceBudget) MarshalJSON() ([]byte, error)
MarshalJSON writes the budget the way it appears in the report JSON.
func (*TraceBudget) UnmarshalJSON ¶ added in v1.14.0
func (t *TraceBudget) UnmarshalJSON(b []byte) error
UnmarshalJSON reads the budget the way it appears in the report JSON.
type UsageError ¶ added in v0.27.3
type UsageError struct {
// contains filtered or unexported fields
}
UsageError reports invalid input or options passed to the headless API.
func (UsageError) Error ¶ added in v0.27.3
func (e UsageError) Error() string
func (UsageError) Unwrap ¶ added in v0.27.3
func (e UsageError) Unwrap() error