Skip to content

Commit

Permalink
fix(spanner): fix session leak (#3461)
Browse files Browse the repository at this point in the history
Fixed a problem where the session was not reused when a panic occurred.

Fixes #3460
  • Loading branch information
8398a7 committed Dec 16, 2020
1 parent 519bfb7 commit 11fb917
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 3 deletions.
8 changes: 5 additions & 3 deletions spanner/client.go
Expand Up @@ -451,6 +451,11 @@ func (c *Client) rwTransaction(ctx context.Context, f func(context.Context, *Rea
var (
sh *sessionHandle
)
defer func() {
if sh != nil {
sh.recycle()
}
}()
err = runWithRetryOnAbortedOrSessionNotFound(ctx, func(ctx context.Context) error {
var (
err error
Expand Down Expand Up @@ -480,9 +485,6 @@ func (c *Client) rwTransaction(ctx context.Context, f func(context.Context, *Rea
resp, err = t.runInTransaction(ctx, f)
return err
})
if sh != nil {
sh.recycle()
}
return resp, err
}

Expand Down
28 changes: 28 additions & 0 deletions spanner/client_test.go
Expand Up @@ -828,6 +828,34 @@ func TestClient_ReadWriteTransaction_Update_QueryOptions(t *testing.T) {
}
}

func TestClient_ReadWriteTransaction_DoNotLeakSessionOnPanic(t *testing.T) {
// Make sure that there is always only one session in the pool.
sc := SessionPoolConfig{
MinOpened: 1,
MaxOpened: 1,
}
_, client, teardown := setupMockedTestServerWithConfig(t, ClientConfig{SessionPoolConfig: sc})
defer teardown()
ctx := context.Background()

// If a panic occurs during a transaction, the session will not leak.
func() {
defer func() { recover() }()

_, err := client.ReadWriteTransaction(ctx, func(ctx context.Context, tx *ReadWriteTransaction) error {
panic("cause panic")
return nil
})
if err != nil {
t.Fatalf("Unexpected error during transaction: %v", err)
}
}()

if g, w := client.idleSessions.idleList.Len(), 1; g != w {
t.Fatalf("idle session count mismatch.\nGot: %v\nWant: %v", g, w)
}
}

func TestClient_SessionNotFound(t *testing.T) {
// Ensure we always have at least one session in the pool.
sc := SessionPoolConfig{
Expand Down

0 comments on commit 11fb917

Please sign in to comment.