leader.go96 lines, 3.2 KB
| 1 | // Package jobs runs scheduled work, like a daily reconciliation, on exactly one |
| 2 | // replica of a service: the leader, elected with a Postgres advisory lock. |
| 3 | package jobs |
| 4 | |
| 5 | import ( |
| 6 | "context" |
| 7 | "fmt" |
| 8 | "log/slog" |
| 9 | "sync" |
| 10 | "time" |
| 11 | |
| 12 | "github.com/jackc/pgx/v5" |
| 13 | "github.com/prometheus/client_golang/prometheus" |
| 14 | "github.com/prometheus/client_golang/prometheus/promauto" |
| 15 | ) |
| 16 | |
| 17 | var leading = promauto.NewGauge(prometheus.GaugeOpts{ |
| 18 | Name: "jobs_leader", |
| 19 | Help: "1 while this replica leads, and runs the jobs. Summed over replicas: 1.", |
| 20 | }) |
| 21 | |
| 22 | // An Elector picks one leader among a service's replicas: the one whose |
| 23 | // database session holds an advisory lock. When that session ends, for any |
| 24 | // reason, Postgres releases the lock, and the next replica in line leads. |
| 25 | type Elector struct { |
| 26 | dsn string |
| 27 | lock string // replicas that use the same name compete |
| 28 | Retry time.Duration // how often the leader checks its session |
| 29 | logger *slog.Logger |
| 30 | } |
| 31 | |
| 32 | // NewElector returns an Elector for the lock called name, in the database at dsn. |
| 33 | func NewElector(dsn, lock string, logger *slog.Logger) *Elector { |
| 34 | return &Elector{dsn: dsn, lock: lock, Retry: 5 * time.Second, logger: logger} |
| 35 | } |
| 36 | |
| 37 | // Run calls lead whenever this replica becomes the leader, with a context |
| 38 | // that's cancelled when it stops being one. It returns when ctx is done. |
| 39 | func (e *Elector) Run(ctx context.Context, lead func(ctx context.Context)) { |
| 40 | for ctx.Err() == nil { |
| 41 | if err := e.campaign(ctx, lead); err != nil && ctx.Err() == nil { |
| 42 | e.logger.Warn("leader election", "lock", e.lock, "err", err) |
| 43 | } |
| 44 | select { |
| 45 | case <-ctx.Done(): |
| 46 | case <-time.After(e.Retry): // after an error: don't hammer the database |
| 47 | } |
| 48 | } |
| 49 | } |
| 50 | |
| 51 | // campaign waits for the lock on a connection of its own, then leads until |
| 52 | // ctx is done or the session is lost. |
| 53 | func (e *Elector) campaign(ctx context.Context, lead func(context.Context)) error { |
| 54 | // Not a connection from the pool: the pool would hand our session, and |
| 55 | // the lock with it, to whoever asks next. |
| 56 | conn, err := pgx.Connect(ctx, e.dsn) |
| 57 | if err != nil { |
| 58 | return err |
| 59 | } |
| 60 | // Closing the connection ends the session: Postgres releases the lock. |
| 61 | defer conn.Close(context.WithoutCancel(ctx)) |
| 62 | e.logger.Info("waiting to lead", "lock", e.lock) |
| 63 | // This waits while another session holds the lock, and returns the moment it's free. |
| 64 | if _, err := conn.Exec(ctx, "SELECT pg_advisory_lock(hashtext($1))", e.lock); err != nil { |
| 65 | return err |
| 66 | } |
| 67 | e.logger.Info("leading", "lock", e.lock) |
| 68 | leading.Set(1) |
| 69 | defer leading.Set(0) |
| 70 | |
| 71 | // Deferred calls run last first: stop the jobs, wait for them, and only |
| 72 | // then let the lock go. Two leaders never run jobs at the same time. |
| 73 | ctx, cancel := context.WithCancel(ctx) |
| 74 | var wg sync.WaitGroup |
| 75 | wg.Go(func() { lead(ctx) }) |
| 76 | defer wg.Wait() |
| 77 | defer cancel() |
| 78 | for { |
| 79 | select { |
| 80 | case <-ctx.Done(): |
| 81 | e.logger.Info("stepping down", "lock", e.lock) |
| 82 | return nil |
| 83 | case <-time.After(e.Retry): |
| 84 | } |
| 85 | if err := ping(ctx, conn, e.Retry); err != nil { |
| 86 | return fmt.Errorf("lost the session, and the lock: %w", err) |
| 87 | } |
| 88 | } |
| 89 | } |
| 90 | |
| 91 | // ping checks that conn's session is alive, within timeout. |
| 92 | func ping(ctx context.Context, conn *pgx.Conn, timeout time.Duration) error { |
| 93 | ctx, cancel := context.WithTimeout(ctx, timeout) |
| 94 | defer cancel() |
| 95 | return conn.Ping(ctx) |
| 96 | } |