From 1827efe4753f7cf8e90f01f956440bfce90c7725 Mon Sep 17 00:00:00 2001 From: fedorHub Date: Thu, 28 Aug 2025 16:13:36 +0200 Subject: [PATCH] feat: sync db --- cmd/wg-portal-2/main.go | 6 ++++++ internal/sync/periodic.go | 35 +++++++++++++++++++++++++++++++++++ 2 files changed, 41 insertions(+) create mode 100644 internal/sync/periodic.go diff --git a/cmd/wg-portal-2/main.go b/cmd/wg-portal-2/main.go index 71c555f..0b2c490 100644 --- a/cmd/wg-portal-2/main.go +++ b/cmd/wg-portal-2/main.go @@ -28,6 +28,7 @@ import ( "github.com/fedor-git/wg-portal-2/internal/app/webhooks" "github.com/fedor-git/wg-portal-2/internal/app/wireguard" "github.com/fedor-git/wg-portal-2/internal/config" + "github.com/fedor-git/wg-portal-2/internal/sync" ) // main entry point for WireGuard Portal @@ -182,6 +183,11 @@ func main() { go metricsServer.Run(ctx) go webSrv.Run(ctx, cfg.Web.ListeningAddress) + // sync WireGuard state periodically in the background + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + go sync.StartPeriodicSync(ctx, wgManager, 30*time.Second) + slog.Info("Application startup complete") // wait until context gets cancelled diff --git a/internal/sync/periodic.go b/internal/sync/periodic.go new file mode 100644 index 0000000..fb1e2ec --- /dev/null +++ b/internal/sync/periodic.go @@ -0,0 +1,35 @@ +package sync + +import ( + "context" + "log" + "time" +) + +func startPeriodicSync(ctx context.Context, wgManager WireguardSynchronizer, interval time.Duration) { + log.Printf("✅ Starting periodic WireGuard sync every %s", interval) + ticker := time.NewTicker(interval) + defer ticker.Stop() + + log.Println("Running initial sync on startup...") + if err := wgManager.SyncDevice(); err != nil { + log.Printf("ERROR during initial sync: %v", err) + } + + for { + select { + case <-ticker.C: + log.Println("⚙️ Ticker fired: running periodic sync...") + if err := wgManager.SyncDevice(); err != nil { + log.Printf("ERROR during periodic sync: %v", err) + } + case <-ctx.Done(): + log.Println("Stopping periodic sync.") + return + } + } +} + +type WireguardSynchronizer interface { + SyncDevice() error +} \ No newline at end of file