Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

MustPing now accepts duration. ShouldPing added. #59

Open
wants to merge 1 commit into
base: v1
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 33 additions & 4 deletions sqlx-runner/init.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package runner

import (
"database/sql"
"fmt"
"time"

"github.com/cenkalti/backoff"
Expand Down Expand Up @@ -34,10 +35,38 @@ func SetCache(store kvs.KeyValueStore) {
}

// MustPing pings a database with an exponential backoff. The
// function panics if the database cannot be pinged after 15 minutes
func MustPing(db *sql.DB) {
// function panics if the database cannot be pinged after the specified duration.
// If no duration is specified it defaults to 15 minutes.
func MustPing(db *sql.DB, timeoutOrNil ...time.Duration) {
var timeout time.Duration
if len(timeoutOrNil) > 0 {
timeout = timeoutOrNil[0]
}

err := pingDB(db, timeout)
if err != nil {
panic(err.Error())
}
}

// ShouldPing pings a database with an exponential backoff. The
// function returns an error if the database cannot be pinged after the specified duration.
// If no duration is specified it defaults to 15 minutes.
func ShouldPing(db *sql.DB, timeoutOrNil ...time.Duration) error {
var timeout time.Duration
if len(timeoutOrNil) > 0 {
timeout = timeoutOrNil[0]
}

return pingDB(db, timeout)
}

func pingDB(db *sql.DB, timeout time.Duration) error {
var err error
b := backoff.NewExponentialBackOff()
if timeout > 0 {
b.MaxElapsedTime = timeout
}
ticker := backoff.NewTicker(b)

// Ticks will continue to arrive when the previous operation is still running,
Expand All @@ -49,8 +78,8 @@ func MustPing(db *sql.DB) {
}

ticker.Stop()
return
return nil
}

panic("Could not ping database!")
return fmt.Errorf("Could not ping database!")
}