ussd-data-connect/cmd/main.go

106 lines
2.2 KiB
Go
Raw Permalink Normal View History

2025-01-02 10:05:09 +01:00
package main
import (
"context"
"errors"
"flag"
"log/slog"
"os"
"os/signal"
"sync"
"syscall"
"time"
"git.grassecon.net/urdt/ussd-data-connect/internal/store"
"git.grassecon.net/urdt/ussd-data-connect/internal/syncer"
"git.grassecon.net/urdt/ussd-data-connect/internal/util"
"github.com/knadh/koanf/v2"
)
const defaultGracefulShutdownPeriod = time.Second * 20
var (
build = "dev"
confFlag string
migrationsFolderFlag string
queriesFlag string
lo *slog.Logger
ko *koanf.Koanf
)
func init() {
flag.StringVar(&confFlag, "config", "config.toml", "Config file location")
flag.StringVar(&migrationsFolderFlag, "migrations", "migrations/", "Migrations folder location")
flag.StringVar(&queriesFlag, "queries", "queries.sql", "Queries file location")
flag.Parse()
lo = util.InitLogger()
ko = util.InitConfig(lo, confFlag)
2025-01-03 08:41:43 +01:00
lo.Info("starting ussd data connect", "build", build)
2025-01-02 10:05:09 +01:00
}
func main() {
var wg sync.WaitGroup
ctx, stop := notifyShutdown()
store, err := store.NewStore(store.StoreOpts{
Logg: lo,
DSN: ko.MustString("postgres.dsn"),
MigrationsFolderPath: migrationsFolderFlag,
QueriesFolderPath: queriesFlag,
})
if err != nil {
lo.Error("could not initialize postgres store", "error", err)
os.Exit(1)
}
syncer := syncer.New(syncer.SyncerOpts{
Logg: lo,
Store: store,
})
// Trigger an initial sync before the ticker routine takes over
if err := syncer.Process(context.Background()); err != nil {
lo.Error("failed to process initial sync", "error", err)
os.Exit(1)
}
2025-01-02 10:05:09 +01:00
wg.Add(1)
go func() {
defer wg.Done()
syncer.Run()
}()
<-ctx.Done()
lo.Info("shutdown signal received")
shutdownCtx, cancel := context.WithTimeout(context.Background(), defaultGracefulShutdownPeriod)
wg.Add(1)
go func() {
syncer.Stop()
defer wg.Done()
}()
go func() {
wg.Wait()
stop()
cancel()
os.Exit(0)
}()
<-shutdownCtx.Done()
if errors.Is(shutdownCtx.Err(), context.DeadlineExceeded) {
stop()
cancel()
lo.Error("graceful shutdown period exceeded, forcefully shutting down")
}
os.Exit(1)
}
func notifyShutdown() (context.Context, context.CancelFunc) {
return signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM, syscall.SIGINT)
}