Skip to the content.

Docs home · Overview · Architecture · Workflows

Deep Dive: Configuration and Request Building

Overview

This page covers how user input becomes a validated config.Config, and how each request’s URL, headers and body are filled in. The supporting packages are placeholders, feeders, the per-worker variable store, extractors, auth providers, HAR conversion, thresholds, tracing, tag filters and set templates.

For the user-facing reference of every key and flag, see Configuration.

Responsibilities

Architecture

graph TB
  FL["config/flags.go - pflag set on a cobra command"] --> LD["config/loader.go - Load"]
  FILE["viper ReadInConfig"] --> LD
  LD --> CFG["config.Config"]
  CFG -.->|"cli.Run only"| VAL["Validate"]
  CFG --> RB["httpclient.RequestBuilder"]
  FEED["feeder.Feeder"] --> RB
  VARS["variables.Store in ctx"] --> PH["placeholders.Apply"]
  RB --> PH
  AUTH["auth.Provider"] --> RB
  RB --> REQ["http.Request"]
  RESP["response body"] --> EX["extractor.ExtractAll"]
  EX --> VARS

Key Files

Implementation Details

Loading and precedence

Load(args) applies settings in three layers:

  1. Struct defaults: Method=GET, Concurrency=1, Timeout=30s, GracefulShutdown=5s, Arrival=uniform.
  2. Config file: read with viper.SetConfigFile and ReadInConfig, so the format comes from the file extension. AllSettings() is then walked by hand.
  3. Flags: copied over the config only when fs.Changed(name) is true.

Viper lowercases every key, so keys are case-insensitive. Most multi-word keys accept the concatenated, snake_case and kebab-case spellings (for example bodyfile, body_file and body-file).

Durations accept Go duration strings or a bare number of seconds. A float is truncated to whole seconds, so 0.5 becomes 0 (asDuration in parsers.go).

Relative paths (body_file, feeder.path, grpc.proto_file, har_file) resolve against the process working directory, not the config file’s directory.

Crankfire’s own code reads these environment variables:

Libraries read some more:

Viper AutomaticEnv is not enabled, so there is no general CRANKFIRE_<KEY> mapping.

Validation

Validate() collects every problem into a ValidationError (validation failed: a; b). It is called only by cli.Run (internal/cli/run.go:54), after Load. BuildRunner does not call it, so TUI runs, set run and daemon runs use the session config unvalidated. store.ImportSessionFromConfigFile (through LoadFromFile) does not validate either.

It covers:

It writes warnings to stderr for:

Request building (HTTP)

NewRequestBuilder* checks that the target is not empty and that header keys are not empty. Header keys and values must not contain CR or LF. It then picks a BodySource:

BodySource Used for
inline body
file body_file; re-opened and streamed on every request
empty no body

The body is scanned once for {{. A body without placeholders is always streamed as is.

Build(ctx) does the following, in order:

  1. feeder.Next(ctx), if a feeder is configured.
  2. Get the variable store from variables.FromContext(ctx).
  3. Apply placeholders to the URL.
  4. Apply placeholders to the body, buffering it first, if it contains placeholders.
  5. Apply placeholders to header values (not keys).
  6. Have the auth provider set Authorization: Bearer .... This overwrites any user-supplied value.

NewClient(timeout) builds the shared transport with:

Redirects are followed using Go’s defaults.

Endpoints

internal/cli/endpoints.go builds one RequestBuilder per endpoint:

Placeholders vs. templates

placeholders.Apply handles the request templates. Its pattern is {{key}} or {{key|default}}, matched by the regex \{\{([^}|]+)(?:\|([^}]*))?\}\}. Keys are not trimmed.

internal/template.Render is unrelated to requests. It is Go text/template ({{.param}}, with the functions default, lower and upper, and missingkey=zero). It is used only for set templates (set new --from-template and the TUI template picker).

Variables and extractors

There is one MemoryStore per worker goroutine. It is a map without locks, created in runner.Run.

After an HTTP response is received:

The two extractor types work as follows:

When an extraction fails, a warning is logged to stderr and the variable is set to "".

Feeders

Auth

The provider is chosen from the auth.type value:

type Provider
oauth2_client_credentials OAuth2Provider, using the client-credentials grant
oauth2_resource_owner OAuth2Provider, using the password grant
oidc_implicit, oidc_auth_code StaticTokenProvider(static_token)

OAuth2Provider behaviour:

HAR conversion

har.Parse reads HAR 1.2 data. Convert turns entries into endpoints using these options:

The HAR endpoints are added after Validate, so duplicate names are not caught.

Thresholds

The grammar is ^([a-z_]+):([a-z0-9]+)\s*(<|<=|>|>=|==)\s*(number)$. The metric and aggregate combinations are:

Metric Aggregates Value
http_req_duration p50, p90, p95, p99, avg, min, max milliseconds
http_req_failed count, rate failure count, or failures / total
http_requests count, rate total requests, or RPS

Tracing

Init returns a no-op provider unless tracing.endpoint is set. When tracing is enabled it sets up:

Request spans are of kind Client and named "<protocol> <endpoint>" or "<protocol> request". They carry the attributes rpc.system and crankfire.endpoint.

Tag filters

A tag filter expression consists of groups separated by whitespace, which are combined with AND. Inside a group, commas mean OR. Tokens must match ^[a-zA-Z0-9._-]{1,64}$, and matching is case-sensitive. Tag filters are used by session list --tag, set list --tag and the TUI filter bar.

Dependencies

API/Interface

func NewLoader() *Loader
func (Loader) Load(args []string) (*Config, error)        // ErrHelpRequested on --help / no args
func LoadFromFile(path string) (*Config, error)
func (c Config) Validate() error
func NewRequestBuilderWithAuthAndFeeder(cfg *config.Config, p AuthProvider, f Feeder) (*RequestBuilder, error)
func (b *RequestBuilder) Build(ctx context.Context) (*http.Request, error)
func Apply(tmpl string, record map[string]string, stores ...variables.Store) string
func ParseMultiple([]string) ([]threshold.Threshold, error)
func Init(ctx context.Context, cfg config.TracingConfig) (*tracing.Provider, error)

Testing

Known Issues & Improvement Opportunities