feat(epic1): implement core infrastructure (stories 1.1-1.5)
Implemented Epic 1 core kernel and infrastructure stories: Story 1.1: Enhanced DI Container - Added providers for database, health, metrics, and error bus - Extended CoreModule to include all core services Story 1.2: Database Layer with Ent ORM - Created Ent schema for User, Role, Permission, AuditLog entities - Implemented many-to-many relationships (User-Role, Role-Permission) - Created database client wrapper with connection pooling - Added database provider to DI container with migration support Story 1.3: Health Monitoring and Metrics System - Implemented health check registry and interface - Added database health checker - Created Prometheus metrics system with HTTP instrumentation - Added health and metrics providers to DI container Story 1.4: Error Handling and Error Bus - Implemented channel-based error bus - Created ErrorPublisher interface - Added error bus provider with lifecycle management Story 1.5: HTTP Server Foundation - Created HTTP server with Gin framework - Implemented comprehensive middleware stack: - Request ID generation - Structured logging - Panic recovery with error bus integration - Prometheus metrics collection - CORS support - Registered core routes: /healthz, /ready, /metrics - Integrated with FX lifecycle for graceful shutdown All components are integrated via DI container and ready for use.
This commit is contained in:
141
internal/server/middleware.go
Normal file
141
internal/server/middleware.go
Normal file
@@ -0,0 +1,141 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"runtime"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
"git.dcentral.systems/toolz/goplt/pkg/errorbus"
|
||||
"git.dcentral.systems/toolz/goplt/pkg/logger"
|
||||
)
|
||||
|
||||
const (
|
||||
requestIDKey = "request_id"
|
||||
userIDKey = "user_id"
|
||||
)
|
||||
|
||||
// RequestIDMiddleware generates a unique request ID for each request.
|
||||
func RequestIDMiddleware() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
requestID := c.GetHeader("X-Request-ID")
|
||||
if requestID == "" {
|
||||
requestID = uuid.New().String()
|
||||
}
|
||||
|
||||
c.Set(requestIDKey, requestID)
|
||||
c.Header("X-Request-ID", requestID)
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
// LoggingMiddleware logs all HTTP requests with structured logging.
|
||||
func LoggingMiddleware(log logger.Logger) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
start := time.Now()
|
||||
path := c.Request.URL.Path
|
||||
method := c.Request.Method
|
||||
|
||||
// Process request
|
||||
c.Next()
|
||||
|
||||
// Calculate duration
|
||||
duration := time.Since(start)
|
||||
|
||||
// Get request ID from context
|
||||
requestID, _ := c.Get(requestIDKey)
|
||||
requestIDStr := ""
|
||||
if id, ok := requestID.(string); ok {
|
||||
requestIDStr = id
|
||||
}
|
||||
|
||||
// Log request
|
||||
log.Info("HTTP request",
|
||||
logger.String("method", method),
|
||||
logger.String("path", path),
|
||||
logger.Int("status", c.Writer.Status()),
|
||||
logger.Any("duration_ms", duration.Milliseconds()),
|
||||
logger.String("request_id", requestIDStr),
|
||||
logger.String("ip", c.ClientIP()),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// PanicRecoveryMiddleware recovers from panics and publishes them to the error bus.
|
||||
func PanicRecoveryMiddleware(errorBus errorbus.ErrorPublisher) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
defer func() {
|
||||
if err := recover(); err != nil {
|
||||
// Capture stack trace
|
||||
stack := make([]byte, 4096)
|
||||
n := runtime.Stack(stack, false)
|
||||
stack = stack[:n]
|
||||
|
||||
// Get request ID from context
|
||||
requestID, _ := c.Get(requestIDKey)
|
||||
ctx := context.WithValue(context.Background(), "request_id", requestID)
|
||||
|
||||
// Create error
|
||||
var panicErr error
|
||||
if e, ok := err.(error); ok {
|
||||
panicErr = e
|
||||
} else {
|
||||
panicErr = &panicError{value: err, stack: stack}
|
||||
}
|
||||
|
||||
// Publish to error bus
|
||||
errorBus.Publish(ctx, panicErr)
|
||||
|
||||
// Return error response
|
||||
c.JSON(http.StatusInternalServerError, gin.H{
|
||||
"error": "Internal server error",
|
||||
})
|
||||
|
||||
c.Abort()
|
||||
}
|
||||
}()
|
||||
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
// panicError wraps a panic value as an error.
|
||||
type panicError struct {
|
||||
value interface{}
|
||||
stack []byte
|
||||
}
|
||||
|
||||
func (e *panicError) Error() string {
|
||||
return "panic recovered"
|
||||
}
|
||||
|
||||
// CORSMiddleware provides CORS support.
|
||||
func CORSMiddleware() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
|
||||
c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
|
||||
c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With")
|
||||
c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS, GET, PUT, DELETE, PATCH")
|
||||
|
||||
if c.Request.Method == "OPTIONS" {
|
||||
c.AbortWithStatus(http.StatusNoContent)
|
||||
return
|
||||
}
|
||||
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
// TimeoutMiddleware sets a request timeout.
|
||||
func TimeoutMiddleware(timeout time.Duration) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
ctx, cancel := context.WithTimeout(c.Request.Context(), timeout)
|
||||
defer cancel()
|
||||
|
||||
c.Request = c.Request.WithContext(ctx)
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
131
internal/server/server.go
Normal file
131
internal/server/server.go
Normal file
@@ -0,0 +1,131 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"git.dcentral.systems/toolz/goplt/internal/health"
|
||||
"git.dcentral.systems/toolz/goplt/internal/metrics"
|
||||
"git.dcentral.systems/toolz/goplt/pkg/config"
|
||||
"git.dcentral.systems/toolz/goplt/pkg/errorbus"
|
||||
"git.dcentral.systems/toolz/goplt/pkg/logger"
|
||||
)
|
||||
|
||||
// Server wraps the HTTP server and Gin router.
|
||||
type Server struct {
|
||||
httpServer *http.Server
|
||||
router *gin.Engine
|
||||
}
|
||||
|
||||
// NewServer creates a new HTTP server with all middleware and routes.
|
||||
func NewServer(
|
||||
cfg config.ConfigProvider,
|
||||
log logger.Logger,
|
||||
healthRegistry *health.Registry,
|
||||
metricsRegistry *metrics.Metrics,
|
||||
errorBus errorbus.ErrorPublisher,
|
||||
) (*Server, error) {
|
||||
// Set Gin mode
|
||||
env := cfg.GetString("environment")
|
||||
if env == "production" {
|
||||
gin.SetMode(gin.ReleaseMode)
|
||||
}
|
||||
|
||||
router := gin.New()
|
||||
|
||||
// Add middleware (order matters!)
|
||||
router.Use(RequestIDMiddleware())
|
||||
router.Use(LoggingMiddleware(log))
|
||||
router.Use(PanicRecoveryMiddleware(errorBus))
|
||||
router.Use(metricsRegistry.HTTPMiddleware())
|
||||
router.Use(CORSMiddleware())
|
||||
|
||||
// Request timeout middleware (optional, can be configured per route if needed)
|
||||
// router.Use(TimeoutMiddleware(timeout))
|
||||
|
||||
// Register core routes
|
||||
registerRoutes(router, healthRegistry, metricsRegistry)
|
||||
|
||||
// Get server configuration
|
||||
port := cfg.GetInt("server.port")
|
||||
if port == 0 {
|
||||
port = 8080
|
||||
}
|
||||
host := cfg.GetString("server.host")
|
||||
if host == "" {
|
||||
host = "0.0.0.0"
|
||||
}
|
||||
|
||||
readTimeout := cfg.GetDuration("server.read_timeout")
|
||||
if readTimeout == 0 {
|
||||
readTimeout = 30 * time.Second
|
||||
}
|
||||
|
||||
writeTimeout := cfg.GetDuration("server.write_timeout")
|
||||
if writeTimeout == 0 {
|
||||
writeTimeout = 30 * time.Second
|
||||
}
|
||||
|
||||
addr := fmt.Sprintf("%s:%d", host, port)
|
||||
|
||||
httpServer := &http.Server{
|
||||
Addr: addr,
|
||||
Handler: router,
|
||||
ReadTimeout: readTimeout,
|
||||
WriteTimeout: writeTimeout,
|
||||
IdleTimeout: 120 * time.Second,
|
||||
}
|
||||
|
||||
return &Server{
|
||||
httpServer: httpServer,
|
||||
router: router,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// registerRoutes registers all core routes.
|
||||
func registerRoutes(
|
||||
router *gin.Engine,
|
||||
healthRegistry *health.Registry,
|
||||
metricsRegistry *metrics.Metrics,
|
||||
) {
|
||||
// Health endpoints
|
||||
router.GET("/healthz", func(c *gin.Context) {
|
||||
status := healthRegistry.LivenessCheck(c.Request.Context())
|
||||
if status.Status == "healthy" {
|
||||
c.JSON(http.StatusOK, status)
|
||||
} else {
|
||||
c.JSON(http.StatusServiceUnavailable, status)
|
||||
}
|
||||
})
|
||||
|
||||
router.GET("/ready", func(c *gin.Context) {
|
||||
status := healthRegistry.ReadinessCheck(c.Request.Context())
|
||||
if status.Status == "healthy" {
|
||||
c.JSON(http.StatusOK, status)
|
||||
} else {
|
||||
c.JSON(http.StatusServiceUnavailable, status)
|
||||
}
|
||||
})
|
||||
|
||||
// Metrics endpoint
|
||||
router.GET("/metrics", gin.WrapH(metricsRegistry.Handler()))
|
||||
}
|
||||
|
||||
// Start starts the HTTP server.
|
||||
func (s *Server) Start() error {
|
||||
return s.httpServer.ListenAndServe()
|
||||
}
|
||||
|
||||
// Shutdown gracefully shuts down the HTTP server.
|
||||
func (s *Server) Shutdown(ctx context.Context) error {
|
||||
return s.httpServer.Shutdown(ctx)
|
||||
}
|
||||
|
||||
// Router returns the Gin router (for adding additional routes).
|
||||
func (s *Server) Router() *gin.Engine {
|
||||
return s.router
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user