Move web/task shutdown to container. Shutdown web before tasks. Add shutdown timeouts to config.

This commit is contained in:
mikestefanello 2025-02-16 09:39:29 -05:00
parent 4e5c5127e8
commit 732e81f5a4
4 changed files with 37 additions and 40 deletions

View file

@ -5,39 +5,37 @@ import (
"crypto/tls"
"errors"
"fmt"
"github.com/mikestefanello/pagoda/pkg/handlers"
"github.com/mikestefanello/pagoda/pkg/services"
"github.com/mikestefanello/pagoda/pkg/tasks"
"log"
"net/http"
"os"
"os/signal"
"sync"
"time"
"github.com/mikestefanello/pagoda/pkg/handlers"
"github.com/mikestefanello/pagoda/pkg/services"
)
func main() {
// Start a new container
// Start a new container.
c := services.NewContainer()
defer func() {
// Gracefully shutdown all services.
if err := c.Shutdown(); err != nil {
log.Fatal(err)
}
}()
// Build the router
// Build the router.
if err := handlers.BuildRouter(c); err != nil {
log.Fatalf("failed to build the router: %v", err)
}
// Register all task queues
// Register all task queues.
tasks.Register(c)
// Start the task runner to execute queued tasks
// Start the task runner to execute queued tasks.
c.Tasks.Start(context.Background())
// Start the server
// Start the server.
go func() {
srv := http.Server{
Addr: fmt.Sprintf("%s:%d", c.Config.HTTP.Hostname, c.Config.HTTP.Port),
@ -63,30 +61,9 @@ func main() {
}
}()
// Wait for interrupt signal to gracefully shut down the server with a timeout of 10 seconds.
// Wait for interrupt signal to gracefully shut down the web server and task runner.
quit := make(chan os.Signal, 1)
signal.Notify(quit, os.Interrupt)
signal.Notify(quit, os.Kill)
<-quit
// Shutdown both the task runner and web server
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
wg := sync.WaitGroup{}
wg.Add(2)
go func() {
defer wg.Done()
c.Tasks.Stop(ctx)
}()
go func() {
defer wg.Done()
if err := c.Web.Shutdown(ctx); err != nil {
log.Fatal(err)
}
}()
wg.Wait()
}