Skip to content

fix(client): risk of resource leak and closing closed channel #208

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

Merged
merged 2 commits into from
Apr 25, 2025
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
31 changes: 22 additions & 9 deletions client/transport/stdio.go
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,14 @@ func (c *Stdio) Start(ctx context.Context) error {
// Close shuts down the stdio client, closing the stdin pipe and waiting for the subprocess to exit.
// Returns an error if there are issues closing stdin or waiting for the subprocess to terminate.
func (c *Stdio) Close() error {
select {
case <-c.done:
return nil
default:
}
// cancel all in-flight request
close(c.done)

if err := c.stdin.Close(); err != nil {
return fmt.Errorf("failed to close stdin: %w", err)
}
Expand Down Expand Up @@ -182,27 +189,33 @@ func (c *Stdio) SendRequest(
return nil, fmt.Errorf("stdio client not started")
}

// Create the complete request structure
responseChan := make(chan *JSONRPCResponse, 1)
c.mu.Lock()
c.responses[request.ID] = responseChan
c.mu.Unlock()

// Marshal request
requestBytes, err := json.Marshal(request)
if err != nil {
return nil, fmt.Errorf("failed to marshal request: %w", err)
}
requestBytes = append(requestBytes, '\n')

// Register response channel
responseChan := make(chan *JSONRPCResponse, 1)
c.mu.Lock()
c.responses[request.ID] = responseChan
c.mu.Unlock()
deleteResponseChan := func() {
c.mu.Lock()
delete(c.responses, request.ID)
c.mu.Unlock()
}

// Send request
if _, err := c.stdin.Write(requestBytes); err != nil {
deleteResponseChan()
return nil, fmt.Errorf("failed to write request: %w", err)
}

select {
case <-ctx.Done():
c.mu.Lock()
delete(c.responses, request.ID)
c.mu.Unlock()
deleteResponseChan()
return nil, ctx.Err()
case response := <-responseChan:
return response, nil
Expand Down