Files
bj_power/bj_power_wms/internal/clock/clock.go
T

107 lines
2.5 KiB
Go
Raw Normal View History

// Package clock 提供 JWT 验签用的"签发方服务器时间"权威基准(2026-11-24 用户拍板)。
// 规则:谁签发 JWT,验签就以那台服务器的时间为准;验签方先向签发方 /api/server-time
// 取当前时间,30 秒缓存降低压力,取不到降级本机时间(10 分钟容差继续兜底)。
// 本机自己签发的 token 直接用本机时间,不走网络。
package clock
import (
"encoding/json"
"fmt"
"net/http"
"sync"
"time"
"github.com/zeromicro/go-zero/core/logx"
)
// Config 时钟权威配置:Issuer=本端签发方标识,Sources=签发方→取时间地址映射(三端配同一份)
type Config struct {
Issuer string
Sources map[string]string
}
const (
cacheTTL = 30 * time.Second
requestTimeout = 1500 * time.Millisecond
)
var (
mu sync.RWMutex
cfg Config
cache = make(map[string]entry)
client = &http.Client{Timeout: requestTimeout}
)
type entry struct {
unix int64
fetchedAt time.Time
}
// Init 启动时注入配置并清空缓存
func Init(c Config) {
mu.Lock()
defer mu.Unlock()
cfg = c
cache = make(map[string]entry)
}
// AuthorityNow 返回 issuer 对应签发方的权威当前时间。
// 本端签发或映射缺失时直接返回本机时间;跨端取时间失败也降级本机时间。
func AuthorityNow(issuer string) time.Time {
if issuer == "" {
return time.Now()
}
mu.RLock()
self := cfg.Issuer
url := cfg.Sources[issuer]
mu.RUnlock()
if issuer == self || url == "" {
return time.Now()
}
mu.RLock()
e, ok := cache[issuer]
mu.RUnlock()
if ok && time.Since(e.fetchedAt) < cacheTTL {
return time.Unix(e.unix, 0)
}
unix, err := fetch(url)
if err != nil {
logx.Errorf("[时钟权威] 取签发方时间失败 issuer=%s url=%s err=%v,降级本机时间", issuer, url, err)
return time.Now()
}
mu.Lock()
cache[issuer] = entry{unix: unix, fetchedAt: time.Now()}
mu.Unlock()
return time.Unix(unix, 0)
}
func fetch(url string) (int64, error) {
resp, err := client.Get(url)
if err != nil {
return 0, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return 0, fmt.Errorf("HTTP %d", resp.StatusCode)
}
var r struct {
ServerTime int64 `json:"serverTime"`
Data struct {
ServerTime int64 `json:"serverTime"`
} `json:"data"`
}
if err := json.NewDecoder(resp.Body).Decode(&r); err != nil {
return 0, err
}
unix := r.ServerTime
if unix <= 0 {
unix = r.Data.ServerTime
}
if unix <= 0 {
return 0, fmt.Errorf("serverTime 无效")
}
return unix, nil
}