Skip to content

Commit

Permalink
Close the client connection after a read error
Browse files Browse the repository at this point in the history
The existing code doesn't `defer c.con.Close()` and exits early if reading encounters any error -- so `.Close()` is never called on the connection. This change stores any read and closing errors, `Join`ing them on return, ensuring that `.Close()` is always called.

I'm not 100% sure but I hope this will help prevent the half-closed client connections referenced from bluesky-social#21

There is probably a more idiomatic way to do this (i am a go noob) but if i understand `errors.Join` and the current code, I think this should keep pretty close to the current intended behavior for any caller.
  • Loading branch information
uniphil committed Nov 17, 2024
1 parent 0ab10bd commit ef6a5a0
Showing 1 changed file with 6 additions and 3 deletions.
9 changes: 6 additions & 3 deletions pkg/client/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package client

import (
"context"
"errors"
"fmt"
"log/slog"
"net/http"
Expand Down Expand Up @@ -121,15 +122,17 @@ func (c *Client) ConnectAndRead(ctx context.Context, cursor *int64) error {

c.con = con

var readErr = nil
if err := c.readLoop(ctx); err != nil {
return fmt.Errorf("read loop failed: %w", err)
readErr = fmt.Errorf("read loop failed: %w", err)
}

var closeErr = nil
if err := c.con.Close(); err != nil {
return fmt.Errorf("failed to close connection: %w", err)
closeErr = fmt.Errorf("failed to close connection: %w", err)
}

return nil
return errors.Join(readErr, closeErr)
}

func (c *Client) readLoop(ctx context.Context) error {
Expand Down

0 comments on commit ef6a5a0

Please sign in to comment.