Skip to content

Commit

Permalink
agent/grpc: slightly refactor handler to reduce nesting
Browse files Browse the repository at this point in the history
  • Loading branch information
nadiamoe committed Aug 17, 2023
1 parent 6936b12 commit 385151c
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 17 deletions.
35 changes: 18 additions & 17 deletions pkg/agent/protocol/grpc/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,28 +61,29 @@ func (h *handler) streamHandler(_ interface{}, serverStream grpc.ServerStream) e
if !ok {
return status.Errorf(codes.Internal, "ServerTransportStream not exists in context")
}

// full method name has the form /service/method, we want the service
serviceName := strings.Split(fullMethodName, "/")[1]
excluded := contains(h.disruption.Excluded, serviceName)
if !excluded {
if h.disruption.ErrorRate > 0 && rand.Float32() <= h.disruption.ErrorRate {
h.metrics.Inc(protocol.MetricRequestsFaulted)
return h.injectError(serverStream)
}
if contains(h.disruption.Excluded, serviceName) {
h.metrics.Inc(protocol.MetricRequestsExcluded)
return h.transparentForward(serverStream)
}

// add delay
if h.disruption.AverageDelay > 0 {
h.metrics.Inc(protocol.MetricRequestsFaulted)
if rand.Float32() < h.disruption.ErrorRate {
h.metrics.Inc(protocol.MetricRequestsFaulted)
return h.injectError(serverStream)
}

delay := int64(h.disruption.AverageDelay)
if h.disruption.DelayVariation > 0 {
variation := int64(h.disruption.DelayVariation)
delay = delay + variation - 2*rand.Int63n(variation)
}
time.Sleep(time.Duration(delay))
// add delay
if h.disruption.AverageDelay > 0 {
h.metrics.Inc(protocol.MetricRequestsFaulted)

delay := int64(h.disruption.AverageDelay)
if h.disruption.DelayVariation > 0 {
variation := int64(h.disruption.DelayVariation)
delay = delay + variation - 2*rand.Int63n(variation)
}
} else {
h.metrics.Inc(protocol.MetricRequestsExcluded)
time.Sleep(time.Duration(delay))
}

return h.transparentForward(serverStream)
Expand Down
6 changes: 6 additions & 0 deletions pkg/agent/protocol/protocol.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ package protocol

import (
"context"
"errors"
"fmt"
"time"

Expand Down Expand Up @@ -102,6 +103,11 @@ func (d *disruptor) Apply(ctx context.Context, duration time.Duration) error {
return fmt.Errorf(" proxy ended with error: %w", err)
}
case <-time.After(duration):
requests, hasMetric := d.proxy.Metrics()[MetricRequests]
if hasMetric && requests == 0 {
return errors.New("proxy did not intercept any request")
}

return nil
case <-ctx.Done():
return ctx.Err()
Expand Down

0 comments on commit 385151c

Please sign in to comment.