stress

package
v1.5.0 Latest Latest
Warning

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

Go to latest
Published: Apr 2, 2026 License: MIT Imports: 11 Imported by: 0

Documentation

Overview

Package stress provides distributed stress testing capabilities

Package stress provides report generation capabilities

Package stress provides stress testing capabilities for TokMan

Package stress provides custom stress test scenarios

Package stress provides test scheduling capabilities

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func BatchReport

func BatchReport(results []*Result, format string) (map[string][]byte, error)

BatchReport generates reports for multiple results

func CommonTemplates

func CommonTemplates() map[string]*ScenarioTemplate

CommonTemplates returns common scenario templates

func Distribute

func Distribute(totalRPS int, distribution map[string]float64) map[string]int

Distribute calculates geographic distribution

func ExportReport

func ExportReport(result *Result, format string) ([]byte, error)

ExportReport exports results to various formats

func FormatComparison

func FormatComparison(c *ResultComparison) string

FormatComparison formats a comparison as a string

func PredefinedScenarios

func PredefinedScenarios() map[string]*Scenario

PredefinedScenarios returns a library of predefined scenarios

Types

type Alert

type Alert struct {
	Type      string
	Metric    string
	Value     float64
	Threshold float64
	Timestamp time.Time
	Severity  string
}

Alert represents a threshold alert

type Config

type Config struct {
	Duration         time.Duration
	WarmupDuration   time.Duration
	RampUpDuration   time.Duration
	CooldownDuration time.Duration
	TargetRPS        int
	MaxConcurrency   int
	Timeout          time.Duration
}

Config holds stress test configuration

func DefaultConfig

func DefaultConfig() Config

DefaultConfig returns default stress test configuration

type Coordinator

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

Coordinator manages distributed test execution

type CostConfig

type CostConfig struct {
	CostPerRequest float64
	CostPerMinute  float64
	Currency       string
}

CostConfig holds cost configuration

type CostEstimator

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

CostEstimator estimates test costs

func (*CostEstimator) Estimate

func (ce *CostEstimator) Estimate(duration time.Duration, rps int) float64

Estimate estimates cost for a test

type DistributedConfig

type DistributedConfig struct {
	CoordinatorAddress string
	NodeID             string
	IsCoordinator      bool
	HeartbeatInterval  time.Duration
	SyncTimeout        time.Duration
}

DistributedConfig holds distributed test configuration

type DistributedResult

type DistributedResult struct {
	NodeResults   []Result
	TotalRequests int64
	SuccessCount  int64
	ErrorCount    int64
	TimeoutCount  int64
	SuccessRate   float64
	ThroughputRPS float64
	AvgLatency    time.Duration
	StartTime     time.Time
	EndTime       time.Time
	Duration      time.Duration
}

DistributedResult holds aggregated results from distributed test

func RunDistributedTest

func RunDistributedTest(config DistributedTestConfig, nodes []*Node) (*DistributedResult, error)

RunDistributedTest runs a complete distributed test

func (*DistributedResult) GenerateReport

func (dr *DistributedResult) GenerateReport() string

GenerateReport generates a distributed test report

type DistributedRunner

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

DistributedRunner manages distributed stress testing

func NewDistributedRunner

func NewDistributedRunner(config DistributedConfig) *DistributedRunner

NewDistributedRunner creates a new distributed runner

func (*DistributedRunner) GetOnlineNodes

func (dr *DistributedRunner) GetOnlineNodes() []*Node

GetOnlineNodes returns only online nodes

func (*DistributedRunner) ListNodes

func (dr *DistributedRunner) ListNodes() []*Node

ListNodes returns all registered nodes

func (*DistributedRunner) RegisterNode

func (dr *DistributedRunner) RegisterNode(node *Node) error

RegisterNode registers a stress testing node

func (*DistributedRunner) RunDistributed

func (dr *DistributedRunner) RunDistributed(ctx context.Context, scenario *Scenario) (*DistributedResult, error)

RunDistributed executes a stress test across all nodes

func (*DistributedRunner) UnregisterNode

func (dr *DistributedRunner) UnregisterNode(nodeID string)

UnregisterNode removes a node

type DistributedScenario

type DistributedScenario struct {
	*Scenario
	NodeAssignments map[string][]string // scenario -> nodes
	TotalRPS        int
	GeographicDist  map[string]float64 // region -> percentage
}

DistributedScenario represents a scenario for distributed execution

type DistributedTestConfig

type DistributedTestConfig struct {
	Name            string
	Scenario        *Scenario
	Duration        time.Duration
	TotalRPS        int
	GeographicDist  map[string]float64
	NodeSelection   LoadBalanceStrategy
	FailOnNodeError bool
}

DistributedTestConfig holds test configuration

type GeographicDistribution

type GeographicDistribution struct {
	Regions map[string]RegionConfig
}

GeographicDistribution defines load distribution by region

func NewGeographicDistribution

func NewGeographicDistribution() *GeographicDistribution

NewGeographicDistribution creates geographic distribution

func (*GeographicDistribution) AddRegion

func (gd *GeographicDistribution) AddRegion(name string, percentage float64, nodes []string)

AddRegion adds a region

func (*GeographicDistribution) DistributeScenario

func (gd *GeographicDistribution) DistributeScenario(scenario *Scenario, totalRPS int) map[string]*Scenario

DistributeScenario distributes scenario across regions

type GeographicLoad

type GeographicLoad struct {
	Regions map[string]*RegionLoad
}

GeographicLoad provides geographic distribution

type HeartbeatMonitor

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

HeartbeatMonitor monitors node health

func NewHeartbeatMonitor

func NewHeartbeatMonitor(runner *DistributedRunner, interval, timeout time.Duration) *HeartbeatMonitor

NewHeartbeatMonitor creates a heartbeat monitor

func (*HeartbeatMonitor) Start

func (hm *HeartbeatMonitor) Start()

Start starts monitoring

func (*HeartbeatMonitor) Stop

func (hm *HeartbeatMonitor) Stop()

Stop stops monitoring

type JobStatus

type JobStatus string

JobStatus represents job status

const (
	JobStatusPending   JobStatus = "pending"
	JobStatusRunning   JobStatus = "running"
	JobStatusCompleted JobStatus = "completed"
	JobStatusFailed    JobStatus = "failed"
	JobStatusPaused    JobStatus = "paused"
)

type LoadBalanceStrategy

type LoadBalanceStrategy string

LoadBalanceStrategy defines load balancing strategy

const (
	StrategyRoundRobin LoadBalanceStrategy = "round_robin"
	StrategyRandom     LoadBalanceStrategy = "random"
	StrategyLeastLoad  LoadBalanceStrategy = "least_load"
)

type LoadBalancer

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

LoadBalancer balances load across nodes

func NewLoadBalancer

func NewLoadBalancer(strategy LoadBalanceStrategy) *LoadBalancer

NewLoadBalancer creates a load balancer

func (*LoadBalancer) AddNode

func (lb *LoadBalancer) AddNode(node *Node)

AddNode adds a node

func (*LoadBalancer) NextNode

func (lb *LoadBalancer) NextNode() *Node

NextNode returns the next node based on strategy

type MetricChange

type MetricChange struct {
	Name      string
	Baseline  float64
	Current   float64
	Change    float64
	ChangePct float64
}

MetricChange represents a change in a metric

type MetricCorrelator

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

MetricCorrelator correlates metrics

func (*MetricCorrelator) Correlate

func (mc *MetricCorrelator) Correlate() map[string]float64

Correlate finds correlations

type MetricDataPoint

type MetricDataPoint struct {
	Timestamp  time.Time
	Latency    time.Duration
	Throughput float64
	Errors     int
	CPU        float64
	Memory     float64
}

MetricDataPoint represents a data point

type Node

type Node struct {
	ID       string
	Address  string
	Status   NodeStatus
	Capacity int
	Load     float64
	LastPing time.Time
	// contains filtered or unexported fields
}

Node represents a stress testing node

type NodeClient

type NodeClient interface {
	Connect(address string) error
	Execute(scenario *Scenario) (*Result, error)
	HealthCheck() error
	Close() error
}

NodeClient interface for node communication

type NodeStatus

type NodeStatus string

NodeStatus represents node status

const (
	NodeStatusOnline  NodeStatus = "online"
	NodeStatusOffline NodeStatus = "offline"
	NodeStatusBusy    NodeStatus = "busy"
)

type RegionConfig

type RegionConfig struct {
	Name       string
	Percentage float64
	Nodes      []string
}

RegionConfig holds region-specific configuration

type RegionLoad

type RegionLoad struct {
	Name       string
	Percentage float64
	RPS        int
	Latency    time.Duration
}

RegionLoad represents load for a region

type ReportGenerator

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

ReportGenerator generates stress test reports

func NewReportGenerator

func NewReportGenerator(format string) *ReportGenerator

NewReportGenerator creates a new report generator

func (*ReportGenerator) Generate

func (rg *ReportGenerator) Generate(result *Result) ([]byte, error)

Generate generates a report from results

type ReportScheduler

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

ReportScheduler schedules automatic report generation

func NewReportScheduler

func NewReportScheduler(interval time.Duration, formats []string, dir string) *ReportScheduler

NewReportScheduler creates a new scheduler

func (*ReportScheduler) Schedule

func (rs *ReportScheduler) Schedule(result *Result) error

Schedule schedules report generation for a test

type ResourceMetrics

type ResourceMetrics struct {
	CPUPercent  float64
	MemoryMB    float64
	Goroutines  int
	GCRuns      uint32
	HeapAllocMB float64
}

ResourceMetrics tracks resource utilization

type Result

type Result struct {
	Scenario         string
	Type             TestType
	StartTime        time.Time
	EndTime          time.Time
	Duration         time.Duration
	TotalRequests    int64
	SuccessCount     int64
	ErrorCount       int64
	TimeoutCount     int64
	LatencyHistogram map[string]time.Duration
	LatencyP50       time.Duration
	LatencyP95       time.Duration
	LatencyP99       time.Duration
	MinLatency       time.Duration
	MaxLatency       time.Duration
	AvgLatency       time.Duration
	ThroughputRPS    float64
	SuccessRate      float64
	ErrorRate        float64
	Errors           map[string]int
	ResourceUsage    ResourceMetrics
}

Result holds stress test results

func Replay

func Replay(originalResult *Result, config Config) (*Result, error)

Replay replays a previous test

func (*Result) GenerateReport

func (r *Result) GenerateReport() string

GenerateReport creates a comprehensive stress test report

type ResultComparison

type ResultComparison struct {
	Baseline *Result
	Current  *Result
	Changes  map[string]MetricChange
}

ResultComparison compares two stress test results

func CompareResults

func CompareResults(baseline, current *Result) *ResultComparison

CompareResults compares two results

type Runner

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

Runner executes stress tests

func NewRunner

func NewRunner(config Config) *Runner

NewRunner creates a stress test runner

func (*Runner) RegisterScenario

func (r *Runner) RegisterScenario(s *Scenario)

RegisterScenario adds a scenario

func (*Runner) Run

func (r *Runner) Run(ctx context.Context, scenarioName string) (*Result, error)

Run executes a stress test for a scenario

func (*Runner) Stop

func (r *Runner) Stop()

Stop gracefully stops the stress test

type Scenario

type Scenario struct {
	Name        string
	Type        TestType
	Description string
	Fn          func(ctx context.Context) error
	Weight      int
}

Scenario defines a stress test scenario

func APIHealthCheckScenario

func APIHealthCheckScenario() *Scenario

APIHealthCheckScenario simulates API health checks

func BatchProcessingScenario

func BatchProcessingScenario() *Scenario

BatchProcessingScenario simulates batch job processing

func CPUIntensiveScenario

func CPUIntensiveScenario() *Scenario

CPUIntensiveScenario simulates CPU-intensive operations

func CacheStressScenario

func CacheStressScenario() *Scenario

CacheStressScenario simulates cache operations

func DatabaseQueryScenario

func DatabaseQueryScenario() *Scenario

DatabaseQueryScenario simulates database queries

func FileUploadScenario

func FileUploadScenario() *Scenario

FileUploadScenario simulates file uploads

func GRPCRequestScenario

func GRPCRequestScenario() *Scenario

GRPCRequestScenario simulates gRPC requests

func GraphQLQueryScenario

func GraphQLQueryScenario() *Scenario

GraphQLQueryScenario simulates GraphQL queries

func IOIntensiveScenario

func IOIntensiveScenario() *Scenario

IOIntensiveScenario simulates I/O operations

func LoginSimulationScenario

func LoginSimulationScenario() *Scenario

LoginSimulationScenario simulates user login

func MemoryIntensiveScenario

func MemoryIntensiveScenario() *Scenario

MemoryIntensiveScenario simulates memory-intensive operations

func MixedWorkloadScenario

func MixedWorkloadScenario() *Scenario

MixedWorkloadScenario combines multiple workloads

func SearchQueryScenario

func SearchQueryScenario() *Scenario

SearchQueryScenario simulates search operations

func StandardScenarios

func StandardScenarios() []*Scenario

StandardScenarios returns common stress test scenarios

func WebSocketStressScenario

func WebSocketStressScenario() *Scenario

WebSocketStressScenario simulates WebSocket connections

func WebhookDeliveryScenario

func WebhookDeliveryScenario() *Scenario

WebhookDeliveryScenario simulates webhook delivery

type ScenarioBuilder

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

ScenarioBuilder builds custom stress test scenarios

func NewScenarioBuilder

func NewScenarioBuilder(name string) *ScenarioBuilder

NewScenarioBuilder creates a new scenario builder

func (*ScenarioBuilder) Build

func (sb *ScenarioBuilder) Build() *Scenario

Build creates the scenario

func (*ScenarioBuilder) WithDescription

func (sb *ScenarioBuilder) WithDescription(desc string) *ScenarioBuilder

WithDescription sets the description

func (*ScenarioBuilder) WithFunction

func (sb *ScenarioBuilder) WithFunction(fn func(ctx context.Context) error) *ScenarioBuilder

WithFunction sets the test function

func (*ScenarioBuilder) WithParameter

func (sb *ScenarioBuilder) WithParameter(key string, value interface{}) *ScenarioBuilder

WithParameter adds a parameter

func (*ScenarioBuilder) WithType

func (sb *ScenarioBuilder) WithType(t TestType) *ScenarioBuilder

WithType sets the scenario type

func (*ScenarioBuilder) WithWeight

func (sb *ScenarioBuilder) WithWeight(w int) *ScenarioBuilder

WithWeight sets the weight

type ScenarioComposer

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

ScenarioComposer composes multiple scenarios

func NewScenarioComposer

func NewScenarioComposer() *ScenarioComposer

NewScenarioComposer creates a new composer

func (*ScenarioComposer) Add

func (sc *ScenarioComposer) Add(scenario *Scenario, weight int) *ScenarioComposer

Add adds a scenario with weight

func (*ScenarioComposer) Compose

func (sc *ScenarioComposer) Compose(name string) *Scenario

Compose creates a composite scenario

type ScenarioTemplate

type ScenarioTemplate struct {
	Name        string
	Description string
	Type        TestType
	BaseFn      func(ctx context.Context, params map[string]interface{}) error
	Defaults    map[string]interface{}
}

ScenarioTemplate represents a reusable scenario template

func (*ScenarioTemplate) Instantiate

func (st *ScenarioTemplate) Instantiate(params map[string]interface{}) *Scenario

Instantiate creates a scenario from template

type Schedule

type Schedule struct {
	Type     ScheduleType
	Interval time.Duration
	Cron     string
	At       time.Time
}

Schedule defines when to run

type ScheduleType

type ScheduleType string

ScheduleType defines schedule types

const (
	ScheduleInterval ScheduleType = "interval"
	ScheduleOnce     ScheduleType = "once"
	ScheduleDaily    ScheduleType = "daily"
	ScheduleWeekly   ScheduleType = "weekly"
)

type ScheduledJob

type ScheduledJob struct {
	ID       string
	Name     string
	Scenario *Scenario
	Schedule Schedule
	LastRun  time.Time
	NextRun  time.Time
	RunCount int
	MaxRuns  int
	Status   JobStatus
	Results  []Result
}

ScheduledJob represents a scheduled test job

type Scheduler

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

Scheduler schedules stress tests

func NewScheduler

func NewScheduler(runner *Runner) *Scheduler

NewScheduler creates a new scheduler

func (*Scheduler) AddJob

func (s *Scheduler) AddJob(job *ScheduledJob) error

AddJob adds a scheduled job

func (*Scheduler) ListJobs

func (s *Scheduler) ListJobs() []*ScheduledJob

ListJobs returns all jobs

func (*Scheduler) RemoveJob

func (s *Scheduler) RemoveJob(jobID string)

RemoveJob removes a job

func (*Scheduler) Start

func (s *Scheduler) Start(ctx context.Context)

Start starts the scheduler

func (*Scheduler) Stop

func (s *Scheduler) Stop()

Stop stops the scheduler

type SyncBarrier

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

SyncBarrier synchronizes distributed test phases

func NewSyncBarrier

func NewSyncBarrier(expected int) *SyncBarrier

NewSyncBarrier creates a sync barrier

func (*SyncBarrier) Wait

func (sb *SyncBarrier) Wait()

Wait waits for all participants

type TestType

type TestType string

TestType defines the type of stress test

const (
	TypeLoad      TestType = "load"
	TypeSpike     TestType = "spike"
	TypeSoak      TestType = "soak"
	TypeStress    TestType = "stress"
	TypeBreakdown TestType = "breakdown"
)

type ThresholdConfig

type ThresholdConfig struct {
	MaxErrorRate  float64
	MaxLatencyP95 time.Duration
	MinThroughput float64
}

ThresholdConfig holds threshold configuration

type ThresholdMonitor

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

ThresholdMonitor monitors results against thresholds

func NewThresholdMonitor

func NewThresholdMonitor(config ThresholdConfig) *ThresholdMonitor

NewThresholdMonitor creates a monitor

func (*ThresholdMonitor) Check

func (tm *ThresholdMonitor) Check(result *Result) []Alert

Check checks a result against thresholds

Jump to

Keyboard shortcuts

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