performance

package
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Sep 4, 2025 License: Apache-2.0 Imports: 19 Imported by: 0

Documentation

Overview

Package performance provides performance optimization configurations and utilities

Index

Constants

This section is empty.

Variables

View Source
var DefaultIntegrationConfig = &Config{
	UseSONIC:              true,
	EnableHTTP2:           true,
	HTTP2MaxConcurrent:    100,
	HTTP2MaxUploadBuffer:  1 << 16,
	EnableProfiling:       false,
	EnableMetrics:         false,
	GOMAXPROCS:            runtime.NumCPU(),
	GOGC:                  100,
	MaxIdleConns:          10,
	MaxConnsPerHost:       5,
	IdleConnTimeout:       30 * time.Second,
	DisableKeepAlives:     false,
	DisableCompression:    false,
	ResponseHeaderTimeout: 5 * time.Second,
}

DefaultIntegrationConfig provides default configuration for integration tests

Functions

func ApplyRuntimeOptimizations

func ApplyRuntimeOptimizations(config *Config, logger *zap.Logger)

ApplyRuntimeOptimizations applies runtime performance optimizations

func JSONMarshal

func JSONMarshal(v interface{}) ([]byte, error)

JSONMarshal uses bytedance/sonic for high-performance JSON marshaling

func JSONUnmarshal

func JSONUnmarshal(data []byte, v interface{}) error

JSONUnmarshal uses bytedance/sonic for high-performance JSON unmarshaling

func SetupHTTP2Server

func SetupHTTP2Server(handler http.Handler, config *Config) *http.Server

SetupHTTP2Server configures an HTTP server with HTTP/2 support

func SetupOptimizedTransport

func SetupOptimizedTransport(config *Config) *http.Transport

SetupOptimizedTransport creates an optimized HTTP transport with HTTP/2 support

func StartMetricsServer

func StartMetricsServer(config *Config, registry *prometheus.Registry, logger *zap.Logger) error

StartMetricsServer starts the Prometheus metrics server

func StartProfilingServer

func StartProfilingServer(config *Config, logger *zap.Logger) error

StartProfilingServer starts the pprof profiling server

Types

type AsyncMetrics

type AsyncMetrics struct {
	QueueDepth int
	Throughput float64
	Workers    int // 2025: Number of worker goroutines
}

AsyncMetrics contains async processing metrics

type AsyncProcessor

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

AsyncProcessor processes tasks asynchronously

func (*AsyncProcessor) GetMetrics

func (ap *AsyncProcessor) GetMetrics() *AsyncMetrics

GetMetrics returns async processing metrics

func (*AsyncProcessor) SubmitTask

func (ap *AsyncProcessor) SubmitTask(task func() error) error

SubmitTask submits a task for processing

type AsyncTask

type AsyncTask struct {
	ID       string
	Name     string
	Type     string
	Priority int
	Data     interface{}
	Context  context.Context
	Timeout  time.Duration
	Function func() error
}

AsyncTask represents an asynchronous task for performance testing

type BenchmarkResult

type BenchmarkResult struct {
	Name           string
	Duration       time.Duration
	StartTime      time.Time
	EndTime        time.Time
	Passed         bool
	RegressionInfo string
	LatencyP50     time.Duration
	LatencyP95     time.Duration
	LatencyP99     time.Duration
	Error          error
	MemoryLeaks    []*MemoryLeak // 2025: Advanced memory leak detection
	Throughput     float64       // 2025: Operations per second
	SuccessCount   int64
	TotalRequests  int64
	PeakMemoryMB   float64
	PeakCPUPercent float64
	StepDurations  []time.Duration
}

BenchmarkResult represents the result of a benchmark

type BenchmarkSuite

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

BenchmarkSuite provides performance benchmarking capabilities with 2025 features

func NewBenchmarkSuite

func NewBenchmarkSuite() *BenchmarkSuite

NewBenchmarkSuite creates a new benchmark suite

func (*BenchmarkSuite) GenerateReport

func (bs *BenchmarkSuite) GenerateReport() string

GenerateReport generates a comprehensive performance report.

func (*BenchmarkSuite) Run

func (bs *BenchmarkSuite) Run(ctx context.Context, name string, fn func()) time.Duration

Run executes a benchmark test

func (*BenchmarkSuite) RunConcurrentBenchmark

func (bs *BenchmarkSuite) RunConcurrentBenchmark(ctx context.Context, name string, concurrency int, duration time.Duration, fn func() error) *BenchmarkResult

RunConcurrentBenchmark executes a concurrent benchmark with advanced metrics

func (*BenchmarkSuite) RunMemoryStabilityBenchmark

func (bs *BenchmarkSuite) RunMemoryStabilityBenchmark(ctx context.Context, name string, duration time.Duration, fn func() error) *BenchmarkResult

RunMemoryStabilityBenchmark executes a memory stability benchmark with leak detection

func (*BenchmarkSuite) RunRealisticTelecomWorkload

func (bs *BenchmarkSuite) RunRealisticTelecomWorkload(ctx context.Context, scenario TelecomScenario) (*BenchmarkResult, error)

RunRealisticTelecomWorkload executes a realistic telecom workload scenario.

type CacheManager

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

CacheManager manages cache operations

func (*CacheManager) Get

func (cm *CacheManager) Get(ctx context.Context, key string) (interface{}, error)

Get retrieves a value from cache

func (*CacheManager) GetStats

func (cm *CacheManager) GetStats() *CacheStats

GetStats returns cache statistics

func (*CacheManager) Set

func (cm *CacheManager) Set(ctx context.Context, key string, value interface{}) error

Set stores a value in cache

type CacheMiddleware

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

CacheMiddleware provides performance monitoring for cache operations

func NewCacheMiddleware

func NewCacheMiddleware(metrics *Metrics) *CacheMiddleware

NewCacheMiddleware creates a new cache middleware for performance monitoring

func (*CacheMiddleware) RecordEviction

func (m *CacheMiddleware) RecordEviction(cacheName string)

RecordEviction records a cache eviction

func (*CacheMiddleware) RecordHit

func (m *CacheMiddleware) RecordHit(cacheName string)

RecordHit records a cache hit

func (*CacheMiddleware) RecordMiss

func (m *CacheMiddleware) RecordMiss(cacheName string)

RecordMiss records a cache miss

func (*CacheMiddleware) UpdateSize

func (m *CacheMiddleware) UpdateSize(cacheName string, sizeBytes float64)

UpdateSize updates the cache size

type CacheStats

type CacheStats struct {
	HitRate  float64
	MissRate float64
	Size     int // 2025: Current cache size
	Capacity int // 2025: Maximum capacity
}

CacheStats contains cache statistics

type Config

type Config struct {
	// JSON processing configuration
	UseSONIC bool `json:"use_sonic" yaml:"use_sonic"`

	// HTTP2 configuration
	EnableHTTP2          bool   `json:"enable_http2" yaml:"enable_http2"`
	HTTP2MaxConcurrent   uint32 `json:"http2_max_concurrent" yaml:"http2_max_concurrent"`
	HTTP2MaxUploadBuffer uint32 `json:"http2_max_upload_buffer" yaml:"http2_max_upload_buffer"`

	// Profiling configuration
	EnableProfiling bool   `json:"enable_profiling" yaml:"enable_profiling"`
	ProfilingAddr   string `json:"profiling_addr" yaml:"profiling_addr"`

	// Metrics configuration
	EnableMetrics bool   `json:"enable_metrics" yaml:"enable_metrics"`
	MetricsAddr   string `json:"metrics_addr" yaml:"metrics_addr"`

	// Runtime optimization
	GOMAXPROCS int `json:"gomaxprocs" yaml:"gomaxprocs"`
	GOGC       int `json:"gogc" yaml:"gogc"`

	// Connection pool settings
	MaxIdleConns          int           `json:"max_idle_conns" yaml:"max_idle_conns"`
	MaxConnsPerHost       int           `json:"max_conns_per_host" yaml:"max_conns_per_host"`
	IdleConnTimeout       time.Duration `json:"idle_conn_timeout" yaml:"idle_conn_timeout"`
	DisableKeepAlives     bool          `json:"disable_keep_alives" yaml:"disable_keep_alives"`
	DisableCompression    bool          `json:"disable_compression" yaml:"disable_compression"`
	ResponseHeaderTimeout time.Duration `json:"response_header_timeout" yaml:"response_header_timeout"`
}

Config holds performance optimization settings

func DefaultConfig

func DefaultConfig() *Config

DefaultConfig returns optimized default performance configuration

type DatabaseMiddleware

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

DatabaseMiddleware provides performance monitoring for database operations

func NewDatabaseMiddleware

func NewDatabaseMiddleware(metrics *Metrics) *DatabaseMiddleware

NewDatabaseMiddleware creates a new database middleware for performance monitoring

func (*DatabaseMiddleware) RecordQuery

func (m *DatabaseMiddleware) RecordQuery(queryType, table string, fn func() error) error

RecordQuery records database query performance

type HTTPMiddleware

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

HTTPMiddleware provides performance monitoring for HTTP requests

func NewHTTPMiddleware

func NewHTTPMiddleware(metrics *Metrics) *HTTPMiddleware

NewHTTPMiddleware creates a new HTTP middleware for performance monitoring

func (*HTTPMiddleware) Handler

func (m *HTTPMiddleware) Handler(next http.Handler) http.Handler

Handler returns an HTTP middleware that records request metrics

type IntentMiddleware

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

IntentMiddleware provides performance monitoring for intent processing

func NewIntentMiddleware

func NewIntentMiddleware(metrics *Metrics) *IntentMiddleware

NewIntentMiddleware creates a new intent middleware for performance monitoring

func (*IntentMiddleware) ProcessIntent

func (m *IntentMiddleware) ProcessIntent(intentType string, fn func() error) error

ProcessIntent processes an intent with performance tracking

type JSONMiddleware

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

JSONMiddleware provides performance monitoring for JSON operations

func NewJSONMiddleware

func NewJSONMiddleware(metrics *Metrics) *JSONMiddleware

NewJSONMiddleware creates a new JSON middleware for performance monitoring

func (*JSONMiddleware) MarshalWithMetrics

func (m *JSONMiddleware) MarshalWithMetrics(v interface{}) ([]byte, error)

MarshalWithMetrics marshals JSON with performance tracking

func (*JSONMiddleware) UnmarshalWithMetrics

func (m *JSONMiddleware) UnmarshalWithMetrics(data []byte, v interface{}) error

UnmarshalWithMetrics unmarshals JSON with performance tracking

type LoadTestResult

type LoadTestResult struct {
	Timestamp      time.Time
	RequestsPerSec float64
	AvgLatency     time.Duration
	P95Latency     time.Duration
	P99Latency     time.Duration
	ErrorRate      float64
}

LoadTestResult represents a load test result

type LoadTester

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

LoadTester provides load testing capabilities (2025 feature)

func NewLoadTester

func NewLoadTester() *LoadTester

NewLoadTester creates a new load tester

func (*LoadTester) RunLoadTest

func (lt *LoadTester) RunLoadTest(ctx context.Context, targetRPS int, duration time.Duration, fn func() error) *LoadTestResult

RunLoadTest executes a load test

type Manager

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

Manager handles performance monitoring and optimization

func NewManager

func NewManager(config *Config, logger *zap.Logger, registry *prometheus.Registry) *Manager

NewManager creates a new performance manager

func (*Manager) GetConfig

func (m *Manager) GetConfig() *Config

GetConfig returns the current performance configuration

func (*Manager) Stop

func (m *Manager) Stop()

Stop gracefully stops the performance manager

type MemoryLeak

type MemoryLeak struct {
	Description string
	AllocBytes  int64
	Location    string
}

MemoryLeak represents a memory leak detection result

type Metrics

type Metrics struct {
	// Request metrics
	RequestDuration *prometheus.HistogramVec
	RequestCounter  *prometheus.CounterVec
	RequestInFlight prometheus.Gauge

	// JSON processing metrics
	JSONMarshalDuration   prometheus.Histogram
	JSONUnmarshalDuration prometheus.Histogram
	JSONProcessingErrors  prometheus.Counter

	// Memory metrics
	HeapAlloc    prometheus.Gauge
	HeapSys      prometheus.Gauge
	HeapIdle     prometheus.Gauge
	HeapInuse    prometheus.Gauge
	HeapReleased prometheus.Gauge
	StackInuse   prometheus.Gauge
	StackSys     prometheus.Gauge
	MSpanInuse   prometheus.Gauge
	MSpanSys     prometheus.Gauge
	MCacheInuse  prometheus.Gauge
	MCacheSys    prometheus.Gauge
	GCPauseTotal prometheus.Gauge
	GCCount      prometheus.Gauge
	Goroutines   prometheus.Gauge

	// HTTP/2 metrics
	HTTP2StreamsActive    prometheus.Gauge
	HTTP2StreamsTotal     prometheus.Counter
	HTTP2FramesReceived   *prometheus.CounterVec
	HTTP2FramesSent       *prometheus.CounterVec
	HTTP2ConnectionErrors prometheus.Counter

	// Cache metrics
	CacheHits      *prometheus.CounterVec
	CacheMisses    *prometheus.CounterVec
	CacheEvictions *prometheus.CounterVec
	CacheSize      *prometheus.GaugeVec

	// Database metrics
	DBConnectionsActive prometheus.Gauge
	DBConnectionsIdle   prometheus.Gauge
	DBQueryDuration     *prometheus.HistogramVec
	DBQueryErrors       *prometheus.CounterVec

	// Business metrics
	IntentsProcessed  *prometheus.CounterVec
	IntentLatency     *prometheus.HistogramVec
	ScalingOperations *prometheus.CounterVec
	ScalingDuration   *prometheus.HistogramVec
}

Metrics holds all performance-related Prometheus metrics

func NewMetrics

func NewMetrics(registry *prometheus.Registry) *Metrics

NewMetrics creates and registers all performance metrics

func (*Metrics) RecordCacheEviction

func (m *Metrics) RecordCacheEviction(cacheName string)

RecordCacheEviction records a cache eviction

func (*Metrics) RecordCacheHit

func (m *Metrics) RecordCacheHit(cacheName string)

RecordCacheHit records a cache hit

func (*Metrics) RecordCacheMiss

func (m *Metrics) RecordCacheMiss(cacheName string)

RecordCacheMiss records a cache miss

func (*Metrics) RecordDBQuery

func (m *Metrics) RecordDBQuery(queryType, table string, duration time.Duration, err error)

RecordDBQuery records database query metrics

func (*Metrics) RecordIntentProcessing

func (m *Metrics) RecordIntentProcessing(intentType, status string, duration time.Duration)

RecordIntentProcessing records intent processing metrics

func (*Metrics) RecordJSONMarshal

func (m *Metrics) RecordJSONMarshal(duration time.Duration, err error)

RecordJSONMarshal records JSON marshaling performance

func (*Metrics) RecordJSONUnmarshal

func (m *Metrics) RecordJSONUnmarshal(duration time.Duration, err error)

RecordJSONUnmarshal records JSON unmarshaling performance

func (*Metrics) RecordRequestDuration

func (m *Metrics) RecordRequestDuration(method, endpoint, status string, duration time.Duration)

RecordRequestDuration records the duration of an HTTP request

func (*Metrics) RecordScalingOperation

func (m *Metrics) RecordScalingOperation(direction, resourceType, status string, duration time.Duration)

RecordScalingOperation records scaling operation metrics

func (*Metrics) UpdateCacheSize

func (m *Metrics) UpdateCacheSize(cacheName string, sizeBytes float64)

UpdateCacheSize updates the current cache size

type MetricsAnalyzer

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

MetricsAnalyzer provides metrics analysis capabilities

func NewMetricsAnalyzer

func NewMetricsAnalyzer() *MetricsAnalyzer

NewMetricsAnalyzer creates a new metrics analyzer

func (*MetricsAnalyzer) AddSample

func (ma *MetricsAnalyzer) AddSample(value float64)

AddSample adds a performance sample

func (*MetricsAnalyzer) CalculateAverage

func (ma *MetricsAnalyzer) CalculateAverage() float64

CalculateAverage calculates the average of collected samples (alias for GetAverage)

func (*MetricsAnalyzer) CalculatePercentile

func (ma *MetricsAnalyzer) CalculatePercentile(percentile float64) float64

CalculatePercentile calculates the specified percentile of collected samples

func (*MetricsAnalyzer) GetAverage

func (ma *MetricsAnalyzer) GetAverage() float64

GetAverage returns the average of collected samples

type MetricsData

type MetricsData struct {
	CPUUsagePercent float64
	MemoryUsageMB   float64
	HeapSizeMB      float64
	GoroutineCount  int
	GCCount         int
}

MetricsData contains performance metrics

type PerformanceIntegrator

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

PerformanceIntegrator provides performance integration capabilities

func NewPerformanceIntegrator

func NewPerformanceIntegrator(config *Config) *PerformanceIntegrator

NewPerformanceIntegrator creates a new performance integrator

func (*PerformanceIntegrator) GetAsyncProcessor

func (pi *PerformanceIntegrator) GetAsyncProcessor() *AsyncProcessor

GetAsyncProcessor returns an async processor instance

func (*PerformanceIntegrator) GetCacheManager

func (pi *PerformanceIntegrator) GetCacheManager() *CacheManager

GetCacheManager returns a cache manager instance

func (*PerformanceIntegrator) GetMonitor

func (pi *PerformanceIntegrator) GetMonitor() *PerformanceMonitor

GetMonitor returns a performance monitor

func (*PerformanceIntegrator) GetPerformanceReport

func (pi *PerformanceIntegrator) GetPerformanceReport() *PerformanceReport

GetPerformanceReport returns a performance report

func (*PerformanceIntegrator) GetProfiler

func (pi *PerformanceIntegrator) GetProfiler() *Profiler

GetProfiler returns a profiler instance

func (*PerformanceIntegrator) OptimizePerformance

func (pi *PerformanceIntegrator) OptimizePerformance() error

OptimizePerformance optimizes performance based on current metrics

func (*PerformanceIntegrator) RunBenchmark

func (pi *PerformanceIntegrator) RunBenchmark(ctx context.Context, name string, fn func()) time.Duration

RunBenchmark executes a performance benchmark

type PerformanceMonitor

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

PerformanceMonitor monitors performance metrics with 2025 features

func NewPerformanceMonitor

func NewPerformanceMonitor() *PerformanceMonitor

NewPerformanceMonitor creates a new performance monitor

func (*PerformanceMonitor) GetP95Latency

func (pm *PerformanceMonitor) GetP95Latency() time.Duration

GetP95Latency returns the 95th percentile latency

func (*PerformanceMonitor) GetP99Latency

func (pm *PerformanceMonitor) GetP99Latency() time.Duration

GetP99Latency returns the 99th percentile latency

func (*PerformanceMonitor) RecordLatency

func (pm *PerformanceMonitor) RecordLatency(latency time.Duration)

RecordLatency records a latency sample

type PerformanceReport

type PerformanceReport struct{}

PerformanceReport contains performance analysis

func (*PerformanceReport) Components

func (pr *PerformanceReport) Components() map[string]interface{}

Components returns component performance data

func (*PerformanceReport) Grade

func (pr *PerformanceReport) Grade() string

Grade returns the performance grade

func (*PerformanceReport) OverallScore

func (pr *PerformanceReport) OverallScore() float64

OverallScore returns the overall performance score

type Profiler

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

Profiler provides performance profiling capabilities

func NewProfiler

func NewProfiler() *Profiler

NewProfiler creates a new profiler

func (*Profiler) CaptureGoroutineProfile

func (p *Profiler) CaptureGoroutineProfile() (map[string]interface{}, error)

CaptureGoroutineProfile captures a goroutine profile

func (*Profiler) CaptureMemoryProfile

func (p *Profiler) CaptureMemoryProfile() (map[string]interface{}, error)

CaptureMemoryProfile captures a memory profile

func (*Profiler) DetectMemoryLeaks

func (p *Profiler) DetectMemoryLeaks() []*MemoryLeak

DetectMemoryLeaks detects potential memory leaks

func (*Profiler) GetMetrics

func (p *Profiler) GetMetrics() *MetricsData

GetMetrics returns performance metrics

func (*Profiler) Start

func (p *Profiler) Start()

Start begins profiling

func (*Profiler) Stop

func (p *Profiler) Stop() map[string]interface{}

Stop ends profiling and returns results

type ScalingMiddleware

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

ScalingMiddleware provides performance monitoring for scaling operations

func NewScalingMiddleware

func NewScalingMiddleware(metrics *Metrics) *ScalingMiddleware

NewScalingMiddleware creates a new scaling middleware for performance monitoring

func (*ScalingMiddleware) RecordScaling

func (m *ScalingMiddleware) RecordScaling(direction, resourceType string, fn func() error) error

RecordScaling records a scaling operation with performance tracking

type ScenarioStep

type ScenarioStep struct {
	Name    string        `json:"name"`
	Execute func() error  `json:"-"`
	Delay   time.Duration `json:"delay"`
}

ScenarioStep represents a single step in a telecom scenario.

type TelecomScenario

type TelecomScenario struct {
	Name        string         `json:"name"`
	Description string         `json:"description"`
	Steps       []ScenarioStep `json:"steps"`
}

TelecomScenario represents a telecom workload testing scenario.

Jump to

Keyboard shortcuts

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