Documentation
¶
Index ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func GracefulShutdownSystem ¶
func GracefulShutdownSystem( ctx context.Context, appLogger logger.Logger, errCh <-chan error, timeout time.Duration, shutdownTasks []ShutdownTask, ) <-chan struct{}
GracefulShutdownSystem orchestrates graceful application shutdown with configurable cleanup tasks. Monitors for OS signals (SIGINT/SIGTERM), internal errors, or context cancellation, then executes shutdown tasks sequentially within the specified timeout to ensure clean resource cleanup.
Shutdown Triggers:
- OS Signals: SIGINT (Ctrl+C), SIGTERM (container/process manager)
- Internal Errors: Application errors sent via errCh channel
- Context Cancellation: Parent context cancellation
Shutdown Process:
- Wait for shutdown trigger (signal, error, or context cancellation)
- Log shutdown initiation with trigger details
- Create timeout context for all cleanup operations
- Execute shutdown tasks sequentially in provided order
- Log each task's completion or failure (failures don't stop shutdown)
- Close done channel to signal shutdown completion
Example Usage:
// Define cleanup tasks in dependency order
shutdownTasks := []serverutils.ShutdownTask{
{Name: "HTTP Server", Op: func(ctx context.Context) error {
return server.Shutdown(ctx)
}},
{Name: "Database", Op: func(ctx context.Context) error {
return db.Close()
}},
{Name: "Cache", Op: func(ctx context.Context) error {
return cache.Close()
}},
}
// Start graceful shutdown monitoring
errCh := make(chan error, 1)
done := serverutils.GracefulShutdownSystem(
ctx, logger, errCh, 30*time.Second, shutdownTasks,
)
// Application runs here...
// Wait for shutdown completion
<-done
logger.Info(ctx, "Application shutdown completed", nil)
Types ¶
type ShutdownOperation ¶
ShutdownOperation defines a cleanup function executed during graceful shutdown. Should handle context cancellation and return quickly to avoid blocking shutdown.
Parameters:
- ctx: Context with shutdown timeout for cancellation control
Returns:
- error: nil on success, error details on failure (logged but doesn't stop shutdown)
Example:
func closeDatabase(ctx context.Context) error {
return db.Close()
}
type ShutdownTask ¶ added in v0.17.0
type ShutdownTask struct {
Name string // Human-readable task name for logging and debugging
Op ShutdownOperation // Cleanup operation to execute
}
ShutdownTask represents a cleanup operation to execute during graceful shutdown. Tasks are executed sequentially in the order they are provided to ensure proper dependency management and resource cleanup ordering.