chore: skip websocket client if net isn't up or time sync hasn't complete

This commit is contained in:
Siyuan Miao
2025-04-03 18:16:41 +02:00
parent 65e4a58ad9
commit 1e9adf81d4
3 changed files with 57 additions and 10 deletions

33
ntp.go
View File

@@ -5,6 +5,7 @@ import (
"fmt"
"net/http"
"os/exec"
"strconv"
"time"
"github.com/beevik/ntp"
@@ -20,13 +21,41 @@ const (
)
var (
builtTimestamp string
timeSyncRetryInterval = 0 * time.Second
timeSyncSuccess = false
defaultNTPServers = []string{
"time.cloudflare.com",
"time.apple.com",
}
)
func isTimeSyncNeeded() bool {
if builtTimestamp == "" {
logger.Warnf("Built timestamp is not set, time sync is needed")
return true
}
ts, err := strconv.Atoi(builtTimestamp)
if err != nil {
logger.Warnf("Failed to parse built timestamp: %v", err)
return true
}
// builtTimestamp is UNIX timestamp in seconds
builtTime := time.Unix(int64(ts), 0)
now := time.Now()
logger.Tracef("Built time: %v, now: %v", builtTime, now)
if now.Sub(builtTime) < 0 {
logger.Warnf("System time is behind the built time, time sync is needed")
return true
}
return false
}
func TimeSyncLoop() {
for {
if !networkState.checked {
@@ -40,6 +69,9 @@ func TimeSyncLoop() {
continue
}
// check if time sync is needed, but do nothing for now
isTimeSyncNeeded()
logger.Infof("Syncing system time")
start := time.Now()
err := SyncSystemTime()
@@ -56,6 +88,7 @@ func TimeSyncLoop() {
continue
}
timeSyncSuccess = true
logger.Infof("Time sync successful, now is: %v, time taken: %v", time.Now(), time.Since(start))
time.Sleep(timeSyncInterval) // after the first sync is done
}