Skip to content

Commit

Permalink
Fix context cancelled error after client close
Browse files Browse the repository at this point in the history
No longer set client error from the receiver goroutine when the client
context is closed. The client context is cancelled when the client is
closed, so the receiver goroutine can stop handling messages. The client
error will be set the next dispatch.

Signed-off-by: Austin Vazquez <[email protected]>
  • Loading branch information
austinvazquez committed Feb 29, 2024
1 parent 20c493e commit d2a448c
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 1 deletion.
3 changes: 2 additions & 1 deletion client.go
Original file line number Diff line number Diff line change
Expand Up @@ -264,6 +264,7 @@ func (c *Client) run() {
for {
select {
case <-c.ctx.Done():
// The client has been closed, so the sender goroutine can now be stopped.
return
case call := <-c.calls:
id := streamID
Expand All @@ -288,7 +289,7 @@ func (c *Client) run() {
for {
select {
case <-c.ctx.Done():
c.setError(c.ctx.Err())
// The client has been closed, so the receiver goroutine can now be stopped.
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 d2a448c

Please sign in to comment.