feat: 优化代理准备并完善远端部署
- 增加严格代理、两分钟预取、白名单去重与分组状态展示\n- 增加远端注册令牌和安全地址校验\n- 增加 Docker Compose、Caddy 示例与控制中心部署文档
This commit is contained in:
@@ -21,7 +21,7 @@ import (
|
||||
const (
|
||||
proxyFetchRounds = 3
|
||||
proxyFetchMaxRounds = 20
|
||||
proxyFetchRetryWait = 300 * time.Millisecond
|
||||
proxyFetchRetryWait = 1200 * time.Millisecond
|
||||
proxyRequestTimeout = 15 * time.Second
|
||||
proxyValidationTimeout = 3 * time.Second
|
||||
proxyValidationWorkers = 3
|
||||
@@ -38,6 +38,10 @@ type proxySettingsSnapshot struct {
|
||||
autoFetchOnTimer bool
|
||||
accountsPerProxy int
|
||||
sparePercent int
|
||||
required bool
|
||||
ready bool
|
||||
state string
|
||||
blockedReason string
|
||||
autoWhitelist bool
|
||||
whitelistReplace bool
|
||||
whitelistPassword string
|
||||
@@ -55,8 +59,14 @@ type validatedProxy struct {
|
||||
}
|
||||
|
||||
type proxyRuntimeGroup struct {
|
||||
groupIndex int
|
||||
accountNames []string
|
||||
activeURL string
|
||||
activeIP string
|
||||
activeRegion string
|
||||
activeRTT time.Duration
|
||||
switchCount int
|
||||
lastError string
|
||||
consecutiveFailures int
|
||||
failed bool
|
||||
}
|
||||
@@ -90,13 +100,14 @@ func (s *Scheduler) UpdateProxySettings(cfg types.Config) {
|
||||
autoFetch := cfg.AutoFetchProxyOnSchedule
|
||||
accountsPerProxy := cfg.AccountsPerProxy
|
||||
sparePercent := cfg.ProxySparePercent
|
||||
required := cfg.ProxyRequired
|
||||
if accountsPerProxy <= 0 {
|
||||
accountsPerProxy = constants.DefaultAccountsPerProxy
|
||||
}
|
||||
if accountsPerProxy > constants.MaxAccountsPerProxy {
|
||||
accountsPerProxy = constants.MaxAccountsPerProxy
|
||||
}
|
||||
if sparePercent <= 0 {
|
||||
if sparePercent < constants.MinProxySparePercent {
|
||||
sparePercent = constants.DefaultProxySparePercent
|
||||
}
|
||||
if sparePercent > constants.MaxProxySparePercent {
|
||||
@@ -113,6 +124,7 @@ func (s *Scheduler) UpdateProxySettings(cfg types.Config) {
|
||||
s.autoFetchProxyOnSchedule != autoFetch ||
|
||||
s.accountsPerProxy != accountsPerProxy ||
|
||||
s.proxySparePercent != sparePercent ||
|
||||
s.proxyRequired != required ||
|
||||
s.autoWhitelist != cfg.ProxyAutoWhitelist ||
|
||||
s.whitelistReplace != cfg.ProxyWhitelistReplace ||
|
||||
s.whitelistPassword != whitelistPassword ||
|
||||
@@ -123,6 +135,12 @@ func (s *Scheduler) UpdateProxySettings(cfg types.Config) {
|
||||
s.autoFetchProxyOnSchedule = autoFetch
|
||||
s.accountsPerProxy = accountsPerProxy
|
||||
s.proxySparePercent = sparePercent
|
||||
s.proxyRequired = required
|
||||
if changed {
|
||||
s.proxyReady = false
|
||||
s.proxyState = "stale"
|
||||
s.proxyBlockedReason = "代理配置已变更,等待重新准备"
|
||||
}
|
||||
s.autoWhitelist = cfg.ProxyAutoWhitelist
|
||||
s.whitelistReplace = cfg.ProxyWhitelistReplace
|
||||
s.whitelistPassword = whitelistPassword
|
||||
@@ -149,7 +167,7 @@ func (s *Scheduler) proxySettings() proxySettingsSnapshot {
|
||||
size = constants.MaxAccountsPerProxy
|
||||
}
|
||||
sparePercent := s.proxySparePercent
|
||||
if sparePercent <= 0 {
|
||||
if sparePercent < constants.MinProxySparePercent {
|
||||
sparePercent = constants.DefaultProxySparePercent
|
||||
}
|
||||
if sparePercent > constants.MaxProxySparePercent {
|
||||
@@ -162,6 +180,10 @@ func (s *Scheduler) proxySettings() proxySettingsSnapshot {
|
||||
autoFetchOnTimer: s.autoFetchProxyOnSchedule,
|
||||
accountsPerProxy: size,
|
||||
sparePercent: sparePercent,
|
||||
required: s.proxyRequired,
|
||||
ready: s.proxyReady,
|
||||
state: s.proxyState,
|
||||
blockedReason: s.proxyBlockedReason,
|
||||
autoWhitelist: s.autoWhitelist,
|
||||
whitelistReplace: s.whitelistReplace,
|
||||
whitelistPassword: s.whitelistPassword,
|
||||
@@ -180,6 +202,8 @@ func (s *Scheduler) closeAccountClients() {
|
||||
s.accountClientsDirty = true
|
||||
s.accountClientsExpireAt = time.Time{}
|
||||
s.proxyGroups = make(map[*client.DouyuClient]*proxyRuntimeGroup)
|
||||
s.proxyGroupHistory = nil
|
||||
s.accountProxyGroup = make(map[string]int)
|
||||
s.proxyStandbys = nil
|
||||
s.proxyClientPool = nil
|
||||
s.proxyExcludedURLs = make(map[string]struct{})
|
||||
@@ -211,6 +235,15 @@ func (s *Scheduler) replaceAccountClients(pool preparedProxyPool) {
|
||||
s.accountClientsDirty = false
|
||||
s.accountClientsExpireAt = pool.expiresAt
|
||||
s.proxyGroups = pool.groups
|
||||
s.accountProxyGroup = make(map[string]int)
|
||||
for _, group := range pool.groups {
|
||||
if group == nil {
|
||||
continue
|
||||
}
|
||||
for _, name := range group.accountNames {
|
||||
s.accountProxyGroup[name] = group.groupIndex
|
||||
}
|
||||
}
|
||||
s.proxyStandbys = pool.standbys
|
||||
s.proxyClientPool = pool.allClients
|
||||
s.proxyExcludedURLs = pool.excludedURLs
|
||||
@@ -222,6 +255,146 @@ func (s *Scheduler) replaceAccountClients(pool preparedProxyPool) {
|
||||
closeDouyuClientList(oldClients)
|
||||
}
|
||||
|
||||
func (s *Scheduler) replaceProxyGroupHistory(groups [][]string, activeCount int, proxies []validatedProxy) {
|
||||
history := make([]types.ProxyGroupStatus, 0, activeCount)
|
||||
for index, accounts := range groups {
|
||||
if index >= len(proxies) {
|
||||
break
|
||||
}
|
||||
proxy := proxies[index]
|
||||
history = append(history, types.ProxyGroupStatus{
|
||||
GroupIndex: index + 1,
|
||||
Role: "active",
|
||||
State: "active",
|
||||
AccountCount: len(accounts),
|
||||
Accounts: append([]string(nil), accounts...),
|
||||
Proxy: client.MaskProxyURL(proxy.url),
|
||||
Region: proxy.region,
|
||||
RTTMs: proxy.rtt.Milliseconds(),
|
||||
})
|
||||
}
|
||||
s.clientMu.Lock()
|
||||
s.proxyGroupHistory = history
|
||||
s.clientMu.Unlock()
|
||||
}
|
||||
|
||||
// ProxyStatus returns a structured status snapshot. It never includes proxy
|
||||
// credentials and is safe to expose to the desktop and remote dashboards.
|
||||
func (s *Scheduler) ProxyStatus() types.ProxyStatusView {
|
||||
cfg := s.proxySettings()
|
||||
s.clientMu.RLock()
|
||||
history := make([]types.ProxyGroupStatus, len(s.proxyGroupHistory))
|
||||
copy(history, s.proxyGroupHistory)
|
||||
for i := range history {
|
||||
history[i].Accounts = append([]string(nil), history[i].Accounts...)
|
||||
}
|
||||
accountGroups := make(map[string]int, len(s.accountProxyGroup))
|
||||
for name, index := range s.accountProxyGroup {
|
||||
accountGroups[name] = index
|
||||
}
|
||||
names := make([]string, 0, len(s.accountClients))
|
||||
for name := range s.accountClients {
|
||||
names = append(names, name)
|
||||
}
|
||||
sort.Strings(names)
|
||||
groupsByIndex := make(map[int]types.ProxyGroupStatus, len(history))
|
||||
for _, group := range history {
|
||||
groupsByIndex[group.GroupIndex] = group
|
||||
}
|
||||
accounts := make([]types.AccountProxyView, 0, len(names))
|
||||
directCount := 0
|
||||
for _, name := range names {
|
||||
groupIndex := accountGroups[name]
|
||||
view := types.AccountProxyView{
|
||||
AccountName: name,
|
||||
GroupIndex: groupIndex,
|
||||
GroupLabel: "未分配",
|
||||
Transport: "unassigned",
|
||||
}
|
||||
if cli := s.accountClients[name]; cli == s.directClient {
|
||||
view.GroupLabel = "直连"
|
||||
view.Transport = "direct"
|
||||
directCount++
|
||||
} else if groupIndex > 0 {
|
||||
view.GroupLabel = fmt.Sprintf("G%d", groupIndex)
|
||||
view.Transport = "proxy"
|
||||
if group, ok := groupsByIndex[groupIndex]; ok {
|
||||
view.Proxy = group.Proxy
|
||||
}
|
||||
}
|
||||
accounts = append(accounts, view)
|
||||
}
|
||||
standbyCount := len(s.proxyStandbys)
|
||||
s.clientMu.RUnlock()
|
||||
|
||||
activeCount := 0
|
||||
for _, group := range history {
|
||||
if group.Role == "active" {
|
||||
activeCount++
|
||||
}
|
||||
}
|
||||
standbyTarget := proxyStandbyCount(activeCount, cfg.sparePercent)
|
||||
state := cfg.state
|
||||
if state == "" {
|
||||
state = "empty"
|
||||
}
|
||||
lastError := cfg.blockedReason
|
||||
switch {
|
||||
case !cfg.enabled:
|
||||
state = "disabled"
|
||||
lastError = ""
|
||||
case directCount > 0:
|
||||
state = "direct_fallback"
|
||||
if lastError == "" {
|
||||
lastError = "账号已回退直连"
|
||||
}
|
||||
case cfg.ready:
|
||||
state = "ready"
|
||||
lastError = ""
|
||||
if reason := proxyDegradedReason(history, standbyCount, standbyTarget); reason != "" {
|
||||
state = "degraded"
|
||||
lastError = reason
|
||||
}
|
||||
case state == "preparing":
|
||||
// Keep the explicit preparing state visible while the pool is refreshed.
|
||||
case lastError != "":
|
||||
state = "failed"
|
||||
case len(history) == 0:
|
||||
state = "empty"
|
||||
default:
|
||||
state = "preparing"
|
||||
}
|
||||
return types.ProxyStatusView{
|
||||
Enabled: cfg.enabled,
|
||||
Required: cfg.required,
|
||||
State: state,
|
||||
ActiveCount: activeCount,
|
||||
StandbyCount: standbyCount,
|
||||
StandbyTarget: standbyTarget,
|
||||
DirectCount: directCount,
|
||||
LastError: lastError,
|
||||
UpdatedAt: time.Now().In(constants.CST).Format("2006-01-02 15:04:05.000"),
|
||||
Groups: history,
|
||||
Accounts: accounts,
|
||||
}
|
||||
}
|
||||
|
||||
func proxyDegradedReason(groups []types.ProxyGroupStatus, standbyCount, standbyTarget int) string {
|
||||
failed := 0
|
||||
for _, group := range groups {
|
||||
if group.State == "failed" {
|
||||
failed++
|
||||
}
|
||||
}
|
||||
if failed > 0 {
|
||||
return fmt.Sprintf("%d 个代理组失败,等待备用代理", failed)
|
||||
}
|
||||
if standbyCount < standbyTarget {
|
||||
return fmt.Sprintf("备用代理不足: %d/%d", standbyCount, standbyTarget)
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func closeDouyuClients(clients map[string]*client.DouyuClient) {
|
||||
items := make([]*client.DouyuClient, 0, len(clients))
|
||||
for _, cli := range clients {
|
||||
@@ -318,6 +491,14 @@ func (s *Scheduler) allClients() []*client.DouyuClient {
|
||||
// prepareProxyGroups 将本次参与抢购的账号按固定顺序分组,并为每组准备独立客户端。
|
||||
// forceRefresh=true 用于定时任务启动前主动刷新短效代理。
|
||||
func (s *Scheduler) prepareProxyGroups(accountProducts map[string]string, forceRefresh bool) error {
|
||||
timeout := proxyImmediateTimeout
|
||||
if forceRefresh {
|
||||
timeout = proxyScheduledTimeout
|
||||
}
|
||||
return s.prepareProxyGroupsUntil(accountProducts, forceRefresh, time.Now().Add(timeout))
|
||||
}
|
||||
|
||||
func (s *Scheduler) prepareProxyGroupsUntil(accountProducts map[string]string, forceRefresh bool, deadline time.Time) error {
|
||||
s.proxyPrepareMu.Lock()
|
||||
defer s.proxyPrepareMu.Unlock()
|
||||
|
||||
@@ -328,38 +509,38 @@ func (s *Scheduler) prepareProxyGroups(accountProducts map[string]string, forceR
|
||||
}
|
||||
if !cfg.enabled {
|
||||
s.closeAccountClients()
|
||||
s.setProxyReadiness(false, "代理未启用")
|
||||
return nil
|
||||
}
|
||||
if !forceRefresh && s.proxyFallbackSnapshot() {
|
||||
if !forceRefresh && !cfg.required && s.proxyFallbackSnapshot() {
|
||||
logger.LogEvent("代理", "warn", "代理此前准备失败,本次抢购直接使用直连,避免再次等待")
|
||||
return nil
|
||||
}
|
||||
if !forceRefresh && s.accountClientsCover(names) {
|
||||
s.setProxyReadiness(true, "")
|
||||
return nil
|
||||
}
|
||||
s.setProxyPreparing("代理正在准备")
|
||||
|
||||
groups := chunkAccountNames(names, cfg.accountsPerProxy)
|
||||
activeCount := len(groups)
|
||||
standbyTarget := proxyStandbyCount(activeCount, cfg.sparePercent)
|
||||
base := s.clientSnapshot()
|
||||
if base == nil {
|
||||
s.activateProxyDirectFallback(errors.New("基础客户端未初始化"))
|
||||
return nil
|
||||
return s.handleProxyPrepareFailure(cfg, names, errors.New("基础客户端未初始化"))
|
||||
}
|
||||
|
||||
poolStartedAt := time.Now()
|
||||
timeout := proxyImmediateTimeout
|
||||
if forceRefresh {
|
||||
timeout = proxyScheduledTimeout
|
||||
timeout := time.Until(deadline)
|
||||
if timeout <= 0 {
|
||||
return s.handleProxyPrepareFailure(cfg, names, errors.New("代理准备截止时间已到"))
|
||||
}
|
||||
proxies, err := s.buildProxyPool(base, cfg, activeCount, activeCount+standbyTarget, nil, timeout)
|
||||
if err != nil {
|
||||
s.activateProxyDirectFallback(err)
|
||||
return nil
|
||||
return s.handleProxyPrepareFailure(cfg, names, err)
|
||||
}
|
||||
if len(proxies) < activeCount {
|
||||
s.activateProxyDirectFallback(fmt.Errorf("代理数量不足: 需要%d个活动代理,实际%d个", activeCount, len(proxies)))
|
||||
return nil
|
||||
closeValidatedProxies(proxies)
|
||||
return s.handleProxyPrepareFailure(cfg, names, fmt.Errorf("代理数量不足: 需要%d个活动代理,实际%d个", activeCount, len(proxies)))
|
||||
}
|
||||
if len(proxies) < activeCount+standbyTarget {
|
||||
logger.LogEvent("代理", "warn", "备用代理不足: 目标%d个,实际%d个;活动代理不受影响",
|
||||
@@ -373,8 +554,12 @@ func (s *Scheduler) prepareProxyGroups(accountProducts map[string]string, forceR
|
||||
proxy := proxies[i]
|
||||
clientOrder = append(clientOrder, proxy.client)
|
||||
runtimeGroups[proxy.client] = &proxyRuntimeGroup{
|
||||
groupIndex: i + 1,
|
||||
accountNames: append([]string(nil), group...),
|
||||
activeURL: proxy.url,
|
||||
activeIP: proxy.ip,
|
||||
activeRegion: proxy.region,
|
||||
activeRTT: proxy.rtt,
|
||||
}
|
||||
for _, name := range group {
|
||||
accountClients[name] = proxy.client
|
||||
@@ -394,6 +579,7 @@ func (s *Scheduler) prepareProxyGroups(accountProducts map[string]string, forceR
|
||||
s.recordProxyResult(proxyClient, err)
|
||||
})
|
||||
}
|
||||
poolStartedAt := time.Now()
|
||||
expiresAt := time.Time{}
|
||||
if cfg.proxyAPI != "" {
|
||||
expiresAt = proxyPoolExpiresAt(cfg.proxyAPI, poolStartedAt)
|
||||
@@ -416,11 +602,60 @@ func (s *Scheduler) prepareProxyGroups(accountProducts map[string]string, forceR
|
||||
standbyTarget: effectiveProxyStandbyTarget(cfg, standbyTarget, len(standbys)),
|
||||
expiresAt: expiresAt,
|
||||
})
|
||||
s.replaceProxyGroupHistory(groups, activeCount, proxies)
|
||||
logger.LogEvent("代理", "success", "代理池准备完成: 账号=%d,每组=%d,活动代理=%d,备用代理=%d/%d",
|
||||
len(names), cfg.accountsPerProxy, activeCount, len(standbys), standbyTarget)
|
||||
s.setProxyReadiness(true, "")
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Scheduler) handleProxyPrepareFailure(cfg proxySettingsSnapshot, names []string, cause error) error {
|
||||
if cfg.required {
|
||||
s.closeAccountClients()
|
||||
s.setProxyReadiness(false, cause.Error())
|
||||
logger.LogEvent("代理", "error", "严格代理模式准备失败,本次不启动且不回退直连: %v", cause)
|
||||
return cause
|
||||
}
|
||||
s.activateProxyDirectFallback(cause)
|
||||
s.setDirectFallbackAccounts(names)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Scheduler) setDirectFallbackAccounts(names []string) {
|
||||
s.clientMu.Lock()
|
||||
if s.directClient != nil {
|
||||
s.accountClients = make(map[string]*client.DouyuClient, len(names))
|
||||
for _, name := range names {
|
||||
s.accountClients[name] = s.directClient
|
||||
}
|
||||
s.accountClientOrder = []*client.DouyuClient{s.directClient}
|
||||
s.accountClientsDirty = false
|
||||
}
|
||||
s.clientMu.Unlock()
|
||||
}
|
||||
|
||||
func (s *Scheduler) setProxyReadiness(ready bool, reason string) {
|
||||
s.proxyMu.Lock()
|
||||
s.proxyReady = ready
|
||||
if ready {
|
||||
s.proxyState = "ready"
|
||||
} else if reason != "" {
|
||||
s.proxyState = "failed"
|
||||
} else {
|
||||
s.proxyState = "empty"
|
||||
}
|
||||
s.proxyBlockedReason = reason
|
||||
s.proxyMu.Unlock()
|
||||
}
|
||||
|
||||
func (s *Scheduler) setProxyPreparing(reason string) {
|
||||
s.proxyMu.Lock()
|
||||
s.proxyReady = false
|
||||
s.proxyState = "preparing"
|
||||
s.proxyBlockedReason = reason
|
||||
s.proxyMu.Unlock()
|
||||
}
|
||||
|
||||
func (s *Scheduler) proxyFallbackSnapshot() bool {
|
||||
s.clientMu.RLock()
|
||||
defer s.clientMu.RUnlock()
|
||||
@@ -434,9 +669,11 @@ func (s *Scheduler) activateProxyDirectFallback(cause error) {
|
||||
s.proxyFallbackActive = active
|
||||
s.clientMu.Unlock()
|
||||
if active {
|
||||
s.setProxyReadiness(false, cause.Error())
|
||||
logger.LogEvent("代理", "warn", "代理准备失败,已回退直连以保证抢购继续: %v", cause)
|
||||
return
|
||||
}
|
||||
s.setProxyReadiness(false, cause.Error())
|
||||
logger.LogEvent("代理", "error", "代理准备失败且直连客户端不可用: %v", cause)
|
||||
}
|
||||
|
||||
@@ -452,6 +689,10 @@ func (s *Scheduler) PrepareProxyGroups(accountProducts map[string]string) error
|
||||
return s.prepareProxyGroups(accountProducts, false)
|
||||
}
|
||||
|
||||
func (s *Scheduler) PrepareProxyGroupsUntil(accountProducts map[string]string, deadline time.Time) error {
|
||||
return s.prepareProxyGroupsUntil(accountProducts, true, deadline)
|
||||
}
|
||||
|
||||
func selectedAccountNames(accountProducts map[string]string) []string {
|
||||
names := make([]string, 0, len(accountProducts))
|
||||
for name, productID := range accountProducts {
|
||||
@@ -487,7 +728,7 @@ func proxyStandbyCount(activeCount, sparePercent int) int {
|
||||
if activeCount <= 0 {
|
||||
return 0
|
||||
}
|
||||
if sparePercent <= 0 {
|
||||
if sparePercent < constants.MinProxySparePercent {
|
||||
sparePercent = constants.DefaultProxySparePercent
|
||||
}
|
||||
if sparePercent > constants.MaxProxySparePercent {
|
||||
@@ -726,6 +967,7 @@ func (s *Scheduler) recordProxyResult(proxyClient *client.DouyuClient, err error
|
||||
if proxyClient == nil {
|
||||
return
|
||||
}
|
||||
cfg := s.proxySettings()
|
||||
|
||||
s.clientMu.Lock()
|
||||
group := s.proxyGroups[proxyClient]
|
||||
@@ -735,6 +977,8 @@ func (s *Scheduler) recordProxyResult(proxyClient *client.DouyuClient, err error
|
||||
}
|
||||
if err == nil {
|
||||
group.consecutiveFailures = 0
|
||||
group.lastError = ""
|
||||
s.updateProxyGroupHistoryLocked(group)
|
||||
s.clientMu.Unlock()
|
||||
return
|
||||
}
|
||||
@@ -744,6 +988,8 @@ func (s *Scheduler) recordProxyResult(proxyClient *client.DouyuClient, err error
|
||||
}
|
||||
|
||||
group.consecutiveFailures++
|
||||
group.lastError = err.Error()
|
||||
s.updateProxyGroupHistoryLocked(group)
|
||||
if group.consecutiveFailures < 2 {
|
||||
failures := group.consecutiveFailures
|
||||
activeURL := group.activeURL
|
||||
@@ -753,7 +999,9 @@ func (s *Scheduler) recordProxyResult(proxyClient *client.DouyuClient, err error
|
||||
}
|
||||
|
||||
event, expiredClients, switched := s.switchGroupToStandbyLocked(proxyClient, group)
|
||||
if !switched && s.directClient != nil {
|
||||
if !switched && cfg.required {
|
||||
group.failed = true
|
||||
} else if !switched && s.directClient != nil {
|
||||
event = s.switchGroupToDirectLocked(proxyClient, group)
|
||||
switched = true
|
||||
}
|
||||
@@ -767,6 +1015,7 @@ func (s *Scheduler) recordProxyResult(proxyClient *client.DouyuClient, err error
|
||||
failedAccounts = len(group.accountNames)
|
||||
failedURL = group.activeURL
|
||||
needRefill = !s.proxyRefillInFlight
|
||||
s.updateProxyGroupHistoryLocked(group)
|
||||
}
|
||||
s.clientMu.Unlock()
|
||||
|
||||
@@ -774,8 +1023,13 @@ func (s *Scheduler) recordProxyResult(proxyClient *client.DouyuClient, err error
|
||||
if switched {
|
||||
logProxySwitch("代理故障切换", event)
|
||||
} else {
|
||||
logger.LogEvent("代理", "warn", "代理组连续失败且暂无备用: 账号=%d 出口=%s,正在尝试补提取",
|
||||
failedAccounts, client.MaskProxyURL(failedURL))
|
||||
if cfg.required {
|
||||
logger.LogEvent("代理", "warn", "严格代理模式下代理组连续失败且暂无备用,暂不直连并等待补提取: 账号=%d 出口=%s",
|
||||
failedAccounts, client.MaskProxyURL(failedURL))
|
||||
} else {
|
||||
logger.LogEvent("代理", "warn", "代理组连续失败且暂无备用: 账号=%d 出口=%s,正在尝试补提取",
|
||||
failedAccounts, client.MaskProxyURL(failedURL))
|
||||
}
|
||||
}
|
||||
if needRefill {
|
||||
s.startProxyRefill()
|
||||
@@ -802,7 +1056,12 @@ func (s *Scheduler) switchGroupToStandbyLocked(oldClient *client.DouyuClient, gr
|
||||
toSource: standby.source,
|
||||
}
|
||||
group.activeURL = standby.url
|
||||
group.activeIP = standby.ip
|
||||
group.activeRegion = standby.region
|
||||
group.activeRTT = standby.rtt
|
||||
group.switchCount++
|
||||
group.consecutiveFailures = 0
|
||||
group.lastError = ""
|
||||
group.failed = false
|
||||
for _, accountName := range group.accountNames {
|
||||
s.accountClients[accountName] = standby.client
|
||||
@@ -810,6 +1069,7 @@ func (s *Scheduler) switchGroupToStandbyLocked(oldClient *client.DouyuClient, gr
|
||||
delete(s.proxyGroups, oldClient)
|
||||
s.proxyGroups[standby.client] = group
|
||||
replaceClientInOrder(s.accountClientOrder, oldClient, standby.client)
|
||||
s.updateProxyGroupHistoryLocked(group)
|
||||
return event, expiredClients, true
|
||||
}
|
||||
return proxySwitchEvent{}, expiredClients, false
|
||||
@@ -821,16 +1081,52 @@ func (s *Scheduler) switchGroupToDirectLocked(oldClient *client.DouyuClient, gro
|
||||
fromURL: group.activeURL,
|
||||
}
|
||||
group.activeURL = ""
|
||||
group.activeIP = ""
|
||||
group.activeRegion = ""
|
||||
group.activeRTT = 0
|
||||
group.switchCount++
|
||||
group.consecutiveFailures = 0
|
||||
group.lastError = ""
|
||||
group.failed = false
|
||||
for _, accountName := range group.accountNames {
|
||||
s.accountClients[accountName] = s.directClient
|
||||
}
|
||||
delete(s.proxyGroups, oldClient)
|
||||
replaceClientInOrder(s.accountClientOrder, oldClient, s.directClient)
|
||||
s.updateProxyGroupHistoryLocked(group)
|
||||
return event
|
||||
}
|
||||
|
||||
func (s *Scheduler) updateProxyGroupHistoryLocked(group *proxyRuntimeGroup) {
|
||||
if group == nil || group.groupIndex <= 0 {
|
||||
return
|
||||
}
|
||||
for i := range s.proxyGroupHistory {
|
||||
item := &s.proxyGroupHistory[i]
|
||||
if item.GroupIndex != group.groupIndex {
|
||||
continue
|
||||
}
|
||||
item.AccountCount = len(group.accountNames)
|
||||
item.Accounts = append([]string(nil), group.accountNames...)
|
||||
item.SwitchCount = group.switchCount
|
||||
item.LastError = group.lastError
|
||||
switch {
|
||||
case group.activeURL == "":
|
||||
item.State = "direct"
|
||||
item.Proxy = ""
|
||||
item.Region = ""
|
||||
case group.failed:
|
||||
item.State = "failed"
|
||||
default:
|
||||
item.State = "active"
|
||||
item.Proxy = client.MaskProxyURL(group.activeURL)
|
||||
item.Region = group.activeRegion
|
||||
item.RTTMs = group.activeRTT.Milliseconds()
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
func replaceClientInOrder(order []*client.DouyuClient, oldClient, newClient *client.DouyuClient) {
|
||||
for i, cli := range order {
|
||||
if cli == oldClient {
|
||||
|
||||
@@ -47,10 +47,10 @@ func TestProxyStandbyCount(t *testing.T) {
|
||||
percent int
|
||||
want int
|
||||
}{
|
||||
{active: 1, percent: 25, want: 1},
|
||||
{active: 6, percent: 25, want: 2},
|
||||
{active: 10, percent: 25, want: 3},
|
||||
{active: 6, percent: 1, want: 1},
|
||||
{active: 1, percent: 50, want: 1},
|
||||
{active: 6, percent: 50, want: 3},
|
||||
{active: 10, percent: 50, want: 5},
|
||||
{active: 6, percent: 1, want: 3},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
if got := proxyStandbyCount(tc.active, tc.percent); got != tc.want {
|
||||
@@ -59,6 +59,26 @@ func TestProxyStandbyCount(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestShouldPrepareProxyOnSchedule(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
cfg proxySettingsSnapshot
|
||||
want bool
|
||||
}{
|
||||
{name: "disabled", cfg: proxySettingsSnapshot{required: true}, want: false},
|
||||
{name: "strict static", cfg: proxySettingsSnapshot{enabled: true, required: true}, want: true},
|
||||
{name: "auto fetch api", cfg: proxySettingsSnapshot{enabled: true, autoFetchOnTimer: true, proxyAPI: "https://example.test"}, want: true},
|
||||
{name: "optional api without auto fetch", cfg: proxySettingsSnapshot{enabled: true, proxyAPI: "https://example.test"}, want: false},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
if got := shouldPrepareProxyOnSchedule(tc.cfg); got != tc.want {
|
||||
t.Fatalf("shouldPrepareProxyOnSchedule()=%v, want %v", got, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestAccountClientsRespectExpiryAndSettingsRevision(t *testing.T) {
|
||||
scheduler := &Scheduler{
|
||||
client: &client.DouyuClient{},
|
||||
@@ -105,7 +125,7 @@ func TestPrepareProxyGroupsRoutesAccountsToDistinctClients(t *testing.T) {
|
||||
ProxyAPI: apiServer.URL,
|
||||
AutoFetchProxyOnSchedule: true,
|
||||
AccountsPerProxy: 2,
|
||||
ProxySparePercent: 25,
|
||||
ProxySparePercent: 50,
|
||||
})
|
||||
|
||||
accountProducts := make(map[string]string)
|
||||
@@ -128,8 +148,8 @@ func TestPrepareProxyGroupsRoutesAccountsToDistinctClients(t *testing.T) {
|
||||
if scheduler.clientForAccount("e") == scheduler.clientForAccount("a") {
|
||||
t.Fatal("e 应使用独立代理客户端")
|
||||
}
|
||||
if len(scheduler.proxyStandbys) != 1 {
|
||||
t.Fatalf("备用代理=%d, want 1", len(scheduler.proxyStandbys))
|
||||
if len(scheduler.proxyStandbys) != 2 {
|
||||
t.Fatalf("备用代理=%d, want 2", len(scheduler.proxyStandbys))
|
||||
}
|
||||
|
||||
standbyClient := scheduler.proxyStandbys[0].client
|
||||
@@ -137,7 +157,7 @@ func TestPrepareProxyGroupsRoutesAccountsToDistinctClients(t *testing.T) {
|
||||
ProxyEnabled: true,
|
||||
ProxyURL: "http://127.0.0.1:1",
|
||||
AccountsPerProxy: 2,
|
||||
ProxySparePercent: 25,
|
||||
ProxySparePercent: 50,
|
||||
})
|
||||
proxyErr := errors.New("read tcp: connection reset by peer")
|
||||
scheduler.recordProxyResult(scheduler.clientForAccount("a"), proxyErr)
|
||||
@@ -169,7 +189,7 @@ func TestPrepareProxyGroupsFallsBackDirectAndSkipsRepeatedWait(t *testing.T) {
|
||||
ProxyEnabled: true,
|
||||
ProxyAPI: apiServer.URL,
|
||||
AccountsPerProxy: 5,
|
||||
ProxySparePercent: 25,
|
||||
ProxySparePercent: 50,
|
||||
})
|
||||
accountProducts := map[string]string{"a": "goods-1"}
|
||||
|
||||
@@ -218,6 +238,123 @@ func TestProxyGroupSwitchesDirectWhenStandbyUnavailable(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestStrictProxyModeDoesNotSwitchDirect(t *testing.T) {
|
||||
act := *activity.Get("peace")
|
||||
base := client.New(&act, "http://douyu.test/time", &trace.Recorder{}, "")
|
||||
scheduler := New(base, types.AppPaths{}, nil, 8, 1, nil, types.SeckillModeAggressive)
|
||||
scheduler.UpdateProxySettings(types.Config{
|
||||
ProxyEnabled: true,
|
||||
ProxyRequired: true,
|
||||
AccountsPerProxy: 5,
|
||||
ProxySparePercent: 50,
|
||||
})
|
||||
groupClient := &client.DouyuClient{}
|
||||
group := &proxyRuntimeGroup{
|
||||
groupIndex: 1,
|
||||
accountNames: []string{"a"},
|
||||
activeURL: "http://user:pass@127.0.0.1:9000",
|
||||
}
|
||||
scheduler.replaceAccountClients(preparedProxyPool{
|
||||
accountClients: map[string]*client.DouyuClient{"a": groupClient},
|
||||
activeClients: []*client.DouyuClient{groupClient},
|
||||
groups: map[*client.DouyuClient]*proxyRuntimeGroup{groupClient: group},
|
||||
allClients: []*client.DouyuClient{groupClient},
|
||||
})
|
||||
scheduler.replaceProxyGroupHistory([][]string{{"a"}}, 1, []validatedProxy{{
|
||||
url: group.activeURL,
|
||||
client: groupClient,
|
||||
}})
|
||||
|
||||
proxyErr := errors.New("read tcp: connection reset by peer")
|
||||
scheduler.recordProxyResult(groupClient, proxyErr)
|
||||
scheduler.recordProxyResult(groupClient, proxyErr)
|
||||
if scheduler.clientForAccount("a") == scheduler.directClient {
|
||||
t.Fatal("strict proxy mode must not switch to direct")
|
||||
}
|
||||
if !group.failed {
|
||||
t.Fatal("failed group should remain tracked for standby refill")
|
||||
}
|
||||
}
|
||||
|
||||
func TestProxyStatusReportsGroupAndAccountMapping(t *testing.T) {
|
||||
act := *activity.Get("peace")
|
||||
base := client.New(&act, "http://douyu.test/time", &trace.Recorder{}, "")
|
||||
scheduler := New(base, types.AppPaths{}, nil, 8, 1, nil, types.SeckillModeAggressive)
|
||||
scheduler.UpdateProxySettings(types.Config{
|
||||
ProxyEnabled: true,
|
||||
AccountsPerProxy: 2,
|
||||
ProxySparePercent: 50,
|
||||
})
|
||||
groupClient := &client.DouyuClient{}
|
||||
group := &proxyRuntimeGroup{
|
||||
groupIndex: 1,
|
||||
accountNames: []string{"a", "b"},
|
||||
activeURL: "http://user:pass@127.0.0.1:9000",
|
||||
activeIP: "127.0.0.1",
|
||||
activeRegion: "test",
|
||||
activeRTT: 45 * time.Millisecond,
|
||||
}
|
||||
standbyClient := &client.DouyuClient{}
|
||||
scheduler.replaceAccountClients(preparedProxyPool{
|
||||
accountClients: map[string]*client.DouyuClient{"a": groupClient, "b": groupClient},
|
||||
activeClients: []*client.DouyuClient{groupClient},
|
||||
groups: map[*client.DouyuClient]*proxyRuntimeGroup{groupClient: group},
|
||||
standbys: []validatedProxy{{client: standbyClient}},
|
||||
allClients: []*client.DouyuClient{groupClient, standbyClient},
|
||||
standbyTarget: 1,
|
||||
})
|
||||
scheduler.replaceProxyGroupHistory([][]string{{"a", "b"}}, 1, []validatedProxy{{
|
||||
url: group.activeURL,
|
||||
client: groupClient,
|
||||
ip: group.activeIP,
|
||||
region: group.activeRegion,
|
||||
rtt: group.activeRTT,
|
||||
}})
|
||||
scheduler.setProxyReadiness(true, "")
|
||||
|
||||
status := scheduler.ProxyStatus()
|
||||
if status.State != "ready" || status.ActiveCount != 1 || len(status.Groups) != 1 {
|
||||
t.Fatalf("unexpected status: %+v", status)
|
||||
}
|
||||
if len(status.Accounts) != 2 || status.Accounts[0].GroupLabel != "G1" || status.Accounts[0].Transport != "proxy" {
|
||||
t.Fatalf("unexpected account mapping: %+v", status.Accounts)
|
||||
}
|
||||
if status.Groups[0].Proxy == "" || status.Groups[0].Proxy == group.activeURL {
|
||||
t.Fatalf("proxy URL should be masked, got %q", status.Groups[0].Proxy)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStrictPrepareFailureBlocksRun(t *testing.T) {
|
||||
apiServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
fmt.Fprint(w, `{"code":-1,"status":200,"message":"secret密匙错误"}`)
|
||||
}))
|
||||
defer apiServer.Close()
|
||||
act := *activity.Get("peace")
|
||||
base := client.New(&act, "http://douyu.test/time", &trace.Recorder{}, "")
|
||||
scheduler := New(base, types.AppPaths{}, nil, 8, 1, nil, types.SeckillModeAggressive)
|
||||
scheduler.UpdateProxySettings(types.Config{
|
||||
ProxyEnabled: true,
|
||||
ProxyRequired: true,
|
||||
ProxyAPI: apiServer.URL,
|
||||
AccountsPerProxy: 5,
|
||||
ProxySparePercent: 50,
|
||||
})
|
||||
err := scheduler.prepareProxyGroupsUntil(map[string]string{"a": "goods-1"}, false, time.Now().Add(2*time.Second))
|
||||
if err == nil {
|
||||
t.Fatal("strict proxy preparation should fail")
|
||||
}
|
||||
if scheduler.proxyFallbackSnapshot() {
|
||||
t.Fatal("strict mode must not activate direct fallback")
|
||||
}
|
||||
if ok, _ := scheduler.ProxyRunGate(); ok {
|
||||
t.Fatal("strict mode run gate should remain closed")
|
||||
}
|
||||
if status := scheduler.ProxyStatus(); status.State != "failed" {
|
||||
t.Fatalf("proxy status=%q, want failed", status.State)
|
||||
}
|
||||
}
|
||||
|
||||
func newTimeProxyServer(t *testing.T) *httptest.Server {
|
||||
t.Helper()
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
@@ -48,7 +48,7 @@ func (s *Scheduler) ScheduleRun(req types.SeckillRequest) (types.ScheduleResult,
|
||||
|
||||
proxyCfg := s.proxySettings()
|
||||
|
||||
if proxyCfg.enabled && proxyCfg.autoFetchOnTimer && proxyCfg.proxyAPI != "" {
|
||||
if shouldPrepareProxyOnSchedule(proxyCfg) {
|
||||
proxyFetchRemain := triggerTime.Sub(serverTime) - proxyFetchBeforeTrigger
|
||||
if proxyFetchRemain < 0 {
|
||||
proxyFetchRemain = 0
|
||||
@@ -58,8 +58,10 @@ func (s *Scheduler) ScheduleRun(req types.SeckillRequest) (types.ScheduleResult,
|
||||
if s.IsRunning() {
|
||||
return
|
||||
}
|
||||
logger.LogEvent("代理", "info", "定时任务触发前,自动提取并校验分组代理...")
|
||||
if err := s.prepareProxyGroups(ap, true); err != nil {
|
||||
deadline := triggerTime.Add(-proxyReadyDeadline)
|
||||
logger.LogEvent("代理", "info", "定时任务触发前 2 分钟,开始提取并校验分组代理,截止=%s",
|
||||
deadline.In(constants.CST).Format("15:04:05.000"))
|
||||
if err := s.prepareProxyGroupsUntil(ap, true, deadline); err != nil {
|
||||
logger.LogEvent("代理", "error", "定时分组代理准备失败: %v", err)
|
||||
return
|
||||
}
|
||||
@@ -120,6 +122,13 @@ func (s *Scheduler) ScheduleRun(req types.SeckillRequest) (types.ScheduleResult,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func shouldPrepareProxyOnSchedule(cfg proxySettingsSnapshot) bool {
|
||||
if !cfg.enabled {
|
||||
return false
|
||||
}
|
||||
return cfg.required || (cfg.autoFetchOnTimer && cfg.proxyAPI != "")
|
||||
}
|
||||
|
||||
func (s *Scheduler) scheduleTimers(accountProducts map[string]string, targetTime, triggerTime time.Time, calibration types.TimeCalibration, attempts, delayMs int, resync bool) {
|
||||
serverTime := calibration.EstimatedServerNow()
|
||||
remain := triggerTime.Sub(serverTime)
|
||||
@@ -154,6 +163,10 @@ func (s *Scheduler) scheduleTimers(accountProducts map[string]string, targetTime
|
||||
estimatedServer.In(constants.CST).Format("15:04:05.000"),
|
||||
calibration.Offset.Milliseconds(),
|
||||
calibration.ErrorBound.Milliseconds())
|
||||
if ok, reason := s.ProxyRunGate(); !ok {
|
||||
logger.LogEvent("代理", "error", "严格代理模式未就绪,本次定时抢购不启动: %s", reason)
|
||||
return
|
||||
}
|
||||
if !s.TryStartRun() {
|
||||
logger.LogEvent("抢购", "warn", "已有抢购任务正在运行,本次定时触发已跳过")
|
||||
return
|
||||
|
||||
@@ -28,7 +28,8 @@ const (
|
||||
timeCalibrateRounds = 3
|
||||
timeCalibrateWait = 1200 * time.Millisecond
|
||||
resyncBeforeTrigger = 8 * time.Second
|
||||
proxyFetchBeforeTrigger = 30 * time.Second
|
||||
proxyFetchBeforeTrigger = 120 * time.Second
|
||||
proxyReadyDeadline = 15 * time.Second
|
||||
calibrationHistorySize = 3
|
||||
maxCooldownCount = 5
|
||||
xiaodianDefaultDelay = 500 * time.Millisecond
|
||||
@@ -68,6 +69,8 @@ type Scheduler struct {
|
||||
accountClientsDirty bool
|
||||
accountClientsExpireAt time.Time
|
||||
proxyGroups map[*client.DouyuClient]*proxyRuntimeGroup
|
||||
proxyGroupHistory []types.ProxyGroupStatus
|
||||
accountProxyGroup map[string]int
|
||||
proxyStandbys []validatedProxy
|
||||
proxyClientPool []*client.DouyuClient
|
||||
proxyExcludedURLs map[string]struct{}
|
||||
@@ -120,6 +123,10 @@ type Scheduler struct {
|
||||
autoFetchProxyOnSchedule bool
|
||||
accountsPerProxy int
|
||||
proxySparePercent int
|
||||
proxyRequired bool
|
||||
proxyReady bool
|
||||
proxyState string
|
||||
proxyBlockedReason string
|
||||
autoWhitelist bool
|
||||
whitelistReplace bool
|
||||
whitelistPassword string
|
||||
@@ -465,6 +472,23 @@ func (s *Scheduler) IsRunning() bool {
|
||||
return s.running
|
||||
}
|
||||
|
||||
// ProxyRunGate reports whether a run may start under strict proxy mode.
|
||||
func (s *Scheduler) ProxyRunGate() (bool, string) {
|
||||
s.proxyMu.RLock()
|
||||
defer s.proxyMu.RUnlock()
|
||||
if !s.proxyEnabled || !s.proxyRequired {
|
||||
return true, ""
|
||||
}
|
||||
if s.proxyReady {
|
||||
return true, ""
|
||||
}
|
||||
reason := s.proxyBlockedReason
|
||||
if reason == "" {
|
||||
reason = "代理尚未就绪"
|
||||
}
|
||||
return false, reason
|
||||
}
|
||||
|
||||
func (s *Scheduler) stopRunChan() <-chan struct{} {
|
||||
s.runMu.Lock()
|
||||
defer s.runMu.Unlock()
|
||||
@@ -519,6 +543,10 @@ func (s *Scheduler) RunNow(accountProducts map[string]string) {
|
||||
logger.LogEvent("代理", "error", "分组代理准备失败,本次抢购不执行: %v", err)
|
||||
return
|
||||
}
|
||||
if ok, reason := s.ProxyRunGate(); !ok {
|
||||
logger.LogEvent("代理", "error", "严格代理模式未就绪,本次抢购不执行: %s", reason)
|
||||
return
|
||||
}
|
||||
|
||||
start := time.Now()
|
||||
deadline := start.Add(seckillMaxDuration)
|
||||
@@ -1194,6 +1222,10 @@ func (s *Scheduler) RunXiaodian(accountProducts map[string]string, attempts, del
|
||||
logger.LogEvent("代理", "error", "分组代理准备失败,本次和平小店抢购不执行: %v", err)
|
||||
return
|
||||
}
|
||||
if ok, reason := s.ProxyRunGate(); !ok {
|
||||
logger.LogEvent("代理", "error", "严格代理模式未就绪,本次和平小店抢购不执行: %s", reason)
|
||||
return
|
||||
}
|
||||
s.startXiaodianReport(accounts, products, reportSessionID)
|
||||
|
||||
stoppedAccounts := make(map[string]string)
|
||||
|
||||
Reference in New Issue
Block a user