fix(seckill): 代理失败时快速回退直连,发布 0.5.3
This commit is contained in:
@@ -26,6 +26,9 @@ const (
|
||||
proxyValidationTimeout = 3 * time.Second
|
||||
proxyValidationWorkers = 3
|
||||
proxyValidateAttempts = 1
|
||||
proxyImmediateTimeout = 5 * time.Second
|
||||
proxyScheduledTimeout = 20 * time.Second
|
||||
proxyRefillTimeout = 20 * time.Second
|
||||
)
|
||||
|
||||
type proxySettingsSnapshot struct {
|
||||
@@ -131,6 +134,7 @@ func (s *Scheduler) UpdateProxySettings(cfg types.Config) {
|
||||
}
|
||||
s.clientMu.Lock()
|
||||
s.accountClientsDirty = true
|
||||
s.proxyFallbackActive = false
|
||||
s.clientMu.Unlock()
|
||||
}
|
||||
|
||||
@@ -182,6 +186,7 @@ func (s *Scheduler) closeAccountClients() {
|
||||
s.proxyStandbyTarget = 0
|
||||
s.proxyPoolGeneration++
|
||||
s.proxyRefillInFlight = false
|
||||
s.proxyFallbackActive = false
|
||||
s.clientMu.Unlock()
|
||||
closeDouyuClientList(oldClients)
|
||||
}
|
||||
@@ -212,6 +217,7 @@ func (s *Scheduler) replaceAccountClients(pool preparedProxyPool) {
|
||||
s.proxyStandbyTarget = pool.standbyTarget
|
||||
s.proxyPoolGeneration++
|
||||
s.proxyRefillInFlight = false
|
||||
s.proxyFallbackActive = false
|
||||
s.clientMu.Unlock()
|
||||
closeDouyuClientList(oldClients)
|
||||
}
|
||||
@@ -272,6 +278,9 @@ func (s *Scheduler) accountClientsCover(accountNames []string) bool {
|
||||
func (s *Scheduler) calibrationClient() *client.DouyuClient {
|
||||
s.clientMu.RLock()
|
||||
defer s.clientMu.RUnlock()
|
||||
if s.proxyFallbackActive && s.directClient != nil {
|
||||
return s.directClient
|
||||
}
|
||||
if len(s.accountClientOrder) > 0 && s.accountClientOrder[0] != nil {
|
||||
return s.accountClientOrder[0]
|
||||
}
|
||||
@@ -287,6 +296,12 @@ func (s *Scheduler) allClients() []*client.DouyuClient {
|
||||
seen[s.client] = struct{}{}
|
||||
out = append(out, s.client)
|
||||
}
|
||||
if (s.proxyFallbackActive || s.client == nil) && s.directClient != nil {
|
||||
if _, ok := seen[s.directClient]; !ok {
|
||||
seen[s.directClient] = struct{}{}
|
||||
out = append(out, s.directClient)
|
||||
}
|
||||
}
|
||||
for _, cli := range s.accountClientOrder {
|
||||
if cli == nil {
|
||||
continue
|
||||
@@ -315,6 +330,10 @@ func (s *Scheduler) prepareProxyGroups(accountProducts map[string]string, forceR
|
||||
s.closeAccountClients()
|
||||
return nil
|
||||
}
|
||||
if !forceRefresh && s.proxyFallbackSnapshot() {
|
||||
logger.LogEvent("代理", "warn", "代理此前准备失败,本次抢购直接使用直连,避免再次等待")
|
||||
return nil
|
||||
}
|
||||
if !forceRefresh && s.accountClientsCover(names) {
|
||||
return nil
|
||||
}
|
||||
@@ -324,16 +343,23 @@ func (s *Scheduler) prepareProxyGroups(accountProducts map[string]string, forceR
|
||||
standbyTarget := proxyStandbyCount(activeCount, cfg.sparePercent)
|
||||
base := s.clientSnapshot()
|
||||
if base == nil {
|
||||
return errors.New("基础客户端未初始化")
|
||||
s.activateProxyDirectFallback(errors.New("基础客户端未初始化"))
|
||||
return nil
|
||||
}
|
||||
|
||||
poolStartedAt := time.Now()
|
||||
proxies, err := s.buildProxyPool(base, cfg, activeCount, activeCount+standbyTarget, nil)
|
||||
timeout := proxyImmediateTimeout
|
||||
if forceRefresh {
|
||||
timeout = proxyScheduledTimeout
|
||||
}
|
||||
proxies, err := s.buildProxyPool(base, cfg, activeCount, activeCount+standbyTarget, nil, timeout)
|
||||
if err != nil {
|
||||
return err
|
||||
s.activateProxyDirectFallback(err)
|
||||
return nil
|
||||
}
|
||||
if len(proxies) < activeCount {
|
||||
return fmt.Errorf("代理数量不足: 需要%d个活动代理,实际%d个", activeCount, len(proxies))
|
||||
s.activateProxyDirectFallback(fmt.Errorf("代理数量不足: 需要%d个活动代理,实际%d个", activeCount, len(proxies)))
|
||||
return nil
|
||||
}
|
||||
if len(proxies) < activeCount+standbyTarget {
|
||||
logger.LogEvent("代理", "warn", "备用代理不足: 目标%d个,实际%d个;活动代理不受影响",
|
||||
@@ -395,6 +421,25 @@ func (s *Scheduler) prepareProxyGroups(accountProducts map[string]string, forceR
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Scheduler) proxyFallbackSnapshot() bool {
|
||||
s.clientMu.RLock()
|
||||
defer s.clientMu.RUnlock()
|
||||
return s.proxyFallbackActive
|
||||
}
|
||||
|
||||
func (s *Scheduler) activateProxyDirectFallback(cause error) {
|
||||
s.closeAccountClients()
|
||||
s.clientMu.Lock()
|
||||
active := s.directClient != nil
|
||||
s.proxyFallbackActive = active
|
||||
s.clientMu.Unlock()
|
||||
if active {
|
||||
logger.LogEvent("代理", "warn", "代理准备失败,已回退直连以保证抢购继续: %v", cause)
|
||||
return
|
||||
}
|
||||
logger.LogEvent("代理", "error", "代理准备失败且直连客户端不可用: %v", cause)
|
||||
}
|
||||
|
||||
func effectiveProxyStandbyTarget(cfg proxySettingsSnapshot, target, actual int) int {
|
||||
if cfg.proxyAPI == "" {
|
||||
return actual
|
||||
@@ -455,15 +500,16 @@ func proxyStandbyCount(activeCount, sparePercent int) int {
|
||||
return count
|
||||
}
|
||||
|
||||
func (s *Scheduler) buildProxyPool(base *client.DouyuClient, cfg proxySettingsSnapshot, required, desired int, excludedURLs map[string]struct{}) ([]validatedProxy, error) {
|
||||
func (s *Scheduler) buildProxyPool(base *client.DouyuClient, cfg proxySettingsSnapshot, required, desired int, excludedURLs map[string]struct{}, timeout time.Duration) ([]validatedProxy, error) {
|
||||
if desired < required {
|
||||
desired = required
|
||||
}
|
||||
if required <= 0 {
|
||||
return nil, nil
|
||||
}
|
||||
deadline := time.Now().Add(timeout)
|
||||
if cfg.proxyAPI != "" {
|
||||
proxies, err := s.fetchAndValidateProxyPool(base, cfg, desired, excludedURLs)
|
||||
proxies, err := s.fetchAndValidateProxyPool(base, cfg, desired, excludedURLs, timeout)
|
||||
if len(proxies) >= required {
|
||||
if len(proxies) < desired {
|
||||
logger.LogEvent("代理", "warn", "动态代理备用数量不足: 目标%d个,实际%d个", desired, len(proxies))
|
||||
@@ -490,7 +536,11 @@ func (s *Scheduler) buildProxyPool(base *client.DouyuClient, cfg proxySettingsSn
|
||||
}
|
||||
templates := make([]validatedProxy, 0, validateCount)
|
||||
for _, rawURL := range staticURLs[:validateCount] {
|
||||
proxy, err := s.validateProxy(base, rawURL, "静态")
|
||||
if time.Now().After(deadline) {
|
||||
closeValidatedProxies(templates)
|
||||
return nil, errors.New("静态代理校验超时")
|
||||
}
|
||||
proxy, err := s.validateProxy(base, rawURL, "静态", time.Until(deadline))
|
||||
if err != nil {
|
||||
closeValidatedProxies(templates)
|
||||
return nil, fmt.Errorf("静态代理不可用: %w", err)
|
||||
@@ -570,7 +620,7 @@ func splitProxyURLs(raw string) []string {
|
||||
return out
|
||||
}
|
||||
|
||||
func (s *Scheduler) fetchAndValidateProxyPool(base *client.DouyuClient, cfg proxySettingsSnapshot, count int, excludedURLs map[string]struct{}) ([]validatedProxy, error) {
|
||||
func (s *Scheduler) fetchAndValidateProxyPool(base *client.DouyuClient, cfg proxySettingsSnapshot, count int, excludedURLs map[string]struct{}, timeout time.Duration) ([]validatedProxy, error) {
|
||||
service := s.proxyService
|
||||
if service == nil {
|
||||
service = proxyprovider.NewService()
|
||||
@@ -583,6 +633,7 @@ func (s *Scheduler) fetchAndValidateProxyPool(base *client.DouyuClient, cfg prox
|
||||
seen[rawURL] = struct{}{}
|
||||
}
|
||||
var lastErr error
|
||||
deadline := time.Now().Add(timeout)
|
||||
|
||||
rounds := proxyFetchRounds
|
||||
if count > rounds {
|
||||
@@ -592,12 +643,23 @@ func (s *Scheduler) fetchAndValidateProxyPool(base *client.DouyuClient, cfg prox
|
||||
rounds = proxyFetchMaxRounds
|
||||
}
|
||||
for round := 0; round < rounds; round++ {
|
||||
remaining := time.Until(deadline)
|
||||
if remaining <= 0 {
|
||||
if lastErr == nil {
|
||||
lastErr = errors.New("代理准备总时长超时")
|
||||
}
|
||||
break
|
||||
}
|
||||
need := count - len(proxies)
|
||||
if need <= 0 {
|
||||
break
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), proxyRequestTimeout)
|
||||
requestTimeout := proxyRequestTimeout
|
||||
if remaining < requestTimeout {
|
||||
requestTimeout = remaining
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), requestTimeout)
|
||||
endpoints, err := service.ExtractWithWhitelist(ctx, cfg.proxyAPI, need, proxyprovider.WhitelistConfig{
|
||||
APIURL: cfg.proxyAPI,
|
||||
LoginPassword: cfg.whitelistPassword,
|
||||
@@ -612,7 +674,7 @@ func (s *Scheduler) fetchAndValidateProxyPool(base *client.DouyuClient, cfg prox
|
||||
break
|
||||
}
|
||||
} else {
|
||||
validated := s.validateProxyBatch(base, endpoints)
|
||||
validated := s.validateProxyBatch(base, endpoints, deadline)
|
||||
for _, item := range validated {
|
||||
if item.err != nil {
|
||||
lastErr = item.err
|
||||
@@ -641,7 +703,13 @@ func (s *Scheduler) fetchAndValidateProxyPool(base *client.DouyuClient, cfg prox
|
||||
}
|
||||
|
||||
if round < rounds-1 {
|
||||
time.Sleep(proxyFetchRetryWait)
|
||||
wait := proxyFetchRetryWait
|
||||
if remaining := time.Until(deadline); remaining < wait {
|
||||
wait = remaining
|
||||
}
|
||||
if wait > 0 {
|
||||
time.Sleep(wait)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -685,6 +753,10 @@ func (s *Scheduler) recordProxyResult(proxyClient *client.DouyuClient, err error
|
||||
}
|
||||
|
||||
event, expiredClients, switched := s.switchGroupToStandbyLocked(proxyClient, group)
|
||||
if !switched && s.directClient != nil {
|
||||
event = s.switchGroupToDirectLocked(proxyClient, group)
|
||||
switched = true
|
||||
}
|
||||
needRefill := false
|
||||
failedAccounts := 0
|
||||
failedURL := ""
|
||||
@@ -743,6 +815,22 @@ func (s *Scheduler) switchGroupToStandbyLocked(oldClient *client.DouyuClient, gr
|
||||
return proxySwitchEvent{}, expiredClients, false
|
||||
}
|
||||
|
||||
func (s *Scheduler) switchGroupToDirectLocked(oldClient *client.DouyuClient, group *proxyRuntimeGroup) proxySwitchEvent {
|
||||
event := proxySwitchEvent{
|
||||
accountNames: append([]string(nil), group.accountNames...),
|
||||
fromURL: group.activeURL,
|
||||
}
|
||||
group.activeURL = ""
|
||||
group.consecutiveFailures = 0
|
||||
group.failed = false
|
||||
for _, accountName := range group.accountNames {
|
||||
s.accountClients[accountName] = s.directClient
|
||||
}
|
||||
delete(s.proxyGroups, oldClient)
|
||||
replaceClientInOrder(s.accountClientOrder, oldClient, s.directClient)
|
||||
return event
|
||||
}
|
||||
|
||||
func replaceClientInOrder(order []*client.DouyuClient, oldClient, newClient *client.DouyuClient) {
|
||||
for i, cli := range order {
|
||||
if cli == oldClient {
|
||||
@@ -777,7 +865,7 @@ func (s *Scheduler) startProxyRefill() {
|
||||
}
|
||||
|
||||
func (s *Scheduler) refillProxyStandbys(base *client.DouyuClient, cfg proxySettingsSnapshot, generation uint64, need int, excludedURLs map[string]struct{}) {
|
||||
proxies, err := s.fetchAndValidateProxyPool(base, cfg, need, excludedURLs)
|
||||
proxies, err := s.fetchAndValidateProxyPool(base, cfg, need, excludedURLs, proxyRefillTimeout)
|
||||
if err != nil {
|
||||
logger.LogEvent("代理", "warn", "备用代理补提取未完全成功: %v", err)
|
||||
}
|
||||
@@ -877,10 +965,17 @@ func copyStringSet(source map[string]struct{}) map[string]struct{} {
|
||||
|
||||
func logProxySwitch(label string, event proxySwitchEvent) {
|
||||
logger.LogEvent("代理", "warn", "%s: 账号=%d %s -> %s IP=%s 归属=%s RTT=%s 来源=%s",
|
||||
label, len(event.accountNames), client.MaskProxyURL(event.fromURL), client.MaskProxyURL(event.toURL),
|
||||
label, len(event.accountNames), proxyDisplay(event.fromURL), proxyDisplay(event.toURL),
|
||||
event.toIP, event.toRegion, event.toRTT.Round(time.Millisecond), event.toSource)
|
||||
}
|
||||
|
||||
func proxyDisplay(raw string) string {
|
||||
if strings.TrimSpace(raw) == "" {
|
||||
return "直连"
|
||||
}
|
||||
return client.MaskProxyURL(raw)
|
||||
}
|
||||
|
||||
func proxyPoolExpiresAt(apiURL string, now time.Time) time.Time {
|
||||
minutes := 10
|
||||
if u, err := url.Parse(strings.TrimSpace(apiURL)); err == nil {
|
||||
@@ -896,13 +991,16 @@ func proxyPoolExpiresAt(apiURL string, now time.Time) time.Time {
|
||||
return now.Add(time.Duration(minutes) * time.Minute)
|
||||
}
|
||||
|
||||
func (s *Scheduler) validateProxy(base *client.DouyuClient, proxyURL, source string) (validatedProxy, error) {
|
||||
func (s *Scheduler) validateProxy(base *client.DouyuClient, proxyURL, source string, timeout time.Duration) (validatedProxy, error) {
|
||||
cli, err := client.NewWithProxy(base.Activity, base.TimeAPIURL, base.Trace, proxyURL)
|
||||
if err != nil {
|
||||
return validatedProxy{}, err
|
||||
}
|
||||
if cli.HTTPClient != nil && cli.HTTPClient.Timeout > proxyValidationTimeout {
|
||||
cli.HTTPClient.Timeout = proxyValidationTimeout
|
||||
if timeout <= 0 || timeout > proxyValidationTimeout {
|
||||
timeout = proxyValidationTimeout
|
||||
}
|
||||
if cli.HTTPClient != nil {
|
||||
cli.HTTPClient.Timeout = timeout
|
||||
}
|
||||
var lastErr error
|
||||
for attempt := 0; attempt < proxyValidateAttempts; attempt++ {
|
||||
@@ -929,7 +1027,7 @@ type proxyValidationResult struct {
|
||||
err error
|
||||
}
|
||||
|
||||
func (s *Scheduler) validateProxyBatch(base *client.DouyuClient, endpoints []proxyprovider.Endpoint) []proxyValidationResult {
|
||||
func (s *Scheduler) validateProxyBatch(base *client.DouyuClient, endpoints []proxyprovider.Endpoint, deadline time.Time) []proxyValidationResult {
|
||||
if len(endpoints) == 0 {
|
||||
return nil
|
||||
}
|
||||
@@ -945,7 +1043,12 @@ func (s *Scheduler) validateProxyBatch(base *client.DouyuClient, endpoints []pro
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
for endpoint := range jobs {
|
||||
proxy, err := s.validateProxy(base, endpoint.URL, "API/"+endpoint.Provider)
|
||||
remaining := time.Until(deadline)
|
||||
if remaining <= 0 {
|
||||
results <- proxyValidationResult{endpoint: endpoint, err: errors.New("代理校验总时长超时")}
|
||||
continue
|
||||
}
|
||||
proxy, err := s.validateProxy(base, endpoint.URL, "API/"+endpoint.Provider, remaining)
|
||||
results <- proxyValidationResult{endpoint: endpoint, proxy: proxy, err: err}
|
||||
}
|
||||
}()
|
||||
|
||||
Reference in New Issue
Block a user