Files
sub2api/backend/internal/service/proxy_expiry_service.go
T
李建琦 6d655c9903
Release / update-version (push) Has been cancelled
Release / build-frontend (push) Has been cancelled
Release / release (push) Has been cancelled
Release / sync-version-file (push) Has been cancelled
CI / shell (push) Canceled after 0s
CI / test (push) Canceled after 0s
CI / frontend (push) Canceled after 0s
CI / golangci-lint (push) Canceled after 0s
Security Scan / backend-security (push) Canceled after 0s
Security Scan / frontend-security (push) Canceled after 0s
Sub2API v1.0 - AI API 网关(二开初始版本,基于上游 Wei-Shaw/sub2api)
2026-08-21 18:30:13 +08:00

64 lines
1.3 KiB
Go

package service
import (
"context"
"log"
"sync"
"time"
)
// ProxyExpiryService 周期扫描到期代理并把绑定账号改投备用/直连。
type ProxyExpiryService struct {
proxyRepo ProxyRepository
interval time.Duration
stopCh chan struct{}
stopOnce sync.Once
wg sync.WaitGroup
}
func NewProxyExpiryService(proxyRepo ProxyRepository, interval time.Duration) *ProxyExpiryService {
return &ProxyExpiryService{proxyRepo: proxyRepo, interval: interval, stopCh: make(chan struct{})}
}
func (s *ProxyExpiryService) Start() {
if s == nil || s.proxyRepo == nil || s.interval <= 0 {
return
}
s.wg.Add(1)
go func() {
defer s.wg.Done()
ticker := time.NewTicker(s.interval)
defer ticker.Stop()
s.runOnce()
for {
select {
case <-ticker.C:
s.runOnce()
case <-s.stopCh:
return
}
}
}()
}
func (s *ProxyExpiryService) Stop() {
if s == nil {
return
}
s.stopOnce.Do(func() { close(s.stopCh) })
s.wg.Wait()
}
func (s *ProxyExpiryService) runOnce() {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
changed, err := s.proxyRepo.SweepExpiredProxies(ctx, time.Now())
if err != nil {
log.Printf("[ProxyExpiry] sweep expired proxies failed: %v", err)
return
}
if changed > 0 {
log.Printf("[ProxyExpiry] re-routed %d accounts off expired proxies", changed)
}
}