| | package swo |
| |
|
| | import ( |
| | "context" |
| | "fmt" |
| | "sync" |
| |
|
| | "github.com/jackc/pgx/v5" |
| | "github.com/jackc/pgx/v5/pgxpool" |
| | "github.com/target/goalert/swo/swodb" |
| | "github.com/target/goalert/util/sqldrv" |
| | ) |
| |
|
| | |
| | |
| | |
| | |
| | |
| | func NewAppPGXPool(oldURL, nextURL string, maxOpen, maxIdle int) (*pgxpool.Pool, error) { |
| | cfg, err := pgxpool.ParseConfig(oldURL) |
| | if err != nil { |
| | return nil, fmt.Errorf("parse old URL: %w", err) |
| | } |
| | sqldrv.SetConfigRetries(cfg) |
| | cfg.MaxConns = int32(maxOpen) |
| | cfg.MinConns = int32(maxIdle) |
| |
|
| | nextCfg, err := pgxpool.ParseConfig(nextURL) |
| | if err != nil { |
| | return nil, fmt.Errorf("parse next URL: %w", err) |
| | } |
| | sqldrv.SetConfigRetries(nextCfg) |
| | nextCfg.MaxConns = int32(maxOpen) |
| | nextCfg.MinConns = int32(maxIdle) |
| |
|
| | var mx sync.Mutex |
| | var isDone bool |
| |
|
| | cfg.BeforeConnect = func(ctx context.Context, cfg *pgx.ConnConfig) error { |
| | mx.Lock() |
| | defer mx.Unlock() |
| |
|
| | if isDone { |
| | |
| | *cfg = *nextCfg.ConnConfig |
| | } |
| | return nil |
| | } |
| |
|
| | cfg.BeforeAcquire = func(ctx context.Context, conn *pgx.Conn) bool { |
| | useNext, err := swodb.New(conn).SWOConnLock(ctx) |
| | if err != nil { |
| | |
| | return false |
| | } |
| | if !useNext { |
| | return true |
| | } |
| |
|
| | |
| | mx.Lock() |
| | isDone = true |
| | mx.Unlock() |
| |
|
| | return false |
| | } |
| |
|
| | cfg.AfterRelease = func(conn *pgx.Conn) bool { |
| | err := swodb.New(conn).SWOConnUnlockAll(context.Background()) |
| | return err == nil |
| | } |
| |
|
| | return pgxpool.NewWithConfig(context.Background(), cfg) |
| | } |
| |
|