Skip to content
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
24 changes: 24 additions & 0 deletions server/registry/internal/storage/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ package storage
import (
"context"
"fmt"
"time"

_ "github.com/GoogleCloudPlatform/cloudsql-proxy/proxy/dialers/postgres"
"github.com/apigee/registry/server/registry/internal/storage/models"
Expand Down Expand Up @@ -63,6 +64,11 @@ func NewClient(ctx context.Context, driver, dsn string) (*Client, error) {
c.close()
return nil, grpcErrorForDBError(ctx, err)
}
if err := applyConnectionLimits(db); err != nil {
c := &Client{db: db}
c.close()
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

FWIW, I find this to be a strange pattern we follow: Create a Client in order to call close() on it, which simply calls close() on the db we just constructed it on, only to then throw the client away.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good topic -- it looks like it's allowing us to keep the following code in one place:

	sqlDB, _ := c.db.DB()
	sqlDB.Close()

That could also be done with Client{db:db}.close()... or directly using the above code.

I don't have a strong preference. @seaneganx ?

return nil, grpcErrorForDBError(ctx, err)
}
return &Client{db: db}, nil
case "postgres", "cloudsqlpostgres":
db, err := gorm.Open(postgres.New(postgres.Config{
Expand All @@ -76,12 +82,30 @@ func NewClient(ctx context.Context, driver, dsn string) (*Client, error) {
c.close()
return nil, grpcErrorForDBError(ctx, err)
}
if err := applyConnectionLimits(db); err != nil {
c := &Client{db: db}
c.close()
return nil, grpcErrorForDBError(ctx, err)
}
return &Client{db: db}, nil
default:
return nil, fmt.Errorf("unsupported database %s", driver)
}
}

// Applies limits to concurrent connections.
// Could be made configurable.
func applyConnectionLimits(db *gorm.DB) error {
sqlDB, err := db.DB()
if err != nil {
return err
}
sqlDB.SetMaxOpenConns(10)
sqlDB.SetMaxIdleConns(10)
sqlDB.SetConnMaxLifetime(60 * time.Second)
return nil
}

// Close closes a database session.
func (c *Client) Close() {
c.close()
Expand Down