account_health.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  1. package service
  2. import (
  3. "context"
  4. "database/sql"
  5. "encoding/json"
  6. "log"
  7. "log/slog"
  8. "math"
  9. "strconv"
  10. "strings"
  11. "sync"
  12. "time"
  13. )
  14. // SettingKeyAccountHealthSettings 全站账号健康分配置(JSON,见 AccountHealthSettings)。
  15. const SettingKeyAccountHealthSettings = "account_health_settings"
  16. // accountHealthReasonPrefix 健康服务写入的临时隔离原因前缀。恢复时只清理
  17. // 带此前缀的行,避免误解除其他功能(限流/刷新)设置的隔离。
  18. const accountHealthReasonPrefix = "health:"
  19. // AccountHealthSettings 账号健康分阈值配置。
  20. type AccountHealthSettings struct {
  21. Enabled bool `json:"enabled"`
  22. WindowMinutes int `json:"window_minutes"`
  23. MinSamples int `json:"min_samples"`
  24. IsolateErrRate float64 `json:"isolate_err_rate"`
  25. RecoverErrRate float64 `json:"recover_err_rate"`
  26. CooldownMinutes int `json:"cooldown_minutes"`
  27. IntervalSeconds int `json:"interval_seconds"`
  28. }
  29. // DefaultAccountHealthSettings 默认阈值:10 分钟窗口 ≥10 个样本且错误率 ≥50% 隔离 30 分钟。
  30. func DefaultAccountHealthSettings() AccountHealthSettings {
  31. return AccountHealthSettings{
  32. Enabled: true,
  33. WindowMinutes: 10,
  34. MinSamples: 10,
  35. IsolateErrRate: 0.5,
  36. RecoverErrRate: 0.2,
  37. CooldownMinutes: 30,
  38. IntervalSeconds: 60,
  39. }
  40. }
  41. // AccountHealthSnapshot 单个账号的健康快照(管理端展示)。
  42. type AccountHealthSnapshot struct {
  43. AccountID int64 `json:"account_id"`
  44. Name string `json:"name"`
  45. Platform string `json:"platform"`
  46. Score int `json:"score"`
  47. ErrRate float64 `json:"err_rate"`
  48. AvgLatencyMs *int `json:"avg_latency_ms,omitempty"`
  49. Total int64 `json:"total"`
  50. Errors int64 `json:"errors"`
  51. State string `json:"state"` // healthy / degraded / isolated
  52. Isolated bool `json:"isolated"`
  53. IsolateReason string `json:"isolate_reason,omitempty"`
  54. IsolatedUntil *time.Time `json:"isolated_until,omitempty"`
  55. EvaluatedAt time.Time `json:"evaluated_at"`
  56. }
  57. // AccountHealthAccountStore 健康评估需要的账号写接口(AccountRepository 已实现)。
  58. type AccountHealthAccountStore interface {
  59. SetTempUnschedulable(ctx context.Context, id int64, until time.Time, reason string) error
  60. ClearTempUnschedulable(ctx context.Context, id int64) error
  61. }
  62. // AccountHealthService 全站账号健康分:按窗口聚合 usage_logs(成功)与
  63. // ops_error_logs(失败),错误率超阈自动临时隔离,恢复后自动解除。
  64. // 隔离复用 TempUnschedulable 机制,到期自动恢复;只动 reason 前缀为 health: 的行。
  65. type AccountHealthService struct {
  66. db *sql.DB
  67. accountRepo AccountHealthAccountStore
  68. settingRepo SettingRepository
  69. mu sync.RWMutex
  70. snapshot map[int64]AccountHealthSnapshot
  71. updated time.Time
  72. stopCh chan struct{}
  73. stopOnce sync.Once
  74. wg sync.WaitGroup
  75. }
  76. // NewAccountHealthService 创建健康服务(不启动后台循环,测试友好)。
  77. func NewAccountHealthService(db *sql.DB, accountRepo AccountHealthAccountStore, settingRepo SettingRepository) *AccountHealthService {
  78. return &AccountHealthService{
  79. db: db,
  80. accountRepo: accountRepo,
  81. settingRepo: settingRepo,
  82. snapshot: make(map[int64]AccountHealthSnapshot),
  83. stopCh: make(chan struct{}),
  84. }
  85. }
  86. // ProvideAccountHealthService 创建并启动健康服务(wire 用)。
  87. func ProvideAccountHealthService(db *sql.DB, accountRepo AccountRepository, settingRepo SettingRepository) *AccountHealthService {
  88. svc := NewAccountHealthService(db, accountRepo, settingRepo)
  89. svc.Start()
  90. return svc
  91. }
  92. // Start 启动周期评估(60s 一次,阈值可配)。
  93. func (s *AccountHealthService) Start() {
  94. if s == nil || s.db == nil || s.accountRepo == nil {
  95. return
  96. }
  97. s.wg.Add(1)
  98. go func() {
  99. defer s.wg.Done()
  100. ticker := time.NewTicker(time.Duration(s.currentSettings().IntervalSeconds) * time.Second)
  101. defer ticker.Stop()
  102. s.runOnce()
  103. for {
  104. select {
  105. case <-ticker.C:
  106. s.runOnce()
  107. case <-s.stopCh:
  108. return
  109. }
  110. }
  111. }()
  112. }
  113. // Stop 停止后台循环。
  114. func (s *AccountHealthService) Stop() {
  115. if s == nil {
  116. return
  117. }
  118. s.stopOnce.Do(func() { close(s.stopCh) })
  119. s.wg.Wait()
  120. }
  121. func (s *AccountHealthService) currentSettings() AccountHealthSettings {
  122. cfg := DefaultAccountHealthSettings()
  123. if s == nil || s.settingRepo == nil {
  124. return cfg
  125. }
  126. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  127. defer cancel()
  128. raw, err := s.settingRepo.GetValue(ctx, SettingKeyAccountHealthSettings)
  129. if err != nil || strings.TrimSpace(raw) == "" {
  130. return cfg
  131. }
  132. var parsed AccountHealthSettings
  133. if err := json.Unmarshal([]byte(raw), &parsed); err != nil {
  134. slog.Warn("account_health.bad_settings", "error", err)
  135. return cfg
  136. }
  137. return normalizeAccountHealthSettings(parsed)
  138. }
  139. func normalizeAccountHealthSettings(in AccountHealthSettings) AccountHealthSettings {
  140. def := DefaultAccountHealthSettings()
  141. // Enabled 显式以存储为准(零值 false 即关闭,不回填默认 true)。
  142. if in.WindowMinutes <= 0 {
  143. in.WindowMinutes = def.WindowMinutes
  144. }
  145. if in.MinSamples <= 0 {
  146. in.MinSamples = def.MinSamples
  147. }
  148. if in.IsolateErrRate <= 0 || in.IsolateErrRate > 1 {
  149. in.IsolateErrRate = def.IsolateErrRate
  150. }
  151. if in.RecoverErrRate < 0 || in.RecoverErrRate > 1 {
  152. in.RecoverErrRate = def.RecoverErrRate
  153. }
  154. if in.RecoverErrRate >= in.IsolateErrRate {
  155. in.RecoverErrRate = def.RecoverErrRate
  156. }
  157. if in.CooldownMinutes <= 0 {
  158. in.CooldownMinutes = def.CooldownMinutes
  159. }
  160. if in.IntervalSeconds < 10 {
  161. in.IntervalSeconds = def.IntervalSeconds
  162. }
  163. return in
  164. }
  165. // GetSettings 读取当前配置(无存储时返回默认)。
  166. func (s *AccountHealthService) GetSettings(ctx context.Context) AccountHealthSettings {
  167. if s == nil {
  168. return DefaultAccountHealthSettings()
  169. }
  170. return s.currentSettings()
  171. }
  172. // UpdateSettings 校验并保存配置。
  173. func (s *AccountHealthService) UpdateSettings(ctx context.Context, in AccountHealthSettings) (AccountHealthSettings, error) {
  174. if s == nil || s.settingRepo == nil {
  175. return DefaultAccountHealthSettings(), nil
  176. }
  177. norm := normalizeAccountHealthSettings(in)
  178. raw, err := json.Marshal(norm)
  179. if err != nil {
  180. return norm, err
  181. }
  182. if err := s.settingRepo.Set(ctx, SettingKeyAccountHealthSettings, string(raw)); err != nil {
  183. return norm, err
  184. }
  185. return norm, nil
  186. }
  187. // Snapshot 返回最近一次评估快照(管理端列表)。
  188. func (s *AccountHealthService) Snapshot() []AccountHealthSnapshot {
  189. if s == nil {
  190. return nil
  191. }
  192. s.mu.RLock()
  193. defer s.mu.RUnlock()
  194. out := make([]AccountHealthSnapshot, 0, len(s.snapshot))
  195. for _, v := range s.snapshot {
  196. out = append(out, v)
  197. }
  198. return out
  199. }
  200. type accountHealthRow struct {
  201. id int64
  202. name string
  203. platform string
  204. ok int64
  205. avgMs sql.NullFloat64
  206. err int64
  207. until sql.NullTime
  208. reason sql.NullString
  209. }
  210. func (s *AccountHealthService) runOnce() {
  211. cfg := s.currentSettings()
  212. if !cfg.Enabled {
  213. return
  214. }
  215. ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
  216. defer cancel()
  217. rows, err := s.queryWindowStats(ctx, cfg.WindowMinutes)
  218. if err != nil {
  219. log.Printf("[AccountHealth] query window stats failed: %v", err)
  220. return
  221. }
  222. now := time.Now()
  223. next := make(map[int64]AccountHealthSnapshot, len(rows))
  224. for _, r := range rows {
  225. snap := decideAccountHealth(r, cfg, now)
  226. next[r.id] = snap
  227. if snap.State == "isolated" && !r.isHealthIsolated(now) {
  228. // 同列多写者(限流/刷新/传输层):若其他子系统已设冷却且未到期,不覆盖。
  229. if r.until.Valid && r.until.Time.After(now) {
  230. next[r.id] = snap
  231. continue
  232. }
  233. until := now.Add(time.Duration(cfg.CooldownMinutes) * time.Minute)
  234. reason := accountHealthReasonPrefix + "auto err_rate=" + formatRate(snap.ErrRate)
  235. if err := s.accountRepo.SetTempUnschedulable(ctx, r.id, until, reason); err != nil {
  236. log.Printf("[AccountHealth] isolate account %d failed: %v", r.id, err)
  237. snap.Isolated = false
  238. next[r.id] = snap
  239. continue
  240. }
  241. slog.Info("account_health.isolated", "account_id", r.id, "err_rate", snap.ErrRate, "total", snap.Total)
  242. snap.Isolated = true
  243. snap.IsolateReason = reason
  244. snap.IsolatedUntil = &until
  245. next[r.id] = snap
  246. }
  247. if snap.State != "isolated" && r.isHealthIsolated(now) && r.hasEnoughSamples(cfg) && snap.ErrRate <= cfg.RecoverErrRate {
  248. if err := s.accountRepo.ClearTempUnschedulable(ctx, r.id); err != nil {
  249. log.Printf("[AccountHealth] recover account %d failed: %v", r.id, err)
  250. continue
  251. }
  252. slog.Info("account_health.recovered", "account_id", r.id, "err_rate", snap.ErrRate)
  253. }
  254. }
  255. s.mu.Lock()
  256. s.snapshot = next
  257. s.updated = now
  258. s.mu.Unlock()
  259. }
  260. func (r accountHealthRow) isHealthIsolated(now time.Time) bool {
  261. return r.until.Valid && r.until.Time.After(now) &&
  262. r.reason.Valid && strings.HasPrefix(r.reason.String, accountHealthReasonPrefix)
  263. }
  264. func (r accountHealthRow) hasEnoughSamples(cfg AccountHealthSettings) bool {
  265. return r.ok+r.err >= int64(cfg.MinSamples)
  266. }
  267. // decideAccountHealth 纯函数:由窗口统计计算评分与期望状态(可单测)。
  268. func decideAccountHealth(r accountHealthRow, cfg AccountHealthSettings, now time.Time) AccountHealthSnapshot {
  269. snap := AccountHealthSnapshot{
  270. AccountID: r.id, Name: r.name, Platform: r.platform,
  271. EvaluatedAt: now,
  272. }
  273. total := r.ok + r.err
  274. snap.Total = total
  275. snap.Errors = r.err
  276. if total == 0 {
  277. snap.Score = 100
  278. snap.State = "healthy"
  279. } else {
  280. snap.ErrRate = float64(r.err) / float64(total)
  281. snap.Score = int(math.Round(100 * (1 - snap.ErrRate)))
  282. snap.State = "healthy"
  283. if total >= int64(cfg.MinSamples) {
  284. if snap.ErrRate >= cfg.IsolateErrRate {
  285. snap.State = "isolated"
  286. } else if snap.ErrRate >= cfg.RecoverErrRate {
  287. snap.State = "degraded"
  288. }
  289. }
  290. }
  291. if r.avgMs.Valid {
  292. v := int(math.Round(r.avgMs.Float64))
  293. snap.AvgLatencyMs = &v
  294. }
  295. if r.until.Valid {
  296. u := r.until.Time
  297. snap.IsolatedUntil = &u
  298. }
  299. if r.reason.Valid {
  300. snap.IsolateReason = r.reason.String
  301. }
  302. snap.Isolated = r.isHealthIsolated(now) || snap.State == "isolated"
  303. return snap
  304. }
  305. func formatRate(v float64) string {
  306. return strconv.FormatFloat(math.Round(v*1000)/10, 'f', 1, 64) + "%"
  307. }
  308. func (s *AccountHealthService) queryWindowStats(ctx context.Context, windowMinutes int) ([]accountHealthRow, error) {
  309. q := `
  310. SELECT a.id, COALESCE(a.name, ''), COALESCE(a.platform, ''),
  311. COALESCE(u.ok_count, 0), u.avg_ms,
  312. COALESCE(e.err_count, 0),
  313. a.temp_unschedulable_until, a.temp_unschedulable_reason
  314. FROM accounts a
  315. LEFT JOIN (
  316. SELECT account_id, COUNT(*) AS ok_count, AVG(duration_ms) AS avg_ms
  317. FROM usage_logs
  318. WHERE created_at >= NOW() - ($1 || ' minutes')::interval
  319. AND account_id IS NOT NULL AND account_id > 0
  320. GROUP BY account_id
  321. ) u ON u.account_id = a.id
  322. LEFT JOIN (
  323. SELECT account_id, COUNT(*) AS err_count
  324. FROM ops_error_logs
  325. WHERE created_at >= NOW() - ($1 || ' minutes')::interval
  326. AND COALESCE(status_code, 0) >= 400
  327. AND NOT COALESCE(is_business_limited, FALSE)
  328. AND account_id IS NOT NULL
  329. GROUP BY account_id
  330. ) e ON e.account_id = a.id
  331. WHERE a.deleted_at IS NULL
  332. AND (u.account_id IS NOT NULL OR e.account_id IS NOT NULL
  333. OR COALESCE(a.temp_unschedulable_reason, '') LIKE 'health:%')`
  334. rows, err := s.db.QueryContext(ctx, q, windowMinutes)
  335. if err != nil {
  336. return nil, err
  337. }
  338. defer func() { _ = rows.Close() }()
  339. var out []accountHealthRow
  340. for rows.Next() {
  341. var r accountHealthRow
  342. if err := rows.Scan(&r.id, &r.name, &r.platform, &r.ok, &r.avgMs, &r.err, &r.until, &r.reason); err != nil {
  343. return nil, err
  344. }
  345. out = append(out, r)
  346. }
  347. return out, rows.Err()
  348. }
  349. // Isolate 手动隔离账号(24h,可手动恢复)。
  350. func (s *AccountHealthService) Isolate(ctx context.Context, id int64) error {
  351. if s == nil || s.accountRepo == nil {
  352. return nil
  353. }
  354. until := time.Now().Add(24 * time.Hour)
  355. return s.accountRepo.SetTempUnschedulable(ctx, id, until, accountHealthReasonPrefix+"manual")
  356. }
  357. // Resume 手动恢复:清隔离并重置快照条目。
  358. func (s *AccountHealthService) Resume(ctx context.Context, id int64) error {
  359. if s == nil || s.accountRepo == nil {
  360. return nil
  361. }
  362. if err := s.accountRepo.ClearTempUnschedulable(ctx, id); err != nil {
  363. return err
  364. }
  365. s.mu.Lock()
  366. delete(s.snapshot, id)
  367. s.mu.Unlock()
  368. return nil
  369. }