feat(web): initial implementation — server, mw, httputil, health (v1.0.0)
Introduces code.nochebuena.dev/einherjar/web — the HTTP transport layer of the
Einherjar framework. Absorbs httpserver, httpmw, and httputil from micro-lib,
replacing gorilla/mux with chi, adopting SecurityBag-native middleware, and
centralizing error handling through a single httputil.Error function.
server:
- Server interface — embeds lifecycle.Component and chi.Router
- Config struct (EINHERJAR_SERVER_* env vars); DefaultConfig
- New(logger, cfg, opts...) Server; WithMiddleware option
- Binds TCP synchronously in OnStart; logs "server: listening" on success
- Graceful shutdown within ShutdownTimeout on OnStop
mw:
- Recover — catches panics, returns 500, logs at Error
- RequestID — injects UUID v7 (UUID v4 fallback) into context and X-Request-ID header
- RequestLogger — structured access log per request
- CORS / CORSAllowAll — chi-based, applied only when origins non-empty
- IPRateLimit / UserRateLimit — pluggable RateLimiterStore interface
- InMemoryRateLimiterStore — token-bucket backed by golang.org/x/time/rate;
background goroutine evicts stale entries every 5 minutes
- StatusRecorder — wraps ResponseWriter to capture HTTP status code
httputil:
- Handle[Req, Res] / HandleNoBody[Res] / HandleEmpty[Req] — generic handler adapters
- Error(logger, w, r, err) — derives log level from status (≥500→Error, 4xx→Warn,
499→Info); writes standardized JSON body; logz enriches *xerrors.Err automatically
- JSON(w, status, v) / NoContent(w) — response helpers
- HandlerFunc adapter type
health:
- NewHandler / NewHandlerWithConfig — runs all Checkable checks concurrently;
returns JSON {status, components} with per-component latency and error
- Config struct (EINHERJAR_HEALTH_CHECK_TIMEOUT, default 5s)
Root factory:
- web.New(logger, cfg...) Server — composes Recover+RequestID+RequestLogger+CORS
in outermost-first order; CORS applied only when AllowedOrigins non-empty
- server.Server interface and web/server/identifiable.go: embeds observability.Identifiable;
ModulePath and ModuleVersion read via runtime/debug.ReadBuildInfo() — prints in launcher banner
This commit is contained in:
8
health/component_status.go
Normal file
8
health/component_status.go
Normal file
@@ -0,0 +1,8 @@
|
||||
package health
|
||||
|
||||
// ComponentStatus is the health state of a single component in the JSON response.
|
||||
type ComponentStatus struct {
|
||||
Status string `json:"status"`
|
||||
Latency string `json:"latency,omitempty"`
|
||||
Error string `json:"error,omitempty"`
|
||||
}
|
||||
11
health/config.go
Normal file
11
health/config.go
Normal file
@@ -0,0 +1,11 @@
|
||||
package health
|
||||
|
||||
import "time"
|
||||
|
||||
// Config configures the health check handler.
|
||||
// The zero value is valid — a 5-second check timeout is applied.
|
||||
type Config struct {
|
||||
CheckTimeout time.Duration `env:"EINHERJAR_HEALTH_CHECK_TIMEOUT" envDefault:"5s"`
|
||||
}
|
||||
|
||||
const defaultCheckTimeout = 5 * time.Second
|
||||
23
health/doc.go
Normal file
23
health/doc.go
Normal file
@@ -0,0 +1,23 @@
|
||||
// Package health provides a concurrent health check HTTP handler.
|
||||
//
|
||||
// The handler runs all registered checks in parallel, collects results within
|
||||
// a configurable timeout, and returns a structured JSON response. It maps
|
||||
// directly onto Kubernetes liveness and readiness probes.
|
||||
//
|
||||
// Components register themselves by implementing
|
||||
// [observability.Checkable] from einherjar/contracts — no adapter needed.
|
||||
//
|
||||
// - [observability.LevelCritical]: if DOWN, overall status is DOWN (503)
|
||||
// - [observability.LevelDegraded]: if DOWN, overall status is DEGRADED (200)
|
||||
//
|
||||
// # Example
|
||||
//
|
||||
// srv.Get("/health", health.NewHandler(logger, db, cache, storage))
|
||||
//
|
||||
// Or with custom timeout:
|
||||
//
|
||||
// srv.Get("/health", health.NewHandlerWithConfig(logger,
|
||||
// health.Config{CheckTimeout: 3 * time.Second},
|
||||
// db, cache,
|
||||
// ))
|
||||
package health
|
||||
102
health/handler.go
Normal file
102
health/handler.go
Normal file
@@ -0,0 +1,102 @@
|
||||
package health
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"code.nochebuena.dev/einherjar/contracts/logging"
|
||||
"code.nochebuena.dev/einherjar/contracts/observability"
|
||||
)
|
||||
|
||||
type checkResult struct {
|
||||
name string
|
||||
status ComponentStatus
|
||||
priority observability.Level
|
||||
}
|
||||
|
||||
type handler struct {
|
||||
logger logging.Logger
|
||||
checks []observability.Checkable
|
||||
timeout time.Duration
|
||||
}
|
||||
|
||||
// NewHandler returns an http.Handler for the health endpoint with default configuration.
|
||||
// Runs all checks concurrently within a 5-second timeout.
|
||||
// Returns 200 (UP / DEGRADED) or 503 (DOWN).
|
||||
func NewHandler(logger logging.Logger, checks ...observability.Checkable) http.Handler {
|
||||
return NewHandlerWithConfig(logger, Config{}, checks...)
|
||||
}
|
||||
|
||||
// NewHandlerWithConfig returns an http.Handler configured by cfg.
|
||||
// If cfg.CheckTimeout is zero the default (5 seconds) is applied.
|
||||
func NewHandlerWithConfig(logger logging.Logger, cfg Config, checks ...observability.Checkable) http.Handler {
|
||||
timeout := cfg.CheckTimeout
|
||||
if timeout == 0 {
|
||||
timeout = defaultCheckTimeout
|
||||
}
|
||||
return &handler{logger: logger, checks: checks, timeout: timeout}
|
||||
}
|
||||
|
||||
func (h *handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
reqLogger := h.logger.WithContext(r.Context())
|
||||
reqLogger.Debug("health: running checks", "count", len(h.checks))
|
||||
|
||||
ctx, cancel := context.WithTimeout(r.Context(), h.timeout)
|
||||
defer cancel()
|
||||
|
||||
resChan := make(chan checkResult, len(h.checks))
|
||||
for _, chk := range h.checks {
|
||||
go func(c observability.Checkable) {
|
||||
start := time.Now()
|
||||
err := c.HealthCheck(ctx)
|
||||
latency := time.Since(start).String()
|
||||
|
||||
status := "UP"
|
||||
errMsg := ""
|
||||
if err != nil {
|
||||
errMsg = err.Error()
|
||||
if c.Priority() == observability.LevelDegraded {
|
||||
status = "DEGRADED"
|
||||
} else {
|
||||
status = "DOWN"
|
||||
}
|
||||
}
|
||||
resChan <- checkResult{
|
||||
name: c.Name(),
|
||||
priority: c.Priority(),
|
||||
status: ComponentStatus{
|
||||
Status: status,
|
||||
Latency: latency,
|
||||
Error: errMsg,
|
||||
},
|
||||
}
|
||||
}(chk)
|
||||
}
|
||||
|
||||
overallStatus := "UP"
|
||||
httpStatus := http.StatusOK
|
||||
components := make(map[string]ComponentStatus, len(h.checks))
|
||||
|
||||
for range h.checks {
|
||||
res := <-resChan
|
||||
components[res.name] = res.status
|
||||
switch res.status.Status {
|
||||
case "DOWN":
|
||||
overallStatus = "DOWN"
|
||||
httpStatus = http.StatusServiceUnavailable
|
||||
case "DEGRADED":
|
||||
if overallStatus == "UP" {
|
||||
overallStatus = "DEGRADED"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
resp := Response{Status: overallStatus, Components: components}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(httpStatus)
|
||||
if err := json.NewEncoder(w).Encode(resp); err != nil {
|
||||
reqLogger.Error("health: failed to encode response", err)
|
||||
}
|
||||
}
|
||||
8
health/response.go
Normal file
8
health/response.go
Normal file
@@ -0,0 +1,8 @@
|
||||
package health
|
||||
|
||||
// Response is the JSON body returned by the health handler.
|
||||
// Status is one of "UP", "DEGRADED", or "DOWN".
|
||||
type Response struct {
|
||||
Status string `json:"status"`
|
||||
Components map[string]ComponentStatus `json:"components"`
|
||||
}
|
||||
Reference in New Issue
Block a user