Skip to content

Commit

Permalink
Fix "concurrent map iteration and map write" while read estransport.M…
Browse files Browse the repository at this point in the history
…etrics.Responses
  • Loading branch information
mainliufeng committed Jan 14, 2022
1 parent 17a0dc1 commit 2373456
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 1 deletion.
34 changes: 34 additions & 0 deletions estransport/estransport_internal_test.go
Expand Up @@ -1109,3 +1109,37 @@ func TestRequestCompression(t *testing.T) {
})
}
}

func TestTransportPerformAndReadMetricsResponses(t *testing.T) {
t.Run("Read Metrics.Responses", func(t *testing.T) {
u, _ := url.Parse("https://foo.com/bar")
tp, _ := New(Config{
EnableMetrics: true,
URLs: []*url.URL{u},
Transport: &mockTransp{
RoundTripFunc: func(req *http.Request) (*http.Response, error) { return &http.Response{Status: "MOCK"}, nil },
}})

ch := make(chan struct{})
go func() {
for {
select {
case <-ch:
break
default:
metrics, _ := tp.Metrics()
for range metrics.Responses {
}
}
}
}()

for i := 0; i < 100000; i++ {
req, _ := http.NewRequest("GET", "/abc", nil)
_, _ = tp.Perform(req)
}

ch <- struct{}{}
close(ch)
})
}
6 changes: 5 additions & 1 deletion estransport/metrics.go
Expand Up @@ -92,7 +92,11 @@ func (c *Client) Metrics() (Metrics, error) {
m := Metrics{
Requests: c.metrics.requests,
Failures: c.metrics.failures,
Responses: c.metrics.responses,
Responses: make(map[int]int, len(c.metrics.responses)),
}

for code, num := range c.metrics.responses {
m.Responses[code] = num
}

if pool, ok := c.pool.(connectionable); ok {
Expand Down

0 comments on commit 2373456

Please sign in to comment.