Skip to content

Commit

Permalink
Fix context cancelled error after client close
Browse files Browse the repository at this point in the history
Sets the client error to ErrClosed when the client is closed and the
inner error is gets set by receive server response go routine.

Signed-off-by: Austin Vazquez <[email protected]>
  • Loading branch information
austinvazquez committed Feb 28, 2024
1 parent 20c493e commit 57a8d60
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 1 deletion.
4 changes: 3 additions & 1 deletion client.go
Original file line number Diff line number Diff line change
Expand Up @@ -288,7 +288,9 @@ func (c *Client) run() {
for {
select {
case <-c.ctx.Done():
c.setError(c.ctx.Err())
// c.ctx has no deadline and is cancelled on client close,
// so set error to closed instead of context cancelled.
c.setError(ErrClosed)
return
default:
mh, p, err := c.channel.recv()
Expand Down
32 changes: 32 additions & 0 deletions client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,3 +68,35 @@ func TestUserOnCloseWait(t *testing.T) {
t.Fatalf("expected error nil , but got %v", err)
}
}

func TestClientReturnsErrClosedAfterClose(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
server := mustServer(t)(NewServer())
testService := &testingServer{}
addr, listener := newTestListener(t)

registerTestingService(server, testService)
go server.Serve(ctx, listener)

t.Cleanup(func() {
server.Shutdown(ctx)
listener.Close()
cancel()
})

client, cleanup := newTestClient(t, addr)
testClient := newTestingClient(client)

t.Cleanup(func() {
cleanup()
})

err := client.Close()
if err != nil {
t.Errorf("Expected nil error on client close, received %v", err)
}

if _, err := testClient.Test(ctx, &testPayload{}); err != ErrClosed {
t.Errorf("Expected ErrClosed after connection has been closed, got %v", err)
}
}

0 comments on commit 57a8d60

Please sign in to comment.