Skip to content

Commit

Permalink
feat: health checks need to consider DB health
Browse files Browse the repository at this point in the history
Closes #831
  • Loading branch information
aeneasr committed Jul 24, 2023
1 parent 782cbde commit 6a497be
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 0 deletions.
33 changes: 33 additions & 0 deletions internal/driver/registry_default.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ var (
type (
RegistryDefault struct {
p persistence.Persister
migrationStatus popx.MigrationStatuses
traverser relationtuple.Traverser
mb *popx.MigrationBox
extraMigrations []fs.FS
Expand Down Expand Up @@ -127,6 +128,38 @@ func (r *RegistryDefault) HealthHandler() *healthx.Handler {
if r.healthReadyCheckers == nil {
r.healthReadyCheckers = healthx.ReadyCheckers{}
}

if _, found := r.healthReadyCheckers["database"]; !found {
r.healthReadyCheckers["database"] = func(_ *http.Request) error {
return r.p.Ping()
}
}

if _, found := r.healthReadyCheckers["migrations"]; !found {
r.healthReadyCheckers["migrations"] = func(req *http.Request) error {
if r.migrationStatus != nil && !r.migrationStatus.HasPending() {
return nil
}

mb, err := r.MigrationBox(req.Context())
if err != nil {
return err
}

status, err := mb.Status(req.Context())
if err != nil {
return err
}

if status.HasPending() {
return errors.Errorf("migrations have not yet been fully applied")
}

r.migrationStatus = status
return nil
}
}

r.healthH = healthx.NewHandler(r.Writer(), config.Version, r.healthReadyCheckers)
}

Expand Down
2 changes: 2 additions & 0 deletions internal/persistence/definitions.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ type (
Connection(ctx context.Context) *pop.Connection
NetworkID(ctx context.Context) uuid.UUID
Transaction(ctx context.Context, f func(ctx context.Context) error) error

Ping() error
}
Migrator interface {
MigrationBox(ctx context.Context) (*popx.MigrationBox, error)
Expand Down
9 changes: 9 additions & 0 deletions internal/persistence/sql/persister.go
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,15 @@ func (p *Persister) Connection(ctx context.Context) *pop.Connection {
return popx.GetConnection(ctx, p.conn.WithContext(ctx))
}

func (p *Persister) Ping() error {
type pinger interface {
Ping() error
}

// This can not be contextualized because of some gobuffalo/pop limitations.
return errors.WithStack(p.conn.Store.(pinger).Ping())
}

func (p *Persister) createWithNetwork(ctx context.Context, v interface{}) (err error) {
ctx, span := p.d.Tracer(ctx).Tracer().Start(ctx, "persistence.sql.createWithNetwork")
defer otelx.End(span, &err)
Expand Down

0 comments on commit 6a497be

Please sign in to comment.