jotaro

package module
v0.1.3 Latest Latest
Warning

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

Go to latest
Published: Nov 16, 2026 License: MIT Imports: 28 Imported by: 0

README

jotaro

English | 日本語

CI Go Reference

A Go library for load-testing HTTP servers with scenarios (a flow such as login → list → order). Results can be written to the console, JSON or HTML, and the CLI can check them against thresholds.

  • Scenarios are plain Go code (if and variables just work)
  • Two ways to apply load
    • Closed: a fixed number of users repeat the scenario (Users), or the number of users changes stage by stage (UserStages)
    • Open: scenarios start at a fixed rate (Rate / Ramp / Stages). Arrivals keep their pace even when the server slows down, and latency is measured from the scheduled start time (Coordinated Omission correction)
  • Measures per-step latency (p50 / p90 / p95 / p99 / max), error breakdown, throughput, TTFB, DNS / TCP / TLS time, and connection reuse rate
  • Also records a per-second time series and the health of the load generator itself (CPU, goroutine count)

For the design rationale see DESIGN.md; for the result format and the threshold spec see docs/result.md.

Status: v0.x. We do not change the API without a reason, and we aim to keep existing code working, in the spirit of the Go 1 compatibility promise. The exception is fixing an existing bug, which can change behavior that code relied on. Such changes are listed in CHANGELOG.md.

Try it

Runnable samples that start their own mock server are in examples/.

go run ./examples/checkout       # a short flow: login → product list → order
go run ./examples/marketplace    # a deeper scenario with five kinds of visitors

Use as a library

go get github.com/RIRUa/jotaro

Requires Go 1.25 or later.

1. Write a scenario
var checkout = jotaro.NewScenario("checkout", func(ctx context.Context, u *jotaro.User) error {
	var login struct {
		Token string `json:"token"`
	}
	if err := u.Step("login", func(s *jotaro.Step) error {
		return s.Post("/login").JSON(creds).Do().Decode(&login)
	}); err != nil {
		return err // return err to stop; ignore it to continue
	}

	u.Think(50 * time.Millisecond) // waiting time; not counted in latency

	return u.Step("order", func(s *jotaro.Step) error {
		return s.Post("/orders").Bearer(login.Token).
			JSON(map[string]int{"item": 1}).
			Do().ExpectStatus(http.StatusCreated)
	})
})
  • Step is the unit of measurement. Results are aggregated per step
  • Build a request with Get / Post / Put / Patch / Delete and send it with Do()
  • The following can be chained onto a request before Do()
    • Headers: Header(k, v) / Headers(map) / Bearer(token) / Basic(user, pass)
    • Query: Query(k, v) / Queries(url.Values) (values are escaped)
    • Body: JSON(v) / Form(url.Values) / Body(v) ([]byte / string / io.Reader are sent as is, url.Values as a form, anything else as JSON. Set Content-Type with Header when you need it)
  • After Do(), chain Decode(&v) (read JSON) or one of the Expect* checks
    • ExpectStatus(code) / ExpectStatusIn(codes...): the status code
    • ExpectHeader(key, want) / ExpectBodyContains(substr): a header value / a substring of the body
    • ExpectJSON(path, want): the value at a dot path such as data.items.0.id. Response.JSON(path) returns that value so you can use it in the next request without defining a struct
    • A failed check returns an error and the step is recorded as expect_mismatch. It is not counted as a request error (see error_rate under Threshold syntax)
  • Think is think time. Scenario time is reported both without and with Think
  • Even if a step fails, the iteration counts as successful as long as the scenario function returns nil. Step failures show up in the per-step stats
  • Cookies are fresh for each iteration. The connection pool is shared by all users

Use a Feeder to hand out different data (accounts, etc.) to each user. LoadCSV reads one from a CSV.

var accounts = jotaro.NewFeeder([]map[string]string{
	{"user": "alice"}, {"user": "bob"},
}, jotaro.Circular)

creds, ok := accounts.Next()
2. Choose the load and run
rep, err := jotaro.Run(ctx, jotaro.Plan{
	Scenario: checkout,
	BaseURL:  "http://localhost:8080",
	Duration: time.Minute,
	Users:    20, // closed model. For the open model, use Arrival instead of Users
})
if err != nil && !errors.Is(err, jotaro.ErrAborted) {
	log.Fatal(err) // an invalid Plan (rep is nil), or a failure to write Raw (rep is still returned)
}

When AbortOn (below) stops a run, Run returns the partial report and an error that wraps jotaro.ErrAborted, so use the report even when err is not nil.

Specify exactly one of Users, UserStages and Arrival.

Setting Meaning
Users: 20 20 users repeat the scenario for Duration
UserStages: []jotaro.UserStage{{Target: 100, For: 30*time.Second}, {Target: 100, For: time.Minute}, {Target: 0, For: 10*time.Second}} Change the number of users stage by stage: ramp up to 100 over 30 seconds, hold for 1 minute, ramp down to 0 over 10 seconds (the first stage starts from StartUsers, 0 by default)
Arrival: jotaro.Rate(50, time.Second) Start 50 scenarios per second
Arrival: jotaro.Ramp(0, 100, time.Second, 10*time.Second) Increase from 0 to 100 per second over 10 seconds
Arrival: jotaro.Stages(...) Switch Arrival stage by stage (ramp up → hold → ramp down, etc.)

To run several flows in one plan, set Scenarios instead of Scenario: Scenarios: []jotaro.Weighted{{Scenario: browse, Weight: 7}, {Scenario: checkout, Weight: 3}}. Each iteration (closed) or arrival (open) picks one of them at random in proportion to the weights, and the report separates the results by scenario name (so the names must differ).

With UserStages, a user that is stopped by a lower target finishes the iteration it is running and then waits; it is not interrupted. Users keep their User.ID and iteration count when they are started again. The number of concurrent iterations over time is Series.Concurrency in the report, so you can check the load shape there.

To repeat a sequence of stages (for example three waves), use jotaro.RepeatUserStages(3, stage1, stage2, ...); it returns the stages repeated 3 times and can be joined with other stages by append. Each round starts from the Target the previous round ended at.

You can also set MaxUsers (the cap on concurrency in the open model; an arrival that comes in while the cap is reached is not run and not waited for, but counted as dropped, and the text report prints a warning: line when that happened), Timeout (the limit for a single request), Grace (how long to wait for running iterations after Duration), Raw (where to write raw data), Progress (an io.Writer, such as os.Stderr, that gets one line per second while the run is in progress, e.g. 12s/60s rps=480 p95=38ms err=0.2%), and MetricsAddr (for example ":9090": serve the state of the run so far at /metrics in the Prometheus text format, so Grafana and similar tools can chart it during the run; it needs no extra dependency and stops when Run returns).

To stop a run as soon as the server is clearly broken, set AbortOn, for example AbortOn: []jotaro.AbortRule{{When: "http_5xx_rate>50%", For: 5 * time.Second}}. When uses the threshold syntax but describes the state to stop at; it is checked every second against the whole run so far, and For is how long it must hold. Running iterations get Grace to finish, then Run returns the partial report together with an error that satisfies errors.Is(err, jotaro.ErrAborted).

3. Output the results
rep.Write(os.Stdout, report.FormatText) // FormatText / FormatJSON / FormatHTML

You can also judge the results against thresholds.

th, _ := report.ParseThreshold("p95<200ms")
checks := rep.Check(th)
checks.Print(os.Stdout)
if !checks.Passed() {
	os.Exit(1)
}
4. Lay out the project

A layout that works well for a load test that lives next to the service it tests:

myservice/
├─ go.mod
└─ loadtest/
   ├─ main.go          # flags, Plan, Run, save the result, Check
   ├─ checkout.go      # scenario (package main)
   ├─ thresholds.go    # var thresholds = []string{"p95<200ms", ...}
   ├─ testdata/        # CSV for Feeder; no secrets
   └─ results/         # git-ignored: result.json, report.html, raw.jsonl

When the scenarios grow in number or you run them against several environments, move them into a module of their own.

CLI

A CLI for processing and judging saved results afterwards.

go install github.com/RIRUa/jotaro/cmd/jotaro@latest

Prebuilt binaries (Linux / macOS / Windows) are attached to each GitHub Release. jotaro version prints the version (please include it in bug reports).

Put options before the file names.

# Build an HTML report from a JSON result (default format is html)
jotaro report -o result.html result.json

# Merge several results (e.g. from different machines) into one (default format is json)
jotaro merge -o merged.json a.json b.json

# Check the thresholds. Exit code 1 if any of them is not met
jotaro check -t 'p95<200ms' -t 'error_rate<1%' -t 'p99{step=login}<100ms' result.json

# Compare with a previous run; fail if any p95 got more than 10% worse
jotaro compare -max-p95-regression 10 base.json new.json

# Convert raw data (Plan.Raw output) for other tools
jotaro export -format vegeta -o results.json raw.jsonl   # then: vegeta report -type=json results.json
jotaro export -format csv -o series.csv raw.jsonl        # per-second counts and percentiles
  • Pass - as the input to read from standard input (report / merge / check / compare / export)
  • With -raw, the input is read as raw JSON Lines data (the output of Plan.Raw) and re-aggregated (report / merge / check / compare). export always reads raw data. Passing non-raw data to -raw or export is an error
  • Choose the output format of report / merge with -format text|json|html, and that of export with -format vegeta|csv
  • compare prints the differences of rps, p50 / p95 / p99 and error rate (overall and per step). With -max-p95-regression <percent> it exits with code 1 when a p95 got worse by more than that
Threshold syntax

metric[{scenario=name,step=name}] operator value. Operators are < <= > >=.

Metric Meaning
min mean p50 p90 p95 p99 max Request latency (200ms, 1.5s)
The above prefixed with corrected_ ttfb_ dns_ connect_ tls_ After CO correction / TTFB / DNS / TCP / TLS time
error_rate Share of requests that ended in a transport-level error: timeout, connection refused, DNS failure and so on (1% or 0.01). A failed Expect* check is not included
http_4xx_rate http_5xx_rate Share of HTTP 4xx / 5xx
iteration_fail_rate Share of failed iterations
iteration_min … iteration_max, iteration_active_min … iteration_active_max Latency of a whole scenario iteration, with / without Think time (filter with {scenario=...})
requests rps dropped Number of requests / requests per second / number of dropped arrivals

When the target or the data is missing, the threshold counts as not met, so that a mistyped step name cannot pass silently. See chapter 5 of docs/result.md for details.

Two things to know when you choose thresholds:

  • error_rate is the share of requests that ended in a transport-level error (timeout, connection refused, DNS failure and so on). A failed Expect* check is not counted as a request error: it fails the step with expect_mismatch, which is listed in the step's errors, and it reaches iteration_fail_rate when the scenario returns that error. To fail a run on wrong responses, return the step's error from the scenario (as in the example above) and set iteration_fail_rate<1%; use http_5xx_rate / http_4xx_rate for HTTP error statuses.
  • In the open model, when MaxUsers is full an arrival is dropped instead of waited for, and a dropped arrival leaves no latency sample. When you use corrected_* thresholds, add dropped<1 so that a run that dropped arrivals cannot pass on the latencies of the arrivals that did run.

MCP server (scenario authoring and result checks)

jotaro mcp starts an MCP server that helps an AI assistant write scenarios and read saved results. It talks over stdio and never runs a scenario: it only checks code and reads result files.

claude mcp add jotaro -- jotaro mcp     # Claude Code; other clients take the same command
Kind Name Purpose
Resource jotaro://guide How to write a scenario: skeleton, API overview, load models, checklist
Resource jotaro://thresholds Threshold syntax and metrics
Resource jotaro://result How to save a result and read it: structure, what each number and error kind means, what to check first
Prompt write_scenario Write a scenario for a described flow, then check it
Tool check_scenario Check a scenario file: Go syntax, jotaro lint (exactly one of Users / UserStages / Arrival, unchecked responses, duplicate step names, ...) and a type check by compiling. Pass dir (a module that requires jotaro) to check against its jotaro version; without it a temporary module with the jotaro version of the running jotaro binary (the latest one for a development build) is used, which needs network access
Tool validate_threshold Parse a threshold such as p99{step=login}<100ms
Tool summarize_result Summarize a saved result file: throughput, error rate, latency per step, dropped arrivals, the worst second, and warnings such as a saturated load generator. Much smaller than the file itself, which holds histograms and a per-second series
Tool check_result Judge a saved result file against thresholds, like jotaro check: pass or fail per threshold with the measured value. raw: true reads raw JSON Lines data

Packages

Package Contents
jotaro Scenarios (Scenario / User / Step) and load models (Plan / Run / Rate / Ramp / Stages / UserStages). The entry point for users
report Aggregation of results (Report), output (text / JSON / HTML), merging, comparing, conversion for other tools, and threshold checks
record Per-request records and reading/writing raw data (JSON Lines)
cmd/jotaro CLI (report / merge / check / compare / export / mcp / version)

Caveats

  • Only HTTP can be measured
  • Without Plan.Raw, percentiles such as p50 are approximations within 1% relative error (records are folded into histograms as they arrive, so memory does not grow with the run). Count, min, max and mean stay exact. With Plan.Raw each record is also written to it as it arrives (still constant memory); to get exact percentiles, re-aggregate the file with jotaro report -raw
  • There is no statistical comparison (whether two results differ significantly). check works by setting criteria and judging pass or fail, and compare shows the differences between two results with a gate on the p95 regression only

License

MIT

Documentation

Overview

Package jotaro is a library for load-testing HTTP servers with scenarios: a flow such as login → list → order, written as plain Go code.

This package is the entry point. It handles scenarios (Scenario / User / Step) and how load is applied (Plan / Run). Load is applied either with a fixed number of users (Plan.Users), with a number of users that changes over time (Plan.UserStages), or by arrival rate (Plan.Arrival with Rate / Ramp / Stages). Plan.Scenarios runs a weighted mix of scenarios instead of a single one. The result is returned as a report.Report. Writing it to the console, JSON or HTML, and checking it against thresholds, is done by the report package; raw per-request records are handled by the record package.

sc := jotaro.NewScenario("checkout", func(ctx context.Context, u *jotaro.User) error {
	return u.Step("login", func(s *jotaro.Step) error {
		return s.Post("/login").JSON(creds).Do().ExpectStatus(200)
	})
})
rep, err := jotaro.Run(ctx, jotaro.Plan{Scenario: sc, BaseURL: url, Users: 20, Duration: time.Minute})
rep.Write(os.Stdout, report.FormatText)
Example

A scenario is plain Go code. Run it with a Plan, here against a local test server.

package main

import (
	"context"
	"fmt"
	"net/http"
	"net/http/httptest"
	"time"

	"github.com/RIRUa/jotaro"
)

func main() {
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		switch r.URL.Path {
		case "/login":
			fmt.Fprint(w, `{"token":"secret"}`)
		default:
			w.WriteHeader(http.StatusCreated)
		}
	}))
	defer srv.Close()

	checkout := jotaro.NewScenario("checkout", func(ctx context.Context, u *jotaro.User) error {
		var login struct {
			Token string `json:"token"`
		}
		if err := u.Step("login", func(s *jotaro.Step) error {
			return s.Post("/login").JSON(map[string]string{"user": "alice"}).Do().Decode(&login)
		}); err != nil {
			return err // return err to stop; ignore it to continue
		}

		u.Think(10 * time.Millisecond) // waiting time; not counted in latency

		return u.Step("order", func(s *jotaro.Step) error {
			return s.Post("/orders").Bearer(login.Token).
				JSON(map[string]int{"item": 1}).
				Do().ExpectStatus(http.StatusCreated)
		})
	})

	rep, err := jotaro.Run(context.Background(), jotaro.Plan{
		Scenario: checkout,
		BaseURL:  srv.URL,
		Duration: 200 * time.Millisecond,
		Users:    2,
	})
	if err != nil {
		fmt.Println("error:", err)
		return
	}
	fmt.Println("ran:", rep.Requests.Count > 0)
	fmt.Println("errors:", len(rep.Requests.Errors))
}
Output:
ran: true
errors: 0

Index

Examples

Constants

This section is empty.

Variables

View Source
var ErrAborted = errors.New("jotaro: run aborted")

ErrAborted is wrapped by the error Run returns when Plan.AbortOn stopped the run early. The report returned together with it covers the run up to the abort. Test for it with errors.Is.

Functions

func LoadCSV

func LoadCSV(r io.Reader) ([]map[string]string, error)

LoadCSV reads a CSV whose first line is the header into rows keyed by column name.

Example

LoadCSV reads rows keyed by the column names of the header line.

package main

import (
	"fmt"
	"strings"

	"github.com/RIRUa/jotaro"
)

func main() {
	rows, err := jotaro.LoadCSV(strings.NewReader("user,password\nalice,a1\nbob,b2\n"))
	if err != nil {
		fmt.Println(err)
		return
	}
	feeder := jotaro.NewFeeder(rows, jotaro.Once)
	row, _ := feeder.Next()
	fmt.Println(feeder.Len(), row["user"], row["password"])
}
Output:
2 alice a1

func Run

func Run(ctx context.Context, p Plan) (*report.Report, error)

Run applies load according to the Plan, then aggregates and returns the result.

Flow of a run:

  1. validate the Plan, and clone the default Transport so connections are not shared with other code
  2. start the health sampler, then run the closed (Users or UserStages) or open (Arrival) loop until Duration ends
  3. wait up to Grace for running iterations, then cancel them
  4. build the report. Records are folded into histograms as they arrive (percentiles within 1% relative error, memory independent of the run length). With Plan.Raw each record is also written to it at once, and the stream is finished (health and final run info) when the run ends

When ctx is done, everything stops at once, including running iterations, and the results so far are returned. Report.Elapsed is the real time until all users have stopped.

Types

type AbortRule added in v0.1.3

type AbortRule struct {
	// When is the condition, such as "error_rate>50%".
	When string
	// For is how long When must hold without a break before the run is aborted. 0 aborts at the first
	// evaluation where it holds. A value of a few seconds keeps one early failure from stopping a run
	// whose statistics have not settled yet.
	For time.Duration
}

AbortRule is one condition of Plan.AbortOn: stop the run as soon as When holds.

When uses the threshold syntax of report.ParseThreshold, but it describes the state to stop at rather than the state to accept. So "http_5xx_rate>50%" aborts once more than half of the requests got a 5xx response:

AbortOn: []jotaro.AbortRule{
	{When: "http_5xx_rate>50%", For: 5 * time.Second},
	{When: "error_rate>50%", For: 5 * time.Second},
	{When: "p95>2s", For: 10 * time.Second},
},

Mind which metric sees the failure: error_rate is the share of requests that ended in a transport-level error (timeout, connection refused, DNS failure and so on). A failed Expect* check is not a request error: it fails the step with expect_mismatch and reaches iteration_fail_rate when the scenario returns that error. An HTTP error status is counted by http_4xx_rate / http_5xx_rate.

The condition is evaluated every second against the whole run so far (not a sliding window), the same way Report.Check reads a finished report. Percentiles are therefore the approximate ones of a run without Plan.Raw. Nothing counts as holding while there is no data yet (for example before the first request has finished, or before a step named in a {step=...} filter has run).

type Arrival

type Arrival interface {
	// contains filtered or unexported methods
}

Arrival is how scenarios arrive in the open model. Arrival times are decided independently of how long a scenario takes.

func Ramp

func Ramp(from, to int, per, over time.Duration) Arrival

Ramp changes the arrival rate linearly from from to to over over. The rate is a count per per; after over has passed it stays at to (if to is 0, arrivals stop there). For example, Ramp(0, 50, time.Second, 30*time.Second) raises the rate from 0 to 50 per second over 30 seconds.

The length of the whole run is set by Plan.Duration. If over is longer than Duration, to is never reached.

func Rate

func Rate(n int, per time.Duration) Arrival

Rate starts scenarios at a rate of n per per. For example, Rate(10, time.Second) is 10 per second.

func Stages

func Stages(stages ...Stage) Arrival

Stages runs several stages in order. The Arrival of each stage runs with the start of that stage as 0 (a Ramp's slope also starts there). For example, ramp up to 50/s over 30 seconds, hold for 60 seconds, then ramp down to 0 over 10 seconds:

Stages(
	Stage{Ramp(0, 50, time.Second, 30*time.Second), 30 * time.Second},
	Stage{Rate(50, time.Second), 60 * time.Second},
	Stage{Ramp(50, 0, time.Second, 10*time.Second), 10 * time.Second},
)

Arrivals stop when all stages are over. The length of the whole run is set by Plan.Duration, so make it match the sum of the For of every stage.

type ExpectError

type ExpectError struct {
	// Want is the status code that was expected. It is 0 for non-status checks.
	Want int
	// Got is the status code that came back.
	Got int
	// Detail describes a non-status mismatch (header, body or JSON value).
	// It is empty for ExpectStatus.
	Detail string
}

ExpectError reports that a response did not match what an Expect* check expected. It is classified as record.ErrExpect (expect_mismatch).

func (*ExpectError) Error

func (e *ExpectError) Error() string

Error implements the error interface.

type FeedMode

type FeedMode int

FeedMode is the order in which a Feeder hands out rows.

const (
	// Circular hands out rows from the first one and wraps around after the last.
	Circular FeedMode = iota
	// Random picks a row at random each time. The same row can be picked twice in a row.
	Random
	// Once hands out rows from the first one and returns false once they are used up.
	// It is meant for data such as accounts that can be used only once.
	Once
)

type Feeder

type Feeder[T any] struct {
	// contains filtered or unexported fields
}

Feeder hands out different data (accounts, input values, ...) to each user. Next may be called from all users at the same time.

Example

A Feeder hands out different data to each user.

package main

import (
	"fmt"

	"github.com/RIRUa/jotaro"
)

func main() {
	accounts := jotaro.NewFeeder([]map[string]string{
		{"user": "alice"}, {"user": "bob"},
	}, jotaro.Circular)

	for range 3 {
		row, _ := accounts.Next()
		fmt.Println(row["user"])
	}
}
Output:
alice
bob
alice
Example (Once)

With Once, rows are handed out once and then Next returns false.

package main

import (
	"fmt"

	"github.com/RIRUa/jotaro"
)

func main() {
	tokens := jotaro.NewFeeder([]string{"t1", "t2"}, jotaro.Once)

	for {
		tok, ok := tokens.Next()
		if !ok {
			break
		}
		fmt.Println(tok)
	}
}
Output:
t1
t2

func NewFeeder

func NewFeeder[T any](rows []T, mode FeedMode) *Feeder[T]

NewFeeder creates a Feeder that hands out rows in the order given by mode.

func (*Feeder[T]) Len

func (f *Feeder[T]) Len() int

Len returns the number of rows.

func (*Feeder[T]) Next

func (f *Feeder[T]) Next() (T, bool)

Next returns the next row. It returns false when there are no rows or when Once has run out.

type Plan

type Plan struct {
	// Scenario is the flow every virtual user runs. Exactly one of Scenario and Scenarios must be set.
	Scenario *Scenario
	// Scenarios is a weighted mix of flows, for example 70% browse and 30% checkout. It cannot be set together
	// with Scenario. Every iteration (closed model) or arrival (open model) picks one scenario at random with
	// probability Weight divided by the sum of the weights. The report and thresholds already separate the
	// results by scenario name, so the scenarios of a mix need distinct names.
	Scenarios []Weighted
	// BaseURL is prepended to the relative paths of requests (for example "http://localhost:8080").
	BaseURL string

	// Users is the number of virtual users running at the same time.
	Users int
	// UserStages changes the number of users over time in the closed model. It cannot be set together with Users or Arrival.
	//
	// Every user keeps its ID (User.ID counts from 0) and its iteration count for the whole run, so a user
	// that is stopped by a smaller target and started again by a larger one carries on where it left off.
	// When the target goes down, the users with the highest IDs stop: each one finishes the iteration it is
	// running (it is not interrupted) and then waits. So the active-user count of the report (Series.Concurrency)
	// can be above the target for a while. After the last stage the number of users stays at its Target until Duration.
	UserStages []UserStage
	// StartUsers is how many users are already running when the first stage of UserStages begins, so that
	// the load does not have to ramp up from 0. 0 means none. It can only be set together with UserStages.
	StartUsers int
	// Arrival is how scenarios arrive (e.g. Rate(10, time.Second)). It cannot be set together with Users or UserStages.
	Arrival Arrival
	// MaxUsers is the cap on concurrency with Arrival. 0 means 1000.
	// Arrivals that come in while the cap is reached are not run and are counted as dropped.
	MaxUsers int
	// After Duration has passed, no new iterations are started.
	Duration time.Duration

	// Timeout is the limit for a single request. 0 means 30 seconds.
	Timeout time.Duration
	// Grace is how long to wait for running iterations to finish after Duration.
	// Those that exceed it are aborted and recorded as record.ErrCanceled. 0 means 30 seconds.
	Grace time.Duration

	// If Raw is not nil, the raw data is written to it as JSON Lines while the run is in progress, one line per
	// record as it arrives (record.RawWriter), so memory stays constant however many requests there are.
	// Even if writing fails, the aggregated Report is returned (together with an error).
	//
	// The Report that Run returns is aggregated incrementally, as without Raw, so its percentiles are within
	// 1% relative error. For exact percentiles, read the raw data back (record.ReadRaw, report.FromRaw,
	// or `jotaro report -raw`).
	Raw io.Writer

	// If Progress is not nil, one line is written to it every second while the run is in progress,
	// for example "12s/60s rps=480 p95=38ms err=0.2%" (elapsed/Duration, throughput of the last second,
	// and p95 and error rate over the run so far). Pass os.Stderr to watch a long run.
	// The p95 is an approximation within 1% relative error. Nothing is written after Run returns,
	// and write errors are ignored. It works together with Raw.
	Progress io.Writer

	// If MetricsAddr is not empty, Run serves the state of the run so far at http://<MetricsAddr>/metrics in the
	// Prometheus text format (for example ":9090"), so Grafana and similar tools can chart it while the run is in
	// progress. It has the request, response class and error counts, the throughput and the latency quantiles of the
	// whole run so far (within 1% relative error). The server stops when Run returns. If the address cannot be
	// listened on, Run fails before sending any request.
	MetricsAddr string

	// AbortOn stops the run early when any of its conditions holds, for example
	// {When: "error_rate>50%", For: 5 * time.Second}. A broken server is then not hit for the whole Duration.
	// See AbortRule for the syntax and how the conditions are evaluated.
	//
	// On abort no new iterations are started and the running ones get Grace, counted from the moment of the abort,
	// to finish (the rest is cancelled and recorded as record.ErrCanceled), exactly as at the end of Duration.
	// Run then returns the report of the run up to that point (and writes Plan.Raw) together with an error
	// that wraps ErrAborted. If Progress is set, a line saying why is written to it.
	AbortOn []AbortRule
}

Plan describes how load is applied.

Specify exactly one of Users, UserStages (closed model) and Arrival (open model).

  • Users: a fixed number of users repeat the scenario until Duration has passed.
  • UserStages: like Users, but the number of users changes over time (ramp up, hold, ramp down).
  • Arrival: scenarios start at a fixed rate, regardless of how long a scenario takes.
Example (AbortOn)

AbortOn stops a run early when a condition holds, so a broken server is not hit for the whole Duration. Run then returns the report up to that point together with an error that wraps ErrAborted.

package main

import (
	"context"
	"errors"
	"fmt"
	"net/http"
	"net/http/httptest"
	"time"

	"github.com/RIRUa/jotaro"
)

func main() {
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(http.StatusServiceUnavailable) // a broken server
	}))
	defer srv.Close()

	ping := jotaro.NewScenario("ping", func(ctx context.Context, u *jotaro.User) error {
		return u.Step("ping", func(s *jotaro.Step) error {
			return s.Get("/").Do().ExpectStatus(http.StatusOK)
		})
	})

	rep, err := jotaro.Run(context.Background(), jotaro.Plan{
		Scenario: ping,
		BaseURL:  srv.URL,
		Duration: time.Minute,
		Users:    2,
		AbortOn:  []jotaro.AbortRule{{When: "http_5xx_rate>50%"}}, // For: 0 aborts at the first evaluation that holds
	})
	fmt.Println("aborted:", errors.Is(err, jotaro.ErrAborted))
	fmt.Println("report returned:", rep != nil && rep.Requests.Count > 0)
}
Output:
aborted: true
report returned: true
Example (Open)

In the open model, scenarios start at a fixed rate whatever the server does. Stages switches the arrival stage by stage: ramp up, hold, ramp down.

package main

import (
	"time"

	"github.com/RIRUa/jotaro"
)

func main() {
	var scenario *jotaro.Scenario // see the Example above

	plan := jotaro.Plan{
		Scenario: scenario,
		BaseURL:  "http://localhost:8080",
		Duration: 100 * time.Second,
		Arrival: jotaro.Stages(
			jotaro.Stage{Arrival: jotaro.Ramp(0, 50, time.Second, 30*time.Second), For: 30 * time.Second},
			jotaro.Stage{Arrival: jotaro.Rate(50, time.Second), For: 60 * time.Second},
			jotaro.Stage{Arrival: jotaro.Ramp(50, 0, time.Second, 10*time.Second), For: 10 * time.Second},
		),
		MaxUsers: 500, // arrivals beyond this are counted as dropped
	}
	_ = plan // jotaro.Run(ctx, plan)
}
Example (Scenarios)

Scenarios runs a weighted mix of flows in one plan. Every iteration picks one scenario in proportion to its weight, and the report keeps the results apart by scenario name, so the names must differ.

package main

import (
	"context"
	"fmt"
	"net/http"
	"net/http/httptest"
	"sort"
	"time"

	"github.com/RIRUa/jotaro"
)

func main() {
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}))
	defer srv.Close()

	visit := func(name, path string) *jotaro.Scenario {
		return jotaro.NewScenario(name, func(ctx context.Context, u *jotaro.User) error {
			return u.Step("visit", func(s *jotaro.Step) error {
				return s.Get(path).Do().ExpectStatus(http.StatusOK)
			})
		})
	}

	rep, err := jotaro.Run(context.Background(), jotaro.Plan{
		Scenarios: []jotaro.Weighted{
			{Scenario: visit("browse", "/products"), Weight: 1}, // 1 : 1 is 50% each; 70 : 30 would be 70% and 30%
			{Scenario: visit("buy", "/orders"), Weight: 1},
		},
		BaseURL:  srv.URL,
		Duration: 200 * time.Millisecond,
		Users:    2,
	})
	if err != nil {
		fmt.Println("error:", err)
		return
	}
	var names []string
	for _, sc := range rep.Scenarios {
		if sc.Iterations.Count > 0 {
			names = append(names, sc.Name)
		}
	}
	sort.Strings(names)
	fmt.Println("scenarios that ran:", names)
}
Output:
scenarios that ran: [browse buy]
Example (UserStages)

UserStages changes the number of users over time in the closed model, here from 2 users up to 4 and down to 0. StartUsers is how many users are already running when the first stage begins.

package main

import (
	"context"
	"fmt"
	"net/http"
	"net/http/httptest"
	"time"

	"github.com/RIRUa/jotaro"
)

func main() {
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}))
	defer srv.Close()

	ping := jotaro.NewScenario("ping", func(ctx context.Context, u *jotaro.User) error {
		return u.Step("ping", func(s *jotaro.Step) error {
			return s.Get("/").Do().ExpectStatus(http.StatusOK)
		})
	})

	rep, err := jotaro.Run(context.Background(), jotaro.Plan{
		Scenario:   ping,
		BaseURL:    srv.URL,
		StartUsers: 2,
		UserStages: []jotaro.UserStage{
			{Target: 4, For: 100 * time.Millisecond},
			{Target: 4, For: 100 * time.Millisecond},
			{Target: 0, For: 100 * time.Millisecond},
		},
		Duration: 300 * time.Millisecond,
	})
	if err != nil {
		fmt.Println("error:", err)
		return
	}
	fmt.Println("ran:", rep.Requests.Count > 0)
	fmt.Println("open model:", rep.Open)
}
Output:
ran: true
open model: false

type Request

type Request struct {
	// Spec is the data form of the request. It can be edited directly before Do.
	Spec RequestSpec
	// contains filtered or unexported fields
}

Request is a request builder. Send it with Do.

Builder methods return the Request so calls can be chained. A failure while building (for example JSON that cannot be encoded) is stored and returned later by the Response, which keeps the chain free of error checks.

func (*Request) Basic

func (r *Request) Basic(user, pass string) *Request

Basic sets Basic authentication in the Authorization header.

func (*Request) Bearer

func (r *Request) Bearer(token string) *Request

Bearer sets a Bearer token in the Authorization header.

func (*Request) Body

func (r *Request) Body(v any) *Request

Body sets the body according to its type.

[]byte / string  sent as is. Content-Type is not set; add it with Header if you need it
io.Reader        read to the end and sent as is. Content-Type is not set
url.Values       same as Form
anything else    same as JSON (structs, maps, slices, ...)

nil sets nothing. Use JSON when you want to make it explicit that the body is JSON (also when you want to send a string as a JSON string).

func (*Request) Do

func (r *Request) Do() *Response

Do sends the request. A network error is kept in the response and returned by Decode or ExpectStatus.

func (*Request) Form

func (r *Request) Form(v url.Values) *Request

Form sets the body as application/x-www-form-urlencoded.

func (*Request) Header

func (r *Request) Header(key, value string) *Request

Header sets a header.

func (*Request) Headers

func (r *Request) Headers(h map[string]string) *Request

Headers sets several headers at once. An existing key is overwritten.

func (*Request) JSON

func (r *Request) JSON(v any) *Request

JSON sets the body as JSON.

func (*Request) Queries

func (r *Request) Queries(v url.Values) *Request

Queries adds several query parameters at once.

func (*Request) Query

func (r *Request) Query(key, value string) *Request

Query adds a query parameter. Repeating a key gives multiple values. Unlike writing it directly into Path, the value is escaped.

type RequestSpec

type RequestSpec struct {
	Method string
	Path   string
	Query  url.Values // added to the query of Path
	Header http.Header
	Body   []byte
}

RequestSpec describes a request. It is kept as data separate from execution so that it can later be built from YAML and the like.

type Response

type Response struct {
	// Code is the HTTP status code. It is 0 when no response was received.
	Code int
	// Header holds the response headers. It is nil when no response was received.
	Header http.Header
	// Body is the whole body, already read.
	Body []byte
	// contains filtered or unexported fields
}

Response is the result of a single request. HTTP 4xx/5xx are not network errors, so Err stays nil and the status goes into Code.

func (*Response) Decode

func (r *Response) Decode(v any) error

Decode reads the body into v as JSON.

func (*Response) Err

func (r *Response) Err() error

Err returns the network error, if any. It does not look at the HTTP status code.

func (*Response) ExpectBodyContains added in v0.1.3

func (r *Response) ExpectBodyContains(substr string) error

ExpectBodyContains checks that the body contains substr.

func (*Response) ExpectHeader added in v0.1.3

func (r *Response) ExpectHeader(key, want string) error

ExpectHeader checks that the response header key equals want.

func (*Response) ExpectJSON added in v0.1.3

func (r *Response) ExpectJSON(path string, want any) error

ExpectJSON checks that the value at path in the JSON body equals want. Both sides are compared in their JSON form, so ExpectJSON("n", 3) matches {"n": 3}.

Example

ExpectJSON checks the value at a path. A mismatch is an *ExpectError (expect_mismatch), which fails the step.

package main

import (
	"fmt"

	"github.com/RIRUa/jotaro"
)

func main() {
	resp := &jotaro.Response{Code: 200, Body: []byte(`{"status":"accepted","count":2}`)}

	fmt.Println(resp.ExpectJSON("status", "accepted"))
	fmt.Println(resp.ExpectJSON("count", 3))
}
Output:
<nil>
jotaro: unexpected JSON at "count" (want 3, got 2)

func (*Response) ExpectStatus

func (r *Response) ExpectStatus(code int) error

ExpectStatus checks that the status code equals code.

func (*Response) ExpectStatusIn added in v0.1.3

func (r *Response) ExpectStatusIn(codes ...int) error

ExpectStatusIn checks that the status code is one of codes.

func (*Response) JSON added in v0.1.3

func (r *Response) JSON(path string) (any, error)

JSON extracts the value at path from the JSON body. path is dot-separated; object keys are looked up by name and array elements by index, e.g. "data.items.0.id". An empty path returns the whole body. Numbers come back as float64, as with encoding/json.

Example

JSON reads one value from a JSON body by a dot path, without declaring a struct. Object keys are looked up by name and array elements by index. Numbers come back as float64.

package main

import (
	"fmt"

	"github.com/RIRUa/jotaro"
)

func main() {
	resp := &jotaro.Response{Code: 200, Body: []byte(`{"data":{"items":[{"id":7,"name":"tea"}]}}`)}

	id, _ := resp.JSON("data.items.0.id")
	name, _ := resp.JSON("data.items.0.name")
	_, err := resp.JSON("data.items.1.id")
	fmt.Println(id, name)
	fmt.Println(err)
}
Output:
7 tea
jotaro: JSON path "data.items.1.id": bad index "1" (len 1)

type Scenario

type Scenario struct {
	// Name labels the scenario in every record and in the report.
	Name string
	// Fn is the flow itself. Returning an error marks the iteration as failed.
	Fn func(ctx context.Context, u *User) error
}

Scenario is the flow that a virtual user runs once.

func NewScenario

func NewScenario(name string, fn func(ctx context.Context, u *User) error) *Scenario

NewScenario creates a scenario.

type Stage

type Stage struct {
	// Arrival decides when scenarios start within this stage, counted from the stage's own start.
	Arrival Arrival
	// For is how long the stage lasts. Arrivals that would fall at or after For are dropped.
	For time.Duration
}

Stage is one stage of Stages. It keeps Arrival going for For.

type Step

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

Step is the entry point for building requests inside u.Step. Every request built from it is recorded under this step's name.

func (*Step) Delete

func (s *Step) Delete(path string) *Request

Delete builds a DELETE request.

func (*Step) Get

func (s *Step) Get(path string) *Request

Get builds a GET request.

func (*Step) Name

func (s *Step) Name() string

Name returns the step name.

func (*Step) Patch

func (s *Step) Patch(path string) *Request

Patch builds a PATCH request.

func (*Step) Post

func (s *Step) Post(path string) *Request

Post builds a POST request.

func (*Step) Put

func (s *Step) Put(path string) *Request

Put builds a PUT request.

func (*Step) Request

func (s *Step) Request(method, path string) *Request

Request builds a request with an arbitrary method.

type User

type User struct {
	// ID identifies the virtual user. In the open model every arrival gets its own ID.
	ID int
	// Iteration counts how many times this user has run the scenario (0-based).
	Iteration int
	// Client sends the requests. Use it directly for anything the Step builders do not cover,
	// but note that such requests are not recorded.
	Client *http.Client
	// contains filtered or unexported fields
}

User is a virtual user that runs the scenario once. ID is the number of the virtual user and does not change across iterations. Client has its own cookie jar per iteration, so every iteration starts a fresh session.

func (*User) Step

func (u *User) Step(name string, fn func(s *Step) error) error

Step runs one section of the scenario and records its duration and outcome. The error returned by fn is returned as is, so the caller decides whether to continue or stop.

func (*User) Think

func (u *User) Think(d time.Duration)

Think waits for d. The time waited is counted in neither the step nor Active. It returns early when ctx is done.

type UserStage added in v0.1.3

type UserStage struct {
	// Target is the number of active users at the end of the stage.
	Target int
	// For is how long the stage lasts.
	For time.Duration
}

UserStage is one stage of Plan.UserStages. During the stage, the number of active users moves linearly from the Target of the previous stage (Plan.StartUsers, 0 by default, for the first stage) to Target over For. Set Target to the previous Target to hold the number of users.

For example, ramp up to 100 users over 30 seconds, hold for 60 seconds, then ramp down to 0 over 10 seconds:

UserStages: []jotaro.UserStage{
	{Target: 100, For: 30 * time.Second},
	{Target: 100, For: 60 * time.Second},
	{Target: 0, For: 10 * time.Second},
},

func RepeatUserStages added in v0.1.3

func RepeatUserStages(n int, stages ...UserStage) []UserStage

RepeatUserStages returns stages repeated n times in a row, for a load shape that goes up and down several times. Every repetition starts from the Target the previous one ended at, so end the sequence at the Target it begins from (or accept that the first stage of the next round moves from there). Join the result with other stages using append.

For example, three waves of ramp up, hold and ramp down, after a first warm-up stage:

UserStages: append(
	[]jotaro.UserStage{{Target: 10, For: 10 * time.Second}},
	jotaro.RepeatUserStages(3,
		jotaro.UserStage{Target: 100, For: 20 * time.Second},
		jotaro.UserStage{Target: 100, For: 30 * time.Second},
		jotaro.UserStage{Target: 10, For: 10 * time.Second},
	)...,
),

It returns nil when n is not positive or no stage is given. The result is a new slice, so changing it does not change stages. Plan.UserStages rejects an empty result.

Example

RepeatUserStages repeats a sequence of stages, for a load shape that goes up and down several times. Join it with other stages using append.

package main

import (
	"fmt"
	"time"

	"github.com/RIRUa/jotaro"
)

func main() {
	stages := append(
		[]jotaro.UserStage{{Target: 10, For: 10 * time.Second}}, // warm up
		jotaro.RepeatUserStages(2,
			jotaro.UserStage{Target: 100, For: 20 * time.Second},
			jotaro.UserStage{Target: 100, For: 30 * time.Second},
			jotaro.UserStage{Target: 10, For: 10 * time.Second},
		)...,
	)
	for _, st := range stages {
		fmt.Println(st.Target, st.For)
	}
}
Output:
10 10s
100 20s
100 30s
10 10s
100 20s
100 30s
10 10s

type Weighted added in v0.1.3

type Weighted struct {
	// Scenario is the flow to run.
	Scenario *Scenario
	// Weight is the relative share of this scenario. It must be positive; only the ratio between weights matters.
	Weight int
}

Weighted is a scenario with its share in Plan.Scenarios.

Directories

Path Synopsis
cmd
jotaro command
Command jotaro is a CLI that works with result files saved by the jotaro library.
Command jotaro is a CLI that works with result files saved by the jotaro library.
examples
checkout command
Command checkout is a sample that shows how to use jotaro.
Command checkout is a sample that shows how to use jotaro.
marketplace command
Command marketplace is a deeper sample than examples/checkout.
Command marketplace is a deeper sample than examples/checkout.
mix command
Command mix is a sample of the plan-level features of jotaro: a weighted mix of scenarios, waves of users, aborting when the server is broken, live progress and metrics, and thresholds per scenario.
Command mix is a sample of the plan-level features of jotaro: a weighted mix of scenarios, waves of users, aborting when the server is broken, live progress and metrics, and thresholds per scenario.
internal
histogram
Package histogram is the log histogram (DDSketch style) that Latency holds for merging.
Package histogram is the log histogram (DDSketch style) that Latency holds for merging.
mcpserver
Package mcpserver is the MCP server behind "jotaro mcp".
Package mcpserver is the MCP server behind "jotaro mcp".
Package record holds the raw data of a load test (records of requests, steps and iterations), and its input and output.
Package record holds the raw data of a load test (records of requests, steps and iterations), and its input and output.
Package report aggregates and outputs the results (Report) of a load test.
Package report aggregates and outputs the results (Report) of a load test.

Jump to

Keyboard shortcuts

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