Skip to content

Commit

Permalink
[v1.4.2] Introduce normalized latency distribution
Browse files Browse the repository at this point in the history
  • Loading branch information
troydai committed Nov 29, 2024
1 parent 56bf17f commit 3aa39d9
Show file tree
Hide file tree
Showing 3 changed files with 49 additions and 7 deletions.
24 changes: 24 additions & 0 deletions internal/http/math.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package http

import (
"math/rand"
"time"
)

type normalDistribution struct {
mean float64
stddev float64
}

func newNormalDistribution(mean, stddev uint64) *normalDistribution {
return &normalDistribution{mean: float64(mean), stddev: float64(stddev)}
}

func (n *normalDistribution) latency() time.Duration {
ms := n.mean + rand.NormFloat64()*n.stddev
if ms < 0 {
return 0
}

return time.Duration(ms) * time.Millisecond
}
30 changes: 23 additions & 7 deletions internal/http/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"log/slog"
"net/http"
"sync/atomic"
"time"

"go.uber.org/fx"

Expand All @@ -18,21 +19,36 @@ var Module = fx.Options(

func ProvideServer(s *settings.Values, l *slog.Logger) *Server {
return &Server{
counter: &atomic.Uint64{},
frequency: s.CrashFrequency,
logger: l,
counter: &atomic.Uint64{},
frequency: s.CrashFrequency,
logger: l,
latencyGen: newNormalDistribution(s.LatencyMean, s.LatencyStddev),
}
}

type Server struct {
counter *atomic.Uint64
frequency uint64
logger *slog.Logger
counter *atomic.Uint64
frequency uint64
logger *slog.Logger
latencyGen *normalDistribution
}

func (s *Server) HandleHTTP(w http.ResponseWriter, r *http.Request) {
s.logger.Info("inbound", "method", r.Method, "url", r.URL.Path, "host", r.Host, "proto", r.Proto, "agent", r.UserAgent(), "peer", r.RemoteAddr, "counter", s.counter.Load())
newCount := s.counter.Add(1)
latency := s.latencyGen.latency()

s.logger.Info("inbound",
"method", r.Method,
"url", r.URL.Path,
"host", r.Host,
"proto", r.Proto,
"agent", r.UserAgent(),
"peer", r.RemoteAddr,
"counter", newCount,
"latency", latency,
)

time.Sleep(s.latencyGen.latency())

if s.frequency != 0 && newCount%s.frequency == 0 {
s.logger.Warn("crash", "counter", newCount)
Expand Down
2 changes: 2 additions & 0 deletions internal/settings/settings.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ var Module = fx.Provide(ProvideSettings)

type Values struct {
CrashFrequency uint64 `env:"HTTP_CRASH_FREQUENCY" envDefault:"10"` // Set to zero to disable
LatencyMean uint64 `env:"HTTP_LATENCY_MEAN" envDefault:"50"`
LatencyStddev uint64 `env:"HTTP_LATENCY_STDDEV" envDefault:"25"`
}

func ProvideSettings() (*Values, error) {
Expand Down

0 comments on commit 3aa39d9

Please sign in to comment.