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:
2026-05-29 15:48:11 +00:00
commit c4ef1948f6
38 changed files with 3095 additions and 0 deletions

60
mw/cors.go Normal file
View File

@@ -0,0 +1,60 @@
package mw
import "net/http"
const (
allowedMethods = "GET, HEAD, PUT, PATCH, POST, DELETE, OPTIONS"
allowedHeaders = "Content-Type, Authorization, X-Request-ID"
)
// CORS sets cross-origin resource sharing headers for the provided origins.
// Returns 204 No Content for OPTIONS preflight requests.
// Pass the outermost origins first; an empty slice is a no-op.
func CORS(origins []string) func(http.Handler) http.Handler {
originSet := make(map[string]struct{}, len(origins))
for _, o := range origins {
originSet[o] = struct{}{}
}
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
origin := r.Header.Get("Origin")
if origin != "" {
if _, allowed := originSet[origin]; allowed {
w.Header().Set("Access-Control-Allow-Origin", origin)
w.Header().Set("Access-Control-Allow-Methods", allowedMethods)
w.Header().Set("Access-Control-Allow-Headers", allowedHeaders)
w.Header().Set("Access-Control-Allow-Credentials", "true")
w.Header().Set("Vary", "Origin")
}
}
if r.Method == http.MethodOptions {
w.WriteHeader(http.StatusNoContent)
return
}
next.ServeHTTP(w, r)
})
}
}
// CORSAllowAll is a convenience wrapper that allows any origin.
// Use only in development — never in production.
func CORSAllowAll() func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
origin := r.Header.Get("Origin")
if origin == "" {
origin = "*"
}
w.Header().Set("Access-Control-Allow-Origin", origin)
w.Header().Set("Access-Control-Allow-Methods", allowedMethods)
w.Header().Set("Access-Control-Allow-Headers", allowedHeaders)
w.Header().Set("Vary", "Origin")
if r.Method == http.MethodOptions {
w.WriteHeader(http.StatusNoContent)
return
}
next.ServeHTTP(w, r)
})
}
}

24
mw/doc.go Normal file
View File

@@ -0,0 +1,24 @@
// Package mw provides transport-level HTTP middleware for Einherjar services.
//
// All middleware functions return func(http.Handler) http.Handler and are
// composed via [server.WithMiddleware] or chi's Use method.
//
// # Recommended middleware order (outermost first)
//
// server.WithMiddleware(
// mw.Recover(),
// mw.RequestID(uuid.NewString),
// mw.RequestLogger(logger),
// mw.CORS([]string{"https://example.com"}),
// )
//
// # Rate limiting
//
// // In-memory (default — no extra dependencies)
// store := mw.NewInMemoryRateLimiterStore(100, 20)
// srv.Use(mw.IPRateLimit(store, logger))
//
// // Distributed — swap store, middleware unchanged
// store := valkeymw.NewRateLimiterStore(client, 100, 20)
// srv.Use(mw.IPRateLimit(store, logger))
package mw

View File

@@ -0,0 +1,71 @@
package mw
import (
"context"
"sync"
"time"
"golang.org/x/time/rate"
)
var _ RateLimiterStore = (*InMemoryRateLimiterStore)(nil)
const inMemoryCleanupInterval = 5 * time.Minute
type limiterEntry struct {
limiter *rate.Limiter
lastSeen time.Time
}
// InMemoryRateLimiterStore is a per-key token-bucket rate limiter backed by
// an in-memory map. Suitable for single-instance deployments or development.
// For distributed rate limiting implement [RateLimiterStore] with a Valkey or
// Redis backend and pass it to [IPRateLimit] or [UserRateLimit] instead.
//
// Stale entries are evicted every 5 minutes by a background goroutine.
// [Allow] always returns a nil error — in-memory never has infrastructure failures.
type InMemoryRateLimiterStore struct {
mu sync.Map
rps rate.Limit
burst int
}
// NewInMemoryRateLimiterStore creates a per-key token bucket store.
// rps is the sustained request rate per second per key.
// burst is the maximum instantaneous burst per key.
func NewInMemoryRateLimiterStore(rps float64, burst int) *InMemoryRateLimiterStore {
s := &InMemoryRateLimiterStore{
rps: rate.Limit(rps),
burst: burst,
}
go s.cleanupLoop()
return s
}
// Allow returns true when the request for key is within the configured rate limit.
func (s *InMemoryRateLimiterStore) Allow(_ context.Context, key string) (bool, error) {
now := time.Now()
v, _ := s.mu.LoadOrStore(key, &limiterEntry{
limiter: rate.NewLimiter(s.rps, s.burst),
lastSeen: now,
})
e := v.(*limiterEntry)
e.lastSeen = now
return e.limiter.Allow(), nil
}
// cleanupLoop runs for the lifetime of the process; it stops only when the process exits.
// This is intentional: InMemoryRateLimiterStore is stateless from a lifecycle perspective.
func (s *InMemoryRateLimiterStore) cleanupLoop() {
ticker := time.NewTicker(inMemoryCleanupInterval)
defer ticker.Stop()
for range ticker.C {
cutoff := time.Now().Add(-inMemoryCleanupInterval)
s.mu.Range(func(k, v any) bool {
if v.(*limiterEntry).lastSeen.Before(cutoff) {
s.mu.Delete(k)
}
return true
})
}
}

27
mw/logger.go Normal file
View File

@@ -0,0 +1,27 @@
package mw
import (
"net/http"
"time"
"code.nochebuena.dev/einherjar/contracts/logging"
)
// RequestLogger logs each request after the handler returns, including method,
// path, status code, and latency. Uses [StatusRecorder] to capture the status.
// Place after [RequestID] so the request ID is available in the log record.
func RequestLogger(logger logging.Logger) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
rec := &StatusRecorder{ResponseWriter: w, Status: http.StatusOK}
next.ServeHTTP(rec, r)
logger.WithContext(r.Context()).Info("request",
"method", r.Method,
"path", r.URL.Path,
"status", rec.Status,
"latency", time.Since(start).String(),
)
})
}
}

73
mw/rate_limit.go Normal file
View File

@@ -0,0 +1,73 @@
package mw
import (
"encoding/json"
"net/http"
"strings"
"code.nochebuena.dev/einherjar/contracts/logging"
"code.nochebuena.dev/einherjar/contracts/security"
)
// IPRateLimit returns middleware that rate-limits requests by client IP address.
// The IP is extracted from X-Forwarded-For (first value) or RemoteAddr.
// When the store returns an error the middleware fails open: the error is logged
// and the request is allowed through.
func IPRateLimit(store RateLimiterStore, logger logging.Logger) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
key := clientIP(r)
ok, err := store.Allow(r.Context(), key)
if err != nil {
logger.WithContext(r.Context()).Warn("rate_limit: store error, failing open", "err", err.Error())
} else if !ok {
rateLimitExceeded(w)
return
}
next.ServeHTTP(w, r)
})
}
}
// UserRateLimit returns middleware that rate-limits by authenticated user ID.
// Falls back to client IP when no [security.Identity] is present in the context.
// When the store returns an error the middleware fails open.
func UserRateLimit(store RateLimiterStore, logger logging.Logger) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
key := clientIP(r)
if id, ok := security.FromContext(r.Context()); ok && id.UID != "" {
key = id.UID
}
ok, err := store.Allow(r.Context(), key)
if err != nil {
logger.WithContext(r.Context()).Warn("rate_limit: store error, failing open", "err", err.Error())
} else if !ok {
rateLimitExceeded(w)
return
}
next.ServeHTTP(w, r)
})
}
}
func clientIP(r *http.Request) string {
if fwd := r.Header.Get("X-Forwarded-For"); fwd != "" {
parts := strings.SplitN(fwd, ",", 2)
return strings.TrimSpace(parts[0])
}
addr := r.RemoteAddr
if i := strings.LastIndex(addr, ":"); i >= 0 {
return addr[:i]
}
return addr
}
func rateLimitExceeded(w http.ResponseWriter) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusTooManyRequests)
_ = json.NewEncoder(w).Encode(map[string]string{
"code": "RESOURCE_EXHAUSTED",
"message": "too many requests",
})
}

17
mw/rate_limiter_store.go Normal file
View File

@@ -0,0 +1,17 @@
package mw
import "context"
// RateLimiterStore is the pluggable backend for rate-limiting middleware.
// The key is determined by the caller (client IP or user ID).
//
// Shipped implementations:
// - [InMemoryRateLimiterStore] — per-key token bucket, stdlib only (this package)
// - einherjar/cache-valkey — Valkey-backed store for distributed deployments
//
// cache-valkey satisfies this interface via Go duck typing — it never imports web/mw.
type RateLimiterStore interface {
// Allow returns true when the request for the given key is within the rate limit.
// A non-nil error means the store is temporarily unavailable; middleware fails open.
Allow(ctx context.Context, key string) (bool, error)
}

27
mw/recover.go Normal file
View File

@@ -0,0 +1,27 @@
package mw
import (
"net/http"
"runtime/debug"
"code.nochebuena.dev/einherjar/contracts/logging"
)
// Recover catches panics in downstream handlers, writes a 500 response, and
// logs the recovered value with a stack trace. Place it as the outermost middleware.
func Recover(logger logging.Logger) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer func() {
if rec := recover(); rec != nil {
logger.WithContext(r.Context()).Error("recover: panic", nil,
"panic", rec,
"stack", string(debug.Stack()),
)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
}
}()
next.ServeHTTP(w, r)
})
}
}

22
mw/requestid.go Normal file
View File

@@ -0,0 +1,22 @@
package mw
import (
"net/http"
"code.nochebuena.dev/einherjar/core/logz"
)
// RequestID injects a unique request ID into the context (via [logz.WithRequestID])
// and sets the X-Request-ID response header.
// generator is called once per request — pass uuid.NewString or a custom function.
func RequestID(generator func() string) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
id := generator()
ctx := logz.WithRequestID(r.Context(), id)
r = r.WithContext(ctx)
w.Header().Set("X-Request-ID", id)
next.ServeHTTP(w, r)
})
}
}

16
mw/status_recorder.go Normal file
View File

@@ -0,0 +1,16 @@
package mw
import "net/http"
// StatusRecorder wraps http.ResponseWriter to capture the written status code.
// Used by [RequestLogger] to log the response status after the handler returns.
type StatusRecorder struct {
http.ResponseWriter
Status int
}
// WriteHeader captures the status code and delegates to the underlying writer.
func (r *StatusRecorder) WriteHeader(code int) {
r.Status = code
r.ResponseWriter.WriteHeader(code)
}