loadtest

package
v0.4.0-rc.3 Latest Latest
Warning

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

Go to latest
Published: Dec 4, 2026 License: Apache-2.0 Imports: 25 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package loadtest is experimental: its API and documented formats may change in a minor release; see https://nsgo.games/docs/stability/.

Package loadtest runs headless network load-test bots against a live game server over WebSocket (ws://, wss://) or encrypted UDP (udp://), driving the game's real wire protocol through netplay.Transport. It has no NSGo view or windowing dependency so bots run in plain Go processes and CI jobs.

A game registers one or more bot scripts implementing Client, loads a versioned loadtest.yaml configuration with Load or LoadFile, and runs the scenario with Run, RunWith, or Main. The resulting Report is a deterministic YAML document recording connection counts, handshake and RTT percentiles, per-channel packet and byte counters, server rejection reasons, unexpected disconnects, and sampled Prometheus metrics from the server's /metrics endpoint.

Index

Examples

Constants

View Source
const (
	// ConfigVersion is the loadtest.yaml schema version this package reads and writes.
	ConfigVersion = 1

	// FileName is the default configuration file name for game loadtest.
	FileName = "loadtest.yaml"

	// DefaultStepInterval is the bot tick period used when Config.StepInterval is zero.
	DefaultStepInterval = 50 * time.Millisecond

	// DefaultMetricsInterval is how often Config.MetricsURL is scraped when Config.MetricsInterval is zero.
	DefaultMetricsInterval = 5 * time.Second
)
View Source
const (
	// ReportVersion is the loadtest report YAML schema version this package reads and writes.
	ReportVersion = 1

	// ReportFileName is the default file name for written YAML loadtest reports.
	ReportFileName = "loadtest.report.yaml"
)

Variables

This section is empty.

Functions

func Main

func Main(scripts map[string]func(i int) Client, opts Options)

Main is the entry point for a game project's cmd/loadtest binary. It binds os.Interrupt cancellation, calls RunCLI with os.Args[1:], and exits with status 1 on error.

func ParseUDPPublicKey

func ParseUDPPublicKey(hexKey string) (*ecdh.PublicKey, error)

ParseUDPPublicKey decodes a hex-encoded 32-byte X25519 public key as printed by UDPServer.PublicKey().Bytes().

func RampUpSchedule

func RampUpSchedule(clients int, rampUp time.Duration) []time.Duration

RampUpSchedule returns the start offset for each of clients bots distributed evenly across rampUp. When clients <= 0 it returns nil. When clients == 1 or rampUp <= 0 every bot starts at offset 0.

Example
package main

import (
	"fmt"
	"time"

	"github.com/nsgo-dev/game/pkg/online/gameserver/loadtest"
)

func main() {
	offsets := loadtest.RampUpSchedule(4, 3*time.Second)
	for i, d := range offsets {
		fmt.Printf("bot %d: %s\n", i, d)
	}
}
Output:
bot 0: 0s
bot 1: 1s
bot 2: 2s
bot 3: 3s

func RecordLoss

func RecordLoss(tx netplay.Transport, ch netplay.Channel, count uint64)

RecordLoss adds count lost packets on ch for the bot owning tx, for scripts that detect protocol-level loss such as skipped snapshot ticks. It is a no-op if tx is not a transport handed to Client.Step by Run or RunWith.

func RecordRTT

func RecordRTT(tx netplay.Transport, d time.Duration)

RecordRTT records an explicit application-level round-trip duration sample for the bot owning tx. Calling RecordRTT switches that bot from automatic send-to-receive latency sampling to explicit samples only. It is a no-op if tx is not a transport handed to Client.Step by Run or RunWith.

func RunCLI

func RunCLI(ctx context.Context, args []string, scripts map[string]func(i int) Client, opts Options, stdout, stderr io.Writer) error

RunCLI parses standard loadtest runner flags (-config, -out, -target, -udp-pubkey, -metrics-url, -clients, -duration, -ramp-up), runs the scenario with RunWith, and writes the deterministic YAML report to -out (or stdout when -out is empty or "-").

func SaveFile

func SaveFile(path string, cfg Config) error

SaveFile writes cfg to path in canonical YAML form, creating parent directories as needed.

func SaveReportFile

func SaveReportFile(path string, r Report) error

SaveReportFile writes r to path in canonical YAML form, creating parent directories as needed.

Types

type ChannelStats

type ChannelStats struct {
	Channel       string `yaml:"channel"`
	Sent          uint64 `yaml:"sent"`
	Received      uint64 `yaml:"received"`
	Lost          uint64 `yaml:"lost"`
	BytesSent     uint64 `yaml:"bytesSent"`
	BytesReceived uint64 `yaml:"bytesReceived"`
}

ChannelStats aggregates packet and byte counters for one netplay.Channel.

type Client

type Client interface {
	Step(ctx context.Context, tx netplay.Transport, now time.Time) error
}

Client is one load-test bot script driven against a live server transport. Run calls Step once on connection and then every Config.StepInterval until the scenario finishes or the bot disconnects.

type ClientCounts

type ClientCounts struct {
	Configured  int `yaml:"configured"`
	Connected   int `yaml:"connected"`
	Rejected    int `yaml:"rejected"`
	DialErrors  int `yaml:"dialErrors"`
	Disconnects int `yaml:"disconnects"`
}

ClientCounts summarizes bot session outcomes for a load-test run. Unless the caller cancels the run, every configured bot ends up in exactly one of Connected, Rejected or DialErrors; a dial still pending when the scenario window ends counts as a dial error. Disconnects counts connected bots that dropped early.

type ClientFunc

type ClientFunc func(ctx context.Context, tx netplay.Transport, now time.Time) error

ClientFunc adapts a plain function to the Client interface.

func (ClientFunc) Step

func (f ClientFunc) Step(ctx context.Context, tx netplay.Transport, now time.Time) error

Step calls f(ctx, tx, now).

type Config

type Config struct {
	Version         int           `yaml:"version"`
	Target          string        `yaml:"target"`
	UDPPublicKey    string        `yaml:"udpPublicKey,omitempty"`
	Clients         int           `yaml:"clients"`
	RampUp          time.Duration `yaml:"rampUp,omitempty"`
	Duration        time.Duration `yaml:"duration"`
	StepInterval    time.Duration `yaml:"stepInterval,omitempty"`
	Script          string        `yaml:"script"`
	MetricsURL      string        `yaml:"metricsURL,omitempty"`
	MetricsInterval time.Duration `yaml:"metricsInterval,omitempty"`
	ClientVersion   string        `yaml:"clientVersion,omitempty"`
}

Config is a versioned loadtest.yaml document describing one network load-test scenario. Bots launch evenly over RampUp and hold steady for Duration (total active window RampUp + Duration).

func DefaultConfig

func DefaultConfig() Config

DefaultConfig returns a starter loadtest.yaml configuration targeting a local WebSocket server with 16 clients, a 1s ramp-up, 10s steady duration, and metrics scraping on http://127.0.0.1:8081/metrics.

func Load

func Load(data []byte) (Config, error)

Load decodes and validates a loadtest.yaml document. Unknown fields, trailing YAML documents, and unsupported versions are refused with a *loaderr.Error.

Example
package main

import (
	"fmt"

	"github.com/nsgo-dev/game/pkg/online/gameserver/loadtest"
)

func main() {
	cfg, err := loadtest.Load([]byte(`version: 1
target: ws://127.0.0.1:8443/game
clients: 16
rampUp: 1s
duration: 10s
script: pingpong
`))
	if err != nil {
		panic(err)
	}
	fmt.Printf("%s clients=%d duration=%s\n", cfg.Script, cfg.Clients, cfg.Duration)
}
Output:
pingpong clients=16 duration=10s

func LoadFile

func LoadFile(path string) (Config, error)

LoadFile reads, decodes, and validates a loadtest.yaml file from disk.

func (Config) Marshal

func (c Config) Marshal() ([]byte, error)

Marshal validates cfg and encodes it as deterministic YAML with 2-space indentation.

func (Config) Validate

func (c Config) Validate() error

Validate checks every field of c and returns a *loaderr.Error naming the first invalid field.

type LatencySummary

type LatencySummary struct {
	Count int           `yaml:"count"`
	Min   time.Duration `yaml:"min,omitempty"`
	P50   time.Duration `yaml:"p50,omitempty"`
	P95   time.Duration `yaml:"p95,omitempty"`
	P99   time.Duration `yaml:"p99,omitempty"`
	Max   time.Duration `yaml:"max,omitempty"`
}

LatencySummary reports sample count, extrema, and nearest-rank percentiles for a set of durations.

func ComputeLatencySummary

func ComputeLatencySummary(samples []time.Duration) LatencySummary

ComputeLatencySummary computes Count, Min, P50, P95, P99, and Max using nearest-rank percentiles over a sorted copy of samples. Samples is never mutated.

Example
package main

import (
	"fmt"
	"time"

	"github.com/nsgo-dev/game/pkg/online/gameserver/loadtest"
)

func main() {
	summary := loadtest.ComputeLatencySummary([]time.Duration{
		5 * time.Millisecond,
		1 * time.Millisecond,
		3 * time.Millisecond,
		2 * time.Millisecond,
		4 * time.Millisecond,
	})
	fmt.Printf("count=%d min=%s p50=%s max=%s\n", summary.Count, summary.Min, summary.P50, summary.Max)
}
Output:
count=5 min=1ms p50=3ms max=5ms

type MatchMetricsSample

type MatchMetricsSample struct {
	Match       string        `yaml:"match"`
	TickCount   uint64        `yaml:"tickCount"`
	TickMean    time.Duration `yaml:"tickMean,omitempty"`
	TickP95     time.Duration `yaml:"tickP95,omitempty"`
	TickP99     time.Duration `yaml:"tickP99,omitempty"`
	Overruns    uint64        `yaml:"overruns"`
	MissedTicks uint64        `yaml:"missedTicks"`
}

MatchMetricsSample summarizes one match's tick histogram and overrun counters exported by gameserver.Health (/metrics).

type Options

type Options struct {
	// Token returns the handshake credential presented by bot i (0-indexed).
	// Nil sends an empty token.
	Token func(i int) []byte

	// ClientVersion returns the build version string presented by bot i.
	// When nil or returning empty, Config.ClientVersion is used.
	ClientVersion func(i int) string

	// UDPPublicKey overrides Config.UDPPublicKey and any ?pubkey= query
	// parameter when dialing udp:// targets.
	UDPPublicKey *ecdh.PublicKey

	// Dial overrides how bots connect to Config.Target. When nil, the built-in
	// dialer opens real WebSocket (ws://, wss://) or Noise NK UDP (udp://)
	// sessions via netplay.
	Dial func(ctx context.Context, botIndex int, target string, opts netplay.DialOptions) (netplay.Transport, error)

	// HTTPClient is used to scrape Config.MetricsURL. When nil, a default
	// client with a 5s timeout is used.
	HTTPClient *http.Client

	// Now supplies the clock used for timing measurements. Nil uses time.Now.
	Now func() time.Time
}

Options configures optional hooks for RunWith and Main.

type RejectCount

type RejectCount struct {
	Reason string `yaml:"reason"`
	Count  int    `yaml:"count"`
}

RejectCount records how many bots were refused during handshake with a given server rejection reason.

type Report

type Report struct {
	Version       int                  `yaml:"version"`
	Target        string               `yaml:"target"`
	Script        string               `yaml:"script"`
	Clients       ClientCounts         `yaml:"clients"`
	RampUp        time.Duration        `yaml:"rampUp,omitempty"`
	Duration      time.Duration        `yaml:"duration"`
	Handshake     LatencySummary       `yaml:"handshake"`
	RTT           LatencySummary       `yaml:"rtt"`
	Channels      []ChannelStats       `yaml:"channels,omitempty"`
	Rejects       []RejectCount        `yaml:"rejects,omitempty"`
	ServerMetrics *ServerMetricsReport `yaml:"serverMetrics,omitempty"`
}

Report is the deterministic YAML result of a load-test run. It contains no wall-clock timestamps or random IDs so recorded reports diff cleanly in review.

func LoadReportFile

func LoadReportFile(path string) (Report, error)

LoadReportFile reads, decodes, and validates a loadtest report YAML file.

func ParseReport

func ParseReport(data []byte) (Report, error)

ParseReport decodes and validates a loadtest report YAML document. Unknown fields, trailing documents, and unsupported versions are refused with a *loaderr.Error.

func Run

func Run(ctx context.Context, cfg Config, scripts map[string]func(i int) Client) (Report, error)

Run executes the load test configured by cfg using the named bot factory in scripts and returns the resulting deterministic Report.

func RunWith

func RunWith(ctx context.Context, cfg Config, scripts map[string]func(i int) Client, opts Options) (Report, error)

RunWith executes the load test configured by cfg with optional hooks such as per-bot authentication tokens, custom dialers, or UDP server public keys.

func (Report) Marshal

func (r Report) Marshal() ([]byte, error)

Marshal validates r, normalizes collection ordering, and encodes it as deterministic YAML with 2-space indentation.

func (Report) Summary

func (r Report) Summary() string

Summary returns a concise, human-readable text summary of r for CLI output.

func (Report) Validate

func (r Report) Validate() error

Validate checks every field of r and returns a *loaderr.Error naming the first invalid field.

type ServerMetricsReport

type ServerMetricsReport struct {
	URL          string                `yaml:"url"`
	ScrapeErrors int                   `yaml:"scrapeErrors"`
	Samples      []ServerMetricsSample `yaml:"samples,omitempty"`
}

ServerMetricsReport holds periodic Prometheus scrapes collected from Config.MetricsURL during a run.

type ServerMetricsSample

type ServerMetricsSample struct {
	Elapsed                time.Duration        `yaml:"elapsed"`
	Peers                  int                  `yaml:"peers"`
	Rooms                  int                  `yaml:"rooms"`
	TickDuration           time.Duration        `yaml:"tickDuration,omitempty"`
	BytesIn                uint64               `yaml:"bytesIn"`
	BytesOut               uint64               `yaml:"bytesOut"`
	GuardPackets           uint64               `yaml:"guardPackets,omitempty"`
	GuardBytes             uint64               `yaml:"guardBytes,omitempty"`
	GuardDropped           uint64               `yaml:"guardDropped,omitempty"`
	GuardViolations        uint64               `yaml:"guardViolations,omitempty"`
	InboxUnreliableDropped uint64               `yaml:"inboxUnreliableDropped,omitempty"`
	InboxReliableRefused   uint64               `yaml:"inboxReliableRefused,omitempty"`
	InboxReliableWarnings  uint64               `yaml:"inboxReliableWarnings,omitempty"`
	Matches                []MatchMetricsSample `yaml:"matches,omitempty"`
}

ServerMetricsSample is one scrape of a gameserver.Health /metrics endpoint at a relative offset from the start of the load-test run.

func ParseMetrics

func ParseMetrics(r io.Reader) (ServerMetricsSample, error)

ParseMetrics parses Prometheus text exposition output from a gameserver.Health /metrics endpoint into a ServerMetricsSample. Unrecognized series are ignored so game-specific collectors never break scraping.

Jump to

Keyboard shortcuts

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