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
- Define the flag set and merge flags over the config file, which is merged over the defaults.
- Decode the config by hand from viper’s settings map, accepting several key spellings.
- Validate the whole config and collect every issue, and print warnings for risky settings. This happens only on the one-shot
crankfire [flags]path. - Build HTTP requests: body source,
{{placeholder}}substitution, feeder records, auth header. - Extract values from responses into the worker’s variable store.
- Convert HAR recordings into endpoints.
- Parse and evaluate thresholds. Set up OpenTelemetry tracing.
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
internal/config/config.go:Configand its nested structs,Validate,ValidationError,TracingConfig.EnabledandShouldPropagate.internal/config/flags.go: flag definitions andapplyFlagOverrides.internal/config/loader.go:Loader.Load,LoadFromFile,applyConfigSettings, the per-section builders, the auth env-var fallbacks and the HAR pre-check.internal/config/parsers.go: lenientas*converters,lookupSettingandtoStringKeyMap.internal/httpclient/client.goandbody_reader.go:RequestBuilder,NewClientandBodySource.internal/placeholders/placeholders.go:ApplyandApplyToMap.internal/variables/store.go:Store,MemoryStore,NewContextandFromContext.internal/extractor/:ExtractAllwith JSONPath (gjson) and regex.internal/feeder/: CSV and JSON feeders.internal/auth/:Provider,OAuth2ProviderandStaticTokenProvider.internal/har/:Parse,ConvertandConvertOptions.internal/threshold/threshold.go:Parse,ParseMultipleandEvaluator.internal/tracing/:Init,StartRequestSpan,EndSpanand the inject helpers.internal/tagfilter/(Parse,Matcher) andinternal/template/render.go(Render).internal/cli/:auth_helpers.go,feeder_helpers.go,har_loader.goandendpoints.goare the CLI-side factories.
Implementation Details
Loading and precedence
Load(args) applies settings in three layers:
- Struct defaults:
Method=GET,Concurrency=1,Timeout=30s,GracefulShutdown=5s,Arrival=uniform. - Config file: read with
viper.SetConfigFileandReadInConfig, so the format comes from the file extension.AllSettings()is then walked by hand. - 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:
CRANKFIRE_AUTH_CLIENT_SECRET,CRANKFIRE_AUTH_PASSWORDandCRANKFIRE_AUTH_STATIC_TOKEN. These are used only when anauth:block exists and the corresponding field is empty.OTEL_SERVICE_NAME.CRANKFIRE_DATA_DIR, read by the store.
Libraries read some more:
HTTP_PROXY,HTTPS_PROXYandNO_PROXY, throughhttp.ProxyFromEnvironment, for HTTP (httpclient/client.go) and the WebSocket dialer (websocket/websocket.go).- The OTLP exporters and batch span processor read the standard
OTEL_EXPORTER_OTLP_*andOTEL_BSP_*variables (OTel SDK behaviour;WithEndpointoverrides the endpoint variable).
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:
- the target (not required with HAR, or when every endpoint has a
url); - non-negative numbers;
bodyandbody_fileset together, anddashboardandjson_outputset together (both are errors);- the arrival model and load patterns;
- endpoints: weight of at least 1, case-insensitive unique names, extractors that have a valid identifier as
varand exactly one ofjsonpathorregex; - the auth type and its required fields;
- the feeder type;
- the protocol and its timeouts, and the gRPC service and method.
grpc.proto_fileis not required here; a missing file fails every request at run time (internal/cli/grpc_requester.go:185-188).
It writes warnings to stderr for:
- rate above 1000 and concurrency above 500;
- the legacy password grant;
- static OIDC tokens;
grpc.insecure.
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:
feeder.Next(ctx), if a feeder is configured.- Get the variable store from
variables.FromContext(ctx). - Apply placeholders to the URL.
- Apply placeholders to the body, buffering it first, if it contains placeholders.
- Apply placeholders to header values (not keys).
- Have the auth provider set
Authorization: Bearer .... This overwrites any user-supplied value.
NewClient(timeout) builds the shared transport with:
ProxyFromEnvironment;- a 30 s dial timeout and keepalive;
- HTTP/2 attempted;
- 256 idle connections in total and 32 per host;
- a 90 s idle timeout and a 10 s TLS handshake timeout.
Redirects are followed using Go’s defaults.
Endpoints
internal/cli/endpoints.go builds one RequestBuilder per endpoint:
- Settings: method, headers and body are merged from global and endpoint values, with endpoint values winning.
- URL: an endpoint
urlis used as is. Otherwise the global target is resolved against the endpoint’spathwithurl.ResolveReference, and percent-encoded{{ }}is restored to braces. - Weight: defaults to 1.
- Selection: a cumulative-weight random draw under a mutex.
- Name: the endpoint name, or the resolved URL when no name is given. It is used as the metrics key.
Placeholders vs. templates
placeholders.Apply handles the request templates. Its pattern is {{key}} or {{key|default}}, matched by the regex \{\{([^}|]+)(?:\|([^}]*))?\}\}. Keys are not trimmed.
- With a variable store: the lookup order is store → feeder record → default. HTTP always runs this way.
- Without a store: only exact
{{key}}from the feeder record is replaced. WebSocket, SSE and gRPC run this way. - Values are inserted as is, with no URL or JSON escaping. A feeder value
red shoesin a query string produces an invalid request line. - An unmatched placeholder becomes
""on the store path (HTTP), but is left unchanged on the no-store path (WebSocket, SSE, gRPC). The store path is meant to keepmatchwhen there is no|default. In practice it never does:FindStringSubmatchalways returns three elements because the default group is optional, solen(parts) > 2is always true (internal/placeholders/placeholders.go).
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:
- Status below 400: all extractors run.
- Status 400 or above: only extractors with
on_error: truerun. - Body limit: only the first 1 MB of the body is read.
The two extractor types work as follows:
- JSONPath uses gjson. A leading
$.is stripped, and$alone means@this. Non-string results are returned as raw JSON. - Regex returns the first capture group, or the whole match if the pattern has no groups. The pattern is compiled on every call.
When an extraction fails, a warning is logged to stderr and the variable is set to "".
Feeders
Recordis amap[string]string.- The CSV feeder reads its header row, skips leading spaces, and rejects a file with no data rows.
- The JSON feeder requires an array of objects. It decodes with
UseNumberand converts each value with%v. - Both feeders hand out records round-robin under a mutex and wrap around forever.
- The CLI wraps the feeder in
sharedFeeder, which copies each record.
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:
- Request: it POSTs a form to
token_url, sending the client ID and secret with HTTP Basic auth and joining scopes with spaces. The token request has a 30 s timeout. - Cache lifetime:
expires_in(1 h if it is missing) minusmin(refresh_before_expiry, lifetime/2). The CLI default forrefresh_before_expiryis 30 s. - Refresh: tokens are fetched on the first request and again when the cached one expires. Concurrent callers share a single in-flight fetch through a
sync.Cond. There is no background refresh and norefresh_tokenflow.
HAR conversion
har.Parse reads HAR 1.2 data. Convert turns entries into endpoints using these options:
- Defaults:
ExcludeStaticandIncludeHeadersare on. - Static assets: dropped by path suffix (
.js,.css, images, fonts,.map). - Headers dropped: hop-by-hop headers,
host,content-lengthand:pseudoheaders.CookieandAuthorizationare kept. - Filters: the CLI parses
host:a,b;method:GET,POST. Host matching is exact and includes the port. - Endpoint fields:
URLis the full recorded URL (sopathis never used to resolve it).NameandPathare the URL path,Methodis copied verbatim,Bodycomes frompostData.text, andWeightis 1 (internal/har/converter.go:98-121). - Like all endpoints, HAR endpoints apply only to the HTTP protocol (
internal/cli/build.go:119-171).
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 |
- Other combinations parse but fail at evaluation time.
<=,>=and==use an epsilon of 1e-9.<and>are exact (threshold.go:257-266).- Despite the
http_names, thresholds apply to every protocol.
Tracing
Init returns a no-op provider unless tracing.endpoint is set. When tracing is enabled it sets up:
- Exporter: OTLP over gRPC (the default) or HTTP, with an optional insecure connection.
- Resource:
service.namecomes from the config, thenOTEL_SERVICE_NAME, thencrankfire. - Processing: a batch span processor.
- Sampler:
ParentBasedwrapping one of three samplers:AlwaysSampleat rate 1,TraceIDRatioBasedbetween 0 and 1, andNeverSampleat 0. - Propagators: TraceContext and Baggage, registered globally.
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
- Internal:
configis imported by most packages.httpclientdepends onplaceholders,variablesandconfig.thresholddepends onmetrics. - External: viper, cobra (as the flag container and help printer, with no subcommand tree), pflag, yaml.v3, gjson, and the OpenTelemetry SDK with its OTLP exporters.
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
internal/config:config_test.go,loader_test.goandextractors_test.gocover validation, aliases and precedence.internal/httpclient:client_test.goandbody_reader_test.go.- Each supporting package (
placeholders,feeder,extractor,auth,har,threshold,tracing,tagfilter,template) has a*_test.go.authaddsoauth2_cache_test.goandoauth2_security_test.go. internal/cli:features_matrix_auth_test.gocovers auth.features_matrix_feeders_test.gocovers feeders.features_matrix_thresholds_test.gocovers thresholds.har_integration_test.gocovers HAR import.samples_test.goparses the shipped sample configs.
Known Issues & Improvement Opportunities
- Flag defaults only apply when the flag is passed.
applyFlagOverridescopies a flag only whenfs.Changed, andLoadseeds only five defaults (internal/config/loader.go:63-71,flags.go).- Effective defaults are therefore 0 for
ws-receive-timeout,sse-read-timeout,grpc-timeoutandtracing-sample-rate, even though--helpshows 10s, 30s, 30s and 1.0.
- Tracing samples nothing by default.
- Because of the previous issue, setting only
--tracing-endpoint(ortracing.endpointwithoutsample_rate) givesSampleRate=0, which meansNeverSample(internal/tracing/provider.go:73-78). - Users must set
sample_rateexplicitly.
- Because of the previous issue, setting only
OTEL_EXPORTER_OTLP_ENDPOINTis never used.- The fallback in
Init(provider.go:47-52) is unreachable, becausecfg.Enabled()already returned when the endpoint was empty (provider.go:34).
- The fallback in
- CSV parsing of list flags.
--header,--thresholdand--ws-messagesare pflagStringSliceflags (flags.go:31,60,80), which parse each value as CSV. A value is split on commas, and a value that contains a double quote is rejected (bare " in non-quoted-field) unless the whole value is CSV-quoted. So--ws-messages '{"type":"ping"}'fails at flag parsing. - Chaining is HTTP-only.
- WebSocket, SSE and gRPC call
placeholders.Applywithout a store, so extracted variables and{{k|default}}do nothing there.
- WebSocket, SSE and gRPC call
- A failed extraction overrides defaults and feeder values. It stores
"", which then takes precedence over the feeder record and over|default. - Misleading feeder error and dead code.
RequestBuilder.Buildwraps every feeder error asfeeder exhausted: ...(client.go:174).feeder.ErrExhaustedis never returned. - The
meanaggregate is rejected.isValidAggregaterefusesmean, so its evaluation branch is unreachable (threshold.go:174,216). - Tag filter spacing. Normalization breaks on two or more spaces on either side of a comma:
"a ,b"and"a, b"both become an empty-token error (internal/tagfilter/parser.go:26-28). - Relative paths resolve against the CWD. Paths are not resolved relative to the config file, which surprises users who run
--config dir/x.yamlfrom elsewhere. - No auth flags. Auth can only be configured in a file.
- Validation is skipped outside the one-shot CLI.
BuildRunnernever callsValidate, so sessions run from the TUI,set runor the daemon can carry invalid values thatcrankfire --configwould reject. Sessionconfig.thresholdsare also never evaluated on those paths. - No escaping of placeholder values. Values are inserted verbatim into URLs, headers and JSON bodies (
internal/placeholders/placeholders.go,httpclient/client.go:183).