diff --git a/config/dev.yml b/config/dev.yml index 8ef942a..20ec306 100644 --- a/config/dev.yml +++ b/config/dev.yml @@ -97,6 +97,8 @@ database: # Enable this if you need the user id in triggers, etc set_user_id: false + ping_timeout: 1m + # Define additional variables here to be used with filters variables: admin_account_id: "5" diff --git a/config/prod.yml b/config/prod.yml index 674a8b4..403872a 100644 --- a/config/prod.yml +++ b/config/prod.yml @@ -54,4 +54,6 @@ database: # Set session variable "user.id" to the user id # Enable this if you need the user id in triggers, etc - set_user_id: false \ No newline at end of file + set_user_id: false + + ping_timeout: 5m diff --git a/serv/config.go b/serv/config.go index 4c1b53e..3663646 100644 --- a/serv/config.go +++ b/serv/config.go @@ -5,6 +5,7 @@ import ( "os" "regexp" "strings" + "time" "unicode" "github.com/gobuffalo/flect" @@ -57,16 +58,17 @@ type config struct { } DB struct { - Type string - Host string - Port uint16 - DBName string - User string - Password string - Schema string - PoolSize int32 `mapstructure:"pool_size"` - MaxRetries int `mapstructure:"max_retries"` - SetUserID bool `mapstructure:"set_user_id"` + Type string + Host string + Port uint16 + DBName string + User string + Password string + Schema string + PoolSize int32 `mapstructure:"pool_size"` + MaxRetries int `mapstructure:"max_retries"` + SetUserID bool `mapstructure:"set_user_id"` + PingTimeout time.Duration `mapstructure:"ping_timeout"` Vars map[string]string `mapstructure:"variables"` Blocklist []string diff --git a/serv/health.go b/serv/health.go new file mode 100644 index 0000000..0742e97 --- /dev/null +++ b/serv/health.go @@ -0,0 +1,30 @@ +package serv + +import ( + "context" + "net/http" +) + +var healthyResponse = []byte("All's Well") + +func health(w http.ResponseWriter, _ *http.Request) { + conn, err := db.Acquire(context.Background()) + if err != nil { + errlog.Error().Err(err).Msg("error acquiring connection from pool") + w.WriteHeader(http.StatusInternalServerError) + return + } + + ctx, _ := context.WithTimeout(context.Background(), conf.DB.PingTimeout) + if err := conn.Conn().Ping(ctx); err != nil { + errlog.Error().Err(err).Msg("error pinging database") + w.WriteHeader(http.StatusInternalServerError) + return + } + + if _, err := w.Write(healthyResponse); err != nil { + errlog.Error().Err(err).Msg("error writing healthy response") + w.WriteHeader(http.StatusInternalServerError) + return + } +} diff --git a/serv/serv.go b/serv/serv.go index 08d58f4..a4cc5bf 100644 --- a/serv/serv.go +++ b/serv/serv.go @@ -123,6 +123,8 @@ func startHTTP() { func routeHandler() http.Handler { mux := http.NewServeMux() + mux.Handle("/health", http.HandlerFunc(health)) + mux.Handle("/api/v1/graphql", withAuth(apiv1Http)) if conf.WebUI {