File size: 1,751 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
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"
)

// NewAppPGXPool returns a pgxpool.Pool that will use the old database until the
// switchover_state table indicates that the new database should be used.
//
// Until the switchover is complete, the old database will be protected with a
// shared advisory lock (4369).
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 {
			// switched, use new config
			*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 {
			// error, don't use
			return false
		}
		if !useNext {
			return true
		}

		// switch to new config, don't use this connection
		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)
}