47 lines
1.2 KiB
Go
47 lines
1.2 KiB
Go
// Package database owns the PostgreSQL connection pool and schema migrations.
|
|
package database
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"time"
|
|
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
)
|
|
|
|
func Connect(ctx context.Context, url string, maxConns int32, wait time.Duration) (*pgxpool.Pool, error) {
|
|
cfg, err := pgxpool.ParseConfig(url)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("parse DATABASE_URL: %w", err)
|
|
}
|
|
|
|
cfg.MaxConns = maxConns
|
|
cfg.MinConns = 1
|
|
cfg.MaxConnLifetime = 30 * time.Minute
|
|
cfg.MaxConnIdleTime = 5 * time.Minute
|
|
cfg.HealthCheckPeriod = 30 * time.Second
|
|
cfg.ConnConfig.ConnectTimeout = 3 * time.Second
|
|
|
|
pool, err := pgxpool.NewWithConfig(ctx, cfg)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("create pool: %w", err)
|
|
}
|
|
|
|
// AGENT: Compose may start the API while PostgreSQL is still booting. A bounded
|
|
// retry keeps the container from crash-looping without hiding a permanent error.
|
|
deadline := time.Now().Add(wait)
|
|
for {
|
|
pingCtx, cancel := context.WithTimeout(ctx, 2*time.Second)
|
|
err = pool.Ping(pingCtx)
|
|
cancel()
|
|
if err == nil {
|
|
return pool, nil
|
|
}
|
|
if time.Now().After(deadline) || ctx.Err() != nil {
|
|
pool.Close()
|
|
return nil, fmt.Errorf("postgres is not reachable: %w", err)
|
|
}
|
|
time.Sleep(500 * time.Millisecond)
|
|
}
|
|
}
|