Skip to content

Commit 385151c

Browse files
committed
agent/grpc: slightly refactor handler to reduce nesting
1 parent 6936b12 commit 385151c

File tree

2 files changed

+24
-17
lines changed

2 files changed

+24
-17
lines changed

pkg/agent/protocol/grpc/handler.go

Lines changed: 18 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -61,28 +61,29 @@ func (h *handler) streamHandler(_ interface{}, serverStream grpc.ServerStream) e
6161
if !ok {
6262
return status.Errorf(codes.Internal, "ServerTransportStream not exists in context")
6363
}
64+
6465
// full method name has the form /service/method, we want the service
6566
serviceName := strings.Split(fullMethodName, "/")[1]
66-
excluded := contains(h.disruption.Excluded, serviceName)
67-
if !excluded {
68-
if h.disruption.ErrorRate > 0 && rand.Float32() <= h.disruption.ErrorRate {
69-
h.metrics.Inc(protocol.MetricRequestsFaulted)
70-
return h.injectError(serverStream)
71-
}
67+
if contains(h.disruption.Excluded, serviceName) {
68+
h.metrics.Inc(protocol.MetricRequestsExcluded)
69+
return h.transparentForward(serverStream)
70+
}
7271

73-
// add delay
74-
if h.disruption.AverageDelay > 0 {
75-
h.metrics.Inc(protocol.MetricRequestsFaulted)
72+
if rand.Float32() < h.disruption.ErrorRate {
73+
h.metrics.Inc(protocol.MetricRequestsFaulted)
74+
return h.injectError(serverStream)
75+
}
7676

77-
delay := int64(h.disruption.AverageDelay)
78-
if h.disruption.DelayVariation > 0 {
79-
variation := int64(h.disruption.DelayVariation)
80-
delay = delay + variation - 2*rand.Int63n(variation)
81-
}
82-
time.Sleep(time.Duration(delay))
77+
// add delay
78+
if h.disruption.AverageDelay > 0 {
79+
h.metrics.Inc(protocol.MetricRequestsFaulted)
80+
81+
delay := int64(h.disruption.AverageDelay)
82+
if h.disruption.DelayVariation > 0 {
83+
variation := int64(h.disruption.DelayVariation)
84+
delay = delay + variation - 2*rand.Int63n(variation)
8385
}
84-
} else {
85-
h.metrics.Inc(protocol.MetricRequestsExcluded)
86+
time.Sleep(time.Duration(delay))
8687
}
8788

8889
return h.transparentForward(serverStream)

pkg/agent/protocol/protocol.go

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ package protocol
55

66
import (
77
"context"
8+
"errors"
89
"fmt"
910
"time"
1011

@@ -102,6 +103,11 @@ func (d *disruptor) Apply(ctx context.Context, duration time.Duration) error {
102103
return fmt.Errorf(" proxy ended with error: %w", err)
103104
}
104105
case <-time.After(duration):
106+
requests, hasMetric := d.proxy.Metrics()[MetricRequests]
107+
if hasMetric && requests == 0 {
108+
return errors.New("proxy did not intercept any request")
109+
}
110+
105111
return nil
106112
case <-ctx.Done():
107113
return ctx.Err()

0 commit comments

Comments
 (0)