Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

shared client: fix memory leak and add fail-safe mechanism #10

Merged
merged 2 commits into from
Apr 11, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 18 additions & 2 deletions shared_client.go
Original file line number Diff line number Diff line change
Expand Up @@ -227,6 +227,17 @@ func handler(wg *sync.WaitGroup, client *Client, conn *Conn, requests chan reque
return
}
start := time.Now()

// Check if we already have a request with the same id
// Due to birthday paradox and the fact that ID is uint16
// it's likely to happen with small number (~200) of concurrent requests
// which would result in goroutine leak as we would never close req.ch
if _, ok := waitingResponses[req.msg.Id]; ok {
req.ch <- sharedClientResponse{nil, 0, fmt.Errorf("duplicate request id %d", req.msg.Id)}
close(req.ch)
continue
}

err := client.SendContext(req.ctx, req.msg, conn, start)
if err != nil {
req.ch <- sharedClientResponse{nil, 0, err}
Expand Down Expand Up @@ -291,8 +302,13 @@ func (c *SharedClient) ExchangeSharedContext(ctx context.Context, m *Msg) (r *Ms
}

// Since c.requests is unbuffered, the handler is guaranteed to eventually close 'respCh'
resp := <-respCh
return resp.msg, resp.rtt, resp.err
select {
case resp := <-respCh:
return resp.msg, resp.rtt, resp.err
// This is just fail-safe mechanism in case there is another similar issue
case <-time.After(time.Minute):
return nil, 0, fmt.Errorf("timeout waiting for response")
}
}

// close closes and waits for the close to finish.
Expand Down
Loading