feat(platform): add postgres, redis, logging and graceful http serving
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
This commit is contained in:
1 parent
9662a3cea2
commit
1a6fadb030
6 files changed
+231
No files matched your search
@@ -0,0 +1,50 @@
|
|||||||
|
package platform
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"net/http"
|
||||||
|
"sync/atomic"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Probe func(context.Context) error
|
||||||
|
|
||||||
|
// Health separates liveness from readiness so a draining instance drops out
|
||||||
|
// of the load balancer before in-flight work is cancelled.
|
||||||
|
type Health struct {
|
||||||
|
probes map[string]Probe
|
||||||
|
draining atomic.Bool
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewHealth(probes map[string]Probe) *Health {
|
||||||
|
return &Health{probes: probes}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Health) Drain() { h.draining.Store(true) }
|
||||||
|
|
||||||
|
func (h *Health) Register(r gin.IRoutes) {
|
||||||
|
r.GET("/healthz", func(c *gin.Context) { c.Status(http.StatusNoContent) })
|
||||||
|
r.GET("/readyz", h.ready)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Health) ready(c *gin.Context) {
|
||||||
|
if h.draining.Load() {
|
||||||
|
c.JSON(http.StatusServiceUnavailable, gin.H{"status": "draining"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
ctx, cancel := context.WithTimeout(c.Request.Context(), 2*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
failed := gin.H{}
|
||||||
|
for name, p := range h.probes {
|
||||||
|
if err := p(ctx); err != nil {
|
||||||
|
failed[name] = err.Error()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(failed) > 0 {
|
||||||
|
c.JSON(http.StatusServiceUnavailable, gin.H{"status": "unready", "failed": failed})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusOK, gin.H{"status": "ready"})
|
||||||
|
}
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
package platform
|
||||||
|
|
||||||
|
import (
|
||||||
|
"log/slog"
|
||||||
|
"os"
|
||||||
|
|
||||||
|
"git.zb-server.de/ZB-Server/uptimesebi/internal/buildinfo"
|
||||||
|
"git.zb-server.de/ZB-Server/uptimesebi/internal/config"
|
||||||
|
)
|
||||||
|
|
||||||
|
func NewLogger(c config.Common, component string) *slog.Logger {
|
||||||
|
opts := &slog.HandlerOptions{Level: c.LogLevel}
|
||||||
|
var h slog.Handler
|
||||||
|
if c.LogFormat == "text" {
|
||||||
|
h = slog.NewTextHandler(os.Stderr, opts)
|
||||||
|
} else {
|
||||||
|
h = slog.NewJSONHandler(os.Stderr, opts)
|
||||||
|
}
|
||||||
|
return slog.New(h).With("component", component, "version", buildinfo.Version)
|
||||||
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
package platform
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"github.com/jackc/pgx/v5/pgxpool"
|
||||||
|
)
|
||||||
|
|
||||||
|
func OpenPostgres(ctx context.Context, url string) (*pgxpool.Pool, error) {
|
||||||
|
cfg, err := pgxpool.ParseConfig(url)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("postgres: %w", err)
|
||||||
|
}
|
||||||
|
pool, err := pgxpool.NewWithConfig(ctx, cfg)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("postgres: %w", err)
|
||||||
|
}
|
||||||
|
if err := pool.Ping(ctx); err != nil {
|
||||||
|
pool.Close()
|
||||||
|
return nil, fmt.Errorf("postgres: %w", err)
|
||||||
|
}
|
||||||
|
return pool, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
package platform
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"github.com/redis/go-redis/v9"
|
||||||
|
)
|
||||||
|
|
||||||
|
func OpenRedis(ctx context.Context, url string) (*redis.Client, error) {
|
||||||
|
opts, err := redis.ParseURL(url)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("redis: %w", err)
|
||||||
|
}
|
||||||
|
rdb := redis.NewClient(opts)
|
||||||
|
if err := rdb.Ping(ctx).Err(); err != nil {
|
||||||
|
_ = rdb.Close()
|
||||||
|
return nil, fmt.Errorf("redis: %w", err)
|
||||||
|
}
|
||||||
|
return rdb, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,72 @@
|
|||||||
|
package platform
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"log/slog"
|
||||||
|
"os"
|
||||||
|
"os/signal"
|
||||||
|
"syscall"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
"github.com/jackc/pgx/v5/pgxpool"
|
||||||
|
"github.com/redis/go-redis/v9"
|
||||||
|
|
||||||
|
"git.zb-server.de/ZB-Server/uptimesebi/internal/config"
|
||||||
|
"git.zb-server.de/ZB-Server/uptimesebi/internal/migrations"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Deps struct {
|
||||||
|
Log *slog.Logger
|
||||||
|
DB *pgxpool.Pool
|
||||||
|
Redis *redis.Client
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *Deps) Close() {
|
||||||
|
if d.DB != nil {
|
||||||
|
d.DB.Close()
|
||||||
|
}
|
||||||
|
if d.Redis != nil {
|
||||||
|
_ = d.Redis.Close()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *Deps) Probes() map[string]Probe {
|
||||||
|
return map[string]Probe{
|
||||||
|
"postgres": func(ctx context.Context) error { return d.DB.Ping(ctx) },
|
||||||
|
"redis": func(ctx context.Context) error { return d.Redis.Ping(ctx).Err() },
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func SignalContext() (context.Context, context.CancelFunc) {
|
||||||
|
return signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
||||||
|
}
|
||||||
|
|
||||||
|
func Connect(ctx context.Context, c config.Common, log *slog.Logger) (*Deps, error) {
|
||||||
|
if err := c.Validate(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
pending, err := migrations.Pending(ctx, c.DatabaseURL)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if pending {
|
||||||
|
return nil, fmt.Errorf("database schema is behind this release, run \"api migrate up\" first")
|
||||||
|
}
|
||||||
|
d := &Deps{Log: log}
|
||||||
|
if d.DB, err = OpenPostgres(ctx, c.DatabaseURL); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if d.Redis, err = OpenRedis(ctx, c.RedisURL); err != nil {
|
||||||
|
d.Close()
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return d, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewRouter() *gin.Engine {
|
||||||
|
gin.SetMode(gin.ReleaseMode)
|
||||||
|
r := gin.New()
|
||||||
|
r.Use(gin.Recovery())
|
||||||
|
return r
|
||||||
|
}
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
package platform
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"log/slog"
|
||||||
|
"net/http"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Serve blocks until ctx is cancelled, then marks the instance as draining,
|
||||||
|
// waits drainDelay for load balancers to notice and shuts down gracefully.
|
||||||
|
func Serve(ctx context.Context, log *slog.Logger, srv *http.Server, health *Health, drainDelay, timeout time.Duration) error {
|
||||||
|
errc := make(chan error, 1)
|
||||||
|
go func() {
|
||||||
|
log.Info("http listening", "addr", srv.Addr)
|
||||||
|
if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
|
||||||
|
errc <- err
|
||||||
|
}
|
||||||
|
close(errc)
|
||||||
|
}()
|
||||||
|
|
||||||
|
select {
|
||||||
|
case err := <-errc:
|
||||||
|
return err
|
||||||
|
case <-ctx.Done():
|
||||||
|
}
|
||||||
|
|
||||||
|
health.Drain()
|
||||||
|
time.Sleep(drainDelay)
|
||||||
|
|
||||||
|
sctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||||
|
defer cancel()
|
||||||
|
return srv.Shutdown(sctx)
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewHTTPServer(addr string, h http.Handler) *http.Server {
|
||||||
|
return &http.Server{
|
||||||
|
Addr: addr,
|
||||||
|
Handler: h,
|
||||||
|
ReadHeaderTimeout: 10 * time.Second,
|
||||||
|
IdleTimeout: 120 * time.Second,
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in new issue
Block a user